body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>This is the code (<a href="https://codesandbox.io/s/bold-glitter-pn30l" rel="nofollow noreferrer">here</a>):</p>
<pre><code>import React, {
useContext,
useReducer,
createContext
} from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const stateReducer = (state, action) => {
switch (action.type) {
case "increment":
return {
count: state.count + 1
};
default:
return state;
}
};
const StateContext = createContext();
const StateProvider = ({ children }) => {
const [state, dispatch] = useReducer(stateReducer, {
count: 0
});
return (
<StateContext.Provider value={{ state, dispatch }}>
{children}
</StateContext.Provider>
);
};
const useCount = () => {
const { state, dispatch } = useContext(StateContext);
const changeCount = () => {
dispatch({ type: "increment" });
};
return {
...state,
changeCount
};
};
const Caller = () => {
const { changeCount } = useCount();
const handleOnClick = () => {
changeCount();
};
return (
<div>
<button type="button" onClick={handleOnClick}>
Test me!
</button>
</div>
);
};
const Main = () => {
const { changeCount } = useCount();
const handleOnClick = () => {
changeCount();
};
console.log("main render");
return (
<div>
<button type="button" onClick={handleOnClick}>
Click Me Boi!
</button>
<Caller />
</div>
);
};
const App = () => (
<StateProvider>
<Main />
</StateProvider>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code></pre>
<p>The issue is this:</p>
<p>My <strong>Main</strong> component uses a hook. that hook returns some state and a function (functions) to modify that state.</p>
<p>My main component, although uses the hook, only wants/cares about the modifying function of that hook, and as such deconstructs only the function.</p>
<p>When I call the hook's function, it causes a rerender of my main component. </p>
<p>I understand that, for example, if I have <code>useState</code> and call its function, that function will change, but if it's a <code>useReducer</code> and I am calling a displatch does it change?</p>
<p>Really my question comes down to this. Is there a way to stop my main component rendering here (because I only rely on the hook's functions and not the state) or would I have to change my implementation to allow the re-render of main and just use memo to save re-renders of the child components?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T00:40:13.597",
"Id": "234461",
"Score": "2",
"Tags": [
"javascript",
"performance",
"react.js"
],
"Title": "Values Not Interested In From Hook Causes Re-Render"
}
|
234461
|
<pre><code> shippingAddress.first_name = shippingAddress.first_name.trim()
shippingAddress.last_name = shippingAddress.last_name.trim()
shippingAddress.address1 = shippingAddress.address1.trim()
shippingAddress.address2 = shippingAddress.address2.trim()
shippingAddress.phone = shippingAddress.phone.trim()
shippingAddress.city = shippingAddress.city.trim()
shippingAddress.province = shippingAddress.province.trim()
shippingAddress.country = shippingAddress.country.trim()
shippingAddress.zip = shippingAddress.zip.trim()
</code></pre>
<p>What is a more elegant way to write this? I am thinking I can map it somehow or use something similar to Ruby's <code>inject</code> but I'm not sure.</p>
|
[] |
[
{
"body": "<p>With single traversal on <em>keys</em> list and trimming all fields of type <code>string</code>:</p>\n\n<pre><code>Object.keys(shippingAddress).forEach((k) => {\n if (typeof shippingAddress[k] == 'string') {\n shippingAddress[k] = shippingAddress[k].trim();\n }\n})\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T05:52:29.580",
"Id": "458534",
"Score": "0",
"body": "Why is ForEach a superior choice to a for loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T05:54:30.513",
"Id": "458535",
"Score": "0",
"body": "@McDerp, with `for` loop you would have to declare additional counter variables and control condition checked on each iteration. You don't need that when dealing with object keys"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T06:04:34.840",
"Id": "458536",
"Score": "0",
"body": "Is trimming this best done in a function that is mapped to a http action or is this function best abstracted to a /utils/misc.js or something like that?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T05:51:45.083",
"Id": "234469",
"ParentId": "234463",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234469",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T02:26:48.710",
"Id": "234463",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Compacting this repetitive JavaScript bit which trims values in an object"
}
|
234463
|
<p>I need to perform a bunch of string manipulation tasks on an original string, then output the final string. Best I could think of is extracting some functionality into functions. Any better way to structure it? Also, are the variable/function names too long?</p>
<ul>
<li>strip out unicode chars from original string A, reverse them into string B</li>
<li>in the remaining string A, remove duplicate words</li>
<li>append: A + B</li>
</ul>
<pre><code>function extract_unicode_characters_from_string($str) {
preg_match_all('/\p{Han}+/u', $str, $unicode_characters_only, PREG_SET_ORDER);
$squashed = array_column($unicode_characters_only, 0);
return $squashed;
}
function strip_unicode_characters_from_string($str) {
return preg_replace('/\p{Han}+/u', '', $str);
}
function strip_duplicates($str){
$exploded_str = explode(' ', $str);
$exploded_str_no_empties = array_filter($exploded_str, function($item) { return !is_null($item) && $item !== ''; });
return implode(' ', array_unique($exploded_str_no_empties));
}
$original_string = 'one two three 喞 喝 four 刷囿 two 跏正 吁';
$array_of_unicode_characters = extract_unicode_characters_from_string($original_string);
$reversed_unicode_characters = implode(' ', array_reverse($array_of_unicode_characters));
$string_without_unicode_characters = strip_unicode_characters_from_string($original_string);
$english_words_no_dupes = strip_duplicates($string_without_unicode_characters);
echo $english_words_no_dupes . ' ' . $reversed_unicode_characters;
</code></pre>
|
[] |
[
{
"body": "<p>Yes, I think your variable names are a bit long. While it is good to be expressive, you don't want to be pushing your line width beyond the recommended max width if avoidable.</p>\n\n<p>I don't know if you need many custom functions here. The shared calls which filter empty and duplicate strings can be a custom call. Otherwise, everything else is single-use.</p>\n\n<p>Consider this snippet which simplifies much of the script by grouping the multibyte and single-byte non-whitespace substrings from the start. No extra exploding, and only one implode call.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/99NV4\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>function uniqueNoEmpty($array) {\n return array_unique(array_filter($array, 'strlen'));\n}\n\n$original_string = 'one two three 喞 喝 four 刷囿 two 跏正 吁';\n\nif (!preg_match_all('~(\\p{Han}+)|(\\S+)~u', $original_string, $out)) {\n echo 'no qualifying strings';\n} else {\n $singleBytes = uniqueNoEmpty($out[2]) ?? [];\n $multiBytes = array_reverse(uniqueNoEmpty($out[1]));\n\n echo implode(' ', array_merge($singleBytes, $multiBytes));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T12:48:15.747",
"Id": "234482",
"ParentId": "234464",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234482",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T03:18:09.943",
"Id": "234464",
"Score": "3",
"Tags": [
"php",
"strings"
],
"Title": "PHP code structure for string manipulation tasks"
}
|
234464
|
<p>I have not done Javascript programming in almost a decade. I see that it has changed a lot. Below is code that displays colourful block digits. Any constructive feedback is welcome.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getRandomColor() {
const colours = ["#FF6663", "#94FF63", "#63FFEA", "#A763FF", "#F2FF63"];
return colours[Math.floor(Math.random() * colours.length)];
}
class Square extends React.Component {
render() {
var squareStyle = {
width: 25,
height: 25,
backgroundColor: this.props.colour || getRandomColor(),
display: "inline-block"
};
return (
<div style={squareStyle}>
</div>
);
}
}
class Digit extends React.Component {
render() {
const divStyle = {
display: "inline-block",
lineHeight: 0,
paddingLeft: "10px",
paddingRight: "10px"
};
const filled = [
[
[1, 1, 1],
[1, 0, 1],
[1, 0, 1],
[1, 0, 1],
[1, 1, 1]
],
[
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1]
],
[
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[1, 0, 0],
[1, 1, 1]
],
[
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
],
[
[1, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[0, 0, 1]
],
[
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
],
[
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
],
[
[1, 1, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1]
],
[
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
],
[
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
];
let rows = [];
for (let y = 0; y < 5; y++) {
for (let x = 0; x < 3; x++) {
let objKey = y * 5 + x;
if (filled[this.props.digit][y][x]) {
rows.push(
<Square key={objKey} />
);
}
else {
rows.push(
<Square colour="#FFFFFF" key={objKey} />
);
}
}
rows.push(
<br key={y + "-br"} />
);
}
return (
<div style={divStyle}>
{rows}
</div>
);
}
}
ReactDOM.render(
<div>
<Digit digit={0} />
<Digit digit={5} />
<Digit digit={9} />
</div>,
document.getElementById("root")
)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p>
<p>To use, add <code><Digit digit={n}/></code> (where <code>0 <= n <= 9</code>). In the future, I plan to change <code>class Digit</code> to <code>class Character</code> (which supports <code>0-9</code>, <code>A-Z</code> and some punctuation characters). I will change the implementation to something like:</p>
<pre><code>filled = {
"A": [
[0, 1, 0],
[1, 0, 1],
[1, 1, 1],
[1, 0, 1],
[1, 0, 1]
]
}
</code></pre>
<p>For those curious, this is what the digits 0 to 9 look like:</p>
<p><a href="https://i.stack.imgur.com/G97ZB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G97ZB.png" alt="digits"></a></p>
<p>(the 1 is right-aligned like the 1 on a digital clock face)</p>
|
[] |
[
{
"body": "<ul>\n<li><code>squareStyle</code> variable should be initialized in constructor instead of render. Reason being, render is called on each state update and so, if your render is called multiple times, the variable inside render will be computed again which will cause the existing colours of the digits to change on each and will be unpleasant to look.</li>\n<li>Usage of var is replaced by let and consts </li>\n</ul>\n\n<p><strong>Modified Code</strong></p>\n\n<pre><code>class Square extends React.Component {\n constructor(props) {\n super(props)\n this.squareStyle = {\n width: 25,\n height: 25,\n backgroundColor: props.colour || getRandomColor(),\n display: \"inline-block\"\n };\n }\n render() {\n return (\n <div style={this.squareStyle}>\n </div>\n );\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T04:40:43.323",
"Id": "234621",
"ParentId": "234468",
"Score": "5"
}
},
{
"body": "<h1>Consistency</h1>\n\n<p>Sometimes the word <code>color</code> or <code>colour</code> is used to describe the look of a <code>Square</code>. Because I'm not a native English speaker I looked it up on <a href=\"https://en.wikipedia.org/wiki/Color\" rel=\"nofollow noreferrer\">wikipedia</a>:</p>\n\n<blockquote>\n <p>color (American English), or colour (Commonwealth English)</p>\n</blockquote>\n\n<h1>The Algorithm</h1>\n\n<p>Currently <code>Digit</code> calculates the form of a concrete digit based on the <code>prop</code> with the name <code>digit</code>. The calculation is inside a nested for-loop with a time complexity of <span class=\"math-container\">\\$O(n)\\$</span>. But actually the calculation is redundant since the form of a digit is known on run-time so we can reduce the time complexity (see final result, where we do not need to loop).</p>\n\n<p>The form of a digit is already defined inside the array <code>filled</code>:</p>\n\n<blockquote>\n <pre><code>const filled = [\n [\n [1, 1, 1],\n [1, 0, 1],\n [1, 0, 1],\n [1, 0, 1],\n [1, 1, 1]\n ],\n /* .... */\n]\n</code></pre>\n</blockquote>\n\n<p>But instead of define the form based on boolean values it is possible to insert the concrete React-Components to avoid the nested for-loops:</p>\n\n<pre><code>const filled = [\n [\n [<Square />, <Square />, <Square />, <br />],\n [<Square />, <Square colour=\"#FFFFFF\"/>, <Square />, <br />],\n [<Square />, <Square colour=\"#FFFFFF\"/>, <Square />, <br />],\n [<Square />, <Square colour=\"#FFFFFF\"/>, <Square />, <br />],\n [<Square />, <Square />, <Square />]\n ] \n];\n</code></pre>\n\n<blockquote>\n <p>Expand to see the working example below</p>\n</blockquote>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getRandomColor() {\n const colours = [\"#FF6663\", \"#94FF63\", \"#63FFEA\", \"#A763FF\", \"#F2FF63\"];\n return colours[Math.floor(Math.random() * colours.length)];\n}\n\nclass Square extends React.Component {\n render() {\n var squareStyle = {\n width: 25,\n height: 25,\n backgroundColor: this.props.colour || getRandomColor(),\n display: \"inline-block\"\n };\n\n return (\n <div style={squareStyle}>\n </div>\n );\n }\n}\n\nclass Digit extends React.Component {\n render() {\n const divStyle = {\n display: \"inline-block\",\n lineHeight: 0,\n paddingLeft: \"10px\",\n paddingRight: \"10px\"\n };\n\n const filled = [\n [\n [<Square />, <Square />, <Square />, <br />],\n [<Square />, <Square colour=\"#FFFFFF\"/>, <Square />, <br />],\n [<Square />, <Square colour=\"#FFFFFF\"/>, <Square />, <br />],\n [<Square />, <Square colour=\"#FFFFFF\"/>, <Square />, <br />],\n [<Square />, <Square />, <Square />]\n ] \n ];\n\n return (\n <div style={divStyle}>\n {filled[this.props.digit]}\n </div>\n );\n }\n}\n\nReactDOM.render(\n <div>\n <Digit digit={0} />\n </div>,\n document.getElementById(\"root\")\n)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n<div id=\"root\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h1>Composition</h1>\n\n<p>Inside <a href=\"https://reactjs.org/docs/composition-vs-inheritance.html\" rel=\"nofollow noreferrer\">Reacts Documentation on composition</a> is described how it can be used effectively.</p>\n\n<h2>Square</h2>\n\n<p>Currently the <code>Square</code>-Component can have random colors or a concrete color based on the <code>prop</code>. (In my opinion this is against the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single-Responsibility Principle</a> ). </p>\n\n<p>By extract the color behavior into separate components we can make the code more declarative:</p>\n\n<pre><code>const filled = [\n [\n [<RandomColoredSquare />, <RandomColoredSquare />, <RandomColoredSquare />, <br />],\n [<RandomColoredSquare />, <EmptySquare />, <RandomColoredSquare />, <br />],\n [<RandomColoredSquare />, <EmptySquare />, <RandomColoredSquare />, <br />],\n [<RandomColoredSquare />, <EmptySquare />, <RandomColoredSquare />, <br />],\n [<RandomColoredSquare />, <RandomColoredSquare />, <RandomColoredSquare />]\n ],\n /* ... */ \n];\n</code></pre>\n\n<p><code>RandomColoredSquare</code> and <code>EmptySquare</code> are <a href=\"https://reactjs.org/docs/composition-vs-inheritance.html#specialization\" rel=\"nofollow noreferrer\">specializations</a> of <code>Spuare</code>:</p>\n\n<pre><code>const Square = ({color}) => \n <div style={{\n width: 25,\n height: 25,\n backgroundColor: color,\n display: \"inline-block\"\n }}>\n </div>\n\nconst RandomColoredSquare = ({colors = [\"#FF6663\", \"#94FF63\", \"#63FFEA\", \"#A763FF\", \"#F2FF63\"]}) => \n <Square color={colors[Math.floor(Math.random() * colors.length)]} />\n\nconst EmptySquare = _ => \n <Square color=\"#FFF\" />\n</code></pre>\n\n<p>I used the the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a> to make the code more readable. Instead of <code>const Square = ({color})</code> I could have written <code>const Square = (props)</code> but then if have to query the <code>color</code> with <code>props.color</code> and now I can use directly the <code>color</code>.</p>\n\n<p>Additionally I make use of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameters</a> together with the destructuring assignment for <code>({colors = [\"#FF6663\", \"#94FF63\", \"#63FFEA\", \"#A763FF\", \"#F2FF63\"]})</code>. </p>\n\n<blockquote>\n <p>Expand to see the working example below</p>\n</blockquote>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const Square = ({color}) => \n <div style={{\n width: 25,\n height: 25,\n backgroundColor: color,\n display: \"inline-block\"\n }}>\n </div>\n\nconst RandomColoredSquare = ({colors = [\"#FF6663\", \"#94FF63\", \"#63FFEA\", \"#A763FF\", \"#F2FF63\"]}) => \n <Square color={colors[Math.floor(Math.random() * colors.length)]} />\n\nconst EmptySquare = _ => \n <Square color=\"#FFF\" />\n\nclass Digit extends React.Component {\n render() {\n const divStyle = {\n display: \"inline-block\",\n lineHeight: 0,\n paddingLeft: \"10px\",\n paddingRight: \"10px\"\n };\n\n const filled = [\n [\n [<RandomColoredSquare />, <RandomColoredSquare />, <RandomColoredSquare />, <br />],\n [<RandomColoredSquare />, <EmptySquare />, <RandomColoredSquare />, <br />],\n [<RandomColoredSquare />, <EmptySquare />, <RandomColoredSquare />, <br />],\n [<RandomColoredSquare />, <EmptySquare />, <RandomColoredSquare />, <br />],\n [<RandomColoredSquare />, <RandomColoredSquare />, <RandomColoredSquare />]\n ] \n ];\n\n return (\n <div style={divStyle}>\n {filled[this.props.digit]}\n </div>\n );\n }\n}\n\nReactDOM.render(\n <div>\n <Digit digit={0} />\n </div>,\n document.getElementById(\"root\")\n)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n<div id=\"root\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Digit</h2>\n\n<p>I think <code><Digit digit={0} /></code> is a less intuitiv API then if we could simply write <code><Zero /></code> which would make our code more declarative at the first glance.\nAdditionally <code>Digit</code> violates the <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open-Close Principle</a>.</p>\n\n<p>We can first describe the more generic component <code>Digit</code> and composite it the \"special\" components <code>Zero</code>, <code>One</code> and so on:</p>\n\n<pre><code>const Zero = _ => \n <Digit>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n\n <br />\n\n /* ... */\n </Digit>\n\nconst Digit = ({children}) => \n <div style={{\n display: \"inline-block\",\n lineHeight: 0,\n paddingLeft: \"10px\",\n paddingRight: \"10px\"\n }}>\n {children}\n </div>\n</code></pre>\n\n<p>For <code>Digit</code> I used the <a href=\"https://reactjs.org/docs/jsx-in-depth.html#children-in-jsx\" rel=\"nofollow noreferrer\">Children in JSX</a> where it is possible to pass Components inside a component instead vie props. </p>\n\n<blockquote>\n <p>Expand to see the working example below</p>\n</blockquote>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const Square = ({color}) => \n <div style={{\n width: 25,\n height: 25,\n backgroundColor: color,\n display: \"inline-block\"\n }}>\n </div>\n\nconst RandomColoredSquare = ({colors = [\"#FF6663\", \"#94FF63\", \"#63FFEA\", \"#A763FF\", \"#F2FF63\"]}) => \n <Square color={colors[Math.floor(Math.random() * colors.length)]} />\n\nconst EmptySquare = _ => \n <Square color=\"#FFF\" />\n\nconst Zero = _ => \n <Digit>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n \n <br />\n \n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n \n <br />\n \n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n \n <br />\n \n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n \n <br />\n \n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Digit>\n\nconst Digit = ({children}) => \n <div style={{\n display: \"inline-block\",\n lineHeight: 0,\n paddingLeft: \"10px\",\n paddingRight: \"10px\"\n }}>\n {children}\n </div>\n\nReactDOM.render(\n <div>\n <Zero />\n </div>,\n document.getElementById(\"root\")\n)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n<div id=\"root\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>But now we have this explicite <code><br /></code>. We could introduce a new Component <code>Row</code> to make it implicit:</p>\n\n<pre><code>const Row = ({children}) =>\n <div>\n {children}\n <br />\n </div>\n\nconst Zero = _ => \n <Digit>\n <Row>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Row>\n\n <Row>\n /* ... */\n </Row>\n\n /* ... */\n\n </Digit>\n</code></pre>\n\n<blockquote>\n <p>Expand to see the working example below</p>\n</blockquote>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const Square = ({color}) => \n <div style={{\n width: 25,\n height: 25,\n backgroundColor: color,\n display: \"inline-block\"\n }}>\n </div>\n\nconst RandomColoredSquare = ({colors = [\"#FF6663\", \"#94FF63\", \"#63FFEA\", \"#A763FF\", \"#F2FF63\"]}) => \n <Square color={colors[Math.floor(Math.random() * colors.length)]} />\n\nconst EmptySquare = _ => \n <Square color=\"#FFF\" />\n\nconst Row = ({children}) =>\n <div>\n {children}\n <br />\n </div>\n\nconst Zero = _ => \n <Digit>\n <Row>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Row>\n </Digit>\n\nconst Digit = ({children}) => \n <div style={{\n display: \"inline-block\",\n lineHeight: 0,\n paddingLeft: \"10px\",\n paddingRight: \"10px\"\n }}>\n {children}\n </div>\n\nReactDOM.render(\n <div>\n <Zero />\n </div>,\n document.getElementById(\"root\")\n)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n<div id=\"root\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h1>Final Result</h1>\n\n<p>The result is longer since we write the digits explicit instead of create them dynamic but with this way we have a much better time complexity and the code is easier to understand since we remove the computational logic and make the code more declarative. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const Square = ({color}) => \n <div style={{\n width: 25,\n height: 25,\n backgroundColor: color,\n display: \"inline-block\"\n }}>\n </div>\n\nconst RandomColoredSquare = ({colors = [\"#FF6663\", \"#94FF63\", \"#63FFEA\", \"#A763FF\", \"#F2FF63\"]}) => \n <Square color={colors[Math.floor(Math.random() * colors.length)]} />\n\nconst EmptySquare = _ => \n <Square color=\"#FFF\" />\n\nconst Row = ({children}) =>\n <div>\n {children}\n <br />\n </div>\n\nconst Zero = _ => \n <Digit>\n <Row>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <EmptySquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Row>\n </Digit>\n\nconst Three = _ =>\n <Digit>\n <Row>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <EmptySquare />\n <EmptySquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <EmptySquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <EmptySquare />\n <EmptySquare />\n <RandomColoredSquare />\n </Row>\n \n <Row>\n <RandomColoredSquare />\n <RandomColoredSquare />\n <RandomColoredSquare />\n </Row>\n </Digit>\n\nconst Digit = ({children}) => \n <div style={{\n display: \"inline-block\",\n lineHeight: 0,\n paddingLeft: \"10px\",\n paddingRight: \"10px\"\n }}>\n {children}\n </div>\n\nReactDOM.render(\n <div>\n <Zero />\n <Three />\n <Zero />\n </div>,\n document.getElementById(\"root\")\n)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n<div id=\"root\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T04:06:04.950",
"Id": "459105",
"Score": "0",
"body": "In your final result, what would you suggest that I `export`? `Square`, `Row`, and `Digit`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T05:53:29.643",
"Id": "459106",
"Score": "1",
"body": "If you consider the number of squares per digit as n then the OPs code per character is not O(n^2) as nested loops do not automatically square complexity. Neither is your example O(1) as each one of the n squares still need to be rendered which is unavoidable. Both the OP's and your example are O(n). There is no O(1) solution to this task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T16:54:26.630",
"Id": "459153",
"Score": "0",
"body": "@Blindman67, I thought it would be valid to ignore the concrete constants.. I will edit my posts. But the assumption about a better time complexity compared to the final result is correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T17:03:58.317",
"Id": "459156",
"Score": "0",
"body": "@FromTheStackAndBack - The export depends on the goal. If you want to create a library where a customer can create his own customizable `digit`, I would export `square`, `row`and `digit` besides your own implementations. The other option is to restrict the client to the `digit`s and types of `squares, etc. you want to provide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T17:56:05.050",
"Id": "459158",
"Score": "0",
"body": "The scalar ( > 0 ) does not effect complexity, 1 times n, 100 times n, or 1billion times n all have the same time complexity O(n). The final result has not changed the complexity of the solution. Nor do i see that your approach is at all practical. The number of characters is likely to be large 0-1, A-Z, and punctuation. The better solution is to have the chars as a string `<ColText text = \"012345,ABCDEFG\" /> and using the char code to lookup each char. A single char can be encoded in a single number CharCode 48, is 0 with 15 pixels 0x7b6f, and 1 is 0x1249"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T11:24:46.813",
"Id": "234692",
"ParentId": "234468",
"Score": "4"
}
},
{
"body": "<h2>Data entry</h2>\n<p>I am not much of a React fan so this is not a how to React, rather, fonts are best handled as sets of pixels in the simplest form possible. Fonts are subject to change and it should be as easy as possible to make changes.</p>\n<p>There is nothing worse than having a complicated long winded data entry process to define visual content. The easier it is to create the more time you have to be creative, and the more likely you are willing to put in creative time.</p>\n<p>Personally I would have defined the Text to be rendered in a low res <code>canvas</code> scaled to make the pixel size to what is desired and contain all the text. It would use much less memory and be rendered much quicker, but I assume your code is React practice, so will keep it as <code><Square></code>, <code><Character></code>, and <code><ColText></code></p>\n<h2>The example</h2>\n<p>The char 0 is</p>\n<pre><code>111\n1 1\n1 1\n1 1\n111\n</code></pre>\n<p>Can be made a string <code>"111101101101111"</code> (or Number <code>0b111101101101111</code>) and using a template to position line breaks <code>"00b00b00b00b00"</code> (0 is a pixel, b is a break) the conversion from string to displayed pixels is easy.</p>\n<p>As the characters <code>"M"</code> <code>"N"</code> and <code>"W"</code> can not be displayed in a 3 pixel wide font the example uses the string length to get the correct template and then builds variable width characters.</p>\n<p>I used a JavaScript <code>Map</code> that maps the pixel strings to each character. Characters not found are replaced with space.</p>\n<p>Rather than define an element for each character the object <code>ColText</code> has the property <code>text</code> and <code>size</code> to define the string of characters to display and the height in CSS pixels to display the font.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const CHAR_HEIGHT = 5, charMap = new Map();\nconst PALLET = [\"#F66\",\"#DC3\",\"#0A4\",\"#AC4\",\"#4AD\",\"#4AA\"];\nconst CHARS = [/* Variable width chars, Space, 0-9, A-Z */ \"0000000000\", \"111101101101111\", \"0101010101\", \"111001111100111\", \"111001011001111\", \"100100101111001\", \"111100111001111\", \"111100111101111\", \"111001001001001\", \"111101111101111\", \"111101111001111\", \"011101111101101\", \"110101111101110\", \"010101100101010\", \"110101101101110\", \"111100110100111\", \"111100110100100\", \"111100100101111\", \"101101111101101\", \"111010010010111\", \"111001001101010\", \"101101110101101\", \"100100100100111\", \"1000111011101011000110001\", \"10011101110110111001\", \"111101101101111\", \"110101110100100\", \"111101101111110\", \"110101110101101\", \"011100111001110\", \"111010010010010\", \"101101101101110\", \"101101101010010\", \"1000110001101010101001010\", \"101101010101101\", \"101101011001010\", \"111001010100111\" ];\n[...\" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"].forEach((c, i) => charMap.set(c, CHARS[i]));\nconst TEMPLATES = [\"bbbb\", \"0b0b0b0b0\", \"00b00b00b00b00\", \"000b000b000b000b000\", \"0000b0000b0000b0000b0000\", \"00000b00000b00000b00000b00000\", \"000000b000000b000000b000000b000000\"];\nconst buildChar = (char, size) => {\n const pixels = charMap.get(charMap.has(char) ? char : \" \");\n let i = 0;\n return [...TEMPLATES[pixels.length / CHAR_HEIGHT | 0]].map(t => (\n t === \"0\" ? \n pixels[i++]===\"1\" ? <Square size={size}/> : <Square colour=\"#FFF\" size={size}/> : \n <br />\n ));\n};\nclass Square extends React.Component {\n render() {\n return (<div style={{width: this.props.size, height: this.props.size, display: \"inline-block\", backgroundColor: this.props.colour || PALLET[Math.random() * PALLET.length | 0]}}></div> );\n }\n}\nclass Character extends React.Component {\n render() {\n const pad = Math.max(3, this.props.size / CHAR_HEIGHT / 2.5) + \"px\";\n return (<div style={{display: \"inline-block\", lineHeight: 0, paddingLeft: pad, paddingRight: pad}}> \n {buildChar(this.props.char, this.props.size / CHAR_HEIGHT)} </div>);\n }\n} \nclass ColText extends React.Component {\n render() {\n return (<div> {[...this.props.text].map(char => <Character char={char} size={this.props.size} />)} </div>);\n }\n}\nReactDOM.render(\n <div> <ColText size=\"50\" text=\"HI THERE 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ\" /><ColText size=\"25\" text=\"GROOVY\"/> </div>,\n document.getElementById(\"root\")\n)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"></script>\n<div id=\"root\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T19:07:51.370",
"Id": "234753",
"ParentId": "234468",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "234692",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T05:32:19.870",
"Id": "234468",
"Score": "7",
"Tags": [
"javascript",
"beginner",
"react.js"
],
"Title": "Colourful block digits"
}
|
234468
|
<p>I have some Python tests I have written, but these are for making assertions about data in infrastructure code (AWS CloudFormation templates). I am using the Unittest framework.</p>
<p>I have code like this:</p>
<pre class="lang-python prettyprint-override"><code>class TestData(unittest.TestCase):
def testConfigStackYaml(self):
bad_list = []
for stack in glob('*/config'):
stack_name = os.path.dirname(stack)
expected_file = "%s/config/%s.yaml" % (stack_name, stack_name)
if not os.path.isfile(expected_file):
bad_list.append(expected_file)
assert not bad_list, "Expected config/<stack_name>.yaml files to exist: %s" % bad_list
def testStacksetMk(self):
bad_list = []
for stack in glob('*/config'):
stack_name = os.path.dirname(stack)
expected_file = "%s/stackset.mk" % stack_name
if not os.path.isfile(expected_file):
bad_list.append(expected_file)
assert not bad_list, "Expected stackset.mk file to exist: %s" % bad_list
</code></pre>
<p>These are just two of my test cases. I have plenty more.</p>
<p>As can be seen, there is a problem with this code. The for loop for each test case is repeated for each test case, resulting in code duplication and inefficient code.</p>
<p>I have done it this way, however, because I want each test case to yield a helpful, specific message about what is wrong.</p>
<p>Can anyone see a cleaner way to implement this, so that I have the best of both worlds: duplication refactored out, but I still get to have a separate test case for each logical test?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T13:26:03.773",
"Id": "458561",
"Score": "0",
"body": "Title of the question doesn't convey your business requirement. Can you change it to something that describes what you are trying to do. How about `Assertions about data in infrastructure code as unit tests`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T13:27:08.713",
"Id": "458562",
"Score": "0",
"body": "@bhathiya-perera ok, done."
}
] |
[
{
"body": "<p>This is an interesting code. </p>\n\n<hr>\n\n<p><strong>Criticism:</strong></p>\n\n<blockquote>\n<pre><code>def testConfigStackYaml(self):\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Can we rename these functions to <code>snake_case</code> such as <code>test_config_stack_yaml</code> maybe.</li>\n</ul>\n\n<blockquote>\n<pre><code>assert not bad_list, \"Expected config/<stack_name>.yaml files to exist: %s\" % bad_list\n</code></pre>\n</blockquote>\n\n<ul>\n<li>You can access unit test asserts from `TestCas</li>\n<li>How:\n\n<ul>\n<li><code>self.assertTrue(expr, msg=None)</code></li>\n<li><code>self.assertFalse(expr, msg=None)</code></li>\n</ul></li>\n<li>More information at: <a href=\"https://docs.python.org/3.6/library/unittest.html#unittest.TestCase.assertTrue\" rel=\"nofollow noreferrer\">https://docs.python.org/3.6/library/unittest.html#unittest.TestCase.assertTrue</a></li>\n</ul>\n\n<blockquote>\n<pre><code>expected_file = \"%s/config/%s.yaml\" % (stack_name, stack_name)\n</code></pre>\n</blockquote>\n\n<ul>\n<li>I personally like using the new formatter. <code>%</code> is more unreadable compared to\n<code>\"{stack_name}/config/{stack_name}\".format(stack_name=stack_name)</code></li>\n<li>We can also use <code>os.path.join</code> to join sections of a path. This makes our intention clear.</li>\n</ul>\n\n<blockquote>\n<pre><code>if __name__ == \"__main__\":\n unittest.main()\n</code></pre>\n</blockquote>\n\n<ul>\n<li>If you add this to the end of the file you can run these test files individually as a simple script.</li>\n</ul>\n\n<hr>\n\n<p><strong>Creating a custom assert</strong></p>\n\n<ul>\n<li>I recommend creating a memeber function named <code>assert_config_exists</code>.</li>\n<li>Parameters: <code>path_format</code>, <code>message_format</code></li>\n</ul>\n\n<pre><code>def assert_config_exists(self, path_format: str, message_format: str):\n bad_list = []\n for stack in glob('*/config'):\n\n stack_name = os.path.dirname(stack)\n expected_file = path_format.format(stack_name=stack_name)\n\n if not os.path.isfile(expected_file):\n bad_list.append(expected_file)\n\n self.assertFalse(bad_list, message_format.format(bad_list=bad_list))\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T13:41:45.053",
"Id": "458566",
"Score": "0",
"body": "Thank you, note that camelCase is used for consistency with the Unittest framework itself, whose methods are named setUp, tearDown etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T13:43:48.507",
"Id": "458567",
"Score": "2",
"body": "Oh my apologies, I see your point https://docs.python.org/3/library/unittest.html The examples in there use snake_case all the same. I guess the Python community really really likes snake_case. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T14:34:55.737",
"Id": "458575",
"Score": "0",
"body": "This is very helpful. I could be missing something, but does that custom member function somehow allow me to address the duplication issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T14:37:02.387",
"Id": "458576",
"Score": "0",
"body": "Oh...my bad. I chose these examples badly. There are other examples I have that couldn't be refactored so easily this way. Ok, this is correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T17:16:03.047",
"Id": "458598",
"Score": "0",
"body": "@AlexHarvey Might it be worth adding those other examples as an edit to your post? Or would you rather create a different question entirely?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T18:04:06.433",
"Id": "458602",
"Score": "1",
"body": "@AMC It's not allowed to change the question after getting answers. It will invalidate the answer/effort I made. Alex you can create a new question "
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T13:40:20.890",
"Id": "234485",
"ParentId": "234471",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234485",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T07:57:41.073",
"Id": "234471",
"Score": "3",
"Tags": [
"python",
"unit-testing"
],
"Title": "Assertions about data in infrastructure code as unit tests"
}
|
234471
|
<p>This is "homework" from a Swift course, which I'm currently taking. A mockup and the image-assets are provided by the instructor. We are supposed to create the layout and to write some appropriate code.</p>
<p><a href="https://i.stack.imgur.com/mi835.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mi835.png" alt="App View"></a></p>
<p>Here's the code of my ViewController:</p>
<pre><code>import UIKit
class ViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var nameText: UITextField!
@IBOutlet weak var sizeText: UITextField!
@IBOutlet weak var weightText: UITextField!
@IBAction func clickHereButton(_ sender: UIButton) {
let name = nameText.text!
let size = Double(sizeText.text!)!
let weight = Double(weightText.text!)!
let bmi = weight / pow(size, 2)
let bmiRounded = (round(bmi * 10) / 10)
print(bmiRounded)
let uac = UIAlertController(title: "BMI for \(name)", message: "Your Body-Mass-Index is \(bmiRounded)", preferredStyle: .alert)
uac.addAction(UIAlertAction(title: "Okay", style: .default))
self.present(uac, animated: true, completion: nil)
}
}
</code></pre>
<p>What are your thoughts about my implementation? What would you have done differently and why?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:12:40.950",
"Id": "458713",
"Score": "0",
"body": "Force-unwrapping `Double(sizeText.text!)` and `Double(weightText.text!)` calls for trouble. Use optional binding instead. You could also set the keyboard type and define some valid ranges for the text fields."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T21:08:29.320",
"Id": "458927",
"Score": "0",
"body": "Should guard against \"division by zero\" in your bmi calculation. The app will crash if size entered is zero. Fun fact, zero is a valid dress size in the US."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-08T20:36:57.820",
"Id": "460485",
"Score": "0",
"body": "I think you are missing check for validation of text value from `UITextField` and displaying appropriate message if it isn't correct. For example on iPad user will be able to enter special symbols, even if you set decimal keyboard for `UITextField`. Another thing that I would recommend - calculate BMI \"live\" when user type in value in text field"
}
] |
[
{
"body": "<p>You are doing double force-unwraps, twice. This is really just asking for trouble </p>\n\n<p>As others have pointed out in their comments, there are a few edge cases you should <code>guard</code> against. Good thing is you can do both at the same time.</p>\n\n<p>Additionally, you should avoid using shortened names for your variables. In Swift, we usually type everything out.</p>\n\n<p>I've updated and annotated your code below, take a look;</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>@IBAction func clickHereButton(_ sender: UIButton) {\n\n // Start by ensuring we have actual values entered by the user\n guard let name = nameText.text, \n let sizeString = sizeText.text,\n let weightString = weightText.text else {\n return\n }\n\n // Then, ensure the values are valid Doubles\n guard let size = Double(sizeString),\n let weight = Double(weightString) else {\n return\n }\n\n // Finally, ensure that size > 0\n guard size > 0 else {\n return\n }\n\n // We now are 100% safe and can start calculating our BMI\n let bmi = weight / pow(size, 2)\n let bmiRounded = (round(bmi * 10) / 10)\n\n // Even though this var name is longer, it's clearer what it is.\n let alertViewController = UIAlertController(title: \"BMI for \\(name)\", message: \"Your Body-Mass-Index is \\(bmiRounded)\", preferredStyle: .alert)\n\n // You can use the `.init(_:)` shorthand when a specific type is required\n alertViewController.addAction(.init(title: \"Okay\", style: .default))\n self.present(alertViewController, animated: true, completion: nil)\n}\n</code></pre>\n\n<p>The only other thing I would improve is to move your actual BMI calculations to a specific function that takes in the <code>size</code> and <code>weight</code> parameters.</p>\n\n<p>For the rest, it's pretty much all good.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-17T13:23:01.990",
"Id": "239057",
"ParentId": "234472",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T08:38:40.227",
"Id": "234472",
"Score": "2",
"Tags": [
"swift",
"ios"
],
"Title": "iOS Body-Mass-Index (BMI) app"
}
|
234472
|
<p>I've created an small lib to allow writing to console with multiple threads and reading from console at the same time avoiding output being written in the middle of input because console cursor is there.
My library implements simple mechanism to make console write output <strong>above</strong> input. </p>
<p><code>TSConsole</code> is the main class for interacting with console.</p>
<p><code>TSCString</code> class used for creating colored strings.</p>
<p><strong>TSConsole.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace ThreadSafeConsole
{
public static class TSConsole
{
/* Private fields */
private static readonly object _lockObject = new object();
private static readonly StringBuilder _buffer = new StringBuilder();
private static bool _isReading = false;
private static int _bufferCursorPos = 0;
private static string _prompt = "";
/* Public Properties */
public static string Prompt
{
get
{
lock (_lockObject)
{
return _prompt;
}
}
set
{
lock (_lockObject)
{
if (_isReading)
throw new InvalidOperationException("Can't set prompt while reading.");
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
_prompt = value;
}
}
}
public static bool IsReading
{
get
{
lock (_lockObject)
{
return _isReading;
}
}
}
/* Public Methods */
public static void WriteLine(string str)
{
if (string.IsNullOrEmpty(str))
throw new ArgumentNullException(nameof(str));
lock (_lockObject)
{
GoToBufferBeginning();
Console.Write(str);
RestoreBuffer();
}
}
public static void WriteLine(IEnumerable<TSCString> enumeration)
{
if (enumeration is null)
throw new ArgumentNullException(nameof(enumeration));
lock (_lockObject)
{
ConsoleColor saveForeground = Console.ForegroundColor;
ConsoleColor saveBackground = Console.BackgroundColor;
GoToBufferBeginning();
foreach (var elem in enumeration)
{
if (!string.IsNullOrEmpty(elem.Data))
{
Console.ForegroundColor = elem.Foreground ?? saveForeground;
Console.BackgroundColor = elem.Backgroung ?? saveBackground;
Console.Write(elem.Data);
}
}
Console.ForegroundColor = saveForeground;
Console.BackgroundColor = saveBackground;
RestoreBuffer();
}
}
public static void WriteLine(params TSCString[] enumeration)
{
WriteLine((IEnumerable<TSCString>)enumeration);
}
public static string ReadLine(int maxLength = 0)
{
lock (_lockObject)
{
if (_isReading)
throw new InvalidOperationException("Some thread is already reading.");
_isReading = true;
_bufferCursorPos = 0;
Console.Write(_prompt);
}
while (true)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
lock (_lockObject)
{
if (!char.IsControl(keyInfo.KeyChar))
{
if (maxLength == 0 || _buffer.Length < maxLength)
{
int i = _buffer.Length - _bufferCursorPos;
Console.Write(keyInfo.KeyChar + _buffer.ToString(_bufferCursorPos, i));
MoveCursor(i * -1);
_buffer.Insert(_bufferCursorPos, keyInfo.KeyChar.ToString(CultureInfo.InvariantCulture));
_bufferCursorPos++;
}
}
else
{
switch (keyInfo.Key)
{
// [Backspace] Remove symbol before cursor
case ConsoleKey.Backspace:
if (_bufferCursorPos != 0)
{
MoveCursor(-1);
int i = _buffer.Length - _bufferCursorPos;
Console.Write(_buffer.ToString(_bufferCursorPos, i) + ' ');
MoveCursor(i * -1 - 1);
_buffer.Remove(_bufferCursorPos - 1, 1);
_bufferCursorPos--;
}
continue;
// [Del] Remove symbol after cursor
case ConsoleKey.Delete:
if (_bufferCursorPos != _buffer.Length)
{
int i = _buffer.Length - _bufferCursorPos;
Console.Write(_buffer.ToString(_bufferCursorPos + 1, i - 1) + ' ');
MoveCursor(i * -1);
_buffer.Remove(_bufferCursorPos, 1);
}
continue;
// [Enter] Clear buffer and return string
case ConsoleKey.Enter:
if (_buffer.Length != 0)
{
GoToBufferBeginning();
int i = _prompt.Length + _buffer.Length;
Console.Write(new string(' ', i));
MoveCursor(i * -1);
string result = _buffer.ToString();
_isReading = false;
_buffer.Clear();
_bufferCursorPos = 0;
return result;
}
continue;
// [Left Arrow] Move cursor left
case ConsoleKey.LeftArrow:
if (_bufferCursorPos != 0)
{
MoveCursor(-1);
_bufferCursorPos--;
}
continue;
// [Right Arrow] Move cursor right
case ConsoleKey.RightArrow:
if (_bufferCursorPos != _buffer.Length)
{
MoveCursor(1);
_bufferCursorPos++;
}
continue;
}
}
}
}
}
/* Private Helpers */
private static void GoToBufferBeginning()
{
if (_isReading)
{
Console.SetCursorPosition(0, Console.CursorTop - (_prompt.Length + _bufferCursorPos) / Console.BufferWidth);
}
}
private static void RestoreBuffer()
{
if (Console.CursorLeft != 0)
Console.Write(new string(' ', Console.BufferWidth - Console.CursorLeft));
if (_isReading)
{
Console.Write(_prompt);
Console.Write(_buffer.ToString());
MoveCursor(_bufferCursorPos - _buffer.Length);
}
}
private static void MoveCursor(int move)
{
if (move == 0)
return;
move += Console.CursorLeft;
int left = move % Console.BufferWidth;
int top = Console.CursorTop + move / Console.BufferWidth;
if (left < 0)
{
left += Console.BufferWidth;
top -= 1;
}
Console.SetCursorPosition(left, top);
}
}
}
</code></pre>
<p><strong>TSCString.cs</strong></p>
<pre><code>using System;
namespace ThreadSafeConsole
{
public class TSCString
{
/* Public Properties */
public string Data { get; set; }
public ConsoleColor? Foreground { get; set; }
public ConsoleColor? Backgroung { get; set; }
/* Constructors */
public TSCString() { }
public TSCString(string data) => Data = data;
public TSCString(string data, ConsoleColor fg) : this(data) => Foreground = fg;
public TSCString(string data, ConsoleColor fg, ConsoleColor bg) : this(data, fg) => Backgroung = bg;
}
}
</code></pre>
<p>Few things I'm not sure about:</p>
<ul>
<li>Should I make <code>TSCString</code> struct instead of class?</li>
<li>Is it okay to have to have constructors like in <code>TSCString</code> or should I better avoid one constructor calling another in this situation?</li>
</ul>
<p>Looking forward to your feedback!</p>
|
[] |
[
{
"body": "<p>Anytime you give up a lock you have to assume another thread could jump in</p>\n\n<pre><code> public static string ReadLine(int maxLength = 0)\n {\n lock (_lockObject)\n {\n if (_isReading)\n throw new InvalidOperationException(\"Some thread is already reading.\");\n\n _isReading = true;\n _bufferCursorPos = 0;\n Console.Write(_prompt);\n }\n\n while (true)\n {\n ConsoleKeyInfo keyInfo = Console.ReadKey(true);\n lock (_lockObject)\n {\n</code></pre>\n\n<p>in ReadLine the lock is given up after setting the isReading and in the loop it give it up as well each loop. Now WriteLine could come in and write since the lock object isn't locked. I don't know if that's your intent or not.</p>\n\n<p>Also I think throwing an exception would make using this harder than it should be. The calling code will need to now to do a try/catch to around all calls. I would suggest following some other patterns in .net by doing a TryWrite or TryRead and instead of throwing return back false if it can't do the method. Or you could even use a TaskCompletionSource and return back a Task and implement a queue for reading and writing and complete the task when the operation is complete. </p>\n\n<p>Also properties like IsReading and Prompt have little to no value when talking multi-threading as the caller you don't know if another thread has changed that value once you read the value. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T11:25:54.497",
"Id": "459211",
"Score": "0",
"body": "_I don't know if that's your intent or not._\nYes, I've done it intentionally. I'm giving up a lock every time to allow threads write to the console while the reading thread is waiting for a key to be pressed. I'm also passing `true` to `Console.ReadKey` method to avoid it from writing pressed key to the console immediately."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T03:33:32.320",
"Id": "234771",
"ParentId": "234474",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234771",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T09:39:03.410",
"Id": "234474",
"Score": "4",
"Tags": [
"c#",
"console"
],
"Title": "Thread-safe console for C#"
}
|
234474
|
<p>There are many side controllers in my project, like the following images.
They share the same head view appearance and layout. </p>
<p><a href="https://i.stack.imgur.com/catDr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/catDr.png" alt="0"></a></p>
<p><a href="https://i.stack.imgur.com/FmLmq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FmLmq.png" alt="8"></a></p>
<p>Use protocol to extract common code .</p>
<pre><code>protocol SideHeaderDelegate: class {
var h: SideHeader{ get set }
var view: UIView! {get}
var follow: UIView {get}
func back()
}
</code></pre>
<p>Use protocol extension to extract the common layout code. </p>
<pre><code>extension SideHeaderDelegate{
func doLayout(_ offset: CGFloat = 0){
view.addSubview(h)
view.addSubview(follow)
let top: CGFloat = 40
h.translatesAutoresizingMaskIntoConstraints = false
follow.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
h.topAnchor.constraint(equalTo: view.topAnchor),
h.leadingAnchor.constraint(equalTo: view.leadingAnchor),
h.trailingAnchor.constraint(equalTo: view.trailingAnchor),
h.heightAnchor.constraint(equalToConstant: top)
])
NSLayoutConstraint.activate([
follow.topAnchor.constraint(equalTo: view.topAnchor, constant: top),
follow.leadingAnchor.constraint(equalTo: view.leadingAnchor),
follow.trailingAnchor.constraint(equalTo: view.trailingAnchor),
follow.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: offset)
])
}
}
</code></pre>
<p>Code of the common head appearance:</p>
<pre><code>class SideHeader: UIView {
weak var delegate: SideHeaderDelegate?
let title: String
let avatar: String
lazy var headline = { () -> UILabel in
let lbl = UILabel()
lbl.textAlignment = .center
lbl.text = title
return lbl
}()
lazy var arrow = { () -> UIImageView in
let img = UIImageView()
img.image = UIImage(named: avatar)
img.isUserInteractionEnabled = true
return img
}()
let line: UIView = {
let string = UIView()
string.backgroundColor = UIColor(rgb: 0xD8D8D8)
return string
}()
init(title name: String, icon: String = "mine_fork") {
title = name
avatar = icon
super.init(frame: CGRect.zero)
backgroundColor = UIColor.white
headline.translatesAutoresizingMaskIntoConstraints = false
arrow.translatesAutoresizingMaskIntoConstraints = false
line.translatesAutoresizingMaskIntoConstraints = false
addSubview(headline)
addSubview(arrow)
addSubview(line)
NSLayoutConstraint.activate([
headline.centerXAnchor.constraint(equalTo: centerXAnchor),
headline.topAnchor.constraint(equalTo: topAnchor, constant: 10)
])
NSLayoutConstraint.activate([
arrow.centerYAnchor.constraint(equalTo: centerYAnchor),
arrow.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
arrow.widthAnchor.constraint(equalToConstant: 26),
arrow.heightAnchor.constraint(equalToConstant: 26)
])
NSLayoutConstraint.activate([
line.bottomAnchor.constraint(equalTo: bottomAnchor),
line.leadingAnchor.constraint(equalTo: leadingAnchor),
line.trailingAnchor.constraint(equalTo: trailingAnchor),
line.heightAnchor.constraint(equalToConstant: 1)
])
let tap = UITapGestureRecognizer()
arrow.addGestureRecognizer(tap)
tap.addTarget(self, action: #selector(SideHeader.pop))
}
func change(title name: String){
headline.text = name
}
@objc
func pop(){
delegate?.back()
}
}
</code></pre>
<p>Usage code: </p>
<p>one controller instance</p>
<pre><code>class VIPCenterCtrl: UIViewController, SideHeaderDelegate {
lazy var follow: UIView = { () -> UITableView in
let tb = UITableView(frame: CGRect.zero, style: UITableView.Style.grouped)
tb.register(for: VIPCenterCell.self)
tb.separatorStyle = .none
tb.delegate = self
tb.dataSource = self
return tb
}()
lazy var h = { () -> SideHeader in
let head = SideHeader(title: "VIP 中心")
head.delegate = self
return head
}()
override func viewDidLoad() {
super.viewDidLoad()
doLayout()
// ...
}
func refresh(){
// ...
let vCenter = self.follow as! UITableView
vCenter.reloadData()
}
}
</code></pre>
<h2>I want some suggestions. Do it more Swifter.</h2>
<p>The refresh data part is not very elegant. I need cast it first, from <code>UIView</code> to <code>UITableView</code></p>
<p><a href="https://github.com/ForStackO/picker/tree/master/generic" rel="nofollow noreferrer">More code on github</a></p>
|
[] |
[
{
"body": "<p>U can go forward.</p>\n\n<p><a href=\"https://i.stack.imgur.com/JVlJk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JVlJk.png\" alt=\"111\"></a></p>\n\n<p>To simplify the question, you can handle the top part like this</p>\n\n<pre><code>protocol SideH: class{\n\n var headline: UILabel! {get set}\n var arrow: UIImageView! {get set}\n var line: UIView! {get set}\n\n // provided by UIViewController\n var view: UIView! { get }\n\n}\n\n\n\nextension SideH{\n\n\n func layout(t title: String){\n view.backgroundColor = UIColor.white\n headline = { () -> UILabel in\n let lbl = UILabel()\n lbl.font = UIFont.regular(ofSize: 18)\n lbl.textColor = UIColor.textHeavy\n lbl.textAlignment = .center\n lbl.text = title\n return lbl\n }()\n\n\n arrow = { () -> UIImageView in\n let img = UIImageView()\n img.image = UIImage(named: \"mine_fork\")\n img.isUserInteractionEnabled = true\n return img\n }()\n\n line = {\n let string = UIView()\n string.backgroundColor = UIColor(rgb: 0xD8D8D8)\n return string\n }()\n\n ///\n\n view.addSubs([headline, arrow, line])\n\n headline.snp.makeConstraints { (maker) in\n maker.centerX.equalToSuperview()\n maker.top.equalToSuperview().offset(20)\n maker.size.equalTo(CGSize(width: 80 + 15, height: 25))\n }\n\n arrow.snp.makeConstraints { (maker) in\n maker.size.equalTo(CGSize(width: 30, height: 30))\n maker.top.equalToSuperview().offset(17)\n maker.leading.equalToSuperview().offset(16)\n }\n\n line.snp.makeConstraints { (maker) in\n maker.leading.trailing.equalToSuperview()\n maker.height.equalTo(1)\n maker.top.equalToSuperview().offset(63)\n }\n\n }\n\n\n func back(){\n if let ctrl = view.parentViewController{\n let tap = UITapGestureRecognizer()\n arrow.addGestureRecognizer(tap)\n\n tap.rx.event.bind { (event) in\n NotificationCenter.default.post(name: .close, object: nil)\n }.disposed(by: ctrl.rx.disposeBag)\n }\n\n }\n\n}\n</code></pre>\n\n<p>The <code>RxSwift</code> part is a little anoying.</p>\n\n<p>If u call it in <code>UIViewController</code>, </p>\n\n<pre><code> // self.rx.disposeBag, or self has a DisposeBag\n tap.rx.event.bind { (event) in\n }.disposed(by: rx.disposeBag)\n</code></pre>\n\n<p>extension code part:</p>\n\n<pre><code>extension UIView {\n var parentViewController: UIViewController? {\n var parentResponder: UIResponder? = self\n while parentResponder != nil {\n parentResponder = parentResponder?.next\n if let viewController = parentResponder as? UIViewController {\n return viewController\n }\n }\n return nil\n }\n}\n\n\nextension UIView{\n\n\n func addSubs(_ views: [UIView]){\n views.forEach(addSubview(_:))\n }\n\n}\n\n\nextension Notification.Name {\n static let close = Notification.Name(\"close\")\n}\n</code></pre>\n\n<p>call like this:</p>\n\n<pre><code>class OnUs: UIViewController, SideH{\n // the 3 props, just decorates\n var headline: UILabel!\n var arrow: UIImageView!\n var line: UIView!\n\n override func viewDidLoad() {\n super.viewDidLoad()\n layout(t: \"关于我们\")\n\n back()\n\n }\n</code></pre>\n\n<p>now u had UI Appearance, UI layout , target action with ( RxSwift, <code>NSObject+Rx</code>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-19T15:13:37.423",
"Id": "240806",
"ParentId": "234475",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "240806",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T09:59:32.620",
"Id": "234475",
"Score": "1",
"Tags": [
"swift",
"protocols"
],
"Title": "iOS: configuring UI appearance and layout, use protocol to extract common code"
}
|
234475
|
<p>This code currently works i wonder if i could make any optimisations or anything to make the code appear cleaner using functions or whatnot, suggestions are welcome!</p>
<pre><code>#include <cmath>
#include <cstdio>
int prompt(const char* name)
{
printf("%s", name);
int value;
scanf("%d", &value);
return value;
}
int main()
{
int mod, a, b, zbroj, razlika, umnozak, kolicnik;
printf("Mod 1 je za zbrajanje \n");
printf("Mod 2 je za oduzimanje \n");
printf("Mod 3 je za mnozenje \n");
printf("Mod 4 je za dijeljenje \n");
printf("U kojem modu zelis biti: \n");
std::scanf("%d", &mod);
switch (mod)
{
case 1:
printf("Odabrali ste zbrajanje! \n");
a = prompt("a: ");
b = prompt("b: ");
zbroj = a + b;
printf("%d + %d = %d", a, b, zbroj);
break;
case 2:
printf("Odabrali ste oduzimanje! \n");
a = prompt("a: ");
b = prompt("b: ");
razlika = a - b;
printf("%d - %d = %d", a, b, razlika);
break;
case 3:
printf("Odabrali ste mnozennje! \n");
a = prompt("a: ");
b = prompt("b: ");
if(a == 0 or b==0){
printf("Mnozite s nulom, a kad se mnozi s nulom rezultat je uvijek 0: \n");
umnozak = 0;
}
else
{
umnozak = a * b;
}
printf("%d * %d = %d", a, b, umnozak);
break;
case 4:
printf("Odabrali ste dijeljenje! \n");
a = prompt("a: ");
b = prompt("b: ");
if(a == 0 or b==0){
printf("Dijelite s nulom, a kad se dijeli s nulom rezultat je uvijek 0: \n");
kolicnik = 0;
}
else
{
kolicnik = a / b;
}
printf("%d / %d = %d", a, b, kolicnik);
break;
default:
printf("Nemamo tu opciju trenutno, prcekajte za nadogradnju programa, ili se javite developeru! \n");
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Check return values for errors</h2>\n\n<p>The call <code>scanf</code> can fail. You must check the return values to make sure it hasn't or your program may crash (or worse) when given malformed input or due to low system resources. Rigorous error handling is the difference between mostly working versus bug-free software. You should strive for the latter.</p>\n\n<h2>Decompose your program into functions</h2>\n\n<p>Almost all of the logic here is in <code>main</code> in one rather long and dense chunk of code. It would be better to decompose this into separate functions.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers). In this particular case, I happen to think it's perfectly appropriate because it's a single short program that and not a header. Some people seem to think it should never be used under any circumstance, but my view is that it can be used as long as it is done responsibly and with full knowledge of the consequences. </p>\n\n<h2>Use <code><cstdio></code> instead of <code><stdio.h></code></h2>\n\n<p>The difference between the two forms is that the former defines things within the <code>std::</code> namespace versus into the global namespace. Language lawyers have lots of fun with this, but for daily use I'd recommend using <code><cstdio></code>. See <a href=\"http://stackoverflow.com/questions/8734230/math-interface-vs-cmath-in-c/8734292#8734292\">this SO question</a> for details.</p>\n\n<h2>Prefer <code>iostream</code> to old-style <code>printf</code></h2>\n\n<p>The <code>iostream</code> library is the more modern C++ way to do I/O. Prefer it over <code>printf</code> and <code>scanf</code>. So instead of this:</p>\n\n<pre><code>printf(\"%d + %d = %d\", a, b, zbroj);\n</code></pre>\n\n<p>Write this: </p>\n\n<pre><code>std::cout << a << \" + \" << b << \" = \" << zbroj << '\\n';;\n</code></pre>\n\n<p>See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rio-streams\" rel=\"noreferrer\">SL.io.3</a> for details.</p>\n\n<h2>Initialize variables before use</h2>\n\n<p>The <code>mod</code> variable is printed before it is set to any value. That is not likely to be useful. Better is to always make sure that all variables are initialized before using them.</p>\n\n<h2>Use constant string concatenation</h2>\n\n<p>This code currently includes these lines:</p>\n\n<pre><code>cout << \"U kojem modu kalkulatora zelis biti? \\n\" << mod;\ncout << \"Mod 1 je za zbrajanje \\n\";\ncout << \"Mod 2 je za oduzimanje \\n\";\ncout << \"Mod 3 je za mnozenje \\n\";\ncout << \"Mod 4 je za dijeljenje \\n\";\n</code></pre>\n\n<p>I would suggest writing it instead like this:</p>\n\n<pre><code>std::cout << \n \"U kojem modu kalkulatora zelis biti? \\n\" \n \"Mod 1 je za zbrajanje \\n\"\n \"Mod 2 je za oduzimanje \\n\"\n \"Mod 3 je za mnozenje \\n\"\n \"Mod 4 je za dijeljenje \\n\";\n</code></pre>\n\n<p>Since the next line happens to be <code>scanf</code>, I'd suggest instead using your <code>prompt</code> function.</p>\n\n<h2>Consider using more idiomatic C++</h2>\n\n<p>While your use of <code>and</code> and <code>not</code> is not techncially wrong, you should be aware that many experienced C++ programmers will be unfamiliar with these operator alternatives, and so if others read your code, it might be an impediment to their understanding of the code. </p>\n\n<h2>Eliminate redundant variables</h2>\n\n<p>I don't speak Croatian, but the variable names are good in that they accurately describe what the variables mean in the context of the program. However, I would suggest that instead of <code>zbroj, razlika, umnozak, kolicnik</code> you could use a single variable <code>rezultat</code>.</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>The mathematical operations in the <code>case</code> statement all include very similar repeated code. Instead of repeating code, it's generally better to make common code into a function. The only thing that varies is the prompt, the mathematical operation and the way the result is printed. An advanced technique would be to gther them all into a data structure. If you're just beginning, don't worry if you can't understand this yet. It uses <a href=\"https://en.cppreference.com/w/cpp/language/lambda\" rel=\"noreferrer\">lambda expressions</a> and C++17 <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"noreferrer\"><code>std::string_view</code></a> among other things. I am putting it here to show how powerful C++ can be:</p>\n\n<pre><code>#include <cmath>\n#include <iostream>\n#include <string_view>\n#include <array>\n\nint prompt(const char* name) \n{\n std::cout << name;\n int value;\n std::cin >> value;\n return value;\n}\n\nint main()\n{ \n\n struct MathOp {\n std::string_view opname;\n int (*operate)(int a, int b);\n std::string_view opsymbol;\n\n void operator()() const {\n std::cout << \"Odabrali ste \" << opname << \"!\\n\";\n int a = prompt(\"a: \");\n int b = prompt(\"b: \");\n int rezultat = operate(a, b);\n std::cout << a << opsymbol << b << \" = \" << rezultat << '\\n';\n }\n\n };\n\n constexpr std::array<MathOp, 4> op{{\n { \"zbrajanje\", [](int a, int b){ return a+b; }, \" + \" },\n { \"oduzimanje\", [](int a, int b){ return a-b; }, \" - \" },\n { \"mnozenje\", [](int a, int b){ return a*b; }, \" * \" },\n { \"dijeljenje\", [](int a, int b){ \n if (b == 0) { \n std::cout << \"dijeljenje s nulom \\n\";\n return 0;\n } \n return a/b;\n }, \" / \" },\n }};\n\n std::cout << \"U kojem modu kalkulatora zelis biti? \\n\";\n for (std::size_t i{0}; i < op.size(); ++i) {\n std::cout << \"Mod \" << i+1 << \" je za \" << op[i].opname << \"\\n\";\n }\n unsigned mod;\n std::cin >> mod;\n\n if (mod > 0 && mod <= op.size()) {\n op[mod-1]();\n } else {\n std::cout << \"Nemamo tu opciju trenutno, prcekajte za nadogradnju programa, ili se javite developeru! \\n\";\n }\n}\n</code></pre>\n\n<p>Now if we want to add exponentiation, for example, all we need to do is add a single line to the <code>op</code> array:</p>\n\n<pre><code>{ \"eksponenciju\", [](int a, int b){ return static_cast<int>(std::pow(a,b)); }, \" ** \" },\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T15:52:22.403",
"Id": "458587",
"Score": "0",
"body": "Thanks for taking your time to explain it to me, and yes its helpful, here's my updated code https://pastebin.com/nX65McD0, and oh god that's a lot of code you've got there which i cannot understand i'll do my best to understand it and apply it to mine over the period of me learning the cpp!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T15:54:12.570",
"Id": "458589",
"Score": "0",
"body": "It takes time to become expert in C++, but the reward is great. Keep at it, and I'm sure you'll get better quickly!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T16:21:35.893",
"Id": "458593",
"Score": "0",
"body": "Actually you have to modify the array size as well, it might be better to use std::vector."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T16:51:37.120",
"Id": "458596",
"Score": "0",
"body": "Yes, you have to modify the array size, but if you use a `std::vector` it can't be `constexpr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T18:09:43.137",
"Id": "458603",
"Score": "1",
"body": "@pacmaninbw Or a native auto-sized array. Which has no disadvantages as there is no need to copy or resize it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T04:14:40.503",
"Id": "458656",
"Score": "0",
"body": "It's certainly worth knowing that a structure like `std::array<MathOp, 4> op` can be used, but I would hesitate to use it if this were actual production code. While the four operations implemented so far are all binary, there's no guarantee that the fifth one will be. It could take one parameter, or three, or even take a variable number of parameters. The fact that the operation is requested first leaves the door wide open for new requirements."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T15:41:22.633",
"Id": "234492",
"ParentId": "234477",
"Score": "7"
}
},
{
"body": "<p>1) Be consistent when placing braces. The following is not consisent:</p>\n\n<pre><code>if(a == 0 or b==0){\n printf(\"Mnozite s nulom, a kad se mnozi s nulom rezultat je uvijek 0: \\n\");\n umnozak = 0;\n}\nelse\n{\n umnozak = a * b;\n}\n</code></pre>\n\n<p>Either write it like this:</p>\n\n<pre><code>if (a == 0 or b==0) {\n printf(\"Mnozite s nulom, a kad se mnozi s nulom rezultat je uvijek 0: \\n\");\n umnozak = 0;\n} else {\n umnozak = a * b;\n}\n</code></pre>\n\n<p>or as</p>\n\n<pre><code>if (a == 0 or b==0)\n{\n printf(\"Mnozite s nulom, a kad se mnozi s nulom rezultat je uvijek 0: \\n\");\n umnozak = 0;\n}\nelse\n{\n umnozak = a * b;\n}\n</code></pre>\n\n<p>You can choose whatever style you like best, but you should stick to it.</p>\n\n<p>2) Don't declare variables before they are used. Delay declaring\nvariables until you actually need them. So instead of</p>\n\n<pre><code>int umnozak;\n... some code here ...\numnozak = a * b;\n</code></pre>\n\n<p>You write</p>\n\n<pre><code>int umnozak = a * b;\n</code></pre>\n\n<p>This causes scoping issues in the clauses of the switch statement so\nthey now have to be surrounded with braces.</p>\n\n<p>3) Handle the division by zero better. It is not true that, say, 4 / 0\n= 0, the result is undefined.</p>\n\n<p>4) The variables <code>zbroj</code> and <code>razlika</code> are only ever used once. Most\nof the time such variables can and should be eliminated, which is\nalso the case here.</p>\n\n<p>The final code, formatted with a compact brace style, would look like this:</p>\n\n<pre><code>#include <stdio.h>\n\nint prompt(const char* name) {\n printf(\"%s\", name);\n int value;\n scanf(\"%d\", &value);\n return value;\n}\n\nint main() {\n printf(\"Mod 1 je za zbrajanje\\n\");\n printf(\"Mod 2 je za oduzimanje\\n\");\n printf(\"Mod 3 je za mnozenje\\n\");\n printf(\"Mod 4 je za dijeljenje\\n\");\n printf(\"U kojem modu zelis biti:\\n\");\n int mod;\n scanf(\"%d\", &mod);\n\n switch (mod)\n {\n case 1: {\n printf(\"Odabrali ste zbrajanje!\\n\");\n int a = prompt(\"a: \");\n int b = prompt(\"b: \");\n printf(\"%d + %d = %d\\n\", a, b, a + b);\n break;\n }\n case 2: {\n printf(\"Odabrali ste oduzimanje!\\n\");\n int a = prompt(\"a: \");\n int b = prompt(\"b: \");\n printf(\"%d - %d = %d\\n\", a, b, a - b);\n break;\n }\n case 3: {\n printf(\"Odabrali ste mnozennje!\\n\");\n int a = prompt(\"a: \");\n int b = prompt(\"b: \");\n printf(\"%d * %d = %d\\n\", a, b, a * b);\n break;\n }\n case 4: {\n printf(\"Odabrali ste dijeljenje! \\n\");\n int a = prompt(\"a: \");\n int b = prompt(\"b: \");\n if (b == 0) {\n printf(\"%d / %d = undefined (divison by zero)\\n\", a, b);\n } else {\n printf(\"%d / %d = %d\\n\", a, b, a / b);\n }\n break;\n }\n default:\n printf(\"Nemamo tu opciju trenutno, prcekajte za nadogradnju programa, ili se javite developeru! \\n\");\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T18:56:27.113",
"Id": "458608",
"Score": "1",
"body": "Oh wow, thanks! i just prefer the way i write it with \"{ }\", because its more readable for me and i'm a beginner still soo.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T19:04:40.830",
"Id": "458609",
"Score": "0",
"body": "also doesn't division by 0 always result with a 0, at least i learnt so by math :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T21:19:44.350",
"Id": "458628",
"Score": "0",
"body": "@Luka Curious. Generally in maths division by zero is undefined. Also, in C and C++, dividing the smallest possible value by -1 is undefined for integral numbers, as the result is not representable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T04:20:47.743",
"Id": "458657",
"Score": "0",
"body": "@Luka I'm curious where this unusual kind of division is taught. I also wonder why you print special messages when either of the operands of the multiplication is zero; `a * b` will happily return the correct answer in that case without any special help. Also, `a / b` will return the correct answer, `0`, if `a` is zero, as long as `b` is not also zero. If I were doing this I would have checked only for `b == 0` in the division code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T18:12:16.543",
"Id": "234499",
"ParentId": "234477",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234492",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T11:36:08.480",
"Id": "234477",
"Score": "4",
"Tags": [
"c++",
"calculator"
],
"Title": "C++ cleaner optimised code, Calculator"
}
|
234477
|
<p>I made an n-body gravitational simulation in python. The algorithm does produce an approximate solution, which is shown at the bottom of the post. Additional methods to produce animations (among other things) <a href="https://github.com/allthemikeysaretaken/NBody-Simulation" rel="nofollow noreferrer">can be found here</a>. I would like to see if efficiency, readability, and/or accuracy can be improved. </p>
<p>The main idea of the algorithm is this: given two bodies of masses <code>m_i</code> and <code>m_j</code> separated by a distance <code>r_ij</code> apart (for <code>i ≠ j</code>), one can calculate the acceleration due to gravity of <code>m_i</code>. This is repeated for all bodies at each iteration of time to get the net acceleration <code>a_i</code> of <code>m_i</code>. The velocity is obtained by integrating the acceleration (since dv = a dt); similarly, displacement is given by integrating velocity. The process repeats for each iteration of time.</p>
<p>For convenience, the class <code>Body</code> contains array attributes such as position, velocity, and acceleration, which are updated at each iteration of time. </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class Body():
"""
This class contains adjustable parameters as attributes. These
parameters include current and previous positions, velocities, and
accelerations.
"""
def __init__(self, identifier, facecolor, position, mass=1, velocity=None, acceleration=None, notes=None):
"""
identifier:
type <str>
facecolor:
type <str>
position:
type <tuple / list / array>
mass:
type <int / float>
velocity:
type <tuple / list / array> or None
acceleration:
type <tuple / list / array> or None
notes:
type <str> or None
"""
self.identifier = identifier
self.facecolor = facecolor
self.position = np.array(position, dtype=float)
self.mass = mass
self.velocity = self.autocorrect_parameter(velocity)
self.acceleration = self.autocorrect_parameter(acceleration)
self._vector_position = [self.position]
self._vector_velocity = [self.velocity]
self._vector_acceleration = [self.acceleration]
self.notes = notes
def __str__(self):
res = ''
for key in ('identifier', 'vector_position'):
value = getattr(self, key)
text = '\n .. {}:\n\t{}\n'.format(key, value)
res += '{}'.format(text)
return res
def autocorrect_parameter(self, args):
"""
args:
type <tuple / list / array> or None
"""
if args is None:
return np.zeros(self.position.shape, dtype=float)
else:
return np.array(args, dtype=float)
@property
def vector_position(self):
return np.array(self._vector_position)
@property
def vector_velocity(self):
return np.array(self._vector_velocity)
@property
def vector_acceleration(self):
return np.array(self._vector_acceleration)
@property
def scalar_position(self):
return np.sqrt(np.sum(np.square(self.vector_position), axis=1))
@property
def scalar_velocity(self):
return np.sqrt(np.sum(np.square(self.vector_velocity), axis=1))
@property
def scalar_acceleration(self):
return np.sqrt(np.sum(np.square(self.vector_acceleration), axis=1))
def get_vector(self, parameter):
"""
parameter:
type <str>
"""
attribute = 'vector_{}'.format(parameter)
return getattr(self, attribute)
def get_scalar(self, parameter):
"""
parameter:
type <str>
"""
attribute = 'scalar_{}'.format(parameter)
return getattr(self, attribute)
</code></pre>
<p>Before creating instances of the <code>Body</code> class, it's important for units to be scaled properly. The class <code>UnitConversions</code> contains convenience methods for this purpose.</p>
<pre><code>class UnitConversions():
"""
This class contains methods to convert measurements from one unit to
another. Measurable quantities include distance, time, velocity, mass,
and acceleration. All values are scaled to their corresponding units
such that each base quantity measured in SI units has a value of 1.
"""
def __init__(self):
self.distance_units = ('meter', 'kilometer', 'mile', 'Astronomical Unit', 'Light Year', 'parsec')
self.distance_values = (1, 1000, 1609, 1.496e11, 9.461e15, 3.086e16)
self.time_units = ('second', 'hour', 'day', 'year')
self.time_values = (1, 3600, 3600*24, 3600*24*365)
self.mass_units = ('gram', 'kilogram', 'lunar mass', 'earth mass', 'solar mass')
self.mass_values = (1/1000, 1, 7.3459e22, 5.9722e24, 1.988e30)
self.distance_conversion_factors = self.get_conversion_factors(self.distance_units, self.distance_values, base_unit='meter')
self.time_conversion_factors = self.get_conversion_factors(self.time_units, self.time_values, base_unit='second')
self.mass_conversion_factors = self.get_conversion_factors(self.mass_units, self.mass_values, base_unit='kilogram')
@staticmethod
def get_conversion_factors(units, values, base_unit):
"""
units:
type <tuple / list / array>
values:
type <tuple / list / array>
base_unit:
type <str>
"""
res = {}
for outer_key, outer_value in zip(units, values):
if outer_key == base_unit:
res[outer_key] = dict(zip(units, values))
else:
res[outer_key] = {}
for inner_key, inner_value in zip(units, values):
res[outer_key][inner_key] = inner_value / outer_value
return res
def convert_distance(self, distance, original_unit, prime_unit='meter'):
"""
distance:
type <int / float / array>
original_unit:
type <str>
prime_unit:
type <str>
"""
conversion_factor = self.distance_conversion_factors[prime_unit][original_unit]
return distance * conversion_factor
def convert_time(self, time, original_unit, prime_unit='second'):
"""
time:
type <int / float / array>
original_unit:
type <str>
prime_unit:
type <str>
"""
conversion_factor = self.time_conversion_factors[prime_unit][original_unit]
return time * conversion_factor
def convert_mass(self, mass, original_unit, prime_unit='kilogram'):
"""
mass:
type <int / float / array>
original_unit:
type <str>
prime_unit:
type <str>
"""
conversion_factor = self.mass_conversion_factors[prime_unit][original_unit]
return mass * conversion_factor
def convert_velocity(self, distance, time, original_distance_unit, original_time_unit, prime_distance_unit='meter', prime_time_unit='second'):
"""
velocity:
type <int / float / array>
original_distance_unit:
type <str>
original_time_unit:
type <str>
prime_distance_unit:
type <str>
prime_time_unit:
type <str>
"""
return self.convert_distance(distance, original_distance_unit, prime_distance_unit) / self.convert_time(time, original_time_unit, prime_time_unit)
def convert_acceleration(self, distance, time, original_distance_unit, original_time_unit, prime_distance_unit='meter', prime_time_unit='second'):
"""
velocity:
type <int / float / array>
original_distance_unit:
type <str>
original_time_unit:
type <str>
prime_distance_unit:
type <str>
prime_time_unit:
type <str>
"""
return self.convert_distance(distance, original_distance_unit, prime_distance_unit) / self.convert_time(time, original_time_unit, prime_time_unit)**2
</code></pre>
<p>The class <code>GravitationalDynamics</code> is used to store and update bodies and their associated parameters. </p>
<pre><code>class GravitationalDynamics():
"""
This class contains methods to run a simulation of N bodies that interact
gravitationally over some time. Each body in the simulation keeps a record
of parameters (position, velocity, and acceleration) as time progresses.
"""
def __init__(self, bodies, t=0, gravitational_constant=6.67e-11):
"""
bodies:
type <tuple / list / array>
t:
type <int / float>
gravitational_constant:
type <float>
"""
self._bodies = bodies
self.nbodies = len(bodies)
self.ndim = len(bodies[0].position)
self.t = t
self._moments = [t]
self.gravitational_constant = gravitational_constant
# self._collision_times = []
@property
def bodies(self):
return self._bodies
@property
def moments(self):
return np.array(self._moments)
def get_acceleration(self, ibody, jbody):
"""
ibody:
type <custom class: Body>
jbody:
type <custom class: Body>
"""
dpos = ibody.position - jbody.position
r = np.sum(dpos**2)
acc = -1 * self.gravitational_constant * jbody.mass * dpos / np.sqrt(r**3)
return acc
def update_accelerations(self):
for ith_body, ibody in enumerate(self.bodies):
ibody.acceleration *= 0
for jth_body, jbody in enumerate(self.bodies):
if ith_body != jth_body:
acc = self.get_acceleration(ibody, jbody)
ibody.acceleration += acc
ibody._vector_acceleration.append(np.copy(ibody.acceleration))
def update_velocities_and_positions(self, dt):
"""
dt:
type <int / float>
"""
for ith_body, ibody in enumerate(self.bodies):
ibody.velocity += ibody.acceleration * dt
ibody.position += ibody.velocity * dt
ibody._vector_velocity.append(np.copy(ibody.velocity))
ibody._vector_position.append(np.copy(ibody.position))
def simulate(self, dt, duration):
"""
dt:
type <int / float>
duration:
type <int / float>
"""
nsteps = int(duration / dt)
for ith_step in range(nsteps):
self.update_accelerations()
self.update_velocities_and_positions(dt)
self.t += dt
self._moments.append(self.t)
## check collisions
</code></pre>
<p>One can use the algorithm above using the commands below. The parameter values of each planet are <a href="https://www.wolframalpha.com/input/?i=orbital%20speed%20of%20mercury" rel="nofollow noreferrer">taken from wolfram alpha</a>.</p>
<pre><code>UC = UnitConversions()
m_sun = UC.convert_mass(1, original_unit='solar mass', prime_unit='kilogram')
Sun = Body(identifier='Sun', facecolor='yellow', mass=m_sun, position=[0, 0, 0])
m_mercury = UC.convert_mass(0.05227, original_unit='earth mass', prime_unit='kilogram')
d_mercury = UC.convert_distance(0.4392, original_unit='Astronomical Unit', prime_unit='meter')
v_mercury = UC.convert_distance(106000, original_unit='mile', prime_unit='meter') / UC.convert_time(1, original_unit='hour', prime_unit='second')
Mercury = Body(identifier='Mercury', facecolor='gray', mass=m_mercury, position=[d_mercury, 0, 0], velocity=[0, v_mercury, 0])
m_earth = UC.convert_mass(1, original_unit='earth mass', prime_unit='kilogram')
d_earth = UC.convert_distance(1, original_unit='Astronomical Unit', prime_unit='meter')
v_earth = UC.convert_distance(66600, original_unit='mile', prime_unit='meter') / UC.convert_time(1, original_unit='hour', prime_unit='second')
Earth = Body(identifier='Earth', facecolor='blue', mass=m_earth, position=[d_earth, 0, 0], velocity=[0, v_earth, 0])
m_mars = UC.convert_mass(0.1704, original_unit='earth mass', prime_unit='kilogram')
d_mars = UC.convert_distance(1.653, original_unit='Astronomical Unit', prime_unit='meter')
v_mars = UC.convert_distance(53900, original_unit='mile', prime_unit='meter') / UC.convert_time(1, original_unit='hour', prime_unit='second')
Mars = Body(identifier='Mars', facecolor='darkred', mass=m_mars, position=[0, d_mars, 0], velocity=[v_mars, 0, 0])
bodies = [Sun, Mercury, Earth, Mars]
dt = UC.convert_time(2, original_unit='day', prime_unit='second')
duration = UC.convert_time(10, original_unit='year', prime_unit='second')
GD = GravitationalDynamics(bodies)
GD.simulate(dt, duration)
</code></pre>
<p>To check that the simulation ran, one can check various parameters of each body in <code>GD.bodies</code>. Alternatively, we can visualize an image using the commands below (animation is provided in github link above). The image on the left shows a sequence of scattered points (one <code>(x, y, z)</code> point with scaling in AU for each time t), and the image on the right shows that the orbits are elliptical (since the closest and farthest points appear periodic over time (AU against years).</p>
<pre><code>fig = plt.figure(figsize=(11, 7))
ax_left = fig.add_subplot(1, 2, 1, projection='3d')
ax_left.set_title('3-D Position')
ax_right = fig.add_subplot(1, 2, 2)
ax_right.set_title('Displacement vs Time')
ts = UC.convert_time(GD.moments, original_unit='second', prime_unit='year')
xticks = np.arange(max(ts)+1).astype(int)
for body in GD.bodies:
vector = body.get_vector('position')
vector_coordinates = UC.convert_distance(vector, original_unit='meter', prime_unit='Astronomical Unit')
scalar = body.get_scalar('position')
scalar_coordinates = UC.convert_distance(scalar, original_unit='meter', prime_unit='Astronomical Unit')
ax_left.scatter(*vector_coordinates.T, marker='.', c=body.facecolor, label=body.identifier)
ax_right.scatter(ts, scalar_coordinates, marker='.', c=body.facecolor, label=body.identifier)
ax_right.set_xticks(xticks)
ax_right.grid(color='k', linestyle=':', alpha=0.3)
fig.subplots_adjust(bottom=0.3)
fig.legend(loc='lower center', mode='expand', ncol=len(GD.bodies))
plt.show()
plt.close(fig)
</code></pre>
<p><a href="https://i.stack.imgur.com/IijBx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IijBx.png" alt="Example Figure"></a></p>
<p>I should note that the simulation is only an approximation. Using both autocorrelation and power spectral density in a simulation containing all 8 planets of our solar system, some of the orbital periods appear exact (such Earth using velocity or acceleration), while others are off by some non-negligible amount (such as Mercury). I don't know whether or not to attribute this to float precision, the method of integration, the use of a discrete time-step to describe continuous motion, or the lack of relativity. That said, the method works for the lower-order case; the figure above shows that Earth's orbital period is one year, with fluctuations about 1 AU. </p>
<p>How can this algorithm be improved? Is anything implemented above something to be frowned upon? Trying to "self-learn" as much as possible, so (please) don't be nice.</p>
|
[] |
[
{
"body": "<p>Below is a list of my suggestions. You can find my changes to\nyour code here:\n<a href=\"https://gist.github.com/bjourne/6270cff58c0238bb863e189ea63d6254\" rel=\"nofollow noreferrer\">https://gist.github.com/bjourne/6270cff58c0238bb863e189ea63d6254</a></p>\n\n<h2>Kill your darlings</h2>\n\n<p>There's a saying in movie production that one must <a href=\"https://en.wiktionary.org/wiki/kill_one%27s_darlings\" rel=\"nofollow noreferrer\">kill one's\ndarlings</a>. It\nmeans that if something is not serving it's purpose it must be deleted\neven if the author is fond of it or has worked very hard with it. I\ncan tell that you have worked hard with the <code>UnitConversions</code> class,\nbut it is an example of such a darling. You can replace it with\nconstants:</p>\n\n<pre><code># Masses\nSOLAR_MASS = 1.988e30\nEARTH_MASS = 5.9722e24\n\n# Distances\nASTRO_UNIT = 1.496e11\nMILE = 1609\n\n# Durations\nHOUR = 3600\nDAY = 24 * HOUR\nYEAR = 365 * DAY\n\nm_earth = 1 * EARTH_MASS\nd_earth = 1 * ASTRO_UNIT\nv_earth = (66_600 * MILE) / (1 * HOUR)\n</code></pre>\n\n<h2>Put code in functions or classes</h2>\n\n<p>It looks like your main code is running at the module level. That can\ncause weird problems with shadowed variables. I suggest always using\nthe following structure:</p>\n\n<pre><code>def main():\n ... main code here...\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h2>Follow PEP 8</h2>\n\n<p>You are violating some of the style guidelines in <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP\n8</a>. For example, you use\ninitial uppercase letters in some variable names and many lines are\nlonger than 79 characters.</p>\n\n<h2>Delete stuff you don't use</h2>\n\n<p>I found lots of ununsed variables and methods in the <code>Body</code> class;\n<code>notes</code>, <code>__str__()</code>, <code>scalar_velocity()</code>, <code>scalar_acceleration()</code>,\n<code>vector_acceleration()</code>, and <code>vector_velocity()</code>.</p>\n\n<h2>Don't put type declarations in comments</h2>\n\n<p>Personally, I'm not a fan of Python's optional type declarations. But\nif you want to use them, you should put them in the parameter lists\nlike this</p>\n\n<pre><code>def get_vector(self, parameter: str):\n attribute = 'vector_{}'.format(parameter)\n return getattr(self, attribute)\n</code></pre>\n\n<p>and not in the comments.</p>\n\n<h2>Prefer positional arguments over keyword arguments</h2>\n\n<p>What I mean is that instead of</p>\n\n<pre><code>Sun = Body(identifier='Sun', facecolor='yellow',\n mass=m_sun, position=[0, 0, 0])\n</code></pre>\n\n<p>you can just write</p>\n\n<pre><code>Sun = Body('Sun', 'yellow', [0, 0, 0], m_sun)\n</code></pre>\n\n<p>which makes the code less verbose. Keyword arguments are sometimes\nuseful but I don't think they are useful in your code.</p>\n\n<h2>Avoid \"magic\"</h2>\n\n<p>Using features that depend on introspection makes code harder to\nunderstand. So instead of</p>\n\n<pre><code>def get_scalar(self, parameter):\n attribute = 'scalar_{}'.format(parameter)\n return getattr(self, attribute)\n...\nscalar = body.get_scalar('position')\n</code></pre>\n\n<p>simply write</p>\n\n<pre><code>scalar = body.scalar_position\n</code></pre>\n\n<h2>Avoid @property</h2>\n\n<p>Methods declared as properties can be misleading to readers because\nthe method call is \"hidden.\" I would suggest avoiding them unless you\nhave compelling reasons to use them (that they look nice is not a good\nreason :)).</p>\n\n<h2>Don't hide privates</h2>\n\n<p>Java recommends you to hide implementation details. But that is not\nthe case in Python and it is ok for users of objects to access member\nattributes directly.</p>\n\n<h2>Consider using abbreviations</h2>\n\n<p>Shorter variable names are preferable because they are easier to\nread. On the other hand, short names doesn't carry as much information\nas long ones so one has to try and find a happy middle ground. In your\ncode, I suggest that you use <code>pos</code>, <code>vel</code> and <code>acc</code> as\nabbreviations for <code>position</code>, <code>velocity</code> and <code>acceleration</code>\nrespectively. For someone interested in N-body simulations, these\nabbreviations should be self-explanatory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T11:21:52.930",
"Id": "458883",
"Score": "1",
"body": "Thank you for the feedback. The only thing I disagree about is the part about \"killing the darlings\". That code block is not necessary for the code snippet shown, but is useful in the full code on github. I did not put the full code because the snippet above is already kind of long and not needed to create a functional example, plus I was hoping to improve the code in terms of efficiency / accuracy. That said, I agree with all of your other corrections and criticisms."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T17:04:01.903",
"Id": "234598",
"ParentId": "234478",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234598",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T11:40:43.420",
"Id": "234478",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"numpy",
"simulation",
"physics"
],
"Title": "N-Body Gravitational Simulation of Point-Masses in Python"
}
|
234478
|
<p>I am creating a simple model relation in ASP.Net core. My model relations are like this:</p>
<ol>
<li>A user can have many posts</li>
<li>A post can have many comments</li>
<li>A user can have many comments</li>
</ol>
<p>Now I am trying to seed the relations using the dbcontext. I have a feeling that I am doing something wrong. Can anybody determine if I am doing it the right way or something can be improved?</p>
<p>Base entity has create and update timestamp only.</p>
<p><strong>User model</strong></p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Transactions;
namespace SocialAppApi.Models
{
public class User : BaseEntity
{
[DatabaseGenerated( DatabaseGeneratedOption.Identity )] [Column( "id", Order = 1 )]
public int Id { get; set; }
[Column( "first_name", TypeName = "VARCHAR(100)", Order = 2 )]
public string FirstName { get; set; }
[Column( "middle_name", TypeName = "VARCHAR(100)", Order = 3 )]
public string MiddleName { get; set; }
[Column( "last_name", TypeName = "VARCHAR(100)", Order = 4 )]
public string LastName { get; set; }
public ICollection< Comment > Comments { get; set; }
public ICollection<Post> Posts { get; set; }
}
}
</code></pre>
<p><strong>Post model</strong></p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace SocialAppApi.Models
{
public class Post : BaseEntity
{
[DatabaseGenerated( DatabaseGeneratedOption.Identity )]
[Column( "id", Order = 1 )]
public int Id { get; set; }
[Column( "content", TypeName = "VARCHAR(MAX)", Order = 2 )]
public string Content { get; set; }
[Column( "image", TypeName = "VARCHAR(255)", Order = 3 )]
public string Image { get; set; }
//Foreign keys
[Column( "user_id" )]
[ForeignKey( "id" )]
public int UserId { get; set; }
public User User { get; set; }
public ICollection< Comment > Comments { get; set; }
}
}
</code></pre>
<p><strong>Comment model</strong></p>
<pre><code>using System.ComponentModel.DataAnnotations.Schema;
namespace SocialAppApi.Models
{
public class Comment : BaseEntity
{
[DatabaseGenerated( DatabaseGeneratedOption.Identity )]
[Column( "id", Order = 1 )]
public int Id { get; set; }
[Column( "content", TypeName = "VARCHAR(MAX)", Order = 2 )]
public string Content { get; set; }
public User User { get; set; }
[Column( "user_id", Order = 3 )]
[ForeignKey( "id" )]
public int UserId { get; set; }
public Post Post { get; set; }
[Column( "post_id", Order = 4 )]
[ForeignKey( "id" )]
public int PostId { get; set; }
}
}
</code></pre>
<p><strong>And finally my seeder class</strong></p>
<pre><code>using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SocialAppApi.Models;
using SocialAppApi.Repositories;
namespace SocialAppApi.Seeders
{
public class DatabaseSeeder
{
public static void SeedDatabase( ApplicationDbContext applicationDbContext )
{
applicationDbContext.Database.Migrate();
if ( !applicationDbContext.Users.Any() )
{
User user1 = new User
{
FirstName = "Bikram",
LastName = "Bhandari",
};
User user2 = new User
{
FirstName = "Sabina",
LastName = "Lamichhane",
};
User user3 = new User
{
FirstName = "Jack",
LastName = "Wonderland",
};
Post user1Post = new Post
{
Content = "This post is about fires going on in NSW"
};
List< Comment > user1PostComments = new List< Comment >
{
new Comment {Content = "So sad to see this"},
new Comment {Content = "Let's hope for a rain"},
};
//add user1 post
user1.Posts = new List< Post > {user1Post};
**Is this right?**
user1Post.Comments = user1PostComments;
user1.Comments = user1PostComments;
**Those two lines above**
//add user1 post comments
applicationDbContext.Users.AddRange( user1, user2, user3 );
applicationDbContext.SaveChanges();
}
}
}
}
</code></pre>
<p>Questions:</p>
<ol>
<li>Can seeder class be modified to set one to many relations easily?</li>
<li>Is it a good practice to have <code>userId</code> in the comment model?</li>
<li><p>While running a migration, I had to change <code>onDelete: ReferentialAction.Cascade</code> to <code>onDelete: ReferentialAction.NoAction</code> because it was complaining as this:</p>
<blockquote>
<p>introducing foreign key on table may cause cycles or multiple paths</p>
</blockquote></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T13:33:40.207",
"Id": "458564",
"Score": "0",
"body": "Why do you feel you are doing something wrong? Is the code working as expected now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T21:58:37.743",
"Id": "458632",
"Score": "0",
"body": "I don't think this can be working code. The foreign keys in `Comment` should be nullable otherwise each comment should belong to a User *and* a Post. If you have questions on how to model this correctly you should turn to Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T23:17:51.600",
"Id": "458642",
"Score": "0",
"body": "@GertArnold Does not a comment belongs to a user in a real-life scenario?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T13:18:21.010",
"Id": "458695",
"Score": "0",
"body": "OK, in a sense Comment is a junction between Post and User. Yes that's possible. I first understood that there were comments on users and/or on posts. But then about your questions. What is not \"easy\" at the moment? The 3rd question isn't relevant here IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T04:46:11.460",
"Id": "458752",
"Score": "0",
"body": "@GertArnold for the 3rd question, I assumed that the person reviewing my code will have the idea of migration. Anyway thank you for your response :)"
}
] |
[
{
"body": "<p>By default, Entity Framework will create the foreign key with the name of the entity primary key that is referenced by the navigation property. </p>\n\n<pre><code>// Navigation Propertites //\n\n// (one-to-x) relation \npublic User User { get; set; } \n\n// (many-to-x) relation\npublic ICollection<User> Users { get; set; } \n\n// works vice versa \n</code></pre>\n\n<p>For the <code>ForeignKey</code> attribute : </p>\n\n<pre><code>//########### Version 1 ###########\npublic int UserId { get; set; }\n\n[ForeignKey( \"UserId\" )] // refer to the UserId (the foreign key) Property\npublic User User { get; set; }\n\n\n//########### Version 2 ###########\n[ForeignKey( \"User\" )] // refer to the User Navigation Property\npublic int UserId { get; set; } // will create this FK with the exact name (UserId)\n\npublic User User { get; set; }\n</code></pre>\n\n<p>both versions will create a foreign key column named <code>UserId</code>. as it's also, a vice versa configuration. So, you just need to change the name of each <code>ForeignKey</code> attribute to target its correct property. </p>\n\n<p>Also, <code>ForeignKey</code> is handy if you want a custom naming for your foreign keys, but in your case, you're rewriting what entity framework does. If both entities primary key name are the same,then it'll rename it to <code>EntityName_ForeignKeyName</code>. For example, <code>User_Id</code>. Which what you did explicitly. </p>\n\n<p>I would also suggest using EF fluent API to control the models instead of using <code>Data Annotations</code> attributes. It has more control than attributes, and it's also readable.</p>\n\n<p>you can use <code>OnModelCreating</code> to configure your models with <code>DbModelBuilder</code>. You can create a class to configure all models so you only pass <code>DbModelBuilder</code> to the constructor, something I do with large entities, I love to keep the configuration for the entities in one place. So, it's more flexible. </p>\n\n<p>So, converting your attributes to EF fluent API would be : </p>\n\n<pre><code>public partial class ApplicationDbContext : DbContext\n{\n public ApplicationDbContext () : base(\"name=DbContext\")\n {\n\n }\n\n public virtual DbSet<Comment> Comments { get; set; }\n public virtual DbSet<Post> Posts { get; set; }\n public virtual DbSet<User> Users { get; set; }\n\n protected override void OnModelCreating(DbModelBuilder modelBuilder)\n {\n /*\n User \n */\n modelBuilder.Entity<User>()\n .Property(p => p.Id)\n .HasColumnName(\"id\")\n .HasColumnOrder(1)\n .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);\n\n modelBuilder.Entity<User>()\n .Property(e => e.FirstName)\n .HasColumnName(\"first_name\")\n .HasMaxLength(100)\n .HasColumnOrder(2)\n .IsUnicode(false);\n\n modelBuilder.Entity<User>()\n .Property(e => e.MiddleName)\n .HasColumnName(\"middle_name\")\n .HasMaxLength(100)\n .HasColumnOrder(3)\n .IsUnicode(false);\n\n modelBuilder.Entity<User>()\n .Property(e => e.LastName)\n .HasColumnName(\"last_name\")\n .HasMaxLength(100)\n .HasColumnOrder(4)\n .IsUnicode(false);\n\n // Foreign Keys\n modelBuilder.Entity<User>()\n .HasMany(e => e.Comments)\n .WithRequired(e => e.User)\n .HasForeignKey(e => e.UserId)\n .WillCascadeOnDelete(false);\n\n modelBuilder.Entity<User>()\n .HasMany(e => e.Posts)\n .WithRequired(e => e.User)\n .HasForeignKey(e => e.UserId);\n\n /*\n Post \n */ \n modelBuilder.Entity<Post>()\n .Property(p => p.Id)\n .HasColumnName(\"id\")\n .HasColumnOrder(1)\n .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);\n\n modelBuilder.Entity<Post>()\n .Property(e => e.Content)\n .HasColumnName(\"content\")\n .HasColumnOrder(2)\n .IsUnicode(false);\n\n modelBuilder.Entity<Post>()\n .Property(e => e.Image)\n .HasColumnName(\"image\")\n .HasMaxLength(255)\n .HasColumnOrder(3)\n .IsUnicode(false);\n\n // Foreign Keys\n modelBuilder.Entity<Post>()\n .HasMany(e => e.Comments)\n .WithRequired(e => e.Post)\n .HasForeignKey(e => e.PostId);\n\n /*\n Comment \n */\n modelBuilder.Entity<Comment>()\n .Property(p => p.Id)\n .HasColumnName(\"id\")\n .HasColumnOrder(1)\n .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);\n\n modelBuilder.Entity<Comment>()\n .Property(e => e.Content)\n .HasColumnName(\"content\")\n .HasColumnOrder(2)\n .IsUnicode(false); \n\n }\n\n} \n</code></pre>\n\n<p>For the models structure, it's fine. but I think it can be improved. I think there is no need for <code>Comments</code> and <code>Posts</code> in <code>User</code> and <code>Post</code> for a couple of reasons. The most obvious reason is <code>performance</code>. assume you need to query User entity to get all current users, each user will be stored along with his posts and comments. The more users, the more collections. This would consume a lot of memory and also affect the performance as well, especially with large entities. So, separating entities and keep each one of them store its own data, is a good practice. There are some cases where using collections of other entities is a must, but always rethink about it before including it. Another reason is to minimize the code redundancy. </p>\n\n<p>so, taking your models, we can do this : </p>\n\n<pre><code>public class User\n{\n public int Id { get; set; }\n\n public string FirstName { get; set; }\n\n public string MiddleName { get; set; }\n\n public string LastName { get; set; }\n}\n\npublic class Post\n{\n public int Id { get; set; }\n\n public string Content { get; set; }\n\n public string Image { get; set; }\n\n public User User { get; set; }\n}\n\n\npublic class Comment\n{\n public int Id { get; set; }\n\n public string Content { get; set; }\n\n public Post Post { get; set; }\n\n public User User { get; set; }\n}\n</code></pre>\n\n<p>and the process would something like this : </p>\n\n<pre><code>var user1 = new User\n{\n FirstName = \"Bikram\",\n LastName = \"Bhandari\",\n};\n\nvar user2 = new User\n{\n FirstName = \"Sabina\",\n LastName = \"Lamichhane\"\n};\n\nvar user3 = new User\n{\n FirstName = \"Jack\",\n LastName = \"Wonderland\"\n};\n\nvar post1 = new Post\n{\n User = user1,\n Content = \"This post is about fires going on in NSW\"\n};\n\n\nvar comments = new List<Comment>\n{\n new Comment\n {\n User = user1,\n Post = post1,\n Content = \"So sad to see this\"\n },\n new Comment\n {\n User = user1,\n Post = post1,\n Content = \"Let's hope for a rain\"\n }\n};\n\n\napplicationDbContext.Users.AddRange(new List<User> { user1, user2, user3 });\n\napplicationDbContext.Posts.Add(post1);\n\napplicationDbContext.Comments.AddRange(comments);\n\napplicationDbContext.SaveChanges();\n</code></pre>\n\n<p>The collection then can be used on your business logic where needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T07:56:54.973",
"Id": "459108",
"Score": "0",
"body": "thank you for the detailed information. Now i am trying fluent API."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T04:17:18.390",
"Id": "234620",
"ParentId": "234481",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234620",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T12:45:42.717",
"Id": "234481",
"Score": "1",
"Tags": [
"c#",
"asp.net",
"entity-framework",
"entity-framework-core"
],
"Title": "ASP.NET EF seed one to many relation"
}
|
234481
|
<p>Say you have an array that is "semi-sorted", e.g. something like this:</p>
<p>[7,8,9,10,1,2,3,4,5,6]</p>
<p>Where a part of the end of the sorted array was transferred to the beginning. </p>
<p>Is there a way to still find an element in it in <code>log(n)</code> time?</p>
<p>Here's my solution:</p>
<pre><code>def findVal(arr, val):
return helper(arr, 0, len(arr) - 1, val)
def helper(arr, start, end, val):
if (start > end) :
return False # empty array
mid = start + (end - start) // 2
if (arr[mid] == val):
return True
if (mid == 0):
return False # 1 element array which is not the value
rightSorted = arr[mid] <= arr[end]
if (rightSorted):
if (val > arr[mid] and val <= arr[end]):
return helper(arr, mid + 1, end, val)
else:
return helper(arr, start, mid - 1, val)
else:
if (val < arr[mid] and val >= arr[start]):
return helper(arr, start, mid - 1, val)
else:
return helper(arr, mid + 1, end, val)
</code></pre>
<p>I guess you could also do this with a simple while loop instead of recursion. </p>
|
[] |
[
{
"body": "<p>I spend some more time refining the solutions. Also found a relevant question that asks to find the min/max of the array <a href=\"https://codereview.stackexchange.com/q/29090/165135\">here</a>.</p>\n<h1>Problem Context</h1>\n<p>Searching a value in an array can be up to <code>O(n)</code> in time complexity - you have to iterate through the array and check for each element if it's equal the search value. But - if the array is sorted, this is reduced to <code>O(log(n))</code> due to a strategy called <strong>Binary Search</strong>. Binary search allows us at each time cut half of the options to consider. You check the middle element in the array, if the search value is bigger you can discard the lower half, if it's lower you can discard the upper half, and now you do the same for the remaining array - until you either find the value or end up with an empty/1-element array - in that case the element is not in the array.</p>\n<p>Here there is a problem that the array is swapped - the question is can we still reduce the time complexity to <code>O(log(n))</code> ?</p>\n<p>The key insight here is that <strong>even though the array itself is not perfectly sorted, at least half of it IS</strong> - and so we can always tell something about that half, and reduce our scope. This is true for every sub-division we make of the array - at least half of it will be sorted (and in some cases, both halves).</p>\n<p>If we are looking for the min/max value, we basically don't care about the part that is sorted, because the pivot value will be in the other half (though the mid value should be included, as it can be the min/max value) - so we can discard the sorted part.</p>\n<p>If we are looking for a specific value - we can automatically check if our value is in the range of the sorted half, if it is we discard the non-sorted half, and focus on the sorted. If it's not we focus on the non-sorted - and do the same.</p>\n<h1>Find Min value</h1>\n<p>Here is a solution in python - here we check if the right half is sorted. If it is, we reduce our scope to the left half. If not, we reduce our scope to the right half (note that in that case we can safely discard the mid point and move beyond it).</p>\n<pre><code>def findMin(arr):\n start = 0\n end = len(arr) - 1\n while(start < end):\n mid = (start + end) // 2\n rightSorted = arr[mid] < arr[end]\n if rightSorted:\n end = mid\n else:\n start = mid + 1\n return arr[start]\n</code></pre>\n<p>The decision to check the right is not arbitrary - it is necessary in case we search for a min value. If we instead search the left, and find out it is sorted - we could not confidently discard that half, as the array might be perfectly sorted - in that case the 0th element is the minimum. So we choose the right in order to be completely sure we still have the min value in the sub array.</p>\n<h1>Find Max value</h1>\n<p>In python this is actually very easy - you just need to go one element before the minimum - and even if the min is in 0 position, python interprets -1 as the last element of the array. So you could just use the same code as above, but with <code>return arr[start-1]</code>.</p>\n<p>Alternatively, we could reverse the min function above:</p>\n<pre><code>def findMax(arr):\n start = 0\n end = len(arr) - 1\n while(start < end):\n mid = (start + end) // 2\n leftSorted = arr[mid] > arr[start]\n if leftSorted:\n start = mid\n else:\n end = mid - 1\n return arr[start]\n</code></pre>\n<h1>Finding a specific value</h1>\n<p>If we want to check if a specific value exists in the array - the same key insight hold.</p>\n<pre><code>def findVal(arr, val): \n start = 0\n end = len(arr) - 1 \n while(start < end):\n mid = (start + end) // 2\n leftSorted = arr[start] <= arr[mid]\n if leftSorted:\n if val >= arr[start] and val <= arr[mid]:\n end = mid\n else:\n start = mid + 1\n else:\n if val >= arr[mid] and val <= arr[end]:\n start = mid\n else:\n end = mid - 1\n return val == arr[start]\n</code></pre>\n<p>A few differences:</p>\n<ol>\n<li><p>we have to check if our value is in the sorted half, and if not discard it.</p>\n</li>\n<li><p>we have to watch out for the case of 2 elements in an ordered array. The issue here is that if we are not careful, we can end up in an endless loop - because the mid point will be either the 1st or the 2nd, depending if we are using a floor or a ceil operation. Since the default python <code>//</code> operation is a floor, mid will be equal to start, and we have to check the left side in order to either choose the 1st or discard it. [if we use ceil, we should check the right side]</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T14:00:36.407",
"Id": "458698",
"Score": "1",
"body": "Why did you post the initial code in Java and the answer in Python? What made you do this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T18:37:00.413",
"Id": "458709",
"Score": "0",
"body": "The languages don't really matter, and while the problem was first presented to me in an interview in Java, I found it easier to work on it now in Python. Also, as mentioned in part of the answer, it is also easier to find the max value in python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:23:52.683",
"Id": "458718",
"Score": "0",
"body": "On Code Review, details matter. The language is more than a detail. Perhaps you were looking for a different site after all, please take a look at our [help/on-topic]."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T13:14:52.853",
"Id": "234533",
"ParentId": "234486",
"Score": "1"
}
},
{
"body": "<p>The solution seems to be very specific to having exactly two parts of the list interchanged.</p>\n\n<p>I'd be more tempted to write something more general, for when there might be many such sorted subsections.</p>\n\n<ul>\n<li>Make a single pass through the list and initialize a table that records each segment's starting and ending indexes (or start index and length).</li>\n<li>Sort that table based on the value at the starting index.</li>\n</ul>\n\n<p>Then, to perform a search:</p>\n\n<ul>\n<li>Binary search the table to determine the appropriate section.</li>\n<li>Binary search the section of the list.</li>\n</ul>\n\n<p>Note that if the table ends up being huge, this approach isn't appropriate.</p>\n\n<hr>\n\n<p>If one always knew for sure that the original list was always in only two parts, it might seem that it would be faster and easier to write very specific code.</p>\n\n<p>But if the general algorithm is applied to that simple case, in practice it does almost no more work than the ad hoc method.</p>\n\n<p>Specific problems are often best solved by general solutions.</p>\n\n<p>In the real world, next week, next month, or next year, your teacher, your boss, or your client will eventually say, \"<em>That program was great. Can you change it to handle <strong>three</strong> sections of sorted data?</em>\". The original special purpose approach will take considerable work to change (and even if it isn't a lot, realized that eventually you'll be asked for four sections). The general approach will be trivial (update the documentation), but you don't need to let your boss or client know that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T14:54:21.433",
"Id": "234535",
"ParentId": "234486",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T14:04:58.897",
"Id": "234486",
"Score": "1",
"Tags": [
"python",
"array",
"binary-search"
],
"Title": "Semi sorted binary search"
}
|
234486
|
<h1>Sum Strings</h1>
<p><a href="https://www.codewars.com/kata/sum-strings-as-numbers/train/javascript" rel="nofollow noreferrer">Codewars kata</a>.</p>
<p>It's supposed to be able to handle big integers.</p>
<p> </p>
<h2>Question</h2>
<blockquote>
<p>Given the string representations of two integers, return the string representation of the sum of those integers.</p>
<p>For example:</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>sumStrings('1','2') // => '3'
</code></pre>
<blockquote>
<p>A string representation of an integer will contain no characters besides the ten numerals "0" to "9".</p>
</blockquote>
<p> </p>
<h2>Solution</h2>
<pre class="lang-js prettyprint-override"><code>"use strict";
const reverseArr = s => s.split("").reverse();
function sumStrings(a, b) {
[a, b] = [reverseArr(a), reverseArr(b)];
let carry = 0;
const arr = []
const [mx, mn] = (a.length >= b.length) ? [a, b] : [b, a];
mx.forEach((itm, idx) => {
let sm = Number(itm) + (Number(mn[idx]) || 0) + carry;
[sm, carry] = sm > 9 ? [sm%10, 1] : [sm, 0];
arr.unshift(sm)
})
if (carry) arr.unshift(carry);
return arr.join("").replace(/^(0+)/, "");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T23:01:51.827",
"Id": "458639",
"Score": "0",
"body": "Can you describe your solution? Why do you reverse arrays so much?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T03:29:40.320",
"Id": "458654",
"Score": "0",
"body": "@dustytrash the solution is supposed to be able to handle big integers. I reverse the strings to make iteration from the end easier (this is not required as I could just start from the last index and use a for loop. but I wanted to use `.forEach()`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T09:50:08.560",
"Id": "458677",
"Score": "0",
"body": "Why the replace, are the input values carrying leading zeros? eg `sumStrings(\"002\", \" 005\")`. If so why is `\"007\"` not a valid return? BTW your function returns `\"\"` rather than `\"0\"` for `sumStrings(\"0\", \"0\")`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T10:39:05.807",
"Id": "458685",
"Score": "0",
"body": "@Blindman67 my function sometimes produces results like \"0987\" as output, and it's supposed to have leading zeros stripped. I guess I'll handle the edge case."
}
] |
[
{
"body": "<h2>JavaScript style</h2>\n<ul>\n<li><p>Delimit cod blocks with <code>{}</code>. Eg <code>if (foo) bar = 0;</code> should be <code>if (foo) { bar = 0; }</code></p>\n</li>\n<li><p>Use semicolons consistently!</p>\n</li>\n<li><p>Avoid <code>Array.unshift</code> as it is much slower than <code>Array.push</code>. If you know the size of the array pre-allocate the array <code>new Array(size)</code> and then pput items on the array via an index. (See example)</p>\n</li>\n<li><p>Be wary of destructuring as it can sometimes be rather slow (engines converting the right side to array (like) before assigning to the left). As destructuring becomes more main stream and JS engines stabilize new features destructuring has and will continue to improve in terms of performance.</p>\n</li>\n</ul>\n<h2>Complexity.</h2>\n<p>Your function is too complex!</p>\n<p>The complexity of this function is <span class=\"math-container\">\\$O(n)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the number of digits in the result. A well written function should thus have a performance that is related linearly to <span class=\"math-container\">\\$n\\$</span> however your functions performance does not have this relationship, demonstrating a logarithmic performance (approx) <span class=\"math-container\">\\$O(n^2)\\$</span> making it very slow for large numbers.</p>\n<p>The reason is your use of <code>Array.unshift</code>. Each time you unshift a value to the array each item on the array needs to be moved up by one item. This is compounded every time the array size doubles as jS will then create a new array, and copy all the items to that array. As JS is a managed environment and memory is not cleaned up until the function exits or is forced by low memory your function not only has high time complexity but on theoretically infinite memory machines also has a storage complexity of <span class=\"math-container\">\\$O(n^2)\\$</span></p>\n<h2>Rewrites</h2>\n<p>The rewrites are both <span class=\"math-container\">\\$O(n)\\$</span> time and space complex, where <span class=\"math-container\">\\$n\\$</span> is number of digits in the result (including leading zeros).</p>\n<p>rather than revers the digits the code pre-allocates the result array with the required number of digits and then works from the least significant digit up.</p>\n<p>Note that when the index into the strings <code>a</code> or <code>b</code> is less than 0 the coercion forced by the bitwise OR 0 <code>| 0</code> will convert <code>undefined</code> to the number <code>0</code>.</p>\n<p>Ignoring leading zeros (assumes that there are no leading zeros for values over 0)</p>\n<pre><code>"use strict";\nfunction sumStrings(a, b) {\n var carry = 0, i = a.length, j = b.length, k = i > j ? i : j;\n const res = new Array(k);\n while (i > 0 || j > 0) {\n const sum = (a[--i] | 0) + (b[--j] | 0) + carry;\n res[--k] = sum % 10;\n carry = (sum > 9 && 1) || 0;\n }\n return (carry ? carry : "") + res.join("");\n}\n</code></pre>\n<p>The next version will accept leading zeros truncating the result string if there is no carry on the last digit. The truncation is at the last non zero digit encountered.</p>\n<pre><code>"use strict";\nfunction sumStrings(a, b) {\n var carry = 0, i = a.length, j = b.length, k = i > j ? i : j, lastNonZero = k;\n const res = new Array(k);\n while (i > 0 || j > 0) {\n const sum = (a[--i] | 0) + (b[--j] | 0) + carry;\n lastNonZero = sum ? k : lastNonZero;\n res[--k] = sum % 10;\n carry = (sum > 9 && 1) || 0;\n }\n return carry ? carry + res.join("") : res.join("").slice(lastNonZero -1); \n}\n</code></pre>\n<h2>BigInt?</h2>\n<p>You could also have just parsed the two strings as BigInt but that is not the point of the exercise.</p>\n<p>The summing algorithm is a basic component of computing, the algorithm will also work on any number base. Eg Binary base 2 Hex base 16.</p>\n<p>With only minor modifications the function will handle any base and never actually add any numbers</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T10:56:38.710",
"Id": "234525",
"ParentId": "234490",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T14:50:26.367",
"Id": "234490",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"programming-challenge",
"strings",
"integer"
],
"Title": "Codewars: Sum Strings"
}
|
234490
|
<p>Sometimes, I have a lot of things I want to ask the Internet, so I decided to make my searches go faster with some automation...</p>
<p>But I think this could be programmed better, even though I think it's pretty compact.</p>
<pre><code>from subprocess import call
with open("C:\\Users\\Andy\\Desktop\\queries.txt").read().splitlines() as f, 0 as i:
while True:
if (((not i) + i) % 2) != 0:
call('start firefox.exe https://duckduckgo.com/?q=' + f[i].replace(" ", "+"), shell=True)
else:
call('start firefox.exe https://duckduckgo.com/?q=' + f[i].replace(" ", "+"), shell=True)
call('timeout 120')
i += 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T12:01:29.493",
"Id": "458773",
"Score": "0",
"body": "@Carcigenicate - So... Is this question good? You got an answer? If you downvoted, can I get a reversal? ... Basically commenting to bump this post..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T13:40:34.747",
"Id": "458781",
"Score": "0",
"body": "Reversed. Give me a few hours to get stuff done and I can make some suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:05:17.347",
"Id": "458784",
"Score": "0",
"body": "This code is still broken. `0 as i` causes exception because numbers can't be used in context managers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:07:56.040",
"Id": "458786",
"Score": "0",
"body": "And `...splitlines() as f` seems broken too, since that would be using a list in a context manager. Again, we need working code to review. This won't run."
}
] |
[
{
"body": "<p>This code still doesn't work.</p>\n\n<pre><code>with open(\"C:\\\\Users\\\\Andy\\\\Desktop\\\\queries.txt\").read().splitlines() as f, 0 as i:\n</code></pre>\n\n<p>will cause two errors since lists and integers don't have an <code>__enter__</code> method.</p>\n\n<p>I still know roughly what you're going for though, so I can make some suggestions about the rest of the code.</p>\n\n<hr>\n\n<p>Even if <code>0 as i</code> did work, that would be an abuse of <code>with</code>. If you want to define a variable, just use the typical <code>i = 0</code> syntax.</p>\n\n<hr>\n\n<p>Your condition in the <code>if</code> is far over complicated. Running it, the intent seems to be just to check if a number is odd or zero. That can be made much simpler:</p>\n\n<pre><code>if i % 2 == 1 or i == 0:\n</code></pre>\n\n<hr>\n\n<p>You duplicate</p>\n\n<pre><code>call('start firefox.exe https://duckduckgo.com/?q=' + f[i].replace(\" \", \"+\"), shell=True)\n</code></pre>\n\n<p>in each branch of the <code>if</code>. That's not necessary though. Really, that whole check is just so you can add a timeout if <code>i</code> is even. That bit can be reduced down to</p>\n\n<pre><code>while True:\n call('start firefox.exe https://duckduckgo.com/?q=' + f[i].replace(\" \", \"+\"), shell=True)\n\n if i % 2 == 0 and i != 0:\n call('timeout 120')\n\n i += 1\n</code></pre>\n\n<hr>\n\n<p>You could also get rid of the need for <code>i += 1</code> but iterating over a <a href=\"https://docs.python.org/2/library/itertools.html#itertools.count\" rel=\"nofollow noreferrer\">count</a> object instead. It's basically an infinite <code>range</code>:</p>\n\n<pre><code>for i in count():\n call('start firefox.exe https://duckduckgo.com/?q=' + f[i].replace(\" \", \"+\"), shell=True)\n\n if i % 2 == 0 and i != 0:\n call('timeout 120')\n</code></pre>\n\n<p>Of course though, this maintains the impossible condition that <code>f</code> is a file of infinite length.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T16:21:42.343",
"Id": "458804",
"Score": "0",
"body": "Since you've just answered, and thank you for that, should I update the question with working code, or does that change the question too much? ... And yeah, I would like it to automatically stop when it hits the end of the file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T16:24:44.530",
"Id": "458805",
"Score": "0",
"body": "@Malady No, code in questions can't be altered once posted as a general rule. In the future, please just make sure the code you post is working. Arguably I shouldn't have answered, but some aspects were separate from the broken parts, so I could comment on them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T16:05:36.123",
"Id": "234593",
"ParentId": "234495",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T17:42:17.957",
"Id": "234495",
"Score": "-4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Rapidly searching the internet with small breaks"
}
|
234495
|
<p>Wracking my brain trying to figure this out. I'm not the greatest with Jquery but know enough to kinda get by. Right now I am trying to develop something that will check if a radio button in a group is checked and then to see if its value matches so it can then show the correct corresponding section. I have a crude JSFiddle made that is close to my staging site's set up. </p>
<p>HTML:</p>
<pre><code><div>
<label>Oak</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Oak_0' checked="checked">
<label>Brown Maple</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Brown Maple_1'>
<label>Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Cherry_2'>
<label>Quartersawn White Oak</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Quartersawn White Oak_3'>
<label>Hard Maple</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Hard Maple_4'>
<label>Hickory</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Hickory_5'>
<!-- Many Others... -->
</div>
<div class="stains-container">
<div class="oak-stains-div">
<h4>Oak</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="b-maple-stains-div">
<h4>Brown Maple</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="cherry-stains-div">
<h4>Cherry</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="qswo-stains-div">
<h4>Quartersawn White Oak</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="h-maple-stains-div">
<h4>Hard Maple</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="hickory-stains-div">
<h4>Hickory</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
</div>
</code></pre>
<p>JS:</p>
<pre><code>jQuery(function ($) {
// Create Variables
var stains = $(".stains-container");
// Check if Oak is checked
var $oakchecked = $("input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.hickory-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");
// Check if B. Maple is checked
var $bmaplechecked = $("input.oak-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.hickory-stains");
var $bmapleactive = $(".oak-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .h-maple-stains-div li, .hickory-stains-div li");
// Check if Cherry is checked
var $cherrychecked = $("input.oak-stains, input.b-maple-stains, input.qswo-stains, input.h-maple-stains, input.hickory-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");
// Check if QSWO is checked
var $qswochecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.h-maple-stains, input.hickory-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");
// Check if H. Maple is checked
var $hmaplechecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.hickory-stains");
var $hmapleactive = $(".oak-stains-div li, .b-maple-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .hickory-stains-div li");
// Check if Hickory is checked
var $hickorychecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.h-maple-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");
// Check if a button is pre-selected and if its value matches
var radio_buttons = $("input[name='tmcp_radio_0']");
if( radio_buttons.is(":checked") && /^Oak_\d$/.test($(this).val())) {
alert("OAK is selected");
$(".oak-stains-div").show();
$oakchecked.prop('checked', false);
$oakactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Brown Maple_\d$/.test($(this).val())) {
alert("B MAPLE is selected");
$(".b-maple-stains-div").show();
$bmaplechecked.prop('checked', false);
$bmapleactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Cherry_\d$/.test($(this).val())) {
alert("CHERRY is selected");
$(".cherry-stains-div").show();
$cherrychecked.prop('checked', false);
$cherryactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Quartersawn White Oak_\d$/.test($(this).val())) {
alert("QSWO is selected");
$(".qswo-stains-div").show();
$qswochecked.prop('checked', false);
$qswoactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Hard Maple_\d$/.test($(this).val())) {
alert("H MAPLE is selected");
$(".h-maple-stains-div").show();
$hmaplechecked.prop('checked', false);
$hmapleactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Hickory_\d$/.test($(this).val())) {
alert("HICKORY is selected");
$(".hickory-stains-div").show();
$hickorychecked.prop('checked', false);
$hickoryactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":not(:checked)")) {
alert("NOTHING is selected");
$(".stains-container").hide();
}
// Check if Oak is selected or pre-selected
radio_buttons.on('change',function(){
if ( /^Oak_\d$/.test($(this).val())) {
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(){
if ( /^Brown Maple_\d$/.test($(this).val())) {
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(){
if ( /^Cherry_\d$/.test($(this).val())) {
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(){
if ( /^Quartersawn White Oak_\d$/.test($(this).val())) {
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(){
if ( /^Hard Maple_\d$/.test($(this).val())) {
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(){
if ( /^Hickory_\d$/.test($(this).val())) {
stains.show();
$(".hickory-stains-div").show();
$hickorychecked.prop('checked', false);
$hickoryactive.removeClass( "tc-active" );
} else {
$(".hickory-stains-div").hide();
}
});
});
</code></pre>
<p>My fiddle: <a href="https://jsfiddle.net/amishdirect/h2acf6n3/4/" rel="nofollow noreferrer">https://jsfiddle.net/amishdirect/h2acf6n3/4/</a></p>
<p>The current issue is even though I have an input with 'checked="checked"' I can not have it recognize that option is checked. I've tried "prop", "is", and "attr" but none pick up the option is checked. This is even just seeing it would see if it was or wasn't. Right now I am stuck because of this. Any help would be greatly appreciated!</p>
<p>I will also say the JS is crude and most likely can be improved and condensed. This is just what I have so I am thankful for any suggestions to improving it as well!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T19:13:16.667",
"Id": "458610",
"Score": "0",
"body": "Bumping for exile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T10:35:28.037",
"Id": "458684",
"Score": "0",
"body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T15:35:26.703",
"Id": "458704",
"Score": "0",
"body": "Ah sorry. The code works except for the portion I was asking on. I'll start a question over at Stackoverflow then. Thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T17:42:31.453",
"Id": "234496",
"Score": "1",
"Tags": [
"jquery"
],
"Title": "Check if Radio Button is Checked and if Value Matches"
}
|
234496
|
<p>I don't know whether if this is the right place to ask this. </p>
<p>I am semi-beginner in C. I always wanted to build my own Programming Language. Here I have built a lexical analyser completely myself. The lexer breaks the source code in tokens consisting of strings, characters, identifiers, constants and special symbols. It ignores single and multi-line comments too. And it can lexically analyse it's own code.</p>
<p>lexer.c</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SYMBOL(term) (term>=123&&term<=126)||(term>=33&&term<=47)||(term>=58&&term<=64)||(term>=91&&term<=96)
#define CAPALPHA(term) (term>='A'&&term<='Z')
#define LOWALPHA(term) (term>='a'&&term<='z')
#define ALPHA(term) ((CAPALPHA(term))||(LOWALPHA(term)))
#define WHITESPACE(term) ((term>=0&&term<=32)||term==127||term=='\n')
#define NUMBER(term) (term>='0'&&term<='9')
#define HEXNUMBER(term) ((term>='A'&&term<='f')||(term>='A'||term<='f'))
#define KEYWORD_COUNT 0
enum type {identifier,string,spsymbol,keyword,character,number,hexnumber};
char type2[25][25]={"identifier\0","string\0","symbol\0","keyword\0","character\0","number\0","hexnumber\0"};
enum keywords {regx,regy};
char keywords2[25][25]={"regx\0","regy\0"};
struct Tokens{ //Tokens structure
char *t; //actual token
int tlen; //token length
int ttype; //token type
int lineno; //token line no
int keyword;
};
struct Tokens *token[100000];
int main(){
char *input=malloc(100000*sizeof(char));
FILE *fp = fopen("file", "r");
FILE *of = fopen("lexout","w");
char symbol;
if(fp != NULL){
int j=0;
while(1)
{ symbol = fgetc(fp);
//printf("%c",symbol);
if (symbol != EOF)
input[j++]=symbol;
else {
input[j++]=symbol;
break;
}
}
fclose(fp);
}
int c=-1; //file current character
int current_token=0; //current_token counter
int line=1; //current line number
int halt=0;
while(1){
if(halt) break;
token[current_token]=(struct Tokens*)malloc(sizeof(struct Tokens)); //allocate memory for token structure
token[current_token]->t=(char*)malloc(sizeof(char)*30); //allocate memory for token size
int tokenTypeSet=0;
int in=0; //structure token counter
while(1){
c++;
if(input[c]=='\n') line++;
/*detect end of file*/
if(input[c]=='%'&&input[c+1]=='E'&&input[c+2]=='O'&&input[c+3]=='F'&&input[c+4]=='%'){
halt=1;
break;
}
/*identify singleline comments*/
if(input[c]=='/'&&input[c+1]=='/'){
while(input[c+1]!='\n'){
c++;
}
continue;
}
/*identify multiline comments*/
if(input[c]=='/'&&input[c+1]=='*'){
c++;
c++;
while(input[c]!='*'&&input[c+1]!='/'){
if(input[c]=='\n'){
line++;
}
c++;
}
c++;
continue;
}
/*identify string*/
if(input[c]=='"'){
//identify token type
if(!tokenTypeSet){
token[current_token]->ttype=string;
tokenTypeSet=1;
}
c++;
while(1){
//newline
if(input[c]=='\n'){
c++;
line++;
}
//backslash escaped
if(input[c]=='\\'&&input[c+1]=='\\'){
token[current_token]->t[in++]=input[c];
c++;
token[current_token]->t[in++]=input[c];
c++;
continue;
}
//double-quote escaped
if(input[c]=='\\'&&input[c+1]=='"'){
token[current_token]->t[in++]=input[c];
c++;
token[current_token]->t[in++]=input[c];
c++;
continue;
}
//contiguous double-quotes
if(input[c]=='"'&&input[c+1]=='"'){
token[current_token]->t[in++]=input[c];
c++;
token[current_token]->t[in++]=input[c];
c++;
continue;
}
//terminate string
if(input[c]=='"'){
//c++;
break;
}
token[current_token]->t[in++]=input[c];
c++;
}
token[current_token]->t[in]='\0';
break;
}
/*identify characters*/
if(input[c]=='\''){
//identify token type
if(!tokenTypeSet){
token[current_token]->ttype=character;
tokenTypeSet=1;
}
c++;
while(1){
//backslash escaped
if(input[c]=='\\'&&input[c+1]=='\\'){
token[current_token]->t[in++]=input[c];
c++;
token[current_token]->t[in++]=input[c];
c++;
continue;
}
//sigle-quote escaped
if(input[c]=='\\'&&input[c+1]=='\''){
token[current_token]->t[in++]=input[c];
c++;
token[current_token]->t[in++]=input[c];
c++;
continue;
}
//contiguous single-quotes
if(input[c]=='\''&&input[c+1]=='\''){
token[current_token]->t[in++]=input[c];
c++;
token[current_token]->t[in++]=input[c];
c++;
continue;
}
//terminate character
if(input[c]=='\''){
//c++;
break;
}
token[current_token]->t[in++]=input[c];
c++;
}
token[current_token]->t[in]='\0';
break;
}
/*mark hexnumbers*/
if(!tokenTypeSet){
if(input[c]=='0'&&(input[c+1]=='x'||input[c+1]=='X')){
token[current_token]->t[in++]=input[c];
c++;
token[current_token]->t[in++]=input[c];
c++;
token[current_token]->ttype=hexnumber;
tokenTypeSet=1;
}
//continue;
}
/*read hex numbers*/
if(token[current_token]->ttype==hexnumber){
if(HEXNUMBER(input[c])||NUMBER(input[c])){
token[current_token]->t[in++]=input[c];
}
if(WHITESPACE(input[c+1])){
token[current_token]->t[in]='\0';
//c++; //undo
break;
}
if(SYMBOL(input[c+1])){
token[current_token]->t[in]='\0';
break;
}
if(!(HEXNUMBER(input[c+1])||NUMBER(input[c+1]))){
token[current_token]->t[in]='\0';
break;
}
continue;
}
/*read an alphabet or an underscore*/
if(ALPHA(input[c])||input[c]=='_'){
//identify token type
if(!tokenTypeSet){
token[current_token]->ttype=identifier;
tokenTypeSet=1;
}
token[current_token]->t[in++]=input[c];
//detect end of token
if(WHITESPACE(input[c+1])){
token[current_token]->t[in]='\0';
//c++; //undo
break;
}
if((SYMBOL(input[c+1]))&&(input[c+1]!='_')){
token[current_token]->t[in]='\0';
break;
}
continue;
}
/*read a symbol*/
if(SYMBOL(input[c])){
if(!tokenTypeSet){
token[current_token]->ttype=spsymbol;
tokenTypeSet=1;
}
token[current_token]->t[in++]=input[c];
//detect end of token
if(WHITESPACE(input[c+1])){
token[current_token]->t[in]='\0';
//c++; //undo
break;
}
if(SYMBOL(input[c+1])||ALPHA(input[c+1])||NUMBER(input[c+1])){
token[current_token]->t[in]='\0';
break;
}
continue;
}
/*read a number*/
if(NUMBER(input[c])){
//identify token type
if(!tokenTypeSet){
token[current_token]->ttype=number;
tokenTypeSet=1;
}
token[current_token]->t[in++]=input[c];
//detect end of token
if(WHITESPACE(input[c+1])){
token[current_token]->t[in]='\0';
//c++; //undo
break;
}
if(!(NUMBER(input[c+1]))){
if(token[current_token]->ttype==identifier&&(ALPHA(input[c+1])||input[c+1]=='_')){
continue;
}
token[current_token]->t[in]='\0';
break;
}
/*if(SYMBOL(input[c+1])||ALPHA(input[c+1])){
token[current_token]->t[in]='\0';
break;
}*/
continue;
}
}
token[current_token]->lineno=line;
current_token++;
}
//DEBUGGER
//printf("Total nos of tokens = %d\n\n",current_token-1);
fprintf(of,"Total nos of tokens = %d\n\n",current_token-1);
for(int i=0;i<current_token-1;i++){
//printf("%s:%s\n",type2[token[i]->ttype],token[i]->t);
if(token[i]->ttype==identifier){
for(int j=0;j<KEYWORD_COUNT;j++){
if(strcmp(token[i]->t,keywords2[j])){
token[i]->ttype=keyword;
break;
}
}
}
fprintf(of,"lnos:%d,%s:%s\n",token[i]->lineno,type2[token[i]->ttype],token[i]->t);
}
printf("%s","***********************\n");
//END OF LEXING
return 0;
}
</code></pre>
<p>To test the lexer you need to create a source file named simply "file".
Inside "file" should be the source code followed by %EOF% string.
For example, file:</p>
<pre><code>#include<stdio.h>
int main(){
int a = 5;
int b = a;
return 0;
}
%EOF%
</code></pre>
<p>Compile the program:<br></p>
<pre><code>gcc lexer.c -o lexer.out -Wall
</code></pre>
<p>Output:</p>
<pre><code>Total nos of tokens = 26
lnos:1,symbol:#
lnos:1,identifier:include
lnos:1,symbol:<
lnos:1,identifier:stdio
lnos:1,symbol:.
lnos:1,identifier:h
lnos:1,symbol:>
lnos:3,identifier:int
lnos:3,identifier:main
lnos:3,symbol:(
lnos:3,symbol:)
lnos:3,symbol:{
lnos:4,identifier:int
lnos:4,identifier:a
lnos:4,symbol:=
lnos:4,number:5
lnos:4,symbol:;
lnos:5,identifier:int
lnos:5,identifier:b
lnos:5,symbol:=
lnos:5,identifier:a
lnos:5,symbol:;
lnos:6,identifier:return
lnos:6,number:0
lnos:6,symbol:;
lnos:7,symbol:}
</code></pre>
<p>Where lnos is the line number the token appears in.
The Source code is well commented. Ask if anything is not clear.</p>
<p>Later I would use these tokens in Parsing phase.</p>
<p>All I am seeking is a little guidance.</p>
<p>I need to know</p>
<ol>
<li>whether this is an efficient way to write a lexer.</li>
<li>Do you see any bad coding practice in the my code. </li>
<li>And if the code could be improved.</li>
</ol>
|
[] |
[
{
"body": "<p>Here are a number of things that may help you improve your program.</p>\n\n<h2>Don't use <code>define</code> for function-like macros</h2>\n\n<p>There is no advantage and considerable disadvantages to using function-like macros. They lack type-checking and tend to lead to bugs. For example, if we use this:</p>\n\n<pre><code>c = '0';\nSYMBOL(++c);\nprintf(\"%c\\n\", c);\n</code></pre>\n\n<p>We would see that it would print \"5\" because unlike a real function, the macro increments the value every time it's mentioned in the macro. </p>\n\n<h2>Use more whitespace for readability</h2>\n\n<p>Lines like this:</p>\n\n<pre><code>if(input[c]=='%'&&input[c+1]=='E'&&input[c+2]=='O'&&input[c+3]=='F'&&input[c+4]=='%'){\n</code></pre>\n\n<p>are very hard to read because of the lack of whitespace. It's much easier to read for most people when written like this:</p>\n\n<pre><code>if (input[c] == '%' && input[c + 1] == 'E' && input[c + 2] == 'O'\n && input[c + 3] == 'F' && input[c + 4] == '%') {\n</code></pre>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>One of the macros in the code is this:</p>\n\n<pre><code>#define SYMBOL(term) (term>=123&&term<=126)||(term>=33&&term<=47)||(term>=58&&term<=64)||(term>=91&&term<=96)\n</code></pre>\n\n<p>However it's difficult to figure out what this means because of all the un-named numerical constants. Better would be to d as you have done for the <code>LOWALPHA</code> macro and use character values directly. Or even better, just use <code>ispunct()</code> as per the next suggestion.</p>\n\n<h2>Use standard functions and facilities</h2>\n\n<p>Several of the macros attempt to duplicate functions that already exist. Specifically <a href=\"https://en.cppreference.com/w/c/string/byte/isupper\" rel=\"nofollow noreferrer\"><code>isupper()</code></a> and many related functions are in <code><ctype.h></code>.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>This code calls <code>malloc</code> several places but never <code>free</code>. This means that the code is leaking memory. It would be much better to get into the habit of using <code>free</code> for each call to <code>malloc</code> and then assuring that you don't leak memory. </p>\n\n<h2>Check the return value of <code>malloc</code></h2>\n\n<p>If the program runs out of memory, a call to <code>malloc</code> can fail. The only indication for this is that the call will return a <code>NULL</code> pointer. You should check for this and avoid dereferencing a <code>NULL</code> pointer (which typically causes a program crash). If the program can't proceed without the memory, free any allocated memory and quit the program gracefully.</p>\n\n<h2>Decompose your program into functions</h2>\n\n<p>All of the logic here is in <code>main</code> in one rather long and dense chunk of code. It would be better to decompose this into separate functions.</p>\n\n<h2>Use <code>bool</code> where appropriate</h2>\n\n<p>The <code>halt</code> flag is being used as a boolean variable. If you <code>#include <stdbool.h></code>, you can use a <code>bool</code> type to better signal how this is being used.</p>\n\n<h2>Simplify your code</h2>\n\n<p>The code currently contains this:</p>\n\n<pre><code>if (fp != NULL) {\n int j = 0;\n while (1) {\n symbol = fgetc(fp);\n //printf(\"%c\",symbol);\n if (symbol != EOF)\n input[j++] = symbol;\n else {\n input[j++] = symbol;\n break;\n }\n }\n fclose(fp);\n}\n</code></pre>\n\n<p>That's much more complex and fragile than it needs to be. It's fragile because there's nothing to prevent it from running beyond the allocated <code>input</code> buffer. It's also more complex than it needs to be with multiple <code>while</code>, <code>if</code> and <code>else</code>. It could be written instead like this:</p>\n\n<pre><code>if (fp == NULL) {\n puts(\"Cannot open input file\");\n exit(1);\n}\nfgets(input, BUFFLEN, fp);\nfclose(fp);\n</code></pre>\n\n<p>Note also that I'm using <code>BUFFLEN</code> instead of a \"magic number\" as mentioned above. Similarly, this code is more convoluted than it needs to be:</p>\n\n<pre><code>int halt = 0;\nwhile (1) {\n if (halt)\n break;\n // more code\n}\n</code></pre>\n\n<p>Write it like this instead:</p>\n\n<pre><code>bool halt = false;\nwhile (!halt) {\n</code></pre>\n\n<h2>Don't use uninitialised memory</h2>\n\n<p>The code allocates memory for a <code>token</code>, but tests the contents of some of its fields before actually initializing it. If you need it set to specific values, you should set it. If zeroes are sufficient, use <code>calloc</code>.</p>\n\n<h2>Don't clutter the code with useless things</h2>\n\n<p>In a number of cases we have code like this:</p>\n\n<pre><code>token[current_token]->t = (char *)malloc(sizeof(char) * 30);\n</code></pre>\n\n<p>However, there's no need to cast the value and <code>sizeof(char)</code> is defined to always be 1. So the code could be written like this instead:</p>\n\n<pre><code>token[current_token]->t = malloc(MAX_TOKEN_LEN);\n</code></pre>\n\n<p>Again, we're avoiding \"magic numbers\" as mentioned earlier.</p>\n\n<h2>Allow the user to specify input and output files</h2>\n\n<p>The file names are currently hardcoded which certainly greatly restricts the usefulness of the program. Consider using <code>argc</code> and <code>argv</code> to allow the user to specify file names on the command line. Also <code>file</code> is certainly a poor choice for a hardcoded file name since it doesn't tell one anything useful about what the file is expected to contain.</p>\n\n<h2>Use a state machine</h2>\n\n<p>You might find it better to use a state machine to do this parsing. See <a href=\"https://codereview.stackexchange.com/questions/134888/parse-2d-matrix-2-versions/138019#138019\">this answer</a> for an example of how to do this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T21:27:35.187",
"Id": "234506",
"ParentId": "234500",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "234506",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T18:20:33.270",
"Id": "234500",
"Score": "4",
"Tags": [
"c",
"compiler",
"lexer"
],
"Title": "Is this a good way to write a lexer?"
}
|
234500
|
<p>I'm writing a tool which users can select multiple choices at once. Whilst I can't provide the actual content, I've replicated it with fruit. I'm replicating some functionality from Nikto where it allows different flags like "-mutation abcd".</p>
<p>for example here we have three fruits:</p>
<pre class="lang-none prettyprint-override"><code>1- apple
2- orange
3- kiwi
</code></pre>
<p>I wanna let users to type "12" or "appleorange" or "21" or "orangeapple" for selecting apple and orange, or "123" or "appleorangekiwi" or vice versa to select apple, orange and kiwi and etc. </p>
<p>Assume that there are more than 3 choices, so it would be pain in the neck if I want to write elif statement for all multiple selections.
How can I make my code simpler and shorter?</p>
<p>Here is my code:</p>
<pre><code>fruits_ls = []
def add_fruits():
while True:
print("choose your favorite fruits:\n"
"1- apple\n"
"2- orange\n"
"3- kiwi\n"
"4- exit\n")
my_fruits = input()
if my_fruits == str(1) or my_fruits == "apple":
fruits_ls.append("Apple")
elif my_fruits == str(2) or my_fruits == "orange":
fruits_ls.append("Orange")
elif my_fruits == str(3) or my_fruits == "kiwi":
fruits_ls.append("Kiwi")
elif my_fruits == str(12) or my_fruits == "appleorange" or my_fruits == str(21) or my_fruits == "orangeapple":
fruits_ls.append("Apple")
fruits_ls.append("Orange")
elif my_fruits == str(13) or my_fruits == "applekiwi" or my_fruits == str(31) or my_fruits == "kiwiapple":
fruits_ls.append("Apple")
fruits_ls.append("Kiwi")
elif my_fruits == str(23) or my_fruits == "orangekiwi" or my_fruits == str(32) or my_fruits == "kiwiorange":
fruits_ls.append("Orange")
fruits_ls.append("Kiwi")
elif my_fruits == str(4) or my_fruits == "exit":
break
add_fruits()
print(fruits_ls)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T09:37:20.260",
"Id": "458676",
"Score": "3",
"body": "@sf31 Have you looking into the existing parsing facilities of `argparse`? Idk if it does this, but have you checked?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T10:45:07.467",
"Id": "458687",
"Score": "0",
"body": "@CodeCaster Please provide answers in answers, not in comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T12:09:27.377",
"Id": "458689",
"Score": "0",
"body": "@Peilonrayz that was not an answer, not even a partial one. It was a warning towards the OP, so they could mention that in their question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T12:29:27.903",
"Id": "458692",
"Score": "0",
"body": "@CodeCaster It was more than enough to be an answer on Code Review. Note that all critiques of code are answer material, and so warnings on edge cases or unforeseen input are fair game in answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:29:14.757",
"Id": "458719",
"Score": "0",
"body": "@Alexander-ReinstateMonica\n\nI just skimmed it, seems helpful, I'll work on it. Thanks!"
}
] |
[
{
"body": "<p>Creating a mapping from input to output can be very useful here. A dictionary is the ideal data structure for this</p>\n\n<pre><code>VALID_INPUTS = {\n '1': 'Apple',\n 'apple': 'Apple',\n '2': 'Orange',\n 'orange': 'Orange',\n '3': 'Kiwi',\n 'kiwi': 'Kiwi',\n}\nEXIT_INPUTS = ['4', 'exit']\n</code></pre>\n\n<p>Then you can loop over this mapping and append the matching inputs</p>\n\n<pre><code>if my_fruits in EXIT_INPUTS:\n break\nfor valid_input, fruit in VALID_INPUTS.items():\n if valid_input in my_fruits:\n fruits_ls.append(fruit)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T21:13:32.340",
"Id": "458622",
"Score": "1",
"body": "A note for op if he opts to use this implementation: you'll need to reconfigure how you exit the while loop. A simple input asking if the user wants to enter more options that trips a boolean controlling the while loop would work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T21:16:17.707",
"Id": "458625",
"Score": "0",
"body": "That's true, you can create another data structure to store these exit inputs (a list for example) and test for the input being one of them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T04:51:36.530",
"Id": "458658",
"Score": "3",
"body": "this would fail if there are more than 10 elements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T05:46:37.197",
"Id": "458661",
"Score": "0",
"body": "Thx. Currently I'm at work and don't access to my system, I'll test the code above and let you know about that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T09:11:31.100",
"Id": "458673",
"Score": "0",
"body": "@hjpotter92 Why is that? I'm not aware of any limit on the size of dictionaries, arrays or tuples, apart from what your machine can manage. (In general, it's more helpful to say \"this would fail *because*...\". If someone thinks that's incorrect, they can provide a correction more easily. And if you're right, then other people have learnt something. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T09:20:11.047",
"Id": "458674",
"Score": "3",
"body": "@Graham you're right. for eg. consider 10=pineapple, 11=guava; how would input `114` or `1104` be parsed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T11:32:11.013",
"Id": "458688",
"Score": "0",
"body": "@hjpotter92 Ah, I see your point. That's not really related to this answer, I think, more to do with the OP's scenario in general? The obvious answer though is to go base-36, where your options go from 0-9 and then from A-Z. (Note for OP: \"0\" makes a nice consistent exit condition.) Conceptually this could be increased to base-<max-Unicode-value>, although exceeding alphanumeric characters should be a pretty clear hint to the OP that their scheme has reached its practical limits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:17:52.397",
"Id": "458715",
"Score": "0",
"body": "Both solutions which @IainShelvington and c4iimeco4ch provide work well, but there is an issue in both, if users type 12, and again type 12 or appleorange, the output would be Apple, Orange, Apple, Orange. How to solve this problem? so that the program doesn't get users' inputs more than once. e.g: it only accepts Apple once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:18:32.503",
"Id": "458716",
"Score": "0",
"body": "@c4llmeco4ch Read the previous comment of mine plz."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:46:30.630",
"Id": "458723",
"Score": "1",
"body": "Simply add ``` and '<fruitnamehere>' not in fruits_ls ``` to the end of each if. This confirms the item is not already in the cart before adding it. You will need to add parens around the or section of the if"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T03:29:39.833",
"Id": "458747",
"Score": "1",
"body": "@sf31 instead of fruit_ls being a list, create a set"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T20:50:17.900",
"Id": "234504",
"ParentId": "234502",
"Score": "11"
}
},
{
"body": "<p>The first thing I would like to do is applaud you for not immediately turning to back-to-back if statements. It's a trap I commonly see when tackling these kinds of problems. However, in this case, I'd ask a question that is counter to my previous point: are your options mutually exclusive? In other words, is it a problem if a person has multiple options in a loop accepted? Given you are accepting inputs like 31 or 12, my expectation is no. As such, instead of:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if my_fruits == str(1) or my_fruits == \"apple\":\n fruits_ls.append(\"Apple\")\nelif my_fruits == str(2) or my_fruits == \"orange\":\n fruits_ls.append(\"Orange\")\nelif my_fruits == str(3) or my_fruits == \"kiwi\":\n fruits_ls.append(\"Kiwi\")\nelif my_fruits == str(12) or my_fruits == \"appleorange\" or my_fruits == str(21) or my_fruits == \"orangeapple\":\n fruits_ls.append(\"Apple\")\n fruits_ls.append(\"Orange\")\n\nelif my_fruits == str(13) or my_fruits == \"applekiwi\" or my_fruits == str(31) or my_fruits == \"kiwiapple\":\n fruits_ls.append(\"Apple\")\n fruits_ls.append(\"Kiwi\")\n\nelif my_fruits == str(23) or my_fruits == \"orangekiwi\" or my_fruits == str(32) or my_fruits == \"kiwiorange\":\n fruits_ls.append(\"Orange\")\n fruits_ls.append(\"Kiwi\")\n\nelif my_fruits == str(4) or my_fruits == \"exit\":\n break\n</code></pre>\n\n<p>A possibility would be checking if an instance of an option is inside the input:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if '1' in my_fruits or 'apple' in my_fruits:\n fruits_ls.append('Apple')\nif '2' in my_fruits or 'orange' in my_fruits:\n fruits_ls.append('Orange')\nif '3' in my_fruits or 'kiwi' in my_fruits:\n fruits_ls.append('Kiwi')\nif '4' == my_fruits:\n break\n</code></pre>\n\n<p>There are some small problems with the above solution that may or may not be in scope. For example, \"121\" will only give \"AppleOrange\" when \"AppleOrangeApple\" may be desired. I can provide further insight if this is the case. </p>\n\n<p>Hopefully this helps. Assuming the need for elifs is always a safe bet at first, but when refactoring code, elifs can be ditched if the answers can coexist without hindering the code's performance. Let me know if I can help further.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T05:54:32.200",
"Id": "458662",
"Score": "0",
"body": "I guess this is the correct answer, I'll check the code tonight and let you know.\nFortunately there is no option like \"121\".\nSo you mean that I should change elifs and rewrite the code like the \"ifs\" you provided, right? because I have some other functions which works almost like this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T08:00:22.143",
"Id": "458670",
"Score": "1",
"body": "Right. The idea is elifs imply one or the other can happen, but not both. Like in a sports game, both teams cannot win at the same time. However, this problem does not have that concern. A user can have both an apple and a kiwi at the same time. Thus, we can use ifs rather than being concerned with elifs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T08:17:14.263",
"Id": "458671",
"Score": "1",
"body": "Even if they are not mutually exclusive, you can adopt a data structure and a loop to make it more clear and expendable, as in https://codereview.stackexchange.com/a/234504/123200"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T20:55:27.640",
"Id": "234505",
"ParentId": "234502",
"Score": "3"
}
},
{
"body": "<p>This could be made into a generic function that accepts a list of items. It displays a menu based on the list and lets the user select one or more items from the menu. Rather than keep a global list, the function returns the list of select items.</p>\n\n<pre><code>def select_items(prompt, items):\n selected_items = set()\n\n while True:\n print(f\"{prompt}:\")\n for n, item in enumerate(items, 1):\n print(f\" {n:2} - {item}\")\n exit_no = n+1\n print(f\" {exit_no:2} - exit\")\n\n raw_selection = input(\"> \")\n selection = raw_selection.lower()\n\n for n, item in enumerate(items, 1):\n if item in selection or str(n) in selection:\n selected_items.add(item)\n\n if 'exit' in selection or str(exit_no) in selection:\n return selected_items\n\n\nselect_items(\"Choose your favorite fruits\", \"apple orange kiwi banana\".split())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:50:18.520",
"Id": "458724",
"Score": "0",
"body": "It works but the issue is still there, if users type each item again and again, the item will be shown in the output twice. like: Choose your favorite fruits: 1 Choose your favorite fruits: 1 Result: Apple, Apple"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T23:52:17.083",
"Id": "458741",
"Score": "1",
"body": "@sf31 - Then change `selected_items` to a `set()` instead of a list (see revised answer). Or check to see if the item is already in `selected_items` before appending it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T06:17:57.007",
"Id": "234521",
"ParentId": "234502",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "234504",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T20:33:16.190",
"Id": "234502",
"Score": "3",
"Tags": [
"python"
],
"Title": "Adding fruits to a basket, allowing selection from ID and name"
}
|
234502
|
<p>I tried to create a reusable component which would allow the user to create cards which can have a header, cover image, avatar section (image, title and sub title), a description, a table, a list and a few buttons (add, delete, edit, like, share). All of these are optional and the user can omit whatever is not needed for a card. Here is the Github link <a href="https://github.com/SagarMajumdar/nevescard" rel="nofollow noreferrer">nevescard component github repo</a>. The end result will looks like this</p>
<p><a href="https://i.stack.imgur.com/7r6xW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7r6xW.jpg" alt="screenshot of some ways in which the card component can be used"></a> </p>
<p>The component is called neves-card</p>
<p><a href="https://i.stack.imgur.com/xPeFr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xPeFr.png" alt="neves-card component"></a></p>
<p>in app.component.ts the data needed for the card(s) is defined as </p>
<pre><code> x = [
{
indx: '58',
features : ['title-main', 'card-cover', 'avatar', 'main-desc', 'tbl', 'list', 'btn-add', 'btn-del', 'btn-share', 'btn-like', 'btn-edit']
, nevesCardTitleMain: 'consequatur saepe rerum est sint'
,nevesCardCover : 'https://images.unsplash.com/photo-1480911620066-b6ccd99c48f3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1342&q=80'
,nevesCardAvatarImg :'https://c402277.ssl.cf1.rackcdn.com/photos/182/images/circle/Chimpanzees_Circle_image_%28c%29_Howard_W._Buffett_WWF_US.jpg?1345516061'
,nevesCardAvatarTitle : 'ljsdkin jshdfj'
,nevesCardAvatarDesc : 'kjfhjfg jfgjshgfshgfjhgj | jhsgfhjsgf | kdha skjjkad '
,nevesCardMainDesc :'Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellendus doloribus tempora, atque dolore quasi aperiam. Tempora nam aut a dolores, praesentium corporis dolorem, accusantium velit minima laudantium excepturi voluptate eum.Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis ducimus qui esse ab delectus, quo quod consectetur, repudiandae deserunt sequi praesentium tempora adipisci ea quidem a numquam maiores. Consectetur, pariatur?Lorem ipsum dolor sit amet consectetur adipisicing elit. A deleniti odio odit et accusamus perspiciatis quo minima asperiores, consequatur saepe rerum est sint ipsum, itaque dicta. Laudantium libero molestiae aperiam.'
, tbldata : [
{head1: 'data1', head2: 'data2' },
{head1: 'data6', head2: 'data299' },
{head1: 'data313', head2: 'data12'}]
, listData: {
list_title: 'list one',
list_content: [ 'abc', 'dsadasd', 'gdgeewrw', 'dsdda', 'dadsssd','gdgeewrw asdada dasd','gdgeewrw asdada dasd','gdgeewrw asdada dasd','gdgeewrw asdada dasd','gdgeewrw asdada dasd' ]
}
}
,
{
indx: '21',
features : ['card-cover', 'avatar', 'list', 'btn-add', 'btn-like', 'btn-edit', 'btn-share']
, nevesCardTitleMain: ''
, nevesCardCover : 'https://images.pexels.com/photos/894443/pexels-photo-894443.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260'
, nevesCardAvatarImg : 'https://c402277.ssl.cf1.rackcdn.com/photos/182/images/circle/Chimpanzees_Circle_image_%28c%29_Howard_W._Buffett_WWF_US.jpg?1345516061'
, nevesCardAvatarTitle : 'Fhijkj jhhjgada '
, nevesCardAvatarDesc : 'lorem ipsum lorem ipsum'
, nevesCardMainDesc : ''
, tbldata : [{}]
, listData: {
list_title: 'list two',
list_content: [ 'abc', 'dsadasd','gdgeewrw asdada dasd','gdgeewrw asdada dasd' ]
}
},
{
indx: '3',
features : ['title-main', 'card-cover', 'main-desc', 'tbl','btn-add', 'tn-del', 'btn-like', 'btn-edit']
,nevesCardTitleMain: 'consequatur saepe rerum est sint'
, nevesCardCover : 'https://i.pinimg.com/564x/b8/f8/c6/b8f8c61ca7d9050b3045eb118d2cdedc.jpg'
, nevesCardAvatarImg : ''
, nevesCardAvatarTitle : ''
, nevesCardAvatarDesc : ''
, nevesCardMainDesc :'Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellendus doloribus tempora, atque dolore quasi aperiam. Tempora nam aut a dolores, praesentium corporis dolorem, accusantium velit minima laudantium excepturi voluptate eum.Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis ducimus qui esse ab delectus, quo quod consectetur, repudiandae deserunt sequi praesentium tempora adipisci ea quidem a numquam maiores. Consectetur, pariatur?Lorem ipsum dolor sit amet consectetur adipisicing elit. A deleniti odio odit et accusamus perspiciatis quo minima asperiores, consequatur saepe rerum est sint ipsum, itaque dicta. Laudantium libero molestiae aperiam.'
, tbldata : [{head1: 'data1', head2: 'data2',head12: 'data1', head23: 'data2',head41: 'data1', head62: 'data2',head18: 'data1', head29: 'data2',head01: 'data1', head02: 'data2',head09: 'data1', head03: 'data2',head04: 'data1', head05: 'data2',head06: 'data1', head011: 'data2',head012: 'data1', head013: 'data2'}]
, listData: {
list_title: '',
list_content: []
}
},
{
indx: '42',
features : ['title-main', 'card-cover', 'main-desc','btn-add', 'btn-del', 'btn-like', 'btn-edit','btn-share']
,nevesCardTitleMain: 'consequatur saepe rerum est sint'
, nevesCardCover : 'https://images.unsplash.com/photo-1576895225171-ce4059ba7d3c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=600&q=60'
, nevesCardAvatarImg :''
, nevesCardAvatarTitle : ''
, nevesCardAvatarDesc : ''
, nevesCardMainDesc :"Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellendus doloribus tempora, atque dolore quasi aperiam. Tempora nam aut a dolores, praesentium corporis dolorem, accusantium velit minima laudantium excepturi voluptate eum.Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis ducimus qui esse ab delectus, quo quod consectetur, repudiandae deserunt sequi praesentium tempora adipisci ea quidem a numquam maiores. Consectetur, pariatur?Lorem ipsum dolor sit amet consectetur adipisicing elit. A deleniti odio odit et accusamus perspiciatis quo minima asperiores, consequatur saepe rerum est sint ipsum, itaque dicta. Laudantium libero molestiae aperiam."
, tbldata : [{}]
, listData: {
list_title: '',
list_content: []
}
},
{
indx: '6',
features : ['title-main']
,nevesCardTitleMain: 'consequatur saepe rerum est sint consequatur saepe rerum'
, nevesCardCover : ''
, nevesCardAvatarImg :''
, nevesCardAvatarTitle : ''
, nevesCardAvatarDesc : ''
, nevesCardMainDesc : ''
, tbldata : [{}]
, listData: {
list_title: '',
list_content: []
}
},
{
indx: '12',
features : ['card-cover']
,nevesCardTitleMain: ''
, nevesCardCover : 'https://i.pinimg.com/564x/8c/cd/97/8ccd97ebaab901742670abbe2f353c53.jpg'
, nevesCardAvatarImg :''
, nevesCardAvatarTitle : ''
, nevesCardAvatarDesc : ''
, nevesCardMainDesc :''
, tbldata : [{}]
, listData: {
list_title: '',
list_content: []
}
}
];
</code></pre>
<p>calling the card component</p>
<pre><code><app-neves-card *ngFor="let v of x"
[nevesIndx] = "v.indx"
[nevesFeatures]="v.features"
[nevesAction]="v.nevesAction"
[nevesCardTitleMain] = "v.nevesCardTitleMain"
[nevesCardCover] = "v.nevesCardCover"
[nevesCardAvatarImg] ="v.nevesCardAvatarImg"
[nevesCardAvatarTitle] = "v.nevesCardAvatarTitle"
[nevesCardAvatarDesc] = "v.nevesCardAvatarDesc"
[nevesCardMainDesc] ="v.nevesCardMainDesc"
[tblData]="v.tbldata"
[listData] = "v.listData"
(outAdd)="fnAdd($event)"
(outDel)="fnDel($event)"
(outEdit)="fnEdit($event)"
(outLike)="fnLike($event)"
(outShare)="fnShare($event)"
></app-neves-card>
</code></pre>
<p>neves-card.component.html</p>
<pre><code><div class="neves-card-container-main">
<div class="neves-card-container" >
<div class="neves-card-title-main" appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'title-main'" ><h2>{{nevesCardTitleMain}}</h2></div>
<div class="neves-card-cover" appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'card-cover'">
<img [src]="nevesCardCover" >
</div>
<div class="neves-card-avatar-wrapper" appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'avatar'">
<div class="neves-card-avatar-img"><img [src]="nevesCardAvatarImg"></div>
<div class="neves-card-avatar-details">
<div class="neves-card-avatar-title"><h4>{{nevesCardAvatarTitle}}</h4></div>
<div class="neves-card-avatar-desc"><p>{{nevesCardAvatarDesc}}</p></div>
</div>
</div>
<div class="neves-card-main-desc" appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'main-desc'">
<p>{{nevesCardMainDesc}}</p>
</div>
<div class="neves-card-tbl" appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'tbl'">
<table>
<thead>
<tr>
<th *ngFor="let head of headers">{{head}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of tblData">
<td *ngFor="let head of headers">
{{ row[head] }}
</td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
</div>
<div class="neves-card-list" appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'list'">
<p>{{listData.list_title}}</p>
<ol>
<li *ngFor="let dt of listData.list_content">
{{dt}}
</li>
</ol>
</div>
<div class="neves-card-buttons">
<button type="button" (click)='nevesAdd(nevesIndx)' appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'btn-add'">+</button>
<button type="button" (click)='nevesDel(nevesIndx)' appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'btn-del'">-</button>
<button type="button" (click)='nevesEdit(nevesIndx)' appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'btn-edit'"><img src="assets/images/edit.png"></button>
<button type="button" (click)='nevesLike(nevesIndx)' appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'btn-like'"><img src="assets/images/heart.png"></button>
<button type="button" (click)='nevesShare(nevesIndx)' appSectionHider [isFeatureRequested]="nevesFeatures" [currElem]="'btn-share'"><img src="assets/images/share.png"></button>
</div>
</div>
</div>
</code></pre>
<p>neves-card.component.ts</p>
<pre><code>import { Component, OnInit, Input, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-neves-card',
templateUrl: './neves-card.component.html',
styleUrls: ['./neves-card.component.css']
})
export class NevesCardComponent implements OnInit {
@Input() nevesCardTitleMain: string;
@Input() nevesCardCover: string;
@Input() nevesCardAvatarImg: string;
@Input() nevesCardAvatarTitle: string;
@Input() nevesCardAvatarDesc: string;
@Input() nevesCardMainDesc: string;
@Input() tblData;
@Input() nevesAction: string[];
@Input() nevesFeatures: string[];
@Input() listData: string[];
@Input() nevesIndx: string;
headers: string[] = [];
@Output() outAdd = new EventEmitter<{nevesindx:string}>();
@Output() outDel = new EventEmitter<{nevesindx:string}>();
@Output() outEdit = new EventEmitter<{nevesindx:string}>();
@Output() outLike = new EventEmitter<{nevesindx:string}>();
@Output() outShare = new EventEmitter<{nevesindx:string}>();
constructor() { }
ngOnInit() {
this.headers = Object.keys(this.tblData[0]);
}
nevesAdd = (indx: string) => { this.outAdd.emit({nevesindx:indx});}
nevesDel = (indx: string) => { this.outDel.emit({nevesindx:indx}); }
nevesEdit = (indx: string) => { this.outEdit.emit({nevesindx:indx});}
nevesLike = (indx: string) => { this.outLike.emit({nevesindx:indx});}
nevesShare = (indx: string) => { this.outShare.emit({nevesindx:indx});}
}
</code></pre>
<p>neves-card.component.css</p>
<pre><code>*{
font-family: sans-serif;
}
.neves-card-title-main ,
.neves-card-avatar-wrapper,
.neves-card-main-desc,
.neves-card-buttons,
.neves-card-tbl,
.neves-card-list {
margin-left:4px;
margin-right: 4px;
}
.neves-card-cover img{
width:100%;
}
.neves-card-container-main
{
display: inline-block;
}
.neves-card-container {
max-width:350px;
border: 1px solid gainsboro;
border-radius: 2px;
margin:5px;
box-shadow: 0px 0px 10px 0px gainsboro;
}
.neves-card-avatar-wrapper {
margin-top:10px;
width:100%;
}
.neves-card-avatar-img{
width: 48px;
height: 48px;
border-radius: 2px;
overflow: hidden;
display: inline-block;
}
.neves-card-avatar-img img {
width:100%;
height:100%;
}
.neves-card-avatar-details {
margin-left:5px;
display: inline-block;
width:65%;
}
.neves-card-avatar-details h4 {
margin:0px;
text-transform: uppercase;
font-size: small;
}
.neves-card-avatar-details p {
margin: 0px;
font-size: smaller;
}
.neves-card-main-desc p {
font-size: small;
}
.neves-card-main-desc
{
height: 125px;
overflow-y: scroll;
margin-top: 10px;
margin-bottom: 10px;
}
.neves-card-buttons {
text-align: right;
}
.neves-card-buttons button {
background-color: white;
border: 0px;
font-size: large;
font-weight: bold;
cursor: pointer;
color:gray;
}
.neves-card-tbl {
_border-radius: 3px;
_overflow: hidden;
margin-top: 20px;
margin-bottom: 20px;
overflow-x: scroll;
max-height: 200px;
overflow-y: scroll;
}
.neves-card-tbl table {
min-width: 100%;
border-collapse: collapse;
}
thead th {
text-align: left;
background-color:#616161;
color:white;
font-weight: normal;
font-size: small;
padding: 5px;
}
tbody td {
font-size: small;
border-left:1px solid white;
border-left: 1px solid #bbbaba;
padding:4px;
}
tbody tr:nth-child(odd) {
background-color: gainsboro;
}
.neves-card-list {
max-height: 200px;
overflow-y: scroll;
font-size: smaller;
margin-bottom: 10px;
}
.neves-card-list p
{
background-color: #616161;
color:white;
padding:4px;
border-radius: 2px;
}
.neves-card-list ol li {
margin-bottom: 2px;
padding:3px;
background-color: gainsboro;
border-radius: 2px;
}
</code></pre>
<p>section-hider.directive.ts</p>
<pre><code>import { Directive ,ElementRef, Renderer2, OnInit, Input} from '@angular/core';
@Directive({
selector: '[appSectionHider]'
})
export class SectionHiderDirective implements OnInit{
@Input() isFeatureRequested :string[];
@Input() currElem:string;
constructor(private elref : ElementRef, private renderer : Renderer2) { }
ngOnInit() {
if(this.isFeatureRequested !== undefined &&
this.isFeatureRequested.length>0 &&
this.isFeatureRequested.indexOf(this.currElem) === -1 ) {
this.renderer.setStyle(this.elref.nativeElement, 'display' , 'none');
}
if(this.isFeatureRequested === undefined ||
this.isFeatureRequested.length === 0) {
this.renderer.setStyle(this.elref.nativeElement, 'display' , 'none');
}
}
}
</code></pre>
<p>Can anyone give feedback on:</p>
<ol>
<li>how the code is written and what changes can be done to improve it?</li>
<li>how is the UI and is it effective?</li>
<li>what other featured can be added to the component?</li>
<li>any other feedback</li>
</ol>
<p>Any feedback weather positive or negative will be appreciated. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T21:25:07.473",
"Id": "458731",
"Score": "1",
"body": "Since your component is pretty complex (and a bit unreadable) I would suggest composing your main card from a number of child components. For example the table and the badge could be their own component."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T20:35:42.700",
"Id": "234503",
"Score": "3",
"Tags": [
"javascript",
"css",
"typescript",
"angular-2+"
],
"Title": "A reusable card component"
}
|
234503
|
<p>I wanted a polyfill of flexible array members in C89.
So I made something similar, and made a toy std::vector with limited functionality on top of it.
Here is the code:</p>
<p>vector.h</p>
<pre class="lang-c prettyprint-override"><code>/* Flexible array member example in C89 - Just because we can!
* It's demonstrated by vectors, but can be generalized.
* MIT License; see below for the license text.
* By Scorbie, 2019. */
#ifndef VECTOR_H
#define VECTOR_H
#include <assert.h>
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
/* We will use a plain array!
* We just store the header/metadata/other-fields/whatever
* in the front few fields, the number of which determined below.
* So the overall picture is the following:
* v-- The start of the allocated memory.
* v v-- The pointer returned.
* | | | | | | |*| | | | | ...
* |<- header->|<- array-- ...
* If we don't know the header size in advance, we can use another
* size_t for specifying the header size:
* | | | | | | | | | | | | |*| | | | | ...
* |<- header->|<- size_t->|<- array-- ...
*/
/* We will going to use this fixed header for our vector. */
struct header {
size_t size;
size_t capacity;
};
/* We define SIZE_MAX, because C89 doesn't define it for us. */
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t)(-1))
#endif
/* If needed, increase the capacity of the given header.
* On success, return the new header.
* On failure, return {0, 0} to signal an error.
* I am not sure whether I should raise an error. (errno=EDOM) */
static inline struct header header_increase_capacity(struct header head) {
assert(head.size <= head.capacity);
if (head.size == SIZE_MAX) {
head.size = 0; head.capacity = 0;
} else if (head.size == head.capacity) {
head.capacity = (head.capacity > SIZE_MAX/2) ? SIZE_MAX : 2 * head.capacity;
}
return head;
}
/* Byte, the unit of all data in C.
* Just gave it a better name to be explicit.
* I'm going to use memcpy to copy data byte by byte.
* This was the only way I found to be C89-conformant. */
typedef unsigned char byte;
#define VECTOR_INITIAL_CAPACITY 32
/* Get the size needed to completely cover the header by items of size item_size. */
static inline size_t header_get_offset(size_t item_size) {
const size_t header_size = sizeof(struct header);
/* header_len: how many items needed to cover the header. */
const size_t header_len = (header_size/item_size) + ((header_size%item_size) ? 1 : 0);
const size_t offset = (item_size * header_len);
return offset;
}
static inline struct header vector_get_header(void* vec, size_t item_size) {
struct header head;
byte* src;
byte* dest;
assert(vec);
src = (byte*)vec - header_get_offset(item_size);
dest = (byte*)(&head); /* To make my linter quiet and be explicit */
memcpy(dest, src, sizeof(struct header));
return head;
}
static inline void vector_set_header(void* vec, size_t item_size, struct header head) {
byte* src;
byte* dest;
assert(vec);
src = (byte*)(&head);
dest = (byte*)vec - header_get_offset(item_size);
memcpy(dest, src, sizeof(struct header));
}
static inline void* vector_init(size_t item_size) {
struct header head = {0, VECTOR_INITIAL_CAPACITY};
assert(item_size < SIZE_MAX / VECTOR_INITIAL_CAPACITY);
void* vec = malloc(item_size * head.capacity);
if (!vec) {
return NULL;
} else {
vec = (byte*)vec + header_get_offset(item_size);
vector_set_header(vec, item_size, head);
return vec;
}
}
static inline void* vector_increase_capacity(void* vec, size_t item_size) {
struct header head;
const size_t header_offset = header_get_offset(item_size);
byte* vec_mem_start = NULL;
byte* new_vec_mem_start = NULL;
void* new_vec = NULL;
assert(vec);
/* Try to allocate more memory with overflow checks. */
head = header_increase_capacity(vector_get_header(vec, item_size));
if ( head.capacity > (SIZE_MAX-header_offset)/(item_size) ) {
errno = EDOM;
} else if (head.capacity == 0) {
errno = EDOM;
} else {
vec_mem_start = (byte*)vec - header_offset;
new_vec_mem_start = realloc(vec_mem_start, header_offset + sizeof item_size * head.capacity);
}
/* Check for failure. */
if (!new_vec_mem_start) {
perror("Error: vector_increase_capacity failed");
return NULL;
} else {
new_vec = new_vec_mem_start + header_offset;
vector_set_header(new_vec, item_size, head);
return new_vec;
}
}
static inline size_t vector_get_size(void* vec, size_t item_size) {
assert(vec);
return vector_get_header(vec, item_size).size;
}
static inline int vector_bounds_check(void* vec, size_t item_size, size_t i) {
return (i >= 0 && i < vector_get_size(vec, item_size)) ? 0 : -1;
}
#endif /* VECTOR_H */
/* MIT License
* Copyright (c) 2019 Scorbie
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
</code></pre>
<p>Here's a small example of a <code>vector<int></code> using it.
main.c</p>
<pre class="lang-c prettyprint-override"><code>#include <assert.h>
#include <stdio.h>
#include "vector.h"
int* stack_init() {
return vector_init(sizeof(int));
}
int* stack_push(int* stack, int item) {
struct header head = vector_get_header(stack, sizeof *stack);
int* new_stack = vector_increase_capacity(stack, sizeof *stack);
if(!new_stack) { return NULL; }
assert(head.size < head.capacity);
new_stack[head.size++] = item;
vector_set_header(new_stack, sizeof *stack, head);
return new_stack;
}
int stack_peek(int* stack) {
size_t size = vector_get_size(stack, sizeof *stack);
return stack[size-1];
}
int stack_pop(int* stack) {
struct header head = vector_get_header(stack, sizeof *stack);
head.size--;
vector_set_header(stack, sizeof *stack, head);
return stack_peek(stack);
}
int stack_size(int* stack) {
return vector_get_size(stack, sizeof *stack);
}
int stack_at(int* stack, size_t i) {
int status = vector_bounds_check(stack, sizeof *stack, i);
if (status == -1) {
errno = ERANGE;
perror("Error while indexing stack");
return -1;
} else {
return stack[i];
}
}
int main(void) {
size_t i;
int* a = stack_init();
stack_push(a, 3);
stack_push(a, 4);
printf("%d\n", stack_peek(a));
for (i=0; i<stack_size(a); ++i) {
printf("%d\n", stack_at(a, i));
}
stack_pop(a);
stack_push(a, 5);
for (i=0; i<stack_size(a); ++i) {
printf("%d\n", stack_at(a, i));
}
return 0;
}
</code></pre>
<p>It would be especially thankful if any of these points are answered:</p>
<ul>
<li>Standard C89 conformance (Are some parts not in C89/result in UB etc?)</li>
<li>Performance (e.g. Is it slower than the sane approach; i.e. using double indirection by struct with pointers?)</li>
<li>Readability (Refactoring / Idiomatic C etc.)</li>
<li>Maintainance (My current expectation: This would get you fired if you use this in production, but only a little later than the one using only macros.)</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T21:22:50.713",
"Id": "458832",
"Score": "1",
"body": "The `inline` keyword is not part of C89. Are you sure you want conformance to C89 and not a newer C standard?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T03:10:05.667",
"Id": "458863",
"Score": "0",
"body": "Thanks for the info! Yes, I would like conformance to C89. (otherwise I would have just used flexible array members in c99) so feel free to nitpick any detail you see as non-C89 conformant. Thanks."
}
] |
[
{
"body": "<p>A very well done effort even though I am not a fan of loading .h files with so much inline code.</p>\n\n<hr>\n\n<ul>\n<li>Standard C89 conformance (Are some parts not in C89/result in UB etc?)</li>\n</ul>\n\n<p>Good to have used <code>unsigned char</code>.</p>\n\n<p>Only UB I see is with pathological <code>size == 0</code> leads to <code>/0</code></p>\n\n<hr>\n\n<ul>\n<li>Performance (e.g. Is it slower than the sane approach; i.e. using double indirection by struct with pointers?)</li>\n</ul>\n\n<p><strong>Consider space performance</strong></p>\n\n<p>An <code>VECTOR_INITIAL_CAPACITY 32</code> would be fairly piggish if code had a largest array of <em>vectors</em>. I'd start with 0 or pass into <code>vector_init()</code> the initial size.</p>\n\n<p><strong>Correct function?</strong></p>\n\n<p>In <code>vector_increase_capacity()</code>, I have doubts that after code sets <code>errno = EDOM;</code> the rest of code is correct. Should not code avoid the following <code>{ new_vec = new_vec_mem_start + header_offset; vector_set_header(new_vec, item_size, head); ... }</code>?</p>\n\n<hr>\n\n<ul>\n<li>Readability (Refactoring / Idiomatic C etc.)</li>\n</ul>\n\n<p><strong>why <code>dest</code></strong></p>\n\n<p>Unclear why extra code. Suggested simplification.</p>\n\n<pre><code>// byte* dest;\n// dest = (byte*)(&head); /* To make my linter quiet and be explicit */\n// memcpy(dest, src, sizeof(struct header));\nmemcpy(&head, src, sizeof *head);\n</code></pre>\n\n<p><strong>unneeded <code>else</code></strong></p>\n\n<pre><code>if (!vec) {\n return NULL;\n// } else {\n}\n vec = (byte*)vec + header_get_offset(item_size);\n vector_set_header(vec, item_size, head);\n return vec;\n// }\n</code></pre>\n\n<hr>\n\n<ul>\n<li>Maintenance (My current expectation: This would get you fired if you use this in production, but only a little later than the one using only macros.)</li>\n</ul>\n\n<p><strong>Post C89</strong></p>\n\n<p>Good this code tests for prior <code>SIZE_MAX</code> as perhaps another .h file made it or maybe code is now using C99</p>\n\n<p><strong>Collisions</strong></p>\n\n<p>Avoid using name space in an unexpected fashion.</p>\n\n<p>Inside <code>vector.h</code>, I would not expect to find a <code>struct</code> named <code>header</code>. I recommend to use <code>vector</code> or <code>vector_header</code>.</p>\n\n<p>This include function names like <code>header_get_offset()</code>. Better to uniformly start with <code>vector</code>.</p>\n\n<p>To define <code>byte</code> as <code>typedef unsigned char byte;</code> in a .h file is fairly brazen to assume some other .h and application did not define it, perhaps a bit differently. I'd recommend simple using <code>unsigned char</code>.</p>\n\n<p><strong>Does <code>#include \"vector.h\"</code> stand on its own?</strong></p>\n\n<p>As a test to insure <code>\"vector.h\"</code> includes itself, needed include files, try <code>\"vector.h\"</code> first.</p>\n\n<pre><code>#include \"vector.h\"\n#include <assert.h>\n#include <stdio.h>\n// #include \"vector.h\"\n</code></pre>\n\n<p><strong>IANAL but</strong></p>\n\n<p>Copyright notices need to be obvious, not buried at the end of code.</p>\n\n<p><strong>No free</strong></p>\n\n<p>I'd a function to call to free all allocations. Perhaps <code>void stack_uninit(void* vec)</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T00:34:56.110",
"Id": "458742",
"Score": "0",
"body": "Wow! A big THANK YOU for the detailed and clear explanation!\nCould you elaborate on static inline, whether it's bad style or personal preference and why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T02:03:43.087",
"Id": "458743",
"Score": "1",
"body": "I see long `inline` functions as [repetitive code](https://en.wikipedia.org/wiki/Code_bloat), rarely improving performance that much (and certainly not [big - 0](https://en.wikipedia.org/wiki/Big_O_notation)). For performance improvements, focusing on high level simplifications is more worth my time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T22:30:02.110",
"Id": "234562",
"ParentId": "234514",
"Score": "1"
}
},
{
"body": "<p>Update: here's the edited code thanks to the feedback!</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>/* Flexible array member example in C89 - Just because we can!\n * It's demonstrated by vectors, but can be generalized.\n * By Scorbie, 2019.\n * Reviewed by StackExchange users \"chux - Reinstate Monica\" and \"Björn Lindqvist\":\n * https://codereview.stackexchange.com/questions/234514\n * \n * MIT License\n * Copyright (c) 2019 Scorbie\n * Copyright (c) 2019 chux - Reinstate Monica\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#ifndef VECTOR_H\n#define VECTOR_H\n\n#include <assert.h>\n#include <errno.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n\n/* We will use a plain array!\n * We just store the header/metadata/other-fields/whatever\n * in the front few fields, the number of which determined below.\n * So the overall picture is the following:\n * v-- The start of the allocated memory.\n * v v-- The pointer returned.\n * | | | | | | |*| | | | | ...\n * |<- header->|<- array-- ...\n * If we don't know the header size in advance, we can use another\n * size_t for specifying the header size:\n * | | | | | | | | | | | | |*| | | | | ...\n * |<- header->|<- size_t->|<- array-- ...\n * */\n\n/* We will going to use this fixed header for our vector. */\nstruct vector_header {\n size_t size;\n size_t capacity;\n};\n\n/* We define SIZE_MAX, because C89 doesn't define it for us. */\n#ifndef SIZE_MAX\n#define SIZE_MAX ((size_t)(-1))\n#endif\n\n/* Get the size needed to completely cover the header by items of size item_size. */\nsize_t vector_header_get_offset(size_t item_size) {\n const size_t header_size = sizeof(struct vector_header);\n /* header_len: how many items needed to cover the header. */\n const size_t header_len = (header_size/item_size) + ((header_size%item_size) ? 1 : 0);\n const size_t offset = (item_size * header_len);\n return offset;\n}\n\nvoid* vector_get_mem_start(void* vec, size_t item_size) {\n assert(vec);\n return (unsigned char*)vec - vector_header_get_offset(item_size);\n}\n\nstruct vector_header vector_get_header(void* vec, size_t item_size) {\n struct vector_header header;\n unsigned char* src = vector_get_mem_start(vec, item_size);\n memcpy(&header, src, sizeof header);\n return header;\n}\n\nvoid vector_set_header(void* vec, size_t item_size, struct vector_header header) {\n unsigned char* dest = vector_get_mem_start(vec, item_size);\n memcpy(dest, &header, sizeof header);\n}\n\n/* Initialize vector with the given initial_capacity. \n * Initial capacity should be >= 1. */\nvoid* vector_init(size_t item_size, size_t initial_capacity) {\n struct vector_header header = {0, initial_capacity};\n void* vec;\n /* Assertions to prevent divide-by-0 and overflows */\n assert(item_size);\n assert(initial_capacity != 0 && initial_capacity < (SIZE_MAX/item_size));\n vec = malloc(initial_capacity * item_size);\n if (!vec) { return NULL; }\n vec = (unsigned char*)vec + vector_header_get_offset(item_size);\n vector_set_header(vec, item_size, header);\n return vec;\n}\n\n/* If needed, increase the capacity of the given header.\n * On success, return the new header.\n * On failure, return {0, 0} to signal an error. */\nstruct vector_header vector_header_increase_capacity(struct vector_header header) {\n assert(header.size <= header.capacity);\n if (header.size == SIZE_MAX) {\n /* No more memory, set it to error value */\n header.size = header.capacity = 0;\n } else if (header.size == header.capacity) {\n header.capacity = (header.capacity >= SIZE_MAX/2) ? SIZE_MAX : (2 * header.capacity);\n }\n return header;\n}\n\nvoid* vector_increase_capacity(void* vec, size_t item_size) {\n struct vector_header header;\n const size_t header_offset = vector_header_get_offset(item_size);\n void* vec_mem_start = vector_get_mem_start(vec, item_size);\n void* new_vec_mem_start = vec_mem_start;\n assert(vec);\n assert(item_size);\n assert(header_offset);\n /* Try to allocate more memory with overflow checks. */\n header = vector_header_increase_capacity(vector_get_header(vec, item_size));\n if (header.capacity == 0 || header.capacity > (SIZE_MAX-header_offset)/(item_size)) {\n errno = EDOM;\n perror(\"Error: vector_increase_capacity failed\");\n return NULL;\n }\n new_vec_mem_start = realloc(vec_mem_start, header_offset + item_size * header.capacity);\n /* Check for failure. */\n if (!new_vec_mem_start) {\n perror(\"Error: vector_increase_capacity failed\");\n return NULL;\n } else {\n void* new_vec = (unsigned char*)new_vec_mem_start + header_offset;\n vector_set_header(new_vec, item_size, header);\n return new_vec;\n }\n}\n\nint vector_is_out_of_bounds(void* vec, size_t item_size, size_t i) {\n return (i > vector_get_header(vec, item_size).size);\n}\n\nvoid vector_free(void* vec, size_t item_size) {\n void* vec_mem_start = vector_get_mem_start(vec, item_size);\n free(vec_mem_start);\n}\n\n#endif /* VECTOR_H */\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T02:52:16.873",
"Id": "234651",
"ParentId": "234514",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "234562",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T03:23:22.137",
"Id": "234514",
"Score": "2",
"Tags": [
"beginner",
"c"
],
"Title": "Flexible array member polyfill && Vector implementation in C89"
}
|
234514
|
<p>What is the problem when I return a promise from <code>angular service</code> instead of Observable?
If it's a matter of any manipulation or side-effect, that I can easily do inside angular service itself. Then why I shouldn't return a promise over observable?</p>
<p><strong>Here's my code for service class</strong></p>
<pre><code>public async getCountriesAsync(filter: PaginateFilter): Promise<Paginate<IdNameTypeModel>> {
return await this.http.get<Paginate<IdNameTypeModel>>(`/api/{version}/Types/{lang}/Countries${filter.url()}`)
.pipe(map(response => {
return response == null ? new Paginate<IdNameTypeModel>() : response;
})).toPromise();
}
</code></pre>
<p><strong>Using inside component</strong></p>
<pre><code>async loadCountries() {
const filter = new PaginateFilter(this.data.pageIndex, this.data.pageSize);
this.countries = await this.dldTypesService.getCountriesAsync(filter);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:24:36.123",
"Id": "461050",
"Score": "0",
"body": "On a side note, always use triple equality -> `response == null` will be `true` if `response = undefined` as well."
}
] |
[
{
"body": "<p>Per se returning a promise from an Angular Service is not bad, however there are numerous things in Angular world that are heavily based on Observables:</p>\n\n<ul>\n<li><del>usually you will likely change the <em>change detection</em> to <code>ChangeDetectionStrategy.OnPush</code> in your components and this will most likely be easier with Angular's <code>async</code> pipe</del> <strong>not a problem</strong>, because <code>async</code> also supports Promises.</li>\n<li>if you use your services for any kind of state and if your are using <em>NgRx</em> for effectively managing it, you'll be using <code>@Effects</code>that are basically a lot of RxJs magic and thus it might be easier to use <em>Observables</em> in the first place.</li>\n<li>composing services for <em>Guards</em> is easier with Observables</li>\n</ul>\n\n<p>Having that said, I agree with you, that typical REST services are <em>fire and forget</em> and thus IMO do not fit really into <code>Observables</code> well which are meant to be constant sources of events.</p>\n\n<p>It is all about composition, Observables allow better composition for <strong>multiple</strong> async operations that need to be <strong>composed</strong>, whereas Promises can be nowadays used pretty easy with <code>async/await</code> for <strong>singular, isolated</strong> operations.</p>\n\n<p>In the end, I'd advise to stick with the same convention throughout your whole app - <strong>either</strong> have all services return <em>Promises</em> and convert them to <em>Observables</em> when needed <strong>or</strong> always use <em>Observables</em>. I assume a lot of examples are using Observables because for non-trivial apps you end up needing better composition options than with pure Promises.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:22:38.427",
"Id": "235531",
"ParentId": "234516",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T04:31:30.213",
"Id": "234516",
"Score": "2",
"Tags": [
"javascript",
"angular.js",
"promise",
"angular-2+",
"rxjs"
],
"Title": "Is returning promise form angular service bad?"
}
|
234516
|
<p>I wrote script to install public key of my system to remote host.
I had tested the script it is working fine for me.
script take data like IP password and ssh port form CVS file.
I do not want to use import os.
only use CSV and paramiko imports.
My aim is to copy public key to my remote host.</p>
<pre><code>import csv
import os
from paramiko import SSHClient, AuthenticationException, AutoAddPolicy
username = "root"
key = open(os.path.expanduser('~/.ssh/id_rsa.pub')).read()
with open("hostinfo.csv") as h:
host = csv.reader(h, delimiter=",")
for i in host:
# csv file field ip,pass,port
HostIP, HostPass, HostPort = i[0], i[1], i[2]
try:
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(AutoAddPolicy)
client.connect(HostIP, HostPort, username, HostPass)
print("Running commands on {0} port {1}".format(HostIP, HostPort))
client.exec_command('mkdir -p ~/.ssh/')
client.exec_command('echo "%s" >> ~/.ssh/authorized_keys' % key)
client.exec_command('chmod 644 ~/.ssh/authorized_keys')
client.exec_command('chmod 700 ~/.ssh/')
print("Key is installed in {0}".format(HostIP))
except AuthenticationException:
raise AuthenticationException('Authentication failed: did you remember to create an SSH key?')
finally:
client.close()
print("connection is closed")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T00:22:15.073",
"Id": "458936",
"Score": "1",
"body": "Any reason you can't use [ssh-copy-id](https://www.ssh.com/ssh/copy-id)? \n\nIt would copy over the public key to the server you desire."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T17:09:16.177",
"Id": "458993",
"Score": "0",
"body": "If I want to install public key in 2000 servers then can I use ssh-copy-id and type password or export data to CSV then use script and Wait for output"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T22:22:47.617",
"Id": "459025",
"Score": "0",
"body": "What data are you collecting? I had assumed all you wanted to do was copy the public key to '2000' servers. Is there specific information you need from each time you copy the key over?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:31:23.543",
"Id": "459036",
"Score": "0",
"body": "2000 server is just for example ; my script is working but can you improve it. I not want os module to use in this script. Only CSV and paramiko I want.@zchpyvr"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:47:42.603",
"Id": "459038",
"Score": "0",
"body": "What I'm trying to say is that you don't need a Python script, there is already a well-written command-line utility for this exact scenario: ssh-copy-id. I recommend looking it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:48:55.997",
"Id": "459039",
"Score": "0",
"body": "Sir you are not understand my point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:51:51.130",
"Id": "459040",
"Score": "0",
"body": "I know command but I have CSV dump data and all servers not have same sab port and this script is helpful for me to copy my keys to server by not typing any password.@Zchpyvr"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:53:55.273",
"Id": "459041",
"Score": "0",
"body": "@Zchpyvr try to copy you ssh key to 200 server with ssh-copy-id then answer me what you feel to doing this for all day"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:58:50.950",
"Id": "459044",
"Score": "0",
"body": "Ok fine. Even if you have settled that is the best approach-- I'm confused why you don't want to import os when os is a core Python library-- it's guaranteed to be there every time you run this script. Can you explain your reasoning behind that requirement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T01:02:13.123",
"Id": "459047",
"Score": "0",
"body": "@Zchpyvr it is my personal point of view I don't like to import os."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T01:03:41.560",
"Id": "459049",
"Score": "0",
"body": "Then use the full absolute path for the key file? Something like `/home/my-user/.ssh/id_rsa.pub`? That way you don't need to import os."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T04:39:02.273",
"Id": "234517",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"ssh"
],
"Title": "ssh key install"
}
|
234517
|
<p>Very new to JS (wrote my "Hello World" around 3 days ago), but not to programming in general. My documentation is inspired by the approach I followed for Python (since I haven't learned JS documentation conventions yet).</p>
<h2>My Code</h2>
<pre class="lang-js prettyprint-override"><code>"use strict";
/*
Inserts elements from a given source array in a specified target array in sorted order. Modifies the target array in place.
Args:
* `source` (Array): Source array. The array is assumed to be already sorted.
Sorting is not done, as a custom sort function may be desired, and checking for sorting is not done as doing so would
greatly diminish the performance benefits of working with already sorted data.
* `target` (Array): Target array. The array is assumed to be already sorted (for similar reasons as above).
* `cmp` (function): Comparison function (predicate).
- Defaults to `<` operator.
- Args:
`a`.
`b`.
- Returns (boolean): Indicates if `a < b`.
It is important that the predicate indiates `a < b` and not `a <= b` so that the sort is stable.
*/
const sortedInsert = function(source, target, cmp = (a, b) => a < b)
{
let insertPosition = 0;
source.forEach(itm => {
let insertAtEnd = true;
for(let i = insertPosition; i < target.length; i++)
{
if(cmp(itm, target[i]))
{
target.splice(i, 0, itm);
insertPosition = i;
insertAtEnd = false;
break;
}
}
if (insertAtEnd)
{
target.splice(target.length, 0, itm);
insertPosition = target.length;
}
})
}
</code></pre>
|
[] |
[
{
"body": "<h2>Good things:</h2>\n\n<ul>\n<li>There is a very descriptive docblock above the function that documents the arguments.</li>\n<li><code>const</code> is used for things that don't change, whereas <code>let</code> is used for values that can be re-assigned.</li>\n</ul>\n\n<h2>Suggestions</h2>\n\n<ul>\n<li>When inserting at the end, just use <code>Array.push()</code> instead of <code>Array.splice()</code>. This not only simplifies the syntax but also should be faster (see this <a href=\"https://jsperf.com/splice-vs-push/12\" rel=\"nofollow noreferrer\">jsperf</a>).</li>\n<li>For <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged 'performance'\" rel=\"tag\">performance</a> reasons it would be wise to use a <code>for...of</code> loop instead of a <code>forEach()</code> to iterate over the items in <code>source</code> - especially for large arrays. Functional programming is nice but it has drawbacks - especially when performance is concerned. Consider that each iteration has a call to <code>cmp</code> so calling an extra function for each element in <code>source</code> could lead to a lot of extra overhead. With such a change the variable <code>insertAtEnd</code> could likely be removed if a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label\" rel=\"nofollow noreferrer\">label</a> outside the outer <code>for</code> loop was added and that label was used with a <code>continue</code> statement instead of the <code>break</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:12:21.867",
"Id": "238068",
"ParentId": "234519",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T04:49:50.103",
"Id": "234519",
"Score": "4",
"Tags": [
"javascript",
"performance",
"beginner",
"array",
"sorting"
],
"Title": "Inserting Elements Into a Sorted Array"
}
|
234519
|
<p>This generates a square matrix with spiral inward increasing values. How can I reduce this code? </p>
<p>Input Number = 3</p>
<p>Output </p>
<p>1 2 3</p>
<p>8 9 4</p>
<p>7 6 5</p>
<pre><code>import math
row=int(input("Input nomber := "))
lis=[[0 for i in range(0,row)]for j in range(0,row)]
y=row
a=1
c=0
z=0
x=1
k=1
f=row/2
f=math.ceil(f)
for b in range(0,f):
if b==k:
row=row-1
x=x+1
z=z+1
k=k+1
for c in range(z,row):
lis[b][c]=a
a=a+1
for d in range(x,row):
lis[d][row-1]=a
a=a+1
for e in range(row-1,z,-1):
lis[row-1][e-1]=a
a=a+1
for f in range(row-2,z,-1):
lis[f][z]=a
a=a+1
for i in range(0,y):
print()
for j in range(0,y):
print(lis[i][j],end="\t")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T06:52:12.390",
"Id": "458664",
"Score": "1",
"body": "What does the code do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T04:07:12.713",
"Id": "458751",
"Score": "0",
"body": "So an input of 3 produces a 3x3 matrix with the numbers 1 to 3². Is there anything significant about the ordering of the numbers? They don’t add up to a constant value, so it isn’t a magic square. At the risk of repeating myself, what does it do? Giving us an example of the output doesn’t tell us anything if we don’t understand what is significant about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T10:43:27.537",
"Id": "458766",
"Score": "0",
"body": "Nice piece of code, but quite unreadable, could you change the variable names to names which reflect the meaning of the variables. [Editing the question before there are answers is ok](https://codereview.meta.stackexchange.com/questions/8893/is-it-allowed-to-edit-code-if-there-is-no-answer)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T12:25:20.583",
"Id": "458775",
"Score": "0",
"body": "@JanKuiken THANK YOU SIR"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T14:19:40.760",
"Id": "469090",
"Score": "0",
"body": "Unrelated to the question, but some of your suggested edits are getting rejected. Quite a lot of them, actually. Please be more careful when suggesting an edit. Please make sure you're not introducing new mistakes, and changing British to American spelling is not considered polite. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T15:35:39.733",
"Id": "469095",
"Score": "0",
"body": "An additional unrelated point. I, and others, have manually fixed a lot of the edits you've made, as some of the content you changed was just wrong. GeeksforGeeks is a name, much like you don't write my name as pylon rays, you don't change GeeksforGeeks to geeks for geeks. That's just rude, and fundamentally incorrect. Please browse [your accepted edits](https://codereview.stackexchange.com/users/210094/brijesh-kalkani?tab=activity&sort=suggestions) for more changes I've made."
}
] |
[
{
"body": "<p>The code can be reduced by using:</p>\n\n<pre><code>row = int(input(\"Input number := \"))\nlis = [[0 for i in range(0,row)] for j in range(0,row)]\ns = []\nif row > 1:\n s += [row-1]\n for i in range(row-1, 0, -1):\n s += [i,i]\nb = 1\ne = 1\na = 0\nc = 0\nd = 0\nlis[0][0] = e\nfor n in s:\n for f in range(n):\n c += a\n d += b\n e += 1\n lis[c][d] = e\n a, b = b, -a\nfor i in range(0,row):\n print()\n for j in range(0,row):\n print(lis[i][j],end=\"\\t\")\n</code></pre>\n\n<p>However this code is as unreadable as your code and probably uses a different method than yours. You do not only write code to perform a specific task, but you also want to communicate to other programmers (or yourself when you look at the code a year later) what you have done. This can be done by:</p>\n\n<ul>\n<li>using sensible variable names </li>\n<li>splitting up codes in smaller pieces (functions) </li>\n<li>comments </li>\n<li>docstrings</li>\n</ul>\n\n<p>Your method is probably very clever, but I cannot figure out how it works from your code. My code can made be more understandable, although far from perfect, by applying previous points:</p>\n\n<pre><code>\"\"\"\nCode to create a square matrix filled with ascending values in a inward\nspiral starting from the upper left. The matrix is a list of lists.\n\nConventions used:\n i - first matrix index or row index\n j - second matrix index or column index\n di, dj - direction vector to move from one matrix position to another\n\"\"\"\n\ndef rotate_90degrees_clockwise(di, dj):\n \"\"\"Rotates a direction vector (di,dj) clockwise, i.e.:\n RIGHT(0,1) -> DOWN(1,0) -> LEFT(0,-1) -> UP(-1,0)\n \"\"\"\n return dj, -di\n\ndef spiral_direction_steps(n):\n \"\"\"Create a list of numbers of steps to go sequentially to the right, \n down, left, up, right, down, left, up, ... etc.. to create a inward \n spiraling route, starting from the upper left, i.e. for n = 3:\n 2 x right, 2 x down, 2 x left, 1 x up, 1 x right\n General idea:\n 1) first we go (n-1) x right, (n-1) x down, (n-1) x left\n 2) then we go (n-2) x up, (n-2) x right\n 3) then we go (n-3) x down, (n-3) x left\n 4) repeat steps 2 and 3 till the number of steps is 1\n \"\"\"\n retval = []\n if n > 1:\n retval += [n-1]\n for i in range(n-1, 0, -1):\n retval += [i,i]\n return retval\n\ndef spiral_matrix(n):\n \"\"\"Generate a square matrix (list of lists) of size n x n, with ascending \n numbers in a clockwise spiral, starting in the upper left corner\n \"\"\"\n mat = [[0 for i in range(0,n)] for j in range(0,n)]\n\n val = 1 # start value\n i, j = 0, 0 # start point\n di, dj = 0, 1 # start direction \n\n mat[i][j] = val # fill start point\n\n # fill other points\n steps = spiral_direction_steps(n)\n for n in steps:\n for _ in range(n):\n i += di\n j += dj\n val += 1\n mat[i][j] = val\n di, dj = rotate_90degrees_clockwise(di, dj)\n return mat\n\ndef print_matrix(mat):\n \"\"\"Prints a matrix which is a list of lists\"\"\"\n for row in mat:\n print()\n for col in row:\n print(col, end=\"\\t\")\n print()\n\ndef main():\n n = int(input(\"Input number := \"))\n matrix = spiral_matrix(n)\n print_matrix(matrix)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T17:12:51.583",
"Id": "234599",
"ParentId": "234520",
"Score": "5"
}
},
{
"body": "<p>As @JanKuiken mentioned, your idea is probably clever, but I can't understand what your code does either! Please add it to the question if possible!</p>\n\n<ul>\n<li><p>You need more spaces in your code!</p></li>\n<li><p>Prefer <code>+=</code> and <code>-=</code> operators as they are more compact than assignments such as <code>x = x + 1</code>.</p></li>\n<li><p><code>for variable in range(0, end)</code> is not necessary as <code>range</code> starts the sequence with 0 by default.</p></li>\n<li><p>Use meaningful variable names</p></li>\n<li><p>The variable <code>y</code> is declared unnecessarily.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>a = 1\nc = 0\nz = 0\nx = 1\nk = 1\n</code></pre>\n\n<ul>\n<li>The above part looks pretty bad. Change it to the below code</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>c = z = 0\na = x = k = 1\n</code></pre>\n\n<ul>\n<li><p>The variable <code>f</code> outside the <code>for</code> loop is conflicting with the <code>f</code> inside the for loop. You can remove the use of <code>f</code> with <code>for b in range(math.ceil(row / 2)):</code></p></li>\n<li><p><code>lis = [[0] * row for j in range(row)]</code> is faster!</p></li>\n<li><p>To print the array, use</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i in lis: # Faster and smaller!\n print(*i, sep='\\t')\n</code></pre>\n\n<p>Here's a glimpse of how your final code might look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import math\n\nrow = int(input(\"Input number := \"))\n\nlis = [[0] * row for j in range(row)]\n\nc = z = 0\na = x = k = 1\n\nfor b in range(math.ceil(row / 2)):\n if b == k:\n row -= 1\n x += 1\n z += 1\n k += 1\n\n for c in range(z, row):\n lis[b][c] = a\n a += 1\n\n for d in range(x, row):\n lis[d][row-1] = a\n a += 1\n\n for e in range(row-1, z, -1):\n lis[row-1][e-1] = a\n a += 1\n\n for f in range(row-2, z, -1):\n lis[f][z] = a\n a += 1\n\nfor i in lis:\n print(*i, sep='\\t')\n</code></pre>\n\n<p>Here's how I'd have approached this problem:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>n = int(input('Enter the size of the grid: '))\nresult = [[0] * n for _ in range(n)]\n\n# Ending points\nei, ej = n // 2, (n - 1) // 2\n\n# 0: RIGHT, 1: DOWN, 2: LEFT, 3: UP\norient = 0\n\ndef fill(i: int, j: int, di: int, dj: int, val: int) -> tuple:\n \"\"\"\n 'i' is the current row index\n 'j' is the current column index\n 'di' is the direction of the row (1: UP, -1: DOWN)\n 'dj' is the direction of the column (1: RIGHT, -1: LEFT)\n 'val' is the next value in the spiral\n \"\"\"\n\n while 0 <= i + di < n and 0 <= j + dj < n:\n if result[i + di][j + dj] != 0:\n break\n\n i += di\n j += dj\n\n result[i][j] = val\n val += 1\n\n return i, j, val\n\n# 'j' is -1 because the (0, 0) is yet to be filled\ni, j = 0, -1\nval = 1\n\nwhile (i, j) != (ei, ej):\n if orient == 0: i, j, val = fill(i, j, 0, 1, val)\n if orient == 1: i, j, val = fill(i, j, 1, 0, val)\n if orient == 2: i, j, val = fill(i, j, 0, -1, val)\n if orient == 3: i, j, val = fill(i, j, -1, 0, val)\n\n orient = (orient + 1) % 4\n\nfor i in result:\n print(*i, sep='\\t')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-21T19:02:25.297",
"Id": "237714",
"ParentId": "234520",
"Score": "5"
}
},
{
"body": "<p>Covering what others suggested (e.g. @Srivaths), please follow at least PEP8 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python PEP8</a></p>\n\n<p>Then, put your code in some function.\nGive meaningful names to variables. (What's a, c, x, z ... why are you not using b? )</p>\n\n<p>You don't need <code>import math</code> -- instead of <code>f=row/2\nf=math.ceil(f)</code>, you can do <code>f = row // 2</code> (assuming you use python 3). </p>\n\n<p>Note that you can solve the problem more generally, for m x n matrix, which you can initialize as:\n<code>matrix = [[0 for col in range(nCols)] for row in range(nRows)]</code>\n(see the answer from <a href=\"https://stackoverflow.com/questions/4056768/how-to-declare-array-of-zeros-in-python-or-an-array-of-a-certain-size/4056782\">StackOverflow</a>, provided by @OK).\nThis\n <code>matrix = [[0] * m] * n</code>, as pointed in the comments, won't work because of list references.</p>\n\n<p>Now, we can also observe that you can fill the \"outer rectangle\", i.e. matrix[0][:] = range(1, nCols + 1); then, you can fill the rightmost column </p>\n\n<pre><code>cnt += nCols\nfor row in range(1, nRows):\n matrix[row][rightIdx] = cnt\n cnt += 1\n# Bottom row:\nmatrix[bottomIdx][leftIdx:] = reversed(range(cnt, cnt + nCols - 1) # might be off by 1;\n# Complete first column\n\n# Put this in a while loop;\n</code></pre>\n\n<p>This problem is similar -- once you have the matrix, print it in a spiral order:\n<a href=\"https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/\" rel=\"nofollow noreferrer\">Geeks for geeks website</a>.</p>\n\n<p>Also, you can check the solution of LeetCode Prob 54, but I would encourage you to try solving the problem yourself first.\n<a href=\"https://leetcode.com/problems/spiral-matrix/\" rel=\"nofollow noreferrer\">Problem 54</a> <a href=\"https://leetcode.com/articles/spiral-matrix/\" rel=\"nofollow noreferrer\">Solution for Problem 54</a></p>\n\n<p>And here is my solution to Problem 54, similar to Solution 2 (Leetcode Solution link above): <a href=\"https://gist.github.com/mcimpoi/13848804099e3460e59967e43040ac7f\" rel=\"nofollow noreferrer\">My solution :)</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-22T23:05:13.950",
"Id": "466327",
"Score": "1",
"body": "As the function used here is `math.ceil(row / 2)`, I believe `row // 2` will floor the parameter. `(row + 1) // 2` should work fine though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-22T23:07:47.730",
"Id": "466328",
"Score": "1",
"body": "Using `lis` as `[[0] * m] * n` would create some weird errors. The reference to `[0] * m` will be created `n` times. If I modify any index, all the values in the column will also be modified."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-22T20:47:32.163",
"Id": "237757",
"ParentId": "234520",
"Score": "6"
}
},
{
"body": "<p>I try to resolve the problem using recursion.\nIt's not the most efficient solution in Python, but it's elegant and clean.</p>\n\n<pre><code>def spiral(mx, i, j, dir, a, max_i, max_j):\n \"\"\"\n mx: matrix to fill\n i, j: matrix position to analize\n dir: direction to fill\n a: list of values to insert\n max_i, max_j: dimension of matrix\n \"\"\"\n # no more value tu insert\n if len(a) == 0:\n # stop recursion\n return\n\n if dir == \"right\":\n if j < max_j and mx[i][j] == 0:\n mx[i][j] = a[0]\n spiral(mx, i, j+1, \"right\", a[1:], max_i, max_i)\n else:\n spiral(mx, i+1, j-1, \"down\", a, max_i, max_j)\n elif dir == \"down\":\n if i < max_i and mx[i][j] == 0:\n mx[i][j] = a[0]\n spiral(mx, i+1, j, \"down\", a[1:], max_i, max_j)\n else:\n spiral(mx, i-1, j-1, \"left\", a, max_i, max_j)\n elif dir == \"left\":\n if j >= 0 and mx[i][j] == 0:\n mx[i][j] = a[0]\n spiral(mx, i, j-1, \"left\", a[1:], max_i, max_j)\n else:\n spiral(mx, i-1, j+1, \"up\", a, max_i, max_j)\n elif dir == \"up\":\n if i >= 0 and mx[i][j] == 0:\n mx[i][j] = a[0]\n spiral(mx, i-1, j, \"up\", a[1:], max_i, max_j)\n else:\n spiral(mx, i+1, j+1, \"right\", a, max_i, max_j)\n\n# square matrix dimesion\nn_dim = 30\n# list of values to insert in matrix\nl = [x+1 for x in range(n_dim**2)]\n# matrix to fill\nmx = [[0 for i in range(n_dim)] for j in range(n_dim)]\n\n# start recursion\nspiral(mx, 0, 0, \"right\", l, n_dim, n_dim)\n\nfor i in range(n_dim):\n for j in range(n_dim):\n print(\"{0:4d}\".format(mx[i][j]), end=\"\")\n print(\"\\n\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T10:45:59.507",
"Id": "238153",
"ParentId": "234520",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234599",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T05:13:33.013",
"Id": "234520",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"matrix"
],
"Title": "Matrix with spiral increasing values"
}
|
234520
|
<p>As the year comes to an end our company need new time-sheets for the new year. Because this is my task to do, I thought I would do my collegues something good by automating some tasks they would otherwise need to do manually. </p>
<p>Until now we had a worksheet for presettings, like setting employee-name, ident-number, remaining holidays and over-time. The users then had to print this sheet, sign it and scan it to send it to our staff-email adress.</p>
<p>Additionally, they enter each day their working and break times and at the first day of the new month they have to print it, sign it and send it to our staff-email adress. They have to do the same for their expenses and for their vacation applications. </p>
<p>To automate these tasks I have added 2 buttons to each of the sheets, one button to print the current sheet with just </p>
<pre><code>Sub PrintActiveSheet()
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False
End Sub
</code></pre>
<p>as the code behind. </p>
<p>The other button to save the sheet as pdf and mail it has this code behind </p>
<pre><code>Private Const January As String = "Januar"
Private Const February As String = "Februar"
Private Const March As String = "März"
Private Const April As String = "April"
Private Const May As String = "Mai"
Private Const June As String = "Juni"
Private Const July As String = "Juli"
Private Const August As String = "August"
Private Const September As String = "September"
Private Const October As String = "Oktober"
Private Const November As String = "November"
Private Const December As String = "Dezember"
Private Const PreSetting As String = "Voreinstellungen"
Private Const VacationApplication As String = "Urlaubsantrag"
Private Const VacationApplicationName As String = "Urlaub_Gleittag_Antrag"
Private Const Expenses As String = "Spesen"
Private Const ExpensesName As String = "Reisekosten"
Private Const WorkingTime As String = "Arbeitszeit"
Private Const StaffEmailAdress = "StaffEmail@Company.org"
Sub SaveAsPdf()
Dim presetSheet As Worksheet
Set presetSheet = ActiveWorkbook.Sheets(1)
Dim shortName As String
shortName = ComposeFileName(presetSheet)
Dim fileName As String
Dim shell As Object
Set shell = CreateObject("WScript.Shell")
fileName = shell.SpecialFolders("MyDocuments") + "\" + shortName + ".pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:= _
fileName, Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
SendAsMail fileName, StaffEmailAdress, shortName
End Sub
Private Sub SendAsMail(fileName As String, receiver As String, subject As String)
Dim outlook As Object
Set outlook = CreateObject("Outlook.Application")
Dim message As Object
Set message = outlook.CreateItem(0)
With message
.Display
.To = receiver
.CC = ""
.subject = subject
.Attachments.Add fileName
End With
End Sub
Private Function ComposeFileName(presetSheet As Worksheet) As String
Dim sheetName As String
sheetName = ActiveSheet.Name
Dim year As String
year = presetSheet.Cells(2, 11)
Dim shortName As String
shortName = presetSheet.Cells(3, 11).Value
If sheetName = PreSetting Then
ComposeFileName = year + "_" + sheetName + "_" + shortName
Exit Function
End If
If sheetName = Expenses Then
ComposeFileName = Mid(year, 3) + "-" + FetchMonthNumber(ActiveSheet.Cells(4, 3).Value) + "_" + ExpensesName + "_" + shortName
Exit Function
End If
If sheetName = VacationApplication Then
ComposeFileName = year + "_" + VacationApplicationName + "_(" + Format(Date) + ")_" + shortName
Exit Function
End If
ComposeFileName = Mid(year, 3) + "-" + FetchMonthNumber(sheetName) + "_" + WorkingTime + "_" + shortName
Exit Function
End Function
Private Function FetchMonthNumber(monthName As String) As String
If monthName = January Then
FetchMonthNumber = "01"
Exit Function
End If
If monthName = February Then
FetchMonthNumber = "02"
Exit Function
End If
If monthName = March Then
FetchMonthNumber = "03"
Exit Function
End If
If monthName = April Then
FetchMonthNumber = "04"
Exit Function
End If
If monthName = May Then
FetchMonthNumber = "05"
Exit Function
End If
If monthName = June Then
FetchMonthNumber = "06"
Exit Function
End If
If monthName = July Then
FetchMonthNumber = "07"
Exit Function
End If
If monthName = August Then
FetchMonthNumber = "08"
Exit Function
End If
If monthName = September Then
FetchMonthNumber = "09"
Exit Function
End If
If monthName = October Then
FetchMonthNumber = "10"
Exit Function
End If
If monthName = November Then
FetchMonthNumber = "11"
Exit Function
End If
If monthName = December Then
FetchMonthNumber = "12"
Exit Function
End If
FetchMonthNumber = ""
End Function
</code></pre>
<p>I imagine there can something be improved and like always I am open for suggestion about any aspect of the code. </p>
|
[] |
[
{
"body": "<p>All your arguments can/should be passed <code>ByVal</code>. As they are presently written they are implicitly <code>ByRef</code>, the default when neither is specified. You want them written ByVal since you're accessing them and not changing them.</p>\n\n<p>Use of <code>\"\"</code> can be rewritten as <code>vbNullString</code>. <code>\"\"</code> leaves doubt as possibly the string had contents previously but were possibly removed accidentally. Maybe? <code>vbNullstring</code> makes it unambiguous that it's intentional.</p>\n\n<p>Sub <code>SaveAsPdf</code> is implicitly public. Explicitly set it to public with <code>Public Sub SaveAsPdf()</code> so there's no doubt you intended it to be this way.</p>\n\n<p><code>Mid</code> can be written as the string version <code>Mid$</code> because year is declared as a string.</p>\n\n<p>Within <code>ComposeFileName</code> you are using the ActiveSheet object. It's better to explicitly supply this dependency as an argument because right now it's an implicit dependency that needs to be known about. This is what it would look like at the call site <code>ComposeFileName(ActiveWorkbook.Sheets(1), ActiveSheet)</code> and below is the rewritten function signature. ***Note that <code>ActiveWorkbook.Sheets(1)</code> should be referenced by its CodeName as explained later.</p>\n\n<pre><code>Private Function ComposeFileName(ByVal presetWorksheet As Worksheet, ByVal happenedToBeTheActiveSheet As Worksheet) As String\n</code></pre>\n\n<p>Again within <code>ComposeFileName</code> you have <code>year = presetSheet.Cells(2, 11).Value2</code> which is a problem waiting to occur. What happens if you insert a row above that cell, or a column to the left of it? You're now referencing an incorrect cell. Update that static cell reference by using a Named range. From the ribbon under the Formulas tab>Defined Names group>Name Manager (Hotkey: <code>Ctrl+F3</code>) to display the Name Manager dialog.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eQ9XR.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eQ9XR.png\" alt=\"enter image description here\"></a></p>\n\n<p>In the Name Manager dialog click the New button to create a named range for this cell. Under Scope choose the sheet it belongs to so it's limited to just that sheet and refer to the cell you want. Providing a descriptive name like YearCell will aid in understanding why it's has a name. Update your code to use <code>presetSheet.Names(\"YearCell\").RefersToRange.Value2</code>. Now when, not if, a row/column is added your cell reference won't break. The same goes for the cells that refer to the variables <code>shortName</code> as well as the cells that contain the month's name.</p>\n\n<hr>\n\n<p>Similar to how cell references are fragile your use of the Worksheet.Name property is also fragile. If the sheet names are changed then your code will break. Prefer using the Worksheet.CodeName property as it can only be changed in the IDE. Do this by going to the Project Explorer and double clicking on the sheet you want to update the CodeName for. From the menu at the top of the IDE View>Properties Window (Hotkey: <code>F4</code>) and where it says (Name) Sheet1 rename it to what you want. Naming it fooSheet allows you to use <code>fooSheet.Name</code> to get the name property or any other member of a worksheet object making your code less prone to easy breakage.</p>\n\n<hr>\n\n<p>Your <code>Const</code> values that deal with months feel like they should be an Enum. This way when you need to use them you can type <code>Months.</code> (note the period) and you'll be given a full list of month names.</p>\n\n<pre><code>Public Enum Months\n NotSet\n January\n February\n' ...\n November\n December\nEnd Enum\n</code></pre>\n\n<p>After converting to an Enum you can use a class module instead of a function. The class below uses a reference set from the menu at the top Tools>References>Microsoft Scripting Runtime which provides access to a dictionary <code>Scripting.Dictionary</code>. When the class is first initialized it populates the dictionaries thereafter allowing you to convert the supplied value instead of checking against every month.</p>\n\n<p>The converter includes guard clauses to raise an error on invalid inputs. These can easily be modified as required.</p>\n\n<pre><code>Option Explicit\n\nPrivate StringForEnum As Scripting.Dictionary\nPrivate EnumForString As Scripting.Dictionary\n\nPrivate Sub Class_Initialize()\n PopulateDictionaries\nEnd Sub\n\nPrivate Sub PopulateDictionaries()\n Set EnumForString = New Scripting.Dictionary\n Set StringForEnum = New Scripting.Dictionary\n\n EnumForString.CompareMode = VBA.VbCompareMethod.vbTextCompare\n EnumForString.Add vbNullString, Months.NotSet\n EnumForString.Add \"Januar\", Months.January\n EnumForString.Add \"Februar\", Months.February\n EnumForString.Add \"März\", Months.March\n EnumForString.Add \"April\", Months.April\n EnumForString.Add \"Mai\", Months.May\n EnumForString.Add \"Juni\", Months.June\n EnumForString.Add \"Juli\", Months.July\n EnumForString.Add \"August\", Months.August\n EnumForString.Add \"September\", Months.September\n EnumForString.Add \"Oktober\", Months.October\n EnumForString.Add \"November\", Months.November\n EnumForString.Add \"Dezember\", Months.December\n\n EnumForString.CompareMode = VBA.VbCompareMethod.vbTextCompare\n Dim i As Variant\n For Each i In EnumForString.Keys\n StringForEnum.Add EnumForString.Item(i), i\n Next\nEnd Sub\n\nPublic Function ToEnum(ByVal value As String) As Months\n If Not EnumForString.Exists(value) Then\n ThrowInvalidArgument \"ToEnum\", value\n End If\n\n ToEnum = EnumForString(value)\nEnd Function\n\nPublic Function ToString(ByVal value As Months) As String\n If Not StringForEnum.Exists(value) Then\n ThrowInvalidArgument \"ToString\", CStr(value)\n End If\n\n ToString = StringForEnum(value)\nEnd Function\n\nPrivate Sub ThrowInvalidArgument(ByVal source As String, ByVal value As String)\n Err.Raise 5, Information.TypeName(Me) & \".\" & source, \"Invalid input '\" & value & \"' was supplied.\"\nEnd Sub\n\nPublic Property Get Enums() As Variant\n Enums = EnumForString.Items\nEnd Property\n\nPublic Property Get Strings() As Variant\n Strings = EnumForString.Keys\nEnd Property\n</code></pre>\n\n<p>The converter is created and used as shown below. As shown it will return a value af <code>1</code></p>\n\n<pre><code>Dim converter As MonthConverter\nSet converter = New MonthConverter\nDebug.Print converter.ToEnum(\"Januar\")\n</code></pre>\n\n<p>Your original function returned a two digit string number. Achieve that by wrapping the return value with the Format member of the Strings class: <code>Strings.Format(converter.ToEnum(\"Januar\"))</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:22:26.637",
"Id": "234553",
"ParentId": "234522",
"Score": "8"
}
},
{
"body": "<p>I'm not a user of Excel so I haven't raised any of the excellent points raised by @IvenBach. This answer is more concerned about separation of concerns and re-usability. </p>\n\n<p>The month name to month number lookup has been consolidated into its own Class which allows a fairly simple process for creating a new MonthNumbers object where January is not month \"01\". I've also taken the opportunity to use only the first 3 letters of the month name as the keys in the internal lookup dictionary so that the class will work with full and partial names of any case.</p>\n\n<p><strong>Class MonthNumbers</strong> </p>\n\n<pre><code>'@PredeclaredId\nOption Explicit\n\nPrivate Type State\n\n NameToNumber As Scripting.Dictionary\n\nEnd Type\n\nPrivate s As State\n\n'Private Sub Class_Initialize()\n'\n' Main.FailIfMeIsNotPredeclaredId Me, MonthNumbers\n'\n'End Sub\n\nPublic Function Make(ByVal NumberArray As Variant, ByVal MonthArray As Variant) As MonthNumbers\n\n With New MonthNumbers\n\n Set Make = .Self(NumberArray, MonthArray)\n\n End With\n\nEnd Function\n\n\nPublic Function Self(ByVal NumberArray As Variant, ByVal MonthsArray As Variant) As MonthNumbers\n\n If UBound(NumberArray) <> UBound(MonthsArray) Then\n\n Err.Raise vbObjectError + 404, \"Months:Self: Arrays must be the same size and have the same Bounds\"\n End\n\n End If\n\n Dim myItem As Long\n Set s.NameToNumber = New Scripting.Dictionary\n For myItem = 0 To UBound(NumberArray)\n\n s.NameToNumber.Add LCase$(Left$(Trim$(MonthsArray(myItem))), 3), LCase$(Left$(Trim$(NumberArray(myItem))), 3)\n\n Next\n\n Set Self = Me\n\nEnd Function\n\n\nPublic Function Number(ByVal MonthName As String) As String\n\n Number = IIf(s.NameToNumber.Exists(LCase$(Left$(MonthName, 3))), s.NameToNumber.Item(LCase$(Left$(MonthName, 3))), vbNullString)\n\nEnd Function\n</code></pre>\n\n<p>There are four different types of report in the method 'ComposeFileName' (at least by the way in which the filenames are constructed differently for each report type). To disentangle the logic I created Four classes - Expenses, PreSetting, VacationApplication and WorkingTime. Due to the lack of inheritance in VBA there is a degree of duplicated code between these classes but I feel it is acceptable to bear this duplication for such small classes. </p>\n\n<p>These classes are static in that they only use the PredeclaredId instance. New instances of the Classes are not created (but could be if the code was adapted). I also relocated the getting of the destination path from the SaveAsPdf method to these classes but it may be that this is a step too far. </p>\n\n<p>The destination path and month to month number lookup are injected into the classes Through the Setup Method as I though this might be done once in a session whereas there may be a number of different other reports produced. The Setup method is unusual in that it is a function which returns the PredeclaredId instance. This has been done to simplify simultaneous setup and addition to a holding scripting.dictionary. The method which takes the spreadsheet to be saved is declared as an Interface to allow intellisense and the avoidance of a Select Case or Multi part If ElseIf Else to select which type of report to save. </p>\n\n<p><strong>Class Expenses</strong></p>\n\n<pre><code>'@PredeclaredId\nOption Explicit\n\nPrivate Const EXPENSES_NAME As String = \"Reisekosten\"\n\nPrivate Type State\n\n SavePath As String\n Months As MonthNumbers\n\nEnd Type\n\nPrivate s As State\n\nImplements IPathAndName\n\nPrivate Function IPathAndName_PathAndName(ByVal ReportSheet As Excel.Worksheet) As String\n\n IPathAndName_PathAndName = PathAndName(ReportSheet)\n\nEnd Function\n\n\nPublic Function Setup(ByVal SavePath As String, ByRef Months As MonthNumbers) As Expenses\n\n Set s.Months = Months\n s.SavePath = SavePath\n Set Setup = Me\nEnd Function\n\n\nPublic Function PathAndName(ByRef ReportSheet As Excel.Worksheet) As String\n\n Dim myWorkbook As Excel.Workbook\n Set myWorkbook = ReportSheet.Parent\n\n Dim myPresetSheet As Excel.Worksheet\n Set myPresetSheet = myWorkbook.Sheets.Item(1)\n\n Dim myActiveSheet As Excel.Worksheet\n Set myActiveSheet = myWorkbook.ActiveSheet\n\n Dim myYear As String\n myYear = myPresetSheet.Cells.Item(2, 11)\n\n Dim myShortName As String\n myShortName = myPresetSheet.Cells.Item(3, 11).Value\n\n PathAndName = _\n s.SavePath _\n & \"\\\" _\n & Mid$(myYear, 3, 2) _\n & \"-\" _\n & s.Months.Number(Left$(myActiveSheet.Cells.Item(4, 3).Value, 3)) _\n & \"_\" _\n & EXPENSES_NAME _\n & \"_\" _\n & myShortName _\n & \".pdf\"\n\n\nEnd Function\n</code></pre>\n\n<p><strong>Class PreSetting</strong></p>\n\n<pre><code>'@PredeclaredId\nOption Explicit\n\nPrivate Type State\n\n SavePath As String\n Months As MonthNumbers\n\nEnd Type\n\nPrivate s As State\n\n\nImplements IPathAndName\n\n\nPrivate Function IPathAndName_PathAndName(ByVal ReportSheet As Excel.Worksheet) As String\n\n IPathAndName_PathAndName = PathAndName(ReportSheet)\n\nEnd Function\n\n\nPublic Function Setup(ByVal SavePath As String, ByVal Months As MonthNumbers) As PreSetting\n\n Set s.Months = Months\n s.SavePath = SavePath\n Set Setup = Me\n\nEnd Function\n\n\nPublic Function PathAndName(ByVal ReportSheet As Excel.Worksheet) As String\n\n Dim myWorkbook As Excel.Workbook\n Set myWorkbook = ReportSheet.Parent\n\n Dim myPresetSheet As Excel.Worksheet\n Set myPresetSheet = myWorkbook.Sheets.[_Default](1)\n\n Dim myActiveSheet As Excel.Worksheet\n Set myActiveSheet = myWorkbook.ActiveSheet\n\n Dim myYear As String\n myYear = myPresetSheet.Cells.Item(2, 11)\n\n Dim myShortName As String\n myShortName = myPresetSheet.Cells.Item(3, 11).Value\n\n PathAndName = _\n s.SavePath _\n & \"\\\" _\n & myYear _\n & \"-\" _\n & myActiveSheet.Name _\n & \"_\" _\n & myShortName _\n & \".pdf\"\n\nEnd Function\n</code></pre>\n\n<p><strong>Class VacationApplication</strong></p>\n\n<pre><code>'@PredeclaredId\nOption Explicit\n\nPrivate Const VACATION_APPLICATION_NAME _\n As String = \"Urlaub_Gleittag_Antrag\"\n\nPrivate Type State\n\n SavePath As String\n Months As MonthNumbers\n\nEnd Type\n\nPrivate s As State\n\n\nImplements IPathAndName\n\n\nPrivate Function IPathAndName_PathAndName(ByVal ReportSheet As Excel.Worksheet) As String\n\n IPathAndName_PathAndName = PathAndName(ReportSheet)\n\nEnd Function\n\n\nPublic Function Setup(ByVal SavePath As String, ByRef Months As MonthNumbers) As VacationApplication\n\n Set s.Months = Months\n s.SavePath = SavePath\n Set Setup = Me\n\nEnd Function\n\n\nPublic Function PathAndName(ByRef ReportSheet As Excel.Worksheet) As String\n\n Dim myWorkbook As Excel.Workbook\n Set myWorkbook = ReportSheet.Parent\n\n Dim myPresetSheet As Excel.Worksheet\n Set myPresetSheet = myWorkbook.Sheets.[_Default](1)\n\n' Dim myActiveSheet As Excel.Worksheet\n' myActiveSheet = myWorkbook.ActiveSheet\n\n Dim myYear As String\n myYear = myPresetSheet.Cells.Item(2, 11)\n\n Dim myShortName As String\n myShortName = myPresetSheet.Cells.Item(3, 11).Value\n\n PathAndName = _\n s.SavePath _\n & \"\\\" _\n & myYear _\n & \"_\" _\n & VACATION_APPLICATION_NAME _\n & \"_(\" _\n & Format$(Date) _\n & \")_\" _\n & myShortName _\n & \".pdf\"\n\n\nEnd Function\n</code></pre>\n\n<p><strong>Class WorkingTime</strong></p>\n\n<pre><code>'@PredeclaredId\nOption Explicit\n\nPrivate Const WORKING_TIME As String = \"Arbeitszeit\"\n\nPrivate Type State\n\n SavePath As String\n Months As MonthNumbers\n\nEnd Type\n\nPrivate s As State\n\n\nImplements IPathAndName\n\n\nPrivate Function IPathAndName_PathAndName(ByVal ReportSheet As Excel.Worksheet) As String\n\n IPathAndName_PathAndName = PathAndName(ReportSheet)\n\nEnd Function\n\n\nPrivate Sub Class_Initialize()\n\n Main.FailIfMeIsNotPredeclaredId Me, WorkingTime\n\nEnd Sub\n\n\nPublic Function Setup(ByVal SavePath As String, ByVal Months As MonthNumbers) As WorkingTime\n\n Set s.Months = Months\n s.SavePath = SavePath\n Set Setup = Me\n\nEnd Function\n\n\nPrivate Function PathAndName(ByRef ReportSheet As Excel.Worksheet) As String\n\n Dim myWorkbook As Excel.Workbook\n Set myWorkbook = ReportSheet.Parent\n\n Dim myPresetSheet As Excel.Worksheet\n Set myPresetSheet = myWorkbook.Sheets.[_Default](1)\n\n Dim myActiveSheet As Excel.Worksheet\n Set myActiveSheet = myWorkbook.ActiveSheet\n\n Dim myYear As String\n myYear = myPresetSheet.Cells.Item(2, 11)\n\n Dim myShortName As String\n myShortName = myPresetSheet.Cells.Item(3, 11).Value\n\n PathAndName = _\n s.SavePath _\n & \"\\\" _\n & Mid$(myYear, 3, 2) _\n & \"-\" _\n & s.Months.Number(myActiveSheet.Name) _\n & \"_\" _\n & WORKING_TIME _\n & \"_\" _\n & myShortName _\n & \".pdf\"\n\nEnd Function\n</code></pre>\n\n<p><strong>Class Interface IPathAndName</strong></p>\n\n<pre><code>Option Explicit\n\n'@Ignore FunctionReturnValueNotUsed\nPublic Function PathAndName(ByVal ReportSheet As Excel.Worksheet) As String\nEnd Function\n</code></pre>\n\n<p>[Sighs.... I've just realised that the interface naming is a bit too similar to the Implementation method, but this is a detail that can be resolved later.]</p>\n\n<p>By rights, all of the above classes should contain a Class_Initialize method which detects correct use of the class (i.e. prevents the use of New to create classes if this is not required etc) but this code is rather complicated and hasn't been presented above.</p>\n\n<p>In the final module the Method to save the spreadsheet as a pdf contains code that could be relocated elsewhere, e.g. the initialising of the Months object and the reports dictionary. I've put it in the SaveAsPdf method on this occasion to avoid having yet another method.</p>\n\n<p><strong>Module Main</strong></p>\n\n<pre><code>Option Explicit\n\nPrivate Const STAFF_EMAIL_ADDRESS = \"StaffEmail@Company.org\"\n\nPrivate Type State\n\n Reports As Scripting.Dictionary\n Months As MonthNumbers\n\nEnd Type\n\nPrivate s As State\n\n\nPublic Sub SaveAsPdf(ByRef ReportSheet As Excel.Worksheet)\n\n If s.Months Is Nothing Then InitialiseMonths\n If s.Reports Is Nothing Then InitialiseReports\n\n ' This use of an interface is a bit contrived as\n ' s.Reports.Item(mySheet.Name).PathAndName\n ' would work just as wel ableit without intellisense\n ' on the s.Reports.Item(mySheet.Name)\n Dim myReport As IPathAndName\n Set myReport = s.Reports.Item(ReportSheet.Name)\n\n Dim myPathandName As String\n myPathandName = myReport.PathAndName(ReportSheet)\n\n ReportSheet.ExportAsFixedFormat _\n Type:=xlTypePDF, _\n fileName:=myPathandName, _\n Quality:=xlQualityStandard, _\n IncludeDocProperties:=True, _\n IgnorePrintAreas:=False, _\n OpenAfterPublish:=False\n\n Dim myShortName As String\n myShortName = Replace(Right$(myPathandName, InStrRev(myPathandName, \"\\\") - 1), \".pdf\", vbNullString)\n\n SendAsMail myPathandName, STAFF_EMAIL_ADDRESS, myShortName\n\nEnd Sub\n\n\nPrivate Sub SendAsMail(ByVal PathAndName As String, ByVal Receiver As String, ByVal Subject As String)\n Dim outlook As Object\n Set outlook = CreateObject(\"Outlook.Application\")\n\n Dim message As Object\n Set message = outlook.CreateItem(0)\n\n With message\n .Display\n .To = Receiver\n .CC = vbNullString\n .Subject = Subject\n .Attachments.Add PathAndName\n End With\nEnd Sub\n\nPrivate Sub InitialiseMonths()\n\n Set s.Months = _\n MonthNumbers.Make _\n ( _\n Split(\"01,02,03,04,05,06,07,08,09,10,11,12\", \",\"), _\n Split(\" Januar,Februar,März,April,Mai, Juni,Juli, August,September,Oktober,November,Dezember\", \",\") _\n )\n\n ' If Month \"0\"1 happens to be April then\n ' Set s.Months = _\n ' MonthNumbers.Make _\n ' ( _\n ' Split(\"10,11,12,01,02,03,04,05,06,07,08,09\", \",\"), _\n ' Split(\" Januar,Februar,März,April,Mai, Juni,Juli, August,September,Oktober,November,Dezember\", \",\") _\n ' )\n\nEnd Sub\n\nPrivate Sub InitialiseReports()\n\n 'Requires a reference to \"Windows Script Host Object Model\"\n Dim myShell As WshShell: Set myShell = New WshShell\n ' Seperate variable for debugging convenience\n\n\n Dim myPath As String\n myPath = myShell.SpecialFolders.Item(\"MyDocuments\")\n\n s.Reports.Add \"Voreinstellungen\", PreSetting.Setup(myPath, s.Months)\n s.Reports.Add \"Urlaubsantrag\", VacationApplication.Setup(myPath, s.Months)\n s.Reports.Add \"Spesen\", Expenses.Setup(myPath, s.Months)\n s.Reports.Add \"Arbeitszeit\", WorkingTime.Setup(myPath, s.Months)\n\nEnd Sub\n</code></pre>\n\n<p>The code above is clean in that it compiles and shows no Inspection results from RubberDuck. However, as I don't have examples of the spreadsheets I haven't run the code so apologies in advance if there are any logic errors.</p>\n\n<p>I hope folks fine the above useful. I've certainly had a very interesting couple of years reading the RubberDuck blogs which have allowed me to progress from a muddle of poorly constructed subs and functions to start to being able to organise my (hobbyist) code a little better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T02:54:22.167",
"Id": "459192",
"Score": "0",
"body": "There are some good ideas in here, but IMO this is over-abstracted: if `IPathAndName` implementations were just different instances of the same class, then there wouldn't be any code duplication. The abstractions are good, just not at a level that feels right all the time. Note that having two parallel arrays is usually considered a code smell: needs a better data structure (like a keyed collection?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T03:04:26.163",
"Id": "459193",
"Score": "0",
"body": "I need to mention that this isn't how I showed factory methods though. `Self` is a `Property Get` that takes no parameters and does nothing more than return a reference to the current instance: turning that into a side-effecting `Function` that mutates the current instance and then returns itself, makes a rather mind-bending runtime context to keep in mind (\"which instance am I mutating?\") when reading that code... and then *because of the side-effects*, you had to add code to prevent mutating the default instance - and it shouldn't be needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T06:47:39.717",
"Id": "459199",
"Score": "0",
"body": "@MathieuGuindon. You are right to observe that things are a bit over extracted. I was just trying to demonstrate an alternative approach which recognised that potentially four different activities had been crammed into a single function. I used dual arrays as input because VBA doesn't allow initialisation at the time of creation. Likewise, code to differentiate between the base instance and other instances should be a must once you have set the PredecalredId of a Class to True. because VBA won't do it for you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T00:59:43.173",
"Id": "234568",
"ParentId": "234522",
"Score": "3"
}
},
{
"body": "<h2>FetchMonthNumber</h2>\n\n<p><code>Get</code> is a standard across most programming languages, where as, <code>Fetch</code> is a standard when playing with a dog. But neither <code>GetMonthNumber</code> or <code>FetchMonthNumber</code> provide any context to the return value of the function. </p>\n\n<blockquote>\n<pre><code> FetchMonthNumber = \"\"\n</code></pre>\n</blockquote>\n\n<p>The code above is unnecessary. <code>FetchMonthNumber</code> is typed as a string and has a default value of <code>\"\"</code>.</p>\n\n<blockquote>\n<pre><code>If monthName = January Then\n FetchMonthNumber = \"01\"\n Exit Function\nEnd If\nIf monthName = February Then\n FetchMonthNumber = \"02\"\n Exit Function\nEnd If\nIf monthName = March Then\n FetchMonthNumber = \"03\"\n Exit Function\nEnd If\n</code></pre>\n</blockquote>\n\n<p>Multiple <code>If</code> statements, in which, only one statement will trigger should be combined.</p>\n\n<pre><code>If MonthName = January Then\n FetchMonthNumber = \"01\"\nElseIf MonthName = February Then\n FetchMonthNumber = \"02\"\nElseIf MonthName = March Then\n FetchMonthNumber = \"03\"\n</code></pre>\n\n<p>Consider using a <code>Select Case</code> when every case is triggered based on different variations of a value</p>\n\n<pre><code>Select Case MonthName\nCase January\n FetchMonthNumber = \"01\"\nCase February\n FetchMonthNumber = \"02\"\n Exit Function\nCase March\n FetchMonthNumber = \"03\"\n</code></pre>\n\n<p>Returning the Month number as long and using <code>Format(MonthNumber,\"##\")</code> will make it easier to change the formats.</p>\n\n<h2>SaveAsPdf()</h2>\n\n<blockquote>\n<pre><code>Set presetSheet = ActiveWorkbook.Sheets(1)\n</code></pre>\n</blockquote>\n\n<p><code>ActiveWorkbook</code> is best used in special situations when working with multiple workbooks. Using <code>ThisWorkbook</code> ensures that the code will always reference the workbook that contains the code.</p>\n\n<p><code>Sheets(1)</code> assumes that the project setup will never change. Referring to worksheets by their code names will make the code more robust. Renaming the worksheets will make the code easier to read.</p>\n\n<blockquote>\n<pre><code>Dim shell As Object\nSet shell = CreateObject(\"WScript.Shell\")\n\nfileName = shell.SpecialFolders(\"MyDocuments\") + \"\\\" + shortName + \".pdf\"\n</code></pre>\n</blockquote>\n\n<p>Not a best practice but I wouldn't both with the <code>shell</code> helper variable. You are not reusing it or testing where or not it is instantiated.</p>\n\n<pre><code>fileName = CreateObject(\"WScript.Shell\").SpecialFolders(\"MyDocuments\") + \"\\\" + shortName + \".pdf\"\n</code></pre>\n\n<p>Alternately, you could use <code>Environ</code> to return the user directory.</p>\n\n<pre><code>fileName = Environ(\"USERPROFILE\") & \"Documents\\\" + shortName + \".pdf\"\n</code></pre>\n\n<p>But why force users to save their files in a specific directory. Consider setting the <code>InitialFilename</code> of the <code>Application.FileDialog(msoFileDialogSaveAs)</code> or <code>Application.GetSaveAsFilename()</code> and allowing the user to specify the file location. </p>\n\n<p>Better yet, I would use the <code>Application.FileDialog(msoFileDialogFolderPicker)</code> to save the file location on the presets worksheet. I would then create a root directory ( e.g. Company PDFs) and subdirectories to file the pdfs by year.</p>\n\n<p>Considering that the files are to be sent by emails and that they are basically time-sensitive signed documents, it may just be best to dump them in the <code>Environ(\"Temp\")</code> where they will be cleaned up during system maintenance. </p>\n\n<h2>ComposeFileName</h2>\n\n<blockquote>\n<pre><code>Dim year As String\n</code></pre>\n</blockquote>\n\n<p>The code above changes all instances of <code>Year</code> to <code>year</code>. Because, for some odd reason, the VBA will rename variables, subs or functions that share a name to match the case of the last declaration of that name. I prefer to use <code>Of</code> to suffix all my date variables (e.g. YearOf, MonthOf, WeekOf, DateOf ...)/</p>\n\n<p>Passing the worksheet as a parameter to <code>ComposeFileName</code> will make the code more versatile. For instance, you decided to add a listbox to the preset sheet send multiple emails based on its selections. Currently you would have to rewrite this subroutine but passing in the worksheet opens up a lot of possibilities.</p>\n\n<blockquote>\n<pre><code>If sheetName = PreSetting Then\n ComposeFileName = Year + \"_\" + sheetName + \"_\" + shortName\n Exit Function\nEnd If\nIf sheetName = Expenses Then\n ComposeFileName = Mid(Year, 3) + \"-\" + FetchMonthNumber(ActiveSheet.Cells(4, 3).Value) + \"_\" + ExpensesName + \"_\" + shortName\n Exit Function\nEnd If\nIf sheetName = VacationApplication Then\n ComposeFileName = Year + \"_\" + VacationApplicationName + \"_(\" + Format(Date) + \")_\" + shortName\n Exit Function\nEnd If\n</code></pre>\n</blockquote>\n\n<p>Here is another instance where using a <code>Select Case</code> statement is easier to read and modify than multiple <code>If</code> statements. </p>\n\n<p>Remove the <code>Exit Function</code> clauses. Not only do they clutter up the screen but they make it harder to modify the code.</p>\n\n<blockquote>\n<pre><code>ComposeFileName = Year + \"_\" + VacationApplicationName + \"_(\" + Format(Date) + \")_\" + shortName\n</code></pre>\n</blockquote>\n\n<p>The default format for <code>Format(Date)</code> is <code>MM/DD/YYYY</code>. Forward slashes(<code>/</code>) are not permitted in filenames. Here are some valid replacement options: <code>MMDDYYYY</code>, <code>MM.DD.YYYY</code> or <code>MM-DD-YYYY</code>.</p>\n\n<p>As IvenBach mentioned, using named ranges and worksheet codenames will make your code easier to read and modify. </p>\n\n<p>Use <code>+</code> to concatenate strings can lead to type mismatch errors and unexpected results. Use <code>&</code> instead.</p>\n\n<p><a href=\"https://i.stack.imgur.com/QBRwo.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QBRwo.png\" alt=\"enter image description here\"></a></p>\n\n<h2>Store Dates as Numbers</h2>\n\n<p>I'm not sure of the project setup but is in generally better to store dates as numbers and format their values as needed. Consider that the preset tab has a cell for the Year and one for the Month name. It may make more sense to use have the date in one cell and have to other cell reference the first. The number format for the Year would be \"YYYY\" and for the Month would be \"[$-de-DE] MMMM\".<br>\nPrefixing the number format with <code>[$-de-DE]</code> tells Excel to display the value in German. The codes on <a href=\"http://www.codedigest.com/CodeDigest/207-Get-All-Language-Country-Code-List-for-all-Culture-in-C---ASP-Net.aspx\" rel=\"noreferrer\">this page: Get All Language-Country Code List for all Culture in C#, ASP.Net</a> can be used with some modifications. The actual CultureInfo code is <code>de-DE</code>. <code>[$de-DE]</code> will prefix the display value with <code>de</code> to specify the German format. Adding a dash <code>[$-de-DE]</code> will remove the prefix. These number formats can also be used by the <code>WorksheetFunction.Text()</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/y03sN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/y03sN.png\" alt=\"enter image description here\"></a></p>\n\n<h2>Refactored Code</h2>\n\n<p>Here is a rough rewrite using most of my suggestions:</p>\n\n<pre><code>Sub SaveAsPdf()\n Dim TargetWorksheet As Worksheet\n Set TargetWorksheet = ActiveSheet\n\n Dim shortName As String\n shortName = GetPDFFileName(TargetWorksheet)\n\n Dim fileName As String\n fileName = Environ(\"USERPROFILE\") & \"Documents\\\" & shortName & \".pdf\"\n\n TargetWorksheet.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fileName, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False\n\n SendAsMail fileName, StaffEmailAdress, shortName\n\nEnd Sub\n\nPrivate Function GetPDFFileName(ByVal TargetWorksheet As Worksheet) As String\n\n Dim YearOf As Long\n YearOf = TargetWorksheet.Range(\"Year\").Value\n\n Dim shortName As String\n shortName = presetSheet.Cells(3, 11).Value\n\n Dim Result As String\n\n Select Case TargetWorksheet.Name\n Case wsPreSetting.Name\n\n Result = YearOf & \"_\" & sheetName & \"_\" & shortName\n\n Case wsExpenses.Name\n\n Dim MonthOf As Long\n MonthOf = GermanMonthToNumber(TargetWorksheet.Range(\"Month\").Value)\n Result = Mid(Year, 3) & \"-\" & Format(MonthOf, \"##\") & \"_\" & ExpensesName & \"_\" & shortName\n\n Case wsVacationApplication.Name\n\n GetPDFFileName = Year & \"_\" & VacationApplicationName & \"_(\" & Format(Date, \"MMDDYY\") & \")_\" & shortName\n\n End Select\n\n GetPDFFileName = Result\n\nEnd Function\n\nPrivate Function GermanMonthToNumber(monthName As String) As Long\n Select Case monthName\n Case January\n GermanMonthToNumber = 1\n Case February\n GermanMonthToNumber = 2\n Case March\n GermanMonthToNumber = 3\n Case April\n GermanMonthToNumber = 4\n Case May\n GermanMonthToNumber = 5\n Case June\n GermanMonthToNumber = 6\n Case July\n GermanMonthToNumber = 7\n Case August\n GermanMonthToNumber = 8\n Case September\n GermanMonthToNumber = 9\n Case October\n GermanMonthToNumber = 10\n Case November\n GermanMonthToNumber = 11\n Case December\n GermanMonthToNumber = 12\n End Select\n\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T18:43:12.597",
"Id": "459086",
"Score": "0",
"body": "When using `Application.WorksheetFunction.Text(2,\"[$-en-US] mmmm\")` I always get January as a result. Trying any other region language results in the region appropriate string for January, irregardless of the numeric argument provided. Testing as a function on a worksheet produces the same result. Am I missing something apparent to get this working properly? :+1: as I didn't know region codes could be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T19:07:29.167",
"Id": "459087",
"Score": "1",
"body": "@IvenBach `WorksheetFunction.Text()` is expecting a date because we're passing `mmm` as a format option. 2 is being evaluated as Day 2 of the Excel calendar. The result of `WorksheetFunction.Text(2,\"mm/dd/yyyy\")` is `#01/02/1900#`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T01:05:48.670",
"Id": "459099",
"Score": "0",
"body": "Excellent explanation. Useful tips."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T14:14:34.730",
"Id": "234633",
"ParentId": "234522",
"Score": "6"
}
},
{
"body": "<p>Your original code is simple and straightforward, easy to follow. There are a couple things that might trip you up when maintaining the code and that I would suggest could change.</p>\n\n<ul>\n<li>You have a solid list of <code>Private Const</code> declarations at the top of your code. Abstracting the strings into consts is very good practice, but eventually you'll find that it's even better to work around the need for as many of the consts as possible. In this regard, I'll repeat the suggestion from IvenBach that you <a href=\"https://riptutorial.com/excel-vba/example/11272/worksheet--name---index-or--codename\" rel=\"nofollow noreferrer\">create worksheet code names</a> in the IDE. </li>\n</ul>\n\n<p>So for my example below, you could rename the worksheets in the IDE manually by editing the Worksheet Properties (Name) field, or by running this short sub (after modifying it as needed):</p>\n\n<pre><code>Private Sub RunOnceToChangeCodeNames()\n '--- you can delete this sub after you run it\n ThisWorkbook.VBProject.VBComponents(\"Voreinstellungen\").Name = \"PresetsWS\"\n ThisWorkbook.VBProject.VBComponents(\"Urlaubsantrag\").Name = \"VacationWS\"\n ThisWorkbook.VBProject.VBComponents(\"Spesen\").Name = \"ExpensesWS\"\nEnd Sub\n</code></pre>\n\n<p>Now you can directly refer to any of these worksheets by its code name directly, as in</p>\n\n<pre><code>Debug.Print PresetsWS.Name\n</code></pre>\n\n<ul>\n<li><p>I'll urge you to be a bit clearer in your variable naming. As an example, you use <code>shortName</code> for the part of the file name in a folder. But I could also interpret <code>shortName</code> to mean it's the shortened name of a person as in \"Wolf\" for \"Wolfgang\". So in my example you'll see <code>shortName</code> changed to <code>shortFilename</code> and other similar changes.</p></li>\n<li><p>For the refactoring of the <code>ComposeFileName</code> function, there are several points.</p>\n\n<ol>\n<li>This is the only code that uses three of the <code>Consts</code> defined above. So I reccommend restricting the scope of these to this function only.</li>\n<li>Change the input parameter to be the currently active worksheet, and pass it as a reference (<code>ByRef</code>). Passing the <code>PresetsWS</code> is meaningless because it never changes, whereas the currently active worksheet is significant.</li>\n<li>Change the several <code>If</code> statements to a <code>Select Case</code> block. The reason is you'll save from using multiple <code>Exit Function</code> points. Whether or not that's a good or bad thing is debatable, but I believe in this situation it makes the code cleaner.</li>\n<li>Notice also that I've pulled the <code>MonthNumber</code> call out of the statement building the string. This is so I can use <code>Format</code> on the month number to create exactly what I want. I could have built this into the <code>MonthNumber</code> function, but that would make it less flexible if I wanted to use it in the future.</li>\n</ol></li>\n</ul>\n\n<p>So here's the <code>ComposeShortFilname</code> function:</p>\n\n<pre><code>Private Function ComposeShortFilname(ByRef thisWS As Worksheet) As String\n Private Const VacationApplicationName As String = \"Urlaub_Gleittag_Antrag\"\n Private Const ExpensesName As String = \"Reisekosten\"\n Private Const WorkingTime As String = \"Arbeitszeit\"\n\n Dim year As String\n year = PresetsWS.Cells(2, 11).Value\n\n Dim shortName As String\n shortName = PresetsWS.Cells(3, 11).Value\n\n Dim month As Long\n Select Case thisWS.CodeName\n Case PresetsWS.CodeName\n ComposeFileName = year & \"_\" & thisWS.CodeName & \"_\" & shortName\n\n Case ExpensesWS.CodeName\n month = MonthNumber(thisWS.Cells(4, 3).Value)\n ComposeFileName = Mid(year, 3) & \"-\" & _\n Format(month, \"0#\") & _\n \"_\" & ExpensesName & \"_\" & shortName\n\n Case VacationWS.CodeName\n ComposeFileName = year & \"_\" & VacationApplicationName & _\n \"_(\" & Format(Date, \"mm-dd-yyyy\") & \")_\" & shortName\n\n Case Else\n month = MonthNumber(thisWS.Name)\n ComposeFileName = Mid$(year, 3) & \"-\" & _\n Format(month, \"0#\") & \"_\" & _\n WorkingTime & \"_\" & shortName\n End Select\nEnd Function\n</code></pre>\n\n<ul>\n<li>I agree with others that your <code>FetchMonthNumber</code> routine is ripe for refactoring. However, I believe it can be greatly simplified using Siddarth's <a href=\"https://stackoverflow.com/a/11895352/4717755\">valuable answer here</a>. </li>\n</ul>\n\n<p>So the routine collapses to</p>\n\n<pre><code>Private Function MonthNumber(ByVal monthName As String) As Long\n MonthNumber = Month(DateValue(\"01 \" & monthName & \" 2019\"))\nEnd Function\n</code></pre>\n\n<p>Notice that the function relies on the application setting for the country code. As your settings should all be using German, then the month name should be interpreted correctly. Also, I believe that the \"Fetch\" part of the function name is redundant and can be shortened to simply <code>MonthNumber</code>. (Note that the year in the code statement above really doesn't matter at all.)</p>\n\n<ul>\n<li>Lastly, concatenate your strings with an ampersand \"&\" and don't use a plus sign \"+\". For <a href=\"https://stackoverflow.com/a/1727709/4717755\">reasons</a>.</li>\n</ul>\n\n<p>So here is the whole module is a single block:</p>\n\n<pre><code>Option Explicit\n\nPrivate Sub RunOnceToChangeCodeNames()\n '--- you can delete this sub after you run it\n ThisWorkbook.VBProject.VBComponents(\"Voreinstellungen\").Name = \"PresetsWS\"\n ThisWorkbook.VBProject.VBComponents(\"Urlaubsantrag\").Name = \"VacationWS\"\n ThisWorkbook.VBProject.VBComponents(\"Spesen\").Name = \"ExpensesWS\"\nEnd Sub\n\nSub SaveAsPdf()\n Private Const StaffEmailAdress = \"StaffEmail@Company.org\"\n Dim shortFilename As String\n shortFilename = ComposeShortFilename(ActiveSheet)\n\n Dim shell As Object\n Set shell = CreateObject(\"WScript.Shell\")\n\n Dim fileName As String\n fileName = shell.SpecialFolders(\"MyDocuments\") & \"\\\" & shortName & \".pdf\"\n\n ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _\n fileName:=fileName, _\n Quality:=xlQualityStandard, _\n IncludeDocProperties:=True, _\n IgnorePrintAreas:=False, _\n OpenAfterPublish:=False\n\n SendAsMail fileName, StaffEmailAdress, shortFilename\nEnd Sub\n\nPrivate Sub SendAsMail(fileName As String, receiver As String, subject As String)\n Dim outlook As Object\n Set outlook = CreateObject(\"Outlook.Application\")\n\n Dim message As Object\n Set message = outlook.CreateItem(0)\n\n With message\n .Display\n .To = receiver\n .CC = \"\"\n .subject = subject\n .Attachments.Add fileName\n End With\nEnd Sub\n\nPrivate Function ComposeShortFilname(ByRef thisWS As Worksheet) As String\n Private Const VacationApplicationName As String = \"Urlaub_Gleittag_Antrag\"\n Private Const ExpensesName As String = \"Reisekosten\"\n Private Const WorkingTime As String = \"Arbeitszeit\"\n\n Dim year As String\n year = PresetsWS.Cells(2, 11).Value\n\n Dim shortName As String\n shortName = PresetsWS.Cells(3, 11).Value\n\n Dim month As Long\n Select Case thisWS.CodeName\n Case PresetsWS.CodeName\n ComposeFileName = year & \"_\" & thisWS.CodeName & \"_\" & shortName\n\n Case ExpensesWS.CodeName\n month = MonthNumber(thisWS.Cells(4, 3).Value)\n ComposeFileName = Mid(year, 3) & \"-\" & _\n Format(month, \"0#\") & _\n \"_\" & ExpensesName & \"_\" & shortName\n\n Case VacationWS.CodeName\n ComposeFileName = year & \"_\" & VacationApplicationName & _\n \"_(\" & Format(Date, \"mm-dd-yyyy\") & \")_\" & shortName\n\n Case Else\n month = MonthNumber(thisWS.Name)\n ComposeFileName = Mid$(year, 3) & \"-\" & _\n Format(month, \"0#\") & \"_\" & _\n WorkingTime & \"_\" & shortName\n End Select\nEnd Function\n\nPrivate Function MonthNumber(ByVal monthName As String) As Long\n MonthNumber = month(DateValue(\"01 \" & monthName & \" 2019\"))\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-01T00:55:31.990",
"Id": "234889",
"ParentId": "234522",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234553",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T08:00:03.100",
"Id": "234522",
"Score": "8",
"Tags": [
"beginner",
"vba"
],
"Title": "Saving worksheets as pdf and sending per mail"
}
|
234522
|
<p>I think we all know the game of Scrabble and how popular it is as a simple programming challenge. Here's my attempt at computing a Scrabble score for a given word done in Go.</p>
<p>I must admit, I'm fairly new to Go (been learning it for a week or so). Having said that, I'd greatly appreciate all sorts of tips for improving not only the solution itself but also the style to be more Go-ish.</p>
<p>I've used <code>golint</code> and <code>gofmt</code> on this, but with <code>gofmt</code> I'm not sure I use it correctly, as it simply prints out the code to <code>stdout</code>.</p>
<p>There's a simple test suit that comes along with the solution.</p>
<pre><code>// Package scrabble deals with proper word score counting
package scrabble
import "strings"
// countScore returns a score map per given word
func countScore() map[rune]int {
var scoreMap = map[string]int{
"aeioulnrst": 1,
"dg": 2,
"bcmp": 3,
"fhvwy": 4,
"k": 5,
"jx": 8,
"qz": 10,
}
var actualScore = make(map[rune]int)
for letters, score := range scoreMap {
for _, letter := range letters {
actualScore[letter] = score
}
}
return actualScore
}
// Score count Scrabble score
func Score(word string) (score int) {
for _, char := range strings.ToLower(word) {
score += countScore()[char]
}
return
}
</code></pre>
<p>As for the solution, I've noticed it's kinda slow. What's more, it takes over <code>600 allocs/op</code>. That's a lot for such a simple task. Why is that?</p>
<pre><code>package scrabble
import "testing"
func TestScore(t *testing.T) {
for _, test := range scrabbleScoreTests {
if actual := Score(test.input); actual != test.expected {
t.Errorf("Score(%q) expected %d, Actual %d", test.input, test.expected, actual)
}
}
}
func BenchmarkScore(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, test := range scrabbleScoreTests {
Score(test.input)
}
}
}
</code></pre>
<p>Test cases:</p>
<pre><code>package scrabble
type scrabbleTest struct {
input string
expected int
}
var scrabbleScoreTests = []scrabbleTest{
{"a", 1}, // lowercase letter
{"A", 1}, // uppercase letter
{"f", 4}, // valuable letter
{"at", 2}, // short word
{"zoo", 12}, // short, valuable word
{"street", 6}, // medium word
{"quirky", 22}, // medium, valuable word
{"OxyphenButazone", 41}, // long, mixed-case word
{"pinata", 8}, // english-like word
{"", 0}, // empty input
{"abcdefghijklmnopqrstuvwxyz", 87}, // entire alphabet available
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T15:14:42.903",
"Id": "458702",
"Score": "1",
"body": "as long as you only need blackbox testing, your tests, and their fixtures, should belong to a package named `scrabble_test`"
}
] |
[
{
"body": "<p>You are almost good. The reason of being slow and allocates a lot is that you create the map for score everytime <code>Score()</code> is called - it is a huge waste. The map never change, and hence only need to be created once at startup.</p>\n\n<p>You can add a global variable <code>var scoreMap = countScore()</code> and re-use the variable in the scope: <code>score += scoreMap[char]</code>.</p>\n\n<p>Further optimization is possible, but I don't think it is needed now.</p>\n\n<p>As for <code>gofmt</code>, it is better to run it as a plugin for your editor - you can search for how to do that; most popular editors have a plugin for Go. If you wish to run it manually, <code>gofmt</code> has a <code>-w</code> flag:</p>\n\n<blockquote>\n <p>-w write result to (source) file instead of stdout</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T12:21:25.720",
"Id": "234530",
"ParentId": "234524",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>I'd greatly appreciate all sorts of tips for improving not only the\n solution itself but also the style to be more Go-ish.</p>\n</blockquote>\n\n<hr>\n\n<p>For a real-world code review, code should be correct, maintainable, reasonably efficient, and, most importantly, readable.</p>\n\n<p>Writing code is a process of stepwise refinement.</p>\n\n<hr>\n\n<p>Go was designed for simplicity, readability, and performance.</p>\n\n<hr>\n\n<p>I ran your benchmark on your complicated code:</p>\n\n<pre><code>$ go version\ngo version devel +4d5bb9c609 Fri Dec 20 23:07:52 2019 +0000 linux/amd64\n$\n\n$ go test *.go -bench=. -benchmem -run=!\nBenchmarkScore-4 9438 126800 ns/op 67275 B/op 512 allocs/op\n</code></pre>\n\n<p>It seems very slow.</p>\n\n<hr>\n\n<p>I ran your benchmark on <a href=\"https://codereview.stackexchange.com/a/234530/13970\">leaf bebop's complicated code</a>:</p>\n\n<pre><code>$ go test *.go -bench=. -benchmem -run=!\nBenchmarkScore-4 1263572 936 ns/op 16 B/op 2 allocs/op\n</code></pre>\n\n<p>It is much better, but still slow.</p>\n\n<hr>\n\n<p>I ran your benchmark on my simpler, \"Go-ish\" code:</p>\n\n<pre><code>$ go test *.go -bench=. -benchmem -run=!\nBenchmarkScore-4 16844323 69.5 ns/op 0 B/op 0 allocs/op\n\n// Score returns the sum of the Scrabble tile points\n// for the letters in a word.\nfunc Score(word string) int {\n var score int\n for i := 0; i < len(word); i++ {\n score += int(points[word[i]])\n }\n return score\n}\n\nvar points = [256]byte{\n 'A': 1, 'a': 1,\n ...\n 'Z': 10, 'z': 10,\n}\n</code></pre>\n\n<p>My code is around 1,819 times faster than your code and it makes no allocations.</p>\n\n<p>My code is around 13 times faster than leaf bebop's code and it makes no allocations.</p>\n\n<hr>\n\n<p>An array is a simple, fast, random access data structure. The <code>points</code> array is constructed once at compile time. </p>\n\n<p><code>scrabble.go</code>:</p>\n\n<pre><code>/*\nPackage scrabble deals with proper word score counting\n\nScrabble Rules | Official Word Game Rules | Board Games\nhttps://scrabble.hasbro.com/en-us/rules\n*/\n\npackage scrabble\n\n// Score returns the sum of the Scrabble tile points\n// for the letters in a word.\nfunc Score(word string) int {\n var score int\n for i := 0; i < len(word); i++ {\n score += int(points[word[i]])\n }\n return score\n}\n\nvar points = [256]byte{\n ' ': 0, // blank\n 'A': 1, 'a': 1,\n 'E': 1, 'e': 1,\n 'I': 1, 'i': 1,\n 'O': 1, 'o': 1,\n 'U': 1, 'u': 1,\n 'L': 1, 'l': 1,\n 'N': 1, 'n': 1,\n 'R': 1, 'r': 1,\n 'S': 1, 's': 1,\n 'T': 1, 't': 1,\n 'D': 2, 'd': 2,\n 'G': 2, 'g': 2,\n 'B': 3, 'b': 3,\n 'C': 3, 'c': 3,\n 'M': 3, 'm': 3,\n 'P': 3, 'p': 3,\n 'F': 4, 'f': 4,\n 'H': 4, 'h': 4,\n 'V': 4, 'v': 4,\n 'W': 4, 'w': 4,\n 'Y': 4, 'y': 4,\n 'K': 5, 'k': 5,\n 'J': 8, 'j': 8,\n 'X': 8, 'x': 8,\n 'Q': 10, 'q': 10,\n 'Z': 10, 'z': 10,\n}\n</code></pre>\n\n<hr>\n\n<hr>\n\n<blockquote>\n <p>Program testing can be a very effective way to show the presence of\n bugs, but it is hopelessly inadequate for showing their absence.</p>\n \n <p>A convincing demonstration of correctness being impossible as long as\n the mechanism is regarded as a black box, our only hope lies in not\n regarding the mechanism as a black box.</p>\n \n <p><a href=\"https://en.wikipedia.org/wiki/Edsger_W._Dijkstra\" rel=\"nofollow noreferrer\">Edsger W. Dijkstra</a></p>\n</blockquote>\n\n<hr>\n\n<p>Your tests don't test for control characters, punctuation, numbers, and non-ASCII characters.</p>\n\n<p>Your complex code and data structures look like a black box to your tests.</p>\n\n<hr>\n\n<p>Locate a definitive description of the Scrabble tile points and scoring system:</p>\n\n<p><a href=\"https://scrabble.hasbro.com/en-us/rules\" rel=\"nofollow noreferrer\">Scrabble Rules | Official Word Game Rules | Board Games</a></p>\n\n<p>Encode the tile points system in readable, array form. Like the definition, uppercase and lowercase letters and their points are on the same line. The lines are in the same order as the definition. Carefully match the array to the definition and the definition to the array, left-to-right then right-to-left and top-to-bottom then bottom-to-top. The Go compiler will check that the keys are unique.</p>\n\n<p>Consider some automated tests, which can also serve as regression tests.</p>\n\n<p>For the points array, compute sum and count verification totals, listing the elements in the same order as the definition, matching array to definition and definition to array, right-to-left, and left-to right.</p>\n\n<p>We are now be able to conclude, if not prove, that the points array is correct.</p>\n\n<p>The Score function, by design is simple and readable.</p>\n\n<pre><code>// Score returns the sum of the Scrabble tile points\n// for the letters in a word.\nfunc Score(word string) int {\n var score int\n for i := 0; i < len(word); i++ {\n score += int(points[word[i]])\n }\n return score\n}\n</code></pre>\n\n<p>For a comprehensive Score function test, use the definition of points encoding, with the tests in the same form as the definition for easy comparison.</p>\n\n<p>Add the test written while developing the algorithm for the Score function. It includes special, unusual, and error cases.</p>\n\n<hr>\n\n<p><code>peterso_test.go</code>:</p>\n\n<pre><code>package scrabble\n\nimport (\n \"strings\"\n \"testing\"\n)\n\n/*\nScrabble Rules | Official Word Game Rules | Board Games\nhttps://scrabble.hasbro.com/en-us/rules\n (0 point)-blank\n (1 point)-A, E, I, O, U, L, N, S, T, R\n (2 points)-D, G\n (3 points)-B, C, M, P\n (4 points)-F, H, V, W, Y\n (5 points)-K\n (8 points)- J, X\n (10 points)-Q, Z\n*/\n\nfunc TestScores(t *testing.T) {\n var (\n sum = 2 * (0*1 + 1*10 + 2*2 + 3*4 + 4*5 + 5*1 + 8*2 + 10*2)\n count = int(('z' - 'a' + 1) + ('Z' - 'A' + 1))\n )\n\n as, ac := 0, 0 // all\n us, uc := 0, 0 // upper\n ls, lc := 0, 0 // lower\n for i := 0; i < len(points); i++ {\n score := int(points[i])\n if score != 0 {\n as += score\n ac++\n if 'A' <= i && i <= 'Z' {\n us += score\n uc++\n }\n if 'a' <= i && i <= 'z' {\n ls += score\n lc++\n }\n }\n }\n if as != sum {\n t.Errorf(\"all sum: got %d; want %d\", as, sum)\n }\n if ac != count {\n t.Errorf(\"all count: got %d; want %d\", ac, count)\n }\n if 2*ls != sum {\n t.Errorf(\"lower sum: got %d; want %d\", 2*ls, sum)\n }\n if 2*lc != count {\n t.Errorf(\"lower count: got %d; want %d\", 2*lc, count)\n }\n if 2*us != sum {\n t.Errorf(\"upper sum: got %d; want %d\", 2*us, sum)\n }\n if 2*uc != count {\n t.Errorf(\"upper count: got %d; want %d\", 2*uc, count)\n }\n}\n\nfunc TestScore2(t *testing.T) {\n var tests1 = []struct {\n word string\n points int\n }{\n {\" \", 0}, // (0 point)-blank\n {\"AEIOULNSTR\", 1}, // (1 point)-A, E, I, O, U, L, N, S, T, R\n {\"DG\", 2}, // (2 points)-D, G\n {\"BCMP\", 3}, // (3 points)-B, C, M, P\n {\"FHVWY\", 4}, // (4 points)-F, H, V, W, Y\n {\"K\", 5}, // (5 points)-K\n {\"JX\", 8}, // (8 points)- J, X\n {\"QZ\", 10}, // (10 points)-Q, Z\n }\n for _, tt := range tests1 {\n word := tt.word\n word += strings.ToUpper(tt.word)\n word += strings.ToLower(tt.word)\n got := Score(word)\n score := 3 * (len(tt.word) * tt.points)\n if got != score {\n t.Errorf(\"Score(%s) : got %d; want %d\", word, got, score)\n }\n }\n\n var tests2 = []struct {\n word string\n score int\n }{\n {\"\", 0},\n {\"Go\", 3},\n {\"Scrabble\", 14},\n {\"09\\t\\r\\n.?!\", 0},\n {\"Français\", 10},\n {\"羅生門\", 0}, // Rashōmon\n }\n for _, tt := range tests2 {\n got := Score(tt.word)\n if got != tt.score {\n t.Errorf(\"Score(%s) : got %d; want %d\", tt.word, got, tt.score)\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<hr>\n\n<blockquote>\n <p>with <code>gofmt</code> I'm not sure I use it correctly, as it simply prints out\n the code to stdout.</p>\n</blockquote>\n\n<p>For most purposes, use the <code>go fmt</code> command.</p>\n\n<blockquote>\n <p><a href=\"https://golang.org/cmd/go/#hdr-Gofmt__reformat__package_sources\" rel=\"nofollow noreferrer\">Gofmt (reformat) package sources</a></p>\n\n<pre><code>Usage:\n\ngo fmt [-n] [-x] [packages]\n</code></pre>\n \n <p>Fmt runs the command 'gofmt -l -w' on the packages named by the import\n paths. It prints the names of the files that are modified.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T10:56:31.540",
"Id": "458880",
"Score": "0",
"body": "That's really great effort and quite complete regarding the problem. But in regard of testing, since we are talking about invalid string input, it might be worth mentioning fuzzing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T16:53:58.393",
"Id": "458992",
"Score": "0",
"body": "@leafbebop: Fuzz testing is neither relevant nor appropriate."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T15:06:14.040",
"Id": "234540",
"ParentId": "234524",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "234540",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T09:35:43.033",
"Id": "234524",
"Score": "4",
"Tags": [
"programming-challenge",
"go"
],
"Title": "Computing Scrabble score in Golang"
}
|
234524
|
<p>I am trying to refactor a chess game I am currently creating so the code is more flexible and maintainable, while doing this, I came across an event listener which I have no idea on how to make "cleaner". Some of the variable names in the event listener are unintuitive but apart from that, I would like to know how to structure the event listener such that it uses multiple methods. I have previously asked a question on Code Review which is also about refactoring, and contains the code from which this function came from, here is the link: <a href="https://codereview.stackexchange.com/questions/234430/object-oriented-javascript-chess-game">Object-Oriented JavaScript chess game</a>. If you have any questions or clarifications needed about the code, feel free to ask.</p>
<pre><code> document.addEventListener('click', function(event){
if(!hasClicked){
if(event.clientX < 480 && event.clientY < 480 && board[Math.floor(event.clientY / 60)][Math.floor(event.clientX / 60)] != "vacant"){
if(humanPlayer.indexOf(board[Math.floor(event.clientY / 60)][Math.floor(event.clientX / 60)]) != -1){
canMove = true;
isHighlightPossibleMoves = true;
hasClicked = true;
highlightPos = {x: Math.floor(event.clientX / 60), y: Math.floor(event.clientY / 60)};
pieceMoves = processMoves({x: Math.floor(event.clientX / 60), y: Math.floor(event.clientY / 60)}, board);
} else {
hasClicked = true;
highlightPos = {x: Math.floor(event.clientX / 60), y: Math.floor(event.clientY / 60)};
canMove = false;
}
}
} else {
if(canMove){
advancePosition = {x: Math.floor(event.clientX / 60), y: Math.floor(event.clientY / 60)};
for(i = 0; i < pieceMoves.moves.length; i++){
if(advancePosition.x == pieceMoves.moves[i].x && advancePosition.y == pieceMoves.moves[i].y){
if(board[highlightPos.y][highlightPos.x] == blackKing || board[highlightPos.y][highlightPos.x] == whiteKing){
if(pieceMoves.moves[i].x - 2 == highlightPos.x || pieceMoves.moves[i].x + 2 == highlightPos.x){
isCastling = true;
} else {
isCastling = false;
}
}
if(isCastling){
board = chess.returnCastledBoard({x: highlightPos.x, y: highlightPos.y}, pieceMoves.moves[i]);
chess = new Chess(board);
isCastling = false;
} else {
if(
board[highlightPos.y][highlightPos.x] == whiteKingSideCastle ||
board[highlightPos.y][highlightPos.x] == whiteQueenSideCastle ||
board[highlightPos.y][highlightPos.x] == blackKingSideCastle ||
board[highlightPos.y][highlightPos.x] == blackQueenSideCastle ||
board[highlightPos.y][highlightPos.x] == blackKing ||
board[highlightPos.y][highlightPos.x] == whiteKing
){
board[highlightPos.y][highlightPos.x].hasClicked = true;
}
board = chess.updateBoard(highlightPos, advancePosition);
chess = new Chess(board);
break;
}
}
}
}
hasClicked = false;
canMove = false;
highlightPos = undefined;
pieceMoves = undefined;
advancePosition = undefined;
}
});
<span class="math-container">````</span>
</code></pre>
|
[] |
[
{
"body": "<h3><em>Toward restructuring and optimization</em></h3>\n\n<p>The expressions <strong><code>Math.floor(event.clientX / 60)</code></strong> and <strong><code>Math.floor(event.clientY / 60)</code></strong> which represents element position are redundantly duplicated across a half of the entire posted function's content.<br>The <em>Extract function technique</em> is reasonably applied and expressed with a separate function:</p>\n\n<pre><code>function getElPosition(e){\n return {x: Math.floor(e.clientX / 60),\n y: Math.floor(e.clientY / 60)};\n}\n</code></pre>\n\n<hr>\n\n<p><code>hasClicked</code> and <code>highlightPos</code> variables are assigned with same values in both exclusive branches of <code>if/else</code> conditional.<br>Thus, the assignment statements are moved out as common ones.<br>Furthermore, both <strong><code>highlightPos</code></strong> and <strong><code>advancePosition</code></strong> are essentially point to the target event element position returned by mentioned <code>getElPosition</code> function. Therefore, they could be just eliminated (see the full approach below).</p>\n\n<hr>\n\n<p>The condition:</p>\n\n<pre><code>if (pieceMoves.moves[i].x - 2 == highlightPos.x || pieceMoves.moves[i].x + 2 == highlightPos.x) {\n isCastling = true;\n} else {\n isCastling = false;\n}\n</code></pre>\n\n<p>is just a verbose version of:</p>\n\n<pre><code>isCastling = (pieceMoves.moves[i].x - 2 == elPos.x || pieceMoves.moves[i].x + 2 == elPos.x);\n</code></pre>\n\n<p>Noisy condition:</p>\n\n<pre><code>if (\n board[highlightPos.y][highlightPos.x] == whiteKingSideCastle ||\n board[highlightPos.y][highlightPos.x] == whiteQueenSideCastle ||\n board[highlightPos.y][highlightPos.x] == blackKingSideCastle ||\n board[highlightPos.y][highlightPos.x] == blackQueenSideCastle ||\n board[highlightPos.y][highlightPos.x] == blackKing ||\n board[highlightPos.y][highlightPos.x] == whiteKing\n)\n</code></pre>\n\n<p>is replaced with flexible <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\"><code>Array.includes</code></a> feature:</p>\n\n<pre><code>if ([whiteKingSideCastle, whiteQueenSideCastle, blackKingSideCastle, \n blackQueenSideCastle, blackKing, whiteKing].includes(board[elPos.y][elPos.x]))\n</code></pre>\n\n<p>The <code>can_move</code> flag can be eliminated and replaced with check of <code>pieceMoves.length</code>.</p>\n\n<p><code>board[highlightPos.y][highlightPos.x]</code> indexing is repeated multiple times and worth to be extracted into a variable:</p>\n\n<pre><code>let boardItem = board[elPos.y][elPos.x];\n</code></pre>\n\n<hr>\n\n<p>See the full optimized approach:</p>\n\n<pre><code>function getElPosition(e){\n return {x: Math.floor(event.clientX / 60),\n y: Math.floor(event.clientY / 60)};\n}\n\ndocument.addEventListener('click', function (event) {\n let elPos = getElPosition(event);\n if (!hasClicked) {\n if (event.clientX < 480 && event.clientY < 480 && board[elPos.y][elPos.x] != \"vacant\") {\n if (humanPlayer.indexOf(board[elPos.y][elPos.x]) != -1) {\n isHighlightPossibleMoves = true;\n pieceMoves = processMoves(Object.assign({}, elPos), board);\n }\n hasClicked = true;\n }\n } else {\n if (pieceMoves && pieceMoves.length) {\n for (let i = 0, len = pieceMoves.moves.length; i < len; i++) {\n let boardItem = board[elPos.y][elPos.x];\n if (elPos.x == pieceMoves.moves[i].x && elPos.y == pieceMoves.moves[i].y) {\n if (boardItem == blackKing || boardItem == whiteKing) {\n isCastling = (pieceMoves.moves[i].x - 2 == elPos.x || pieceMoves.moves[i].x + 2 == elPos.x);\n }\n if (!isCastling) {\n if ([whiteKingSideCastle, whiteQueenSideCastle, blackKingSideCastle,\n blackQueenSideCastle, blackKing, whiteKing].includes(boardItem))\n {\n boardItem.hasClicked = true;\n }\n board = chess.updateBoard(elPos, elPos);\n chess = new Chess(board);\n break;\n }\n board = chess.returnCastledBoard({x: elPos.x, y: elPos.y}, pieceMoves.moves[i]);\n chess = new Chess(board);\n isCastling = false;\n }\n }\n }\n hasClicked = false;\n pieceMoves = undefined;\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T13:36:59.807",
"Id": "458696",
"Score": "1",
"body": "A function separated from the event listener with a name that's indicative of it's intent would be a good addition to this answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T12:53:52.673",
"Id": "234531",
"ParentId": "234526",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234531",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T11:03:53.337",
"Id": "234526",
"Score": "1",
"Tags": [
"javascript",
"functional-programming",
"event-handling"
],
"Title": "Clean up function in Javascript Event Listener"
}
|
234526
|
<p>I am making a ros node to implement dijkstra's algorithm on a 1000x1000 pixel map.</p>
<p>I have used map_server to convert the map into an nav_msgs/OccupancyGrid. </p>
<p>The map is in the form of a row dominant matrix and I have declared visited, distance and prev in the same form. Distance stores the distance of each index and is initially declared with a huge number. visited is a bool array storing whether that index has been visited or not. prev stores the shortest path followed.</p>
<p>struct node is initialised to make a priority queue storing node and distance in increasing order.</p>
<p>void dijkstra is the function that does the heavy loading in this program.</p>
<p>What I'm looking for if there are any blind spots I'm not considering and if there are some optimisations. </p>
<pre><code>#include <ros/ros.h>
#include <math.h>
#include <queue>
#include <vector>
#include <std_msgs/String.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseArray.h>
#include <nav_msgs/OccupancyGrid.h>
#include <nav_msgs/GetMap.h>
#include <ros/console.h>
#define FMAX 999999999.99
geometry_msgs::PoseArray pa;
int rows = 1000, columns = 1000, size = rows * columns;
bool visited[1000000];
float distance[1000000];
int prev[1000000];
int source = 15100, destination = 990500; // Give source and destination
int dr[] = {1, -1, 0, 0, 1, 1, -1, -1}; // Direction vectors
int dc[] = {0, 0, 1, -1, 1, -1, 1, -1};
struct node
{
int index;
float dist;
node(int index, float dist)
: index(index), dist(dist)
{
}
};
struct compareDist
{
bool operator()(node const& n1, node const& n2)
{
return n1.dist > n2.dist;
}
};
// Priority queue
std::priority_queue <node, std::vector<node>, compareDist> pq;
int index(int r, int c)
{
return (r * 1000) + c;
}
void init()
{
std::cout << "init";
for(int i = 0; i < size; i++)
{
distance[i] = FMAX;
visited[i] = false;
prev[i] = 99999999;
}
}
float dist_(int index1, int index2)
{
int r1, c1, r2, c2;
r1 = index1 / columns; r2 = index2 / columns;
c1 = index1 - (r1 * 1000); c2 = index2 - (r2 * 1000);
return sqrt(pow(r1 - r2, 2) + pow(c1 - c2, 2));
}
void dijkstra(const nav_msgs::OccupancyGrid& map)
{
prev[source] = 0;
node first = {source, 0.0}; // Define source
pq.push(first);
while(!pq.empty())
{
node temp = pq.top();
pq.pop();
int nodeIndex = temp.index;
float nodeDist = temp.dist;
visited[nodeIndex] = true;
int r = nodeIndex / columns;
int c = nodeIndex - (r * columns);
int rr, cc;
for(int i = 0; i < 8; i++) // to calculate neighbours
{
rr = r + dr[i];
cc = c + dc[i];
if(rr < 0 || rr >= 1000 || cc < 0 || cc >= 1000 || visited[index(rr, cc)] == true)
continue;
if(map.data[index(rr, cc)] == 100)
{
visited[index(rr, cc)] = true; // Marking blocked paths as visited
continue;
}
else
{
node neighbour(index(rr, cc), dist_(nodeIndex, index(rr, cc)));
float alt = nodeDist + neighbour.dist;
if(alt < distance[index(rr, cc)])
{
visited[index(rr, cc)] = true;
distance[index(rr, cc)] = alt;
prev[index(rr, cc)] = nodeIndex;
node next(index(rr, cc), alt);
pq.push(next);
}
if(visited[destination] == true)
break;
}
}
if(visited[destination] == true)
break;
}
std::vector <int> path;
// prev contains the path. Trace it back to get the path.
path.push_back(destination);
while(true)
{
path.push_back(prev[path.back()]);
if(path.back() == 0)
break;
}
for(int i = 0; i < path.size(); i++)
{
int x, y;
x = path.back() / columns;
y = path.back() - (x * columns);
path.pop_back();
geometry_msgs::Pose p;
p.position.x = x;
p.position.y = y;
p.position.z = 0;
pa.poses.push_back(p);
}
}
int main(int argc, char **argv)
{
init();
distance[source] = 0;
visited[source] = true;
ros::init(argc, argv, "dijkstra");
ros::NodeHandle n("~");
ros::ServiceClient client = n.serviceClient<nav_msgs::GetMap>("/static_map");
nav_msgs::GetMap srv;
client.call(srv);
nav_msgs::OccupancyGrid my_map = srv.response.map;
ros::Publisher pose_array_pub = n.advertise<geometry_msgs::PoseArray>("/poseArray", 1);
pa.header.frame_id = "map";
dijkstra(my_map);
while(ros::ok())
{
pose_array_pub.publish(pa);
}
ros::spin();
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>You have lots of global variables. That works for a one-off program, but if you ever want to package your functionality into a library or so, you need to rewrite this to put them into the main program. Might as well do so immediately. (In particular your \"dijkstra\" function should return an explicit result. Not be void and work on a global variable.)</p>\n\n<p>You declare a couple of large static arrays. 1. That's wasteful for smaller problems. 2. Your program will crash if you try something larger. 3. You are putting them on the stack so this runs into problems if your OS limits the stack size. Conclusion: please make them dynamic. std::vector is great for this. That also prevents you from having lots of \"magic numbers\" in your code.</p>\n\n<p>\"if(visited[destination] == true)\" You know that that's the same as \n<code>if(visited[destination])</code>?</p>\n\n<p>Algorithm optimizations? If you implemented it correctly it'll probably be fine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T21:01:16.170",
"Id": "234758",
"ParentId": "234527",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T11:20:36.337",
"Id": "234527",
"Score": "2",
"Tags": [
"c++",
"pathfinding"
],
"Title": "ROS implementation of Dijkstra's algorithm to shortest path"
}
|
234527
|
<p>I'm quite new to C programming so I'm trying to learn the basics. I've made a program that creates a linked list of numbers, then ask user for which number he/she wants to replace and then what number should come instead.</p>
<p>I finally got it to work, but since I'm learning this on my own no one is there to say when my style is bad or if I use bad methods for solving my problems. So I kindly ask if you see something that's done in an unwise way to let me know.</p>
<p>So here's the code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int val;
struct node* next;
};
typedef struct node node_t;
// Function that evaluate the value in the nodes of the linked list and replace it.
void replace(node_t ** head, int replacement_value, int new_value) {
node_t **tracer = head;
while ((*tracer)->next != NULL && (*tracer)->val != replacement_value) {
(*tracer) = (*tracer)->next;
}
(*tracer)->val = new_value;
}
// Function that prints out the linked list.
void printlist(node_t *head) {
node_t *temporary = head;
while (temporary != NULL) {
printf("%d - ", temporary->val);
temporary = temporary->next;
}
printf("\n");
}
// The following creates nodes in the linked list.
node_t *create_new_node(int val) {
node_t *result = malloc(sizeof(node_t));
result->val = val;
result->next = NULL;
return result;
}
int main(){
node_t *head = NULL;
node_t *tmp;
// The following creates the linked list.
for (int i=0; i<25; i++) {
tmp = create_new_node(i);
tmp->next = head;
head=tmp;
}
printf("First print:\n");
printlist(head);
int replacement_value;
int new_value;
printf("Which number do you wish to replace?\n");
scanf("%d", &replacement_value);
printf("What number do you want to replace it with?\n");
scanf("%d", &new_value);
node_t *temphead;
temphead = head;
replace(&temphead, replacement_value, new_value);
printf("Modified print:\n");
printlist(head);
return(0);
}
</code></pre>
|
[] |
[
{
"body": "<p>For a new user of C you really aren't doing too bad, you're not using global variables which is very good. The functions are small and well defined. The program as a whole is well organized so that function prototypes are not required.</p>\n\n<p>This program could have a few more function and that would simplify <code>main()</code>:</p>\n\n<ul>\n<li>A function that asks the user for input and performs error checking on the input before returning values, this would also localize the variables for input in the function </li>\n<li>There are some basic linked list operations that are not here that might be helpful <code>insert_node()</code>, <code>delete_node()</code> and <code>append_node()</code> <code>find_node()</code>, other functions such as <code>replace()</code> can utilize these basic functions </li>\n<li>It might be good to have a function that prints a title and then calls <code>printlist()</code> which would reduce the amount of code in <code>main()</code> </li>\n<li>A function to initialize the linked list </li>\n</ul>\n\n<h2>Missing Error Checking</h2>\n\n<p>There are two places where error checking in this program, first, it is generally a best practice to error check all user input before using the input values. Users can make mistakes when entering data, they may just hit the enter key without entering data, they may enter a string instead of a number, they may enter a number that is not in the list which could cause problems while searching the list.</p>\n\n<p>The second place where error checking is necessary is after any memory allocation in the C programming language, some or most high level languages will throw exceptions if memory allocation fails. In C programming if memory allocation fails the call to <code>malloc()</code>, <code>calloc()</code> or <code>realloc()</code> returns NULL. It is very important to check the value returned to make sure it is not NULL before using the memory, access through a NULL pointer causes unknown behavior. This can cause a number of problems including the crashing of the program or the corruption of data in the program.</p>\n\n<pre><code>node_t *create_new_node(int val) {\n node_t *result = malloc(sizeof(node_t));\n if (result == NULL)\n {\n fprintf(stderr, \"malloc failed in create_new_node()\\n\");\n return result;\n }\n result->val = val; // Unknown behavior here if malloc() failed\n result->next = NULL;\n return result;\n}\n</code></pre>\n\n<h2>Include Files That Are Not Necessary</h2>\n\n<p>The code contains <code>#include <string.h></code> however, no functions defined in this include file are utilized. The `#include statement copies the contents of the file into the current file, it will increase the compile time and if you are using an editor that also creates a makefile it may add an unnecessary dependency to the makefile. There may also be collisions with functions defined in the code. Basically don't include files you don't need.</p>\n\n<h2>Return From Main</h2>\n\n<p>The C compiler is smart enough to add <code>return 0;</code> at the end of this program, if the code does contain multiple returns from <code>main()</code> such as program failure when <code>malloc()</code> fails the code will be more readable if <code>return EXIT_FAILURE;</code> or <code>return EXIT_SUCCESS;</code>. These macros are included from <code>stdlib.h</code> which is already included in this program.</p>\n\n<h2>Readability</h2>\n\n<p>The code would be more readable and easier to maintain if there were spaces between operators and operands <code>for (int i=0; i<25; i++) {</code> versus <code>for (int i = 0; i < 25; i++) {</code>. It would also make the code more readable and maintainable if the <code>25</code> in the for loop was a symbolic constant</p>\n\n<pre><code>#define LIST_SIZE 25\n\n...\n\n for (int i = 0; i < LIST_SIZE; i++) {\n tmp = create_new_node(i);\n if (tmp == NULL)\n {\n return EXIT_FAILURE;\n }\n tmp->next = head;\n head=tmp;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T15:01:03.350",
"Id": "234537",
"ParentId": "234532",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234537",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T12:54:03.417",
"Id": "234532",
"Score": "3",
"Tags": [
"c",
"linked-list"
],
"Title": "Linked list where user replace a chosen number in the list with a number chosen by user - how can it be improved?"
}
|
234532
|
<p>This is my solution to the Codewars problem <a href="https://www.codewars.com/kata/5b3077019212cbf803000057" rel="nofollow noreferrer">TV Remote (symbols)</a>.</p>
<p><strong>Description</strong></p>
<p>In short, you are given a virtual keyboard with 3 modes between which can be switched by pressing the <code>Shift</code> button on the virtual keyboard. </p>
<p>You have to navigate using only arrow buttons (<code>up</code>, <code>right</code>, <code>down</code>, <code>left</code>) and an <code>OK</code>-button to press the currently selected button. Wraparound is possible.</p>
<p>The challenge is to find the shortest sequence of button presses with which you can write a given <code>string</code> (ignoring optimizations such as prematurely switching Mode).</p>
<p><strong>Questions</strong></p>
<ol>
<li>Is it correct to make methods which don't rely on the internal state
(such as <code>calculateMoves</code>) <code>static</code>? Or is it recommended to
effectively duplicate its functionality (for <code>row</code> and <code>col</code> each)
and use its internal state? </li>
<li>Since I'm not all too experienced with OOP, did I break any common
conventions?</li>
</ol>
<p><strong>Code</strong></p>
<pre class="lang-js prettyprint-override"><code>type Coords = { row: number, col: number }
function mod(a: number, b: number): number {
return ((a % b) + b) % b
}
class TvRemote {
private static readonly ModeButton = 'aA#'
private static readonly Mode = [
// Mode1 = [0]
[
'abcde123'.split(''),
'fghij456'.split(''),
'klmno789'.split(''),
'pqrst.@0'.split(''),
'uvwxyz_/'.split(''),
[TvRemote.ModeButton, ' ', , , , , , ,]
],
// Mode2 = [1]
[
'ABCDE123'.split(''),
'FGHIJ456'.split(''),
'KLMNO789'.split(''),
'PQRST.@0'.split(''),
'UVWXYZ_/'.split(''),
[TvRemote.ModeButton, ' ', , , , , , ,]
],
// Mode3 = [2]
[
`^~?!\'"()`.split(''),
'-:;+&%*='.split(''),
'<>€£$¥¤\\'.split(''),
'[]{},.@§'.split(''),
['#', '¿', '¡', , , , '_', '/'],
[TvRemote.ModeButton, ' ', , , , , , ,]
]
]
private static readonly NumRows = 6
private static readonly NumCols = 8
private currRow = 0
private currCol = 0
private currModeIndex = 0
private buttonPresses = 0
public getButtonPresses (): number {
return this.buttonPresses
}
public write (string: string): void {
for (const char of string) {
this.moveToChar(char)
this.pressButton()
}
}
private currentMode(): string[][] {
return TvRemote.Mode[this.currModeIndex]
}
private currentChar(): string {
return this.currentMode()[this.currRow][this.currCol]
}
private moveToChar (char: string): void {
this.switchToCorrectMode(char)
const { row, col } = this.getCoordinates(char)
const moveRowsBy = TvRemote.calculateMoves(this.currRow, row, TvRemote.NumRows)
const moveColsBy = TvRemote.calculateMoves(this.currCol, col, TvRemote.NumCols)
this.move(moveRowsBy, moveColsBy)
}
private switchToCorrectMode (char: string): void {
if (this.existsInCurrentMode(char)) return
for (let i = 0; i < TvRemote.Mode.length - 1; i++) {
if (!this.existsInCurrentMode(TvRemote.ModeButton) && TvRemote.Mode.length > 1) {
throw new Error('Missing button to switch modes')
}
this.moveToChar(TvRemote.ModeButton)
this.pressButton()
if (this.existsInCurrentMode(char)) {
return this.moveToChar(char)
}
}
throw new Error(`Character "${char}" does not exist on keyboard`)
}
private static calculateMoves (curr: number, target: number, maxNum: number): number {
// positive: right for x, down for y
const movePos = (maxNum + target - curr) % maxNum
const moveNeg = - (maxNum + curr - target) % maxNum
return Math.abs(movePos) <= Math.abs(moveNeg) ? movePos : moveNeg
}
private move (moveRowsBy: number, moveColsBy: number): void {
this.currRow = mod(this.currRow + moveRowsBy, TvRemote.NumRows)
this.buttonPresses += Math.abs(moveRowsBy)
this.currCol = mod(this.currCol + moveColsBy, TvRemote.NumCols)
this.buttonPresses += Math.abs(moveColsBy)
}
private pressButton(): void {
this.buttonPresses++
const currChar = this.currentChar()
console.log(currChar)
if (currChar === TvRemote.ModeButton) {
this.currModeIndex = mod(this.currModeIndex + 1, TvRemote.Mode.length)
}
}
private existsInCurrentMode (char: string): boolean {
const { row , col } = this.getCoordinates(char)
return row !== -1 && col !== -1
}
private getCoordinates (char: string): Coords {
let col = -1
let row = this.currentMode().findIndex(rowEntries => {
col = rowEntries.indexOf(char)
return col !== -1
})
return { row, col }
}
}
</code></pre>
<p><strong>Example output</strong></p>
<p>Calling <code>.write('Too Easy?')</code> should result in <code>71</code> button presses.
See <a href="https://www.codewars.com/kata/5b3077019212cbf803000057#example" rel="nofollow noreferrer">here</a> for a detailed explanation.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T14:50:02.817",
"Id": "234534",
"Score": "2",
"Tags": [
"object-oriented",
"programming-challenge",
"typescript",
"pathfinding",
"coordinate-system"
],
"Title": "Codewars: Remote Control Virtual Keyboard"
}
|
234534
|
<p>Using Rails 6. Here's a piece that I wrote just to display number of stars. Obviously I am disgusted by my own code. How would you refactor?</p>
<pre><code># application_helper.rb
module ApplicationHelper
def show_star_rating(rating)
zero_star_icon_name = "star"
full_star_icon_name = "star_fill"
half_star_icon_name = "star_lefthalf_fill"
total_stars = []
round_by_half = (rating * 2).round / 2.0
(round_by_half.to_i).times { total_stars << full_star_icon_name }
if round_by_half - round_by_half.to_i == 0.5
total_stars << half_star_icon_name
end
if total_stars.size != 5
(5 - total_stars.size).times { total_stars << zero_star_icon_name }
end
total_stars
end
end
# show.html.erb
<% show_star_rating(agent_review.rating).each do |star| %>
<i class="f7-icons"><%= star %></i>
<% end %>
</code></pre>
|
[] |
[
{
"body": "<p>You can make use of the <a href=\"https://ruby-doc.org/core/Array.html#method-c-new\" rel=\"noreferrer\"><code>Array.new</code></a>, passing in the maximum number of stars you want to show, and defaulting all the stars to empty. Then, you can <a href=\"https://ruby-doc.org/core/Array.html#method-i-fill\" rel=\"noreferrer\"><code>fill</code></a> in the number of full stars you need. Then, finally, thanks to <code>Numeric</code>'s <a href=\"https://ruby-doc.org/core/Numeric.html#method-i-divmod\" rel=\"noreferrer\"><code>divmod</code></a> returning either <code>0</code> or <code>1</code> for the number of half stars you need, you make one more pass and <code>fill</code> in the number of half stars you need:</p>\n\n<pre><code>module StarHelper\n EMPTY_STAR_ICON = 'star'.freeze\n FULL_STAR_ICON = 'star_fill'.freeze\n HALF_STAR_ICON = 'star_lefthalf_fill'.freeze\n\n def full_and_half_star_count(rating)\n (rating * 2).round.divmod(2)\n end\n\n def stars(rating, max_stars: 5)\n full_stars, half_stars = full_and_half_star_count(rating)\n\n Array.new(max_stars, EMPTY_STAR_ICON).\n fill(FULL_STAR_ICON, 0, full_stars).\n fill(HALF_STAR_ICON, full_stars, half_stars)\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T19:01:22.943",
"Id": "458912",
"Score": "0",
"body": "Same as my answer on the [StackOverflow question](https://stackoverflow.com/questions/59477682/rails-helper-to-display-rating-in-stars/59480841#59480841), but it seems more on topic here than over there, so adding it over on this side"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T20:45:04.373",
"Id": "458924",
"Score": "0",
"body": "I like the `fill` approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T22:56:02.543",
"Id": "458933",
"Score": "0",
"body": "Welcome to Code Review, you answer is a great first answer. Thank you for taking the time to port your answer across."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T13:30:29.640",
"Id": "458972",
"Score": "0",
"body": "Thanks. I'd move the `full_and_half_star_count` private too."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T19:00:45.723",
"Id": "234641",
"ParentId": "234536",
"Score": "6"
}
},
{
"body": "<p>I doubt if all those logic is meant to be in the ApplicationHelper. You could create a new helper file and move that logic.</p>\n\n<p>As you have three constant values declared within the method body, you can move them outside as constants, and modify the value of <code>total_stars</code> depending on the conditions you have:</p>\n\n<pre><code>ZERO_STAR_ICON_NAME = \"star\"\nFULL_STAR_ICON_NAME = \"star_fill\"\nHALF_STAR_ICON_NAME = \"star_lefthalf_fill\"\n\ndef show_star_rating(rating)\n round_by_half = (rating * 2).round / 2.0\n total_stars = Array.new(round_by_half, FULL_STAR_ICON_NAME)\n total_stars += [HALF_STAR_ICON_NAME] if round_by_half - round_by_half.to_i == 0.5\n total_stars += Array.new(5 - total_stars.size, ZERO_STAR_ICON_NAME) unless total_stars.size == 5\nend\n</code></pre>\n\n<ul>\n<li>You can use <code>unless</code> whenever you have a <code>!=</code> condition to make the statement more clear.</li>\n<li>You can use <code>Array.new</code> to create a new array and sum (<code>+=</code>) it to the current value of <code>total_stars</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:10:28.407",
"Id": "234661",
"ParentId": "234536",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234641",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T15:00:54.080",
"Id": "234536",
"Score": "4",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Rails Helper to display rating in stars"
}
|
234536
|
<p>I am writing code to implement data sync from multiple sources. I want code to be maintainable to add more data sources if required.</p>
<p>Here is the pattern I wish to follow:</p>
<pre><code>class Source1Client:
def get_domain(self):
pass
def get_endpoint(self):
pass
def get_headers(self):
pass
def make_post_request(self, url, data, headers):
response = requests.post(url, data, headers=headers)
return response
def make_get_request(self, url, data):
response = requests.get(url, data)
return response
class Source2Client:
def get_domain(self):
pass
def get_endpoint(self):
pass
def get_headers(self):
pass
def make_post_request(self, url, data, headers):
response = requests.post(url, data, headers=headers)
return response
def make_get_request(self, url, data):
response = requests.get(url, data)
return response
def call_stored_procedure(self, query):
pass
def run_query(self, query):
pass
class BaseSync:
def convert_data_to_serialized_objects(self, data, serializer, many=True):
db_object, db_object_list = {}, []
for i in data:
for column, value in i.items():
db_object = {**db_object, **{column: value}}
db_object_list.append(db_object)
schema = serializer(many=many)
m = schema.dump(db_object_list)
return m.data
def get_serialized_data(
self,source=None, query=None, proc=None, serializer=None, many=True, proc_kwargs={},
endpoint=None, method=None, data=None, headers=None
):
if source == "source1":
client = Source1Client()
if source == "source2":
client = Source2Client()
if proc:
formatted_query = proc.format(**proc_kwargs)
raw_data = cllient.call_stored_procedure(formatted_query)
if query:
raw_data = client.run_query(query)
else:
if method == "get":
raw_data == client.make_get_request(endpoint, data)
if method == "post":
raw_data == client.make_post_request(endpoint, data, headers)
serialized_data = self.convert_data_to_serialized_objects(
raw_data, serializer, many=many
)
return serialized_data
class DataSync(BaseSync):
def sync_source1_data():
source1_data = self.get_serialized_data(source="source1", endpoint="source1url/path")
# other operations
def sync_source2_data():
source1_data = self.get_serialized_data(source="source2", endpoint="source1url/path")
# other operations
</code></pre>
<p>In my code <code>get_serialized_data</code> is using multiple if-else cases, which will make code dirty and hard to read if more sources are added. Also, it has too many parameters, which is against clean code principles. </p>
<p>What can be a better implementation to make code cleaner, maintainable and readable?</p>
|
[] |
[
{
"body": "<p>Use <strong>__init__</strong> to handle bunch of arguments, then your <code>self</code> will take of passing arguments to your respective definition - that's the good way to use <a href=\"https://docs.python.org/3/tutorial/classes.html\" rel=\"nofollow noreferrer\">OOP in python</a>.</p>\n\n<pre><code>class Foo:\n def __init__(self, value_a, value_b):\n self.a = value_a\n self.b = value_b\n\n def func(self):\n pass\n</code></pre>\n\n<p>To avoid multiple if else you can have list or dict and from there you can access. \nHope this helps !!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T16:03:17.263",
"Id": "234541",
"ParentId": "234539",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T15:05:56.710",
"Id": "234539",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"object-oriented"
],
"Title": "Implementing data sync from multiple source using OOP concepts"
}
|
234539
|
<p>I'm quite new to both Java and OOP.</p>
<p>I'm assuming that pretty much everything about my code can be improved and I appreciate any feedback. However, I am particularly interested in what you think about my code clarity/structure/organisation. For example, I've struggled to decide when functionality should be extracted into their own separate class ever since I've started with Java, so feedback on that would help me a lot.</p>
<p>This is also my first time including any error handling, what do you think of my efforts in that regard?</p>
<p>My classes are also be seen on github <a href="https://github.com/BLBaylis/Smart_Calculator" rel="nofollow noreferrer">here</a>. I'm also not sure how much code is correct to post inside this question. What happens if it is too much code to reasonably include in the post? How large could projects posted to this forum be?</p>
<p>Thanks</p>
<h3>Main.java</h3>
<pre><code>package calculator;
public class Main {
private Main() {
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.run();
}
}
</code></pre>
<h3>Calculator.java</h3>
<pre><code>package calculator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Calculator {
private UserVariables userVariables = new UserVariables();
Calculator() {
}
enum InputType {
COMMAND, ASSIGNMENT, CALCULATION
}
private String getCommandMessage(String command) {
if ("/exit".equals(command)) {
return "Bye!";
} else if ("/help".equals(command)) {
return "Type in a calculation with spaces between each number and operator";
} else {
return "Unknown command";
}
}
private InputType determineInputType(String userInput) {
if (userInput.charAt(0) == '/') {
return InputType.COMMAND;
}
Matcher assignmentMatcher = Pattern.compile("=").matcher(userInput);
if (assignmentMatcher.find()) {
return InputType.ASSIGNMENT;
}
return InputType.CALCULATION;
}
final void run() {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String userInput = scanner.nextLine();
if (userInput.isEmpty()) {
continue;
}
InputType inputType = determineInputType(userInput);
switch (inputType) {
case COMMAND:
String message = getCommandMessage(userInput);
System.out.println(message);
if ("\\exit".equals(userInput)) {
return;
}
break;
case ASSIGNMENT:
try {
userVariables.assignVariable(userInput);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
break;
case CALCULATION:
try {
System.out.println(new Calculation(userInput).getResult());
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
break;
}
}
}
}
</code></pre>
<h3>Calculation.java</h3>
<pre><code>package calculator;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayDeque;
import java.util.Deque;
class Calculation {
private String result;
private final static String operatorPrecededByOperandRegex = "(?<=\\w)(?=([-+*^/]))";
private final static String operatorFollowedByOperandRegex = "(?<=[-+*^/])(?=\\w)";
private final static String anyBracketRegex = "(?<=[()])|(?=[()])";
Calculation(String inputString) {
this.result = performCalculation(inputString);
}
String getResult() {
return result;
}
private String performCalculation(String inputString) {
String validSingleOperandRegex = String.format("%s*(\\w+|\\d+)", "[+-]");
boolean hasOneOperand = inputString.matches(validSingleOperandRegex);
if (hasOneOperand) {
String variableValue = UserVariables.get(inputString);
return result = variableValue == null ? inputString : variableValue;
}
String[] inputArr = processInputString(inputString);
Deque<String> notationQueue = new ArrayDeque<>();
Deque<String> operatorStack = new ArrayDeque<>();
convertInfixToPostfix(inputArr, notationQueue, operatorStack);
Deque<String> calcStack = new ArrayDeque<>();
return calculatePostfixExpression(notationQueue, calcStack);
}
private String[] processInputString(String inputString) {
String spacesRemovedInputString = inputString.replaceAll("\\s+", "");
/*The three regular expressions that comprise this regex each have zero width meaning that they are empty
and instead these regexps just check for a condition to be true. The reason for this is so when the inputString
is split, none of the elements we are looking for are removed from the array in the process.
*/
String stringSplitRegex = String.format("(%s|%s|%s)",
operatorPrecededByOperandRegex,
operatorFollowedByOperandRegex,
anyBracketRegex
);
String[] inputArr = spacesRemovedInputString.split(stringSplitRegex);
String[] substitutedArr = substituteVariables(inputArr);
return fixOperators(substitutedArr);
}
static private String[] substituteVariables(String[] inputArr) {
for (int i = 0; i < inputArr.length; i += 2) {
if (UserVariables.containsKey(inputArr[i])) {
inputArr[i] = UserVariables.get(inputArr[i]);
}
}
return inputArr;
}
static private String[] fixOperators(String[] inputArr) {
for (int i = 1; i < inputArr.length; i += 1) {
if (inputArr[i].matches("[+-]+")) {
inputArr[i] = Operator.parseOperator(inputArr[i]);
}
}
return inputArr;
}
private void convertInfixToPostfix(String[] inputArr, Deque<String> notationQueue, Deque<String> operatorStack) throws IllegalArgumentException{
for (String currInput : inputArr) {
boolean nextOperatorOnOperatorStackIsOpeningBracket = "(".equals(operatorStack.peekFirst());
boolean currInputIsOpeningBracket = "(".equals(currInput);
if (currInput.matches("[+-]*\\d+")) {
//if curr input is operand, add to notation queue
notationQueue.addLast(currInput);
} else if (operatorStack.isEmpty() || nextOperatorOnOperatorStackIsOpeningBracket || currInputIsOpeningBracket) {
operatorStack.addFirst(currInput);
} else if (")".equals(currInput)) {
/*If the current input is a closing bracket, pop from operator stack and push those onto notation queue
until an opening bracket is found. Neither the opening or closing bracket is added to the notation
queue.*/
handleClosingBracket(notationQueue, operatorStack);
} else {
/*If none of the above conditions are true, then that means the current input is an operator with a
lower priority than the operator that is next on the operator stack. At this point, the stack is popped
until this is no longer the case, then the new operator is pushed onto the same stack*/
handleLowerPriorityOperator(currInput, notationQueue, operatorStack);
}
}
/*Once all inputs have been checked, add any remaining operators on stack to end of notation queue*/
while (!operatorStack.isEmpty()) {
String next = operatorStack.removeFirst();
if ("(".equals(next) || ")".equals(next)) {
throw new IllegalArgumentException("Invalid expression");
}
notationQueue.addLast(next);
}
}
private void handleClosingBracket(Deque<String> notationQueue, Deque<String> operatorStack) throws IllegalArgumentException {
boolean openingBracketPopped = false;
while (!operatorStack.isEmpty() && !openingBracketPopped) {
String nextOperator = operatorStack.removeFirst();
if ("(".equals(nextOperator)) {
openingBracketPopped = true;
} else {
//add anything that isn't an opening bracket to notationStack
notationQueue.addLast(nextOperator);
}
}
if (!openingBracketPopped) {
throw new IllegalArgumentException("Invalid expression");
}
}
private void handleLowerPriorityOperator(String operator, Deque<String> notationQueue, Deque<String> operatorStack) {
int operatorPriority = Operator.getOperatorPriority(operator);
assert operatorStack.peekFirst() != null;
String stackOperator = operatorStack.peekFirst();
int stackOperatorPriority = Operator.getOperatorPriority(stackOperator);
while (!operatorStack.isEmpty() && operatorPriority <= stackOperatorPriority) {
notationQueue.addLast(operatorStack.removeFirst());
if ("(".equals(operatorStack.peekFirst())) {
break;
}
stackOperatorPriority = operatorStack.isEmpty() ? 0 : Operator.getOperatorPriority(operatorStack.peekFirst());
}
operatorStack.addFirst(operator);
}
private String calculatePostfixExpression(Deque<String> notationQueue, Deque<String> calcStack) throws IllegalArgumentException {
while (!notationQueue.isEmpty()) {
String next = notationQueue.removeFirst();
if (next.matches("[+-]?\\d+")) {
calcStack.addFirst(next);
} else {
BigDecimal result;
BigDecimal pop1 = new BigDecimal(String.valueOf(calcStack.removeFirst()));
BigDecimal pop2 = new BigDecimal(String.valueOf(calcStack.removeFirst()));
switch (next) {
case "+":
result = pop1.add(pop2);
break;
case "-":
result = pop2.subtract(pop1);
break;
case "*":
result = pop2.multiply(pop1);
break;
case "/":
result = pop2.divide(pop1, RoundingMode.HALF_UP);
break;
case "^":
result = pop2.pow(pop1.intValue());
break;
default:
throw new IllegalArgumentException("Postfix expression contained character which is neither " +
"digit nor allowed operator");
}
calcStack.addFirst(result.toString());
}
}
return calcStack.getFirst();
}
}
</code></pre>
<h3>Operator.java</h3>
<pre><code>package calculator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Operator {
static final private Pattern minusPattern = Pattern.compile("-");
static String parseOperator(String operator) {
if (operator.length() == 1) {
return operator;
}
Matcher minusRegexMatcher = minusPattern.matcher(operator);
int minusCount = 0;
while (minusRegexMatcher.find()) {
minusCount++;
}
return minusCount % 2 == 1 ? "-" : "+";
}
static int getOperatorPriority(String operator) {
switch (operator) {
case "^":
return 3;
case "*":
case "/":
return 2;
case "+":
case "-":
return 1;
default:
throw new IllegalArgumentException("Unknown Operator");
}
}
}
</code></pre>
<h3>UserVariables.java</h3>
<pre><code>package calculator;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class UserVariables {
static private Map<String, String> userVariables = new HashMap<>();
UserVariables(){
}
private static void put(String key, String value) {
userVariables.put(key, value);
}
static String get(String key) {
return userVariables.get(key);
}
static boolean containsKey(String key) {
return userVariables.containsKey(key);
}
void assignVariable(String userInput) throws IllegalArgumentException {
userInput = userInput.replaceAll("\\s+", "");
String[] assignmentArr = userInput.split("=");
if (assignmentArr.length != 2) {
throw new IllegalArgumentException("Invalid assignment");
}
String variableName = assignmentArr[0];
Matcher validVariableNameMatcher = Pattern.compile("[a-zA-Z]+").matcher(variableName);
if (!validVariableNameMatcher.matches()) {
throw new IllegalArgumentException("Invalid identifier");
}
try {
String variableValue = new Calculation(assignmentArr[1]).getResult();
UserVariables.put(variableName, variableValue);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid assignment");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Due to time constraints, I have only viewed the first two classes, here are my comments:</p>\n\n<h2>Main.java</h2>\n\n<ol>\n<li><p>There is no need for a private default constructor, unless you explicitly want to prevent from calling that method (e.g. in a singleton design pattern)</p></li>\n<li><p>In my eyes, the whole class is redundant. the <code>main()</code> method can be placed in <code>Calculator</code>. it is common practice to have a main method that initializes the class it resides in. </p></li>\n</ol>\n\n<h2>Calculator.java</h2>\n\n<ol>\n<li><p><strong>inconsistency:</strong> in <code>run()</code> the exit command's literal is <code>\"\\\\exit\"</code> while in <code>getCommandMessage()</code> it is <code>\"/exit\"</code> so not sure how to exist the program. </p></li>\n<li><p><strong>Separation of Concerns:</strong> Calculator class is responsible for reading input from console, parsing and validating, and write to the console. When you will want to evolve this program to have an html interface, you wil have to rewrite the entire class. According to the principle of <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">Separation of Concerns</a>, you should have separate classes for reading and writing input. this design allows for having the same <code>Calculator</code> to work with different sources of input and destinations of output. </p></li>\n<li><p><strong>Make use of enums as classes:</strong> Java enums are powerful constructs that allow to attach properties and behaviors (=methods) to the set of values. as a rule of thumb, every closed set of values should be expressed as an enum. in your case, you started fine with <code>InputType</code>, but what about the set of commands? . if you have a <code>Command</code> enum, you can assign <code>message</code> String property to every value (you can have an <code>UNKNOWN</code> command as well) and that can replace the whole <code>getCommandMessage()</code>. regarding <code>determineInputType()</code>: you can assign a <code>Predicate<String></code> to every enum value and apply that predicate to the input String. </p></li>\n</ol>\n\n<p>here's an illustration of what I am talking about:</p>\n\n<pre><code>enum InputType {\n COMMAND((userInput) -> userInput.charAt(0) == '/'),\n ASSIGNMENT((userInput) -> userInput.indexOf(\"=\") > -1),\n CALCULATION((userInput) -> true); // must be last enum value\n\n Predicate<String> isUserInputApply;\n\n InputType(Predicate<String> isUserInputApply) {\n this.isUserInputApply = isUserInputApply;\n }\n\n public static InputType determineInputType(String userInput) {\n return Arrays.stream(values())\n .filter(inType -> inType.isUserInputApply.test(userInput))\n .findFirst()\n .orElse(CALCULATION);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T15:11:08.177",
"Id": "458985",
"Score": "0",
"body": "Hi @Sharon Ben Asher, thanks for taking a look! I think I've underestimated the usefulness of enum! One question though, my main class is set up the way it is because I'm following the advice of this short article https://coderanch.com/wiki/660020/Main-Pain. Do you disagree with this practice or I am applying it unnecessarily?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T18:47:54.170",
"Id": "459001",
"Score": "0",
"body": "My advice was to move main *as is* into Calculator, so it remains short."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:18:12.423",
"Id": "459019",
"Score": "0",
"body": "Ah, my mistake!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T08:23:04.623",
"Id": "234624",
"ParentId": "234542",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234624",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T16:45:27.227",
"Id": "234542",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"calculator"
],
"Title": "A calculator with support for large integers and variables"
}
|
234542
|
<p>I've wrote a little program to play Tic-Tac-Toe:</p>
<pre class="lang-java prettyprint-override"><code>public class Control {
public static void main(String args[]) {
Gui gui = new Gui();
}
}
</code></pre>
<p>The following classed is used for applying the rules of tic-tac-toe:</p>
<pre class="lang-java prettyprint-override"><code>import javax.swing.*;
public class TicTacToe {
public static int count = 0;
public static String[][] board = new String[3][3];
public boolean test = true;
public void buttonClicked(JButton button) {
if(test) {
if(button.getText().equals("")) {
count++;
if(count % 2 == 1) {
button.setText("X");
}
if(count % 2 == 0) {
button.setText("O");
}
}
}
}
public void gameRules(JButton button) {
if(test) {
//"X" or "O"?
String string = button.getText();
//Gives coordinates of the button
int x = Character.getNumericValue(button.getName().charAt(0));
int y = Character.getNumericValue(button.getName().charAt(1));
board[x][y] = string;
if(board[0][0] != null && board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) {
JOptionPane.showMessageDialog(null,string + " won.");
test = false;
}
else if(board[0][2] != null && board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0])) {
JOptionPane.showMessageDialog(null,string + " won.");
test = false;
}
else if(count == 9) {
JOptionPane.showMessageDialog(null, "draw.");
test = false;
}
else {
for (int i = 0; i < 3; i++) {
if (board[i][0] != null && board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2])) {
JOptionPane.showMessageDialog(null, string + " won.");
test = false;
break;
}
if (board[0][i] != null && board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i])) {
JOptionPane.showMessageDialog(null, string + " won.");
test = false;
break;
}
}
}
}
}
}
</code></pre>
<p>And finally the class for the GUI:</p>
<pre class="lang-java prettyprint-override"><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui {
public Gui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
TicTacToe ticTacToe = new TicTacToe();
panel.setLayout(new java.awt.GridLayout(3, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++) {
final JButton button = new JButton();
String string = i + "" + j;
button.setText("");
button.setName(string);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
ticTacToe.buttonClicked(button);
ticTacToe.gameRules(button);
}
});
button.setFont(new Font("Arial", Font.PLAIN, 40));
button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel.add(button);
}
}
frame.add(panel);
frame.setSize(400,400);
frame.setVisible(true);
}
}
</code></pre>
<p>I would appreciate any suggestions to improve the code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T18:50:55.497",
"Id": "458710",
"Score": "0",
"body": "What's the point of the `test` variable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:17:51.473",
"Id": "458714",
"Score": "0",
"body": "When on player won, it is set to false, and so noone will be able to add another \"X\" or \"O\" to the grid."
}
] |
[
{
"body": "<h2>Event Dispatching Thread</h2>\n\n<p>Since Swing is not thread safe, all Swing UI component creation and modification should be done on the Event Dispatching Thread (EDT). It isn’t a problem with this program, but you could run into it if you also created (say) a <code>javax.swing.Timer</code> in your initiation.</p>\n\n<p>It is an easy change to create the GUI on the EDT. Instead of <code>Gui gui = new Gui();</code> use:</p>\n\n<pre><code>SwingUtilities.invokeLater(Gui::new);\n</code></pre>\n\n<h2>But I Won???</h2>\n\n<p>Play a game, with these moves:</p>\n\n<pre><code> O | X | O\n---+---+---\n X | | X\n---+---+---\n O | X | O\n</code></pre>\n\n<p>And then put the final X in the center. You win in two directions at once, but because <code>count == 9</code>, the game is a draw?</p>\n\n<h2>Separate GUI / Logic</h2>\n\n<p>It looks like you tried to separate the GUI from the game logic, but:</p>\n\n<ul>\n<li><code>TicTacToe</code> still accesses/manipulates <code>JButton</code> objects</li>\n<li><code>TicTacToe</code> shows <code>JOptionPane</code> dialogs</li>\n</ul>\n\n<p>So, it is not separate from the Swing GUI; you could not reuse it in an SWT or JavaFX application.</p>\n\n<p>The <code>TicTacToe</code> class should have functions something like:</p>\n\n<ul>\n<li><code>bool isValidMove(int x, int y)</code></li>\n<li><code>void makeMove(int x, int y)</code></li>\n<li><code>bool isGameOver()</code></li>\n<li><code>Player getWinner()</code></li>\n</ul>\n\n<p>and the GUI should convert buttons into x, y locations, display messages, etc</p>\n\n<h2><code>static</code></h2>\n\n<p>Can you play a second game? No. There is no way to reset <code>count</code> for a new game. It would continue to count above 9 with additional moves!</p>\n\n<p>Can you play two games at once? No! There is only one <code>board</code> object. Two simultaneous games would corrupt each other’s <code>board</code> and <code>count</code> variables!</p>\n\n<p>Why are these variables <code>static</code>? It prevents multiple <code>TicTacToe</code> objects from being created. If you removed <code>static</code> from the variables, you could start a new game by creating a new <code>TicTacToe</code> object (and resetting the GUI). </p>\n\n<p><strong>Advanced:</strong> Also, you could allow the computer to experiment with different moves, and look several moves in the future, ... but only if you could create these extra <code>TicTacToe</code> boards which aren’t the ones being displayed in the UI.</p>\n\n<h2>Simplify Logic</h2>\n\n<pre><code> if(count % 2 == 1) {\n button.setText(\"X\");\n }\n if(count % 2 == 0) {\n button.setText(\"O\");\n }\n</code></pre>\n\n<p>If <code>count % 2</code> is not <code>1</code>, it must be <code>0</code>. Use an <code>else</code> clause:</p>\n\n<pre><code> if(count % 2 == 1) {\n button.setText(\"X\");\n } else {\n button.setText(\"O\");\n }\n</code></pre>\n\n<hr>\n\n<p>This test is very verbose:</p>\n\n<pre><code> if(board[0][0] != null && board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2])) {\n</code></pre>\n\n<p>Who can win on any turn? The player that just made a move, of course. And their symbol is stored in <code>string</code> (a terrible variable name, by the way).</p>\n\n<p>So if the above test was to pass, all the symbols would equal <code>string</code>, so you could write it a little more concisely as:</p>\n\n<pre><code> if(string.equals(board[0][0]) && string.equals(board[1][1]) && string.equals(board[2][2]) {\n</code></pre>\n\n<p>If you defined constants (or better, used <code>enum</code> if you are familiar with them):</p>\n\n<pre><code> public final static String PLAYER_X = \"X\";\n public final static String PLAYER_O = \"O\";\n</code></pre>\n\n<p>and explicitly set the contents of <code>board[][]</code> to either one of those objects, then you could safely test for object <strong>identity</strong>, instead of <strong>equality</strong>:</p>\n\n<pre><code> if(board[0][0] == player && board[1][1] == player && board[2][2] == player) {\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T22:23:02.710",
"Id": "234561",
"ParentId": "234544",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "234561",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T16:58:40.943",
"Id": "234544",
"Score": "2",
"Tags": [
"java",
"tic-tac-toe"
],
"Title": "Tic-Tac-Toe in Java with GUI"
}
|
234544
|
<p>I have a 60GB file of domain names. Some of them are repeated several times and some of them have sub domains that need stripping out too.</p>
<p>For example this might give you a better idea of what the file looks like.</p>
<pre><code>email.example.com
test.staging.lol.uni.ac.uk
hello.test.com
email.example.com
test.com
</code></pre>
<p>After parsing the file I would like to create another file that contains.</p>
<pre><code>example.com
uni.ac.uk
test.com
</code></pre>
<p>As you can see duplicate base domains are removed and we've left with just the base domain and the top level domain with no duplicates.</p>
<p>Here is my attempt so far and while it works, it's dog slow.</p>
<pre><code> string[] topLevelDomains = new string[] { ".travelersinsurance", ".accountants", ".lamborghini", ".progressive", ".productions", ".theguardian", ".blackfriday", ".engineering", ".enterprises", ".photography", ".investments", ".motorcycles", ".blockbuster", ".contractors", ".rightathome", ".schaeffler", ".foundation", ".swiftcover", ".apartments", ".associates", ".supersport", ".immobilien", ".industries", ".healthcare", ".africa.com", ".technology", ".eurovision", ".nationwide", ".consulting", ".restaurant", ".republican", ".accountant", ".protection", ".properties", ".university", ".directory", ".community", ".education", ".montblanc", ".accenture", ".microsoft", ".melbourne", ".marshalls", ".marketing", ".financial", ".lifestyle", ".frontdoor", ".lancaster", ".solutions", ".barcelona", ".insurance", ".institute", ".analytics", ".police.uk", ".homegoods", ".amsterdam", ".security", ".partners", ".computer", ".services", ".telecity", ".lighting", ".showtime", ".football", ".clothing", ".pharmacy", ".training", ".cleaning", ".attorney", ".budapest", ".observer", ".holdings", ".brussels", ".supplies", ".broadway", ".guardian", ".graphics", ".download", ".capetown", ".discover", ".discount", ".uconnect", ".diamonds", ".ventures", ".business", ".builders", ".democrat", ".pictures", ".feedback", ".plumbing", ".exchange", ".mortgage", ".esurance", ".software", ".engineer", ".catering", ".property", ".delivery", ".genting", ".gallery", ".hosting", ".hoteles", ".holiday", ".hangout", ".hamburg", ".guitars", ".watches", ".weather", ".website", ".wedding", ".whoswho", ".windows", ".winners", ".youtube", ".zuerich", ".flowers", ".florist", ".flights", ".fitness", ".fishing", ".finance", ".markets", ".fashion", ".farmers", ".express", ".exposed", ".network", ".domains", ".cruises", ".organic", ".courses", ".coupons", ".country", ".cooking", ".contact", ".company", ".cologne", ".college", ".citadel", ".pioneer", ".caravan", ".capital", ".recipes", ".brother", ".rentals", ".booking", ".science", ".singles", ".surgery", ".systems", ".theatre", ".tickets", ".trading", ".academy", ".kitchen", ".com.vc", ".aip.ee", ".org.ee", ".org.uz", ".net.uz", ".com.uz", ".net.lr", ".fie.ee", ".org.uy", ".net.uy", ".mil.uy", ".gub.uy", ".edu.uy", ".com.uy", ".com.eg", ".nsn.us", ".med.ee", ".isa.us", ".fed.us", ".dni.us", ".edu.eg", ".org.lr", ".plc.uk", ".org.uk", ".nhs.uk", ".net.uk", ".gov.lr", ".ltd.uk", ".gov.uk", ".edu.lr", ".com.lr", ".eun.eg", ".org.ug", ".com.ug", ".edu.bh", ".com.ar", ".com.bh", ".grp.lk", ".gov.bf", ".ltd.lk", ".gov.eg", ".web.lk", ".soc.lk", ".com.vi", ".k12.vi", ".net.vi", ".org.vi", ".lib.ee", ".com.vn", ".ngo.lk", ".net.vn", ".org.vn", ".edu.vn", ".edu.lk", ".gov.vn", ".org.lk", ".int.vn", ".com.lk", ".int.lk", ".biz.vn", ".net.lk", ".sch.lk", ".pro.vn", ".com.vu", ".edu.vu", ".gov.lk", ".net.vu", ".org.vu", ".gov.ee", ".edu.ee", ".cn.com", ".com.ws", ".gov.lc", ".net.ws", ".org.ws", ".edu.lc", ".org.lc", ".gov.ws", ".mar.it", ".net.lc", ".edu.ws", ".com.lc", ".photos", ".mil.ec", ".gob.ec", ".org.lb", ".alt.za", ".net.lb", ".edu.za", ".gov.za", ".gov.lb", ".law.za", ".edu.lb", ".com.lb", ".mil.za", ".net.za", ".ngo.za", ".nis.za", ".org.hu", ".org.la", ".nom.za", ".com.la", ".per.la", ".gov.la", ".org.za", ".edu.la", ".web.za", ".gov.ec", ".edu.ec", ".abarth", ".org.ua", ".net.ua", ".physio", ".gov.ua", ".edu.ua", ".com.ua", ".mil.eg", ".net.la", ".int.la", ".piaget", ".com.kz", ".org.ec", ".mil.tz", ".mil.kz", ".abbott", ".abbvie", ".gov.kz", ".net.kz", ".edu.kz", ".pro.ec", ".med.ec", ".k12.ec", ".active", ".idv.tw", ".org.tw", ".net.tw", ".com.tw", ".mil.tw", ".gov.tw", ".edu.tw", ".net.eg", ".org.eg", ".edu.tt", ".gov.tt", ".org.kz", ".fin.ec", ".net.ec", ".com.de", ".net.ky", ".com.ec", ".africa", ".int.tt", ".pro.tt", ".agency", ".biz.tt", ".net.tt", ".org.tt", ".com.tt", ".org.ky", ".sci.eg", ".travel", ".art.dz", ".com.ky", ".kep.tr", ".edu.tr", ".k12.tr", ".mil.tr", ".pol.tr", ".bel.tr", ".gov.tr", ".tel.tr", ".pol.dz", ".bbs.tr", ".gov.ky", ".edu.ky", ".com.se", ".gen.tr", ".web.tr", ".org.tr", ".net.tr", ".biz.tr", ".airbus", ".com.tr", ".com.es", ".nom.es", ".mil.to", ".edu.to", ".org.to", ".net.to", ".gov.to", ".com.to", ".org.es", ".airtel", ".alipay", ".edu.dz", ".alsace", ".rnu.tn", ".rns.tn", ".alstom", ".gov.dz", ".pictet", ".de.com", ".anquan", ".org.tn", ".net.tn", ".nat.tn", ".net.dz", ".ind.tn", ".gov.tn", ".fin.tn", ".ens.tn", ".com.tn", ".gob.es", ".edu.tm", ".mil.tm", ".gov.tm", ".nom.tm", ".net.tm", ".org.tm", ".org.bb", ".com.tm", ".edu.es", ".gov.tl", ".com.et", ".gov.et", ".web.tj", ".org.dz", ".org.tj", ".nic.tj", ".net.tj", ".net.bb", ".mil.tj", ".int.tj", ".gov.tj", ".lom.it", ".edu.tj", ".com.tj", ".eu.com", ".biz.tj", ".gov.bb", ".org.et", ".edu.bb", ".net.th", ".com.bb", ".lig.it", ".gb.com", ".laz.it", ".fvg.it", ".edu.et", ".biz.et", ".aramco", ".emr.it", ".net.et", ".com.dz", ".org.sz", ".biz.bb", ".gb.net", ".com.fr", ".org.sy", ".com.sy", ".mil.sy", ".net.sy", ".gov.sy", ".edu.sy", ".web.do", ".gov.sx", ".nom.fr", ".red.sv", ".org.sv", ".gob.sv", ".edu.sv", ".com.sv", ".prd.fr", ".sld.do", ".org.do", ".hu.com", ".author", ".net.do", ".hu.net", ".mil.do", ".spb.su", ".gov.do", ".cam.it", ".gob.do", ".nov.su", ".edu.do", ".com.do", ".art.do", ".bayern", ".gov.dm", ".edu.dm", ".org.dm", ".net.dm", ".com.dm", ".jp.net", ".cal.it", ".berlin", ".pro.cy", ".bharti", ".mil.kr", ".org.cy", ".net.cy", ".kr.com", ".bas.it", ".blanco", ".ltd.cy", ".gov.cy", ".com.cy", ".org.st", ".net.st", ".mil.st", ".gov.st", ".biz.cy", ".edu.st", ".no.com", ".com.st", ".qc.com", ".ru.com", ".abr.it", ".org.so", ".net.so", ".com.so", ".gov.cx", ".org.cw", ".net.cw", ".org.sn", ".edu.it", ".edu.sn", ".com.sn", ".art.sn", ".tra.kp", ".bostik", ".org.sl", ".gov.sl", ".edu.sl", ".net.sl", ".com.sl", ".cci.fr", ".edu.cw", ".broker", ".rep.kp", ".mil.sh", ".org.sh", ".gov.sh", ".net.sh", ".com.sh", ".com.cw", ".per.sg", ".edu.sg", ".gov.sg", ".org.sg", ".net.sg", ".com.sg", ".inf.cu", ".gov.cu", ".net.cu", ".org.cu", ".edu.cu", ".com.cu", ".org.kp", ".camera", ".gov.kp", ".com.ge", ".edu.kp", ".com.kp", ".com.ba", ".edu.ge", ".org.se", ".gov.ge", ".gov.kn", ".org.ge", ".mil.ge", ".edu.kn", ".net.ge", ".career", ".org.kn", ".net.kn", ".pvt.ge", ".gov.it", ".net.gg", ".org.gg", ".fhv.se", ".quebec", ".sa.com", ".com.gh", ".edu.gh", ".gov.gh", ".org.gh", ".casino", ".racing", ".mil.gh", ".mil.ba", ".com.gi", ".ltd.gi", ".gov.ba", ".gov.sd", ".realty", ".med.sd", ".edu.sd", ".org.sd", ".net.sd", ".com.sd", ".gov.gi", ".edu.sc", ".org.sc", ".net.sc", ".gov.sc", ".com.sc", ".mod.gi", ".org.sb", ".net.sb", ".gov.sb", ".edu.sb", ".com.sb", ".edu.gi", ".sch.sa", ".edu.sa", ".pub.sa", ".med.sa", ".gov.sa", ".org.sa", ".net.sa", ".com.sa", ".org.gi", ".web.co", ".mil.rw", ".int.rw", ".edu.ba", ".com.rw", ".int.is", ".edu.rw", ".net.rw", ".gov.rw", ".com.km", ".rec.co", ".mil.ru", ".gov.ru", ".org.co", ".nom.co", ".center", ".snz.ru", ".net.co", ".mil.co", ".int.co", ".chanel", ".nkz.ru", ".ass.km", ".gov.co", ".mil.km", ".edu.km", ".chrome", ".church", ".kms.ru", ".circle", ".org.is", ".cmw.ru", ".prd.km", ".edu.co", ".claims", ".gov.km", ".clinic", ".nom.km", ".com.co", ".org.km", ".vrn.ru", ".gov.is", ".coffee", ".comsec", ".condos", ".coupon", ".credit", ".com.ki", ".reisen", ".udm.ru", ".gov.ki", ".org.ki", ".net.ki", ".biz.ki", ".tsk.ru", ".edu.ki", ".net.ba", ".tom.ru", ".mil.kg", ".dating", ".datsun", ".stv.ru", ".gov.kg", ".spb.ru", ".edu.kg", ".com.kg", ".net.kg", ".dealer", ".org.kg", ".degree", ".rnd.ru", ".ptz.ru", ".org.ba", ".edu.is", ".dental", ".edu.an", ".design", ".com.is", ".nsk.ru", ".net.is", ".nov.ru", ".org.an", ".direct", ".net.an", ".msk.ru", ".se.com", ".com.an", ".org.al", ".biz.az", ".repair", ".doosan", ".report", ".mil.jo", ".gov.jo", ".sch.jo", ".edu.jo", ".net.jo", ".dunlop", ".org.jo", ".khv.ru", ".dupont", ".durban", ".com.jo", ".pro.az", ".org.je", ".net.je", ".sch.ir", ".review", ".emerck", ".energy", ".jar.ru", ".org.ir", ".net.ir", ".gov.ie", ".net.al", ".estate", ".gov.ir", ".events", ".expert", ".mil.az", ".us.org", ".mil.al", ".family", ".cbg.ru", ".rocher", ".web.id", ".bir.ru", ".mil.cn", ".org.cn", ".se.net", ".net.cn", ".gov.cn", ".edu.cn", ".rogers", ".viajes", ".org.ru", ".net.ru", ".int.ru", ".edu.ru", ".com.ru", ".net.iq", ".com.gl", ".gov.al", ".gov.rs", ".edu.az", ".edu.rs", ".org.rs", ".viking", ".edu.gl", ".www.ro", ".com.cn", ".org.az", ".net.cm", ".rec.ro", ".flickr", ".nom.ro", ".villas", ".edu.al", ".org.ro", ".com.ro", ".net.gl", ".nom.re", ".gov.cm", ".com.re", ".org.gl", ".sch.qa", ".org.qa", ".net.qa", ".com.cm", ".mil.qa", ".gov.qa", ".edu.qa", ".com.qa", ".gov.az", ".org.py", ".net.py", ".mil.py", ".gov.py", ".edu.py", ".com.al", ".com.py", ".com.gn", ".mil.cl", ".int.az", ".net.az", ".ryukyu", ".com.az", ".safety", ".edu.gn", ".virgin", ".com.pt", ".org.ai", ".int.pt", ".edu.pt", ".org.pt", ".gov.pt", ".net.pt", ".gov.gn", ".net.ps", ".org.ps", ".com.ps", ".plo.ps", ".sec.ps", ".gov.ps", ".edu.ps", ".org.gn", ".sakura", ".gob.cl", ".gov.cl", ".futbol", ".vision", ".org.iq", ".gallup", ".net.gn", ".com.aw", ".net.ai", ".est.pr", ".int.ci", ".garden", ".biz.pr", ".pro.pr", ".sanofi", ".edu.pr", ".gov.pr", ".org.pr", ".net.pr", ".com.pr", ".com.gp", ".net.gp", ".net.pn", ".edu.pn", ".org.pn", ".school", ".gov.pn", ".net.ci", ".edu.gp", ".com.iq", ".george", ".schule", ".edu.ci", ".mil.iq", ".edu.iq", ".giving", ".gov.iq", ".com.ai", ".uk.com", ".global", ".com.io", ".waw.pl", ".off.ai", ".com.ci", ".voting", ".org.ci", ".gov.cd", ".vic.au", ".nom.ag", ".google", ".uk.net", ".tas.au", ".eu.int", ".gratis", ".qld.au", ".us.com", ".voyage", ".uy.com", ".mil.in", ".vuelos", ".gov.in", ".walter", ".nsw.au", ".res.in", ".health", ".warman", ".edu.in", ".hermes", ".shouji", ".hiphop", ".act.au", ".sch.id", ".hockey", ".nic.in", ".ind.in", ".webcam", ".gov.bz", ".asn.au", ".edu.bz", ".org.bz", ".net.bz", ".hughes", ".gov.au", ".com.bz", ".gen.in", ".com.by", ".mil.by", ".gov.by", ".org.bw", ".net.ag", ".org.in", ".imamat", ".net.in", ".org.bt", ".net.bt", ".gov.bt", ".insure", ".org.ag", ".intuit", ".edu.ac", ".edu.bt", ".com.bt", ".gov.bs", ".edu.bs", ".jaguar", ".org.bs", ".net.bs", ".com.bs", ".zlg.br", ".net.id", ".vet.br", ".com.ag", ".tur.br", ".joburg", ".trd.br", ".tmp.br", ".teo.br", ".juegos", ".kaufen", ".srv.br", ".slg.br", ".rec.br", ".kinder", ".kindle", ".edu.af", ".qsl.br", ".psi.br", ".psc.br", ".pro.br", ".kyknet", ".za.com", ".elk.pl", ".lancia", ".ppg.br", ".org.br", ".latino", ".odo.br", ".lawyer", ".ntr.br", ".net.af", ".lefrak", ".biz.id", ".not.br", ".edu.au", ".net.br", ".mus.br", ".soccer", ".mil.br", ".org.af", ".med.br", ".com.af", ".mat.br", ".social", ".lel.br", ".living", ".org.au", ".leg.br", ".gov.af", ".locker", ".net.au", ".jus.br", ".jor.br", ".london", ".mil.id", ".gr.com", ".inf.br", ".ind.br", ".imb.br", ".gov.br", ".org.im", ".ggf.br", ".luxury", ".com.au", ".madrid", ".g12.br", ".maison", ".makeup", ".fst.br", ".net.im", ".market", ".mattel", ".fot.br", ".fnd.br", ".ven.it", ".vda.it", ".far.br", ".eti.br", ".etc.br", ".esp.br", ".vao.it", ".eng.br", ".emp.br", ".edu.br", ".eco.br", ".ecn.br", ".gov.pl", ".com.ac", ".mobily", ".cnt.br", ".mil.ae", ".cng.br", ".cim.br", ".sos.pl", ".bmd.br", ".monash", ".sex.pl", ".rel.pl", ".gov.ae", ".in.net", ".mormon", ".com.im", ".nom.pl", ".moscow", ".mil.pl", ".bio.br", ".xihuan", ".ato.br", ".art.br", ".gsm.pl", ".arq.br", ".edu.pl", ".biz.pl", ".gov.as", ".atm.pl", ".mutual", ".aid.pl", ".org.pl", ".net.pl", ".com.pl", ".org.gp", ".sch.ae", ".gos.pk", ".gop.pk", ".gon.pk", ".gok.pk", ".gob.pk", ".gov.pk", ".web.pk", ".biz.pk", ".fam.pk", ".org.pk", ".edu.pk", ".net.pk", ".com.pk", ".nagoya", ".com.gr", ".mil.ph", ".ngo.ph", ".edu.ph", ".gov.ph", ".org.ph", ".net.ph", ".com.ph", ".edu.gr", ".edu.pf", ".org.pf", ".com.pf", ".net.gr", ".net.pe", ".com.pe", ".org.pe", ".mil.pe", ".nom.pe", ".gob.pe", ".edu.pe", ".org.gr", ".nom.pa", ".med.pa", ".abo.pa", ".ing.pa", ".net.pa", ".edu.pa", ".sld.pa", ".org.pa", ".com.pa", ".gob.pa", ".xperia", ".gov.gr", ".com.gt", ".pro.om", ".org.om", ".net.om", ".natura", ".med.om", ".gov.om", ".edu.om", ".com.om", ".studio", ".edu.gt", ".agr.br", ".adv.br", ".org.nz", ".net.nz", ".adm.br", ".mil.nz", ".org.ae", ".mil.bo", ".iwi.nz", ".net.bo", ".yachts", ".gen.nz", ".org.bo", ".cri.nz", ".com.br", ".gob.gt", ".ind.gt", ".com.nr", ".net.nr", ".org.nr", ".edu.nr", ".gov.nr", ".int.bo", ".biz.nr", ".mil.gt", ".net.gt", ".net.ae", ".org.gt", ".gob.bo", ".mil.ng", ".gov.ng", ".sch.ng", ".org.ng", ".net.ng", ".gov.bo", ".edu.ng", ".com.ng", ".co.com", ".edu.bo", ".umb.it", ".nom.ad", ".nissan", ".supply", ".web.nf", ".rec.nf", ".per.nf", ".net.nf", ".com.nf", ".com.gy", ".net.gy", ".com.hk", ".edu.hk", ".gov.hk", ".org.na", ".com.na", ".com.bo", ".sydney", ".tos.it", ".taa.it", ".target", ".org.ac", ".mil.ac", ".pro.na", ".org.bm", ".idv.hk", ".net.bm", ".mil.my", ".edu.my", ".gov.my", ".org.my", ".net.my", ".com.my", ".net.hk", ".net.mx", ".edu.mx", ".gob.mx", ".org.mx", ".com.mx", ".org.hk", ".org.mw", ".net.mw", ".gov.bm", ".int.mw", ".gov.mw", ".edu.mw", ".edu.bm", ".com.mw", ".tattoo", ".biz.mw", ".tur.ar", ".com.hn", ".pro.mv", ".org.mv", ".net.mv", ".com.bm", ".office", ".mil.mv", ".int.mv", ".olayan", ".gov.mv", ".edu.mv", ".org.ar", ".com.mv", ".biz.mv", ".org.bi", ".edu.hn", ".museum", ".sic.it", ".net.ac", ".sex.hu", ".gov.mu", ".org.mu", ".net.mu", ".com.mu", ".org.hn", ".org.mt", ".net.mt", ".edu.mt", ".com.mt", ".net.hn", ".org.ms", ".net.ms", ".gov.ms", ".edu.ms", ".com.ms", ".mil.hn", ".gov.mr", ".gob.hn", ".net.ar", ".mil.ar", ".online", ".gov.mo", ".edu.mo", ".org.mo", ".net.mo", ".com.mo", ".com.hr", ".org.mn", ".edu.mn", ".gov.mn", ".com.ht", ".edu.bi", ".org.ml", ".net.ml", ".gov.ml", ".com.bi", ".edu.ml", ".com.ml", ".oracle", ".orange", ".inf.mk", ".gov.mk", ".edu.mk", ".net.mk", ".org.mk", ".com.mk", ".tennis", ".otsuka", ".int.ar", ".gov.ar", ".com.mg", ".mil.mg", ".edu.mg", ".gob.ar", ".prd.mg", ".gov.mg", ".nom.mg", ".org.mg", ".net.ht", ".gov.bh", ".its.me", ".gov.me", ".sar.it", ".edu.me", ".org.me", ".net.me", ".gov.ac", ".pro.ht", ".org.ht", ".org.bh", ".tienda", ".med.ht", ".pug.it", ".edu.ar", ".org.ma", ".gov.ma", ".net.ma", ".pmn.it", ".art.ht", ".ae.org", ".org.ly", ".med.ly", ".sch.ly", ".edu.ly", ".plc.ly", ".gov.ly", ".net.ly", ".com.ly", ".net.bh", ".ar.com", ".asn.lv", ".net.lv", ".br.com", ".mil.lv", ".org.lv", ".gov.lv", ".edu.lv", ".com.lv", ".pol.ht", ".mol.it", ".gov.lt", ".edu.ht", ".org.ls", ".msk.su", ".total", ".ge.it", ".tours", ".fr.it", ".pb.ao", ".co.ao", ".fm.it", ".trade", ".trust", ".fi.it", ".fg.it", ".og.ao", ".gv.ao", ".fe.it", ".fc.it", ".ed.ao", ".en.it", ".tunes", ".cz.it", ".ct.it", ".cs.it", ".cr.it", ".co.it", ".cn.it", ".cl.it", ".ci.it", ".ch.it", ".vegas", ".ce.it", ".cb.it", ".video", ".vista", ".ca.it", ".co.uz", ".co.vi", ".me.uk", ".co.uk", ".ac.uk", ".ne.ug", ".go.ug", ".sc.ug", ".ac.ug", ".or.ug", ".co.ug", ".zt.ua", ".zp.ua", ".vn.ua", ".uz.ua", ".te.ua", ".sm.ua", ".ac.vn", ".sb.ua", ".rv.ua", ".pl.ua", ".od.ua", ".mk.ua", ".lv.ua", ".lt.ua", ".lg.ua", ".kv.ua", ".ks.ua", ".kr.ua", ".km.ua", ".ac.za", ".co.za", ".kh.ua", ".if.ua", ".dp.ua", ".dn.ua", ".cv.ua", ".cr.ua", ".cn.ua", ".ck.ua", ".tm.za", ".in.ua", ".tv.tz", ".sc.tz", ".or.tz", ".ne.tz", ".me.tz", ".go.tz", ".co.tz", ".ac.tz", ".actor", ".adult", ".aetna", ".co.tt", ".nc.tr", ".dr.tr", ".av.tr", ".tv.tr", ".co.tm", ".go.tj", ".co.tj", ".ac.tj", ".or.th", ".mi.th", ".in.th", ".go.th", ".co.th", ".ac.th", ".archi", ".ac.sz", ".co.sz", ".audio", ".autos", ".azure", ".baidu", ".beats", ".tm.cy", ".bible", ".bingo", ".black", ".boats", ".co.st", ".tm.fr", ".ac.cy", ".boots", ".bosch", ".build", ".tm.se", ".sa.cr", ".pp.se", ".or.cr", ".cards", ".go.cr", ".fi.cr", ".ed.cr", ".co.gg", ".co.cr", ".fh.se", ".bd.se", ".ac.se", ".ac.cr", ".tv.sd", ".co.rw", ".ac.rw", ".co.gl", ".chase", ".cheap", ".chloe", ".cisco", ".citic", ".click", ".cloud", ".coach", ".codes", ".crown", ".tw.cn", ".mo.cn", ".cymru", ".hk.cn", ".dabur", ".zj.cn", ".dance", ".yn.cn", ".xz.cn", ".xj.cn", ".tj.cn", ".sx.cn", ".deals", ".sn.cn", ".sh.cn", ".sd.cn", ".sc.cn", ".qh.cn", ".nx.cn", ".nm.cn", ".ln.cn", ".dodge", ".jx.cn", ".js.cn", ".jl.cn", ".drive", ".hn.cn", ".hl.cn", ".dubai", ".hi.cn", ".he.cn", ".hb.cn", ".ha.cn", ".earth", ".gx.cn", ".edeka", ".email", ".epost", ".epson", ".gz.cn", ".gs.cn", ".gd.cn", ".fj.cn", ".cq.cn", ".faith", ".bj.cn", ".ah.cn", ".fedex", ".final", ".pp.ru", ".ac.ru", ".in.rs", ".ac.rs", ".co.rs", ".ac.cn", ".nt.ro", ".tm.ro", ".ac.gn", ".co.cm", ".go.pw", ".ed.pw", ".or.pw", ".ne.pw", ".co.pw", ".forex", ".forum", ".co.cl", ".md.ci", ".gallo", ".ac.pr", ".games", ".go.ci", ".co.pn", ".ac.ci", ".ed.ci", ".gifts", ".gives", ".glade", ".glass", ".co.ci", ".globo", ".gmail", ".or.ci", ".gc.ca", ".yk.ca", ".sk.ca", ".qc.ca", ".pe.ca", ".green", ".gripe", ".group", ".gucci", ".on.ca", ".guide", ".nu.ca", ".nt.ca", ".ns.ca", ".nl.ca", ".nf.ca", ".nb.ca", ".mb.ca", ".bc.ca", ".ab.ca", ".homes", ".horse", ".house", ".of.by", ".iinet", ".ikano", ".co.bw", ".intel", ".irish", ".jetzt", ".tv.br", ".koeln", ".kyoto", ".av.it", ".at.it", ".weber", ".weibo", ".ar.it", ".aq.it", ".ap.it", ".ao.it", ".an.it", ".al.it", ".works", ".ag.it", ".world", ".ac.ae", ".xerox", ".yahoo", ".co.ae", ".zippo", ".id.ir", ".co.ir", ".ac.ir", ".ac.in", ".za.bz", ".co.in", ".tv.im", ".tt.im", ".co.im", ".ac.im", ".or.id", ".my.id", ".go.id", ".co.id", ".ac.id", ".co.ca", ".co.nl", ".nokia", ".co.na", ".ws.na", ".tv.na", ".cc.na", ".in.na", ".ca.na", ".mx.na", ".us.na", ".dr.na", ".or.na", ".nowtv", ".co.mw", ".ac.mw", ".omega", ".or.mu", ".co.mu", ".ac.mu", ".iz.hr", ".or.bi", ".osaka", ".co.bi", ".co.mg", ".tm.mg", ".ac.me", ".co.me", ".tm.mc", ".paris", ".ac.ma", ".co.ma", ".id.ly", ".parts", ".id.lv", ".party", ".co.ls", ".ac.lk", ".photo", ".co.hu", ".co.lc", ".ac.be", ".tm.hu", ".tv.bb", ".pizza", ".place", ".poker", ".co.bb", ".praxi", ".press", ".prime", ".rs.ba", ".sc.kr", ".re.kr", ".pe.kr", ".or.kr", ".ne.kr", ".ms.kr", ".kg.kr", ".hs.kr", ".go.kr", ".es.kr", ".co.kr", ".ac.kr", ".promo", ".co.ba", ".quest", ".rehab", ".tm.km", ".reise", ".or.jp", ".ne.jp", ".lg.jp", ".gr.jp", ".go.jp", ".ed.jp", ".co.jp", ".ad.jp", ".ac.jp", ".co.je", ".vv.it", ".vt.it", ".vs.it", ".vr.it", ".ricoh", ".vi.it", ".pp.az", ".rocks", ".rodeo", ".ve.it", ".vc.it", ".vb.it", ".va.it", ".ud.it", ".tv.it", ".ts.it", ".tr.it", ".tp.it", ".to.it", ".tn.it", ".salon", ".te.it", ".ta.it", ".sv.it", ".wa.au", ".ss.it", ".sr.it", ".sp.it", ".sener", ".so.it", ".seven", ".si.it", ".sa.au", ".sa.it", ".nt.au", ".ro.it", ".rn.it", ".rm.it", ".shoes", ".ri.it", ".rg.it", ".oz.au", ".id.au", ".re.it", ".rc.it", ".ra.it", ".pz.it", ".pv.it", ".pu.it", ".pt.it", ".skype", ".pr.it", ".sling", ".smart", ".po.it", ".pn.it", ".smile", ".pi.it", ".pg.it", ".solar", ".pe.it", ".pd.it", ".pc.it", ".or.at", ".space", ".gv.at", ".co.at", ".pa.it", ".ot.it", ".ac.at", ".or.it", ".stada", ".store", ".og.it", ".nu.it", ".study", ".no.it", ".style", ".sucks", ".na.it", ".mt.it", ".ms.it", ".swiss", ".mo.it", ".mn.it", ".tatar", ".mi.it", ".me.it", ".mc.it", ".mb.it", ".lu.it", ".lt.it", ".lo.it", ".li.it", ".tires", ".tirol", ".le.it", ".lc.it", ".tmall", ".kr.it", ".today", ".is.it", ".tokyo", ".im.it", ".tools", ".gr.it", ".it.ao", ".go.it", ".toray", ".legal", ".lexus", ".mp.br", ".lilly", ".linde", ".lipsy", ".loans", ".locus", ".lotte", ".lotto", ".lupin", ".macys", ".mango", ".fm.br", ".media", ".miami", ".tm.pl", ".money", ".mopar", ".pc.pl", ".movie", ".am.br", ".nadex", ".ac.pa", ".co.om", ".tv.bo", ".nexus", ".co.nz", ".ac.nz", ".bv.nl", ".co.gy", ".nikon", ".ninja", ".bz.it", ".bt.it", ".bs.it", ".vodka", ".br.it", ".bo.it", ".bn.it", ".bl.it", ".bi.it", ".bg.it", ".wales", ".co.ag", ".ba.it", ".watch", ".co.ve", ".lease", ".prod", ".prof", ".able", ".surf", ".adac", ".yoga", ".talk", ".raid", ".ally", ".read", ".army", ".work", ".auto", ".reit", ".kiwi", ".baby", ".band", ".bank", ".taxi", ".land", ".rent", ".rest", ".info", ".rich", ".beer", ".best", ".life", ".like", ".jobs", ".bike", ".bing", ".limo", ".blog", ".blue", ".link", ".live", ".loan", ".bofa", ".loft", ".zero", ".bond", ".love", ".aero", ".team", ".luxe", ".buzz", ".room", ".cafe", ".rsvp", ".call", ".camp", ".tech", ".care", ".cars", ".casa", ".cash", ".meet", ".meme", ".mobi", ".menu", ".cbre", ".safe", ".mini", ".mint", ".cern", ".co.no", ".chat", ".city", ".club", ".cool", ".name", ".sale", ".tips", ".date", ".deal", ".moto", ".diet", ".dish", ".docs", ".b.br", ".save", ".duck", ".duns", ".post", ".navy", ".vote", ".fail", ".town", ".fans", ".farm", ".fast", ".fiat", ".film", ".fire", ".fish", ".toys", ".news", ".next", ".scot", ".ford", ".a.se", ".seat", ".b.se", ".c.se", ".d.se", ".e.se", ".f.se", ".seek", ".g.se", ".h.se", ".i.se", ".fund", ".nico", ".k.se", ".l.se", ".m.se", ".n.se", ".o.se", ".p.se", ".r.se", ".nike", ".zone", ".game", ".tube", ".s.se", ".t.se", ".u.se", ".w.se", ".x.se", ".y.se", ".z.se", ".sexy", ".gent", ".gift", ".show", ".gold", ".silk", ".site", ".golf", ".skin", ".xbox", ".goog", ".sohu", ".open", ".guge", ".guru", ".song", ".help", ".here", ".sony", ".weir", ".page", ".host", ".pars", ".spot", ".c.la", ".wiki", ".pics", ".imdb", ".zara", ".asia", ".immo", ".star", ".ping", ".pink", ".play", ".plus", ".wine", ".java", ".porn", ".gap", ".sap", ".run", ".fly", ".rio", ".fan", ".ren", ".esq", ".qvc", ".dwg", ".pru", ".dot", ".pin", ".dnp", ".pet", ".dev", ".ott", ".day", ".net", ".csc", ".ong", ".cfd", ".one", ".ceo", ".obi", ".cbs", ".ntt", ".edu", ".nra", ".xxx", ".now", ".abb", ".ngo", ".aco", ".new", ".aeg", ".nba", ".cba", ".mtn", ".anz", ".mov", ".car", ".moi", ".axa", ".gov", ".zip", ".mma", ".bbt", ".mlb", ".bcn", ".meo", ".bzh", ".med", ".bot", ".mba", ".bet", ".ltd", ".bio", ".lol", ".bmw", ".law", ".cal", ".yun", ".you", ".xyz", ".int", ".xin", ".wtf", ".wtc", ".wme", ".win", ".wed", ".vip", ".vet", ".ups", ".trv", ".top", ".thd", ".tci", ".tax", ".tab", ".stc", ".srt", ".srl", ".soy", ".sky", ".ski", ".sex", ".tel", ".mil", ".sas", ".foo", ".rip", ".fit", ".ril", ".eus", ".red", ".eat", ".pub", ".pnc", ".dog", ".pid", ".ooo", ".dad", ".onl", ".crs", ".biz", ".off", ".ceb", ".nyc", ".cbn", ".nrw", ".com", ".org", ".aaa", ".nhk", ".abc", ".nfl", ".ads", ".nec", ".msd", ".app", ".mom", ".bar", ".pro", ".bbc", ".mit", ".cab", ".men", ".buy", ".man", ".bid", ".bnl", ".lat", ".joy", ".jnj", ".jmp", ".iwc", ".itv", ".ist", ".ink", ".ing", ".ice", ".how", ".hiv", ".hbo", ".got", ".goo", ".cat", ".gmx", ".bom", ".sew", ".li", ".lc", ".ar", ".aq", ".lb", ".la", ".kz", ".ao", ".ky", ".kr", ".kp", ".kn", ".an", ".am", ".km", ".ki", ".kg", ".jp", ".jo", ".al", ".ai", ".je", ".ag", ".it", ".is", ".af", ".ir", ".iq", ".io", ".in", ".im", ".ae", ".ie", ".ad", ".cx", ".cz", ".de", ".dj", ".cw", ".cv", ".dk", ".dm", ".do", ".cu", ".dz", ".ec", ".cr", ".yt", ".ee", ".ws", ".wf", ".vu", ".vn", ".vi", ".co", ".vg", ".ve", ".vc", ".va", ".uz", ".eg", ".uy", ".us", ".uk", ".ug", ".ua", ".tz", ".tw", ".tv", ".tt", ".es", ".cn", ".tr", ".tp", ".to", ".cm", ".tn", ".tm", ".cl", ".et", ".tl", ".tk", ".tj", ".th", ".tg", ".tf", ".td", ".ci", ".ch", ".cg", ".cf", ".cd", ".cc", ".eu", ".fi", ".tc", ".fm", ".fo", ".fr", ".sz", ".ca", ".sy", ".sx", ".sv", ".bz", ".su", ".st", ".by", ".sr", ".bw", ".bv", ".so", ".sn", ".sm", ".bt", ".sl", ".sk", ".sj", ".si", ".bs", ".sh", ".sg", ".ga", ".gb", ".gd", ".ge", ".gf", ".gg", ".gh", ".gi", ".se", ".sd", ".sc", ".sb", ".sa", ".gl", ".rw", ".ru", ".rs", ".ro", ".re", ".gm", ".gn", ".qa", ".py", ".pw", ".pt", ".ps", ".gp", ".pr", ".pn", ".pm", ".pl", ".pk", ".gq", ".gr", ".ph", ".br", ".pf", ".pe", ".pa", ".gs", ".gt", ".bo", ".om", ".nz", ".nu", ".nr", ".no", ".bm", ".nl", ".gw", ".bj", ".gy", ".ng", ".nf", ".hk", ".ne", ".bi", ".nc", ".bh", ".bg", ".na", ".bf", ".be", ".my", ".mx", ".hm", ".bb", ".hn", ".mw", ".mv", ".mu", ".mt", ".ba", ".ms", ".mr", ".hr", ".mq", ".mp", ".az", ".ax", ".aw", ".mo", ".ht", ".mn", ".ml", ".mk", ".mh", ".mg", ".me", ".md", ".mc", ".ma", ".au", ".ly", ".lv", ".lu", ".at", ".as", ".lt", ".ls", ".lr", ".lk", ".hu", ".id", ".ac" };
HashSet<string> domainHashList = new HashSet<string>();
int lineNumber = 0;
double pc = 0;
double totalLines = 1906663905;
var t = Task.Run(() =>
{
using (var fileStream = File.OpenRead("F:\\domains-final\\domains\\domains-final.csv"))
{
using (var reader = new StreamReader(fileStream))
{
while (reader.Peek() >= 0)
{
lineNumber++;
pc = Math.Round((lineNumber / totalLines) * 100, 10);
Dispatcher.Invoke(() =>
{
lineLabel.Content = "Line number: " + lineNumber.ToString() + " Percentage: " + pc.ToString();
});
try
{
string line = reader.ReadLine();
if (!line.Contains('.')) continue;
foreach (string topLevelDomain in topLevelDomains)
{
string domain = line.Trim();
if (domain.EndsWith(topLevelDomain))
{
string cleanedDomainTemp = line.Replace(topLevelDomain, "");
if (!cleanedDomainTemp.Contains('.'))
{
string cleanedDomain = cleanedDomainTemp + topLevelDomain;
if (domainHashList.Contains(domain)) break;
domainHashList.Add(domain);
File.AppendAllText("F:\\domains-final\\domains\\doms.txt", domain + Environment.NewLine);
}
else
{
string cleanedDomain = cleanedDomainTemp.Split('.').Last() + topLevelDomain;
if (domainHashList.Contains(cleanedDomain)) break;
domainHashList.Add(cleanedDomain);
File.AppendAllText("F:\\domains-final\\domains\\doms.txt", cleanedDomain + Environment.NewLine);
}
break;
}
}
}
catch { }
}
}
}
});
</code></pre>
<p>I'm looking at my computer's resources while running this, and the disk access is at 0-1% and the CPU usage is at 30%, so I'm assuming I'm maxing out just one core.</p>
<p>I have some ideas but I'm not 100% sure how to implement them correctly as C# isn't my main language.</p>
<ol>
<li>Spawn more threads and use all CPU cores</li>
<li>Attempt to load 1/3 of the file into my 32GB of memory at a time</li>
<li>Buffer up the disk writing and write 1000 domains into the results file at a time</li>
<li>See if I can find a more efficient way of converting to base + TLD (but I can't find one so far)</li>
</ol>
<p>What improvements can I make to speed this code up?</p>
|
[] |
[
{
"body": "<p>When using more than one <code>Using</code> block you actually don't need to nest the second one inside of the first one, so this:</p>\n\n<pre><code>using (var fileStream = File.OpenRead(\"F:\\\\domains-final\\\\domains\\\\domains-final.csv\"))\n{\n using (var reader = new StreamReader(fileStream))\n {\n...\n</code></pre>\n\n<p>looks like this instead</p>\n\n<pre><code>using (var fileStream = File.OpenRead(\"F:\\\\domains-final\\\\domains\\\\domains-final.csv\"))\nusing (var reader = new StreamReader(fileStream))\n{\n...\n</code></pre>\n\n<p>inside of your foreach loop I would also invert the first if statement to dump out of the current iteration, this will lessen the amount of indentation that you have inside the foreach loop.</p>\n\n<p>in the if part of the if/else statement inside the foreach loop, you create the variable <code>cleanedDomain</code> but don't use it inside of that statement, once you leave the statement that variable is disposed of, you could remove that assignment as it could save you a little performance but it might not be noticeable. I removed it in the \"<em>After</em>\" code to clean up some noise.</p>\n\n<p>Foreach loop Before:</p>\n\n<pre><code>foreach (string topLevelDomain in topLevelDomains)\n{\n string domain = line.Trim();\n if (domain.EndsWith(topLevelDomain))\n {\n string cleanedDomainTemp = line.Replace(topLevelDomain, \"\");\n if (!cleanedDomainTemp.Contains('.'))\n {\n string cleanedDomain = cleanedDomainTemp + topLevelDomain;\n if (domainHashList.Contains(domain)) break;\n\n domainHashList.Add(domain);\n\n File.AppendAllText(\"F:\\\\domains-final\\\\domains\\\\doms.txt\", domain + Environment.NewLine);\n }\n else\n {\n string cleanedDomain = cleanedDomainTemp.Split('.').Last() + topLevelDomain;\n\n if (domainHashList.Contains(cleanedDomain)) break;\n\n domainHashList.Add(cleanedDomain);\n\n File.AppendAllText(\"F:\\\\domains-final\\\\domains\\\\doms.txt\", cleanedDomain + Environment.NewLine);\n }\n\n break;\n }\n}\n</code></pre>\n\n<p>Foreach Loop After:</p>\n\n<pre><code>foreach (string topLevelDomain in topLevelDomains)\n{\n string domain = line.Trim();\n if (!domain.EndsWith(topLevelDomain)) continue;\n\n string cleanedDomainTemp = line.Replace(topLevelDomain, \"\");\n if (!cleanedDomainTemp.Contains('.'))\n {\n if (domainHashList.Contains(domain)) break;\n\n domainHashList.Add(domain);\n File.AppendAllText(\"F:\\\\domains-final\\\\domains\\\\doms.txt\", domain + Environment.NewLine);\n }\n else\n {\n string cleanedDomain = cleanedDomainTemp.Split('.').Last() + topLevelDomain;\n if (domainHashList.Contains(cleanedDomain)) break;\n\n domainHashList.Add(cleanedDomain);\n File.AppendAllText(\"F:\\\\domains-final\\\\domains\\\\doms.txt\", cleanedDomain + Environment.NewLine);\n }\n\n break;\n}\n</code></pre>\n\n<hr>\n\n<p>I would also caution you against using a try/catch to simply bypass exceptions in your code without handling them appropriately.</p>\n\n<p>You should not catch all exceptions and do nothing in the catch statement, it is bad practice. Instead, you should see what exceptions that do occur and figure out how to handle those situations in your code during the development stage, maybe you catch certain exceptions and perform certain tasks inside that catch statement. Allowing exceptions to bubble up and alert you lets you know that there are issues in your input or issues with a connection to the application, if you simply keep the application running without handling the exception you could be throwing your money into a server and not know it.</p>\n\n<hr>\n\n<p>Your variables <code>pc</code> and <code>totalLines</code> are magic numbers</p>\n\n<p>it appears that <code>pc</code> is a percentage, but the other variable has what seems to be an arbitrary number <code>1906663905</code> you should let yourself know what this number is, or find a way to get it from the file that is being read in (assuming it is the total number of lines in the file that you are reading from.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T18:50:36.103",
"Id": "234548",
"ParentId": "234545",
"Score": "3"
}
},
{
"body": "<p>I would separate out the Reading of lines from a file to it's own method. A nice way to report back progress is the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.iprogress-1?view=netframework-4.8\" rel=\"nofollow noreferrer\">IProgress</a> interface. That way we can just calculate the progress and report it back. You can make this more complex than just the percentage but I just passed back the percentage. if you want line count you can do the code for that. But just beware reporting back to the dispatcher can eat up time. It's why I only push back when the percentage changed. Also stream are going to be buffered so the percentage will be a tad off but with large files it's close enough from my experience. </p>\n\n<p>I personally like the extra brackets on using statements but I also always put brackets on single line if. That to me is a personal preference and you should base it on your coding guidelines. </p>\n\n<p>This method is similar to <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readlines?view=netframework-4.8\" rel=\"nofollow noreferrer\">File.ReadLines</a> but since we needed Progress I created this method.</p>\n\n<pre><code>private static IEnumerable<string> FileReadLines(string file, IProgress<int> progress)\n{\n var fileSize = new FileInfo(file).Length;\n using (var fileStream = File.OpenRead(file))\n {\n using (var reader = new StreamReader(fileStream))\n {\n Int? previousProgress = null;\n while (!reader.EndOfStream)\n {\n var line = reader.ReadLine();\n if (line != null)\n {\n if (progress != null)\n {\n var percentDone = (int)Math.Round((reader.BaseStream.Position * 100d) / fileSize, 0);\n if (previousProgress != percentDone)\n {\n progress.Report(percentDone);\n previousProgress = percentDone;\n }\n }\n yield return line;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>Now I moved the array of top level domains into a static field and change it to a hashset. Plus I calculated the depth of domains.</p>\n\n<pre><code>private static readonly HashSet<string> _topLevelDomains = new HashSet<string>(new[] {\n \".travelersinsurance\", \".accountants\", \"....\"}); // did not include them all here to save ones and zeros\nprivate static int _maxDomainLevel = _topLevelDomains.Max(d => d.Count(x => x == SplitChar));\nprivate const char SplitChar = '.';\n</code></pre>\n\n<p>Now I created a method to take a line from the file and return back keyvaluepairs based on the potential matches in the top level domain hashset. </p>\n\n<pre><code>private static IEnumerable<KeyValuePair<string, string>> GetDomains(string domain)\n{\n var domainParts = domain.Split(SplitChar);\n int start;\n if (domainParts.Length <= _maxDomainLevel)\n {\n start = 1;\n }\n else\n {\n // only need to match on part of the string since we can eliminate any that have more parts than in the top level domain\n start = domainParts.Length - _maxDomainLevel;\n }\n for (var i = start; i < domainParts.Length; i++)\n {\n var range = domainParts.Length - i;\n // build up the domain from the subparts\n var key = SplitChar + string.Join(SplitChar, Enumerable.Range(i, range)\n .Select(x => domainParts[x]));\n var value = domainParts[i - 1] + key;\n yield return new KeyValuePair<string, string>(key, value);\n }\n}\n</code></pre>\n\n<p>Now that we have all the pieces we can write some PLINQ code to process it all in parallel </p>\n\n<pre><code>public static void ParseFile(string inputfile, string outputFile, IProgress<int> progress)\n{\n var domains = FileReadLines(inputfile, progress)\n .AsParallel()\n .Where(x => x.Contains('.'))\n .Select(x => GetDomains(x).FirstOrDefault(kv => _topLevelDomains.Contains(kv.Key)))\n .Select(kv => kv.Value) \n .Where(x => x != null)\n .Distinct();\n File.AppendAllLines(outputFile, domains);\n}\n</code></pre>\n\n<p>Now you can call it like so. My example I was putting progress to console but you would also push it to the dispatcher. </p>\n\n<pre><code>ParseFile(@\"c:\\temp\\source.txt\", @\"c:\\temp\\output.txt\", new Progress<int>(l => Console.WriteLine(l)));\n</code></pre>\n\n<p>I, obviously, don't have a 60Gig file but I believe with using PLINQ and changing the top level domains to be a hash set will be quicker. If you want total control then I would use a producer/consumer like the TPL DataFlow but I think it's over kill for this. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T01:38:44.243",
"Id": "234617",
"ParentId": "234545",
"Score": "8"
}
},
{
"body": "<p>A 60 GB file fits a <strong>lot</strong> of domains.</p>\n\n<p>Reporting progress after each of them results in so many calls, that the application may end up spending more time reporting the progress than doing useful work. </p>\n\n<p>Consider reporting the progress less often, say only in 1 or 0.1% increments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T20:24:59.350",
"Id": "458920",
"Score": "2",
"body": "Lot of domains reminded me of fortune teller men in wagon. I see domains in your future. Jesus that’s a lot of domains :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T15:03:02.007",
"Id": "459325",
"Score": "0",
"body": "It is only necessary to update progress when the displayed progress value changes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T10:29:23.047",
"Id": "234627",
"ParentId": "234545",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "234617",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T17:12:26.013",
"Id": "234545",
"Score": "8",
"Tags": [
"c#",
"performance"
],
"Title": "60GB file loading domain to base domain + tld parser"
}
|
234545
|
<p>You are given to paint a floor area of size A. There will be 12 paint buckets from 4 primary
colors with each having 3 shades (i.e. total 12 buckets). The bucket size, or more specifically,
the amount of area you can paint from each shade is given in the following arrays.
The different shades of the same primary color are shown in the same row.</p>
<ul>
<li>[12, 23, 14]</li>
<li>[10, 30, 15]</li>
<li>[16, 22, 35]</li>
<li>[14, 24, 20]</li>
</ul>
<p><strong>Problem & Constraints</strong></p>
<p>You need to select 4 shades to paint the floor area such that;</p>
<ol>
<li>Entire floor area should be painted; also no overlaps of shades are allowed </li>
<li>"One and only one" shade from each primary color has been selected for the final painting </li>
<li>Amount of wastage is minimized (i.e. assume once we open and use a bucket, any
remainings will be discarded)</li>
</ol>
<p>Implement a python program to answer the following problems;</p>
<p>Q1. The color shades (or buckets) satisfying the above constraints (if A = 100)<br>
Q2. The amount of wastage in the above scenario<br>
Q3. What will be the solution for Q1 and Q2 if A = 90?</p>
<p><strong>Note:</strong> You may use the below notation to reference each shade in the above map. </p>
<p>R - row index<br>
C - column index<br>
(r,c) - shade in (r+1)th row and (c+1)th column<br>
e.g. (0,0) -> 12, (0,1) -> 23, (1,2) -> 15, etc.</p>
<p>With this, the answer for Q1 can be given in the format [(0,1), (1,2), (2,0), (3,2)]</p>
<hr>
<p><strong>If user enter 100 system should display color code areas with their coordinates which sum are most close to 100</strong></p>
<p><strong>Example</strong></p>
<pre><code>Enter your Area = 100
100 ~ 101(sum of areas 12+30+35+24, There for 101 is the closet number to 100)
Shades = [12 30 35 24]
Cordinates of shades = (0,0)(1,1)(2,2)(3,1)
</code></pre>
<hr>
<p><strong>This is my answering code</strong></p>
<pre><code>import numpy as np
import itertools
colors = np.array([[12, 23, 14], [10, 30, 15], [16, 22, 35], [14, 24, 20]])
max_tot = 0
#get total of all integers which are in array
for i in range(len(colors)):
max_tot = max_tot + max(colors[i])
#Enter Area
area = int(input("Enter your Area = "))
if(area > max_tot):
print("Area is too long. Don't have enough paints for painting")
elif(area <= 0):
print("Wrong area")
else:
#get shades which are given lowest minimum wastage
for element in itertools.product(*colors):
if(sum(element) >= area):
x = sum(element)
if(x <= max_tot):
max_tot = x
el = np.array(element)
print()
print("sum of shades =", max_tot)
print("minimum wastage =" , max_tot - area)
print("Shades =", el)
print("Cordinates of shades = " ,end ='')
#get coordinates using manual method
for i in range(4):
g,h = np.where(colors == el[i])
print("(" ,g[0],",", h[0], ")", sep=' ', end='', flush=True)
</code></pre>
<p><strong>Output -:</strong></p>
<pre><code>Enter your Area = 100
sum of shades = 101
minimum wastage = 1
Shades = [12 30 35 24]
Cordinates of shades = ( 0 , 0 )( 1 , 1 )( 2 , 2 )( 3 , 1 )
</code></pre>
<hr>
<p>You can see I have got coordinates of <code>12 30 35 24</code> is manual type. That is not a good programming method. </p>
<p>How can I get that coordinates directly(using better way)?</p>
<p><strong>Note that I have done all question. I want a better answer for Q3</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T23:21:28.493",
"Id": "459028",
"Score": "0",
"body": "I'm not sure there is a better solution. As long as the dimensionality of `colors` remains small, this will be the optimal solution. Can you explain why you believe this is not a good programming method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T04:44:45.803",
"Id": "459055",
"Score": "0",
"body": "There is a way get coordinates of arrays in few lines. My way is tricky method not correct method"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T18:33:30.987",
"Id": "234546",
"Score": "1",
"Tags": [
"python",
"array",
"pyth"
],
"Title": "How to get cordinates of selected numbers which are from array?"
}
|
234546
|
<p>I was wondering if anyone would be kind enough to review my basic c++ program. I'm a beginner programmer so was hoping to get feedback on how well I've used object oriented programming i.e. using a class in my program. And in general, how can I make my program better? Many thanks in advance.</p>
<pre><code>// Created by George Austin Bradley on 08/12/2019.
// Copyright © 2019 George Austin Bradley. All rights reserved.
//
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
class User{
private:
string sName;
string sCarName;
string sCarFuelType;
string sChoiceOfLocation;
double dFuelCost;
int iMilesToTravel;
double dTotalToBePaid;
double dVATAmount;
double dEstimatedTime;
public:
User()
:sName(""),sCarName(""), sCarFuelType(""), sChoiceOfLocation(""), dFuelCost(0), iMilesToTravel(0), dTotalToBePaid(0),dVATAmount(0), dEstimatedTime(0){
}
void SetName()
{
cout << "What's your name?: ";
cin >> sName;
}
void SetCarFuelType(){
bool bValid = false;
char cSelection = 0;
do{
cout << "What's your fuel type? (p) petrol or (d) diesel: ";
cin >> cSelection;
cSelection = toupper(cSelection);
if (cSelection == 'P')
{
sCarFuelType = "Petrol";
dFuelCost = 0.33;
cout << "You've chosen " << sCarFuelType << " as your fuel type.\n";
bValid = true;
}
else if (cSelection == 'D')
{
sCarFuelType = "Diesel";
dFuelCost = 0.40;
cout << "You've chosen " << sCarFuelType << " as your fuel type.\n";
bValid = true;
}
else
{
cout << "Invalid input. Please try again!";
}
}while(bValid == false);
}
void SetCarName()
{
bool bValid = false;
do{
cout << "What car do you drive?: ";
cin >> sCarName;
bValid = true;
}while(bValid == false);
}
void DisplayTravelDestinations()
{
cout << "\n";
cout << "Select a location number from the menu...\n";
cout << "1. South West - 141 Miles\n";
cout << "2. Leeds - 195\n";
cout << "3. Birmingham - 220\n";
cout << "4. Glasglow - 230 miles\n";
cout << "\n";
}
void SetLocation(){
bool bValid = false;
char cSelection = 0;
do{
DisplayTravelDestinations();
cout << "Where do you want to travel?: ";
cin >> cSelection;
cSelection = toupper(cSelection);
switch(cSelection)
{
case '1':
sChoiceOfLocation = "South West";
iMilesToTravel = 141;
bValid = true;
break;
case '2':
sChoiceOfLocation = "Leeds";
iMilesToTravel = 195;
bValid = true;
break;
case '3':
sChoiceOfLocation = "Birmingham";
iMilesToTravel = 220;
bValid = true;
break;
case '4':
sChoiceOfLocation = "Glasglow";
iMilesToTravel = 230;
bValid = true;
break;
default:
cout << "Invalid input! Please try again.";
continue;
}
}while(bValid == false);
}
void CalculateTotalToBePaid()
{
if (iMilesToTravel < 100)
{
dTotalToBePaid = iMilesToTravel * dFuelCost;
}
else
{
dTotalToBePaid = 100 * dFuelCost;
dTotalToBePaid += (iMilesToTravel - 100) * (dFuelCost / 2);
}
}
void CalculateVAT()
{
double dVATPercentage = 0.2;
dVATAmount = dTotalToBePaid * dVATPercentage;
}
void CalculateEstimatedTravelTime()
{
const int iAverage = 50;
dEstimatedTime = iMilesToTravel / iAverage;
}
string GetName(){return sName;}
string GetCarName(){return sCarName;}
string GetFuelType(){return sCarFuelType;}
string GetChoiceOfLocation(){return sChoiceOfLocation;}
double GetFuelCost(){return dFuelCost;}
int GetMilesToTravel(){return iMilesToTravel;}
double GetTotalToBePaid(){return dTotalToBePaid;}
double GetVATAmount(){return dVATAmount;}
double GetEstimatedTime(){return dEstimatedTime;}
};
bool ContinueOptions()
{
char cSelection = 0;
cout << "Do you wish to restart? (Y/N) ";
cin >> cSelection;
cSelection = toupper(cSelection);
if(!cin)
{
return false;
}
bool bGoAgain = toupper(static_cast<unsigned char>(cSelection)) == 'Y';
cout << (bGoAgain ? "You've chosen to start again\n" : "Goodbye!\n");
return bGoAgain;
}
void DisplayResults(User George)
{
cout << fixed << setprecision(2);
cout << "Hi " << George.GetName() << ", you're driving in a " << George.GetCarName() << ".\n";
cout << "The car your driving runs on " << George.GetFuelType() << " which costs £" << George.GetFuelCost() << " an hour.\n";
cout << "The destination you have chosen is " << George.GetChoiceOfLocation() << " and is a distance of " << George.GetMilesToTravel() << " miles.\n";
cout << "The journey will cost you £" << George.GetTotalToBePaid() << " with 20% VAT: £" << George.GetVATAmount() << ".\n";
cout << "The estimated amount of time it will take is " << George.GetEstimatedTime() << " hours.\n";
}
void GetUserInformation(User &George)
{
George.SetName();
George.SetCarName();
George.SetCarFuelType();
George.SetLocation();
George.CalculateTotalToBePaid();
George.CalculateVAT();
George.CalculateEstimatedTravelTime();
}
int main() {
do{
User George;
GetUserInformation(George);
DisplayResults(George);
}while(ContinueOptions());
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T22:57:29.220",
"Id": "458739",
"Score": "0",
"body": "You might want to consider following the advice of previous questions in new questions, the code still has `using namespace std;` in it. You might also want to remove the licensing information since posting the code here effectively makes in public domain and Stack Overflow Inc. Has their own licensing for the questions asked."
}
] |
[
{
"body": "<h2>Avoid <code>using namespace std;</code></h2>\n\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\n<h2>DRY Code</h2>\n\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n\n<p>In the example code below, 2 private functions, <code>SetExcusionData(std::string location, int distance)</code> and <code>SetFuelTypeAndCost(std::string ftype, double cost)</code> have been added. These private functions reduce the code in <code>SetLocation()</code> and <code>SetCarFuelType()</code>.</p>\n\n<p>The logic in <code>SetLocation()</code> has been altered slightly to reduce the code in the function as well, the variable <code>bValid</code> is initialized to true rather than false, and the only place <code>bValid</code> needs to be modified is in the <code>default</code> case. There is no reason to use <code>toupper()</code> in this function because there is no upper case 1 through 4. The logic has also been modified so that the variable <code>cSelection</code> is an integer rather than a character.</p>\n\n<h2>Readability</h2>\n\n<p>The code would be more readable if there was more horizontal spacing, int the code most of the do while loops end with something like this <code>}while(bValid == false);</code> there should space between <code>}</code> and <code>while</code> and there should be a space between <code>while</code> and <code>(</code>.</p>\n\n<h2>Minor Input Issue</h2>\n\n<p>I generally include the make and model of my car as a car name, the code currently doesn't handle multiple word line well as input, it might be better in some cases to get the whole line of input and process it. I might also want to use both my first and last name when asked my name.</p>\n\n<h2>Program Organization</h2>\n\n<p>Most classes in C++ are implemented by a header file and a c++ source file. In most C++ editors there should be a button or a menu item that supports Add Class that creates this two file structure for you. One of the major benefits of this organization is that functions can be maintained/edits without needed to rebuild other files that include the header. Another benefit of this file organization is it somewhat easier to read the definition of the class, since the member variables and the member functions are just a list. Here is the User class broken up using a normal C++ editor: </p>\n\n<h2>User2.h</h2>\n\n<pre><code>#ifndef CARMILAGEGEORGE_USER2_H\n#define CARMILAGEGEORGE_USER2_H\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <iomanip> \n\nclass User2 {\npublic:\n User2();\n void SetName();\n void SetCarFuelType();\n void SetCarName();\n void DisplayTravelDestinations();\n void SetLocation();\n void CalculateTotalToBePaid();\n void CalculateVAT();\n void CalculateEstimatedTravelTime();\n std::string GetName(){return sName;}\n std::string GetCarName(){return sCarName;}\n std::string GetFuelType(){return sCarFuelType;}\n std::string GetChoiceOfLocation(){return sChoiceOfLocation;}\n double GetFuelCost(){return dFuelCost;}\n int GetMilesToTravel(){return iMilesToTravel;}\n double GetTotalToBePaid(){return dTotalToBePaid;}\n double GetVATAmount(){return dVATAmount;}\n double GetEstimatedTime(){return dEstimatedTime;}\n\nprivate:\n void SetFuelTypeAndCost(std::string ftype, double cost);\n void SetExcusionData(std::string location, int distance);\n std::string sName;\n std::string sCarName;\n std::string sCarFuelType;\n std::string sChoiceOfLocation;\n double dFuelCost;\n int iMilesToTravel;\n double dTotalToBePaid;\n double dVATAmount;\n double dEstimatedTime;\n};\n\n#endif //CARMILAGEGEORGE_USER2_H\n</code></pre>\n\n<h2>User2.cpp</h2>\n\n<pre><code>#include \"User2.h\"\n\nUser2::User2()\n :sName(\"\"), sCarName(\"\"), sCarFuelType(\"\"), sChoiceOfLocation(\"\"), dFuelCost(0), iMilesToTravel(0), dTotalToBePaid(0),dVATAmount(0), dEstimatedTime(0)\n{\n}\n\nvoid User2:: SetName()\n{\n std::cout << \"What's your name?: \";\n std::cin >> sName;\n}\n\nvoid User2::SetFuelTypeAndCost(std::string ftype, double cost)\n{\n sCarFuelType = ftype;\n dFuelCost = cost;\n}\n\nvoid User2:: SetCarFuelType(){\n bool bValid = false;\n char cSelection = 0;\n std::cout << \"What's your fuel type? (p) petrol or (d) diesel: \";\n\n do{\n std::cin >> cSelection;\n cSelection = toupper(cSelection);\n if (cSelection == 'P')\n {\n SetFuelTypeAndCost(\"Petrol\", 0.33);\n bValid = true;\n }\n else if (cSelection == 'D')\n {\n SetFuelTypeAndCost(\"Diesel\", 0.40);\n bValid = true;\n }\n if (!bValid)\n {\n std::cout << \"Invalid input. Please try again!\";\n }\n } while (bValid == false);\n\n std::cout << \"You've chosen \" << sCarFuelType << \" as your fuel type.\\n\";\n}\n\nvoid User2::SetCarName()\n{\n bool bValid = false;\n\n do{\n std::cout << \"What car do you drive?: \";\n std::cin >> sCarName;\n bValid = true;\n\n } while (bValid == false);\n\n}\n\nvoid User2::DisplayTravelDestinations()\n{\n std::cout << \"\\n\";\n std::cout << \"Select a location number from the menu...\\n\";\n std::cout << \"1. South West - 141 Miles\\n\";\n std::cout << \"2. Leeds - 195\\n\";\n std::cout << \"3. Birmingham - 220\\n\";\n std::cout << \"4. Glasglow - 230 miles\\n\";\n std::cout << \"\\n\";\n}\n\nvoid User2::SetExcusionData(std::string location, int distance)\n{\n sChoiceOfLocation = location;\n iMilesToTravel = distance;\n}\n\nvoid User2::SetLocation(){\n bool bValid = true;\n int cSelection = 0;\n do{\n DisplayTravelDestinations();\n std::cout << \"Where do you want to travel?: \";\n std::cin >> cSelection;\n switch(cSelection)\n {\n case 1:\n SetExcusionData(\"South West\", 141);\n break;\n case 2:\n SetExcusionData(\"Leeds\", 195);\n break;\n case 3:\n SetExcusionData(\"Birmingham\", 220);\n break;\n case 4:\n SetExcusionData(\"Glasglow\", 230);\n break;\n default:\n std::cout << \"Invalid input! Please try again.\";\n bValid = false;\n continue;\n }\n } while (bValid == false);\n\n}\n\nvoid User2::CalculateTotalToBePaid()\n{\n if (iMilesToTravel < 100)\n {\n dTotalToBePaid = iMilesToTravel * dFuelCost;\n\n }\n else\n {\n dTotalToBePaid = 100 * dFuelCost;\n dTotalToBePaid += (iMilesToTravel - 100) * (dFuelCost / 2);\n }\n}\n\nvoid User2::CalculateVAT()\n{\n double dVATPercentage = 0.2;\n dVATAmount = dTotalToBePaid * dVATPercentage;\n\n}\n\nvoid User2::CalculateEstimatedTravelTime()\n{\n const int iAverage = 50;\n dEstimatedTime = iMilesToTravel / iAverage;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T23:45:16.053",
"Id": "458740",
"Score": "0",
"body": "Hi, thanks so much for reviewing my program. I really appreciate how you’ve shown me how to separate the class into a different file. And what you did with the duplicated code is just fantastic and has made things even better in terms of efficiency. I shall definitely follow that rule of thumb for future reference. Many thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T11:59:46.120",
"Id": "458772",
"Score": "0",
"body": "I have a question. Is there a better way to input my calculations instead of calling them in a procedure outside the class? If you know what I mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T13:50:37.567",
"Id": "458782",
"Score": "0",
"body": "Rather then calling all three calculations in `void GetUserInformation(User2 &George)` there could be a single public interface called Calculate that called the 3 calculation functions. The other option is that the constructor doesn't do very much right now and the body of void GetUserInformation(User2 &George) could all be in the constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:00:38.457",
"Id": "458783",
"Score": "0",
"body": "The function `DisplayResults(User2 George)` should be in the class User as well, that would remove the need for public accessor functions. You could actually make `DisplayResults(User2 George)` into an override of the `<<` operator for User. `std::cout << George;`. Another reason not to use `using namespace std;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T16:47:41.640",
"Id": "458807",
"Score": "0",
"body": "How would I make DisplayResults(User2 George) into an override operator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T17:30:23.063",
"Id": "458811",
"Score": "0",
"body": "First convert it to User.DisplayResults(). Then find examples on the internet of how to override `<<`, they are out there, try stackoverflow first. https://www.geeksforgeeks.org/overloading-stream-insertion-operators-c/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T18:08:54.040",
"Id": "458816",
"Score": "0",
"body": "Okay! Thanks very much for your help."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T22:50:03.330",
"Id": "234564",
"ParentId": "234547",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "234564",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T18:46:38.180",
"Id": "234547",
"Score": "1",
"Tags": [
"c++",
"beginner",
"c++11",
"c++17"
],
"Title": "Car Milage and Cost Calculating System based off menu selections (using a class)"
}
|
234547
|
<p>We are using a plugin for our WordPress website. I'm trying to add some custom code to it and finally got it working however it is ultra janky. The HTML is a simplified version of the actual site's but it's the JQuery I need help with. I'm trying to trim as much fat as I possibly can. I'm am not the greatest with JQuery but know enough to stumble and get by. </p>
<p>The goal is when the page loads is to check if the radio group has an option checked and to then display the correct one and hide the rest. The same goes for when someone changes that option however it now needs to uncheck any other option they might have already checked for the previous one. I'm looking for help to condense this down while having this work the way it currently is. Unfortunately I can not go based off other attributes except for name and value. Any help on this would be greatly appreciated!</p>
<p>HTML:</p>
<pre><code><div>
<label>Oak</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Oak_0' checked="checked">
<label>Brown Maple</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Brown Maple_1'>
<label>Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Cherry_2'>
<label>Quartersawn White Oak</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Quartersawn White Oak_3'>
<label>Hard Maple</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Hard Maple_4'>
<label>Hickory</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='Hickory_5'>
<!-- Many Others... -->
</div>
<div class="stains-container">
<div class="oak-stains-div">
<h4>Oak</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="b-maple-stains-div">
<h4>Brown Maple</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="cherry-stains-div">
<h4>Cherry</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="qswo-stains-div">
<h4>Quartersawn White Oak</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="h-maple-stains-div">
<h4>Hard Maple</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
<div class="hickory-stains-div">
<h4>Hickory</h4>
<label>Michael's Cherry</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Rich Tobacco</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<label>Dark Knight</label>
<input type='radio' name="tmcp_radio_0" class='some-class-of-radiogroup' value='value'>
<!-- Many Others... -->
</div>
</div>
</code></pre>
<p>JS:</p>
<pre><code>jQuery(function ($) {
// Create Variables
var stains = $(".stains-container");
// Check if Oak is checked
var $oakchecked = $("input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.hickory-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");
// Check if B. Maple is checked
var $bmaplechecked = $("input.oak-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.hickory-stains");
var $bmapleactive = $(".oak-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .h-maple-stains-div li, .hickory-stains-div li");
// Check if Cherry is checked
var $cherrychecked = $("input.oak-stains, input.b-maple-stains, input.qswo-stains, input.h-maple-stains, input.hickory-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");
// Check if QSWO is checked
var $qswochecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.h-maple-stains, input.hickory-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");
// Check if H. Maple is checked
var $hmaplechecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.hickory-stains");
var $hmapleactive = $(".oak-stains-div li, .b-maple-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .hickory-stains-div li");
// Check if Hickory is checked
var $hickorychecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.h-maple-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");
// Check if a button is pre-selected and if its value matches
var radio_buttons = $("input[name='tmcp_radio_0']");
if( radio_buttons.is(":checked") && /^Oak_\d$/.test($(this).val())) {
alert("OAK is selected");
$(".oak-stains-div").show();
$oakchecked.prop('checked', false);
$oakactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Brown Maple_\d$/.test($(this).val())) {
alert("B MAPLE is selected");
$(".b-maple-stains-div").show();
$bmaplechecked.prop('checked', false);
$bmapleactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Cherry_\d$/.test($(this).val())) {
alert("CHERRY is selected");
$(".cherry-stains-div").show();
$cherrychecked.prop('checked', false);
$cherryactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Quartersawn White Oak_\d$/.test($(this).val())) {
alert("QSWO is selected");
$(".qswo-stains-div").show();
$qswochecked.prop('checked', false);
$qswoactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Hard Maple_\d$/.test($(this).val())) {
alert("H MAPLE is selected");
$(".h-maple-stains-div").show();
$hmaplechecked.prop('checked', false);
$hmapleactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":checked") && /^Hickory_\d$/.test($(this).val())) {
alert("HICKORY is selected");
$(".hickory-stains-div").show();
$hickorychecked.prop('checked', false);
$hickoryactive.removeClass( "tc-active" );
} else if( radio_buttons.is(":not(:checked)")) {
alert("NOTHING is selected");
$(".stains-container").hide();
}
// Check if Oak is selected or pre-selected
radio_buttons.on('change',function(){
if ( /^Oak_\d$/.test($(this).val())) {
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(){
if ( /^Brown Maple_\d$/.test($(this).val())) {
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(){
if ( /^Cherry_\d$/.test($(this).val())) {
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(){
if ( /^Quartersawn White Oak_\d$/.test($(this).val())) {
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(){
if ( /^Hard Maple_\d$/.test($(this).val())) {
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(){
if ( /^Hickory_\d$/.test($(this).val())) {
stains.show();
$(".hickory-stains-div").show();
$hickorychecked.prop('checked', false);
$hickoryactive.removeClass( "tc-active" );
} else {
$(".hickory-stains-div").hide();
}
});
});
</code></pre>
<p>My fiddle: <a href="https://jsfiddle.net/amishdirect/h94c7rsw/7/" rel="nofollow noreferrer">https://jsfiddle.net/amishdirect/h94c7rsw/7/</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T19:22:46.837",
"Id": "234549",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"jquery"
],
"Title": "Display Correct Div based on Radio Button Checked"
}
|
234549
|
<p>I'm trying to generate the sum of a collection of strings by calcuating each character's byte value into a sum:</p>
<pre><code>$sum = 0;
foreach( $array as $item ) {
$bytes = unpack( 'C*', $item );
for( $i = 1; $i <= count( $bytes ); $i++ ) {
if( isset( $bytes[$i+1] ) ) {
$sum += $bytes[$i] - $bytes[$i+1];
} else {
$sum -= $bytes[$i];
}
}
}
return $sum;
</code></pre>
<p>The goal here is to compare past sums with newly generated sums (that is to say, check if there has been a new addition to the collection, suppose <code>Item4</code>) and perform actions if yes.</p>
<p>As such, it's very important that:</p>
<ol>
<li>The algorithm can compute the sum irrespective of the order of the items.</li>
<li>The algorithm doesn't get confused by a case where let's say <code>Item3</code> now becomes <code>temI3</code> (and therefore the sum value is still the same, even though it's clearly not the same <code>Item</code>).</li>
</ol>
<p>The whole secondary loop is to check against exactly that: loop through each byte (character) from each <code>Item$i</code> and to the final summ, add the differene between the first and second bytes. If there isn't a next one and we are at the end of the string, simply subtract if from the whole sum.</p>
<p>As such, the following:</p>
<p>Input(s): <code>['Item1', 'Item2', 'Item3']</code> / <code>['Item1', 'Item2', 'Item3']</code> , output: <code>the same int</code>. Where as <code>['Item1', 'Item2', 'Ite3m']</code> outputs a different <code>int</code>.</p>
<p>The performance as of now is as follows:</p>
<p><code>100000 items across 100 runs: 0.18s / 1000000 items across 100 runs: 2.05s</code></p>
<p>And although I understand that to parse and do these calculations for a million items in 2s is rather fast for PHP, I still think that, if you look at what the thing does, it's still slow.</p>
<p>Any way to speed this up?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T21:30:16.983",
"Id": "458732",
"Score": "0",
"body": "Hmm, have you tried simply not calling `count( $bytes )` over and over during each iteration of the nested loop? Try calling it once. (I guess this is a review and can be an answer, but it feels pretty meagar.) Or how about `++$i` instead of `$i++`? Can you decrement instead of increment to somehow avoid `isset()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T04:48:45.293",
"Id": "458753",
"Score": "0",
"body": "Is there a reason that you are not simply using `===` to compare `$bytes` arrays?"
}
] |
[
{
"body": "<h1>Dont call functions in loop conditions.</h1>\n\n<p>Calling count as condition of a for is a common mistake. It has the same behaviour but it is slower because the count function has to be called repeatedly although it returns the same value all the time. Unless the count changes during iterations, prefetch the count before the loop.</p>\n\n<h1>Iterate only where body is same</h1>\n\n<p>In your for you always check if the element is the last one, to do something else in that case. You better exclude it from the for, and handle the last element separately.</p>\n\n<h1>Unpack is not necesary</h1>\n\n<p>I wasnt really sure until I benched it, but just accessing individual characters of the strings with the <code>[]</code> operator and using the <code>ord</code> function to get the numeric value of bytes seems quite faster.</p>\n\n<h1>Not sure your algorithm is correct</h1>\n\n<p>As I've shown in me2 implementation, you are actualy adding just the first charracter of each word and subracting last character of each word twice.\nIt means that none of the characters except first and last in each word is contributing to the resulting sum. Therefore item <code>Item1</code> is the same as <code>Ixxx1</code>. (Try for <code>$input2</code> in the code below and see for yourself).</p>\n\n<pre><code><?php\n\nfunction op(array $array)\n{\n $sum = 0;\n\n foreach( $array as $item ) {\n $bytes = unpack( 'C*', $item );\n\n for( $i = 1; $i <= count( $bytes ); $i++ ) {\n if( isset( $bytes[$i+1] ) ) {\n $sum += $bytes[$i] - $bytes[$i+1];\n } else {\n $sum -= $bytes[$i];\n }\n }\n }\n\n return $sum;\n}\n\nfunction op2(array $array)\n{\n $sum = 0;\n\n foreach( $array as $item ) {\n $bytes = unpack( 'C*', $item );\n\n $length = count( $bytes );\n for( $i = 1; $i < $length ; $i++ ) {\n $sum += $bytes[$i] - $bytes[$i+1];\n }\n if ($length > 0) {\n $sum -= $bytes[$length];\n }\n\n }\n\n return $sum;\n}\n\nfunction me(array $array)\n{\n $sum = 0;\n\n foreach( $array as $item ) {\n $length_1 = strlen($item) - 1;\n for ($i = 0; $i < $length_1; ++$i) {\n $sum += ord($item[$i]) - ord($item[$i + 1]);\n }\n if ($length_1 >= 0) {\n $sum -= ord($item[$length_1]);\n }\n\n }\n\n return $sum;\n}\n\nfunction me2(array $array)\n{\n $sum = 0;\n\n foreach( $array as $item ) {\n $length = strlen($item);\n if ($length == 1) {\n $sum -= ord($item[0]);\n } elseif ($length > 1) {\n $sum += ord($item[0]) - 2 * ord($item[$length-1]);\n }\n }\n\n return $sum;\n}\n\nfunction bench(callable $callback, array $input, int $reps = 10000)\n{\n $total = 0;\n for ($i = 0; $i < $reps; ++$i) {\n $start = \\microtime(true);\n $callback($input);\n $total += \\microtime(true) - $start;\n }\n return $total / $reps;\n\n}\n\n$input1 = ['Item1', 'Item2', 'Item3', 'X', ''];\n$input2 = ['Ixxx1', 'Ixxx2', 'Ixxx3', 'X', ''];\n\n$outOp = op($input1);\n$outOp2 = op2($input1);\n$outMe = me($input1);\n$outMe2 = me2($input1);\n\necho 'OP: ' . bench('op', $input1);\necho \\PHP_EOL;\necho $outOp;\necho \\PHP_EOL;\n\necho 'OP improved: ' . bench('op2', $input1);\necho \\PHP_EOL;\necho $outOp2;\necho \\PHP_EOL;\n\necho 'No unpack: ' . bench('me', $input1);\necho \\PHP_EOL;\necho $outMe;\necho \\PHP_EOL;\n\necho 'Me2: ' . bench('me2', $input1);\necho \\PHP_EOL;\necho $outMe2;\necho \\PHP_EOL;\n</code></pre>\n\n<pre><code>OP: 3.5921573638916E-6\n-169\nOP improved: 3.3084869384766E-6\n-169\nNo unpack: 1.4432907104492E-6\n-169\nMe2: 5.5739879608154E-7\n-169\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T17:56:29.520",
"Id": "458814",
"Score": "0",
"body": "You are right, yours is way faster. Unfortunately, both my implementation, as well as yours suffer from the same issue: it doesn't compute a different sum if the order of characters (and therefore the word itself is different) is different: `['Item1', 'Item2', 'Ietm3']` is the same sum as `['Item1', 'Item2', 'Item3']`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T18:03:18.607",
"Id": "458815",
"Score": "0",
"body": "I know you showed me that your function performs way faster, but you're **comparing me having to go through the whole string, vs. you taking only the first and last characters of each string item**. I need to parse each string fully and compute a number that's representative of a string. I need the `count` to know how long each string I'm parsing is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T18:21:50.057",
"Id": "458817",
"Score": "0",
"body": "I went ahead and accepted the answer as, within the scope of the question, which is performance, it does its job if we pair it the output of my function. I would GREATLY appreciate any help with the algorithm, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T18:24:33.510",
"Id": "458818",
"Score": "0",
"body": "`return crc32( implode( \"\", $array) )` across `100000` runs takes `0.00265`, not sure it can be improved though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T21:52:50.647",
"Id": "458835",
"Score": "0",
"body": "@DanielM Yeah, the \"first+last char\" version will be more or less effective than yours for strings of different lengths. But it indeed does not satisfy your requirements. But neither does your original code. I included that version exactly to point this out. Anyway, problem here is that no matter how you compute the sum/hash, you are mapping potentialy infinite set of values to a finite range of possible values of int (or string of fixed length). This will unevitably lead to ambiguities. crc32 also has this artifact. If it is acceptable for you, sure go ahead and use that one."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T11:14:48.437",
"Id": "234584",
"ParentId": "234551",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234584",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T19:28:50.170",
"Id": "234551",
"Score": "2",
"Tags": [
"php",
"array"
],
"Title": "Sum of array of strings to bytes"
}
|
234551
|
<p>I just wrote a Python script that will take a list of urls and find which ones are about to expire. </p>
<p>The program queries a database, gets the websites, sanitizes the list, then loops through the list and prints the expiration dates to the file. Any websites that expire within 30 days are printed to a text file as well as to the terminal.</p>
<p>The program has two main deficiencies:</p>
<ol>
<li>The DNS lookup doesn't always work. Sometimes it returns correct information and sometimes it doesn't.</li>
<li>The program is not written in either object-oriented or functional style.</li>
<li>The program is written with a poor implementation of Python modules and is probably not Pythonic.</li>
</ol>
<p>I would love to get some input on how to make this code better. Everything feels super clunky to me. For example, the sanitization process feels over-complicated, as I feel like I'm jumping through too many hoops to convert the SQL results to a string. The Popen processes feel over-complicated as well. </p>
<p>Would love to get some help making this better.</p>
<pre class="lang-py prettyprint-override"><code>import database
import re
import time
import datetime
import subprocess
from subprocess import PIPE, Popen
import sys
from termcolor import colored, cprint
import pymysql.cursors
###
# FUNCTIONS
###
# Writes expiration data to the file
def write_to_file(filename, url, days_to_expiration, expiration_date):
f = open(filename, "a+")
f.write(url + ' expires in ' + str(days_to_expiration) + ' days on ' + expiration_date + '\n')
f.close()
###
# END FUNCTIONS
###
###
# MAIN
###
###REMOVED QUERY INFORMATION###
results = cursor.fetchall()
# Sanitize results
results_no_blanks = list(filter(lambda x: x[0] != '', results)) # Remove Blank results
results_no_protocol = list(map(lambda x: re.sub(r'^(https?:)?(\/\/)?(www.)?', '', ''.join(x)), results_no_blanks)) # Remove protocols
final_results = list(map(lambda x: re.sub(r'\/', '', ''.join(x)), results_no_protocol)) # Remove trailing slashses
# Prepare text file
a = open("danger.txt","a+")
a.write('DNS Expirations checked on: ' + datetime.datetime.today().strftime("%m/%d/%Y"))
a.write('\n')
a.close()
# Get WHOIS data for each URL
for result in final_results:
url = ''.join(result)
# Use command line to get WHOIS data
p1 = Popen(['whois', url], stdout=PIPE)
p2 = Popen(["grep", "Expiration\|Expiry"], stdin=p1.stdout, stdout=PIPE)
p3 = subprocess.Popen(["awk", "{print $5}"], stdin=p2.stdout, stdout=PIPE)
p4 = subprocess.Popen(['head', '-c', '14'], stdin=p3.stdout, stdout=PIPE)
# Turn result into a string
bytes_result = p4.communicate()
result = bytes_result[0][1:-3]
resulter = result.decode('utf-8')
# Workaround: Sometimes whois returns a string with missing date data.
try:
if resulter != '':
resulter_date = datetime.datetime.strptime(resulter, '%Y-%m-%d')
except ValueError:
print('Oops, something failed. Invalid String Format for URL {}, which returned {}.'.format( url, resulter))
# Get the days until DNS expiration
difference = resulter_date - datetime.datetime.today()
days_until_expiration = difference.days
# Print results to command line and print soon-to-expire URLs to text file.
if days_until_expiration < 30:
cprint('DANGER!!!', 'red', 'on_green')
cprint('The URL {} expires in {} days on {}!'.format( url, difference.days, resulter), 'red', 'on_green')
cprint('DANGER!!!', 'red', 'on_green')
write_to_file('danger.txt', url, days_until_expiration, resulter)
elif days_until_expiration > 31 and days_until_expiration < 91:
cprint('The URL {} expires in {} days on {}!'.format( url, difference.days, resulter), 'yellow', 'on_blue')
else:
cprint('The URL {} expires in {} days on {}!'.format( url, difference.days, resulter), 'green')
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T15:19:04.657",
"Id": "458797",
"Score": "0",
"body": "Remember, this is code review, we can't help you debug code that isn't working correctly, we also can't help you rewrite the code to be object oriented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:58:09.880",
"Id": "458952",
"Score": "0",
"body": "The DNS lookup not always working, is that a code problem, a connection problem or a host (their side) problem?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T19:38:21.333",
"Id": "234552",
"Score": "2",
"Tags": [
"python",
"sql",
"bash"
],
"Title": "Python Script to look for DNS expiration"
}
|
234552
|
<p>I've finished implementing a dynamic array in C++. I'm a beginner in C++ and also in algorithms and data structures, so any constructive feedback about improving the implementation would be greatly appreciated. </p>
<pre><code>#include <iostream>
using namespace std;
#define INITIAL_CAPACITY 5
template <class T>
class dynamic_array {
T *array;
int MIN_CAPACITY = INITIAL_CAPACITY;
int GROWTH_FACTOR = 2;
int size;
public:
// constructor init
dynamic_array() {
array = new T[MIN_CAPACITY];
size = 0;
}
// append @ the end
void append(T element) {
if(size == MIN_CAPACITY) {
resize();
}
array[size] = element;
size++;
}
void deleteAt(int pos) {
if((pos > size) || (pos < 0)) {
cout << "Invalid index";
return;
}
for(int i = pos; i <= size; i++) {
array[i] = array[i+1];
}
size--;
}
void insertAt(int element, int pos) {
if((pos > size) || (pos < 0)) {
cout << "Invalid index";
return;
}
if(size == MIN_CAPACITY) {
resize();
}
size++;
for(int i = size - 1; i >= pos; i--) {
if(i == pos) {
array[i] = element;
} else {
array[i] = array[i-1];
}
}
}
// returns size of array
int length() {
return size;
}
// doubles capacity if it has to and deletes reference to current array.
void resize() {
MIN_CAPACITY *= GROWTH_FACTOR;
T *temp = new T[MIN_CAPACITY];
copy(temp);
delete [] array;
array = temp;
}
// copies original array into temp
void copy(T temp[]) {
for(int i = 0; i < size; i++) {
temp[i] = array[i];
}
}
// returns element in x position.
T get(int pos) {
return array[pos];
}
};
int main() {
dynamic_array<int> dynArr;
dynArr.append(3);
dynArr.append(4);
dynArr.append(5);
dynArr.append(4);
dynArr.append(33);
dynArr.append(3);
dynArr.deleteAt(6);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T17:27:04.833",
"Id": "458995",
"Score": "0",
"body": "Thank you so much for the resources provided! Both answers were really helpful and insightful."
}
] |
[
{
"body": "<p>The code is pretty good as it is. Here is how I would improve it:</p>\n\n<h2>Constant handling</h2>\n\n<p>In C++, you should prefer <code>const</code> over <code>#define</code>. So</p>\n\n<pre><code>#define INITIAL_CAPACITY 5\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>const int INITIAL_CAPACITY = 5;\n</code></pre>\n\n<p>Also don't use all uppercase names for non constant variables. It is\nconfusing and breaks the 50 year old tradition.</p>\n\n<h2>Clearer names</h2>\n\n<p>I renamed a few of your variables:</p>\n\n<ul>\n<li><p><code>MIN_CAPACITY => capacity</code> Because the instance variable holds the\n<em>current</em> capacity of the dynamic array, not the <em>minimum</em> capacity.</p></li>\n<li><p><code>length() => size</code> The words <em>length</em> and <em>size</em> are synonymous but\nusing them both can cause confusion. A reader might think is the\nlength the number of elements in the array and size the allocacted\nsize, or vice versa?</p></li>\n</ul>\n\n<h2>Offby one errors</h2>\n\n<p>You have an offby one error in <code>deleteAt</code>. If you have a dynamic array\nwith 5 elements, then their positions are 0 to 4 so <code>deleteAt(5)</code>\nshouldn't work, but it does. I've fixed that for you.</p>\n\n<h2>Pretty printing</h2>\n\n<p>Adding pretty printing functions is almost always a good idea because\nthey make debugging much easier. I've added one for you.</p>\n\n<h2>Error handling</h2>\n\n<p>Your error handling consists of printing to stdout and letting the\nprogram continue to run. That is incorrect because errors might not be\ndiscovered if stdout is redirected or the user is not paying attention\nto what is printed.</p>\n\n<p>There are many ways to handle errors. I've implemented basic assert\nbased error handling for you. But you can certainly be fancier and use\nexceptions or status codes.</p>\n\n<h2>Functions implemented in terms of each other</h2>\n\n<p>For all dynamic arrays <code>dynarr.append(x)</code> is equivalent to\n<code>dynarr.insertAt(x, dynarr.size())</code>. So <code>append</code> can just call\n<code>insertAt</code>.</p>\n\n<h2>Destructor</h2>\n\n<p>Your dynamic array allocates memory in the constructor, but there is\nno corresponding destructor that frees the memory. I've added one\nlooking like this:</p>\n\n<pre><code>~dynamic_array() {\n delete[] array;\n}\n</code></pre>\n\n<h2>Copying memory</h2>\n\n<p>There's a function called <code>std::copy</code> which you can use for copying\nmemory. That way, you don't have to write your own copy function.</p>\n\n<h2>Pointless comments</h2>\n\n<p>Writing good comments is hard. As a reviewer I much prefer no comments\nover pointless comments. An example of a pointless comment is <code>//\nconstructor init</code>. I can see that the lines below is the constructor\nso the comment doesn't tell me anything I didn't already know. Same\nfor the comment <code>// returns size of array</code>.</p>\n\n<h2>Source code</h2>\n\n<p>Here is the improved version of the dynamic array:</p>\n\n<pre><code>#include <assert.h>\n#include <cstring>\n#include <iostream>\n\nusing namespace std;\n\nconst int INITIAL_CAPACITY = 2;\nconst int GROWTH_FACTOR = 2;\n\ntemplate <class T>\nclass dynamic_array {\n T *array;\n int capacity = INITIAL_CAPACITY;\n int _size;\n\npublic:\n dynamic_array() {\n array = new T[capacity];\n _size = 0;\n }\n\n ~dynamic_array() {\n delete[] array;\n }\n\n void deleteAt(int pos) {\n assert(0 <= pos && pos < _size);\n _size--;\n for (int i = pos; i < _size; i++) {\n array[i] = array[i + 1];\n }\n }\n\n void insertAt(int element, int pos) {\n assert(0 <= pos && pos <= _size);\n if(_size == capacity) {\n resize();\n }\n for(int i = _size; i > pos; i--) {\n array[i] = array[i-1];\n }\n _size++;\n array[pos] = element;\n }\n\n void append(T element) {\n insertAt(element, _size);\n }\n\n int size() {\n return _size;\n }\n\n // doubles capacity if it has to and deletes reference to current array.\n void resize() {\n capacity *= GROWTH_FACTOR;\n T *temp = new T[capacity];\n copy(array, array + _size, temp);\n delete [] array;\n array = temp;\n }\n\n T get(int pos) {\n return array[pos];\n }\n\n void pretty_print() {\n cout << \"[\";\n for (int i = 0; i < _size - 1; i++) {\n cout << array[i] << \" \";\n }\n if (_size) {\n cout << array[_size - 1];\n }\n cout << \"]\\n\";\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T17:24:32.927",
"Id": "458810",
"Score": "0",
"body": "Using `memcpy` here is not a good idea, and will behave badly if T isn't trivially copyable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T18:46:04.693",
"Id": "458819",
"Score": "0",
"body": "True, it should be `std::copy`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T12:39:26.420",
"Id": "234587",
"ParentId": "234556",
"Score": "3"
}
},
{
"body": "<p>Hi and welcome to the site. Your code already looks quite good. However, there are still some issues beyond what @Björn Linqvist wrote.</p>\n\n<ol>\n<li><p><code>const</code> correctness</p>\n\n<p>This means that all variables as well as function arguments that are not mutated should be declared <code>const</code>. In addition methods that do not change the state of the object, aka pure observers should also be marked <code>const</code>. This greatly improves the ability to reason about code and helps the compiler help you. As an example</p>\n\n<pre><code>int size() const {\n return _size;\n}\n\nT get(const int pos) const {\n return array[pos];\n}\n</code></pre></li>\n<li><p>The latter function is an even better example as it shows that something is missing. Often inside <code>const</code> code pathes you need to access elements of the array. So you need both a <code>const</code> and a non-<code>const</code> accessor. Also you are returning a <em>copy</em> of the object. Generally, a reference is returned.</p>\n\n<pre><code>T& get(const int pos) {\n return array[pos];\n}\n\nconst T& get(const int pos) const {\n return array[pos];\n}\n</code></pre></li>\n<li><p>Your <code>deleteAt</code> function is subtly incorrect.</p>\n\n<pre><code>void deleteAt(int pos) {\n assert(0 <= pos && pos < _size);\n _size--;\n for (int i = pos; i < _size; i++) {\n array[i] = array[i + 1];\n }\n}\n</code></pre>\n\n<p>Here you are shifting the elements from <code>[pos, size_ - 1]</code> to the left. However, what happens when <code>T</code> is a nontrivial type that has a destructor? The element at position <code>size_</code> is copied to position <code>size_ - 1</code> but is still <code>alive</code>. You need to explicitely call <code>std::destroy</code> here or you will get a lot of incredibly hard to debug bugs.</p></li>\n<li><p>Honor conventional naming.</p>\n\n<p>C++ has a rich ecosystem of libraries and the STL. Most of these use consistent naming conventions, e.g. <code>insert</code> rather than <code>insertAt</code>. This might not seem a big deal but other programmers will have a hard time using your code. Even worse you will have a hard time using other code as you will mix those names. </p>\n\n<p>This is especially bad when naming contradicts expected behavior. <code>resize</code> conventionally takes a input argument that represents the size the container should have. Your <code>resize</code> method does something different so it will be highly confusing.</p></li>\n<li><p>Please do not use <code>using namespace std;</code> This will at some point get you in all sorts of trouble. Maybe not with the STL but definitely when you use it with other namespaces as the actual functionality of <code>using namespace foo</code> is highly surprising. There is a reason namespaces are generally short and typing <code>std::</code> is quite easy.</p></li>\n<li><p>Iterators.</p>\n\n<p>C++ algorithm use iterators as an incredibly powerfull abstraction. You should provide <code>begin()</code> and <code>end()</code> methods. Also you should understand why you would want <code>begin()</code> and <code>begin() const</code> and <code>cbegin()</code>. </p></li>\n<li><p>Algorithms. </p>\n\n<p>C++ algorithms are incredibly powerfull and the STL is full of them. You should have a look at the algorithms and try to use them in you code (insert and erase are good candidates). I can highly recommend Connor Hoekstra and his <a href=\"https://www.youtube.com/watch?v=pUEnO6SvAMo\" rel=\"nofollow noreferrer\">Algorithm Intuition</a> talk.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T20:04:12.070",
"Id": "234607",
"ParentId": "234556",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "234607",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T20:50:46.510",
"Id": "234556",
"Score": "3",
"Tags": [
"c++",
"beginner",
"algorithm",
"array"
],
"Title": "Dynamic Array Implementation in C++"
}
|
234556
|
<p>Here is a functional "card-drafting engine" which runs through pygame. It simulates fliping cards face up on the table, and the ability for two players to draft through the cards.There are two questions I have, and am very open to advice.</p>
<pre><code>import pygame
import random
import pandas as pd
"""Layout"""
DISPLAY_HEI = 700
DISPLAY_WID = 1400
CARD_WIDTH = 100
CARD_HEIGHT = 150
TOP_Y = 100
MID_Y = DISPLAY_HEI / 2 - CARD_HEIGHT / 2
BOT_Y = DISPLAY_HEI - CARD_HEIGHT - TOP_Y
CENTER_X = DISPLAY_WID / 2
CENTER_PH_X = CENTER_X - CARD_WIDTH / 2
LEFT_PH_1_X = CENTER_PH_X - (CARD_WIDTH * 3)
LEFT_PH_2_X = CENTER_PH_X - (CARD_WIDTH * 1.5)
RIGHT_PH_1_X = CENTER_PH_X + (CARD_WIDTH * 3)
RIGHT_PH_2_X = CENTER_PH_X + (CARD_WIDTH * 1.5)
PH_BOARDER = 10
DRAFTZONE_W = CARD_WIDTH * 1.5
DRAFTZONE_H = DISPLAY_HEI
P1_ZONE_X = 0
P1_ZONE_Y = 0
P2_ZONE_X = DISPLAY_WID - DRAFTZONE_W
P2_ZONE_Y = 0
FPS = 60
W = (166, 166, 166)
R = (255, 10, 10)
B = (64, 64, 64)
G = (45, 171, 7)
U = (7, 45, 171)
M = (222, 222, 7)
A = (140, 109, 45)
L = (125, 45, 125)
DARK_BRN = (71, 53, 34)
LIGHT_BRN = (181, 121, 58)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREY = (50, 50, 50)
</code></pre>
<p>Here we create the card list from which we are drafting.</p>
<pre><code>xlsx_file = 'cube2019-12-19.xlsx'
WHITE_DF = pd.read_excel(xlsx_file, 'White')
RED_DF = pd.read_excel(xlsx_file, 'Red')
BLACK_DF = pd.read_excel(xlsx_file, 'Black')
GREEN_DF = pd.read_excel(xlsx_file, 'Green')
BLUE_DF = pd.read_excel(xlsx_file, 'Blue')
MULTI_DF = pd.read_excel(xlsx_file, 'Multi')
ART_DF = pd.read_excel(xlsx_file, 'Artifact')
LAND_DF = pd.read_excel(xlsx_file, 'Land')
ALL_DF = [WHITE_DF, RED_DF, BLACK_DF, GREEN_DF, BLUE_DF, MULTI_DF, ART_DF, LAND_DF]
</code></pre>
<p>And we begin OOP...
For DRY, should I not have multiple classes all with 'render' and 'is_over' functions? Is there a neater way to write this?</p>
<pre><code>"""Placeholders will show up as background figures and will have the cards 'snap into place' when they are dragged onto them."""
class Placeholder(object):
def __init__(self, x, y, col, width=CARD_WIDTH + PH_BOARDER, height=CARD_HEIGHT + PH_BOARDER):
self.x = x
self.y = y
self.col = col
self.width = width
self.height = height
def render(self, screen):
pygame.draw.rect(screen, self.col, (self.x, self.y, self.width, self.height))
def is_over(self, pos):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
P1 = Placeholder(LEFT_PH_1_X, TOP_Y, BLACK)
P2 = Placeholder(LEFT_PH_2_X, TOP_Y, BLACK)
P3 = Placeholder(CENTER_PH_X, TOP_Y, BLACK)
P4 = Placeholder(RIGHT_PH_1_X, TOP_Y, BLACK)
P5 = Placeholder(RIGHT_PH_2_X, TOP_Y, BLACK)
P6 = Placeholder(LEFT_PH_1_X, MID_Y, BLACK)
P7 = Placeholder(LEFT_PH_2_X, MID_Y, BLACK)
P8 = Placeholder(CENTER_PH_X, MID_Y, BLACK)
P9 = Placeholder(RIGHT_PH_1_X, MID_Y, BLACK)
P10 = Placeholder(RIGHT_PH_2_X, MID_Y, BLACK)
P11 = Placeholder(LEFT_PH_1_X, BOT_Y, BLACK)
P12 = Placeholder(LEFT_PH_2_X, BOT_Y, BLACK)
P13 = Placeholder(CENTER_PH_X, BOT_Y, BLACK)
P14 = Placeholder(RIGHT_PH_1_X, BOT_Y, BLACK)
P15 = Placeholder(RIGHT_PH_2_X, BOT_Y, BLACK)
ALL_PH = [P1, P2, P3, P4, P5,
P6, P7, P8, P9, P10,
P11, P12, P13, P14, P15]
class Card(object):
def __init__(self, name, cmc, tpe, col, x=pos[0], y=pos[1], width=CARD_WIDTH, height=CARD_HEIGHT):
self.name = name
self.cmc = cmc
self.tpe = tpe
self.x = x
self.y = y
self.width = width
self.height = height
if col == 'W':
self.col = W
if col == 'R':
self.col = R
if col == 'B':
self.col = B
if col == 'U':
self.col = U
if col == 'G':
self.col = G
if col == 'MULTI':
self.col = M
if col == 'A':
self.col = A
if col == 'L':
self.col = L
def render(self, screen):
pygame.draw.rect(screen, self.col, (self.x, self.y, self.width, self.height))
font = pygame.font.SysFont('ariel', 18)
text = font.render(self.name, 1, WHITE)
screen.blit(text,
(self.x + (self.width / 2 - text.get_width() / 2),
self.y + (self.height / 2 - text.get_height() / 2)))
def is_over(self, pos):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
"""Technical name of the deck of cards that are being drafted is 'cube'."""
class Cube(object):
def __init__(self):
self.cards = []
self.build()
self.shuffle()
def build(self):
for df in ALL_DF:
for ind, row in df.iterrows():
self.cards.append(
Card(name=row['Name'], cmc=row['CMC'],
tpe=row['Type'], col=row['Color'])
)
def shuffle(self):
random.shuffle(self.cards)
def top_card(self):
return self.cards.pop()
class DraftZone(object):
def __init__(self, x, y, col=LIGHT_BRN, width=DRAFTZONE_W, height=DRAFTZONE_H):
self.col = col
self.x = x
self.y = y
self.width = width
self.height = height
def render(self, screen):
pygame.draw.rect(screen, self.col, (self.x, self.y, self.width, self.height))
font = pygame.font.SysFont('ariel', 18)
text = font.render('DraftZone', 1, WHITE)
screen.blit(text,
(self.x + (self.width / 2 - text.get_width() / 2),
self.y + (self.height / 2 - text.get_height() / 2)))
def is_over(self, pos):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
</code></pre>
<p>Here's where I got confused. I wanted to obviously have a single class Player, but ran into trouble. I would create player1 = Player... and player2 = Player... BUT whenever either player 'drafted' a card, <em>both</em> players' rosters would be updated (because I assume, the class "Player" had a single 'roster list' which was being appended by the 'draft' function.
I don't know how to do this, and would love some suggestions.</p>
<pre><code>class Player1(object):
def __init__(self, d_zone_x, d_zone_y, name):
self.d_zone_x = d_zone_x
self.d_zone_y = d_zone_y
self.draft_zone = DraftZone(self.d_zone_x, self.d_zone_y)
self.name = name
roster = []
def draft(self, card):
pick_num = len(self.roster) + 1
self.roster.append((pick_num, card.name))
class Player2(object):
def __init__(self, d_zone_x, d_zone_y, name):
self.d_zone_x = d_zone_x
self.d_zone_y = d_zone_y
self.draft_zone = DraftZone(self.d_zone_x, self.d_zone_y)
self.name = name
roster = []
def draft(self, card):
pick_num = len(self.roster) + 1
self.roster.append((pick_num, card.name))
PLAYER1 = Player1(P1_ZONE_X, P1_ZONE_Y, 'Player 1')
PLAYER2 = Player2(P2_ZONE_X, P2_ZONE_Y, 'Player 2')
PLAYERS = [PLAYER1, PLAYER2]
def print_rosters():
for player in PLAYERS:
print(f'\n{player.name}:')
for each in player.roster:
print(each)
</code></pre>
<p>And the main, of course.</p>
<pre><code>def main():
pygame.init()
cube = Cube()
screen = pygame.display.set_mode((DISPLAY_WID, DISPLAY_HEI))
running = True
render_list = []
mouse_pressed = False # pressed down THIS frame
mouse_down = False # mouse held down
mouse_released = False # released THIS frame
right_clicked = False # to delete
target = None # target of drag / drop or delete
while running:
screen.fill(DARK_BRN)
PLAYER1.draft_zone.render(screen)
PLAYER2.draft_zone.render(screen)
for ph in ALL_PH:
ph.render(screen)
pos = pygame.mouse.get_pos()
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
print_rosters() # Print rosters on exit.
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
mouse_pressed = True
mouse_down = True
elif event.button == 3:
right_clicked = True
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
mouse_released = True
mouse_down = False
"""Handling 'drag and drop'."""
if mouse_pressed:
for item in render_list:
if item.is_over(pos):
target = item
if target is None: # create new card if you're not dragging one
target = cube.top_card()
render_list.append(target)
if mouse_down and target is not None:
target.x = pos[0] - CARD_WIDTH / 2 # grabs the center of the card
target.y = pos[1] - CARD_HEIGHT / 2
if mouse_released:
for ph in ALL_PH: # snap-to-placeholders
if ph.is_over(pos):
target.x = ph.x + PH_BOARDER / 2
target.y = ph.y + PH_BOARDER / 2
for player in PLAYERS: # drafting cards
if player.draft_zone.is_over(pos):
player.draft(target)
render_list.remove(target)
target = None
if right_clicked: # right-click to delete
for item in render_list:
if item.is_over(pos):
render_list.remove(item)
for item in render_list:
item.render(screen)
mouse_pressed = False
mouse_released = False
right_clicked = False
# mid_clicked = False
pygame.display.flip()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>(I'm on my phone on a road trip, so I can't do anything fancy here)</p>\n\n<p>Your issues with <code>roster</code> are because you have it as a attribute of the class, not an instance attribute. That means that every instance shares the same <code>roster</code>. You need to define it in the <code>__init__</code> (or elsewhere, but ideally in the initializer) as <code>self.roster</code>, just like you did with the other instance attributes.</p>\n\n<pre><code>class Player:\n def __init__(self, d_zone_x, d_zone_y, name):\n self.d_zone_x = d_zone_x\n self.d_zone_y = d_zone_y\n self.draft_zone = DraftZone(self.d_zone_x, self.d_zone_y)\n self.name = name\n self.roster = [] # Here\n\n def draft(self, card):\n pick_num = len(self.roster) + 1\n self.roster.append((pick_num, card.name))\n</code></pre>\n\n<p>When referring to it previously, <code>self.roster</code> worked despite it not being an instance attribute because you can refer to class attributes using an instance. Also note, you don't need <code>(object)</code> in Python 3. That was important in 2, but Python 3 uses \"new style\" classes by default. </p>\n\n<p>With that change, now you can write:</p>\n\n<pre><code>PLAYER1 = Player(P1_ZONE_X, P1_ZONE_Y, 'Player 1')\nPLAYER2 = Player(P2_ZONE_X, P2_ZONE_Y, 'Player 2')\n\nPLAYERS = [PLAYER1, PLAYER2]\n</code></pre>\n\n<hr>\n\n<p>I think your use of UPPERCASE names for some variables like <code>PLAYER1</code> and <code>PLAYER2</code> are inappropriate. In my mind, constants (which uppercase signifies) are variables that always hold the same value. Now, you never reassign <code>PLAYER1</code>, <em>but</em>, since it and <code>PLAYER2</code> are mutable, they don't maintain the same value throughout the program.</p>\n\n<p>Yes, it could be argued that the \"value\" being referred to as constant is the reference to the object, not the value of the object itself.</p>\n\n<p>I'm going to suggest though only treating objects as constants if the <em>value of the object itself, as well as the reference to it</em> remain constant. I'd like to hear though if anyone disagrees with me on this point.</p>\n\n<hr>\n\n<p>I think the <code>if col ==</code> checks in <code>Card</code> could be neatened up using a dictionary. Something like:</p>\n\n<pre><code>COL_NAME_TO_VALUE = \\\n {\"W\": W, \n \"R\": R\n . . . }\n\n. . . \n\nself.col = COL_NAME_TO_VALUE[col]\n</code></pre>\n\n<p>That gets rid of all the duplicate <code>if col == . . .: self.col =. . .</code> bits which would complicate refactoring later. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T20:50:20.893",
"Id": "458925",
"Score": "0",
"body": "Yes, thank you. All good advice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T23:59:45.563",
"Id": "234567",
"ParentId": "234560",
"Score": "3"
}
},
{
"body": "<p>In addition to what @Carcigenicate said:</p>\n\n<p>Spell out <code>color</code> instead of <code>col</code> - I thought it was short for <code>column</code>.</p>\n\n<p><code>pygame</code> has a Rect class. Use it instead of separate x,y,width,height attributes. The Rect class already implements <code>is_over</code>-functionality. If desired, some common code can be pulled out into a parent/base class.</p>\n\n<p>Make text bliting into a standalone function.</p>\n\n<p>Example code (untested) to give you an idea:</p>\n\n<pre><code>PH_WIDTH = CARD_WIDTH + PH_BORDER\nPH_HEIGHT = CARD_HEIGHT + PH_BORDER\n\nARIEL18 = pygame.font.SysFont('ariel', 18)\n\ndef blittext(text, point, font, color):\n text = font.render(text, True, color)\n screen.blit(text,\n (point.x - text.get_width() / 2),\n (point.y - text.get_height() / 2))\n\nclass GameObject:\n def __init__(self, color, rect):\n self.color = color\n self.rect = rect\n\n def is_over(self, point):\n return self.rect.collidepoint(point)\n\n\nclass Placeholder(GameObject):\n def __init__(self, color, x, y):\n super().__init__(color, Rect(x, y, PH_WIDTH, PH_HEIGHT))\n\n def render(self, screen):\n pygame.draw.rect(screen, self.col, self.rect)\n\n\nclass Card(GameObject):\n def __init__(self, color, x, y, name, cmc, tpe):\n super().__init__(self, color, Rect(x, y, CARD_WIDTH, CARD_HEIGHT))\n self.name = name\n self.cmc = cmc\n self.tpe = tpe\n\n\n def render(self, screen):\n pygame.draw.rect(screen, self.color, self.rect)\n blittext(self.name, point, ARIAL18, WHITE)\n\n\nclass DraftZone(GameObject):\n def __init__(self, color, x, y):\n self.color = color\n super().__init__(color, Rect(x, y, DRAFTZONE_W, DRAFTZONE_H)\n\n def render(self, screen):\n pygame.draw.rect(screen, self.color, self.rect)\n blittext('DraftZone', point, ARIAL18, WHITE)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T17:19:29.470",
"Id": "458809",
"Score": "1",
"body": "@Graipher - Yes, fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T20:51:14.103",
"Id": "458926",
"Score": "0",
"body": "Appreciated. Didn't know about collidepoint..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T08:07:53.463",
"Id": "234578",
"ParentId": "234560",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T22:18:44.743",
"Id": "234560",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"gui",
"pygame"
],
"Title": "Card-'Drafting' Engine"
}
|
234560
|
<p>I am trying to code a menu that:</p>
<p>Is horizontal on lg+ displays at the top of the page</p>
<ul>
<li>Shows a hamburger menu when the user scrolls from the top</li>
<li>Will display as the collapsed format when the hamburger is clicked on desktop and mobile</li>
<li>I managed to code this in a way that exhibits all of the proper behaviors, but it feels realllly hackish. I'm thinking there absolutely has to be a better way to accomplish this.</li>
</ul>
<p>I'd really appreciate it if someone could take a look at this and let me know what the best way to accomplish this is.</p>
<p>Codeply is here: <a href="https://www.codeply.com/p/tODl9hO4Xr" rel="nofollow noreferrer">https://www.codeply.com/p/tODl9hO4Xr</a></p>
<p>Thanks in advance for your advice.</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style type="text/css">
.kc-inside-navigation {
background: #f4f3f1;
height: 73px;
border-bottom: 2px solid #00654e;
}
body {
padding-top: 72px;
}
.nav-collapse .menu {
width: 90%;
height: 100%;
float: right;
background: white;
-webkit-box-shadow: 20px 3px 29px -28px rgba(0, 0, 0, 0.75);
-moz-box-shadow: 20px 3px 29px -28px rgba(0, 0, 0, 0.75);
box-shadow: 20px 3px 29px -28px rgba(0, 0, 0, 0.75);
}
.nav-collapse .dropdown-menu {
position: fixed;
}
.nav-collapse .kc-utility-navigation {
background: #00654e;
}
.nav-collapse .kc-utility-navigation ul {
list-style-type: none;
padding: 0;
font-weight: 300;
font-size: .9rem;
columns: 2;
-webkit-columns: 2;
-moz-columns: 2;
margin-bottom: 0;
}
.kc-inside-navigation .cta-btn {
color: #fff;
text-transform: uppercase;
font-weight: 500;
padding: 0.5rem;
}
@media (min-width: 992px) {
.kc-inside-navigation .cta-btn {
margin-right: 1.5rem;
}
.kc-inside-navigation .cta-btn:last-child {
margin-right: 0;
}
.kc-inside-navigation .cta-btn span {
padding-left: 0.5rem;
}
.kc-inside-navigation .cta-btn i {
font-size: 1.5rem;
}
.kc-inside-navigation .phone a {
color: #00654e;
}
body {
padding-top: 110px;
}
.nav-expand {
background: #fff;
}
.nav-expand ul.navbar-nav {
display: flex;
flex-direction: row;
height: 40px;
}
.nav-expand li.nav-item {
margin-right: 1.5rem;
}
.nav-expand a:link, .nav-expand a:visited {
color: #00654e;
}
.nav-expand .kc-utility-navigation {
display: none;
}
.nav-collapse .menu {
width: 40%;
}
}
</style>
<title>Test Item</title>
</head>
<body>
<header class="fixed-top">
<div class="d-flex kc-inside-navigation">
<div class="container align-self-center">
<div class="d-flex justify-content-between">
<a href="index.html" class="navbar-brand align-self-center"><img src="http://placehold.it/250x40" alt="Logo"></a>
<div class="kc-cta-buttons d-flex align-self-center">
<a class="cta-btn btn-rfi d-flex flex-fill align-self-center" href="boring.html"><span class="align-self-center">Request More Info</span> <i class="align-self-center fas fa-angle-right"></i></a>
<a class="cta-btn btn-apply d-flex flex-fill align-self-center" href="#"><span class="align-self-center">Apply Now</span> <i class="align-self-center fas fa-angle-right"></i></a>
<a class="cta-btn btn-txt d-flex flex-fill d-lg-none align-self-center" href="sms:5857661304"><span class="align-self-center">Text a Question</span> <i class="align-self-center fas fa-mobile-alt"></i></i></a>
<a class="cta-link d-none d-lg-block align-self-center" href="tel:18003353852">1-800-335-3852</a>
</div>
<div class="align-self-center" style="width: 35px">
<button class="navbar-toggler collapsed align-self-center p-0" id="mainNavButton" type="button" data-toggle="collapse" data-target="#theDropdown" aria-controls="theDropdown" aria-expanded="false" aria-label="Toggle navigation" style="display: none">
<span class="icon"></span><span>Menu</span>
</button>
</div>
</div>
</div>
</div>
<div id="theDropdown" class="nav-expand collapse show">
<div class="wrapper">
<div class="container">
<div class="menu">
<nav class="">
<ul class="navbar-nav" id="mainMenu">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="academicsNavbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Academics
</a>
<div class="dropdown-menu" aria-labelledby="academicsNavbarDropdown">
<a class="dropdown-item" href="#">Majors and Programs</a>
<a class="dropdown-item" href="#">Evening and Online</a>
<a class="dropdown-item" href="#">Graduate Programs</a>
<a class="dropdown-item" href="#">Field Period®</a>
<a class="dropdown-item" href="#">Experiential Learning</a>
<a class="dropdown-item" href="#">Career Development</a>
<a class="dropdown-item" href="#">Global Education</a>
<a class="dropdown-item" href="#">Your Faculty</a>
<a class="dropdown-item dropdown-toggle" href="#" id="academicResourcesNavbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Resources</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="admissionsNavbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Admissions
</a>
<div class="dropdown-menu" aria-labelledby="admissionsNavbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="tuitionNavbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Tuition &amp; Aid
</a>
<div class="dropdown-menu" aria-labelledby="tuitionNavbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="lifeNavbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Life @ KC
</a>
<div class="dropdown-menu" aria-labelledby="lifeNavbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link" href="#" id="athleticsNavbarDropdown" role="button">
Athletics
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link" href="#" id="fpNavbarDropdown">
Field Period®
</a>
</li>
</ul>
<div class="kc-utility-navigation">
<div class="container ml-0 pl-0 ml-lg-auto pl-lg-auto" id="kc-utility-container">
<ul class="something">
<li class="nav-item"><a href="#" class="nav-link">KC Portal</a></li>
<li class="nav-item"><a class="nav-link">Directory</a></li>
<li class="nav-item"><a class="nav-link">About</a></li>
<li class="nav-item"><a class="nav-link">Library</a></li>
<li class="nav-item"><a class="nav-link">Email</a></li>
<li class="nav-item"><a class="nav-link">News &amp; Events</a></li>
<li class="nav-item"><a class="nav-link">Alumni</a></li>
<li class="nav-item"><a class="nav-link">Make a Gift</a></li>
</ul>
</div>
</div>
</nav>
</div>
</div>
</div>
</div>
</header>
<div style="height: 1000px;"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
changeNavbar();
$(window).resize(function () {
changeNavbar();
});
$(window).scroll(function () {
changeNavbar();
});
function changeNavbar() {
var theDropdown = $("#theDropdown");
var windowWidth = $(window).width();
if (windowWidth < 992) {
// if it's xs, xm, or md, just keep the navbar collapsed.
theDropdown.removeClass("nav-expand show").addClass("nav-collapse");
$('.kc-inside-navigation .navbar-toggler').show();
} else {
if ($(this).scrollTop() >= 100) {
if (theDropdown.hasClass('show') && (theDropdown.hasClass('nav-collapse'))) {
// do nothing because the user has expanded the collapse and is scrolling.
} else {
$('.kc-inside-navigation .navbar-toggler').fadeIn();
theDropdown.removeClass("nav-expand show").addClass("nav-collapse");
}
} else {
theDropdown.removeClass("nav-collapse").addClass("nav-expand show");
$('.kc-inside-navigation .navbar-toggler').addClass("collapsed");
if (windowWidth > 992) {
$('.kc-inside-navigation .navbar-toggler').fadeOut();
}
}
}
}
$(".kc-inside-navigation .navbar-toggler").click(function() {
var menuTarget = $(this).data('target');
menuTarget.toggle();
});
});
</script>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T15:02:21.613",
"Id": "458792",
"Score": "0",
"body": "Welcome to the code review website. Is the code working as expected? Are all the features you want in the code implemented? On this website we review code and provide suggestions on how the code can be improved. We can't help you implement features that are not implemented yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T15:44:58.267",
"Id": "458801",
"Score": "0",
"body": "Yes. It's doing everything I need, but I feel like it's a bit hackish. Just looking for ways to improve it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T22:32:10.180",
"Id": "234563",
"Score": "4",
"Tags": [
"jquery",
"html",
"css",
"twitter-bootstrap"
],
"Title": "Bootstrap 4 Menu Collapse on Scroll"
}
|
234563
|
<p>My application state is represented by a string of numbers and I'm trying to encode the string so that it is as small as possible (ie. fewest number of characters). An example string would be: <code>133223333302302040</code></p>
<p>I realized that most of these strings consist of number pairs containing <code>0</code>, <code>1</code>, <code>2</code>, <code>3</code> (<code>4</code> and <code>5</code> also exist but are rare). I decided to replace the most common number pairs with letters, shortening my encoded string by ~50%</p>
<p>I have a function that returns the mapping:</p>
<pre><code>function getValueMap(lettersFirst = false) {
const map = {
'00': 'a',
'01': 'b',
'02': 'c',
'03': 'd',
'10': 'e',
'11': 'f',
'12': 'g',
'13': 'h',
'20': 'i',
'21': 'j',
'22': 'k',
'23': 'l',
'30': 'm',
'31': 'n',
'32': 'o',
'33': 'p'
};
if (lettersFirst) {
return Object.fromEntries(Object.entries(map).map(([k, v]) => [v, k]));
} else {
return map;
}
}
</code></pre>
<p>To encode, I iterate through every pair of input numbers, check if it is in the map, and if so, add the letter to the encoded output. For odd length inputs I simply remove the last digit, dont encode it, and simply append the number to the output string untouched:</p>
<pre><code>encode(text) {
const map = getValueMap();
let values;
let suffix = '';
if (text.length % 2 !== 0) {
suffix = text.charAt(text.length - 1);
values = text.slice(0, -1);
} else {
values = text;
}
let encoded = '';
for (let i = 0; i <= text.length - 2; i += 2) {
if (map[values[i] + values[i + 1]]) {
encoded += map[values[i] + values[i + 1]];
} else {
encoded += values[i] + values[i + 1];
}
}
encoded += suffix;
return encoded;
}
</code></pre>
<p>To decode, iterate through the string, if its a letter, add the corresponding number pair to the decoded output. If its already a number, simply add the number instead:</p>
<pre><code>decode(encoded) {
const map = getValueMap(true);
let decoded = '';
for (let i = 0; i < encoded.length; i++) {
if (encoded[i].toLowerCase() !== encoded[i].toUpperCase()) {
decoded += map[encoded[i]];
} else {
decoded += encoded[i];
}
}
return decoded;
}
</code></pre>
<p>Some example inputs and outputs:</p>
<pre><code>Encode:
13223233202200252044 -> hkopika25i44
Decode:
holppcmi40 -> 133223333302302040
</code></pre>
<p>Is there a more straightforward way to do this? My implementation feels unnecessarily obtuse. For example, do I actually need to create a map/reverse map when I could maybe rely on indexing the pair array or alphabet instead? Is there a more elegant way to iterate over pairs of numbers? Or to build up the final encoded/decoded form without appending to a string?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T09:58:07.360",
"Id": "458876",
"Score": "0",
"body": "Does the string of numbers have a maximum length?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T11:10:00.113",
"Id": "458881",
"Score": "0",
"body": "The max length will fluctuate between 20-22. Each individual number within that string cannot be greater than 5"
}
] |
[
{
"body": "<p>First a few suggestions to your design.\nYou are effectively trying to represent list of small numbers as <code>String</code>, with no actual meaning (at least that's how I understood it).\nI'd consider:</p>\n\n<ul>\n<li>Represent it for what it is - list of small numbers could be represented as byte array. That seems a lot more natural and convenient.</li>\n<li>Use some simpler mapping, if it doesn't matter what kind of character is the result. If numbers really are in range between 0 and 32 and not much higher, I'd go for mapping function, that for example adds 65 (and substracts 65 in reverse). That mapping function is really simple and you don't need any kind of map. Your code would be reduced only to initial tokenization basically. <code>00</code> becomes <code>A</code>, <code>30</code> becomes <code>_</code> according to their ASCII codes (+65).</li>\n</ul>\n\n<p>In case you wanna keep your String representation, here are my points to your code:</p>\n\n<p><code>getValueMap</code></p>\n\n<ul>\n<li>Names <code>getValueMap</code> name and <code>lettersFirst</code> don't really say what much about what do they do. </li>\n<li>There's no point to recalculate reverse map everytime. Flag parameters with this kind of <code>if</code> are typical code smell and bad practice. </li>\n<li>I suggest creating 2 module variables <code>codesToCharacters</code> (original map) and <code>charactersToCodes</code> (once pre-calculated) instead. </li>\n</ul>\n\n<p><code>decode</code></p>\n\n<ul>\n<li>I'd love if this function was just mapping encoded data to decoded data based on mapping function. </li>\n<li>Not sure, why is there that <code>if</code>. I think you are trying to check, if current character is letter or not and if so, map it, otherwise use the character. That took me a while to understand. If there was really need, I would extract that to function with propper name (like <code>isLetter</code>) to increase readability.</li>\n<li>Anyway, why even doing that? Why not instead look into the map and if map contains key, use map value, otherwise use original character.</li>\n</ul>\n\n<p>Function would look something like (pseudocode, not tested):</p>\n\n<pre><code>function decode(encoded) {\n\n return encoded.split(\"\").map(\n c => {\n charactersToCodes.hasKey(c) ? charactersToCodes[c] : c\n }).join()\n\n}\n</code></pre>\n\n<p><code>encode</code> would be on same principle, only difference is, that you need to tokenize it correctly first and then map :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T11:47:06.470",
"Id": "458770",
"Score": "0",
"body": "Thanks for your insight! Your suggested approach with `map` is so much more elegant"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T05:18:30.547",
"Id": "234572",
"ParentId": "234570",
"Score": "2"
}
},
{
"body": "<p>Another simple solution would be base conversion. The original string contains the characters <code>0</code> to <code>5</code>, meaning it is in base 6. Every pair of characters can therefore be encoded as one base 36 character. The resulting string will contain the characters <code>a</code> to <code>z</code> and <code>0</code> to <code>9</code>.</p>\n\n<p>A string of length <code>n</code> will, after conversion, have length <code>n/2</code> if <code>n</code> is even, or <code>(n/2) + 1</code> if <code>n</code> is odd. </p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function convertBase(str, fromBase, toBase) {\n return parseInt(str, fromBase).toString(toBase);\n}\n\nfunction encode(str) {\n const hasEvenLength = str.length % 2 === 0;\n const chuncks = hasEvenLength ? [] : [str.substr(0, 1)];\n const startIndex = hasEvenLength ? 0 : 1;\n for (let i = startIndex; i < str.length - 1; i += 2) {\n chuncks.push(str.substr(i, 2));\n }\n return chuncks.map(chunck => convertBase(chunck, 6, 36)).join('');\n}\n\nfunction decode(str) {\n return str.split('').map(char => convertBase(char, 36, 6)).join('');\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T11:22:31.997",
"Id": "234629",
"ParentId": "234570",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234572",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T02:04:47.700",
"Id": "234570",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Encode/decode number pairs to letters"
}
|
234570
|
<p>I wrote the following Python program to take 1 word from the user and return certain characters replaced by numbers. Given a dictionary, the program should print all possible combinations of the same word with various characters substituted:</p>
<pre><code>import sys
def main(argv):
if len(argv) != 2:
print(f"USAGE: {argv[0]} [word]")
return
replacements = {}
# Populate the known replacements
replacements['i'] = ['1']
replacements['e'] = ['3']
replacements['m'] = ['/v\\']
replacements['a'] = ['4']
replacements['r'] = ['2']
replacements['o'] = ['0']
print_possibilities(argv[1], replacements, [])
def print_possibilities(s: str, replacements: dict, dupes: list):
ctr = 0
tally = 0
for c in s:
if c.lower() in replacements:
tally += 1
if tally == 0:
return
for c in s:
if c.lower() in replacements:
for r in replacements[c.lower()]:
tmp = list(s)
tmp[ctr] = r
as_str = ''.join(tmp)
if as_str in dupes:
continue
print(as_str)
dupes.append(as_str)
print_possibilities(as_str, replacements, dupes)
ctr += 1
return
if __name__ == '__main__':
main(sys.argv)
</code></pre>
<p>I've tested with <code>python3 replace_word.py mondoman</code> and I get this output:</p>
<pre><code>/v\ondoman
/v\0ndoman
/v\0nd0man
/v\0nd0/v\an
/v\0nd0/v\4n
/v\0nd0m4n
/v\0ndo/v\an
/v\0ndo/v\4n
/v\0ndom4n
/v\ond0man
/v\ond0/v\an
/v\ond0/v\4n
/v\ond0m4n
/v\ondo/v\an
/v\ondo/v\4n
/v\ondom4n
m0ndoman
m0nd0man
m0nd0/v\an
m0nd0/v\4n
m0nd0m4n
m0ndo/v\an
m0ndo/v\4n
m0ndom4n
mond0man
mond0/v\an
mond0/v\4n
mond0m4n
mondo/v\an
mondo/v\4n
mondom4n
</code></pre>
<p>I feel that this could be improved to be more performant and more idiomatic and would like a code review.</p>
|
[] |
[
{
"body": "<p>Think about the problem as a repeated Cartesian product. It allows us\nto use the very useful <code>product</code> function from the <code>itertools</code> module:</p>\n\n<pre><code>>>> list(product('ab', 'AB', 'xy'))\n[('a', 'A', 'x'), ('a', 'A', 'y'), ('a', 'B', 'x'),\n('a', 'B', 'y'), ('b', 'A', 'x'), ('b', 'A', 'y'),\n('b', 'B', 'x'), ('b', 'B', 'y')]\n</code></pre>\n\n<p>So your problem can be solved by replacing each character in the\nstring with its possible replacemnets and running <code>product</code> on the\nresult:</p>\n\n<pre><code>import itertools\nimport sys\n\ndef alternatives(ch, repls):\n key = ch.lower()\n if key in repls:\n return [ch, repls[key]]\n return [ch]\n\ndef main(argv):\n if len(argv) != 2:\n print(f\"USAGE: {argv[0]} [word]\")\n return\n\n # Populate the known replacements\n replacements = {'a' : '4', 'e' : '3', 'i' : '1',\n 'm' : '/v\\\\', 'o' : '0', 'r' : '2'}\n\n s = [alternatives(ch, replacements) for ch in argv[1]]\n for it in itertools.product(*s):\n print(''.join(it))\n\nif __name__ == '__main__':\n main(sys.argv)\n</code></pre>\n\n<p>Note that this version is not exactly identical to your original. If\nyou enter \"mondoman\" the program will output \"mondoman\" as one\ncombination.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T15:13:44.820",
"Id": "458795",
"Score": "1",
"body": "I was just looking at this question thinking \"oo, this looks like a good place for `itertools`\" but you beat me to the answer. :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T13:55:28.130",
"Id": "234589",
"ParentId": "234573",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T05:36:46.133",
"Id": "234573",
"Score": "2",
"Tags": [
"python",
"strings",
"hash-map"
],
"Title": "Print a word with numbers substituted for characters"
}
|
234573
|
<h1>Scenario</h1>
<p>A session would start & end within a time frame. Within this time frame, the device would be moving within a constraint environment. The movement would be extremely slow (slow-walking to stillness).</p>
<p>This session could (& would) be entered & exited several times, although doing just a single session might be sufficient for the user.</p>
<h1>Objective</h1>
<p>Once this session is complete, it is the intention to have a location that would help any other user to get to that location. So during the session, a single location data would be recorded. The objective is to have the most accurate & precise single location data.</p>
<p><strong>Device</strong>: any iOS device</p>
<h1>Required parameters</h1>
<ol>
<li><a href="https://developer.apple.com/documentation/corelocation/cllocationcoordinate2d/1423513-latitude" rel="nofollow noreferrer">Latitude</a></li>
<li><a href="https://developer.apple.com/documentation/corelocation/cllocationcoordinate2d/1423552-longitude" rel="nofollow noreferrer">Longitude</a></li>
<li><a href="https://developer.apple.com/documentation/corelocation/cllocation/1423599-horizontalaccuracy" rel="nofollow noreferrer">Horizontal Accuracy</a></li>
<li><a href="https://developer.apple.com/documentation/corelocation/cllocation/1423820-altitude" rel="nofollow noreferrer">Altitude</a></li>
<li><a href="https://developer.apple.com/documentation/corelocation/cllocation/1423550-verticalaccuracy" rel="nofollow noreferrer">Vertical Accuracy</a></li>
</ol>
<p>I have a class called as LocationData.cs, where data is being populated whenever there is an update.</p>
<p>// LocationData.cs</p>
<pre><code>internal static class LocationData
{
internal static double Altitude = DummyValue;
internal static double VerticalAccuracy = DummyValue;
internal static double HorizontalAccuracy = DummyValue;
internal static ISN_CLLocationCoordinate2D Coordinate = new ISN_CLLocationCoordinate2D(0,0);
}
</code></pre>
<p>Now using the data available, how to figure the best accurate & precise location?</p>
<p>Here is my approach. The following method runs through the entire session.</p>
<pre><code>private IEnumerator examineForAccurateAndPreciseLocationData()
{
do
{ // Starts when session starts
assignHorizontalLocationValuesAppropriately();
assignVerticalLocationValuesAppropriately();
// This do-while loop runs every 1 second
yield return new WaitForSeconds(1f);
} while (CreateSessionBuffer.ISrunning == true);
// ends when session is complete
}
private void assignHorizontalLocationValuesAppropriately()
{
if (LocationData.HorizontalAccuracy < 0)
{ return; }// Just in case if there is an absence of reliable data
// If accuracy is less than a positive number, it assigns an immediate value
if (XPHeader.Location.HorizontalAccuracy < System.Double.Epsilon)
{
XPHeader.Location.HorizontalAccuracy = LocationData.HorizontalAccuracy;
XPHeader.Location.Coordinate.Latitude = LocationData.Coordinate.Latitude;
XPHeader.Location.Coordinate.Longitude = LocationData.Coordinate.Longitude;
}
else if (XPHeader.Location.HorizontalAccuracy > LocationData.HorizontalAccuracy)
{ // if there is a better accuracy, then it assigns the value that is available
XPHeader.Location.HorizontalAccuracy = LocationData.HorizontalAccuracy;
XPHeader.Location.Coordinate.Latitude = LocationData.Coordinate.Latitude;
XPHeader.Location.Coordinate.Longitude = LocationData.Coordinate.Longitude;
}
}
private void assignVerticalLocationValuesAppropriately()
{
if (LocationData.VerticalAccuracy < 0)
{ return; }
if (XPHeader.Location.VerticalAccuracy < System.Double.Epsilon)
{
XPHeader.Location.VerticalAccuracy = LocationData.VerticalAccuracy;
XPHeader.Location.Altitude = LocationData.Altitude;
}
else if (XPHeader.Location.VerticalAccuracy > LocationData.VerticalAccuracy)
{
XPHeader.Location.VerticalAccuracy = LocationData.VerticalAccuracy;
XPHeader.Location.Altitude = Geo.LocationData.Altitude;
}
}
</code></pre>
<p>Thank you for your time.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T06:42:20.113",
"Id": "458869",
"Score": "0",
"body": "maybe this would help you out https://developer.apple.com/documentation/corelocation/getting_the_user_s_location/using_the_standard_location_service"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T05:48:12.143",
"Id": "459056",
"Score": "0",
"body": "Thank you for your response. I have applied that information found in that article when I populate LocationData.cs."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T05:48:06.793",
"Id": "234574",
"Score": "3",
"Tags": [
"c#",
"beginner",
"unity3d",
"geospatial",
"location-services"
],
"Title": "Accurate && precise location data within a timeframe (session)?"
}
|
234574
|
<p>This is an AI class that takes an array of the board as an argument, and plays the best move after evaluating the board and gets a win rate. I haven't used any java package to do this. How can I make a genetic tree and calculate all possibilities for a given situation</p>
<pre><code>public class AI
{
int turn,ID;
AI(int pID)
{
ID=pID;
turn=0;
}
int getWinRate(int t[])
{
int comb[][] = {{1,2,3},{4,5,6},{7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}} ;
int AIwin,oppWin,empty,j,d;
int WinRate = 0;
for(int i=0;i<8;i++) //Count AI win combinations
{
AIwin=oppWin=empty=0;
for(j=0;j<3;j++)
{
d= comb[i][j]-1;
if(t[d]==2)
AIwin++;
if(t[d]==1)
oppWin++;
if(t[d]==0)
empty++;
}
//Changing win rate according to win conditions
if(AIwin==3)
WinRate+=100;
if(AIwin==2 && empty==1)
WinRate+=3;
if(oppWin==2 && empty==1)
WinRate-=10;
}
return WinRate;
}
void play(int t1[])
{
int t[]=t1.clone();
int i,j,c=0;
for(i=0;i<9;i++){
if(t[i]==0)
c++;
}
int[] moves=new int[c];
c=0;
for(i=0;i<9;i++)
{
if(t[i]==0)
{ moves[c++]=i;}
}
int rate,boardcopy[]=t.clone();boardcopy[moves[0]]=2;
int bestMove=moves[0],maxRate=getWinRate(boardcopy);
for(i=0;i<moves.length;i++)
{
boardcopy=t.clone();
boardcopy[moves[i]]=2;
rate=getWinRate(boardcopy);
if(rate>maxRate)
{
maxRate=rate;
bestMove=moves[i];
}
}
System.out.println("The Mighty AI plays : "+(bestMove+1));
turn++;
t1[bestMove]=2;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't see what the actual question is, but I assume you want someone to review your code in a general way.</p>\n\n<p><strong>You should always use explicit rather than implicit scoping.</strong></p>\n\n<pre><code>int getWinRate(int t[]){} //implicit scoping (not recommended)\n\npublic int getWinRate(int t[]){} //explicit scoping (recommended)\n</code></pre>\n\n<p><strong>Define single variable, field or method per line, for more clearer code.</strong></p>\n\n<pre><code>int AIwin,oppWin,empty,j,d; // not recommended\n\nint oppWin; // recommended\nint empty;\nint j;\nint d;\n</code></pre>\n\n<p><strong>Class names start with uppercase letters and fields, methods an variables names start with lowercase letters.</strong></p>\n\n<pre><code>int WinRate = 0; // not recommended\n\nint winRate = 0; // recommended\n</code></pre>\n\n<p><strong>Define iterators in <code>for</code> loops, and if you don't use array index in the calculations maybe you should use <a href=\"https://www.geeksforgeeks.org/for-each-loop-in-java/\" rel=\"nofollow noreferrer\"><code>foreach</code></a> function.</strong></p>\n\n<pre><code>int i;\n\nfor(i=0;i<9;i++) // not recommended\n{\n if(t[i]==0)\n { moves[c++]=i;}\n} \n\nfor(int i = 0; i < 9; i++) // recommended\n{\n if(t[i] == 0)\n {moves[c++] = i;}\n} \n\nfor(int i : t) // recommended foreach function\n{\n if(i == 0) // i - is not a iterator, but a array member\n {\n // Do some thing with i\n }\n} \n</code></pre>\n\n<p>Overall your code looks far to complex for it's simple task. Hope this helps you to improve yourself in coding.</p>\n\n<p>I suggest you use <a href=\"https://github.com/\" rel=\"nofollow noreferrer\">GitHub</a> if you don't already use it, and than in the <a href=\"https://github.com/marketplace\" rel=\"nofollow noreferrer\">Marketplace</a> page you should subscribe to <a href=\"https://codebeat.co/\" rel=\"nofollow noreferrer\">CodeBeat</a>, <a href=\"https://app.codacy.com/\" rel=\"nofollow noreferrer\">Codacy</a> and <a href=\"https://bettercodehub.com/\" rel=\"nofollow noreferrer\">BetterCodeHub</a> apps for <a href=\"https://en.wikipedia.org/wiki/Automated_code_review\" rel=\"nofollow noreferrer\">automated code review</a>. It is free of charge for public repositories. It is very helpful. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T18:52:11.137",
"Id": "458820",
"Score": "1",
"body": "I think your suggestion for the `foreach` loop is misplaced. Since the code uses both the value and the index, a `fori` loop is better suited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T20:07:21.287",
"Id": "458825",
"Score": "0",
"body": "@tinstaafl You are absolutely right. I will change it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T02:49:06.293",
"Id": "458860",
"Score": "0",
"body": "Thanks for you review @Zoran but does a 60 -line code which can play a game itself seem unsuitable . Anyways is there a simpler way I can do this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T07:46:15.010",
"Id": "458870",
"Score": "0",
"body": "@AnmolAgrawal I will try to make the AI backend logic, and I will update my answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T15:00:28.840",
"Id": "234591",
"ParentId": "234576",
"Score": "2"
}
},
{
"body": "<p>Here is some advice for your code.</p>\n\n<h3>General recommendations</h3>\n\n<p>1) For readability, I suggest that you change the way that you create your arrays; since the \"C-style\" array declaration is harder to read and less used in Java, in my opinion.</p>\n\n<p><em>Before</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int y[] = {};\n</code></pre>\n\n<p><em>After</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int[] y = {};\n</code></pre>\n\n<p>2) In my opinion, I suggest that you wrap the logic of the condition / loop with braces, even if there's only one line of code; this provide consistency and prevent probable bugs if you want to add code to the condition and forget to add the braces.</p>\n\n<p><em>Before</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (t[i] == 0)\n c++;\n</code></pre>\n\n<p><em>After</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (t[i] == 0) {\n c++;\n}\n</code></pre>\n\n<h3><code>getWinRate</code> method</h3>\n\n<p>1) Since the <code>comb</code> is always the same, I sugest that you extract it in a constant.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class AI {\n //[...]\n private static final int[][] COMB = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, {1, 5, 9}, {3, 5, 7}};\n //[...]\n}\n</code></pre>\n\n<p>2) Instead of using a series of <code>if</code> on a value that can have only one of the values, I suggest that you use the <code>if-else</code> or a <code>switch</code> statement and extract the evaluation of <code>t[d]</code> in a variable.</p>\n\n<p><em>Before</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (t[d] == 2)\n AIwin++;\nif (t[d] == 1)\n oppWin++;\nif (t[d] == 0)\n empty++;\n</code></pre>\n\n<p><em>if-else</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int currentValue = t[d];\nif (currentValue == 2)\n AIwin++;\nelse if (currentValue == 1)\n oppWin++;\nelse //Zero\n empty++;\n</code></pre>\n\n<p><strong>or</strong></p>\n\n<p><em>switch</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>switch (t[d]) {\n case 2:\n AIwin++;\n break;\n case 1:\n oppWin++;\n break;\n default: //Zero\n empty++;\n break;\n}\n</code></pre>\n\n<h3><code>play</code> method</h3>\n\n<p>1) In my opinion, instead of cloning an array, you can use <code>java.util.Arrays#copyOf(int[], int)</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> int[] t = Arrays.copyOf(t1, t1.length);\n</code></pre>\n\n<p>2) The <code>j</code> variable is unused.</p>\n\n<p>3) I suggest that you use better names for your variable, it makes the code harder to read.</p>\n\n<p>4) In my opinion, you can extract some of the logic into sub-methods.</p>\n\n<p>a) Create a method to calculate the number of available moves.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private int calculateNumberOfEmptySpace(int[] game) {\n int nb = 0;\n\n for (int i = 0; i < 9; i++) {\n if (game[i] == 0) {\n nb++;\n }\n }\n\n return nb;\n }\n //[...]\nvoid play(int[] t1) {\n int[] copyOfTheGame = Arrays.copyOf(t1, t1.length);\n int numberOfPossibleMoves = calculateNumberOfEmptySpace(t1); \n}\n</code></pre>\n\n<p>5) The index in the last loop is not used, you can use a <code>for-each</code></p>\n\n<p><em>Before</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (i = 0; i < moves.length; i++) {\n boardcopy = t.clone();\n boardcopy[moves[i]] = 2;\n rate = getWinRate(boardcopy);\n if (rate > maxRate) {\n maxRate = rate;\n bestMove = moves[i];\n }\n}\n</code></pre>\n\n<p><em>After</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (int move : moves) {\n boardcopy = t.clone();\n boardcopy[move] = 2;\n rate = getWinRate(boardcopy);\n if (rate > maxRate) {\n maxRate = rate;\n bestMove = move;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T14:00:31.067",
"Id": "234632",
"ParentId": "234576",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T07:06:08.767",
"Id": "234576",
"Score": "1",
"Tags": [
"java",
"beginner",
"tic-tac-toe",
"ai"
],
"Title": "A simple AI for Tic-Tac-Toe game"
}
|
234576
|
<p>Shown below is a function I wrote for pawn move generation, I find it difficult to understand what the code does in a glance due to the cumbersome if statements, so any changes I make are done unnecessarily slowly. Is there a way to avoid these complex if statements so that the code is more maintainable?</p>
<pre><code> if(standardPawn.indexOf(this.board[position.y][position.x]) != -1){
if(position.x + 1 < 8){
if(board[position.y][position.x + 1].canEnpas === true && standardPawn.indexOf(board[position.y][position.x + 1]) == -1){
moves.push({x: position.x + 1, y: position.y - 1});
}
}
if(position.y == 6){
if(board[position.y - 1][position.x] == "vacant"){
moves.push({x: position.x, y: position.y - 1});
}
if(board[position.y - 2][position.x] == "vacant" && board[position.y - 1][position.x] == "vacant"){
moves.push({x: position.x, y: position.y - 2});
}
} else if(position.y - 1 >= 0){
if(board[position.y - 1][position.x] == "vacant"){
moves.push({x: position.x, y: position.y - 1});
}
}
if(position.x + 1 < 8 && position.y - 1 >= 0){
if(getPieceType({x: position.x + 1, y: position.y - 1}, this.board) != pieceType && board[position.y - 1][position.x + 1] != "vacant"){
moves.push({x: position.x + 1, y: position.y - 1});
}
}
if(position.x - 1 >= 0 && position.y - 1 >= 0){
if(getPieceType({x: position.x - 1, y: position.y - 1}, this.board) != pieceType && board[position.y - 1][position.x - 1] != "vacant"){
moves.push({x: position.x - 1, y: position.y - 1});
}
}
} else {
if(position.x + 1 < 8){
if(board[position.y][position.x + 1].canEnpas === true && standardPawn.indexOf(board[position.y][position.x + 1]) != -1){
moves.push({x: position.x + 1, y: position.y + 1});
}
}
if(position.y == 1){
if(board[position.y + 1][position.x] == "vacant"){
moves.push({x: position.x, y: position.y + 1});
}
if(board[position.y + 2][position.x] == "vacant" && board[position.y + 1][position.x] == "vacant"){
moves.push({x: position.x, y: position.y + 2});
}
} else if(position.y + 1 < 8){
if(board[position.y + 1][position.x] == "vacant"){
moves.push({x: position.x, y: position.y + 1});
}
}
if(position.x + 1 < 8 && position.y + 1 < 8){
if(getPieceType({x: position.x + 1, y: position.y + 1}, this.board) != pieceType && board[position.y + 1][position.x + 1] != "vacant"){
moves.push({x: position.x + 1, y: position.y + 1});
}
}
if(position.x - 1 >= 0 && position.y + 1 < 8){
if(getPieceType({x: position.x - 1, y: position.y + 1}, this.board) != pieceType && board[position.y + 1][position.x - 1] != "vacant"){
moves.push({x: position.x - 1, y: position.y + 1});
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You can enhance the readability by extracting the conditons of your ifs to functions without chanceing the performance. Plus you can remove your duplicate code like positon.x +1 < 8</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T16:50:52.747",
"Id": "234596",
"ParentId": "234577",
"Score": "1"
}
},
{
"body": "<p>You can predefine some of the conditions. E.g.</p>\n\n<pre><code>let blocked = (board[position.y - 1][position.x] !== \"vacant\")\nlet unmoved = (y === 6)\n…\n</code></pre>\n\n<p>You can also define some short functions. E.g. <code>isEnemy(x,y)</code> would return true if there is an enemy piece at that position.</p>\n\n<p>Then using those variables in the tests will make them look tidier, and be easier to read and understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T19:35:53.187",
"Id": "234605",
"ParentId": "234577",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234605",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T07:07:18.883",
"Id": "234577",
"Score": "1",
"Tags": [
"javascript",
"chess"
],
"Title": "Cleaning up complex if statements for Chess game"
}
|
234577
|
<p>I have written a quick sort routine to inplace sort an array in descending order:</p>
<pre><code>module sort
contains
recursive subroutine qsort_self(array)
real(kind=8) :: array(:), temp
integer :: length, pivot, i, j
i = 0
j = 0
length = 0
pivot = 1
temp = 0
length = size(array)
if (length > 1) then
i = 2
j = size(array)
do while (i <= j)
do while (array(j) < array(pivot))
j = j - 1
enddo
do while ((array(i) > array(pivot)) .and. (i<=length))
i = i + 1
enddo
if (i > j) exit
temp = array(j)
array(j) = array(i)
array(i) = temp
i = i + 1
j = j - 1
enddo
temp = array(pivot)
array(pivot) = array(j)
array(j) = temp
pivot = j
call qsort_self(array(1:pivot-1))
call qsort_self(array(pivot + 1 : length))
endif
end subroutine qsort_self
end module sort
program p
use sort
implicit none
integer :: size_,i
real(kind=8), allocatable :: b6(:)
size_ = 100
allocate(b6(size_))
do i = 1, size_
b6(i) = real(rand(), 8)
enddo
print *, "unsorted: ", b6
call qsort_self(b6)
print *,"sorted a= ", b6
end program p
</code></pre>
<p>It works fine for now, but without <code>.and. (i<=length)</code> part of code, i run into errors where if array is in ascending order, <code>i</code> goes out of bound. I checked several online implementations, such as this: </p>
<p><a href="https://stackoverflow.com/questions/11196571/quick-sort-sorts-descending-not-ascending">https://stackoverflow.com/questions/11196571/quick-sort-sorts-descending-not-ascending</a></p>
<p>and I believe they suffer from same flaw. Is here any better way of doing it?
I Always want to take first element as pivot because of the array structure.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T15:03:00.040",
"Id": "458793",
"Score": "1",
"body": "Welcome to CodeReview@SE. Could you mention the Fortan version/dialect? (from Fortran 90, inline comments should be possible) (punched cards, anyone?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T15:11:41.857",
"Id": "458794",
"Score": "0",
"body": "@greybeard at least it doesn't have line numbers and gotos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T03:51:43.863",
"Id": "458866",
"Score": "0",
"body": "F90. Comments on <40 lines, one of the most famous algorithms?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T09:34:46.807",
"Id": "458875",
"Score": "0",
"body": "Documenting comments with ***every single piece of code***."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T11:37:38.697",
"Id": "458884",
"Score": "0",
"body": "I really wont argue further unless their is some actual advice included. But, I am sorry, this is somewhat stupid. Comments are not some holy relic that makes any code more readable. Uselessly commenting a 40 line code with three variables and 3 while loops can break the flow of reader too. So i disagree on commenting _**every single piece of code**_. Its useless and leads to situation like: https://i.redd.it/iuy9fxt300811.png."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T09:20:30.477",
"Id": "459068",
"Score": "0",
"body": "*piece of code* as in externally visible, not as in statement/line/whatever. You want to use `qsort_self(array)`? Great. How do you know whether it sorts *values* or *records containing keys*? Does it keep the amount of stack needed in check? It might implement ACM algorithm 64: does it use Hoare partition (63), Lomuto, or something else?"
}
] |
[
{
"body": "<h2>Errors in the code</h2>\n\n<p>This piece</p>\n\n<pre><code>array(i) > array(pivot) .and. i <= length\n</code></pre>\n\n<p>is not valid code. If <code>i > length</code> you will get an out of bounds access with <code>array(i)</code>.\nIf you rewrite it as</p>\n\n<pre><code>i <= length .and. array(i) > array(pivot)\n</code></pre>\n\n<p>it is still wrong, because there is no short circuiting in Fortran. Or to be more precise: Fortran operators are neither short-circuit nor eager. The language specification allows the compiler to select the method for optimization. In your case the compiler reorders and short circuits apparently.\nThe only way to write it reliably correctly is unfortunately:</p>\n\n<pre><code>if (i <= length) then\n if (array(i) > array(pivot)) then\n ...\n</code></pre>\n\n<hr>\n\n<p>A declaration with a number literal like <code>real(kind=8)</code> is not portable. You might think, that it is 8 bytes and/or double precision, but the actual integer value for different kinds is implementation dependent. It just happens to be the case, that <code>gfortran</code> and <code>ifort</code> use the kind value <code>8</code> to denote double precision, but on another compiler this might be wrong.\nYou should always use</p>\n\n<pre><code>integer, parameter :: dp = selected_real_kind(15, 307)\n</code></pre>\n\n<p>if you want to have a certain range and precision or</p>\n\n<pre><code>use, intrinsic :: iso_fortran_env, only: real64\n</code></pre>\n\n<p>if you want to have a float with 8 bytes.\n(Of course these both will be the same on most architectures today.)</p>\n\n<hr>\n\n<p>There is no <code>implicit none</code> in the module. Strictly speaking this is not an error and you declared all variables correctly, but code without <code>implicit none</code> should be considered faulty.</p>\n\n<h2>Major Code improvements</h2>\n\n<p>You should always add one of <code>intent(in), intent(out), intent(inout)</code> to the dummy arguments of your procedures.</p>\n\n<hr>\n\n<p><s>\nFortran arrays can be declared with arbitrary numerical indices. You implicitly assumed in your code, that they start at 1 (which is the default).\nIf you want your routine to work with differently indexed arrays, it is necessary to query the upper and lower bounds.</p>\n\n<pre><code>do i = lbound(array, dim=1), ubound(array, dim=1)\n</code></pre>\n\n<p>This makes it also explicit when you really mean the size, and when the bounds.</p>\n\n<p></s></p>\n\n<p>What I initially wrote is wrong. If you use assumed-shape arrays, the dummy argument becomes again 1-indexed by default.\nHad to learn that myself the hard way. Sorry. :-/</p>\n\n<hr>\n\n<p>I agree you with you that these <40 lines don't require comments for the most parts, but you can write it more readable without comments, by defining a <code>swap</code> subroutine. This would also reduce the clutter of local variables.</p>\n\n<p>If you define a <code>get_pivot</code> function, it will be easy to change to different pivoting strategies.</p>\n\n<hr>\n\n<p>You have superfluous assignments to <code>length</code> in your code.\nIMHO you don't need this variable anyway, because you can insert <code>size(array)</code> at every appearance. Any decent compiler will do common-subexpression-elimination on these calls.</p>\n\n<hr>\n\n<p>Where possible I would use <code>pure</code> and <code>elemental</code> on your procedures.\nThey are amazing. ;-)</p>\n\n<h2>Architecture</h2>\n\n<p>I would always make all names in a module <code>private</code> and export explicitly with <code>public</code>. On the other hand I would only import used names.</p>\n\n<hr>\n\n<p>In the long run, you want to have a second argument where one can pass a <code>pure logical</code> function that compares two elements. Doing so, the user can sort according to his/her constraints.</p>\n\n<h2>Formatting</h2>\n\n<p>Thank you for writing <code>Fortran</code> and not <code>FORTRAN</code> code.\nIf you don't scream at people it is much easier to read your code. ;-)</p>\n\n<hr>\n\n<p>Of course this is opinion based so, whatever I say, stick to the style of your environment. <strong>But</strong> for example the whitespace around your binary operators was not consistent. An indentation of two spaces is IMHO too short.</p>\n\n<hr>\n\n<p>I assume that you are from science and you and your peers use python. In this case it is quite easy to stick to the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">python formatting guidelines</a> in Fortran.</p>\n\n<h2>Minor Code improvements</h2>\n\n<p>I agree that the code mostly does not require comments,\nbut at least public functions of a module should get a docstring on how to use them.</p>\n\n<hr>\n\n<p><code>size</code> in the program can be made constant.</p>\n\n<hr>\n\n<p>The upper and lower bound in array slices can be ommited <code>A(lbound(A, 1) : 5) == A(: 5)</code></p>\n\n<hr>\n\n<p>I would not use <code>p</code> as program name. If you do so, you can't use it as variable name anymore.</p>\n\n<hr>\n\n<p>There is <code>random_number</code> to generate an array of real numbers.</p>\n\n<h2>Possible improved version</h2>\n\n<pre><code>module sort\n implicit none\n private\n public :: dp, qsort\n integer, parameter :: dp = selected_real_kind(15, 307)\n\n abstract interface\n logical pure function compare_t(a, b)\n import :: dp\n real(dp), intent(in) :: a, b\n end function\n end interface\n\ncontains\n\n !> @brief\n !> Sort array inplace according to comparison function comp.\n !>\n !> @details\n !> The comparison function has to be a pure, logical function\n !> that compares two elements of array in a strict partial order.\n !> That means equality has to evaluate to false.\n pure recursive subroutine qsort(array, comp)\n real(kind=dp), intent(inout) :: array(:)\n procedure(compare_t) :: comp\n\n integer :: pivot, i, j\n\n i = 0\n j = 0\n pivot = get_pivot(array)\n if (size(array) > 1) then\n i = lbound(array, dim=1)\n j = ubound(array, dim=1)\n do while (i <= j)\n do while (comp(array(i), array(pivot)))\n i = i + 1\n end do\n do while (comp(array(pivot), array(j)))\n j = j - 1\n end do\n if (i >= j) exit\n call swap(array(i), array(j))\n i = i + 1\n j = j - 1\n end do\n call swap(array(pivot), array(j))\n call qsort(array(: j - 1), comp)\n call qsort(array(j + 1 : ), comp)\n end if\n end subroutine qsort\n\n pure subroutine swap(a, b)\n real(dp), intent(inout) :: a, b\n real(dp) :: temp\n temp = a\n a = b\n b = temp\n end subroutine\n\n pure function get_pivot(array) result(res)\n real(dp), intent(in) :: array(:)\n integer :: res\n res = lbound(array, dim=1)\n end function\n end module sort\n\n\nprogram test_qsort_procedures\n use sort, only: dp, qsort\n implicit none\n integer, parameter :: size_ = 100\n real(kind=dp), allocatable :: b6(:)\n\n allocate(b6(size_))\n call random_number(b6)\n\n print *, \"unsorted: \", b6\n call qsort(b6, increasing)\n print *,\"increasing a= \", b6\n call qsort(b6, decreasing)\n print *,\"decreasing a= \", b6\n\n contains\n\n logical pure function increasing(a, b)\n real(dp), intent(in) :: a, b\n increasing = a < b\n end function\n\n logical pure function decreasing(a, b)\n real(dp), intent(in) :: a, b\n decreasing = a > b\n end function\nend program test_qsort_procedures\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T11:00:18.060",
"Id": "461383",
"Score": "0",
"body": "Thank you for such comprehensive answer. I was not aware of lbounds and definitely let the short circuiting error slip. Regarding 2-space indent, program name and docstring, this function is supposed to be a part of bigger submodule, hence the short program name; and already existing indent was 2 :'(. However thank you again for such comprehensive review, I would definitely include the changes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:18:50.080",
"Id": "461391",
"Score": "1",
"body": "Welcome. ;-) I just wrote down the stuff, that I would have liked to hear in the beginning. Especially the short circuiting can become really nasty, as you can imagine."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:27:20.660",
"Id": "235628",
"ParentId": "234582",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "235628",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T09:17:17.073",
"Id": "234582",
"Score": "5",
"Tags": [
"sorting",
"quick-sort",
"fortran"
],
"Title": "Reverse quick sort in Fortran"
}
|
234582
|
<p>I have developed this script to read <code>employee_language</code> table records of a PostgreSQL database using Python 2 (due to some OS limitation). I want to find duplicate language records for each employee, check if there are any duplicate language records for each employee, get the most completed language records among duplicated language records and finally return the ids of language records which are not duplicated with ids of most completed language records of duplicated ones (one records among many duplicates for every language record). This method works well for me but when I run this script for a great number of employee records (500K to 1000K) and it take a long time. Therefore, I'm wondering how I can make this method faster and restructure it better.</p>
<pre><code>def read_employees_with_language_record(self):
self.apps_cursor.execute("""
SELECT id FROM hr_employee limit 1000
""")
employee_ids = self.apps_cursor.fetchall()
counter = 0
for employee_id in employee_ids:
# Call method to get duplicate language records for employee
language_records_not_be_deleted = self.get_employee_language_data(
employee_id['id'])
counter += 1
# Call method to delete duplicate language records for employee
self.delete_employee_duplicate_language_record(
employee_id['id'], language_records_not_be_deleted)
print 'Employee count ##############', counter
def get_employee_language_data(self, employee_id):
self.apps_cursor.execute("SELECT id, language_id, hr_employee_id, lang_write, lang_speak, lang_read FROM employee_language WHERE hr_employee_id=%s" % employee_id)
employee_languages = self.apps_cursor.fetchall()
language_id_list = Counter(language.get('language_id')
for language in employee_languages)
repeated_language_records = []
non_repeated_language_records = []
duplicate_language_ids_list = set()
repeated_language_records_not_to_be_deleted = []
for language in employee_languages:
if language_id_list[language['language_id']] > 1:
duplicate_language_ids_list.add(language['language_id'])
repeated_language_records.append(language)
else:
non_repeated_language_records.append(language)
for unique_record in duplicate_language_ids_list:
temp_list = []
flag_3 = False
flag_2 = False
flag_1 = False
for repeated in repeated_language_records:
if repeated['language_id'] == unique_record:
if None not in (repeated['lang_speak'], repeated['lang_read'], repeated['lang_write']):
temp_list = repeated
flag_3 = True
elif (repeated['lang_speak'], repeated['lang_read'], repeated['lang_write']).count(None) == 1 and not flag_3:
temp_list = repeated
flag_2 = True
elif (repeated['lang_speak'], repeated['lang_read'], repeated['lang_write']).count(None) == 2 and not flag_3 and not flag_2:
temp_list = repeated
flag_1 = True
elif not flag_3 and not flag_2 and not flag_1:
temp_list = repeated
repeated_language_records_not_to_be_deleted.append(temp_list)
language_record_ids_not_to_be_deleted = []
for record in non_repeated_language_records + repeated_language_records_not_to_be_deleted:
language_record_ids_not_to_be_deleted.append(int(record['id']))
return language_record_ids_not_to_be_deleted
deleted_language_record_ids_list = []
def delete_employee_duplicate_language_record(self, hr_employee_id, record_ids):
if record_ids:
self.apps_cursor.execute("""
SELECT id FROM employee_language WHERE hr_employee_id=%s AND id NOT IN %s
""", (hr_employee_id, tuple(record_ids),))
deleted_language_records = self.apps_cursor.fetchall()
for language_record in deleted_language_records:
self.deleted_language_record_ids_list.append(
language_record['id'])
self.apps_cursor.execute("""
DELETE FROM employee_language WHERE hr_employee_id=%s AND id NOT IN %s
""", (hr_employee_id, tuple(record_ids),))
def print_total_deleted_language_record(self):
print 'Total deleted language records are: ', len(
self.deleted_language_record_ids_list)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:43:05.577",
"Id": "458790",
"Score": "0",
"body": "You could change your SQL query to already give you the count of each language"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T04:44:21.953",
"Id": "458867",
"Score": "0",
"body": "You're right with count, bu I don't just need the count. I need to get the duplicate language records then among them, find and get the most completed one and delete others. So, I don't think count can help me in this case."
}
] |
[
{
"body": "<p>Looking at your code, I can see two potential slowdowns:</p>\n\n<ol>\n<li>When you do a <code>.count</code>, Python is implicitly performing a for-loop over each element in the array. This scales horribly with bigger tables and is definitely causing a slowdown. The comment about returning a count would actually help a lot. Below, I've implemented a similar solution.</li>\n<li>Converting a list to a set is usually fine, but in this case, when you have almost a million elements, it is not efficient. It is especially inefficient when there was no use for the list in the first place. From the code you gave, it seems like the best solution is to directly instantiate a set and add to that incrementally. </li>\n</ol>\n\n<p>Implementing those points and then cleaning up the logic should result in something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\n\ndef get_employee_language_data(self, employee_id):\n self.apps_cursor.execute(\"SELECT id, language_id, hr_employee_id, lang_write, lang_speak, lang_read FROM employee_language WHERE hr_employee_id=%s\" % employee_id)\n employee_languages = self.apps_cursor.fetchall()\n\n language_id_list = Counter(language.get('language_id') for language in employee_languages)\n\n repeated_language_records = []\n non_repeated_language_records = []\n duplicate_language_ids_list = set()\n repeated_language_records_not_to_be_deleted = []\n\n for language in employee_languages:\n if language_id_list[language['language_id']] > 1:\n duplicate_language_ids_list.add(language['language_id'])\n repeated_language_records.append(language)\n else:\n non_repeated_language_records.append(language)\n\n\n for unique_record in duplicate_language_ids_list:\n temp_list = []\n flag_3 = False\n flag_2 = False\n flag_1 = False\n for repeated in repeated_language_records:\n\n if repeated['language_id'] == unique_record:\n\n if None not in (repeated['lang_speak'], repeated['lang_read'], repeated['lang_write']):\n temp_list = repeated\n flag_3 = True\n\n elif (repeated['lang_speak'], repeated['lang_read'], repeated['lang_write']).count(None) == 1 and not flag_3:\n temp_list = repeated\n flag_2 = True\n\n elif (repeated['lang_speak'], repeated['lang_read'], repeated['lang_write']).count(None) == 1 and not flag_3 and not flag_2:\n temp_list = repeated\n flag_1 = True\n\n elif not flag_3 and not flag_2 and not flag_1:\n temp_list = repeated\n\n repeated_language_records_not_to_be_deleted.append(temp_list)\n\n language_record_ids_not_to_be_deleted = []\n\n for record in non_repeated_language_records + repeated_language_records_not_to_be_deleted:\n language_record_ids_not_to_be_deleted.append(int(record['id']))\n\n return language_record_ids_not_to_be_deleted\n</code></pre>\n\n<p>I'm sure there are further improvements that could be made, but I cannot follow the specific logic of the code you gave. More context and examples would be necessary to simplify it further. I am certain this is faster, but as fast as it could be. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T04:29:29.783",
"Id": "459956",
"Score": "0",
"body": "I applied above changes in my code and test it with measuring the script run time with original script. With testing for several scenarios, these changes made the script even slower then before. I'm still wonder how can make this script faster and I tired some methods but nothing changed a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T16:13:42.193",
"Id": "459997",
"Score": "0",
"body": "@IbrahimRahimi Can you post your updated code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T04:38:52.510",
"Id": "460067",
"Score": "0",
"body": "It's too long and can't be fit in a comment. Should I post it as an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T15:49:21.953",
"Id": "460135",
"Score": "0",
"body": "@IbrahimRahimi, no please post it as an edit to your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T07:54:01.163",
"Id": "460890",
"Score": "0",
"body": "I have posted it as an edit for the answer. Please review it and let me know I can improve it any way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T14:35:44.597",
"Id": "460908",
"Score": "0",
"body": "@IbrahimRahimi I mean, make it as an edit to **your original question**. That is what I should've said before"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T09:04:17.287",
"Id": "460975",
"Score": "0",
"body": "code updated in question part."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T23:02:35.130",
"Id": "234686",
"ParentId": "234586",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T12:07:24.723",
"Id": "234586",
"Score": "1",
"Tags": [
"python",
"performance",
"python-2.x",
"postgresql"
],
"Title": "Reading employee data from a PostgreSQL database"
}
|
234586
|
<p>So I am solving this task:
We have an permutation of the numbers 1..n.
I need to answer m queries:
<strong>-How many numbers between X-th and Y-th position are in the interval [L,K] (<=k and >= L)?</strong></p>
<p>So my solution is simple: I create a <strong>segment tree</strong> and in <strong>every node i keep an map</strong> -> which numbers are in this interval and the position (when they are sorted).</p>
<p><strong>For example ( 98, 14 , 22, 45, 33) the map for this interval is (14,1)(22,2),(33,3),(45,5)..</strong>
Then when i recieve a query (X,Y,l,k) I find the interval in the tree,then I use lower bound (to the map in the node (so i get <strong>Log(n)</strong> time complexity)) to find the closest element to l and the closest element to k and <strong>substract</strong> their positions. The solution works, but i exceed the time for some test. Any tips how can i make it faster ? Maybe faster way to create the maps in the nodes ? Or faster search in the tree? </p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <map>
using namespace std;
#define IntervalsIntersect(left,right,X, Y) (left <= Y && right >= X)
struct node
{
map<int, int> m;
};
int getNextIndRight(int ind, int n) // By going right how does the interval changes
{
int diff = n - ind;
if (diff % 2 == 0)
return n - diff / 2;
return n - diff / 2 - 1;
}
int getNextIndLeft(int ind, int n)
{
int diff = n - ind;
if (diff % 2 == 0)
return ind + 1 + diff / 2;
return (ind + diff / 2) + 1;
}
void build(int* a, node* t, int v, int tl, int tr, int left, int right)
{
if (tl == tr)
{
t[v].m.insert(pair<int, int>(a[tl], 1));
}
else
{
int tm = (tl + tr) / 2;
build(a, t, v * 2, tl, tm, left, getNextIndRight(left, right));
build(a, t, v * 2 + 1, tm + 1, tr, getNextIndLeft(left, right), right);
t[v].m = t[v * 2].m;
t[v].m.insert(t[v * 2 + 1].m.begin(), t[v * 2 + 1].m.end());
int i = 1;
for (auto &p : t[v].m)
{
p.second = i++;
}
}
}
int countInInterval(map<int, int>& m, int k, int l)
{
//for (auto &p : m)
// cout<<p.first<<" "<<p.second<<endl;
auto it = m.lower_bound(k);
auto it2 = m.lower_bound(l);
bool firstOK = it != m.end();
bool secondOK = it2 != m.end();
if (!firstOK && !secondOK)
return 0;
else if (firstOK && !secondOK)
return m.size() - it->second + 1;
if (it == it2)
{
if (k <= it->first&&it->first <= l)
return 1;
return 0;
}
int res= (it2->second - it->second);
if (k <= it2->first && it2->first <= l)
res++;
return res;
}
bool hasIntersection(int left, int right, int X, int Y)
{
return left <= Y && right >= X;
}
int f(node* t, int* a, int left, int right, int n, int v, int X, int Y, int k, int l)
{
if (left >= X && right <= Y)
return countInInterval(t[v].m, k, l);
int leftFirst = left;
int rightFirst = getNextIndRight(left, right);
int res = 0;
if (IntervalsIntersect(leftFirst, rightFirst, X, Y))
res += f(t, a, left, getNextIndRight(left, right), n, v * 2, X, Y, k, l);
int leftsecond = getNextIndLeft(left, right);
int rightsecond = right;
if (IntervalsIntersect(leftsecond, rightsecond, X, Y))
res += f(t, a, getNextIndLeft(left, right), right, n, v * 2 + 1, X, Y, k, l);;
return res;
}
int main()
{
int n, m;
cin >> n >> m;
int* a = new int[n];
for (int i = 0; i < n; i++)
cin >> a[i];
node* t = new node[4 * n + 1];
build(a, t, 1, 0, n - 1, 1, n);
for (int i = 0; i < m; i++)
{
int x, y, k, l;
cin >> x >> y >> k >> l;
cout << f(t, a, 1, n, n, 1, x, y, k, l) << endl;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:07:41.160",
"Id": "458785",
"Score": "1",
"body": "Do you have some test cases? I don't understand why you can't use binary search here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:11:03.270",
"Id": "458787",
"Score": "0",
"body": "map is implemented like a BST. I use segment tree, because i need an interval of the permutation, not the whole permutation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:12:37.927",
"Id": "458788",
"Score": "2",
"body": "I would suggest expanding all the variables with single letters to meaningful names. This is a total mess trying examine your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:58:33.853",
"Id": "458791",
"Score": "1",
"body": "Welcome to code review, if this is a programming challenge, can you please add a linke to the website."
}
] |
[
{
"body": "<p>I believe the problem lies in the initialization time. If I am not wrong it is like <code>O(n^2 log n)</code> which might be a problem for tests with large <code>n</code> and small sample size.</p>\n\n<p>To fix it you'll have to redo the whole algo if I am not mistaken.</p>\n\n<p>There is a method that doesn't have the same long initialization problem while retaining the same <code>O(log n)</code> (at least on average, <code>O(log^2 n)</code> at worst) time per iteration - simply build a two dimensional segment tree. Since we work with a permutation it will be rather sparse.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T15:20:07.480",
"Id": "458799",
"Score": "0",
"body": "Why would I use 2D segment tree for an 1D array? My teacher told me that it could be done with a normal segment tree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T17:16:51.487",
"Id": "458808",
"Score": "0",
"body": "@SimonJachson because graph of the 1-dimensional array is 2 dimensional and you basically want to know how many points are in one of the rectangles. Or did I misunderstand something? 1 dimensional sieve would be good if you wanted to know what is within a segment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T09:29:50.400",
"Id": "458874",
"Score": "0",
"body": "You cannot say O(something) on average and O(other) in worst case. O(some) is the asymptotic upper limit and thus the worst case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T12:42:55.523",
"Id": "458886",
"Score": "0",
"body": "@slepic ...you are simply wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T07:40:46.120",
"Id": "458943",
"Score": "0",
"body": "Yeah yeah Im kinda sick of Ppl like you WHO keep telling me I am wrong without any reasoning why would that be. I am Always ready to admit i was wrong but if you dont have any arguments you wont convince me. There Is no value to your comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T12:24:43.490",
"Id": "458969",
"Score": "0",
"body": "@slepic if a person looks on black wall and says its white. What can be explained to them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T08:11:37.413",
"Id": "459061",
"Score": "0",
"body": "There Is no black nor white. Shine a bright light on \"black\" surface And it Will be \"white\". Black or White Is just a degree of presence/absence of light (of all visible wavelengths). We decide which Is which by some intuitive threshold (And we say it Is Grey when we Are not sure). Arogant people who think things Are either Black or White WHO keep adding useless comments maybe should not explain anything to anyone."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T14:54:43.227",
"Id": "234590",
"ParentId": "234588",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T13:26:37.330",
"Id": "234588",
"Score": "2",
"Tags": [
"c++",
"c",
"time-limit-exceeded",
"complexity"
],
"Title": "Permutation 1...N. Answer queries \"How many numbers between [X,Y] position are in the interval [L,K]\"?"
}
|
234588
|
<p>I want to learn Wasm and Rust. This project can execute Wasm from GitHub Pages. The first attempts failed because of some policy error with the Wasm MIME type. When I tried <a href="https://github.com/yewstack/yew" rel="nofollow noreferrer">Yew Framework</a> then <a href="https://montao.github.io/spooks-web/" rel="nofollow noreferrer">it worked</a> to run Wasm for my first attempt (it just writes random rows from a text file).</p>
<p>For some reason I got a MIME type error when trying the <a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_wasm" rel="nofollow noreferrer">official example</a> from Mozilla and I want to be independent of node and npm whereas the official example requires npm (and would generate the MIME type error when deployed to GitHub Pages (but running as expected locally with the npm webpack)). </p>
<p>Here is my code done with yew framework. It is also in the <a href="https://github.com/montao/spooks-wasm-src" rel="nofollow noreferrer">repository</a>.</p>
<p><strong>Cargo.toml</strong></p>
<pre><code>[package]
name = "spooks-wasm"
version = "0.1.1"
authors = ["Niklas <n*****@*****mail.com>"]
edition = "2018"
[dependencies]
stdweb = "0.4.20"
getopts = "0.2"
rand = {version = "0.7", features = ['stdweb']}
easy_reader = "0.5.0"
yew = { path = "../.." }
</code></pre>
<p><strong>main.rs</strong></p>
<pre><code>fn main() {
yew::start_app::<counter::Model>();
}
</code></pre>
<p><strong>lib.rs</strong></p>
<pre><code>#![recursion_limit = "128"]
extern crate easy_reader;
extern crate getopts;
extern crate rand;
use stdweb::web::Date;
use yew::services::ConsoleService;
use yew::{html, Component, ComponentLink, Html, ShouldRender};
use std::env;
use std::io::{Cursor, Error, Seek, SeekFrom, Write};
use crate::rand::Rng;
use easy_reader::EasyReader;
use getopts::Options;
pub struct Model {
link: ComponentLink<Self>,
console: ConsoleService,
value: i64,
spooks: String,
}
pub enum Msg {
Increment,
Decrement,
Bulk(Vec<Msg>),
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let mut c = Cursor::new(Vec::new());
let str42 = include_str!("spook.lines").as_bytes();
// // Write into the "file" and seek to the beginning
c.write_all(str42).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
let mut reader = EasyReader::new(c).unwrap();
let _res = reader.build_index();
let tmpspooks = reader.random_line().unwrap().unwrap() + &reader.random_line().unwrap().unwrap() + &reader.random_line().unwrap().unwrap() + &reader.random_line().unwrap().unwrap() + &reader.random_line().unwrap().unwrap();
Model {
link,
console: ConsoleService::new(),
value: 0,
spooks: tmpspooks
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
let mut c = Cursor::new(Vec::new());
let str42 = include_str!("spook.lines").as_bytes();
// // Write into the "file" and seek to the beginning
c.write_all(str42).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
let mut reader = EasyReader::new(c).unwrap();
let _res = reader.build_index();
self.spooks = reader.random_line().unwrap().unwrap() + &reader.random_line().unwrap().unwrap() + &reader.random_line().unwrap().unwrap() + &reader.random_line().unwrap().unwrap() + &reader.random_line().unwrap().unwrap();
match msg {
Msg::Increment => {
self.value = self.value + 1;
self.console.log("plus one");
}
Msg::Decrement => {
self.value = self.value - 1;
self.console.log("minus one");
}
Msg::Bulk(list) => {
for msg in list {
self.update(msg);
self.console.log("Bulk action");
}
}
}
true
}
fn view(&self) -> Html {
html! {
<div>
<p>{ &self.spooks }</p>
<nav class="menu">
<button onclick=self.link.callback(|_| Msg::Increment)>
{ "Spook" }
</button>
</nav>
</div>
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T16:39:35.030",
"Id": "234595",
"Score": "1",
"Tags": [
"rust",
"webassembly"
],
"Title": "Printing random lines from a file and compiling it to WebAssembly for web view"
}
|
234595
|
<p>I'm trying to find a sensible way to structure a REST API written in Flask. I'm new to writing such things and I've not seen this structure used anywhere else, so before I continue I wanted to ask whether this is a decent way of structuring my API code, or if I'm missing something.</p>
<p>I have decided on the following structure, with seperate modules containing flask.Blueprint objects.</p>
<pre><code>src
├──api
│ ├──v1
│ │ ├──__init__.py
│ │ └──api_blueprint.py
│ │
│ ├──v2
│ │ ├──__init__.py
│ │ └──api_blueprint.py
│ │
│ ├──__init__.py
│ │
. └──runApi.py
</code></pre>
<p>When I need to apply a change to the API, I'll create a new version folder, then import the resource classes from the previous version and override their methods</p>
<p>e.g. src/api/v1/api_blueprint.py contains</p>
<pre class="lang-py prettyprint-override"><code>import flask
import flask_restful
api_bp = flask.Blueprint('api_v1', __name__)
api = flask_restful.Api(api_bp)
class Vla(flask_restful.Resource):
def get(self):
return {'gleep':'glorp'}
api.add_resource(Vla, '/vla')
</code></pre>
<p>and src/api/v2/api_blueprint.py - the hypothetical second version of the API - contains a Resource inherited from v1 and has whatever methods required overridden</p>
<pre class="lang-py prettyprint-override"><code>import flask
import flask_restful
from v1.api_blueprint import Vla
api_bp = flask.Blueprint('api_v2', __name__)
api = flask_restful.Api(api_bp)
class Vla(Vla):
def get(self):
return {'gleep':'florp?'}
api.add_resource(Vla, '/vla')
</code></pre>
<p>And finally runApi.py</p>
<pre class="lang-py prettyprint-override"><code>import flask
from v1.api_blueprint import api_bp as api_v1
from v2.api_blueprint import api_bp as api_v2
app = flask.Flask(__name__)
app.register_blueprint(api_v1, url_prefix='/api/v1')
app.register_blueprint(api_v2, url_prefix='/api/v2')
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
</code></pre>
<p>So, in short, is there anything wrong with this method of versioning my API?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T20:57:44.033",
"Id": "458828",
"Score": "0",
"body": "I'd avoid doing such things beyond two versions, and certainly not do such things on production, because building with fragmentation at the get-go is going to cause issues in the future. I think what would be better, and simpler to maintain, are [Git Branching and Merging](https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging), because there will be less unnecessary importing and changes to code. Additionally Git has [tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging) which can be useful for marking code changes that are potentially breaking between versions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T21:11:39.483",
"Id": "458830",
"Score": "0",
"body": "Hi @S0AndS0, \nEvery version (or at least several) of the API will need to remain available for use, so I'm not sure that branching is the way to go.\nAlso, when you talk about 'fragmentation', do you mean just having v1, v2, v3, etc. or do you mean my user of inheritance in order to not have duplicate code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T21:37:55.143",
"Id": "458834",
"Score": "0",
"body": "In that case it's good idea to set limits on how far back your versions may go before refactoring code, otherwise it'll become a huge chore to figure out what is being executed. And yes to both as far as fragmentation, while what you're doing is great for prototyping and quick tests, when a code base gets more complex tracing the stack is going to become time consuming (and cognitively taxing) if ya aren't staying on-top of merging features, side-effects, and such... I've a few projects that are _stillborn_ (forever unpublished), because it's to much of a pain to get back into the _flow_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T22:05:59.553",
"Id": "458839",
"Score": "0",
"body": "I'm hoping that there wont be too many versions, but I know from experience that there's no way to predict everything so preparing for versioning is a necessary evil. \nHowever, I do appreciate the point of trying to keep things simple. In the past I've implemented things that I thought would be time savers, but actually ended up causing so much complexity that they made things _much_ harder to debug cost significantly more time. With that in mind for each version I'll probably just duplicate the api code and alter from there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T22:41:09.873",
"Id": "458844",
"Score": "0",
"body": "Heh, I'm tempted to quote one of my ancestors regarding hopes... On the vain of keeping things simple; `git commit` tracks changes, `git log` reviews'em, and `git checkout <ref>` reverts (I think of it like targeted _undo_). All of which allows for keeping things more tidy. That all stated, it's your project and non-refundable time, all I'm trying to suggest is that a few seconds of committing changes may save many minuets to hours of re-reading and debugging; branching/tagging is kinda a supper-set of such practices that helps with _bookmarking_ known good states of a project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T17:47:03.520",
"Id": "458906",
"Score": "0",
"body": "Just to be clear, are you looking for a methodical discussion on if this is a good idea or are you looking at programmatic ways to do the code you gave above?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:30:19.697",
"Id": "458948",
"Score": "0",
"body": "The former. The code above, albeit basic, is already working. \nI just wanted to run this by people who've got more experience than I do in order to avoid complications down the road."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T16:59:55.687",
"Id": "234597",
"Score": "1",
"Tags": [
"python",
"rest",
"flask"
],
"Title": "Anything Wrong with This Method of API Versioning Using Flask?"
}
|
234597
|
<p>The problem is as follows: Given two arrays, write a function to compute their intersection.</p>
<p>The below code is my solution.I'm just curious as to what the space time and complexity of below algorithm would be. </p>
<pre><code>var intersection = function(nums1, nums2) {
const intersectionArr = nums1.filter((value)=> nums2.includes(value));
return [...new Set(intersectionArr)];
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T09:03:38.713",
"Id": "458873",
"Score": "1",
"body": "Please add tag of the language in which this is written (I suppose js?) Despite i think question purely about complexity iss offtopic on this site, the time complexity Is probably O(n^2) And Space Is O(n)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T17:59:56.917",
"Id": "234601",
"Score": "1",
"Tags": [
"array",
"complexity"
],
"Title": "Intersection of Two Arrays - Space Time And Complexity"
}
|
234601
|
<p>Is my Python Script to play Hanoi Tower respectful of OOP spirit?</p>
<p>I have difficulties to create meaningful classes so I started an easy project. Here is one class at the plateau level and then a class to handle towers.</p>
<p>How can it be improved (on the OOP level and on script level)?</p>
<p>I want then a GUI with TKinter, a third class GUI would be suited ?</p>
<p>Thank you</p>
<pre><code>import numpy as np
NB_DISKS = 3
class Plateau:
"""Class for the whole plateau"""
def __init__(self):
self.init_plateau()
def init_plateau(self):
"""List of towers,first tower full"""
self.nb_disks = NB_DISKS
self.towers = [Tower(self.nb_disks), Tower(0), Tower(0)]
def motion(self, tower_from, tower_to):
"""Motion from one tower to another one with checking"""
from_tower = self.towers[tower_from-1]
to_tower = self.towers[tower_to-1]
if from_tower.get_last_disk()>to_tower.get_last_disk(): #Receive 0 if to_tower is empty
disk = from_tower.get_last_disk()
from_tower.delete_disk()
to_tower.add_disk(disk)
self.check_victory()
self.print_towers()
else:
print('Last disk number from origin has to be bigger than reception one')
def check_victory(self):
"""Check if last tower has an ordered list or not"""
last_tower = self.towers[2].get_whole_tower()
if len(last_tower) == self.nb_disks:
diff_last_tower = np.diff(last_tower)
if np.unique(diff_last_tower) == 1:
print('victory:')
self.print_towers()
print('new plateau:')
self.init_plateau()
def print_towers(self):
"""Print the towers"""
for elt in self.towers:
elt.print_tower()
print('\n')
class Tower:
"""Class for a tower"""
def __init__(self,nb_disks):
"""Creation of a tower"""
if nb_disks !=0:
self.tower = list(range(1, nb_disks+1))
else:
self.tower = []
def get_last_disk(self):
"""Return last element of the tower"""
if self.tower == []:
return 0
else:
return self.tower[-1]
def delete_disk(self):
"""Delete last disk of the tower"""
self.tower.pop()
def add_disk(self,disk):
"""Add a disk to the top of the tower"""
self.tower.append(disk)
def get_whole_tower(self):
"""Return the complete tower"""
return(self.tower)
def print_tower(self):
"""Print the element of the tower"""
print(self.tower)
if __name__ == '__main__':
game = Plateau()
game.motion(1,3)
game.motion(1,3) # Try to move a big disk on a small one
game.motion(1,2)
game.motion(3,2)
game.motion(1,3)
game.motion(2,1)
game.motion(2,3)
game.motion(1,3)
</code></pre>
|
[] |
[
{
"body": "<p>From the OOP/typing level, you might want to consider having <code>Disk</code> be a type. If it doesn't need any methods, you could just make it a subtype of <code>int</code>:</p>\n\n<pre><code>from typing import NewType\n\nDisk = NewType('Disk', int)\n</code></pre>\n\n<p>Some notes on your interfaces:</p>\n\n<ol>\n<li><p>Since you always use <code>get_last_disk</code> and <code>delete_disk</code> together, why not combine them? The thing you really want is a <code>pop_top_disk</code> operation that removes and returns the last disk (that's already how you're implementing <code>delete_disk</code> anyway).</p></li>\n<li><p><code>add_disk</code> could implement the \"no larger disk on a smaller one\" rule.</p></li>\n<li><p><code>get_whole_tower</code> seems bad because it's exposing the internal data structure of the tower; this violates your entire OOP abstraction. Note also that in general you should distinguish between \"private\" and \"public\" members of your classes.</p></li>\n<li><p>Rather than making <code>NB_DISKS</code> a global and having <code>Plateau</code> initialize itself from that, <code>Plateau</code>'s initializer should take the number of disks as a parameter.</p></li>\n<li><p>The Pythonic way of making a \"print\" function is to implement the magic function <code>__repr__</code> to return a string.</p></li>\n<li><p>The int values of your disks should be reversed so that bigger numbers represent bigger disks.</p></li>\n<li><p>This is more an English thing than a Python thing, but the verb form of \"motion\" is \"move\" so it would be better to name your method <code>move</code>. :)</p></li>\n</ol>\n\n<p>Here's the final code I came up with after implementing the above suggestions:</p>\n\n<pre><code>from typing import NewType\n\nDisk = NewType('Disk', int)\n\nclass WrongOrder(Exception):\n def __init__(self, top: int, bottom: int) -> None:\n super().__init__(\"Can't put a disk of size %d on a disk of size %d\" % (top, bottom))\n\nclass Plateau:\n \"\"\"Class for the whole plateau\"\"\"\n def __init__(self, nb_disks: int) -> None:\n self._init_plateau(nb_disks)\n\n def _init_plateau(self, nb_disks: int) -> None:\n self._towers = [Tower(nb_disks), Tower(0), Tower(0)]\n\n def move(self, from_tower: int, to_tower: int) -> None: \n \"\"\"Move from one tower to another (towers specified as an int from 1-3). \n Prints an error if the move is invalid.\"\"\"\n # Convert from 1-index to 0-index.\n from_tower -= 1\n to_tower -= 1\n # Make the move, print exception if it fails.\n try:\n disk = self._towers[from_tower].pop_top_disk()\n try:\n self._towers[to_tower].add_disk(disk)\n except WrongOrder:\n # don't drop the disk! Put it back where we got it and reraise.\n self._towers[from_tower].add_disk(disk)\n raise\n except Exception as e:\n print('Move failed: ', str(e))\n else:\n self._check_victory()\n print(self)\n\n\n def _check_victory(self) -> None:\n \"\"\"Check if all disks have moved to the last tower (victory condition).\n If the player has achieved victory, reset the game.\n \"\"\"\n if sum(tower.height for tower in self._towers) == self._towers[2].height:\n print('victory:') \n print(self)\n print('new plateau:')\n self._init_plateau(self._towers[2].height) \n\n def __repr__(self) -> str:\n \"\"\"Print the towers\"\"\"\n return \"\\n\".join([repr(tower) for tower in self._towers]) + \"\\n\"\n\nclass Tower:\n \"\"\"Class for a tower\"\"\"\n def __init__(self, nb_disks: int) -> None:\n \"\"\"Creation of a tower\"\"\"\n self._tower = [Disk(size) for size in range(1, nb_disks + 1)]\n self._tower.reverse() # order the stack from largest to smallest\n\n def pop_top_disk(self) -> Disk:\n \"\"\"Remove and return the top disk on this tower.\"\"\"\n return self._tower.pop()\n\n def add_disk(self, disk: Disk) -> None:\n \"\"\"Add a disk to the top of the tower.\n Raises WrongOrder if the disk being added is too big.\n \"\"\"\n if len(self._tower) and self._tower[-1] < disk:\n raise WrongOrder(disk, self._tower[-1])\n self._tower.append(disk)\n\n @property\n def height(self) -> int:\n \"\"\"Number of disks in the tower.\"\"\"\n return len(self._tower)\n\n def __repr__(self) -> str: \n \"\"\"Print the elements of the tower\"\"\"\n return repr(self._tower)\n\n\nif __name__ == '__main__':\n game = Plateau(3)\n game.move(1,3)\n game.move(1,3) # Try to move a big disk on a small one \n game.move(1,2)\n game.move(3,2) \n game.move(1,3)\n game.move(2,1) \n game.move(2,3) \n game.move(1,3)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T20:02:29.970",
"Id": "458824",
"Score": "0",
"body": "This is mostly good. I may add an answer of my own, but I wanted to react to your point #1: In OP's code, they _did not_ always use `get_last_disk` and `delete_disk` together, because they weren't treating illegal moves as exceptional. Between your nested-`try` pattern and what OP wrote, I think I'd prefer the original!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T10:16:52.357",
"Id": "458877",
"Score": "0",
"body": "Thanks, you provided me nice advices on POO and Python. I will look more for @Property, __repr__ and exception handling. NewType seems also to be a nice feature"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T19:37:03.700",
"Id": "234606",
"ParentId": "234602",
"Score": "4"
}
},
{
"body": "<p>The \"spirit\" of Object Oriented Programming is two-fold: </p>\n\n<ul>\n<li>To give us an enforceable metaphor for reasoning about our code. (\"objects\" as objects)</li>\n<li>To give us heuristics about how to compartmentalize out code. (encapsulation)</li>\n</ul>\n\n<p>The purist perspective of OOP can be a bit verbose, and in python it's not usually necessary. </p>\n\n<blockquote>\n <p>I want then a GUI with TKinter, a third class GUI would be suited ?</p>\n</blockquote>\n\n<p>Try thinking about it like this: An object method will have <em>both</em> a method that it's called on <em>and a context in which it gets called.</em> If you build a class to encapsulate your GUI, where will it's methods get called from? </p>\n\n<p>One of the principal things objects do is manage state. If a function needs to <em>update</em> state, that suggests that the function and the state could be encapsulated together in an object. If the function just needs to <em>read</em> a state, and that state (data) could be passed in as an argument by the calling context, then the function can be a static method or a global function. If a class <em>only</em> has static methods, then you don't need a class at all. That's a good thing: the less state you're managing the less opportunity to mess it up.</p>\n\n<blockquote>\n <p>How can it be improved (on the OOP level and on script level)?</p>\n</blockquote>\n\n<p><a href=\"https://codereview.stackexchange.com/a/234606/200133\">Sam Stafford's</a> points #4 and #5 are good, as is the suggestion to have <code>Disk</code> as a new type. </p>\n\n<ol>\n<li>You could also neglect to declare a proper class for the Towers by just having <code>Tower = NewType('Tower', List(Disk))</code>.</li>\n<li>If you're thinking of the normal input and output as a user-interface, then you probably shouldn't be printing (or reading input) from inside class methods. That said, <em>logging</em> is a fine thing to do, and <code>print</code> is a low-effort way to do it.</li>\n<li><code>Plateau.motion()</code> does too many things. Checking for victory should certainly go outside in the calling context. I would suggest that validating the user-input also doesn't belong in there. </li>\n<li>Similarly, <code>Plateau.check_victory()</code> shouldn't set up the new game, and <code>init_plateau</code> should get inlined into <code>Plateau.__init__()</code>. When you start a new game just build a new Plateau. </li>\n</ol>\n\n<p>Taken to the extreme, you could have a static class representing the state of the game, and a function to start a new game, and then you'd repeatedly call a function <code>(GameState, PlayerMove)->GameState</code>. At that point you'd be breaking past traditional imperative OOP into a more \"functional\" style. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T10:20:03.690",
"Id": "458878",
"Score": "0",
"body": "Ok thanks, I will focus on writing smaller methods"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T22:28:58.460",
"Id": "234613",
"ParentId": "234602",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T18:00:30.967",
"Id": "234602",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"tower-of-hanoi"
],
"Title": "Script for Python Hanoi Tower OOP"
}
|
234602
|
<p>Please be gentle. I'm a pygame n00b and haven't touched pygame in years. This is my unique implementation of the classic game snake. In this game, the snake has a velocity which can vary along both axes of motion in increments of one pixel per frame and the tail follows the exact path the head travels as the snake moves about the screen. If you move too slowly, you die (an unintended behavior but I have deemed it desirable.) If you collide with your own tail, you die. If you collide with an edge, you die and if you reverse direction, you die. My question concerns the manner in which the snakes body is represented internally.</p>
<p>My original plan for implementing this game was to store only the points at which the head changed velocity. Behavior equivalent to the above game description would be implemented by computing a point between the first point beyond the length of the tail (always at index 0 of <code>SnakeTail.body</code>) and the next point and storing it as <code>SnakeTail.pos</code>. This would be the distance remaining after the distance between all other points and the head position were subtracted from index 1 in <code>SnakeTail.body</code>.</p>
<p>By doing all rendering and collision detection using <code>SnakeTail.pos</code>-><code>SnakeTail.body[1:]</code>-><code>head</code>, behavior equivalent to the above description and the below implementation could be achieved.</p>
<p>I was honestly surprised how complex this really was. Vector math is hard! Any help will be greatly appreciated.</p>
<p>I have researched this matter extensively and found no answers.</p>
<p>O_G_Python.py:</p>
<pre><code>
import pygame
pygame.init()
import pygame.math as vectmath
import pygame.font as font
import random
# Screen dimension constants
S_WIDTH = 800
S_HEIGHT = 600
SCREEN_DIMENSIONS = (S_WIDTH, S_HEIGHT)
# Numerical game constants.
UNIT_SIZE = 15
NUM_SNACKS = 5
SNAKE_MAX_SPEED = 15
EVT_TIME = pygame.USEREVENT
VELOCITY_INCREMENT = 0.25
# Index constants
X = 0
Y = 1
# Vector constants.
INITIAL_VELOCITY = vectmath.Vector2((2, 2))
INITIAL_POSITION = vectmath.Vector2((S_WIDTH / 2, S_HEIGHT / 2))
# Color constants
PURPLE = (0x4b, 0x12, 0x54)
RED = (0xFF, 0x00, 0x00)
ORANGE = (0xf9, 0x7e, 0x20)
DARK_BLUE = (0x0f, 0x13, 0x54)
WHITE = (0xFF, 0xFF, 0xFF)
# Some functions that will be used frequently within this game.
def lineEndpointOnReverseVector(vect, startPos, lineLen, unitSize = 1):
lineLen *= unitSize
# Invert the vector
vect = vectmath.Vector2( -vect.x, -vect.y )
# Normalize the vector.
vect = vect.normalize()
# Scale the normalized vector by the desired length.
vect.x *= lineLen; vect.y *= lineLen
# Offset the vector by startPos and return it.
return vectmath.Vector2(startPos.x + vect.x, startPos.y + vect.y)
class LinkedVector:
def __init__ (self, position, parent):
# Copying both of these may be sub optimal in terms of memory usage, but
# it makes this class more reusable.
self.pos = vectmath.Vector2((position.x, position.y))
self.parent = vectmath.Vector2((parent.x, parent.y))
self.dist = self.pos.distance_to(self.parent)
# The snake head gets its own class because I want it to be responsible for
# rendering itself.
class SnakeHead:
def __init__ (self, initHeadPos, initHeadVel):
self.pos = vectmath.Vector2(initHeadPos)
self.vel = vectmath.Vector2(initHeadVel)
self.prevVel = None
self.color = ORANGE
# The way the tail gets rendered has complex dependencies on the number of
# bends in the snake and its length so this gets its own class too.
class SnakeTail:
def __init__ (self, initPos, initLen, initBody = None):
self.pos = initPos
if initBody == None:
self.body = [LinkedVector(
vectmath.Vector2((0, 0)),
initPos
)]
else:
self.body = initBody
self.bodyLen = initLen
self.color = DARK_BLUE
def update (self, head):
# Get rid of all bends in the snake body which are beyond the total length of
# the snake except the first as this is used for linear interpolation in the draw
# method.
headToFirstBendDist = head.pos.distance_to(self.body[-1].pos)
if headToFirstBendDist > self.bodyLen:
# In case of the whole body being out of the range of the first bend,
# calculate the coordinates of the end point of a line on a linear interpolation
# between the head and the last point in the body list which contains all the bends
# in the snake.
self.pos = head.pos.lerp(self.body[-1].pos, (float(self.bodyLen) / float(headToFirstBendDist)) % 1.0)
self.body = [LinkedVector(self.pos, head.pos)]
return # That's all our work done in this case.
# Iterate over the points and discard the points out of bounds of the snakes body length.
distanceSoFar = headToFirstBendDist
newBody = [self.body[-1]]
clearedFirstElement = False
for idx in range(-1, -len(self.body) - 1, -1):
point = self.body[idx]
# Keep the points that are within range of the head given the current body length.
if self.bodyLen > distanceSoFar + point.dist:
if not clearedFirstElement:
newBody.insert(0, point)
else:
newBody[0] = point
distanceSoFar += point.dist
else:
# TODO: Add calcs to compute a point between the current point and self.body[1] at distance
# distanceSoFar - self.bodyLen to make it possible to store only the points at which velocity
# changes and still produce the same behavior.
self.body = newBody
return
def draw (self, screen, head):
for idx, point in enumerate(self.body):
# Drawing code to be used if the above TODO is successfully implemented.
# if idx == 0:
# pygame.draw.circle(screen, self.color, (int(self.pos.x), int(self.pos.y)), int(UNIT_SIZE / 2))
# if len(self.body) >= 2:
# pygame.draw.line(
# screen,
# self.color,
# (int(self.pos.x), int(self.pos.y)),
# (int(self.body[idx + 1].pos.x), int(self.body[idx + 1].pos.y)),
# UNIT_SIZE
# )
# else:
# pygame.draw.line(
# screen,
# self.color,
# (int(self.pos.x), int(self.pos.y)),
# (int(head.pos.x), int(head.pos.y)),
# UNIT_SIZE
# )
if idx in range(0, len(self.body) - 2):
pygame.draw.circle(screen, self.color, (int(point.pos.x), int(point.pos.y)), int(UNIT_SIZE / 2))
pygame.draw.line(
screen,
self.color,
(int(point.pos.x), int(point.pos.y)),
(int(self.body[idx + 1].pos.x), int(self.body[idx + 1].pos.y)),
UNIT_SIZE
)
else:
pygame.draw.circle(screen, self.color, (int(point.pos.x), int(point.pos.y)), int(UNIT_SIZE / 2))
pygame.draw.line(
screen,
self.color,
(int(point.pos.x), int(point.pos.y)),
(int(head.pos.x), int(head.pos.y)),
UNIT_SIZE
)
class Snake:
def __init__ (self, initHeadPos, initHeadVel, initLen = 5 * UNIT_SIZE):
self.head = SnakeHead(initHeadPos, initHeadVel)
tailPos = lineEndpointOnReverseVector(
self.head.vel,
self.head.pos,
initLen,
UNIT_SIZE
)
self.tail = SnakeTail(
tailPos,
initLen,
[LinkedVector(tailPos, self.head.pos)]
)
def addToVel (self, velocity, limit = -1):
# Store a copy of the current velocity for collision detection and rendering purposes.
self.head.prevVel = vectmath.Vector2((self.head.vel.x, self.head.vel.y))
if limit >= 0:
# Handle cases of the speed being limited by adding the velocity
# and checking to see if it's over the limit.
alteredVel = vectmath.Vector2((
self.head.vel.x + velocity[X],
self.head.vel.y + velocity[Y]
))
if alteredVel.magnitude() <= limit:
self.head.vel = alteredVel
reachedLimit = False
else:
reachedLimit = True
else:
self.head.vel = vectmath.Vector2((
self.head.vel.x + velocity[X],
self.head.vel.y + velocity[Y]
))
reachedLimit = False
# Set the prevVel property to None if velocity is not 0 to tell the update and draw methods to
# use the current velocity.
if self.head.vel.x != 0 or self.head.vel.y != 0:
self.head.prevVel = None
if reachedLimit:
self.head.color = DARK_BLUE
self.tail.color = ORANGE
else:
self.head.color = ORANGE
self.tail.color = DARK_BLUE
# Append the coordinates at which the head changed direction to the bends list.
self.tail.body.append(LinkedVector(self.head.pos, self.tail.body[-1].pos))
# Return reachedLimit. This will be used by the game loop to briefly change how the snake is
# rendered if the user tries to go over the speed limit.
return reachedLimit
def createHeadTriangle (self, velocity, position):
# Transform the verticies of the isociles triangle below to make
# it face the direction of motion and translate to the heads
# position on the screen.
headLen = UNIT_SIZE * 2
headWidth = UNIT_SIZE * 1
# The coords of the three verticies positioned around the origin to make the
# rotation easier.
topLeft = vectmath.Vector2(-float(headWidth / 2), -float(headLen / 2))
topRight = vectmath.Vector2(float(headWidth / 2), -float(headLen / 2))
bottomCenter = vectmath.Vector2(0.0, float(headLen / 2))
theta = vectmath.Vector2(velocity).angle_to(vectmath.Vector2(0, 1))
topLeft = topLeft.rotate(-theta)
topRight = topRight.rotate(-theta)
bottomCenter = bottomCenter.rotate(-theta)
# For now, just return this triangle to see how it looks.
return (
(int(topRight.x) + position[X], int(topRight.y) + position[Y]),
(int(topLeft.x) + position[X], int(topLeft.y) + position[Y]),
(int(bottomCenter.x) + position[X], int(bottomCenter.y) + position[Y])
)
def getHeadTriangle (self):
# This getter gets the head triangle facing the direction of motion when velocity is
# non-zero and returns the head facing along the previous velocity vector in cases of
# the head velocity being 0 to stop the head snapping to theta = 0.
if self.head.prevVel != None:
return self.createHeadTriangle(self.head.prevVel, self.head.pos)
else:
return self.createHeadTriangle(self.head.vel, self.head.pos)
def collidedWithTail (self):
headTriangle = self.getHeadTriangle()
for idx in range(0, len(self.tail.body) - 45):
point = self.tail.body[idx]
x, y = (point.pos.x, point.pos.y)
for vertex in headTriangle:
a = x - vertex[X] - x if vertex[X] > x else vertex[X] - x
b = y - vertex[Y] - y if vertex[Y] > y else vertex[Y] - y
if a*a + b*b <= (UNIT_SIZE / 2) * (UNIT_SIZE / 2): return True
# TODO: Add additional check to see if the points in the head come within UNIT_SIZE / 2
# of the line segment from tail.body[idx] to tail.body[idx + 1] and the line segment
# tail.pos to tail.body[0] to accomodate the TODO optimization described above.
def update (self, screenW, screenH):
self.head.pos.x += self.head.vel.x
self.head.pos.y += self.head.vel.y
headTriangle = self.getHeadTriangle()
# Append a new point to the snake body.
self.tail.body.append(LinkedVector(self.head.pos, self.tail.body[-1].pos))
# Update the tail.
self.tail.update(self.head)
# Detect edge collisions and return True if the collision has occurred.
for point in headTriangle:
if point[X] < 0 or point[X] > S_WIDTH:
return True
if point[Y] < 0 or point[Y] > S_HEIGHT:
return True
return self.collidedWithTail()
def draw (self, screen):
if self.head.prevVel != None:
# Get the head triangle at the previous velocity to keep it from snapping to theta = 0.
headTriangle = self.createHeadTriangle(self.head.prevVel, self.head.pos)
else:
# The current velocity is not 0.
headTriangle = self.createHeadTriangle(self.head.vel, self.head.pos)
self.tail.draw(screen, self.head)
pygame.draw.polygon(screen, self.head.color, headTriangle)
def main ():
screen = pygame.display.set_mode(SCREEN_DIMENSIONS)
pygame.display.set_caption("0 G Python")
running = True
clock = pygame.time.Clock()
snake = Snake(INITIAL_POSITION, INITIAL_VELOCITY)
snackCoords = [
vectmath.Vector2((random.randint(8, S_WIDTH - 8), random.randint(8, S_HEIGHT - 8)))
for x in range(NUM_SNACKS)
]
score = 0
gameFontName = "freesansbold.ttf"
gameFontName = font.match_font(gameFontName)
# Cross-platform compatibility stuff.
if gameFontName == None:
gameFontName = font.match_font(font.get_default_font())
gameFont = font.Font(gameFontName, 30)
else:
gameFont = font.Font(gameFontName, 30)
time = 0
pygame.time.set_timer(EVT_TIME, 1000)
# Key held boolean flags
upHeld = False
downHeld = False
leftHeld = False
rightHeld = False
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == pygame.K_w:
upHeld = True
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
downHeld = True
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
leftHeld = True
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
rightHeld = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_w:
upHeld = False
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
downHeld = False
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
leftHeld = False
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
rightHeld = False
if event.type == EVT_TIME:
time += 1
# Update the snakes velocity.
if upHeld:
snake.addToVel((0, -VELOCITY_INCREMENT), SNAKE_MAX_SPEED)
if downHeld:
snake.addToVel((0, VELOCITY_INCREMENT), SNAKE_MAX_SPEED)
if leftHeld:
snake.addToVel((-VELOCITY_INCREMENT, 0), SNAKE_MAX_SPEED)
if rightHeld:
snake.addToVel((VELOCITY_INCREMENT, 0), SNAKE_MAX_SPEED)
# Update the snake.
collisionDetected = snake.update(S_WIDTH, S_HEIGHT)
if collisionDetected:
score = 0
time = 0
snake = Snake(INITIAL_POSITION, INITIAL_VELOCITY)
snackCoords = [
vectmath.Vector2((random.randint(8, S_WIDTH - 8), random.randint(8, S_HEIGHT - 8)))
for x in range(NUM_SNACKS)
]
# Fill in the background.
screen.fill(PURPLE)
# Draw the score onto the screen.
scoreSurface = gameFont.render(f"Score: {score}", False, WHITE)
screen.blit(scoreSurface, (5, 5))
timeSurface = gameFont.render(f"Time: {time}", False, WHITE)
screen.blit(timeSurface, (5, scoreSurface.get_height() + 5))
# Render the snacks onto the screen and generate new coordinates for snacks
# if all the snacks have been eaten.
if len(snackCoords) != 0:
tempSnacks = []
headTriangle = snake.getHeadTriangle()
for idx, snack in enumerate(snackCoords):
beenEaten = False
intSnack = ( int(snack.x), int(snack.y) )
pygame.draw.circle(screen, RED, intSnack, int(UNIT_SIZE / 2))
# Check for collisions between the snakes head and a snack.
for point in headTriangle:
a = point[X] - snack.x if point[X] > snack.x else snack.x - point[X]
b = point[Y] - snack.y if point[Y] > snack.y else snack.y - point[Y]
if a * a + b * b < (UNIT_SIZE / 2) * (UNIT_SIZE / 2):
beenEaten = True
snake.tail.bodyLen += UNIT_SIZE * 5
score += 5
if not beenEaten: tempSnacks.append(snack)
snackCoords = tempSnacks
else:
snackCoords = [
vectmath.Vector2((random.randint(8, S_WIDTH - 8), random.randint(8, S_HEIGHT - 8)))
for x in range(NUM_SNACKS)
]
# Render the snake onto the screen.
snake.draw(screen)
pygame.display.flip()
clock.tick(30)
if __name__ == "__main__":
main()
</code></pre>
<p>Edit: I dramatically improved the gameplay by changing acceleration from key pressed to key held.</p>
<p>Edit: improved phrasing to make the question more understandable.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T22:11:31.907",
"Id": "234611",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"pygame"
],
"Title": "I want to enhance the memory performance of this game by storing only locations where velocity changes"
}
|
234611
|
<p>This is more to get clarity on an implementation that I did. I am working on a React, Node, and Electron application that essentially has a form that a user inputs values that will update some content files.</p>
<p>The application has to scale for a lot of different scenarios so I found that I kept writing switch statements to incorporate all of these scenarios. So for the sake of time I wrote a class that:</p>
<ol>
<li>Takes in two arrays, An array of keys and array of functions that correspond to those keys.</li>
<li>The constructor function creates a table for the values</li>
<li>Then there is a method on the class that allows you to look up that value and returns it</li>
</ol>
<p>here is the code</p>
<pre><code>Array.prototype.createObjectFromKeysandValues = function(array) {
let table = {}
for(let pointer=0;pointer<this.length;pointer++){
let key = this[pointer]
let value = array[pointer]
table[key]=value
}
return table
}
module.exports = class KeyFunctionMappingTable {
constructor(keys, values){
this.lookUpTable = Object.assign({},
keys.createObjectFromKeysandValues(values),
{ default: () => new Error("Value Not Found")})
}
findHandlerFunction(value){
return this.lookUpTable[value]|| this.lookUpTable.default
}
}
</code></pre>
<p>So when the code is implemented it looks like this ( this scenario is for React Components) :</p>
<pre><code>const factory = new KeyFunctionMappingTable(['select', 'input'], [
(options, labelText) => ( <Select options={options} labelText={labelText} />),
(options, labelText) => ( <Input labelText={labelText} />)])
</code></pre>
<p>I am finding that I have about three of these "mappings" throughout the code.</p>
<p>What I want to know is if this seems like a readable implementation and does this make sense to strangers. If you dont think so please let me know your suggestion.</p>
|
[] |
[
{
"body": "<p>You have just added an unneeded layer of complexity to the problem.</p>\n\n<p>You can just create the <code>factory</code> as an <code>Object</code></p>\n\n<pre><code>const factory = {\n select(opts, text) { return (<select options={opts} labelText={text} />) },\n input(opts, text) { return (<input labelText={text} />) },\n default() { return new Error(\"Value Not Found\") }\n};\n</code></pre>\n\n<p>Then call the function with</p>\n\n<pre><code>(factory[value] || factory.default)(opts, text);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T02:21:57.713",
"Id": "458859",
"Score": "0",
"body": "Hey thanks for this. Should I keep the class or just use objects through out the application in all of the instances of this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T03:44:35.340",
"Id": "458865",
"Score": "1",
"body": "@GrantHerman Keep it simple and just use the object where you previously assigned `KeyFunctionMappingTable`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T08:57:19.663",
"Id": "458872",
"Score": "0",
"body": "You may also want to add method that encpsulates the invocation with fallback to default, so that the `|| factory.default` invocation does not get repeated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T01:52:47.283",
"Id": "234618",
"ParentId": "234615",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "234618",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-24T23:19:21.823",
"Id": "234615",
"Score": "5",
"Tags": [
"javascript",
"object-oriented",
"node.js",
"react.js",
"electron"
],
"Title": "Class for Switch statements"
}
|
234615
|
<p>The code takes a very simple xml and converts it into a dataframe in csv file.</p>
<p>This is the Xml file</p>
<pre><code><Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Phones>
<Date />
<Prog />
<Box />
<Feature />
<WIN>MAFWDS</WIN>
<Set>234234</Set>
<Pr>23423</Pr>
<Number>afasfhrtv</Number>
<Simple>dfasd</Simple>
<Nr />
<gt>6070106091</gt>
<Reno>1233</Reno>
<QW>3234</QW>
<ER />
<VR />
<Use />
<Dar>sdfsd</Dar>
<age />
<name1>sdfsfdfs</name1>
<Sys>IVECO E.A.SY.</Sys>
<aac>2019-05-29</aac>
<time>02:00</time>
<nuk name="This is some text" text_g="asadsdas" text_h="2">fsdfsfd3432fdf</nuk>
</Phones>
</Data>
</code></pre>
<p>This is my code.
It works, it just gets way too long when I want to include all the children of the father <strong>phones</strong>.
Looking for some help on how to shorter the code but it performing the same purpose.</p>
<p>This is the code</p>
<pre><code>import xml.etree.cElementTree as et
import pandas as pd
df = pd.DataFrame()
def getvalueofnode(node):
""" return node text or None """
return node.text if node is not None else None
def main():
""" main """
parsed_xml = et.parse("short.xml")
dfcols = ['Date', 'Prog', 'Box', 'Feature', 'WIN']
df_xml = pd.DataFrame(columns=dfcols)
for node in parsed_xml.findall('Phones'):
Date = node.find("Date")
Prog = node.find('Prog')
Box = node.find('Box')
Feature = node.find('Feature')
WIN = node.find('WIN')
df = df_xml.append(
pd.Series([getvalueofnode(Date), getvalueofnode(Prog), getvalueofnode(Box),
getvalueofnode(Feature), getvalueofnode(WIN)], index=dfcols),
ignore_index=True)
df.to_csv("./export.csv")
main()
</code></pre>
<p>This is all the columns declared fro dfcols</p>
<pre><code>dfcols = ['Date', 'Prog', 'Box', 'Feature', 'WIN',
'Set', 'Pr', 'Number','Simple','Nr',
'gt', 'Reno','QW', 'ER','VR', 'Use',
'Dar','age','name1', 'Sys' 'aac',
'time', 'nuk']
</code></pre>
<p><strong>Additional</strong> </p>
<p>The element <strong>nuk</strong> has multiple attributes so each attributes gets its own column
Example</p>
<p>nuk_name, nuk_text_g, nuk_text_h </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T08:07:03.500",
"Id": "458871",
"Score": "0",
"body": "With *all the children of the father phones* - did you mean all tags within `Phones` parent tag having dataframe to declare 23 columns?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T10:31:19.433",
"Id": "458879",
"Score": "0",
"body": "@RomanPerekhrest, yes that is what I meant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T11:10:43.587",
"Id": "458882",
"Score": "0",
"body": "You said \"it just gets way too long when I want to include all the children\" and that's the case of your concern. So you need to post the actual code where you attempted \"to include all the children\". That's 2 different cases - parsing a particular tags and parsing all the tags. Post or extend the code that is of concern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T13:00:18.347",
"Id": "458888",
"Score": "0",
"body": "@RomanPerekhrest, I didn't add all the code because it just was too long. Inside the for loop I want to go through all the tags and parse them. When I wrote all of them the code inside the for loop gets long"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T13:05:07.997",
"Id": "458889",
"Score": "0",
"body": "at least, show how did you define `dfcols` for all columns. Did you hardcode 23 names manually OR parse the 1st block to get dynamic column names? Post the fragment where you defined `dfcols` for all tags"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T14:16:04.503",
"Id": "458890",
"Score": "0",
"body": "@RomanPerekhrest, I updated my question above."
}
] |
[
{
"body": "<p>There are multiple ways to improve upon this code. I'll go through each thing I found and show how to better implement a solution.</p>\n\n<ul>\n<li><code>getvalueofnode()</code> is redundant. You're checking if something is not <code>None</code> but returning <code>None</code> if the object is <code>None</code>. Instead of using this wrapper function, it is far simpler to just use the value of <code>node.text</code>. So in this example, every instance of <code>getvalueofnode(node)</code> should be translated to <code>node.text</code> without consequence. </li>\n<li>From the comments, it seems like you have a list of columns you would like to add from the xml. This seems like an excellent case for a for loop-- provided you have a predefined list of the columns you would like to extract.</li>\n<li>I notice you are using two dataframes. Why? From what I can gather, it is simpler to only keep track of one dataframe and use that for the result. </li>\n<li>On the topic of dataframes, it is better to collect all your values first and then translate the array of arrays to a dataframe <strong>at the end</strong>. Using <code>df.append</code> is an expensive operation and is not preferred when adding one row at a time in a predictable manner like this solution. It is better to collect all the values first and then convert the whole 2D array to a dataframe.</li>\n</ul>\n\n<p>With those points in mind and a few more Pythonic changes, here is what a cleaned up version should look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import xml.etree.cElementTree as ET\nimport pandas as pd\n\n\nif __name__ == '__main__':\n\n parsed_xml = ET.parse(\"xml_parsing.xml\")\n dfcols = ['Date', 'Prog', 'Box', 'Feature', 'WIN']\n\n values = []\n for node in parsed_xml.findall('Phones'):\n values.append(map(lambda n: node.find(n).text, dfcols))\n\n df_xml = pd.DataFrame(values, columns=dfcols)\n\n df_xml.to_csv(\"./xml_parsing.csv\")\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T18:20:18.023",
"Id": "458911",
"Score": "0",
"body": "thank you for your answers, Some really good points. I tried the code. It is created the columns but didn't get the data their carry. So it was empty besides the columns"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T17:39:28.627",
"Id": "234638",
"ParentId": "234616",
"Score": "1"
}
},
{
"body": "<h3>Optimization and restructuring</h3>\n\n<p><em>Redundant and inefficient things</em><br>\nThe <code>getvalueofnode</code> function is unneeded: <code>text</code> attribute of a node will be <code>None</code> or string value. <br>All intermediate dataframes are also unnecessary.<br>Avoid using <code>pd.Dataframe.append</code> method within any loop as it will create a copy of accumulated dataframe of <strong>each</strong> loop iteration.</p>\n\n<p><em>Namings</em><br>\nUse a meaningful names for your functions and <code>if __name__ == '__main__':</code> <em>guard</em>.<br>I would suggest <strong><code>phones_to_df</code></strong> function name.</p>\n\n<hr>\n\n<p>Assuming that the goal is to convert all <code>Phones</code> tags child nodes into dataframe records - all you need is collect a dictionaries of child nodes as <code><el.tag: el.text></code> mappings at once (+ special case for <strong><code>nuk</code></strong> tag, see below).<br>Note, that some <code>Phones</code> tags could have their children in different order. So a list of dictionaries provides a robust way to arrange columns to respective values.</p>\n\n<p>See the concise optimized approach below:</p>\n\n<pre><code>import xml.etree.cElementTree as cET\nimport pandas as pd\n\n\ndef phones_to_df(fname):\n tree = cET.parse(fname)\n pd.DataFrame([{**{el.tag: el.text for el in list(phone)},\n **{f'nuk_{k}': v for k, v in phone.find('nuk').items()}}\n for phone in tree.iterfind('Phones')]).to_csv('export.csv', index=False)\n\n\nif __name__ == '__main__':\n phones_to_df(fname=\"test.xml\")\n</code></pre>\n\n<hr>\n\n<p>After generating the expected <code>export.csv</code> file the resulting sample dataframe may look as below (I've tested on xml file with 2 <code>Phones</code> tags):</p>\n\n<pre><code>print(pd.read_csv('export.csv').to_string())\n\n Date Prog Box Feature WIN Set Pr Number Simple Nr gt Reno QW ER VR Use Dar age name1 Sys aac time nuk nuk_name nuk_text_g nuk_text_h\n0 NaN NaN NaN NaN MAFWDS 234234 23423 afasfhrtv dfasd NaN 6070106091 1233 3234 NaN NaN NaN sdfsd NaN sdfsfdfs IVECO E.A.SY. 2019-05-29 02:00 fsdfsfd3432fdf This is some text asadsdas 2\n1 NaN NaN NaN NaN ABCD 123 456 aaa bbb NaN 1111 222 333 NaN NaN NaN rrr NaN wwww TIMES E.A.SY. 2019-12-29 03:00 text ... This is some text asadsdas 2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T19:40:09.470",
"Id": "458916",
"Score": "0",
"body": "thank you very much . The only problem I'm having right now is with the element nuk. I would have liked to show all of its attributes like one column for nuk_name, nuk_text_g , nuk_text_h. Considering that is also important information and I need to have in the csv file"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T20:05:26.123",
"Id": "458918",
"Score": "0",
"body": "@ebe, You need to reflect your requirements in your main question so all the contributors could see all the conditions from the very start"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T20:26:51.083",
"Id": "458921",
"Score": "0",
"body": "@ RomanPerekhrest , I'm sorry that is my mistake. Already added. Would really appreciate if you would help me with park and then me marking this as answered so it would be helpful in case anyone is facing similar problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T21:50:55.647",
"Id": "458928",
"Score": "0",
"body": "@ebe, Ok, the update is ready, you may check"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:39:38.263",
"Id": "459011",
"Score": "0",
"body": "I marked the question as answered. thank you. I have on quick question. Is It possible to make so that I read from a folder that as xml files and parses them into one csv file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T20:13:32.183",
"Id": "459013",
"Score": "0",
"body": "@ebe, that could be a case for another CR question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T20:24:25.580",
"Id": "459014",
"Score": "0",
"body": "I would post a question but CR is for code that already works and I can just aks how to read through multiple xmls. Can you help me ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T11:30:15.537",
"Id": "459115",
"Score": "0",
"body": "hello, can you please have a look at this , still struggling on how to read through multiple xml files using your code. https://stackoverflow.com/a/59501200/12325998"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T12:53:19.363",
"Id": "459116",
"Score": "0",
"body": "@ebe, But that question has already been answered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T12:57:02.503",
"Id": "459117",
"Score": "0",
"body": "if you look at the comment I have added a link to were the entire code answered is and it is not working for me. Considering that to give the path to a folder of xml files is given but then also the name to a single xml file. Would really appreciate your answer there"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T19:05:44.577",
"Id": "234642",
"ParentId": "234616",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "234642",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T00:46:00.597",
"Id": "234616",
"Score": "4",
"Tags": [
"python",
"pandas"
],
"Title": "Xml to Csv Python Code too long"
}
|
234616
|
<p>I've never programmed in C before, but decided I wanted to try making Chess. Currently there's no way to check whether the game has ended. Was looking for critique for future projects.</p>
<pre><code>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
// 1 pawn 2 rock 3 bishop 4 knight 5 queen 6 king
int currentTurn = 1;
int board[8][8] = {
{2,4,3,5,6,3,4,2},
{1,1,1,1,1,1,1,1},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1},
{2,4,3,5,6,3,4,2}
};
int blackWhite[8][8] = {
{2,2,2,2,2,2,2,2},
{2,2,2,2,2,2,2,2},
{2,2,2,2,2,2,2,2},
{1,1,1,2,2,2,2,2},
{2,2,2,2,2,2,2,2},
{2,2,2,2,2,2,2,2},
{1,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,1}
};
int moves[8][8];
int getValidMoves(int x, int y){
int piece = board[y][x];
int color = blackWhite[y][x];
int canMove = 1;
moves[y][x] = 2;
if(x > 7 || x < 0 || y > 7 || y < 0)
return 1;
if(piece == 0){
return 1;
}
void towerMoves(){
for(int dir = -1; dir < 2; dir+=2){
int count = 1;
while(1){
if(x+(count*dir) <= 7 && x+(count*dir) >= 0){
if(board[y][x+(count*dir)] != 0){
if(blackWhite[y][x+(count*dir)] != color){
moves[y][x+(count*dir)] = 3;
canMove = 0;
}
break;
}else{
moves[y][x+(count*dir)] = 1;
canMove = 0;
}
}else{
break;
}
count++;
}
count = 1;
while(1){
if(y+(count*dir) <= 7 && y+(count*dir) >= 0){
if(board[y+(count*dir)][x] != 0){
if(blackWhite[y+(count*dir)][x] != color){
moves[y+(count*dir)][x] = 3;
canMove = 0;
}
break;
}else{
moves[y+(count*dir)][x] = 1;
canMove = 0;
}
}else{
break;
}
count++;
}
}
}
void runnerMove(){
for(int xDir = -1; xDir < 2; xDir+=2){
for(int yDir = -1; yDir < 2; yDir+=2){
int count = 1;
while(1){
if(x+(count*xDir) <= 7 && x+(count*xDir) >= 0 && y+(count*yDir) <= 7 && y+(count*yDir) >= 0){
if(board[y+(count*yDir)][x+(count*xDir)] != 0){
if(blackWhite[y+(count*yDir)][x+(count*xDir)] != color){
moves[y+(count*yDir)][x+(count*xDir)] = 3;
canMove = 0;
}
break;
}else{
moves[y+(count*yDir)][x+(count*xDir)] = 1;
canMove = 0;
}
}else{
break;
}
count++;
}
}
}
}
if(piece == 1){
if(color == 1){
if(y == 6 && board[y-2][x] == 0){
moves[y-2][x] = 1;
canMove = 0;
}
if(y-1 >= 0){
if(board[y-1][x] == 0){
moves[y-1][x] = 1;
canMove = 0;
}
if(x + 1 <= 7 && blackWhite[y-1][x+1] == 2 && board[y-1][x+1] != 0){
moves[y-1][x+1] = 3;
canMove = 0;
}
if(x - 1 >= 0 && blackWhite[y-1][x-1] == 2 && board[y-1][x-1] != 0){
moves[y-1][x-1] = 3;
canMove = 0;
}
}
}else{
if(y == 1 && board[y+2][x] == 0){
moves[y+2][x] = 1;
canMove = 0;
}
if(y+1 <= 7){
if(board[y+1][x] == 0){
moves[y+1][x] = 1;
canMove = 0;
}
if(x + 1 <= 7 && blackWhite[y+1][x+1] == 1 && board[y+1][x+1] != 0){
moves[y+1][x+1] = 3;
canMove = 0;
}
if(x - 1 >= 0 && blackWhite[y+1][x-1] == 1 && board[y+1][x-1] != 0){
moves[y+1][x-1] = 3;
canMove = 0;
}
}
}
}
if(piece == 4){
for(int i = -1; i < 2; i+=2){
//TODO CLEAN THIS UP
if(x+i <= 7 && x+i >= 0 && y+(2*i) >= 0 && y+(2*i) <= 7){
moves[y+(2*i)][x+i] = blackWhite[y+(2*i)][x+i] == color && board[y+(2*i)][x+i] != 0 ? 0 : 1;
canMove = 0;
}
if(y+i <= 7 && y+i >= 0 && x+(2*i) >= 0 && x+(2*i) <= 7){
moves[y+i][x+(2*i)] = blackWhite[y+i][x+(2*i)] == color && board[y+i][x+(2*i)] != 0 ? 0 : 1;
canMove = 0;
}
if(x-i <= 7 && x-i >= 0 && y+(2*i) >= 0 && y+(2*i) <= 7){
moves[y+(2*i)][x-i] = blackWhite[y+(2*i)][x-i] == color && board[y+(2*i)][x-i] != 0 ? 0 : 1;
canMove = 0;
}
if(y-i <= 7 && y-i >= 0 && x+(2*i) >= 0 && x+(2*i) <= 7){
moves[y-i][x+(2*i)] = blackWhite[y-i][x+(2*i)] == color && board[y-i][x+(2*i)] != 0 ? 0 : 1;
canMove = 0;
}
}
}
if(piece == 3){
runnerMove();
}
if(piece == 2){
towerMoves();
}
if(piece == 5){
towerMoves();
runnerMove();
}
if(piece == 6){
for(int xDir = -1; xDir < 2; xDir++){
for(int yDir = -1; yDir < 2; yDir++){
if(xDir+x <= 7 && xDir+x >= 0 && y+yDir >= 0 && yDir+y <= 7 && !(xDir == 0 && yDir == 0)){
if(board[yDir+y][xDir+x] != 0){
if(blackWhite[yDir+y][xDir+x] != color)
moves[yDir+y][xDir+x] = 3;
canMove = 0;
}else{
moves[yDir+y][xDir+x] = 1;
canMove = 0;
}
}
}
}
}
return canMove;
}
void drawBoard(){
printf(" ");
for(int y = 0; y < 8; y++){
printf("%d: ",y+1);
}
printf("\n");
for(int x = 0; x < 8; x++){
printf("%d: ",x+1);
for(int y = 0; y < 8; y++){
if(board[x][y] != 0){
printf("%d%d",board[x][y],blackWhite[x][y]);
}else{
printf("--");
}
printf(" ");
}
printf("\n");
}
}
void drawMoves(){
printf(" ");
for(int y = 0; y < 8; y++){
printf("%d: ",y+1);
}
printf("\n");
for(int x = 0; x < 8; x++){
printf("%d: ",x+1);
for(int y = 0; y < 8; y++){
if(moves[x][y] == 0){
printf("--");
}else{
printf("%d%d",moves[x][y],moves[x][y]);
}
printf(" ");
}
printf("\n");
}
}
char message[] = "White's turn";
int main(){
while(1){
system("@cls||clear");
printf("----------------\n");
printf(" Chess in C\n");
printf("----------------\n\n");
printf("1.Start\n");
printf("2.Rules\n");
printf("3.Exit\n");
printf("Input: ");
int input;
scanf("%d", &input);
switch(input){
case 1:
goto start;
break;
case 2:
system("@cls||clear");
printf("-Every chess piece is displayed as a two digit number, example 42\n");
printf("-The first number, 4 in this case indicates what chess piece it is\n");
printf("-The second number, 2 indicates what color it is\n");
printf("-When selecting a chess piece you select a cordinate where to origin is top left\n");
printf("-Firstly you select a x position by typing a number from 1-8 and press enter\n");
printf("-After that you select a y position from 1-8 and press enter\n");
printf("-A menu will apear with availbe moves where a 22 is idicating of where your chess piece is and 11 for where it can move\n");
printf("-If the move will result in a capture a 33 will be displayed instead of a 11\n");
printf("-Follow the above steps on picking a cordinate to chose where the chess piece should be moved\n\n");
printf("-Chess piece numbers are as follows: 1 pawn, 2 rook, 4 knight, 3 bishop, 5 queen, 6 king\n");
printf("-Color numbers are as follows: 1 white, 2 black\n\n");
scanf("%d", &input);
break;
case 3:
return 0;
break;
}
}
start:
while(1){
system("@cls||clear");
if(currentTurn == 1){
printf("White's turn\n\n");
}else{
printf("Black's turn\n\n");
}
drawBoard();
int input[2];
for(int i = 0; i < 2; i++){
int c;
scanf("%d", &c);
input[i] = c - 1;
}
int x = input[0];
int y = input[1];
if(board[y][x] == 0)
continue;
if(blackWhite[y][x] != currentTurn)
continue;
if(getValidMoves(x,y) == 1)
continue;
system("@cls||clear");
drawBoard();
printf("\n");
drawMoves();
for(int i = 0; i < 2; i++){
int c;
scanf("%d", &c);
input[i] = c - 1;
}
if(moves[input[1]][input[0]] == 1 || moves[input[1]][input[0]] == 3){
blackWhite[input[1]][input[0]] = blackWhite[y][x];
board[input[1]][input[0]] = board[y][x];
board[y][x] = 0;
currentTurn = currentTurn == 1 ? 2 : 1;
}
for(int x_ = 0; x_ < 8; x_++){
for(int y_ = 0; y_ < 8; y_++){
moves[x_][y_] = 0;
}
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T05:08:29.807",
"Id": "458868",
"Score": "1",
"body": "`2 rock` guess `7 paper 8 scissors` have been lost due to `weather`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T12:23:30.520",
"Id": "458885",
"Score": "3",
"body": "Welcome to code review. What version of C are you compiling with because my C99 compiler doesn't allow the definition/declaration of functions within other functions. It seems like the code is doing this to get around parameter passage."
}
] |
[
{
"body": "<h1>Use <code>enum</code>s to give names to numbers</h1>\n\n<p>It would be great if you could write <code>PAWN</code> instead of <code>1</code>, since it will be much clearer what you are doing in the code. The way to do this is to declare an <code>enum</code> for all possible chess piece types:</p>\n\n<pre><code>enum Type {\n NONE = 0,\n PAWN,\n ROOK,\n BISHOP,\n KNIGHT,\n QUEEN,\n KING,\n};\n</code></pre>\n\n<p>I added <code>NONE</code> as well, it will be useful later to indicate tiles without a piece on them.\nOnce you have done that, instead of <code>if (piece == 1)</code>, you can write <code>if (piece == PAWN)</code>. Similarly, do this for the color of pieces:</p>\n\n<pre><code>enum Color {\n BLACK = 1,\n WHITE,\n};\n</code></pre>\n\n<h1>Define a <code>struct</code> to combine chess piece type and color</h1>\n\n<p>Chess piece type and color go together, so it makes sense to make a struct out of this:</p>\n\n<pre><code>struct Piece {\n enum Type type;\n enum Color color;\n};\n</code></pre>\n\n<p>Now we have that, we can combine the arrays <code>board</code> and <code>blackWhite</code> into one:</p>\n\n<pre><code>struct Piece board[8][8];\n</code></pre>\n\n<p>Now, instead of writing <code>color = blackWhite[y][x]</code>, you can write <code>color = board[y][x].color</code>.</p>\n\n<p>Note, you could have made a single <code>enum</code> that listed both the black and white pieces (with names like <code>WHITE_ROOK</code>), and avoid having to create <code>struct Piece</code>, but indeed in your code it makes sense to have piece type and color as separate elements.</p>\n\n<h1>Don't use nested functions</h1>\n\n<p>Nested functions are a GCC extension, but are not standard C. This means your code is not portable. Just move the functions <code>towerMoves()</code> and <code>runnerMove()</code> outside of <code>getValidMoves()</code>. Of course, now you need to pass <code>x</code> and <code>y</code> as arguments to these functions, and they should return the value of <code>canMove</code>.</p>\n\n<h1>Use <code>switch</code>-statements where appropriate</h1>\n\n<p>Instead of having a long list of <code>if</code>-statements to check for each possible value of <code>piece</code> in <code>getValidMoves()</code>, write a <code>switch</code>-statement, like so:</p>\n\n<pre><code>switch (piece) {\ncase PAWN:\n ...\n break;\ncase ROOK:\n towerMoves();\n break;\ncase ...:\n}\n</code></pre>\n\n<p>Not only does this improve the structure of your code, the compiler will actually check that you implemented a <code>case</code>-statement for each possible value of <code>piece</code>, and will warn you if you missed one.</p>\n\n<h1>Move more code into separate functions</h1>\n\n<p><code>getValidMoves()</code> is a very long function, even with the nested functions moved out of it. It makes sense to also make separate functions for getting the valid moves for each of the other chess piece types. This way, <code>getValidMoves()</code> will be much shorter and clearer to read.</p>\n\n<h1>Be consistent when naming functions and variables</h1>\n\n<p>Decide whether you want to call it a rook or a tower, a bishop or a runner. Prefer using the official names for chess pieces.</p>\n\n<p>You are also not consistent with other things; for example one functions is <code>towerMoves()</code>, another <code>runnerMove()</code> without the s. These functions are also just specializations of <code>getValidMoves()</code>. So be more consistent, and name the first two <code>getValidRookMoves()</code> and <code>getValidBishopMoves()</code>.</p>\n\n<h1>Add whitespaces to make the structure of your code more clear</h1>\n\n<p>Add empty lines between functions, and between major sections within functions. This helps make the structure of your code more clear.</p>\n\n<h1>Avoid using <code>system()</code></h1>\n\n<p>Don't call <code>system()</code> for things you can just as well do within C itself. Using <code>system()</code> has a huge overhead, and it is not portable. To clear the screen, you can use ANSI escape codes, which will work in most terminals. See: <a href=\"https://stackoverflow.com/questions/37774983/clearing-the-screen-by-printing-a-character\">https://stackoverflow.com/questions/37774983/clearing-the-screen-by-printing-a-character</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:13:24.657",
"Id": "458945",
"Score": "0",
"body": "Thank you so much. Didn't know what enums was before this, but i'll 100% use them in the future. Again thank you, really good response :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T22:29:54.123",
"Id": "234647",
"ParentId": "234619",
"Score": "14"
}
},
{
"body": "<p>Small review</p>\n\n<p><strong>Put test first</strong></p>\n\n<pre><code>int getValidMoves(int x, int y){\n // Move test here\n if(x > 7 || x < 0 || y > 7 || y < 0) {\n return 1;\n }\n\n int piece = board[y][x];\n int color = blackWhite[y][x];\n int canMove = 1;\n moves[y][x] = 2;\n\n // Why test so late? \n // Damage has been done access the above arrays with out-of-bounds indexes\n // if(x > 7 || x < 0 || y > 7 || y < 0)\n // return 1;\n</code></pre>\n\n<p><strong>Avoid naked magic numbers</strong></p>\n\n<p>Aside from maybe 0 and 1, constants deserve identification. </p>\n\n<pre><code>#define MAX_RANK 7\n#define MAX_COLUMN 7\n\n// if(x > 7 || x < 0 || y > 7 || y < 0)\nif(x > MAX_COLUMN || x < 0 || y > MAX_RANK || y < 0) {\n return 1;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#define RANK_N 8\n#define COLUMN_N 8\nif(x >= COLUMN_N || x < 0 || y >= RANK_N || y < 0) {\n return 1;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T11:56:23.677",
"Id": "234664",
"ParentId": "234619",
"Score": "4"
}
},
{
"body": "<p>Avoid many duplicate calculations.\nThe code will be shorter and easy to read.</p>\n\n<p>i.e. in towerMoves</p>\n\n<pre><code>void towerMoves(){\n for(int dir = -1; dir < 2; dir+=2){\n for(int tx = x+dir; tx>=0 && tx<=7; tx+=dir) {\n if(board[y][tx] != 0) {\n if(blackWhite[y][tx] != color) {\n moves[y][tx] = 3;\n canMove = 0;\n }\n break;\n } else {\n moves[y][tx] = 1;\n canMove = 0;\n }\n }\n for(int ty = y+dir; ty>=0 && ty<=7; ty+=dir) {\n if(board[ty][x] != 0){\n if(blackWhite[ty][x] != color){\n moves[ty][x] = 3;\n canMove = 0;\n }\n break;\n }else{\n moves[ty][x] = 1;\n canMove = 0;\n }\n }\n }\n}\n</code></pre>\n\n<p>or with piece 4</p>\n\n<pre><code>void cleanUp(int y, int x) {\n if(x >= 0 && x <= 7 && y >= 0 && y <= 7){\n moves[y][x] = blackWhite[y][x] == color && board[y][x] != 0 ? 0 : 1;\n canMove = 0;\n }\n}\n\nif(piece == 4){\n for(int i = -1; i < 2; i+=2){\n cleanUp(y+2*i, x+i);\n cleanUp(y+i, x+2*i);\n cleanUp(y+2*i, x-i);\n cleanUp(y-i, x+2*i);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T10:27:50.503",
"Id": "235158",
"ParentId": "234619",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T03:45:09.343",
"Id": "234619",
"Score": "6",
"Tags": [
"beginner",
"c",
"game"
],
"Title": "Chess game in C"
}
|
234619
|
<p>So in my quest to learn coding while having very little formal training has got me here. I am trying to learn the OOP concept and this is my first proper attempt at using OOP.</p>
<p>Can you guys point out what can be improved and what are the better practices? I have tried my best to make the program as robust as possible - the debugging took hours. Is that normal?</p>
<pre><code># Game of Blackjack
import random
# Classes
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f'{self.rank} of {self.suit}'
class Deck:
def __init__(self, type_of_deck='empty'):
self.cards = []
if type_of_deck == 'full':
for suit in suits:
for num in ranks:
self.cards.append(Card(suit, num))
def __str__(self):
temp_string = ''
for card in self.cards:
temp_string += str(card)
temp_string += ', '
return temp_string
def __len__(self):
return len(self.cards)
def draw_card(self, position=0):
if self.cards:
if position == 'top':
position = 0
elif position == 'bottom':
position = -1
elif position == 'random':
position = random.randrange(len(self))
return self.cards.pop(position)
else:
return False
def insert_card(self, card, position=0):
if not isinstance(card, Card):
raise TypeError("Given object is not a Card")
if position == 'top':
position = 0
elif position == 'bottom':
position = -1
elif position == 'random':
position = random.randrange(len(self))
self.cards.insert(position, card)
def view_card(self, position=0):
if self.cards:
if position == 'top':
position = 0
elif position == 'bottom':
position = -1
elif position == 'random':
return random.choice(self.cards)
return str(self.cards[position])
else:
return 'None'
def shuffle(self):
random.shuffle(self.cards)
def clear(self):
self.cards = []
class Hand(Deck):
def __init__(self):
Deck.__init__(self)
self.points = 0
def calculate_points(self):
aces = 0
self.points = 0
for card in self.cards:
if isinstance(card.rank, int):
self.points += card.rank
elif card.rank == 'Ace':
self.points += 1 # aces at minimum has a value of 1
aces += 1
elif isinstance(card.rank, str):
self.points += 10
while self.points <= 11 and aces > 0: # Tallying up aces as that is all that's left
self.points += 10
aces -= 1
def insert_card(self, card, position=0): # Extending the method in order to account for revised points after each
# card is added
Deck.insert_card(self, card, position)
self.calculate_points()
class Player:
def __init__(self, name, starting_cash=0):
self.hand = Hand() # initialise an empty hand object
self.in_game = True
self.account = starting_cash
self.victory_state = False
self.name = name
def __str__(self):
return self.name
def bet(self, amount):
if amount > self.account or amount < 0:
raise ValueError('Balance_Exceeded or invalid value')
else:
self.account -= amount
return amount
def payout(self, amount):
self.account += amount
return True
# Functions
def display_state(deck, dealer, player, type_of_display='partial'):
print('---------------------------------------------------------------------')
print('Deck Dealer Player')
print(f'{len(deck)} cards left {len(dealer.hand)} cards on hand {len(player.hand)} cards on hand')
if type_of_display == 'full':
print(f' points : {dealer.hand.points} points : {player.hand.points}')
else:
print(
f' Top card : {dealer.hand.view_card("bottom"):{15}} points : {player.hand.points}')
print(f'Cards in hand : {player.hand}')
if type_of_display == 'full':
print(f"Cards in dealer's hand : {dealer.hand}")
print(f"Account Balance : {player.account} Pool : {pool} Dealer's Balance : {dealer.account}")
print('--------------------------------------------------------------------')
# Function to payout depending on victor which is read from a boolean state (player.victory_state) in their objects
def victory_result(dealer, player, prize_pool):
if dealer.victory_state and not player.victory_state:
dealer.payout(prize_pool)
print('The house has won, Better luck next time')
elif player.victory_state and not dealer.victory_state:
player.payout(prize_pool)
print('Congratulations on your victory, care for another try on your luck?')
return 0
def ask_for_new_game():
while True:
if input('Another run? Enter y to continue, enter any other key to exit ').upper() == 'Y':
return True
else:
return False
def check_for_bust(player_1, player_2):
if player_1.hand.points > 21:
player_1.in_game = False
player_2.in_game = False
player_2.victory_state = True
print(f'{player_1} has BUST!')
def no_bust_victory_check(player, dealer):
if not player.victory_state and not dealer1.victory_state:
if dealer.hand.points >= player1.hand.points:
dealer.victory_state = True
else:
player.victory_state = True
def make_bet(player, dealer):
game_state1 = True
prize_pool = 0
while True:
if player.account == 0: # End the game when player is out of cash
print('Your account is empty, Game over!')
game_state1 = False
break
if game_state1:
try:
prize_pool = player.bet(int(input('Enter the amount to bet ')))
if dealer1.account < prize_pool: # End the game when dealer is out of cash
print('Dealer cannot bet that amount anymore, Game Over!')
game_state1 = False
break
prize_pool += dealer.bet(prize_pool)
break
except ValueError:
print('Enter a proper value')
return prize_pool, game_state1
def player_action(player, dealer, deck_in_play):
while player.in_game or dealer.in_game:
if player.in_game:
while True: # while loop to force proper input
try:
control_value = input("Enter your choice - (H)it or (S)tand ").upper()
if control_value == 'H':
player.hand.insert_card(deck_in_play.draw_card())
break
elif control_value == 'S':
player.in_game = False
break
else:
print('Invalid value try again!')
except TypeError:
print('Invalid value try again!')
display_state(deck_in_play, dealer, player)
check_for_bust(player, dealer)
if dealer.in_game and dealer.hand.points <= break_point: # Break off point is 16 right?
dealer.hand.insert_card(deck_in_play.draw_card())
display_state(deck_in_play, dealer, player)
else:
dealer.in_game = False
check_for_bust(dealer, player)
if __name__ == "__main__":
# Suits and Cards for creating a full deck
suits = ('Spades', 'Hearts', 'Clubs', 'Diamonds')
ranks = ('Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King')
# Constants
break_point = 16
player_starting_cash = 1000
dealer_starting_cash = 2000
# Initialisation of game variables
pool = 0
playing_deck = Deck('full')
playing_deck.shuffle()
player1 = Player('Player', player_starting_cash)
dealer1 = Player('House', dealer_starting_cash)
game_state = True
# Main loop
while game_state and len(playing_deck) > 10:
player1.in_game = True
player1.victory_state = False
dealer1.in_game = True
dealer1.victory_state = False
player1.hand.clear()
dealer1.hand.clear()
display_state(playing_deck, dealer1, player1)
# Let the player bet an amount and force a proper input
pool, game_state = make_bet(player1, dealer1) # Tuple unpacking for multiple values...
if not game_state: # break out of main game session since either the Player or the House has lost
break
# Initially draw 2 cards each for dealer and player
for i in range(0, 2):
dealer1.hand.insert_card(playing_deck.draw_card())
player1.hand.insert_card(playing_deck.draw_card())
display_state(playing_deck, dealer1, player1)
# Let the player and dealer hit until they stand
player_action(player1, dealer1, playing_deck)
no_bust_victory_check(player1, dealer1)
pool = victory_result(dealer1, player1, pool)
display_state(playing_deck, dealer1, player1, 'full')
game_state = ask_for_new_game()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T17:35:19.873",
"Id": "458905",
"Score": "2",
"body": "\"the debugging took hours. Is that normal?\" Debugging usually takes me as long as writing the program itself. Sometimes I don't even know whether I'm debugging, creating a feature or whether it's actually refactoring. Makes it hard to track. In the end, as long as the code works and it's good code, does it matter what part of the development took the longest?"
}
] |
[
{
"body": "<p>Don't have much time, just some things I noticed.\n<hr></p>\n\n<h1><code>Deck.__str__</code></h1>\n\n<p>This method can utilize the <code>.join</code> built in method. Your current implementation leaves a \",\" at the end of the string. <code>.join</code> is smart enough not to. Take a look:</p>\n\n<pre><code>def __str__(self):\n return ', '.join(str(card) for card in cards).strip()\n</code></pre>\n\n<p>Does the exact same thing yours does, but in one line. <code>.strip()</code> removes the extra whitespace at the end of the string.</p>\n\n<h1><code>ask_for_new_game</code></h1>\n\n<p>This function can also be written in one line. Since you're checking one boolean expression, and returning a value either way, the <code>while True:</code> loop isn't necessary. There is also an easier way to return a boolean. Take a look:</p>\n\n<pre><code>def ask_for_new_game():\n return input('Another run? Enter y to continue, enter any other key to exit ').upper() == 'Y'\n</code></pre>\n\n<p>Since you are evaluating a <em>boolean</em> expression, and returning <em>boolean</em> values, you can simply return the expression. Since it returns a boolean value, that value will be returned.</p>\n\n<h1><code>Deck.__init__</code></h1>\n\n<p>You can simplify this method to one line using list comprehension. Take a look:</p>\n\n<pre><code>def __init__(self, type_of_deck='empty'):\n self.cards = [Card(suit, num) for num in ranks for suit in suits if type_of_deck == 'full']\n</code></pre>\n\n<p>While it may seem like a longer line, it reduces line count, which is <em>almost</em> always a good thing.</p>\n\n<h1><code>Player.bet</code> bug</h1>\n\n<p>There is a bug in this method. It allows the user to bet 0 and start the game. Take a look at the first line in the method:</p>\n\n<pre><code>def bet(self, amount):\n if amount > self.account or amount < 0:\n raise ValueError('Balance_Exceeded or invalid value')\n else:\n self.account -= amount\n return amount\n</code></pre>\n\n<p>A simple fix is to change <code>amount < 0</code> to <code>amount <= 0</code>.</p>\n\n<h1>Type Hints</h1>\n\n<p>You should use type hints to express what type of parameter are accepted and what values are returned by your methods/functions. Here's an example:</p>\n\n<pre><code>def bet(self, amount: int) -> int:\n</code></pre>\n\n<p>This says that the parameters <code>amount</code> should be an integer when passed, and that the method returns an integer. While this may be a trivial example, it helps as you write bigger and more expandable programs. It also helps people reading your code understand what types the method accepts.</p>\n\n<h1>Docstrings</h1>\n\n<p>You should include docstrings to your methods/functions to provide description about what each of them do. Take a look at <a href=\"http://www.sphinx-doc.org/en/master/\" rel=\"noreferrer\">sphinx</a>. It's a great tool that can \"create intelligent and beautiful documentation\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T16:20:32.147",
"Id": "458897",
"Score": "0",
"body": "I am very thankful for your review. Using .join() method skipped me even though I have used it in the past. Same with list comprehension - much obliged for reminding me. The ask_ for_new_game function originally only accepted Y and N, i skipped that for some reason and ended with the old structure, good point about shortening it. I will learn to use hints, pycharm kept reminding me about that a lot throughout when writing the code. About the bug, betting zero means the pool will also be zero, hence no benefit to the player - so should it be considered a bug?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T11:55:12.387",
"Id": "234630",
"ParentId": "234622",
"Score": "6"
}
},
{
"body": "<p>I question if a hand <strong>is a</strong> deck of cards. Certain functionality that you have, like shuffling, viewing, and inserting to specific positions, doesn't seem to make much sense in the context of a hand. A hand may be a collections of cards, similar to a deck, but that doesn't mean one is the other.</p>\n\n<p>Also, I don't think having <code>points</code> as an attribute is ideal. That's one thing that can become mismatched later if you refactor. It's a redundant field given a hand of cards can be easily checked when needed for a value. If it was an expensive calculation, then ya, caching the results may make sense. In this case though, I can't see performance being a concern.</p>\n\n<p>I'd probably get rid of the <code>Hand</code> class altogether, and just make it a list of cards:</p>\n\n<pre><code>class Player:\n def __init__(self, name, starting_cash=0):\n self.hand = [] # initialize an empty list\n self.in_game = True\n self.account = starting_cash\n self.victory_state = False\n self.name = name\n</code></pre>\n\n<p>Lists already have <code>insert</code> (and <code>append</code>) and <code>clear</code> methods, and can be trivially iterated to do whatever. </p>\n\n<p>I'll admit, I'm biased from writing Clojure. I avoid writing collection-like-wrapper classes unless I found that there's specific, delicate states that I need. Usually, a basic collection like a dictionary or list already does mostly what you want, and wrapping it just complicates otherwise simple, easy to read operations.</p>\n\n<p>To deal with <code>points</code>, I'd probably give the player <code>calculate_points</code> method (or have a standalone function) that calculates points as needed. Again, I don't think there's a ton of gain by caching that, and caching can lead to consistency problems. For example, your <code>clear</code> method doesn't reset <code>points</code>. If the user clears the deck, then tries to use <code>points</code> before calling <code>calculate_points</code>, they'll get an invalid result.</p>\n\n<hr>\n\n<p>I wouldn't have <code>Deck</code> accept a <code>type_of_deck</code> string. That leads to a couple problems:</p>\n\n<ul>\n<li><p>If the user typos the string, it will silently fail. </p></li>\n<li><p>You'll need to remember to change the string in both the constructor and use-sites if you ever refactor. IDE refactoring won't be able to help you with that.</p></li>\n</ul>\n\n<p>Instead, I'd make the <code>__init__</code> just a basic setter, then have a <code>populate</code> method:</p>\n\n<pre><code>class Deck:\n def __init__(self):\n self.cards = []\n\n def populate(self):\n self.clear() # To avoid double-populating\n\n for suit in suits:\n for num in ranks:\n self.cards.append(Card(suit, num))\n</code></pre>\n\n<p>Then, the user can call <code>populate</code> instead of passing a string. You could also, either instead of populate, or along with it, have a \"pseudo-constructor\" class method:</p>\n\n<pre><code>@classmethod\ndef new_populated(cls):\n new_deck = cls() # Same as Deck()\n new_deck.populate()\n\n return new_deck\n\n. . .\n\nplaying_deck = Deck.new_populated() # instead of Deck('full')\n</code></pre>\n\n<p>I think it reads much better and will allow for less mistakes.</p>\n\n<hr>\n\n<p><code>insert_card</code> and <code>view_card</code> are more complicated than they need to be. You're having each doing multiple jobs based on a passed string. Trying to anticipate future needs and creating new features ahead of time can be helpful, but also remember: in many cases, <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">you aren't going to need those features</a>.</p>\n\n<p>Look at your uses of both:</p>\n\n<ul>\n<li><p><code>insert_card</code> never uses the second parameter. Can you ever, within the context of a blackjack deck of cards, see ever needing to add a card to multiple positions (or really, would you <em>ever</em> add a card to a blackjack deck after the deck is formed?)</p></li>\n<li><p><code>view_card</code> is only used once, and is used to view the \"bottom\" card of a hand. I think normal indexing of a list would suffice here.</p></li>\n</ul>\n\n<p>Unless you can think of a good reason to keep them as is, I'd get rid of <code>view_card</code> and reduce <code>insert_card</code> down to a minimum simple line of code to do an insert.</p>\n\n<p>Just like before, messing around with strings to dispatch behavior is messy and can lead to errors.</p>\n\n<hr>\n\n<hr>\n\n<p>We're getting ready to do Christmas stuff now, so I need to go.</p>\n\n<p>Good luck and Merry Christmas.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T10:19:45.827",
"Id": "458960",
"Score": "0",
"body": "Much thanks for the good points, a hand doesn't need the full functionality of a deck, though i figured much of the behavior was same why not use it - it's more so because I wanted to try the inheritance features in python than a proper use case. Thanks for introducing me to pseudo constructors, they sound very useful. Good catch on hand.points giving incorrect value even after the hand is clear - how would you have implemented it in an air tight manner - call it after any change to hand? Agree on the needless features. How would you dispatch behavior without strings as in display_state func?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T15:47:26.020",
"Id": "458991",
"Score": "1",
"body": "@AravindPallippara For `points `, like I said, I would just compute them as needed instead of storing them. That'll be cheap math to do. And for dispatching, for cases where you do want to dispatch on something like a string, use an Enum (`from enum import Enum`). Enums give more safety since they can't easily be typo'd, and are easier to refactor. The doc page for them explains how to use them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T17:58:47.443",
"Id": "234639",
"ParentId": "234622",
"Score": "7"
}
},
{
"body": "<p>Specific suggestions:</p>\n\n<ol>\n<li>The <code>try</code>/<code>catch</code> blocks should be as small as possible. In the first case that means only <code>bet = int(input('Enter the amount to bet '))</code> should be guarded, and in the second case only <code>control_value = input(\"Enter your choice - (H)it or (S)tand \").upper()</code>.</li>\n<li>You could still take this much further in terms of OO. <code>Game</code> and <code>Dealer</code> classes, for example, would be helpful to encapsulate several of the methods.</li>\n<li>An abstract deck of cards is a sequence of cards, so it should probably inherit from <code>list</code>. One immediate benefit is that the custom <code>__len__</code> simply goes away.</li>\n<li><code>view_card</code> should return <code>None</code> rather than <code>'None'</code> if there are no cards. Or you could even throw something like a <code>NoCardsInDeckError</code> since you should never reach that point.</li>\n<li>The suits and ranks are the same for all decks (at least if you're playing Blackjack) so they should probably conceptually be <code>enum</code>s.</li>\n<li><p>It is generally considered good practice to implement your own exception classes rather than overloading built-in ones. And giving one thing <em>two</em> meanings is generally a bad idea. So</p>\n\n<pre><code>if amount > self.account or amount < 0:\n raise ValueError('Balance_Exceeded or invalid value')\n</code></pre>\n\n<p>should probably be something like</p>\n\n<pre><code>if amount > self.account:\n raise BalanceExceededError()\nelif amount <= 0:\n raise TooLowBetError()\n</code></pre></li>\n<li>I can't quite tell, but it looks like the support for more than one player is not yet complete. <code>check_for_bust</code> only allows for two players, for example.</li>\n<li>Writing this in TDD fashion would be a handy way to ensure a minimal and correct implementation. You would probably need in the order of 30+ tests to ensure basic game compliance and many more to get to a bulletproof implementation.</li>\n<li>More generally, asking yourself questions like \"Is it still a deck if there are no cards in it?\" or \"Who or what is responsible for this?\" can be useful ways to work out the model.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T10:25:35.927",
"Id": "458961",
"Score": "0",
"body": "I understand that a 'game' class would have helped, but why would a dealer class make sense when much of the functionality is extremely similar to a player? Also is it better to go for full OOP or mix and match paradigms to make code more readable? Agree with inheriting from list, that makes a lot of sense, just would have had to extend the insert method with isinstance check. I was lazy about implementing exception classes, I will keep that in mind for next time. And yeah there isnt support for more than 2 players, I should expand it. I haven't got to using unit testing proper, I should soon"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T04:35:30.690",
"Id": "459054",
"Score": "1",
"body": "Good point about the `Dealer` class. One thing which comes to mind is that the dealer is probably better suited than the game (and certainly the players!) to handle the pot and winnings. As usual it depends a lot on the structure of the rest of the game. As for unit testing, I would highly recommend learning TDD, not just unit testing. I used unit testing for some years before being taught actual TDD, and it makes a huge difference to the testability and conciseness of your result."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T01:40:03.483",
"Id": "234648",
"ParentId": "234622",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234639",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T06:54:09.157",
"Id": "234622",
"Score": "13",
"Tags": [
"python",
"python-3.x",
"object-oriented"
],
"Title": "Basic Blackjack program in Python"
}
|
234622
|
<p><a href="https://www.hackerrank.com/challenges/30-binary-numbers" rel="noreferrer">hackerrank.com Task</a>:</p>
<blockquote>
<p>Given a base-10 integer, <em>n</em>, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in <em>n</em>'s binary representation.</p>
</blockquote>
<p>This question has already been answered but it was in Ruby and I couldn't quite understand the concept, I am just starting to code. What can you suggest me to improve on this piece of code? I think its quite long considering the work it does or is this the efficient solution?</p>
<pre><code>count = 0
max_value = 1
if __name__ == '__main__':
n = int(input())
binary_num = bin(n).split("b")
binary_num = binary_num[1]
print(binary_num)
for index, i in enumerate(binary_num):
if i == "1":
count += 1
next_item = index + 1
while next_item < len(binary_num):
if binary_num[next_item] == "1":
count += 1
counter = count
temp = counter
next_item += 1
if temp > max_value:
max_value = temp
else:
counter = count
count = 0
break
if next_item == (len(binary_num)):
break
print("count is =",max_value)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T07:26:04.427",
"Id": "459058",
"Score": "5",
"body": "Your instinct is quite right. There is no *need* to convert numbers to strings in order to work with binary. The trap that you and most of other answers (included the accepted one) fall in, is not knowing how to work with binary numbers. See Anatolii's answer for what the normal, more efficient (albeit very commonly unknown) approach is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T02:30:36.907",
"Id": "459104",
"Score": "2",
"body": "This task is a good exercise, but since people re bringing up efficiency, I think it's worth mentioning that newer processors have this [built in to the hardware](https://en.wikipedia.org/wiki/SSE4#POPCNT_and_LZCNT)."
}
] |
[
{
"body": "<p>I am a newbie to coding myself, but your logic is kind of hard to follow - probably my problem. You should use slicing operation on the string to get the '0b' removed from <code>bin()</code> function result as i feel like a cleaner method.</p>\n\n<p>Here's an alternate logic I came up with</p>\n\n<pre><code>count = 0\nfinal_count = 0\nconcecutive_check = False\n\nif __name__ == '__main__':\n n = int(input())\n bin_representation = bin(n)[2:] #slice operation to remove 'ob'\n print(bin_representation)\n\n for num in bin_representation:\n if concecutive_check and num == '1':\n count +=1\n elif concecutive_check and num == '0':\n concecutive_check = False\n if count > final_count:\n final_count = count\n count = 0\n elif num == '1':\n concecutive_check = True\n count = 1\n\n if count > final_count: # final check just in case the binary string ends in 1 and doesn't trigger the above if statements\n final_count = count\n print(f'{final_count} max sequence count')\n</code></pre>\n\n<p>As general coding practices, comments where appropriate would be good (as in if something is understandable from the name of the function or object it doesn't need a comment), or if there is a nonsensical aspect like my second <code>count > final count</code> check, explaining the reason for that.</p>\n\n<p>Another thing i noticed is you using the <code>enumerate</code> operation without really using the index for anything beyond as a counter for loop... why? wouldn't the generic for loop over iterable take care of that?</p>\n\n<p>I think the logic route you used is a bit round about way of doing it, a single boolean state variable and two int variable is all you need to keep track of the longest count over the string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T08:40:49.507",
"Id": "234625",
"ParentId": "234623",
"Score": "5"
}
},
{
"body": "<p>The whole idea is achievable with a few lines of code and based on designating segments of <strong><code>1</code></strong> 's items (repeated consecutive sequence) using <strong><code>0</code></strong> segments as separators.<br>\nSee the concise solution below:</p>\n\n<pre><code>def find_max_ones(num):\n if not num:\n return 0\n bin_num = bin(num)[2:]\n print(bin_num)\n return len(max(bin_num.replace('0', ' ').split(), key=len))\n\n\nif __name__ == '__main__':\n num = int(input('Enter integer number:'))\n max_ones = find_max_ones(num)\n print(\"max 1's count is\", max_ones)\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>Enter integer number:1000\n1111101000\nmax 1's count is 5\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T16:20:20.963",
"Id": "458896",
"Score": "4",
"body": "I know this is not meant to be codegolfed, but your return line can be written shorter as `return len(max(bin_num.split('0')))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T16:45:42.917",
"Id": "458900",
"Score": "3",
"body": "@Zchpyvr, I would not consider that as better approach. Consider this case: `bin(18888889)[2:].split('0')` that generates `['1', '', '1', '', '', '', '', '', '', '111', '', '', '1', '111', '', '1']` , a list of **16** items for further traversal. While the former approach returns a list of 6 items."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T16:57:24.917",
"Id": "458901",
"Score": "0",
"body": "Sure, although all the extra items are empty strings. Assuming the empty strings create extra overhead, what would you think of using `re`: `max(re.split(r'0+', bin(18888889)[2:]))`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T17:00:07.120",
"Id": "458902",
"Score": "0",
"body": "Or at least can we agree that `key=len` is not necessary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T22:07:51.583",
"Id": "458930",
"Score": "6",
"body": "using `re`: `max(re.split(r'0+', bin(18888889)[2:]))`. >> it's harder to read. If no performance gain, code should aim for maximal readability. Code is a _human_ machine interface after all"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T23:36:00.133",
"Id": "458934",
"Score": "0",
"body": "@Poutrathor My profiler gives me a 100x speed improvement. But I do agree with readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T23:42:24.230",
"Id": "458935",
"Score": "0",
"body": "Compared to @roman 's answer? That's a nice improvement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:37:42.530",
"Id": "458949",
"Score": "1",
"body": "@Zchpyvr, Why telling people \"fairy tails\" about **100**x speed improvement? Your approach is slower: `In [56]: %timeit len(max(bin(18888889000)[2:].replace('0', ' ').split(), key=len)) \n1.74 µs ± 160 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)` - \n`In [57]: %timeit len(max(re.split(r'0+', bin(18888889000)[2:]))) \n4.26 µs ± 196 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:41:27.100",
"Id": "458950",
"Score": "0",
"body": "@Poutrathor, I would not believe in every comment saying 100x or 1000x speedups - it's better to check it out for yourself to find the truth. See the above comment with timings. Critical thinking is an advantage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T10:11:46.220",
"Id": "458958",
"Score": "3",
"body": "@RomanPerekhrest Oh :) I did not believe him (nor do I believe you, yet). I merely wrote a polite answer awaiting the time I could test it myself and asking \"compared to\" [which implementation] such an improvement was measured. For one, you tested only one number 188888889000."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:01:36.973",
"Id": "459003",
"Score": "1",
"body": "My bad, I must've misread 'ns' as 'μs'. I apologize for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:06:20.530",
"Id": "459004",
"Score": "0",
"body": "My comments about the other points remain valid, however. There are a lot of simple ways to improve this answer that are better in terms of readability and performance. Even using `.split('0')` is more performant and easier to read than your answer. But if you want to ignore me based on an error on my part about speed, then I understand. I just wanted to suggest some edits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:07:05.717",
"Id": "459005",
"Score": "1",
"body": "@Zchpyvr, Admitting faults is a strong human quality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T20:57:14.247",
"Id": "459016",
"Score": "0",
"body": "@Zchpyvr: I'd recommend posting your own answer with a focus on performance, where you'll have room to show a fast version and prove your points about what's faster for what kinds of input numbers (fits in 32 bits; huge; a few long runs of ones, alternating zeros and ones). I suspect that expanding a number into a list of base-2 digits at all is relatively slow, and I seem to recall a solution for this involving a bitwise trick. But maybe only in C where you don't have Python interpreter overhead, and maybe involving popcount or bitscan (`__builtin_ctz()` count trailing zeros)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:21:39.440",
"Id": "459020",
"Score": "1",
"body": "@Zchpyvr The author wasn't asking about the highest performance solution anyways. This one is good enough as it's easy to understand, it has a linear time complexity (in regard to binary digits) and the author also accepted it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T09:14:22.540",
"Id": "459066",
"Score": "0",
"body": "@Zchpyvr: Ah right, Anatolii's answer was what I was remembering: iterate `x &= x << 1;` until `x` becomes zero, counting the iterations. It's not O(1), just O(result), but doesn't involve any bit-scan."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T21:14:18.733",
"Id": "459092",
"Score": "2",
"body": "Using strings to manipulate numbers strikes me as incredibly inelegant."
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T09:01:24.273",
"Id": "234626",
"ParentId": "234623",
"Score": "13"
}
},
{
"body": "<blockquote>\n <p>I think its quite long considering the work it does</p>\n</blockquote>\n\n<p>Your instinct is right - it's quite long. It can be implemented with much fewer lines of code, especially in <strong>Python</strong>. A solution from @RomanPerekhrest highlights it quite well.</p>\n\n<blockquote>\n <p>is this the efficient solution?</p>\n</blockquote>\n\n<p>From the time complexity prospective, it's not an efficient solution. It's O(n<sup>2</sup>), where <code>n</code> - number of binary digits in your number. Why? Because in your outer loop, you process each digit one by one regardless of the results in your inner loop. So, if your inner loop finds a segment of ones you don't move <code>ì</code> and <code>index</code> to a bit position following this segment. Instead, you pick a second bit in this segment and find the same segment without the first bit again.</p>\n\n<p>For instance, let's say we have a number which binary representation is <code>111110</code>. Then your algorithm will find the following segments of ones:</p>\n\n<pre><code>11111 | 4 inner loop steps\n 1111 | 3 inner loop steps\n 111 | 2 inner loop steps\n 11 | 1 inner loop steps\n 1 | 0 inner loop steps\n</code></pre>\n\n<p>An optimal solution has a O(n) time complexity. I'll leave it up to you to update your code based on the explanation above. </p>\n\n<p><strong>Bonus</strong></p>\n\n<p>I noticed that each answer uses <code>bin()</code> to calculate the longest segment of ones. However, it's not really needed since this approach has an additional <code>O(n)</code> space complexity (as you recall it from the previous paragraph, <code>n</code> - number of binary digits). </p>\n\n<p>We could just use bitwise operators to achieve the same result. For example, let's say there's a number <code>1100011101</code>. It has <code>3</code> separate segments of ones: Now, let's play a bit - we will calculate a left shifted version of <code>x</code> and then perform bitwise <code>AND</code> on it. Then, for the shifted version we will calculate its left shifted number and so on.</p>\n\n<pre><code>1 1 0 0 0 1 1 1 0 1 0 (x)\n &\n1 0 0 0 1 1 1 0 1 0 0 (x << 1)\n---------------------\n1 0 0 0 0 1 1 0 0 0 0 y = ((x) & (x << 1))\n\n\n1 0 0 0 0 1 1 0 0 0 0 (y)\n & \n0 0 0 0 1 1 0 0 0 0 0 (y << 1)\n---------------------\n0 0 0 0 0 1 0 0 0 0 0 z = ((y) & (y << 1))\n\n\n0 0 0 0 0 1 0 0 0 0 0 (z)\n & \n0 0 0 0 1 0 0 0 0 0 0 (z << 1)\n---------------------\n0 0 0 0 0 0 0 0 0 0 0 ((z) & (z << 1))\n</code></pre>\n\n<p>So, as you can see it took us <code>3</code> steps to reach <code>0</code>. But <code>3</code> is also the length of the longest segment of ones. And it's not a coincidence because bitwise <code>AND</code> of a number and its shifted version shortens each segment of ones by <code>1</code>. Hence, the longest segment will lose all its ones after < length of the longest segment of ones > steps.</p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>def find_max_ones(number):\n maxLength = 0\n\n while number > 0:\n left_shifted_number = number << 1\n number = number & left_shifted_number\n maxLength += 1\n\n return maxLength\n\n\nif __name__ == '__main__':\n number = int(input('Enter integer number:'))\n max_ones = find_max_ones(number)\n\n print(\"Length of the longest segment is \", str(max_ones))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T11:08:01.960",
"Id": "234628",
"ParentId": "234623",
"Score": "21"
}
},
{
"body": "<p>This is a good opportunity to learn two things, separation of concerns and the standard library module <code>itertools</code>. </p>\n\n<p>You have three separate issues, each of which you can put into their own function:</p>\n\n<ol>\n<li>Take input from the user</li>\n<li>Turn it into a sequence of <code>0</code> and <code>1</code>.</li>\n<li>Find the longest run of <code>1</code>.</li>\n</ol>\n\n<p>For the user input it can be as simple as your one line, or slightly more sophisticated as this function:</p>\n\n<pre><code>def ask_user(message=\"\", type_=str):\n while True:\n try:\n return type_(input(message))\n except ValueError:\n print(\"wrong type, try again\")\n</code></pre>\n\n<p>Later you might want to add things like validator functions, allowed ranges, etc, but this should suffice for now.</p>\n\n<p>Turning the number into a binary sequence is easy:</p>\n\n<pre><code>def to_binary(n):\n return bin(n)[2:]\n</code></pre>\n\n<p>Or even like this, as mentioned in the comments by Eric:</p>\n\n<pre><code>def to_binary(x):\n return format(x, \"b\")\n</code></pre>\n\n<p>And for the last step you can use <code>itertools.groupby</code>:</p>\n\n<pre><code>from itertools import groupby\n\ndef longest_run_of(it, value):\n return max(len(list(group))\n for c, group in groupby(it)\n if c == value)\n</code></pre>\n\n<p>Putting it all together, using some <code>f-string</code> for slightly easier string formatting:</p>\n\n<pre><code>if __name__ == \"__main__\":\n n = ask_user(\"Enter a number: \", int)\n n_bin = to_binary(n)\n longest_run = longest_run_of(n_bin, \"1\")\n print(f\"count is = {longest_run}\")\n</code></pre>\n\n<p>Once you are this far it becomes a lot easier to try and test different implementations, as you can change (and test) each part individually. At this point it might make sense to start profiling to see which implementation is the fastest, depending on your needs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T11:37:32.347",
"Id": "458968",
"Score": "2",
"body": "`to_binary = '{:b}'.format` is simpler than using `bin` to add `0b` then removing it again. `to_binary = lambda x: format(x, 'b')` also works, and avoids some string parsing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T17:52:39.313",
"Id": "458999",
"Score": "2",
"body": "@Eric What about `def to_binary(x): return f'{x:b}'`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:04:28.903",
"Id": "459017",
"Score": "0",
"body": "@SolomonUcko Directly invoking `format` might be better, because it does not need to parse the f-string. Some profiling would be needed there as well, though. In addition, it means requiring Python 3.6, which may or may not be a concern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:09:37.080",
"Id": "459018",
"Score": "0",
"body": "@Graipher Aren't f-strings are parsed at compile time? I'll investigate more when I get a chance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:40:11.230",
"Id": "459022",
"Score": "3",
"body": "@Graipher At least for me, f-strings result in direct usage of the `FORMAT_VALUE` bytecode instruction, instead of loading and calling `format`, which uses `LOAD_GLOBAL` then `CALL_FUNCTION`, which is almost certainly *significantly* slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:51:29.670",
"Id": "459023",
"Score": "0",
"body": "@SolomonUcko Fair enough, I was not at a PC, so could not directly check myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T22:22:53.333",
"Id": "459026",
"Score": "0",
"body": "@Graipher Makes sense. (Frankly, you don't technically *need* a computer if you can use something like Termux, a terminal emulator, or some sort of Python app instead, but it is significantly easier on an actual computer with an actual keyboard and stuff.)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T15:44:58.950",
"Id": "234634",
"ParentId": "234623",
"Score": "15"
}
},
{
"body": "<p>A few improvements following principles of <em>Cleancode</em> and <em>Divide & Conquer</em>:</p>\n\n<ol>\n<li>Split into small tasks, each one a function.</li>\n<li>Use meaningful names.</li>\n<li>Leverage the language's power.</li>\n</ol>\n\n<h3>Split into small tasks, each one a function</h3>\n\n<p>The challenge's description <em>explicitly</em> names 2 tasks, thus implemented in <strong>functions</strong>:</p>\n\n<ol>\n<li><code>convert_to_binary(number)</code></li>\n<li><code>max_consecutive_1s_of_binary(binary)</code></li>\n</ol>\n\n<p>Above functions already have <strong>meaningful names</strong> (see 2), expressing <em>what</em> they do. </p>\n\n<p>Besides you have other tasks, given <em>implicitly</em>:</p>\n\n<ol>\n<li>Read a (decimal) number from STDIN</li>\n<li>Determine length of a sequence (of max consecutive 1s)</li>\n<li>Print number to STDOUT (length of max consecutive 1s)</li>\n</ol>\n\n<p>These side-tasks can be implemented using existing functions (in Python).</p>\n\n<h3>Use meaningful names</h3>\n\n<p>From above functional design you can derive <strong>data-structures and variables</strong>. Name them to express <em>what</em> (in context of your program) they contain:</p>\n\n<ol>\n<li><code>number_input</code></li>\n<li><code>binary_representation</code></li>\n<li><code>max_consecutive_1s</code></li>\n<li><code>length_of_max_consecutive_1s</code></li>\n</ol>\n\n<h3>Leverage the language's power</h3>\n\n<p>Use already built-in functions where suitable:</p>\n\n<ol>\n<li>Use <a href=\"https://stackoverflow.com/questions/1395356/how-can-i-make-bin30-return-00011110-instead-of-0b11110\"><code>bin</code> and <strong>slicing</strong></a> for stripping of the <em>binary marker</em>; or use <a href=\"https://stackoverflow.com/questions/699866/python-int-to-binary-string\"><code>format(number, 'b')</code></a> directly</li>\n<li><a href=\"https://stackoverflow.com/questions/13209288/python-split-string-based-on-regex\"><strong>string-splitting</strong> by regex</a> for split the binary representation into <em>consecutive 1s</em> using <code>0</code> as split-marker (very smart <a href=\"https://codereview.stackexchange.com/a/234626\">solution by Roman</a>)</li>\n<li><strong>max</strong> for finding the maximum of a list based on some <em>key criterion</em> (here the length)</li>\n</ol>\n\n<h3>See also</h3>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/37605328/calculating-consecutive-1s-in-a-binary-number\">https://stackoverflow.com/questions/37605328/calculating-consecutive-1s-in-a-binary-number</a></li>\n<li><a href=\"https://www.geeksforgeeks.org/maximum-consecutive-ones-or-zeros-in-a-binary-array/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/maximum-consecutive-ones-or-zeros-in-a-binary-array/</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T16:04:04.380",
"Id": "234636",
"ParentId": "234623",
"Score": "4"
}
},
{
"body": "<p>I don't know about the other programming languages but it's quite easy to implement this particular program using inbuilt functions.\nSo here is my code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import groupby \ndef output(n): \n binary_num = bin(n).replace(\"0b\",\"\") \n print(max(len(list(group)) for i,group in groupby(binary_num) if i== '1')) \n\n\nif __name__ == '__main__': \n n = int(input()) \n output(n) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:53:54.273",
"Id": "477335",
"Score": "1",
"body": "Usually alternative implementations are not considered valid answers if they don't contain a review. After all, this is Code *Review*, not Code *Alternatives*. However, since you specifically move toward in-built functions and your code is much shorter, the review is implied. But please keep that in mind next time. Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:56:29.050",
"Id": "477336",
"Score": "1",
"body": "Do note that if I ever find constructs like yours in production code, I'd delete it outright. That last line of your `output` function is abysmal. There is way too much happening on a single line, hurting readability and maintainability. If you go the route of oneliners, perhaps putting it in some kind of generator function would be more appropriate."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T05:34:59.410",
"Id": "243203",
"ParentId": "234623",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234626",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T07:52:55.300",
"Id": "234623",
"Score": "17",
"Tags": [
"python",
"strings"
],
"Title": "Counting the number of consecutive 1's in binary"
}
|
234623
|
<p>Just starting to get the idea of MVC with tkinter. I wrote this simple program and I'm looking for feedback. There are no errors, but I don't know if I set it up right or not. </p>
<pre><code>import tkinter as tk
class Model():
def __init__(self):
self.list = ["email", "sms", 'voice']
class View(tk.Frame):
def __init__(self, parent, controller):
self.controller = controller
tk.Frame.__init__(self, parent, bg="yellow", bd=2,
relief=tk.RIDGE)
self.parent = parent
self.pack()
self.labelVariable=tk.StringVar()
self.output=tk.Label(self, textvariable=self.labelVariable,
bg="orange", fg="white")
self.output.pack()
self.hello = tk.Button(self, text="Show", command=
self.controller.hello_Button_Pressed, bd=2,
relief=tk.RIDGE)
self.hello.pack(side="left")
class Controller():
def __init__(self):
self.root = tk.Tk()
self.model = Model()
self.view = View(self.root, self)
self.root.title("MVC example")
self.root.geometry("250x350")
self.root.config(background="LightBlue4")
self.root.mainloop()
def hello_Button_Pressed(self):
self.view.labelVariable.set(self.model.list)
if __name__ == '__main__':
c = Controller()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:57:10.170",
"Id": "458951",
"Score": "0",
"body": "Welcome to Code Review. Can you tell us more about what the code is supposed to do? Does the code have a purpose? I understand you want to learn about MVC, that's your goal. What's the goal of the *code*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T09:19:29.297",
"Id": "458956",
"Score": "0",
"body": "Hi @Mast, thanks for responding. This code is just to print the list onto the label. Nothing else. I could do this code without MVC, but to elevate my learning, i wanted to organize it with MVC. If this is correct, without much feedback, I will begin to rewrite most of my other programs into MVC, so any thoughts are welcomed. thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T01:09:38.277",
"Id": "463952",
"Score": "0",
"body": "Please [edit] the question to add the purpose of the code there. In the comment it is not visible enough."
}
] |
[
{
"body": "<p>The code looks like it is set up fine for MVC. I'm not an expert but I have enogh experience to tell that it's fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T20:04:58.377",
"Id": "460174",
"Score": "0",
"body": "thanks @Cruise Lickerman. it took me a while to understand the set up of MVC, and now I can start use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-06T21:39:15.013",
"Id": "460185",
"Score": "0",
"body": "Yeah took me a while also"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T23:54:27.453",
"Id": "235138",
"ParentId": "234635",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T15:56:32.527",
"Id": "234635",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"mvc",
"tkinter"
],
"Title": "feedback needed for my first python tkinter simple MVC, list element to print to label"
}
|
234635
|
<h1>Background</h1>
<p>This is solution to <a href="https://projecteuler.net/problem=11" rel="nofollow noreferrer">Problem 11</a> on Project Euler that is concerned with finding <em>largest product of four adjacent numbers</em> in the provided grid.</p>
<p>Other than solving the problem I was also interested in creating a search function that would have a more generic character and could search across any number of adjacent numbers.</p>
<h2>Provided Grid</h2>
<p><em>Read as <code>11grid.txt</code> in the provided code.</em></p>
<pre><code>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
</code></pre>
<h1>Solution</h1>
<h2>Notes</h2>
<p>The solution:</p>
<ol>
<li>Gets addresses of all cells in the matrix</li>
<li>From each address creates a list of neighbours in each direction (North, South, ...)</li>
<li>Product is calculated on each of the sets</li>
<li>Max product is returned</li>
</ol>
<h2>Code</h2>
<pre><code># Notes -------------------------------------------------------------------
# Problem 11
# Data --------------------------------------------------------------------
# Read provided matrix
M <-
matrix(
data = scan("./problems/11/11grid.txt"),
nrow = 20,
ncol = 20
)
# Support -----------------------------------------------------------------
# Pad matrix for the desired number of neighbhours
pad_matrix <- function(M, n = 4) {
# Create a list of NAs to pad
l <- lapply(X = 1:n, function(x) {
NA
})
# Pad columns
lc <- l
lc[[1]] <- M
Mcols <- do.call(what = cbind, args = lc)
Mcols <- do.call(what = cbind, args = {
# Pad other side
lc[[1]] <- Mcols
rev(lc)
})
# Pad rows
lr <- l
lr[[1]] <- Mcols
Mcols_rows <- do.call(what = rbind, args = lr)
Mcols_rows <- do.call(what = rbind, args = {
# Pad other side
lr[[1]] <- Mcols
rev(lr)
})
Mcols_rows
}
# Search ------------------------------------------------------------------
search_product <- function(M = M, n = 4) {
addresses <- expand.grid(x = sequence(nrow(M)),
y = sequence(ncol(M)))
n_search <- n - 1
# Create padded matrx
M_pad <- pad_matrix(M = M, n = n)
neighbhours_res <- apply(
X = addresses,
MARGIN = 1,
FUN = function(M_addr) {
tryCatch(
expr = list(
North = M_pad[M_addr["x"]:(M_addr["x"] - n_search), M_addr["y"]],
North_East = c(M_pad[M_addr["x"], M_addr["y"]], sapply(
X = 1:n_search,
FUN = function(i) {
M_pad[M_addr["x"] - i,
M_addr["y"] + i]
}
)),
East = M_pad[M_addr["x"], M_addr["y"]:(M_addr["y"] + n_search)],
South_East = c(M_pad[M_addr["x"], M_addr["y"]], sapply(
X = 1:n_search,
FUN = function(i) {
M_pad[M_addr["x"] + i,
M_addr["y"] + i]
}
)),
South = M_pad[M_addr["x"]:(M_addr["x"] + n_search), M_addr["y"]],
South_West = c(M_pad[M_addr["x"], M_addr["y"]], sapply(
X = 1:n_search,
FUN = function(i) {
M_pad[M_addr["x"] + i,
M_addr["y"] - i]
}
)),
West = M_pad[M_addr["x"], M_addr["y"]:(M_addr["y"] - n_search)],
North_West = c(M_pad[M_addr["x"], M_addr["y"]], sapply(
X = 1:n_search,
FUN = function(i) {
M_pad[M_addr["x"] - i,
M_addr["y"] - i]
}
))
),
error = function(e) {
NA
}
)
}
)
products <-
rapply(object = neighbhours_res,
f = prod,
classes = "numeric")
# Keep max only
max(products, na.rm = TRUE)
}
res <- search_product(M = M, n = 4)
res
</code></pre>
|
[] |
[
{
"body": "<p>When working with matrices in R, you can often do an operation with a single command if you are clever about how that is structured. Take padding a matrix with <code>npad</code> missing values as an example. Your current code does this by first padding the columns and then padding the rows. However, you could define a correct-sized matrix with all missing values to start, and then store the original matrix at the correct location within the new matrix:</p>\n\n<pre><code>pad_matrix2 <- function(M, npad) {\n padded <- matrix(NA, nrow(M)+2*npad, ncol(M)+2*npad)\n padded[seq(npad+1, nrow(M)+npad),seq(npad+1, ncol(M)+npad)] <- M\n padded\n}\n</code></pre>\n\n<p>This is much more compact code and will also be more efficient.</p>\n\n<p>In terms of the <code>search_product</code> function, you have a lot of repeated code that does the same thing for a particular direction. You could avoid that by looping through a set of directions that you want to search:</p>\n\n<pre><code>search_product2 <- function(M, n=4) {\n npad <- n-1\n M_pad <- pad_matrix2(M, npad)\n directions <- rbind(c(1, 0), c(0, 1), c(1, 1), c(1, -1))\n all.pos <- expand.grid(r=seq(npad+1, nrow(M)+npad),\n c=seq(npad+1, ncol(M)+npad))\n max(apply(directions, 1, function(direction) {\n max(Reduce(\"*\", lapply(seq(0, n-1), function(dist) {\n M_pad[cbind(all.pos$r+dist*direction[1],\n all.pos$c+dist*direction[2])]\n })), na.rm=TRUE)\n }))\n}\nsearch_product2(M, 4) == search_product(M, 4)\n# [1] TRUE\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:28:16.750",
"Id": "237978",
"ParentId": "234643",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237978",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-25T19:17:23.740",
"Id": "234643",
"Score": "2",
"Tags": [
"programming-challenge",
"matrix",
"r"
],
"Title": "R solution to max product in matrix for four adjacent numbers (Euler 11)"
}
|
234643
|
<p>I wrote a code to parse an <a href="https://www.hackerrank.com/challenges/attribute-parser/problem" rel="nofollow noreferrer">HTML knock-off from HackerRank</a>, and I would like a review. Mostly I hope to get better at STL and code style. But any tips would be very welcome. </p>
<p>Sample input that I would read from <code>cin</code> to parse and answer queries:</p>
<blockquote>
<p>4 3<br>
<tag1 value = "HelloWorld"><br>
<tag2 name = "Name1"><br>
</tag2><br>
</tag1><br>
tag1.tag2~name<br>
tag1~name<br>
tag1~value</p>
</blockquote>
<p>My code:</p>
<pre><code>#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
int main() {
std::string scope, cin_buffer, name;
std::string::iterator strg_it;
int lines, querrys;
std::map<std::string,std::string> variables;
std::cin >> cin_buffer;
lines = atoi(cin_buffer.c_str());
std::cin >> cin_buffer;
querrys = atoi(cin_buffer.c_str());
for (int lines_processed=0; lines_processed<lines; ++lines_processed){
std::cin >> std::ws;
while (std::cin.peek()!= '\n'){
std::cin >> cin_buffer;
if (cin_buffer.at(0)=='<' && cin_buffer.at(1)!='/'){
strg_it = remove_if( begin(cin_buffer), end(cin_buffer),
[](unsigned char c){return c=='<' || c=='>';});
cin_buffer.erase(strg_it, end(cin_buffer));
if (scope.length()>0){
scope += "." + cin_buffer;
}else{
scope = cin_buffer;
}
}else if (cin_buffer.at(0)=='<' && cin_buffer.at(1)=='/'){
int length_to_erase = (scope.length())-(cin_buffer.length()-3);
scope.erase(length_to_erase);
if (scope.back()=='.'){
scope.erase(scope.length()-1);
}
}else{
name = scope + "~" + cin_buffer;
std::cin >> cin_buffer;
std::cin >> cin_buffer;
strg_it = remove_if( begin(cin_buffer), end(cin_buffer),
[](unsigned char c){return c=='"' || c=='>';} );
cin_buffer.erase(strg_it, end(cin_buffer));
variables[name]=cin_buffer;
}
}
}
for (int querry_number=0; querry_number<querrys; ++querry_number){
std::cin >> cin_buffer;
if (variables.find(cin_buffer)!=end(variables)){
std::cout << variables[cin_buffer] << std::endl;
}else{
std::cout << "Not Found!" << std::endl;
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T07:49:51.633",
"Id": "458944",
"Score": "0",
"body": "Welcome to CodeReview@SE. I took the liberty to remove the advance thanks in accordance with [Expected Behavior](https://codereview.stackexchange.com/help/behavior). You have done well on [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), another thing to keep in mind would be [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)"
}
] |
[
{
"body": "<p>It is good to see that you've avoided the use of <code>using namespace std;</code>.</p>\n\n<p><strong>Coding</strong></p>\n\n<p>Declare variables as close to their initial use as possible, and prefer construction of that initial value to default constructing an object then assigning the initial value. <code>lines</code> and <code>querrys</code> can be declared when they are assigned:</p>\n\n<pre><code>auto lines = atoi(cin_buffer.c_str());\n// ...\nauto querrys = atoi(cin_buffer.c_str());\n</code></pre>\n\n<p><code>name</code> can be declared where it is used. <code>strg_it</code> can also be declared (in both places) as <code>auto</code>. This can help the compiler improve the code by letting it know the value isn't needed after the <code>erase</code> call.</p>\n\n<pre><code>auto strg_it = remove_if( begin(cin_buffer), end(cin_buffer), \n [](unsigned char c){return c=='<' || c=='>';});\ncin_buffer.erase(strg_it, end(cin_buffer));\n</code></pre>\n\n<p>Alternatively, when using the erase-remove idiom, you can put the erase and remove in one statement</p>\n\n<pre><code> cin_buffer.erase(remove_if( begin(cin_buffer), end(cin_buffer), [](unsigned char c){return c=='<' || c=='>';}), end(cin_buffer));\n</code></pre>\n\n<p>and not need the variable at all.</p>\n\n<p>You have no error checking on your inputs. You should check for failed input, non-integer conversions from <code>atoi</code>, etc. One alternative (since you have a <code>std::string</code>) is to use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/stol\" rel=\"nofollow noreferrer\"><code>std::stoi</code></a>, which will throw an exception if there is an error during conversion.</p>\n\n<p><code>cin_buffer.at(0)</code> will throw with an empty string, and <code>cin_buffer.at(1)</code> will throw an exception if the string only has one character in it.</p>\n\n<p><code>variables[name]=cin_buffer;</code> will replace any existing value for <code>name</code> if one already exists. This may be the expected behavior.</p>\n\n<p>In your final search loop, store the result of <code>find</code> in a variable to avoid having to look it up again.</p>\n\n<pre><code>auto it = variables.find(cin_buffer);\nif (it != end(variables)) {\n std::cout << it->second << `\\n`;\n} else\n</code></pre>\n\n<p>You should avoid using <code>std::endl</code> unless absolutely necessary. Since it flushes the output, there can be a considerable performance hit when using it.</p>\n\n<p><strong>Readability</strong></p>\n\n<p>You should put more spaces in your code, rather than jamming all those characters together. Put spaces around binary operators</p>\n\n<pre><code>for (int lines_processed = 0; lines_processed < lines; ++lines_processed) {\n</code></pre>\n\n<p>which also makes it clearer that <code>lines_processed < lines</code> is an expression and not part of a possible template <code>lines_processed<lines></code>.</p>\n\n<p>The parentheses around <code>(scope.length())</code> are unnecessary.</p>\n\n<p>Spelling is important. Variable names should be spelled correctly to make it easier to read and easier to search for. <code>querrys</code> should be spelled <code>queries</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T04:38:43.640",
"Id": "234653",
"ParentId": "234649",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234653",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T02:09:44.557",
"Id": "234649",
"Score": "1",
"Tags": [
"c++",
"parsing",
"c++17"
],
"Title": "Parsing HTML knock-off for answering queries for values"
}
|
234649
|
<p>I would appreciate some feedback on the below code I wrote for a Project Euler problem. The answer comes out correct but I'd like feedback on the design of the function and implementation of docstrings. It seems to me that it may be overly complicated but I'm not sure how to simplify. </p>
<pre><code>"""
Number letter counts
Problem 17
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are
3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many
letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains
23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing
out numbers is in compliance with British usage.
Answer = 21124
"""
num_word_map = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',
15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty',
50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty',
90: 'ninety', 100: 'hundred', 1000: 'thousand'}
def convert_to_word(x, spacing=''):
"""
Recursive function that converts number to it's equivalent word up to a limit of 9999.
Function is called recursively until x < 20.
Parameters
----------
x : number to convert to word
spacing : keeps track appropriate value to enter between words. This will be 'and' or an empty string
Returns
-------
Equivalent word for the number x
"""
if x / 1000 == 1:
return convert_to_word(x // 1000) + num_word_map[1000]
if 0 < x//100 < 10:
if x % 100:
return convert_to_word(x//100) + num_word_map[100] + convert_to_word(x % 100, 'and')
else:
return convert_to_word(x//100) + num_word_map[100]
elif 2 <= x//10 < 10:
return spacing + num_word_map[x - (x % 10)] + convert_to_word(x % 10)
# 0 included to prevent TypeError on a value like 80
elif 0 <= x < 20:
return spacing + num_word_map[x]
else:
"Value out of bounds"
def count_letters(limit=1000):
"""
Counts the number of letters in a word corresponding to a number from one to limit
Parameters
----------
limit : upper limit of numbers to convert and count to
Returns
-------
None
"""
count = 0
for val in range(1, limit + 1):
s = convert_to_word(val)
print(s)
count += len(s)
print(count)
if __name__ == '__main__':
count_letters()
</code></pre>
|
[] |
[
{
"body": "<p>Nice use of <code>\"\"\"docstrings\"\"\"</code>.</p>\n\n<hr>\n\n<p>This code is useless:</p>\n\n<pre><code>else:\n \"Value out of bounds\"\n</code></pre>\n\n<p>If the else clause is reached, the string statement is executed, with no effect. Just like executing a docstring statement has no effect.</p>\n\n<p>You want:</p>\n\n<pre><code>else:\n raise ValueError(\"Value of out bounds\")\n</code></pre>\n\n<hr>\n\n<p>The function <code>convert_to_word()</code> returns strange values like <code>\"sevenhundredandtwentyfive\"</code>, which is only useful for counting letters, and nothing else. A more flexible return might be <code>[\"seven\", \"hundred\", \"and\", \"twenty\", \"five\"]</code>, allowing the caller to count words, or letters ... or ... join the words with spaces.</p>\n\n<hr>\n\n<p>Several recursive calls are unnecessary.</p>\n\n<p><code>convert_to_word(x//100)</code> could simply be <code>num_word_map[x // 100]</code>, and <code>convert_to_word(x % 10)</code> could be <code>num_word_map[x % 10]</code>.</p>\n\n<hr>\n\n<p>Comparison of a floating point value and an integer for equality is dangerous <code>x / 1000 == 1</code>. Simply use <code>x == 1000</code>.</p>\n\n<hr>\n\n<p>For this problem, instead of storing the words in <code>num_word_map</code>, you could simply store the lengths of the words. </p>\n\n<hr>\n\n<p>Your <code>\"\"\"docstring\"\"\"</code> usage is good. You describe what the function does, what the parameters are, and what the return value is. Someone wishing to use your functions would only need to type <code>help(convert_to_word)</code> and they should have all the information required to use the function.</p>\n\n<p>There is no formal \"right way\" to format the docstrings, but there are some tools which expect things a certain way.</p>\n\n<p>For instance</p>\n\n<pre><code>\"\"\"\n... omitted ...\n\nNOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains\n23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of \"and\" when writing\nout numbers is in compliance with British usage.\nAnswer = 21124\n\"\"\"\n</code></pre>\n\n<p>This docstring contains 2 examples with answers, and one answer to a large question. You can embed examples in a <code>\"\"\"docstring\"\"\"</code>, and it can become a built-in test for your module.</p>\n\n<pre><code>\"\"\"\n... omitted ...\n\nAnswer = 21124\n\nNOTE: Do not count spaces or hyphens. The use of \"and\" when writing\nout numbers is in compliance with British usage. For example:\n\n>>> len(convert_to_word(342)) # three hundred and forty-two\n23\n\n>>> len(convert_to_word(115)) # one hundred and fifteen\n20\n\"\"\"\n</code></pre>\n\n<p>Starting at the <code>>>></code>, the text look like lines straight out of what you might see if you typed commands in a Python REPL. The lines beginning with <code>>>></code> are the commands, and the lines below that are the command output. The <code>doctest</code> module can read the docstrings in a module, find lines formatted this way, execute the commands, and verify the output matches the expected output. You might run this as:</p>\n\n<pre><code>python3 -m doctest numbers-letters.py\n</code></pre>\n\n<p>The output of the above command should be nothing, because the tests would pass. Let's add one more test in the doc string:</p>\n\n<pre><code>\"\"\"\n... omitted ...\n\n>>> len(convert_to_word(342)) # three hundred and forty-two\n23\n\n>>> len(convert_to_word(115)) # one hundred and fifteen\n20\n\n>>> convert_to_word(115)\n'one hundred and fifteen'\n\"\"\"\n</code></pre>\n\n<p>Now running the doctest will produce output due to the failing test:</p>\n\n<pre><code>python3.8 -m doctest number-letters.py \n**********************************************************************\nFile \"/Users/aneufeld/Documents/Stack Overflow/number-letters.py\", line 23, in number-letters\nFailed example:\n convert_to_word(115)\nExpected:\n 'one hundred and fifteen'\nGot:\n 'onehundredandfifteen'\n**********************************************************************\n1 items had failures:\n 1 of 3 in number-letters\n***Test Failed*** 1 failures.\n</code></pre>\n\n<p>The output doesn't match because the test output contains spaces, which the function doesn't actually produce.</p>\n\n<p>Other tools exist which read the docstrings, such as the <a href=\"http://www.sphinx-doc.org/en/master/\" rel=\"nofollow noreferrer\">Sphinx</a> documentation generator. It has formatting requirements; read the docs for details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T20:27:07.223",
"Id": "459090",
"Score": "0",
"body": "Thank you for the feedback. It's really helpful!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T06:40:36.757",
"Id": "234656",
"ParentId": "234652",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T03:13:08.327",
"Id": "234652",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"recursion",
"numbers-to-words"
],
"Title": "Number in words: recursive function"
}
|
234652
|
<h2>The Challenge</h2>
<blockquote>
<p>Given a <em>big string</em> and a <em>list of smaller strings</em>, find the <em>minimum amount of spaces</em> that must be inserted between characters of the string in such way that it becomes composed only of elements from the list of smaller strings. (and which are the respective elements used). [Python 3]</p>
</blockquote>
<p>For instance, if you had as a string: 'foobarpy' and as a list: ['foo', 'bar', 'py', 'foob', 'arpy'], the optimal solution would be: foob arpy, requiring you to insert only a single space in the string.</p>
<p><em>Basically:</em></p>
<p>-The "big string" must be "transformed" into a combination of elements from the list, only by inserting spaces in between characters of it (with the least amount of spaces as possible) </p>
<p>-Elements can't be repeated</p>
<p>-Not all the elements must be used </p>
<pre class="lang-py prettyprint-override"><code># Sample input
big_string = '3141592653589793238462643383279'
small_strings = ['3', '314', '49', '9001', '15926535897', '14', '9323', '8462643383279', '4', '793', '3141592653589793238462643383278', '314159265358979','3238462643383279']
</code></pre>
<h2>My Solution</h2>
<p>As I see it, instead of trying to "slice" the given string, it's easier to try to combine the elements from the list and look for the match with the least elements.
My full code: <a href="https://repl.it/@LucasWerner/String-Least-Spacing" rel="nofollow noreferrer">https://repl.it/@LucasWerner/String-Least-Spacing</a></p>
<ol>
<li>Get rid of elements in the list that don't appear in the string.</li>
</ol>
<pre class="lang-py prettyprint-override"><code># Required modules
import itertools
import numpy as np
small_strings = [x for x in small_strings if x in big_string]
</code></pre>
<ol start="2">
<li>Combine elements in groups of sizes from 1 to the length of the list (just gathering to whole thing together) and check whether the combination has the same length as the given string... that would select fewer possibilites to further analyze. Store the possibilites as a list of tuples.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>possibilites = list()
for k in range(1, len(small_strings)): #k is the size of the combination
c = list(itertools.combinations(small_strings, k))
combinations = [x for x in c if sum(len(i) for i in x) == big_string_len]
possibilites.extend(combinations)
</code></pre>
<ol start="3">
<li>Permutate the tuples inside the list to see if they match the big_string. If so, store the permutated tuple in a list of matches.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>matches = list()
for tup in possibilites:
p = list(itertools.permutations(tup))
permutations = [x for x in p if ''.join(x) == big_string]
matches.extend(permutations)
</code></pre>
<ol start="4">
<li>Bind the matches with their lengths in a dictionary</li>
</ol>
<pre class="lang-py prettyprint-override"><code>sizes = dict()
for tup in matches:
sizes[tup] = len(tup)
</code></pre>
<ol start="5">
<li>Finding the optimal solution (minimal length and where it occurres)</li>
</ol>
<pre class="lang-py prettyprint-override"><code>min_key = min(sizes, key=sizes.get)
min_val = sizes[min_key]
</code></pre>
<ol start="6">
<li>Giving the optimal solution</li>
</ol>
<pre class="lang-py prettyprint-override"><code>print('Best solution is', ' '.join(min_key), 'with', min_val - 1, 'space(s)')
</code></pre>
<p>Which in this case would print:</p>
<blockquote>
<p>Best solution is 314159265358979 3238462643383279 with 1 space(s)</p>
</blockquote>
<p>It's my first month learning Python and I was really hoping to get some feedback and tips from far more experient programmers about what I could change/learn/improve in the code to make it better/more efficient. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T07:06:46.560",
"Id": "458939",
"Score": "0",
"body": "Welcome to CodeReview@SE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T07:08:16.787",
"Id": "458940",
"Score": "0",
"body": "(It is unusual for questions here to present code \"from a single source code file\" as separate snippets. I am not sure I like it - can you provide a hyperlink to some code repository so reviewers can get an overall view without pasting snippets themselves?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T15:33:03.217",
"Id": "458987",
"Score": "0",
"body": "Just added a link to the project, directly in repl, where you can test it. Here it is: https://repl.it/@LucasWerner/String-Least-Spacing"
}
] |
[
{
"body": "<p>Firstly, great job on creating a solution that works. That is often the first step in creating an optimal solution. </p>\n\n<p>But as you may have noticed, making combinations and permutations based on the number of elements in <code>small_strings</code> will start to scale incredibly as you process longer and longer <code>small_strings</code> arrays. </p>\n\n<p>Mathematically, your solution is concise and straight-forward-- kudos again to that. The approach I will suggest is based on Dynamic Programming and preprocessing. This is to speed up scenarios where you have a very large (>100) number of <code>small_strings</code>. </p>\n\n<hr>\n\n<p>This approach will use the fact that we can solve the whole problem in the same manner of solving a subset of the problem. Specifically, if we can construct the <code>big_string</code> piece by piece, then we can simply add the result of the part we have constructed and add/recurse it on the rest of the string. </p>\n\n<p>The first idea to consider is building a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">trie</a> for the strings in <code>small_strings</code>. Also known as a prefix tree, a trie will help us figure out which strings we can use to 'construct' the <code>big_string</code>. I highly recommend understanding the concept of a trie for further insight into this problem.</p>\n\n<p>Secondly, we want to implement a function that explores the problem space in a way that is efficient and breaks on paths that yield no results. This is typical of many DP (Dynamic Programming) problems and often looks like recursion in practice. Knowing when and how to implement this comes with practice. I also highly recommend practicing some classical DP problems if you want to become a skilled developer.</p>\n\n<p>With those points in mind, here's a solution:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def buildTrie(words):\n trie = {}\n for word in words:\n current = trie\n for c in word:\n current = current.setdefault(c, {})\n current['isWord'] = word\n\n return trie\n\n\ndef findPrefixes(trie, word):\n results = {}\n current = trie\n\n for length, l in enumerate(word, start=1):\n if l in current:\n current = current[l]\n else:\n break\n if current.get('isWord'):\n results[current['isWord']] = length\n\n return results\n\n\ndef find_num_spaces(big_string, small_strings):\n trie = buildTrie(small_strings)\n N = len(big_string)\n\n def helper(index=0):\n nonlocal trie, N\n\n if index == N:\n return 0\n\n prefixes = findPrefixes(trie, big_string[index:])\n\n if prefixes:\n return min(1 + helper(index + length) for length in prefixes.values())\n else:\n return float('inf')\n\n return helper() - 1\n\n\nbig_string = '3141592653589793238462643383279'\nsmall_strings = ['3', '314', '49', '9001', '15926535897', '14', '9323', '8462643383279', '4', '793', '3141592653589793238462643383278', '314159265358979', '3238462643383279']\n\nassert find_num_spaces(big_string, small_strings) == 1\n\nbig_string = '3141592653589793238462643383279'\nsmall_strings = ['3', '314', '49', '9001', '15926535897', '14', '9323', '8462643383279', '4', '793', '3141592653589793238462643383278', '3141592', '65358979323']\n\nassert find_num_spaces(big_string, small_strings) == 2\n</code></pre>\n\n<p>Since we do our preprocessing in the form of a trie, we know how to efficiently reconstruct our <code>big_string</code>. The general idea here is that we are trading space for time complexity. Storing our strings allows for efficient exploration of the problem space. </p>\n\n<p>Note: I assumed you only needed the number of spaces required-- requiring the specific strings involved would tweak this solution slightly. There would be an additional variable that would track the working solution through the recursion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T20:42:25.180",
"Id": "234682",
"ParentId": "234654",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234682",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T04:59:52.197",
"Id": "234654",
"Score": "5",
"Tags": [
"python",
"strings",
"combinatorics",
"hash-map"
],
"Title": "Minimum amount of spaces inserted in a given string, such that it gets composed only of elements from a given list"
}
|
234654
|
<p>I have implemented a Matrix class that allocates memory using <code>unique_ptr</code>. How to make it more diverse and optimized in terms of memory usage and efficiency?</p>
<pre><code>//
// Created by Mayukh Sarkar on 26/12/19.
//
#ifndef DP2_MATRIX_H
#define DP2_MATRIX_H
#include <cstdio>
#include <memory>
#include <algorithm>
template <typename T>
class Matrix {
private:
size_t row{};
size_t col{};
std::unique_ptr<T[]> data;
public:
explicit Matrix(size_t row, size_t col, T def) {
// Create a matrix of row X col and initialize
// each element of the matrix with def
this->row = row;
this->col = col;
this->data = std::make_unique<T[]>(this->row * this->col);
std::fill_n(data.get(), row*col, def);
}
// Overload the [] operator for the 2d array like access
T* operator[](int r) {
if (r >= row) {
throw std::out_of_range("Can not access out of bound element!");
}
return &this->data[r*col];
}
// Overload the << operator for console logging
friend std::ostream& operator<< (std::ostream& os, Matrix &mObj) {
auto shape = mObj.shape();
for(int i=0; i< shape.first; i++) {
for(int j=0; j<shape.second; j++) {
os << mObj[i][j] << " ";
}
os << "\n";
}
return os;
}
// Set all the values of the Matrix
void setValues(T value) {
std::fill_n(data.get(), row*col, value);
}
// Get row and col values
std::pair<size_t, size_t> shape() const {
return std::make_pair(this->row, this->col);
}
};
#endif //DP2_MATRIX_H
</code></pre>
<p>I want to specifically optimize the <code>[]operator</code> overloading because I feel it is not good to handle pointers directly. Any suggestions? </p>
|
[] |
[
{
"body": "<h2>Pragma once</h2>\n\n<p>Instead of</p>\n\n<pre><code>#ifndef DP2_MATRIX_H\n#define DP2_MATRIX_H\n</code></pre>\n\n<p>consider using</p>\n\n<pre><code>#pragma once\n</code></pre>\n\n<p>Once is non-standard, but supported by all compilers supporting\nC++14 and reduces compilation times.</p>\n\n<h2>Includes</h2>\n\n<p>On MSVC, <code>#include <stdexcept></code> is needed for the <code>out_of_range</code>\nerror. I also think your include lines look tidier if you sort them in\nalphabetical order. :)</p>\n\n<h2>Bounds checking</h2>\n\n<pre><code>Matrix<int>(10, 10, 0)[10][0]\n</code></pre>\n\n<p>Is an error that will be detected by your bounds checking, but</p>\n\n<pre><code>Matrix<int>(10, 10, 0)[0][10]\n</code></pre>\n\n<p>is the same type of error, but won't be detected. Consider following\nthe STL convention described in <a href=\"https://stackoverflow.com/questions/1026042/when-implementing-operator-how-should-i-include-bounds-checking\">this Stackoverflow\nanswer</a>. That\nis, you remove bounds checking from <code>operator[]</code> but add a method <code>at</code>\nwhich does bounds checking for both dimensions.</p>\n\n<h2>Const correctness</h2>\n\n<p>You should add <code>const</code> declared variants of the accessors. You can\nalso add it to the parameters, but imho, that is not as useful.</p>\n\n<p>Result:</p>\n\n<pre><code>#pragma once\n\n#include <algorithm>\n#include <cstdio>\n#include <memory>\n#include <stdexcept>\n\ntemplate <typename T>\nclass Matrix {\nprivate:\n size_t row{};\n size_t col{};\n std::unique_ptr<T[]> data;\n void boundscheck(int r, int c) const {\n if (!(0 <= r && r < row && 0 <= c && c < col)) {\n throw std::out_of_range(\"Can not access out of bound element!\");\n }\n }\npublic:\n // Set all the values of the Matrix\n void setValues(T value) {\n std::fill_n(data.get(), row*col, value);\n }\n explicit Matrix(size_t row, size_t col, T def) {\n // Create a matrix of row X col and initialize\n // each element of the matrix with def\n this->row = row;\n this->col = col;\n this->data = std::make_unique<T[]>(this->row * this->col);\n setValues(def);\n }\n // Overload the [] operator for the 2d array like access\n T* operator[](int r) {\n return &this->data[r * col];\n }\n const T* operator[](int r) const {\n return &this->data[r * col];\n }\n T& at(int r, int c) {\n boundscheck(r, c);\n return this->data[r * col + c];\n }\n const T& at(int r, int c) const {\n boundscheck(r, c);\n return this->data[r * col + c];\n }\n // Overload the << operator for console logging\n friend std::ostream& operator<< (std::ostream& os, Matrix &mObj) {\n auto shape = mObj.shape();\n for(int i=0; i< shape.first; i++) {\n for(int j=0; j<shape.second; j++) {\n os << mObj[i][j] << \" \";\n }\n os << \"\\n\";\n }\n return os;\n }\n // Get row and col values\n std::pair<size_t, size_t> shape() const {\n return std::make_pair(this->row, this->col);\n }\n};\n</code></pre>\n\n<p>I don't think it is possible to make a general matrix class consume less memory or run quicker than that. Compilers generate pretty good code for the accessor functions. You probably have to use a different data type such as a sparse matrix to improve performance much. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:15:59.170",
"Id": "459007",
"Score": "0",
"body": "It is really a shame that C++ doesn't have anything that can enforce OutOfBoud access with `[] operator` or even `[][] operator`. Anyway nice solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T16:51:32.250",
"Id": "459079",
"Score": "0",
"body": "@MayukhSarkar For that, you use `.at()`. Also, `.operator()()` is common for multi-dimensional indexing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T17:08:07.000",
"Id": "459082",
"Score": "0",
"body": "@Deduplictor Yeah but a [][] operator would have been nice. Wonder how boost does it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T17:25:56.993",
"Id": "459084",
"Score": "0",
"body": "@MayukhSarkar You can fake it using nested classes. But imo, you shouldn't do it. It makes the code harder to understand for no tangible benefit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T22:54:47.717",
"Id": "459095",
"Score": "0",
"body": "@MayukhSarkar If you're creating an overload of `operator[]`, you can include range checks in it, but that is not the norm. Some compilers include range checks in `operator[]` when building debug versions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T20:10:11.903",
"Id": "459165",
"Score": "1",
"body": "You should make input for `operator[]` and function `at` of type `size_t` - so on definition it is clear that you don't accept negative values. It will also fix a few casting warnings and some when user misuses `operator []`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T21:15:45.647",
"Id": "459170",
"Score": "0",
"body": "@ALX23z Yes, or `unsigned`. The reason I didn't add it is because I've seen different sources use different types for the parameter to `operator[]`. Some use `int`, others `unsigned` or `size_t` so I wasn't sure would be the best."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T22:29:16.383",
"Id": "459175",
"Score": "0",
"body": "The thing is that it should coincide with `rows / cols` type whatever it is."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T12:50:50.350",
"Id": "234666",
"ParentId": "234655",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T06:23:03.390",
"Id": "234655",
"Score": "3",
"Tags": [
"c++",
"matrix",
"c++14"
],
"Title": "Matrix class with overloaded `operator[]`"
}
|
234655
|
<p>What would be the shortest way to capture folder structure in code? I would like to have a more or less reusable strictly typed approach to use in scripts instead of stringly typed paths we all usually deal with. Here is how a part of my simple “system info” utility looks like:</p>
<pre><code>static void Main(string[] args)
{
foreach(var cursor in SystemDisk.Windows.Cursors.Animated)
Console.WriteLine(cursor);
}
</code></pre>
<p>Where:</p>
<pre><code>using static System.IO.Directory;
public static class SystemDisk
{
public static string Drive { get; set; } = "C:";
public static string AutoexecBat => $"{Drive}\\Autoexec.bat";
public static class Windows
{
public static string Path => $"{Drive}\\Windows";
public static string SystemIni => $"{Path}\\System.ini";
public static class Cursors
{
public static string Path => $"{Windows.Path}\\Cursors";
public static IReadOnlyList<string> Animated => GetFiles(Path, "*.ani");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:59:26.317",
"Id": "458953",
"Score": "0",
"body": "What do you need this folder structure for? Please [edit] the question and add some details about what you want to do with these paths."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T14:59:44.570",
"Id": "458983",
"Score": "0",
"body": "@RolandIllig here it is. It is supposed to be a reusable type though, just a way to get intellisense hints while typing file paths - so i can not know all the use cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T15:29:50.607",
"Id": "458986",
"Score": "0",
"body": "@DmitryNogin `folder structure` do you mean files and folders that inside that folder ? like the command prompt line `dir` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T15:36:24.027",
"Id": "458988",
"Score": "0",
"body": "@iSR5 yep, something like this. I would like visual studio to get me a hint about what is next while typing in a file path - compiler should check my paths basically. It could work with registry keys as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T18:24:53.257",
"Id": "459000",
"Score": "0",
"body": "It sounds like you want a `Trie` structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T18:53:09.950",
"Id": "459002",
"Score": "0",
"body": "@tinstaafl Yep, something like this. No dynamically allocated memory though - it makes it be different from data structures. I want it all be visible to C# editor/compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T20:05:48.567",
"Id": "459012",
"Score": "0",
"body": "Did a simple search on google and found [this](https://marketplace.visualstudio.com/items?itemName=ionutvmi.path-autocomplete). Looks like exactly what you want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:23:37.890",
"Id": "459021",
"Score": "0",
"body": "@tinstaafl Thanks, but it works with VSC only (not VS), developer's machine could have different folder structure (different root for a project is a very realistic thing to happen). I also would like to change property types to something like `public static IniFile SystemIni => $\"{Path}\\\\System.ini\"` to have a handy manipulation API in-place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T23:50:42.803",
"Id": "459033",
"Score": "0",
"body": "@DmitryNogin are you trying to use a Visual Studio extension for that ? or are you trying to make a new one ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:11:17.603",
"Id": "459034",
"Score": "0",
"body": "@iSR5 neither of that. Any extension will probably depend on local disk folder structure which will be different on a server, so i am not a big fun of them all. What i need is my own class, a C# type, which is relatively easy to define and very, very easy to use in many places across the app. The class api should mimic folder structure (i need almost the same for capturing a shape of my registry key hierarchy too). The cheapest way to have a hierarchical class api in C# is to use nested static classes as far as i can see."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:56:22.073",
"Id": "459042",
"Score": "0",
"body": "@DmitryNogin I'm trying to understand what are looking for, from what I understood so far, you're trying to create a shared class or an internal library which generates a directory path dynamically. so for instance, you type `OSDrive`, this would generate the path of the Windows directory (e.g. `C:\\Windows`) as you don't need to have fixed paths, you need the class or library to be working on any server that runs `Windows` is much similar to Windows Environment variables (e.g. `%APPDATA%`) , is that what are you asking for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T01:00:54.307",
"Id": "459045",
"Score": "0",
"body": "@iSR5 I would like to document in code important files and registry keys of my app in a strictly typed way, so I would like a type with a hierarchical api as registry and disk files/folders are hierarchical by nature. It should drive me when I need to provide a file path, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T01:03:21.450",
"Id": "459048",
"Score": "0",
"body": "@DmitryNogin Oh, so you just want to convert constants into a strong typed objects right ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T01:10:00.627",
"Id": "459050",
"Score": "0",
"body": "@iSR5 Yep, kind of. Just looking for a \"hierarchical\" configurable representation which mimics the nature of the target media to reduce recognition gap :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T01:12:50.163",
"Id": "459051",
"Score": "1",
"body": "@DmitryNogin, now we are in the same page I guess ;)"
}
] |
[
{
"body": "<p>I've got the idea you're trying to achieve, however, this would be too much work to do if you're going to implement it this way. </p>\n\n<p>If you are still convinced that this is the only way, you can use <code>struct</code> and define the OS structure like you did, and keep it only for path something like this : </p>\n\n<pre><code>public struct SystemDisk\n{\n private static string Drive => Path.GetPathRoot(Environment.SystemDirectory);\n\n //using Refelction, will give you the object's full name, we then convert it to string and adjust it to be parsed as an OS path.\n private static string GetPath(Type type) => @Drive + @type.FullName.Substring(type.FullName.IndexOf('.') + \"SystemDisk\".Length + 2).Replace('+', Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;\n\n public struct Windows\n {\n public static string Root => $@\"{GetPath(typeof(Windows))}\";\n\n public static string SystemIni => $@\"{Root}System.ini\";\n\n public struct System\n {\n public static string Root => $@\"{GetPath(typeof(System))}\";\n }\n\n public struct System32\n {\n public static string Root => $@\"{GetPath(typeof(System32))}\";\n }\n\n public struct Cursors\n {\n public static string Root => $@\"{GetPath(typeof(Cursors))}\";\n public static IReadOnlyList<string> Animated => GetFiles(Root, \"*.ani\");\n }\n }\n}\n</code></pre>\n\n<p>if you're going to continue on this road, and you need to create a <code>struct</code> for each directory in the system folders, you can write a method to get the directories, and then design a model for it, then returning this model as string, then just copy and paste. To do that, you'll have to get first the directories, then get each directory name, after that, you'll remove any special chars from the name, then just make a model template and pass the directory name to it, get the representative string, and copy / paste into the class. </p>\n\n<p>Here is method to camel case the name : </p>\n\n<pre><code>public static string CamelCase(string str)\n{\n str = str.Replace(\".\", \" \").Replace(\"-\", \" \").Replace(\"_\", \" \"); \n\n return str.Contains(\" \")\n ? string.Join(\"\", str.Split(' ').Select(x => char.ToUpper(x[0]) + x.Substring(1)))\n : char.ToUpper(str[0]) + str.Substring(1);\n}\n</code></pre>\n\n<p>now we can do a method to build the model template : </p>\n\n<pre><code>public static string StructModelBuilder(string name, int indentlevel, string body = \"\")\n{\n var sb = new StringBuilder(string.Empty);\n\n string indentLv1 = indentlevel == 0 ? string.Empty : new string(' ', indentlevel);\n\n string indentLv2 = indentLv1 == string.Empty ? new string(' ', 4) : new string(' ', indentlevel * 2);\n\n sb.Append(Environment.NewLine);\n sb.Append(indentLv1);\n sb.Append($\"public struct {name}\");\n sb.Append(Environment.NewLine);\n sb.Append(indentLv1);\n sb.Append(\"{\");\n sb.Append(Environment.NewLine);\n sb.Append(indentLv2);\n sb.Append($\"public static string Root => $@\\\"{{GetPath(typeof({name}))}}\\\";\");\n sb.Append(Environment.NewLine); \n sb.Append(body); \n sb.Append(indentLv1);\n sb.Append(\"}\");\n sb.Append(Environment.NewLine);\n\n return sb.ToString();\n}\n</code></pre>\n\n<p>now, we can create a method where we get the directories list, and just pass them to the template to get the model</p>\n\n<pre><code>public static string GetStructureModel(string path)\n{\n if (string.IsNullOrEmpty(path))\n return string.Empty;\n\n\n //Directory.GetDirectories($@\"{path}\", \"*.*\", SearchOption.AllDirectories); // to include all sub-directories (recursively).\n var root_dir = Directory.GetDirectories($@\"{path}\");// just get the top level directories.\n\n // remove the last Directory Sparator Charcter (e.g. back-slash \\) and get the name of the directory\n var root_name = path.TrimEnd('\\\\').Substring(path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1);\n\n var rootNameCamelCase = CamelCase(path.TrimEnd('\\\\'));\n\n var sb = new StringBuilder(string.Empty);\n\n var model = StructModelBuilder(rootNameCamelCase, 0, \"@body\");\n\n foreach (var dir in root_dir)\n {\n var dir_name = path.TrimEnd('\\\\').Substring(path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1);\n\n var dirNameCamelCase = CamelCase(dir_name);\n\n sb.Append(StructModelBuilder(dirNameCamelCase, 4));\n }\n\n return model.Replace(\"@body\", sb.ToString()); \n}\n</code></pre>\n\n<p>now you just pass the path like this : </p>\n\n<pre><code>var model = GetStructureModel(@\"C:\\Windows\");\n</code></pre>\n\n<p>you can from here take the model, paste it into the class, and adjust whatever needed. this is not perfect, but it should get the job done. </p>\n\n<p>personally, I wouldn't go this far if I were in your seat, instead, I'll use Window Environment Variables instead, to not re-invent the wheels. also, I'll make use of <code>Enum</code> and make things shorter. For instance, instead of making a full path to the <code>System32</code>, I'll just use an <code>Enum</code> and define <code>System32</code>, and with a simple <code>switch</code> statement, it'll return the full path, and so on. this would make more sense to me and would be easier to maintain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T16:08:50.093",
"Id": "459149",
"Score": "0",
"body": "Thanks. Actually, I think I would do it manually, as I just would like to document important relevant file/registry entries only and developer machine file structure could be different. Generally speaking, I was just looking for a cheap way to define hierarchical class API which could be useful in many applications to reduce presentation complexity. It is a shame that in 2020 we have no native language mechanism for that being done syntactically efficient :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T23:24:38.193",
"Id": "459181",
"Score": "0",
"body": "@DmitryNogin the only issue is that you are trying to search for nails in a farm to put them in one box. It's possible, but it will not be easy. because the actual system paths are spread between .NET classes, each for its uses. you'll find something like `KnownFolders` but this even don't have all the folders. I have not played with Windows SDK, but I'm sure you'll find something useful there. You'll need to get the actual class or object that define the system path you need instead of store it as string, so if there is any updates on the path, your library should catch the new path for it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T05:09:13.317",
"Id": "234720",
"ParentId": "234658",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234720",
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:00:09.597",
"Id": "234658",
"Score": "1",
"Tags": [
"c#"
],
"Title": "How to capture disk folder structure?"
}
|
234658
|
<p>Whats the best practice for calling a function with a complex set of arguments?</p>
<p>I've seen a <strong>1</strong> and <strong>2</strong> in most codebases, but I haven't seen <strong>3</strong>.
Since it's almost impossible to search for <code>**{</code> in codebases, does anyone know why this pattern isn't used more often? </p>
<p>I'm using Google's <a href="https://googleapis.github.io/google-api-python-client/docs/dyn/sheets_v4.spreadsheets.html#batchUpdate" rel="nofollow noreferrer">Sheet's API v4</a> as a demonstration, which has a complex API.</p>
<hr>
<h2>1. Calling with arguments (Most commonly observed)</h2>
<ul>
<li>Requires building the inner structure first</li>
</ul>
<pre class="lang-py prettyprint-override"><code>body = {
"body": {
"requests": [
{
"addSheet": {
"properties": {
"title": "some title"
}
}
}
]
}
}
request = service.spreadsheets().batchUpdate(
spreadsheetId=spreadsheetId, body=body)
</code></pre>
<h2>2. Define a <code>dict</code> first (Similar vertical parsing to 1)</h2>
<ul>
<li>Cleaner to see on invocation</li>
<li>May allow for manipulation of values</li>
</ul>
<pre class="lang-py prettyprint-override"><code>params = {
"spreadsheetId": spreadsheetId
"body": {
"requests": [
{
"addSheet": {
"properties": {
"title": "some title"
}
}
}
]
}
}
request = service.spreadsheets().batchUpdate(**params)
</code></pre>
<h2>3. Inline a <code>dict</code> (Not seen in practice, why?)</h2>
<ul>
<li>Clear intent (single-source, fixed properties)</li>
<li>Single pass vertical parsing</li>
</ul>
<pre class="lang-py prettyprint-override"><code>request = service.spreadsheets().batchUpdate(**{
"spreadsheetId": spreadsheetId
"body": {
"requests": [
{
"addSheet": {
"properties": {
"title": "some title"
}
}
}
]
}
})
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T11:26:46.833",
"Id": "458966",
"Score": "1",
"body": "Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, **hypothetical code**, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]."
}
] |
[
{
"body": "<p>Disclaimer: I'm not the super duper python crack.</p>\n\n<p>When discussing such questions I usually like to figure out first, what's the thing we're optimizing for.\nIf it's performance you might make other decisions than when its maintainability or readability.</p>\n\n<p>For readability all of them are fine and have small benefits or disadvantages.\nIn the end the style wins you're most used to. However, there might be technical dis/advantages which I'm not aware of.</p>\n\n<p>Option 1 has in favor that the call is a bit more explicit about what its doing, because there is one important argument explicitly added (spreadsheetId) and a number of arguments with less importance.</p>\n\n<p>If you scroll over the code, 1 has a small advantage there I'd say.</p>\n\n<p>I don't exactly get, what you mean by </p>\n\n<blockquote>\n <p>Since it's almost impossible to search for **{ in codebases,</p>\n</blockquote>\n\n<p>But my gut says, if you need to search something as a string other than a name, there is something odd, which needs to be fixed.</p>\n\n<p>Maybe your parameters have a degree of complexity where it would make sense to add functions which create them (and also document their intention through their name).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T11:28:26.780",
"Id": "458967",
"Score": "2",
"body": "Welcome to Code Review. Please note that it's considered bad style to answer off-topic questions. We have plenty of unanswered, on-topic questions that could use your attention instead. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T11:11:44.513",
"Id": "234663",
"ParentId": "234660",
"Score": "1"
}
},
{
"body": "<p>As general practice, I prefer using positional arguments simply because they're easier to typecheck with <code>mypy</code>. In the case of using some external API that doesn't have python3 type annotations (booo) I'd create a stub file that includes all of the types that I'm using and then code against that.</p>\n\n<p>For your example, a quick search didn't turn up any existing mypy stubs, so I assume I'm stuck writing my own. Here's how I'm gonna do it for the code sample you've provided:</p>\n\n<pre><code>from typing import List, TypedDict\n\nclass _Properties(TypedDict, total=False):\n title: str\n\nclass _AddSheet(TypedDict, total=False):\n properties: _Properties\n\nclass _Request(TypedDict, total=False):\n addSheet: _AddSheet\n\nclass _Body(TypedDict, total=False):\n requests: List[_Request]\n\ndef batchUpdate(spreadsheetId: str, body: _Body) -> None: ...\n</code></pre>\n\n<p>This is a very incomplete type declaration for that potentially massive <code>_Body</code> object (also, note that I'm assuming that none of these fields are required; omit the <code>total=False</code> if you want to enforce totality), but since I'm probably not going to use all of those fields, my strategy is going to be to add them to my declaration as I use them, and have that be the source of truth (i.e. as long as I declare it correctly once in that file, mypy will make sure I use it correctly everywhere else).</p>\n\n<p>Now I can call that function in my code like this:</p>\n\n<pre><code>batchUpdate(\n spreadsheetId, { \n 'requests': [{ \n 'addSheet': { \n 'properties': { \n 'title': \"some title\" \n } \n } \n }]\n }\n)\n</code></pre>\n\n<p>(BTW, if you want to completely ignore my advice about typing, this is the calling syntax I'd use regardless.)</p>\n\n<p>The benefit of having added typing is that if I typo something, e.g. I misspell \"properties\", I'll get an error from mypy like this:</p>\n\n<pre><code>spreadsheet.py:22: error: Extra key 'prperties' for TypedDict \"_AddSheet\"\n</code></pre>\n\n<p>If I forget that <code>requests</code> is a list and I omit the brackets, I get:</p>\n\n<pre><code>spreadsheet.py:21: error: Incompatible types (expression has type \"Dict[str, Dict[str, Dict[str, str]]]\", TypedDict item \"requests\" has type \"List[_Request]\")\n</code></pre>\n\n<p>Getting a static error like this is a lot easier than having a typo in my server API call that results in a (possibly cryptic) runtime error.</p>\n\n<p>My experience is that using the <code>**kwargs</code> syntax generally makes it harder to enforce good typing, so I tend to avoid it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T18:34:36.757",
"Id": "234678",
"ParentId": "234660",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T08:03:53.093",
"Id": "234660",
"Score": "0",
"Tags": [
"python"
],
"Title": "Calling method with complex arguments"
}
|
234660
|
<p>I implemented a <strong>sha256</strong> hash function for javascript just for a practice and I want to know if my code needs more improvement. Please tell me which to simplify if there's any. Thanks.</p>
<p>Here is my code:</p>
<pre><code>var sha256TOOLS = {};
//sha256 constant
sha256TOOLS.k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
//sha256 intial hashes
sha256TOOLS.h = [0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19];
sha256TOOLS.addFrontZero = function addFrontZero(str, fixedlength){
while(str.length < fixedlength){
str = 0 + str;
}
return str;
};
sha256TOOLS.rotr = function rotr(n,x){
return (((x >>> n) | (x << 32 - n)) >>> 0) % Math.pow(2,32);
};
sha256TOOLS.ch = function ch(x,y,z){
return (x & y) ^ (~x & z);
};
sha256TOOLS.maj = function maj(x,y,z){
return (x & y) ^ (x & z) ^ (y & z);
};
sha256TOOLS.sigma0 = function sigma0(x){
return this.rotr(2,x) ^ this.rotr(13,x) ^ this.rotr(22,x);
};
sha256TOOLS.sigma1 = function sigma1(x){
return this.rotr(6,x) ^ this.rotr(11,x) ^ this.rotr(25,x);
};
sha256TOOLS.omega0 = function omega0(x){
return this.rotr(7,x) ^ this.rotr(18,x) ^ (x >>> 3);
};
sha256TOOLS.omega1 = function omega1(x){
return this.rotr(17,x) ^ this.rotr(19,x) ^ (x >>> 10);
};
sha256TOOLS.mod = function mod(a,b){
var temp = a % b;
while(temp < 0){
temp += b;
}
return temp;
};
var sha256 = (sha256 || function sha256(string){
//copy constant values and initial hashes
var H = sha256TOOLS.h.slice();
var K = sha256TOOLS.k.slice();
//sha256 pre processing
//convert string to ascii code first then to binary
//////////////////////////////////////////////////////
var str =[];
for(var ia=0; ia<string.length; ia++){
var ta = (string.charCodeAt(ia)).toString(2);
ta = (ta.length < 8) ? sha256TOOLS.addFrontZero(ta,8) : ta;
str.push(ta);
}
//turn str into string
str = str.join("");
//////////////////////////////////////////////////////
//Padding the message
var zeroBits = sha256TOOLS.addFrontZero("",sha256TOOLS.mod(448-(str.length+1), 512));
var lengthBits = sha256TOOLS.addFrontZero((str.length).toString(2), 64);
str = str + "1" + zeroBits + lengthBits;
//////////////////////////////////////////////////////
//checking length off message
if(str.length > Math.pow(2,64)){
throw "message length greater than 2 ** 64";
}
//////////////////////////////////////////////////////
//parsing the message M into N 512 bit block
//////////////////////////////////////////////////////
var M = [];
for(var ib=0; ib<str.length; ib+=512){
var tempa = [];
for(var j=0; j < 512; j+=32){
tempa.push(str.substr(ib+j,32));
}
M.push(tempa);
}
//////////////////////////////////////////////////////
//main loop goes here!
var a, b, c, d, e, f, g, h, t1, t2;
for(var i=0; i<M.length; i++){
//Message schedule have length of 64
var W = [];
var temp;
//prepare for message diggest,, compression etc...
//////////////////////////////////////////////////////
for(var tb=0; tb<64; tb++){
if(tb < 16){
W.push(parseInt(M[i][tb], 2) % Math.pow(2,32));
}else{
temp = (sha256TOOLS.omega1(W[tb-2]) + W[tb-7] + sha256TOOLS.omega0(W[tb-15]) + W[tb-16]) % Math.pow(2,32);
W.push(temp);
}
}
//////////////////////////////////////////////////////
//real computation between
//ints mod 2 ** 32
//////////////////////////////////////////////////////
a = H[0];
b = H[1];
c = H[2];
d = H[3];
e = H[4];
f = H[5];
g = H[6];
h = H[7];
for(var t=0; t<64; t++){
t1 = (h + sha256TOOLS.sigma1(e) + sha256TOOLS.ch(e,f,g) + K[t] + W[t]) % Math.pow(2,32);
t2 = (sha256TOOLS.sigma0(a) + sha256TOOLS.maj(a,b,c)) % Math.pow(2,32);
h = g;
g = f;
f = e;
e = (d + t1) % Math.pow(2,32);
d = c;
c = b;
b = a;
a = (t1 + t2) % Math.pow(2,32);
}
H[0] = (a + H[0]) % Math.pow(2,32);
H[1] = (b + H[1]) % Math.pow(2,32);
H[2] = (c + H[2]) % Math.pow(2,32);
H[3] = (d + H[3]) % Math.pow(2,32);
H[4] = (e + H[4]) % Math.pow(2,32);
H[5] = (f + H[5]) % Math.pow(2,32);
H[6] = (g + H[6]) % Math.pow(2,32);
H[7] = (h + H[7]) % Math.pow(2,32);
}
//////////////////////////////////////////////////////
var output = "";
for(var ic=0; ic<8; ic++){
var tempb = (H[ic] >>> 0).toString(16);
output += (sha256TOOLS.addFrontZero(tempb, 8));
}
return output;
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T10:56:59.183",
"Id": "458962",
"Score": "1",
"body": "Try to replace comments with function calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T11:21:10.270",
"Id": "458965",
"Score": "1",
"body": "`var a, b, c, d, e, f, g, h, t1, t2;` Why not use an array like you did for `H`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T22:22:22.737",
"Id": "462884",
"Score": "0",
"body": "SHA-256 is specified to work on bits (or rather bytes for most implementations). Any character encoding / decoding should be separate from the SHA-256 functionality itself. Furthermore, any sensible SHA-256 implementation should implement an `update` method to allow it to process data piecemeal. This is really important especially if the input data is not present in total in the first place (authenticating multiple fields, for instance, or implementing HMAC)."
}
] |
[
{
"body": "<h2>Bug</h2>\n<p>JavaScript strings are Unicode. Your code assumes that the characters in the string are less than 256. If a character is over 256 the resulting binary encoded string will be the wrong length and the hash will fail.</p>\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\" rel=\"nofollow noreferrer\">Typed arrays</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView\" rel=\"nofollow noreferrer\"><code>DataView</code></a></h2>\n<p>There is no need to convert the numbers to a string of zeros and ones. The conversion is a massive CPU overhead, chews up RAM (16bytes for every character) and there is a lot of additional code converting to and from that string.</p>\n<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\" rel=\"nofollow noreferrer\">typed arrays</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView\" rel=\"nofollow noreferrer\"><code>DataView</code></a> to pack the string into 32Bit integers. The arrays, apart from <code>Uint8ClampedArray</code> will automatically mask the number as they are written so you do not need to do all the <code>% (2 ** 32)</code> operations.</p>\n<p>The max string length in JS is <span class=\"math-container\">\\$2^{53}\\$</span> the check you do is a little overkill as just to build a string of size <span class=\"math-container\">\\$2^{64}\\$</span> would take many 100s of years on a top end machine.</p>\n<h2>Minor points</h2>\n<ul>\n<li>You can pad a string with zeros using <code>String.padStart</code>. eg <code>binStr = number.toString(2).padStart(32, "0");</code></li>\n<li>Use the power operator <code>**</code> rather than <code>Math.pow</code>. eg <code>Math.pow(2, 32) === 2 ** 32</code></li>\n<li>Avoid repeating the same calculation. eg Create a constant <code>const int32Mod = 2 ** 32</code> to hold the modulo rather than calculate it every time</li>\n</ul>\n<h2>Rewrite</h2>\n<p>I started from scratch and used typed arrays and a few other methods to speed things up. The rewrite will create a hash in about 1/15th the time and uses a lot less memory.</p>\n<p>Rather than use the class syntax to create the tools (which is not secure) I have encapsulated the tools and hash function via closure to prevent interception of any data to be hashed.</p>\n<p>The function using the <code>Uint8Array</code> will mask out the top 8 bits of Javascripts string characters. It would be simple to modify to allow for the hash to work on the full 16bits per character using <code>Uint16Array</code></p>\n<pre><code>const sha256 = (() => {\n const stringFillArray = (str, arr, i = 0) => { while(i < str.length) { arr[i] = str.charCodeAt(i++) } }\n const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];\n const K = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];\n const ch = (x, y, z) => (x & y) ^ (~x & z);\n const maj = (x, y, z) => (x & y) ^ (x & z) ^ (y & z);\n const sigma0 = x => (((x >>> 2) | (x << 30)) ^ ((x >>> 13) | (x << 19)) ^ ((x >>> 22) | (x << 10)));\n const sigma1 = x => (((x >>> 6) | (x << 26)) ^ ((x >>> 11) | (x << 21)) ^ ((x >>> 25) | (x << 7)));\n const omega0 = x => (((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3));\n const omega1 = x => (((x >>> 17) | (x << 15)) ^ ((x >>> 19) | (x << 13)) ^ (x >>> 10));\n const buf32 = new Array(64);\n const hTemp = new Int32Array(8);\n const totals = new Int32Array(2);\n const o1 = omega0, o2 = omega1, s1 = sigma0, s2 = sigma1, t = hTemp, b = buf32; // Aliases\n\n const hashIt = string => {\n var i = 0, j, result = [];\n const hashed = new Uint32Array(H);\n const packChunk = i => o2(b[i - 2]) + b[i - 7] + o1(b[i - 15]) + b[i - 16];\n const hashVals = (i = 0) => {\n while (i < 64) {\n totals[0] = t[7] + s2(t[4]) + ch(t[4], t[5], t[6]) + K[i] + b[i++];\n totals[1] = s1(t[0]) + maj(t[0], t[1], t[2]);\n t[7] = t[6];\n t[6] = t[5];\n t[5] = t[4];\n t[4] = t[3] + totals[0];\n t[3] = t[2];\n t[2] = t[1];\n t[1] = t[0];\n t[0] = totals[0] + totals[1];\n }\n };\n const sumVals = (i = 0) => { while (i < 8) { hashed[i] = t[i] + hashed[i++] } };\n const stringBuf = new ArrayBuffer(((string.length / 64 | 0) + 1) * 64);\n const stringView = new DataView(stringBuf);\n const bytes = new Uint8Array(stringBuf);\n const words = new Int32Array(stringBuf);\n\n stringFillArray(string, bytes);\n bytes[string.length] = 0x80;\n stringView.setUint32(bytes.length - 4, string.length * 8);\n while (i < words.length) {\n j = 0;\n while (j < 16) { buf32[j] = stringView.getInt32((i + (j++)) * 4) }\n while (j < 64) { buf32[j] = packChunk(j++) }\n hTemp.set(hashed);\n hashVals();\n sumVals();\n i += 16;\n }\n\n i = 0;\n while (i < 8) { result[i] = hashed[i++].toString(16).padStart(8, "0") }\n return result.join("");\n };\n return str => hashIt(str);\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-27T22:28:54.013",
"Id": "462885",
"Score": "0",
"body": "I've placed a remark about the encoding / update functionality [below the question](https://codereview.stackexchange.com/questions/234662/sha256-javascript-implementation#comment462884_234662) that may be interesting to you as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T03:44:07.423",
"Id": "234718",
"ParentId": "234662",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "234718",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T10:08:45.130",
"Id": "234662",
"Score": "3",
"Tags": [
"javascript",
"cryptography",
"hash-map"
],
"Title": "SHA256 javascript implementation"
}
|
234662
|
<p>I have created like this validator for reactive form, all working but I think I used so many statements, can somebody help me to make proper validation</p>
<p>Here is my validator</p>
<pre><code>export function validateIfOneIsRequired(): ValidatorFn {
return function validateIfOneIsRequired(formGroup: FormGroup) {
const startTime = formGroup.controls.startTime.value;
const endTime = formGroup.controls.endTime.value;
if (startTime === '' && endTime === '') {
return null;
}
if (startTime && endTime) {
return null;
}
if (!startTime && endTime) {
return { startTimeIsRequired: OperationalTime.startTimeIsRequired };
}
if (startTime && !endTime) {
return { endTimeIsRequired: OperationalTime.endTimeIsRequired };
}
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T12:41:11.820",
"Id": "458970",
"Score": "0",
"body": "Please [edit] your question and elaborate what this code exactly is supposed to do, and how it is used in context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T12:43:46.810",
"Id": "458971",
"Score": "0",
"body": "if you look the code you will see that this is validator for reactive forms? it should validate if one of fields is required"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T12:39:10.450",
"Id": "234665",
"Score": "1",
"Tags": [
"typescript",
"angular-2+"
],
"Title": "Custom validator for reactive forms angular"
}
|
234665
|
<p>I am trying to make a function for floating point numbers comparison.<br>
The goal is to "evaluate" all operators in single function: >, >=, =, <=, <.
If X>Y, then F>0. If X==Y, F==0. If X<=Y, F<=0 etc (where F is returned value).<br>
I took a piece of code from <a href="https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon" rel="nofollow noreferrer">numeric limits</a>. First thing I changed, in scaling of epsilon, <code>fabs(x+y)</code> to <code>fabs(x)+fabs(y)</code> (because if <code>x=-y</code>, we would be comparing diff to 0; which probably would work fine, but sounds kinda stupid). I've also seen an approach using <code>max(fabs(x), fabs(y))</code>, can we say that one of them is better than the others?<br>
Third parameter, DecadesOfInAccuracy, means how many digits above epsilon() should be ignored.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <limits>
#include <iostream>
template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, int>::type
cmp(T x, T y, unsigned int doia = 0)
{
std::cout << "X: " << x << std::endl;
std::cout << "Y: " << y << std::endl;
std::cout << "D: " << fabs(x - y) << std::endl;
std::cout << "M: " << std::numeric_limits<double>::min() * pow(10, doia+1) << std::endl;
std::cout << "E: " << std::numeric_limits<T>::epsilon() * (fabs(x) + fabs(y)) * pow(10, doia + 1) << std::endl;
if (fabs(x - y) < std::numeric_limits<double>::min() * pow(10, doia + 1))
return 0;
bool ltoeq = (x - y) <= std::numeric_limits<T>::epsilon() * (fabs(x)+fabs(y)) * pow(10, doia + 1);
bool gtoeq = (y - x) <= std::numeric_limits<T>::epsilon() * (fabs(x) + fabs(y)) * pow(10, doia + 1);
std::cout << "L: " << ltoeq << std::endl;
std::cout << "G: " << gtoeq << std::endl;
return gtoeq - ltoeq;
}
int main()
{
std::cout.precision(std::numeric_limits<double>::max_digits10 + 5);
double x = 0.0001000000000000001;
double y = 0.0001;
int res = cmp(x, y, 0);
std::cout << res << std::endl << std::endl;
if (res > 0)
std::cout << "X>Y" << std::endl;
if (res >= 0)
std::cout << "X>=Y" << std::endl;
if (res == 0)
std::cout << "X==Y" << std::endl;
if (res <= 0)
std::cout << "X<=Y" << std::endl;
if (res < 0)
std::cout << "X<Y" << std::endl;
return 0;
}
</code></pre>
<p>It "correctly" returns equality for pairs like <code>0.0001000000000000001; 0.0001</code>, <code>1.0-4*0.2; 0.2</code>, <code>0; -0</code>, <code>100000000000.0001; 100000000000</code>.<br>
Is there something I forgot to consider, or maybe something can be simplified? (of course except couts, which will be removed :P).<br>
I am using VS2019 if that matters.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T14:20:35.477",
"Id": "458973",
"Score": "0",
"body": "Welcome to code review where we review working code to provide suggestions on how the code can be improved. What is the expected output? Is this code working as expected? Exactly how many relations to expect to be output at the end. If this code is not working as expected then it is off-topic for the code review site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T14:30:35.813",
"Id": "458976",
"Score": "0",
"body": "It works as expected for these examples. I need a way to test much more cases or someone to evaluate if the code will always work. Expected output is on the beginning. Positive if x is definitely smaller than y, 0 for equal and negative if x is definitely greater than y."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T14:36:23.337",
"Id": "458978",
"Score": "0",
"body": "Sorry for being obvious but to add more test cases make a struct with test data and then have an array or vector of those structs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:56:01.043",
"Id": "459024",
"Score": "0",
"body": "@pacmaninbw I did some testing, function works perfectly in range e308 => ~e-294 (for max precision). You can see the output here: https://github.com/herhor67/C-C-/tree/master/float_comp Unfortunately it can't compare to 0.0, which is most desired for me. Maybe I should add a special case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T23:24:31.480",
"Id": "459029",
"Score": "0",
"body": "Now it seems that the thread would fit better at stack overflow..."
}
] |
[
{
"body": "<blockquote>\n <p>Is there something I forgot to consider</p>\n</blockquote>\n\n<p><strong>Overflow</strong></p>\n\n<p><code>fabs(x) + fabs(y)</code> is prone to overflow, even if mathematically <code>epsilon() * (fabs(x) + fabs(y)) * pow(10, doia + 1)</code> is representable as a <code>T</code>, resulting in incorrect results.</p>\n\n<p>I'd expect <code>cmp(T x, T y, unsigned int doia = 0)</code> to work over the entire range of <code>x,y</code>.</p>\n\n<pre><code>// alternative\n(fabs(x)/2 + fabs(y)/2) * (epsilon() * pow(10, doia + 1) * 2)\n</code></pre>\n\n<p><strong>Not-a-number</strong></p>\n\n<p>The generation of <code>gtoeq, ltoeq</code> are 0 when either/both <code>x</code> or <code>y</code> are a <em>not-a-number</em>. Thus code returns 0, incorrectly implying near equality. Perhaps return something to indicate more that 3 conditions like a 4-bit (==,>,<,not comparable) or a <code>double</code> -1,0,1,NAN.</p>\n\n<p><strong>Precision</strong></p>\n\n<p>The <code>+ 1</code> in <code>doia + 1</code> does not well allow code to just use <code>epsilon</code>, but minimally must use <code>10 * epsilon</code>. Consider dropping the <code>+ 1</code>.</p>\n\n<p>Rather than an integer indicating some power-of-ten * epsilon, consider simply using the desired precision or <code>n * epsilon()</code>. For me I'd rather use a power-of-2.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-20T22:35:19.987",
"Id": "235922",
"ParentId": "234667",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T13:25:11.387",
"Id": "234667",
"Score": "0",
"Tags": [
"c++",
"floating-point"
],
"Title": "Function for comparing floating point numbers"
}
|
234667
|
<p>The problem is: </p>
<blockquote>
<p>Given an undirected graph represented as an adjacency matrix and an
integer k, write a function to determine whether each vertex in the
graph can be coloured such that no two adjacent vertices share the same
colour using at most k colours.
Source: <a href="https://www.dailycodingproblem.com/" rel="nofollow noreferrer">https://www.dailycodingproblem.com/</a></p>
</blockquote>
<p>The proposed solution uses a backtracking algorithm (<a href="https://www.dailycodingproblem.com/blog/graph-coloring" rel="nofollow noreferrer">https://www.dailycodingproblem.com/blog/graph-coloring</a>), but I would like to know if just evaluating the vertice degree is enough (source: <a href="https://youtu.be/LUDNz2bIjWI?t=169" rel="nofollow noreferrer">https://youtu.be/LUDNz2bIjWI?t=169</a>). </p>
<pre><code> boolean canBeColored(int[][] adjacencyMatrix, int colors) {
for (int row = 0; row < adjacencyMatrix.length; row++) {
int degree = 0;
for (int column = 0; column < adjacencyMatrix[row].length; column++) {
if (adjacencyMatrix[row][column] == 1) {
degree++;
}
}
if (degree > colors) {
return false;
}
}
return true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T14:32:03.977",
"Id": "458977",
"Score": "0",
"body": "What programming language is this? Where is the rest of the program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T14:41:23.507",
"Id": "458979",
"Score": "0",
"body": "It is Java, and this is the whole program."
}
] |
[
{
"body": "<p>It is not. Consider a triangle graph which has tree nodes and three edges. All vertices has degree two but three colors are required to color it. Your function would fail for that input. </p>\n\n<p>In fact, the problem is NP-complete meaning that it is not known if an efficient algorithm can be constructed for solving it. So if you can do it, you'll win fame and fortune and also a very large monetary prize.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T15:25:39.947",
"Id": "234697",
"ParentId": "234668",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234697",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T13:33:40.110",
"Id": "234668",
"Score": "0",
"Tags": [
"java",
"graph"
],
"Title": "Graph degree as solution for undirected graph paint"
}
|
234668
|
<p>I'm learning object oriented programming and am still trying to understand the best way to structure a class for modularity and attempting to follow DRY principles. I currently created a class containing multiple requests that share the same <code>self.reponse</code> block repeatedly. I am not sure the best way to abstract this outside of each function call since I am also returning the <code>response</code> object within each method.</p>
<p>My code currently looks like this: </p>
<pre><code>import requests
import urllib3
import logging
import re
from itertools import zip_longest
log = logging.getLogger()
server = "https://example.com"
organization = "/example/"
username = "example@example.com"
PAT = "xxxxxxxxxxxxxxxxxxxxx"
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class InvokeRequest():
def __init__(self):
self.server = server + organization
# Get All Repositories
def getRepositories(self, project):
self.URL = self.server + project + "/_apis/git/repositories"
self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
return self.response.json()
# Get All Build Definitions
def getBuildDefinitions(self, project):
self.URL = self.server + project + "/_apis/build/definitions/"
self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
return self.response.json()
# Get Specific Build Definition
def getBuildDefinitionID(self, project, ID):
self.URL = self.server + project + "/_apis/build/definitions/" + str(ID)
self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
return self.response.json()
# Get All Release Definitions
def getReleaseDefinitions(self, releaseID):
self.URL = self.server + releaseID + "/_apis/git/releaseID"
self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
return self.response.json()
request = InvokeRequest()
repos = request.getRepositories("DevOps")
list_of_repos = []
for repo in repos["value"] or []:
list_of_repos.append(repo["name"])
buildDefinitions = request.getBuildDefinitions("DevOps")
build_definition_IDs = []
build_pipeline_names = []
for build in buildDefinitions["value"]:
if build["queueStatus"] == "enabled": # Skip over disabled builds
build_definition_IDs.append(build["id"])
build_pipeline_names.append(build["name"])
associated_build_repos = [] # Repos containing an associated build pipeline
for ID in build_definition_IDs:
buildDefinition = request.getBuildDefinitionID("DevOps", ID)
log.debug(buildDefinition["repository"].get("name"), "has pipeline")
try:
associated_build_repos.append(buildDefinition["repository"].get("name"))
except KeyError as e:
log.error(e)
</code></pre>
<p>For now, I am only passing a single project <code>"DevOps"</code>, however, this will change in the future. I want to find a way to prevent repeating this specific block of code:</p>
<pre><code>self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
return self.response.json()
</code></pre>
<p>I have considered creating a base class called <code>InvokeRequestConfig()</code> or something similar to create the setup of the server and response object, that way I could inherit that class in <code>InvokeRequest()</code>. however I think that adds a lot of complexity that might not be necessary.</p>
<p>What is the best way to reuse the code above to make it more modular and follow best practices of OOP and DRY?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T14:23:57.083",
"Id": "458974",
"Score": "0",
"body": "All code should be DRY whether it is Object Oriented or not, Object Oriented code should be SOLID https://en.wikipedia.org/wiki/SOLID."
}
] |
[
{
"body": "<p>All the methods in <code>InvokeRequest</code> are basically the same. The only part that differs is the URL. Just pass that in instead of passing in the parts of the URL and constructing the URL in the function.</p>\n\n<p>Before I show the function that I came up with though, I'll note that there's no reason <code>InvokeRequest</code> should be a class, and there's also no reason that <code>self.URL</code> and <code>self.response</code> in those methods should be instance attributes. I'm far from practiced in OOP, but making arbitrary bits of code into classes isn't helpful. <em>If</em> you were passing the <code>self.server</code> data into the constructor, then <em>maybe</em> there would be some justification. As it stands now though, I'm going to get rid of the class and instance attributes.</p>\n\n<p>To start out with, here's the basic part that was repeated in all the methods:</p>\n\n<pre><code>def get_response(url):\n response = requests.get(url, auth=(username, PAT), verify=False)\n return response.json()\n</code></pre>\n\n<p>It now expects that the <code>url</code> will be passed in like I mentioned. You can ease making the URL though using a helper:</p>\n\n<pre><code>def build_url(*parts):\n return BASE_URL + \"\".join(parts)\n</code></pre>\n\n<p>If you haven't encountered var-args before, <code>*parts</code> just means that the function accepts as many arguments as you want, and bundles them into a tuple.</p>\n\n<p>Now you can write:</p>\n\n<pre><code>json = get_response(build_url(project, \"/_apis/git/repositories\")) # Was getRepositories\njson = get_response(build_url(releaseID, \"/_apis/git/releaseID\")) # Was getReleaseDefinitions\njson = get_response(build_url(project, \"/_apis/build/definitions/\", str(ID))) # Was getBuildDefinitionID\n</code></pre>\n\n<p>You could also put the call to <code>build_url</code> inside <code>get_response</code> and have <code>*parts</code> as the parameter to <code>get_response</code>:</p>\n\n<pre><code>def get_response(*parts):\n url = build_url(*parts)\n response = requests.get(url, auth=(username, PAT), verify=False)\n return response.json()\n\njson = get_response(project, \"/_apis/git/repositories\")\njson = get_response(releaseID, \"/_apis/git/releaseID\")\njson = get_response(project, \"/_apis/build/definitions/\", str(ID))\n</code></pre>\n\n<p>Which you want to use depends on if <code>get_response</code> will always use a URL returned by <code>build_url</code>, or if it can differ.</p>\n\n<p>You could wrap the calls to <code>get_response</code> in some functions too to avoid needing to manually put the URL together each time:</p>\n\n<pre><code>def get_build_definition_ID():\n return get_response(project, \"/_apis/build/definitions/\", str(ID))\n</code></pre>\n\n<hr>\n\n<p>Also note the naming convention I used. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">Python uses snake_case</a>, not camelCase.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T16:57:12.450",
"Id": "234672",
"ParentId": "234669",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "234672",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T13:43:54.647",
"Id": "234669",
"Score": "2",
"Tags": [
"python",
"object-oriented"
],
"Title": "Python Making Methods Modular and DRY"
}
|
234669
|
<p>I have created a script for article scraping - it finds title, subtitle, href-link, and the time of publication. Once retrieved, information is converted to a pandas dataframe, and the link for the next page is returned as well (so that it parses page after page). </p>
<p>Everything works as expected, though I feel there should be an easier -or more elegant- way of loading a subsequent page within <code>main</code> function. </p>
<hr>
<pre class="lang-py prettyprint-override"><code>import requests
import pandas as pd
from bs4 import BeautifulSoup
from time import sleep
def read_page(url):
r = requests.get(url)
return BeautifulSoup(r.content, "lxml")
def news_scraper(soup):
BASE = "https://www.pravda.com.ua"
container = []
for i in soup.select("div.news.news_all > div"):
container.append(
[
i.a.text, # title
i.find(class_="article__subtitle").text, # subtitle
i.div.text, # time
BASE + i.a["href"], # link
]
)
dataframe = pd.DataFrame(container, columns=["title", "subtitle", "time", "link"])
dataframe["date"] = (
dataframe["link"]
.str.extract("(\d{4}/\d{2}/\d{2})")[0]
.str.cat(dataframe["time"], sep=" ")
)
next_page = soup.select_one("div.archive-navigation > a.button.button_next")["href"]
return dataframe.drop("time", axis=1), BASE + next_page
def main(START_URL):
print(START_URL)
results = []
soup = read_page(START_URL)
df, next_page = news_scraper(soup)
results.append(df)
while next_page:
print(next_page)
try:
soup = read_page(next_page)
df, next_page = news_scraper(soup)
results.append(df)
except:
next_page = False
sleep(1)
return pd.concat([r for r in results], ignore_index=True)
if __name__ == "__main__":
df = main("https://www.pravda.com.ua/archives/date_24122019/")
assert df.shape == (120, 4) # it's true as of today, 12.26.2019
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:11:25.940",
"Id": "459006",
"Score": "0",
"body": "Why do you have a `sleep(1)` in the for loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:16:56.843",
"Id": "459008",
"Score": "0",
"body": "Note, the last consequent page ends with `<a href=\"/archives/\" class=\"button button_next\">...</a>` link, that assigns `/archives/` to `next_page` . How are you handling that case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:30:39.357",
"Id": "459009",
"Score": "0",
"body": "@Zchpyvr Since I want to scrape a lot of pages, I thought that making a pause between requests would be necessary to avoid getting banned"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:32:26.080",
"Id": "459010",
"Score": "0",
"body": "@RomanPerekhrest Regarding `archives` I didn't think it all through. Since `/archives` would throw an error if I tried to scrape it with `news_scraper` function, I thought I'd just stop at that point and set `next_page` to `False` to quit `while` loop"
}
] |
[
{
"body": "<h3><em>Optimization and restructuring</em></h3>\n\n<p><em>Function's responsibility</em></p>\n\n<p>The initial approach makes the <code>read_page</code> function depend on both <code>requests</code> and <code>BeautifulSoup</code> modules (though <code>BeautifulSoup</code> functionality/features is not actually used there). Then, a <code>soup</code> instance is passed to <code>news_scraper(soup)</code> function.<br>To reduce dependencies let <code>read_page</code> function extract the remote webpage and just return its contents <code>r.content</code>. That will also uncouple <code>news_scraper</code> from <code>soup</code> instance arguments and allow to pass any markup content, making the function more unified.</p>\n\n<hr>\n\n<p><em>Namings</em></p>\n\n<p><code>BASE = \"https://www.pravda.com.ua\"</code> within <code>news_scraper</code> function is essentially acting like a local variable. But considering it as a constant - it should be moved out at top level and renamed to a meaningful <strong><code>BASE_URL = \"https://www.pravda.com.ua\"</code></strong>.</p>\n\n<p><code>i</code> is not a good variable name to reflect a document element in <code>for i in soup.select(\"div.news.news_all > div\")</code>. Good names are <code>node</code>, <code>el</code>, <code>atricle</code> ...</p>\n\n<p>The <code>main</code> function is better renamed to <strong><code>news_to_df</code></strong> to reflect the actual intention.<br><code>main(START_URL)</code> - don't give arguments uppercased names, it should be <code>start_url</code>.</p>\n\n<hr>\n\n<p><em>Parsing news items and composing <code>\"date\"</code> value</em></p>\n\n<p>As you parse webpages (html pages) - specifying <strong><code>html.parser</code></strong> or <strong><code>html5lib</code></strong> (not <code>lxml</code>) is preferable for creating <code>BeautifulSoup</code> instance.</p>\n\n<p>Extracting an <em>article publication time</em> with generic <code>i.div.text</code> would be wrong as a parent node <code>div.article</code> could potentially contain another child <code>div</code> nodes with text content. Therefore, the search query should be more exact: <strong><code>news_time = el.find(class_='article__time').text</code></strong>.<br>Instead of assigning, traversing and dropping <code>\"time\"</code> column and aggregating:</p>\n\n<pre><code>dataframe[\"date\"] = (\n dataframe[\"link\"]\n .str.extract(\"(\\d{4}/\\d{2}/\\d{2})\")[0]\n .str.cat(dataframe[\"time\"], sep=\" \")\n )\n</code></pre>\n\n<p>- that all can be eliminated and the <code>date</code> column can be calculated at once by combining the extracted <em>date</em> value (powered by precompiled regex pattern <strong><code>DATE_PAT = re.compile(r'\\d{4}/\\d{2}/\\d{2}')</code></strong>) and <code>news_time</code> value.</p>\n\n<p>Instead of collecting a list of lists - a more robust way is to collect a list of dictionaries like <code>{'title': ..., 'subtitle': ..., 'date': ..., 'link': ...}</code> as that will prevent confusing the order of values for strict list of column names.</p>\n\n<p>Furthermore, instead of <code>append</code>ing to list, a sequence of needed dictionaries can be efficiently collected with <em>generator</em> function. See the full implementation below. </p>\n\n<hr>\n\n<p><em>The <code>main</code> function (new name: <code>news_to_df</code>)</em></p>\n\n<p>The <code>while next_page:</code> turned to <code>while True:</code>.</p>\n\n<p><code>except:</code> - do not use bare <code>except</code>, at least catch basic <code>Exception</code> class: <strong><code>except Exception:</code></strong>.</p>\n\n<p>The repeated blocks of <code>read_page</code>, <code>news_scraper</code> and <code>results.append(df)</code> statements can be reduced to a single block (see below).<br>One subtle nuance is that the ultimate \"next\" page will have <strong><code>'/archives/'</code></strong> in its <code>a.button.button_next.href</code> path, signaling the end of paging. It's worth to handle that situation explicitly:</p>\n\n<pre><code>if next_page == '/archives/':\n break\n</code></pre>\n\n<hr>\n\n<p>The final optimized solution:</p>\n\n<pre><code>import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport re\n\nBASE_URL = \"https://www.pravda.com.ua\"\nDATE_PAT = re.compile(r'\\d{4}/\\d{2}/\\d{2}')\n\n\ndef read_page(url):\n r = requests.get(url)\n return r.content\n\n\ndef _collect_newsitems_gen(articles):\n for el in articles:\n a_node = el.a\n news_time = el.find(class_='article__time').text\n yield {'title': a_node.text, \n 'subtitle': el.find(class_=\"article__subtitle\").text,\n 'date': f'{DATE_PAT.search(a_node[\"href\"]).group()} {news_time}',\n 'link': f'{BASE_URL}{a_node[\"href\"]}'}\n\n\ndef news_scraper(news_content):\n soup = BeautifulSoup(news_content, \"html5lib\")\n articles = soup.select(\"div.news.news_all > div\")\n next_page_url = soup.select_one(\"div.archive-navigation > a.button.button_next\")[\"href\"]\n df = pd.DataFrame(list(_collect_newsitems_gen(articles)),\n columns=[\"title\", \"subtitle\", \"date\", \"link\"])\n\n return df, f'{BASE_URL}{next_page_url}'\n\n\ndef news_to_df(start_url):\n next_page = start_url\n results = []\n\n while True:\n print(next_page)\n try:\n content = read_page(next_page)\n df, next_page = news_scraper(content)\n results.append(df)\n if next_page == '/archives/':\n break\n except Exception:\n break\n\n sleep(1)\n\n return pd.concat([r for r in results], ignore_index=True)\n\n\nif __name__ == \"__main__\":\n df = news_to_df(\"https://www.pravda.com.ua/archives/date_24122019/\") \n assert df.shape == (120, 4) # it's true as of today, 12.26.2019\n</code></pre>\n\n<p>If printing the final resulting <code>df</code> with <code>print(df.to_string())</code> - the output would look like below (with cutted the middle part to make it a bit shorter):</p>\n\n<pre><code>https://www.pravda.com.ua/archives/date_24122019/\nhttps://www.pravda.com.ua/archives/date_25122019/\nhttps://www.pravda.com.ua/archives/\n title subtitle date link\n0 Голова Закарпаття не зрозумів, за що його звіл... Голова Закарпатської обласної державної адміні... 2019/12/24 23:36 https://www.pravda.com.ua/news/2019/12/24/7235...\n1 Стало відомо коли відновлять будівництво об'єк... На зустрічі представників керівництва ХК Київм... 2019/12/24 22:41 https://www.pravda.com.uahttps://www.epravda.c...\n2 ВАКС продовжив арешт Гримчаку до 14 лютого Вищий антикорупційний продовжив арешт для коли... 2019/12/24 22:25 https://www.pravda.com.ua/news/2019/12/24/7235...\n3 Економічні новини 24 грудня: транзит газу, зни... Про транзит газу, про зниження \"платіжок\", про... 2019/12/24 22:10 https://www.pravda.com.uahttps://www.epravda.c...\n4 Трамп: США готові до будь-якого \"різдвяного по... Президент США Дональд Трамп на тлі побоювань щ... 2019/12/24 22:00 https://www.pravda.com.uahttps://www.eurointeg...\n5 У податковій слідчі дії – електронні сервіси п... Державна податкова служба попереджає, що елект... 2019/12/24 21:55 https://www.pravda.com.ua/news/2019/12/24/7235...\n6 Мінфін знизив ставки за держборгом до 11% річних Міністерство фінансів знизило середньозважену ... 2019/12/24 21:31 https://www.pravda.com.uahttps://www.epravda.c...\n7 Україна викреслила зі списку на обмін ексберку... Російський адвокат Валентин Рибін заявляє, що ... 2019/12/24 21:13 https://www.pravda.com.ua/news/2019/12/24/7235...\n8 Посол: іспанський клуб покарають за образи укр... Посол України в Іспанії Анатолій Щерба заявив,... 2019/12/24 20:45 https://www.pravda.com.uahttps://www.eurointeg...\n9 Міністр енергетики: \"Газпром\" може \"зістрибнут... У Міністерстві енергетики не виключають, що \"Г... 2019/12/24 20:03 https://www.pravda.com.uahttps://www.epravda.c...\n10 Зеленський призначив Арахамію секретарем Націн... Президент Володимир Зеленський затвердив персо... 2019/12/24 20:00 https://www.pravda.com.ua/news/2019/12/24/7235...\n...\n110 Уряд придумав, як захистити українців від шкод... Кабінет міністрів схвалив законопроєкт, який з... 2019/12/25 06:54 https://www.pravda.com.ua/news/2019/12/25/7235...\n111 Кіберполіція та YouControl домовилися про спів... Кіберполіція та компанія YouControl підписали ... 2019/12/25 06:00 https://www.pravda.com.ua/news/2019/12/25/7235...\n112 В окупованому Криму продають прикарпатські яли... У центрі Сімферополя, на новорічному ярмарку п... 2019/12/25 05:11 https://www.pravda.com.ua/news/2019/12/25/7235...\n113 У США схожий на Санту чоловік пограбував банк,... У Сполучених Штатах чоловік з білою, як у Сант... 2019/12/25 04:00 https://www.pravda.com.ua/news/2019/12/25/7235...\n114 У Росії за \"дитячу порнографію\" посадили блоге... Верховний суд російської Чувашії засудив до тр... 2019/12/25 03:26 https://www.pravda.com.ua/news/2019/12/25/7235...\n115 Уряд провів екстрене засідання через газові пе... Кабінет міністрів у вівторок ввечері провів ек... 2019/12/25 02:31 https://www.pravda.com.ua/news/2019/12/25/7235...\n116 Нова стратегія Мінспорту: розвиток інфраструкт... Стратегія розвитку спорту і фізичної активност... 2019/12/25 02:14 https://www.pravda.com.ua/news/2019/12/25/7235...\n117 Милованов розкритикував НБУ за курс гривні та ... Міністр розвитку економіки Тимофій Милованов р... 2019/12/24 01:46 https://www.pravda.com.uahttps://www.epravda.c...\n118 Російські літаки розбомбили школу в Сирії: заг... Щонайменше 10 людей, в тому числі шестеро – ді... 2019/12/25 01:04 https://www.pravda.com.ua/news/2019/12/25/7235...\n119 Ліквідація \"майданчиків Яценка\": Зеленський пі... Президент Володимир Зеленський підписав закон,... 2019/12/25 00:27 https://www.pravda.com.ua/news/2019/12/25/7235...\n</code></pre>\n\n<h3><em>P.S. From Ukraine with love ...</em></h3>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T08:36:10.870",
"Id": "459062",
"Score": "0",
"body": "Thanks so much, I learnt a lot. Дякую :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T08:39:36.607",
"Id": "459065",
"Score": "0",
"body": "@politicalscientist, you're welcome"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T22:57:25.870",
"Id": "234685",
"ParentId": "234675",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "234685",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T17:42:16.637",
"Id": "234675",
"Score": "4",
"Tags": [
"python",
"web-scraping",
"beautifulsoup"
],
"Title": "Scraping next page using BeautifulSoup"
}
|
234675
|
<p>I been writing code for my company for years and there is never any constructive criticism for what I do. I am the only developer here and I would appreciate your opinion on this web page I made. It grabs data from a mssql database and places it in a data table adds some calculations then displays the data in a gridview. I added some css and javascript to make it look better. But is my javascript too sloppy.</p>
<p><a href="https://codepen.io/jrhenderson16/pen/BayZGpY" rel="nofollow noreferrer">link: to codepen.io</a></p>
<pre><code><script>
jQuery(function () {
$(document).ready(function () {
var xd = document.getElementById("datepicker");
var xde = document.getElementById("datepicker2");
var d = new Date();
var d2 = new Date();
var parlen = 0;
var colwidth = document.getElementById('GridView1').rows[0].cells[0].offsetWidth;
d.setDate(d.getDate() - 2);
d2.setDate(d2.getDate() - 1);
xd.value = d.toLocaleDateString();
xde.value = d2.toLocaleDateString();
$("th").css("background-color", "#5FE 1");
$("td:last-child()").css("background-color", "#3FE 1");
$("td:first-child()").css("background-color", "#EFE 1");
parlen = $("th").length;
$("#GridView1 tr td:contains('No Data')").css("background-color", "#EEE 1");
$("tr:nth-child(2)").css("background-color", "#ba67f0");
// $("td:nth-child()").hover($(this).css("background-color", "#EFE 1"), $(this).css("background-color", "#F3E 1"));
$("#GridView1 tr td:nth-of-type(n)").hover(function () {
// var pl = this.parent.length();
var cb = 1 + this.cellIndex;
var rb = 1 + this.parentElement.rowIndex;
if (cb > 1 && cb < parlen) {
$("td:nth-child(" + cb + ")").css("background-color", "yellow");
$("td:nth-child(" + cb + ")").css("font-size", "16px");
$("td:nth-child(" + cb + ")").css("font-bold", "true");
$("tr:nth-child(" + rb + ") td").css("background-color", "yellow");
$("td:last-child()").css("background-color", "#3FE 1");
$("td:first-child()").css("background-color", "#EFE 1");
// $("td:nth-child(" + cb + ")").css("column-width", 2*colwidth);
}
}, function () {
var cb = 1 + this.cellIndex;
var rb = 1 + this.parentElement.rowIndex;
if (cb > 1 && cb < parlen) {
$("td:nth-child(" + cb + ")").css("background-color", "white");
$("td:nth-child(" + cb + ")").css("font-size", "12px");
$("td:nth-child(" + cb + ")").css("font-bold", "true");
$("#GridView1 tr td:contains('No Data')").css("background-color", "#EEE 1");
$("tr:nth-child(" + rb + ") td").css("background-color", "white");
$("tr:nth-child(2) td").css("background-color", "#ba67f0");
$("td:last-child()").css("background-color", "#3FE 1");
$("td:first-child()").css("background-color", "#EFE 1");
}
});
});
</script>
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T22:38:04.330",
"Id": "459027",
"Score": "0",
"body": "Welcome to CodeReview@SE. Can you please try and improve the title of your question following [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) Please check the vertical space in the code block, too."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T17:44:24.917",
"Id": "234676",
"Score": "3",
"Tags": [
"jquery",
"css",
"asp.net",
"jsx"
],
"Title": "Prettified GridView: is this JS code concise?"
}
|
234676
|
<p>I've decided on splitting my environments keeping them in .js files in an environment folder and keep all the sensitive information in .env file (use a third-party module 'DOTENV').</p>
<p>That's what I've come up with but I understand that it's not the best practice and there are a lot of things which should have been implemented in a completely different way but I just lack experience and practice.</p>
<p>At first, I tried to use as more " for loop " as it's possible because as far as I know, it's the fastest way to loop through an object, but in some cases, it was much easier to with "map or filter".</p>
<p>It doesn't look nice to assign data by returning a Promise, and I thought maybe there is a way to get data without a Promise or maybe create a class in place of a function. But the class will still return a Promise as far as I know...</p>
<p>And I am not sure if I used logging right and error handling. That's a completely new thing for me at the moment, but I used "try catch" to catch them and simply logged them on the console and put into a file.</p>
<pre><code>import { readdirSync } from 'fs';
import path from "path";
import { logger } from '../src/utils/logging';
import { merge } from "lodash";
// FIXME: Function returns a Promise with the data.
// It's not comfortable and seem a bad practice - too much code for a simple task,
// and deal with a promise what may outcome in decreasing perfomance
// ( The simplest code, the fastest code )
export let env = getEnvironment().then(
res => { return res },
err => logger.error(err)
);
// TODO: Rewrite this function into a class Environment to keep it organized and implement ES6 standart
async function getEnvironment() {
const mode = process.env.NODE_ENV || 'development';
const rootPath = process.cwd();
const folder = 'environment';
const loadEnvironments = () => {
// Getting the list of available environments in the "environment" folder,
// at the same time excluding index.js file
const list = readdirSync(path.join(rootPath, folder)).filter(file => !/(?=^(index.js))/i.test(file));
const parameters = {};
// Loading the files found in the folder,
// merging them with the help of a "lodash" library
// just to get one common Object with all possible parameters from all found environments
const loaded = list.map(fileName => {
let name = fileName.split('.')[0];
let loadedFile = require(path.join(rootPath, folder, fileName));
const file = loadedFile[name];
merge(parameters, { ...file });
return loadedFile;
});
// Picking the currect mode out of already loaded ones
const current = { ...loaded.filter(file => file[mode]).map(file => file[mode])[0] };
// Returning an object with all parameters
return {
parameters,
current
}
};
const environments = loadEnvironments();
const environment = {} = looping(environments.parameters, environments.current);
function looping(obj, values) {
const collection = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] !== 'object') {
try {
if (values.hasOwnProperty(key)) {
// By a recursive function run through all parameters,
// transforming the keys to uppercased,
// assigning value to 'obj' (file containing all the parameters)
// from the current mode
collection[key.toUpperCase()] = values[key];
} else {
// if there is no such a key in the current mode,
// 'null' is assigned
collection[key.toUpperCase()] = null;
}
} catch (e) {
logger.error(` Missing parameter "${key.toUpperCase()}" in ${mode} mode!!!`);
}
} else {
// Recursing through the object and the nested objects
collection[key.toUpperCase()] = looping(obj[key], values[key]);
}
}
}
return collection;
}
// When parameters are ready,
// the current mode is assigned
environment["MODE"] = mode;
return environment;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T17:46:42.487",
"Id": "234677",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"api"
],
"Title": "Splitting environments: prod and dev modes"
}
|
234677
|
<p>I don't have much experience with testing but I'm trying to make it part of my routine to develop better software.</p>
<p>The class below is a service class in Laravel. It needs to save a record on the database, saving the customer's <code>customer_id</code>, a route (<code>location_id_from</code> and <code>location_id_to</code>) and which location to bill (<code>location_id_bill</code>). The billing location can be null, in which case it will try to determine which one to use.</p>
<p>The code works, but I don't see how to completely unit test the <code>newJob</code> function. From what I've learned so far, I could replace the static methods <code>whereId</code> with an injected repository in the constructor.</p>
<p>Regarding the validation, I'm currently doing the validation, and if it doesn't passes, it will throw an exception with all errors messages.</p>
<p>So:</p>
<ul>
<li>how to test the actual job creation without touching the database</li>
<li>is there a better way to do the validation?</li>
</ul>
<pre class="lang-php prettyprint-override"><code>class Job
{
public function newJob(int $customer_id, int $location_id_from, int $location_id_to, int $location_id_bill): \App\Models\Customer\Job
{
$location_from = Location::whereId($location_id_from);
$location_to = Location::whereId($location_id_to);
if ($location_id_bill === null) {
$location_bill = Location::whereId($location_id_bill);
} else {
$location_bill = new Location();
}
$errors = $this->newJobValidate($customer_id, $location_from, $location_to, $location_bill);
if (count($errors)) {
throw ValidationException::withMessages($errors);
}
$job = new \App\Models\Customer\Job();
$job->customer_id = $customer_id;
$job->location_id_from = $location_from->id;
$job->location_id_to = $location_to->id;
$job->location_id_bill = $location_bill->id;
$job->save();
return $job;
}
private function newJobValidate(int $customer_id, Location $location_from, Location $location_to, Location $location_bill)
{
$errors = [];
if ($location_to->type === Location::TYPE_COMMON && $location_from->type === Location::TYPE_COMMON) {
// same location, but not customer's
$errors[] = __('job.errors.same_location_common');
}
if ($location_to->type === Location::TYPE_CUSTOMER && $location_to->customer->customer_id !== $customer_id ||
$location_from->type === Location::TYPE_CUSTOMER && $location_from->customer->customer_id !== $customer_id) {
$errors[] = __('job.errors.location_doesnt_belong_to_customer');
}
if ($location_bill->id === null) {
if ($location_to->type === Location::TYPE_CUSTOMER && $location_from->type === Location::TYPE_CUSTOMER) {
$errors[] = __('job.errors.must_select_bill_location');
} elseif ($location_from->type === Location::TYPE_CUSTOMER) {
$location_bill->id = $location_from->id;
} else {
$location_bill->id = $location_to->id;
}
}
if ($location_bill->id !== $location_from->id && $location_bill->id !== $location_to->id) {
$errors[] = __('job.errors.bill_location_different');
}
return $errors;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:05:37.717",
"Id": "460588",
"Score": "0",
"body": "This question reads \"how do I test the job creation without touching the database?\" and as such You may get a better response to this question from [SQA.StackExchange, please read their help page](https://sqa.stackexchange.com/help/asking) before posting there."
}
] |
[
{
"body": "<p>An important question: why don’t you want to touch the database in the test? You have a few different options for getting phpunit to play nicely with a database. Doing so lets you test things more thoroughly as you can do assertions that the data has landed in the database as you expected. </p>\n\n<p>As a starting point, based on what I see in this method, I would recommend adding something along these lines in phpunit.xml within the <code><php></code> tag</p>\n\n<pre><code> <env name=\"DB_DATABASE\" value=\"testing\"/>\n</code></pre>\n\n<p>And create a database lined up with the “testing” value set in <code>DB_DATABASE</code>. These values equate to .env values, so you can add additional <code>DB_USERNAME</code>, etc values as appropriate. </p>\n\n<p>You can use the <code>RefreshDatabase</code> trait to reset migrations within your newly created testing database on each test. That is described at <a href=\"https://laravel.com/docs/6.x/database-testing#resetting-the-database-after-each-test\" rel=\"nofollow noreferrer\">https://laravel.com/docs/6.x/database-testing#resetting-the-database-after-each-test</a> </p>\n\n<p>It looks like you need some Location and Customer data in your database for this job to work. If you don’t already have factories for these models, make some as described at <a href=\"https://laravel.com/docs/6.x/database-testing#writing-factories\" rel=\"nofollow noreferrer\">https://laravel.com/docs/6.x/database-testing#writing-factories</a> </p>\n\n<p>As a starting point you can manually call factories in your test – <code>factory(App\\Customer::class)->create();</code> will put a factory generated customer into your database. If you need three of them, – <code>factory(App\\Customer::class, 3)->create();</code> The factory method returns the created entities, so you can do: </p>\n\n<pre><code> $customer = factory(App\\Customer::class)->create();\n $locations = factory(App\\Location::class, 3)->create();\n newJob(\n $customer->id, \n Arr::get($locations, 0)->id, \n Arr::get($locations, 1)->id, \n Arr::get($locations, 2)->id\n);\n</code></pre>\n\n<p>Now the job should be in your testing.jobs table, and you can make an assertion of that:</p>\n\n<pre><code>$this->assertDatabaseHas(‘jobs’,[\n‘customer_id’ => $customer->id,\n‘location_id_from’ => Arr::get($locations, 0)->id,\n‘location_id_to’ => Arr::get($locations, 1)->id,\n‘location_id_ bill’ => Arr::get($locations, 2)->id,\n]);\n</code></pre>\n\n<p>Yes there’s a some overhead in getting the database incorporated into your test setup and in writing the factory, but the end result is a more thorough test. Worth it, in my opinion. </p>\n\n<p>I hope something here helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:13:56.740",
"Id": "238052",
"ParentId": "234679",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:04:12.350",
"Id": "234679",
"Score": "2",
"Tags": [
"php",
"phpunit"
],
"Title": "More testable record insertion code"
}
|
234679
|
<p>I have a transformer helper function. It reduces over the array and transform key/value pairs. At the end of the loop there is the key 'EXAMPLE1' exists and I should insert two objects after the first and the second array(result) items. Right now, it works as expected, but I have concerns - is it a good approach for using splice inside reduce in my case?</p>
<pre><code> const commonData = Object.entries(settings).reduce((result, [currentKey, currentValue]) => {
if (currentKey === SETTINGS_FIELDS.EXAMPLE1) {
const type = {
key: myKey,
value: myValue,
}
const code = {
key: myKey,
value: myValue,
}
const insertedData = result.splice(2, 0, type, code)
return [...result, ...insertedData]
}
return result.concat({ key: transformToUpperCase(currentKey), value: currentValue })
}, [])
return [...commonData]
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T16:52:25.297",
"Id": "459080",
"Score": "0",
"body": "I don't understand why you're using reduce here. Do you just want to insert these two key/value pairs into the array? Then just use `splice()` on the array directly. Do you want to do it only if the `settings` object contained the key `EXAMPLE1`? Then do it. What do you mean by \"at the end of the loop\"?"
}
] |
[
{
"body": "<p>Looks like you were trying to follow the best practices on not mutating data but this is an overkill:</p>\n\n<ul>\n<li>when processing data locally in a function there's no need to clone the intermediate data</li>\n<li>no need to clone the array in <code>return</code>, it's already a temporary cloned array</li>\n<li><code>reduce</code> is the wrong choice here - at least if you keep its needless duplication of the resultant array in each step - the task is a simple transformation of each element so <code>map()</code> seems a better choice + an additional splice on the special key</li>\n<li><code>insertedData</code> is always an empty array so no need for <code>[...result, ...insertedData]</code></li>\n<li>for consistency, if you use <code>splice</code> and <code>concat</code> then go all the way and use <code>concat</code> instead of array spread as well or switch to array spread instead of concat.</li>\n</ul>\n\n<p>Simplified code using <code>map()</code>:</p>\n\n<pre><code>function foo() {\n\n const commonData = Object.entries(settings).map(([key, value]) => ({\n key: transformToUpperCase(key),\n value,\n }));\n\n if (Object.hasOwnProperty.call(settings, SETTINGS_FIELDS.EXAMPLE1)) {\n commonData.splice(2, 0, {\n key: myKey,\n value: myValue,\n }, {\n key: myKey,\n value: myValue,\n });\n }\n\n return commonData;\n}\n</code></pre>\n\n<p>If you don't override prototype of <code>settings</code> or objects in general the key check can be simplified further: <code>if (SETTINGS_FIELDS.EXAMPLE1 in settings)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T05:59:20.110",
"Id": "235939",
"ParentId": "234680",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T19:37:54.683",
"Id": "234680",
"Score": "2",
"Tags": [
"javascript",
"mapreduce"
],
"Title": "The best way for inserting multiple objects into array"
}
|
234680
|
<p>After using an online tool to convert a PDF <a href="https://pastebin.com/NUpvBNyY" rel="nofollow noreferrer">glossary</a> of English-French cognates to a .txt file, I wanted to write a simple script to extract the cognate pairs and save them to a CSV. I could then import them to my flashcard software (Anki). The .txt file ended up being rather messy, and, as a novice programmer who's new to R, the only solution I found was rather crude. </p>
<p>Feedback on the slice/append calls in 1.) and the <em>hideous</em> indexing in 3.) would be particularly appreciated.</p>
<pre><code>library(tidyverse) # dplyr
glossary <- as_tibble(read.delim("papers/frenchcognates.txt", encoding = "UTF-8", stringsAsFactors = FALSE))
## 1.) Extract cognates and language headings into a table. ##
cognates <- glossary %>%
# Select only the English-French half of the glossary.
slice(1:1872) %>%
# Extract the glossary entries (cognates) and headings ("English" or "French")
filter(str_detect(Glossary, "^[E-F]?[[:lower:]-]+[ \\(to\\)]*$")) %>%
# Language headings are misplaced for certain letters. Delete...#
slice(-543) %>%
slice(-613) %>%
slice(-723)
#...then move for the while-loop later #
cognates <- append(cognates$Glossary,"French", after=551)
cognates <- append(cognates,"French", after=622) # append() coerced the list to character vector
cognates <- append(cognates,"French", after=733)
## 2.) Loop to separate words into two lists by language heading. ##
words <- vector("list", 2)
lang <- 1 # Using the language headers as a gate
for (word in cognates) {
if (word == "English") {
lang <- 1
} else if (word == "French") {
lang <- 2
} else {
words[[lang]] <- c(words[[lang]], word)
}
## 3.) Combine lists into matrix/data frame, then save into CSV. ##
# Regex problem: months in English are capitalized, but aren't in French.
words[[2]] <- words[[2]][!(words[[2]] %in% c("août", "décembre", "mars"))]
words.mtx <- cbind(words[[1]], words[[2]])
# Convert to data frame (add colnames first)
colnames(words.mtx) <- c("english", "french") # add column names
words.df <- as_tibble(words.mtx)
# Save to CSV
write_csv(words.df, "writing/cognates") # folder in my wd
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T21:10:06.260",
"Id": "234683",
"Score": "1",
"Tags": [
"strings",
"regex",
"r"
],
"Title": "Extracting English-French cognates from a messy .txt glossary"
}
|
234683
|
<p>I have a redis caching server. If that caching server is down, my app will query the database directly.</p>
<p>I want to know from the logs if my caching server is not reachable. However, if I add a log error, it would completely spam my logfiles if a high amount of users would try to access data.</p>
<p>As a result, I would like to only log the very first error occurrence, resetting only if no errors occurred for an hour.</p>
<p>Is this a feasable approach at all? If so, please review my implementation:</p>
<pre><code>public class CustomCacheErrorHandler implements CacheErrorHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private long errorOccurred;
private final long ONEHOUR = 3600000;
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
if (errorOccurred < (System.currentTimeMillis() - ONEHOUR))
logger.error("Error while getting cache " + cache.getName() + " for Key " + key);
errorOccurred = System.currentTimeMillis()
}
}
</code></pre>
<p>Using currentTimeMillis over System.nanoTime() and a final long ONEHOUR over TimeUnit.HOURS.toMillis(1) for performance.</p>
<p>Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T01:25:20.477",
"Id": "459052",
"Score": "0",
"body": "An alternate way of doing this is to count the number of identical errors, and then add a line \"Repeats X times.\" after the first error message. This way the frequency of the error is still evident without having to fill a log file with redundant messages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T07:33:53.907",
"Id": "459060",
"Score": "0",
"body": "@markspace at the point \"after the first error message\" you cannot yet know \"repeats X times\". How exactly do you think this should work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T16:36:59.487",
"Id": "459078",
"Score": "0",
"body": "@RolandIllig 1. Read message. 2. String compare with previous message. 3. If same increment counter. 4. If different and counter > 1, insert message \"Repeats X times\". It's not rocket science. I think there's already existing log parsers and other object that do this right now, look around."
}
] |
[
{
"body": "<p>Your code currently checks when the last error occurred. This might not be what you actually want. Assuming that an error occurs every 30 minutes, I would expect to have a log entry every 60 minutes. Your current code produces one log entry at the beginning, and no more log entries after that.</p>\n\n<p>I once wrote similar code, and I separated the code into two Java classes: the <code>Throttler</code> for the actual algorithm and the <code>ThrottledLogger</code> for using the algorithm to throttle log messages.</p>\n\n<p>I'm still happy with that old code, and it had the following additional features:</p>\n\n<ul>\n<li>It allows several events before throttling kicks in.</li>\n<li>When throttling kicks in, that is logged as well (\"further log messages will be suppressed\").</li>\n<li>When throttling has finished, that is logged as well (\"suppressed {} messages\").</li>\n</ul>\n\n<p>With these changes, the log messages do not hide any important information. The throttled logger I used was created like this:</p>\n\n<pre><code>new ThrottledLogger(\n logger,\n 5, // number of allowed messages\n 1, TimeUnit.HOUR // 1 more message every hour\n);\n</code></pre>\n\n<p>With this information you should be able to write the same code as I did. Be sure to write some unit tests for the throttling algorithm, to demonstrate that it works indeed like you want it to work.</p>\n\n<p>If you don't need this additional complexity, you should at least move the <code>errorOccurred =</code> assignment into the body of the <code>if</code> statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:58:25.293",
"Id": "459043",
"Score": "0",
"body": "Thanks for input! The idea of using such a ThrottledLogged is interesting and surely has its place, in my case however I think it would not work, because the message limit would be already be consumed after the first second of my server being down."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T01:01:43.280",
"Id": "459046",
"Score": "0",
"body": "The errorOccured must be outside the if statement, because the method handleCacheGetError is being executed only if the server is down, hence it will update only if the server is down:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T07:29:54.030",
"Id": "459059",
"Score": "0",
"body": "In that case, maybe you need 2 variables: `errorOccurred` and `errorLogged`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T00:01:30.287",
"Id": "234688",
"ParentId": "234687",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-26T23:25:10.943",
"Id": "234687",
"Score": "2",
"Tags": [
"java",
"error-handling",
"spring"
],
"Title": "Java: Only log first error occurrence (with hourly reset)"
}
|
234687
|
<p>I've started to fill my GitHub profile with small applications to educate and showcase my skills. However, I feel like I'm missing something essential, while creating these projects. </p>
<p>Could you take a look at this component, and advice me on how to refactor it? Its purpose is to get Coin Data from an API, and display the chart if the data is present : </p>
<pre><code>import React from 'react';
import {connect} from 'react-redux';
import {formatCrypto} from '../../common/formating';
import ChartContainer from './chartContainer';
class Liquidity extends React.Component {
constructor(props) {
super(props);
this.state = {
chartData: [],
minmaxValues: {},
isLinear: false,
};
};
/***
* @method getDerivedStateFromProps - defines if the chart should be updated, since useEffect
* hook was giving a warning for async component rendering
* @param props - nextProps of the app
* @param state - nextState of the app
* @return {null} - returns null when there is no updates for the current state
*/
static getDerivedStateFromProps({coinsData}, state) {
if (!coinsData) return null;
let parsedChartData = [];
if (coinsData) {
parsedChartData = [{
id: 'CoinMarketCap API response',
data: [...coinsData.map((el) => {
return {
id: el.id,
name: el.name,
marketCap: '$' + formatCrypto(el.quote.USD.market_cap, 3),
volume: '$' + formatCrypto(el.quote.USD.volume_24h, 3),
priceChange: formatCrypto(Math.abs(el.quote.USD.percent_change_24h)) + '%',
x: el.quote.USD.market_cap,
y: el.quote.USD.volume_24h,
z: Math.abs(el.quote.USD.percent_change_24h)
}
})]
}];
}
return {chartData: parsedChartData};
}
swapChart = () => {
this.setState((prevState) => ({isLinear: !prevState.isLinear}));
};
render() {
const {chartData, isLinear} = this.state;
return (
<>
<div className="d-flex justify-content-between">
<h2>Liquidity</h2>
<button
className={'btn btn-primary'}
type="button"
onClick={() => this.swapChart()}
>
Switch to {isLinear ? 'logarithmic' : 'linear'}
</button>
</div>
<ChartContainer chartData={chartData} isLinear={isLinear}/>
</>
)
}
}
const mapStateToProps = (state) => {
const {coinsData} = state.cmcListCallReducer;
return {coinsData};
};
export default connect(mapStateToProps)(Liquidity);
</code></pre>
<p>This component is a part of the largest app I've created so far. The app repo is <a href="https://github.com/An1mus/topcoin" rel="nofollow noreferrer">here</a>, in case you might be interested in a big picture. I will appreciate any kind of critics related to the project in general, since maybe my structure sucks more, than code styling.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T14:56:58.003",
"Id": "459075",
"Score": "1",
"body": "Welcome to code review. You might also want to try to answer a few questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T23:36:10.487",
"Id": "459096",
"Score": "0",
"body": "Sure thing, I would love to, but my skills aren't high enough yet at my opinion. :)"
}
] |
[
{
"body": "<p>You're using redux for state management. The problem with mixing local state and redux state is that component render cycles are asynchronous, which oftentimes can cause finicky race conditions. If you're going to use redux, commit to it. If you aren't using any middlewares like <code>redux-thunk</code>, I highly suggest you do so. Dispatching actions and making api calls are ensured to be synchronous when using thunk actions</p>\n\n<p>Your component is \"responsible\" for too much. It's a violation of the single responsibility principle, makes the component harder to reason, and is [far] more difficult to test. One of the main selling points of redux is the ability to tuck away how data is being passed. It lets you create a separation of concerns and will make your components much easier to reason and maintain. If I were in your position, I would create the following:</p>\n\n<h3>Make your api call inside a redux thunk action, and store the raw values in the store</h3>\n\n<p>Data calls and transfer are ensured to be synchronous. I would place the data in its entirety, just in case you need the raw data elsewhere</p>\n\n<pre><code>getCoinsData = () => async dispatch => {\n coinsData = await // api call\n const parsedCoinsData = coinsData.map((el) => { // Array#map already creates a new array. No need to spread it\n const {\n market_cap,\n volume_24h,\n percent_change_24h,\n percent_change_24h\n } = el.quote.USD\n return {\n id: el.id,\n name: el.name,\n marketCap: market_cap,\n volume24h: volume_24h,\n percentChange24h: percent_change_24h\n }\n })\n dispatch({\n type: SET_COINS_DATA,\n data: parsedCoinsData\n })\n}\n</code></pre>\n\n<h3>Create a selector to create the chart data</h3>\n\n<p>Creating a selector to parse/structure the data for your needs is an easy way to hide how the data is being created for your component to use <em>and</em> be able to hold all of the data in its unadulterated state in your redux store.</p>\n\n<pre><code>getChartData = state => {\n const { coinsData } = state.cmcListCallReducer;\n return [\n {\n id: 'CoinMarketCap API response',\n data: coinsData.map((el) => {\n const {\n id,\n name,\n marketCap,\n volume24h,\n percentChange24h,\n } = el\n return {\n id,\n name,\n marketCap: '$' + formatCrypto(marketCap, 3),\n volume: '$' + formatCrypto(volume24h, 3),\n priceChange: formatCrypto(Math.abs(percentChange24h)) + '%',\n x: marketCap,\n y: volume24h,\n z: Math.abs(percentChange24h)\n }\n })\n }\n ]\n}\n</code></pre>\n\n<p>And then your component would just look like this.</p>\n\n<pre><code>import React from 'react';\nimport { connect } from 'react-redux';\nimport ChartContainer from './chartContainer';\n\nclass Liquidity extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n minmaxValues: {},\n isLinear: false,\n };\n };\n\n swapChart = () => {\n this.setState((prevState) => ({ isLinear: !prevState.isLinear }));\n };\n\n render() {\n const { isLinear } = this.state;\n const { chartData } = this.props\n return (\n <>\n <div className=\"d-flex justify-content-between\">\n <h2>Liquidity</h2>\n\n <button\n className={'btn btn-primary'}\n type=\"button\"\n onClick={() => this.swapChart()}\n >\n Switch to {isLinear ? 'logarithmic' : 'linear'}\n </button>\n </div>\n <ChartContainer chartData={chartData} isLinear={isLinear} />\n </>\n )\n }\n}\n\nconst mapStateToProps = (state) => {\n return { \n chartData: getChartData(state)\n };\n};\n\nexport default connect(mapStateToProps)(Liquidity);\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T21:20:23.427",
"Id": "459263",
"Score": "0",
"body": "This is extremely elaborative, thank you a lot! But could you clarify 2 things shortly, just yes/no would be enough:\n1) If I'm using redux-state I mustn't use state? So for my component, `isLinear` and `minmaxValues` from the state, `should` be taken from `store` instead.\n2) The end result makes component almost for display only. Should I keep my components clean from any kind of computations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T02:29:09.087",
"Id": "459277",
"Score": "0",
"body": "1. Depends on the context. In most cases, redux is the way to go when it comes to handing async data flow. 2. `isLinear` can definitely be kept in local state. It's very much encapsulated within the component. It has no interaction with any outside process. I don't know what `minmaxValues` is, but if it has any possible async behavior when interacting with your api call, then put it in your thunk action"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T20:56:51.807",
"Id": "459363",
"Score": "0",
"body": "I see now, thank you for all the answers!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T04:31:23.977",
"Id": "234773",
"ParentId": "234694",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234773",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T13:55:48.153",
"Id": "234694",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "React app that interacts with CoinMarketCap API"
}
|
234694
|
<h1>Code Review : Could promises be 'chained'?</h1>
<p>I am developing a simple Quote tool for the business-owner to fill in a form (item number, item name, price, etc) and send to the potential customer.</p>
<p>This code review request is in reference to the "view-quote" page, which simply displays a quote that was previously sent. (see pic)</p>
<p><a href="https://i.stack.imgur.com/mAxwz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mAxwz.png" alt="[pic]"></a></p>
<h1>Data Structure</h1>
<p>As you can see, the data is broken up into three tables:</p>
<ol>
<li><strong>Quotes Table:</strong> Holds general info about the quote.</li>
<li><strong>Clients Table:</strong> Holds general client info.</li>
<li><strong>Items Table:</strong> Holds individual quote items.</li>
</ol>
<h1>Fetch-ing The Quote Data</h1>
<p>When a user hits this page, a parameter is passed in the URL (for example):</p>
<pre><code>view-quote.html?quote_id=GL555
</code></pre>
<p>So from here, I needed to query the QUOTES table first.</p>
<p>Within those results, is our CLIENT_ID. Using that, I then query the CLIENTS table.</p>
<p>Lastly, I query the ITEMS table to get all items associated with the QUOTE.</p>
<blockquote>
<p>Did I Break A Promise?</p>
</blockquote>
<p>I am fairly new to writing modern JavaScript, however, I did manage to get this code functioning. But as you will see, I believe this code could be re-factored a number of ways.</p>
<h1>The JavaScript</h1>
<pre><code>// Quotes View - View Model
// +---------------------------------------------------------------------------+
// | View Quote View Model |
// | |
// | view-quote-view-model.js |
// +---------------------------------------------------------------------------+
// | |
// +---------------------------------------------------------------------------+/
let ItemsModel = function (item_number, item_name, item_price, quantity, manufacturer, subtotal) {
this.item_number = item_number;
this.item_name = item_name;
this.item_price = item_price;
this.quantity = quantity;
this.manufacturer = manufacturer;
this.subtotal = subtotal;
}
// GLOBAL PAGE VARIABLES
var gQuoteNumber = $_GET("quote_number");
var gClientId;
var gGrandTotal = 0;
console.log(`Quote Number: ${gQuoteNumber}`);
function ViewQuoteViewModel() {
var self = this; // Scope Trick
/* QUOTE Observables */
self.quote_id = ko.observable();
self.quote_number = ko.observable(gQuoteNumber);
self.quote_date = ko.observable();
self.amount = ko.observable();
self.business_name = ko.observable();
self.notes = ko.observable();
/* CLIENT Observables */
self.client_id = ko.observable();
self.first_name = ko.observable();
self.last_name = ko.observable();
self.email = ko.observable();
self.phone = ko.observable();
self.address = ko.observable();
self.city = ko.observable();
self.state = ko.observable();
self.zip = ko.observable();
self.grand_total = ko.observable(gGrandTotal);
/* ITEMS Observables */
self.items = ko.observableArray();
/* COMPUTED */
self.fullName = ko.computed(function() {
return self.first_name() + " " + self.last_name();
}, self);
/* GET PAGE DATA */
self.getQuote = function (quoteNumber) {
return fetch(apiQuotesOne + gQuoteNumber, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then(handleErrors)
.then(function(response) {
return response.json();
}).then(function(data) {
// Populate Observables
self.quote_id(data[0].id);
self.quote_number(gQuoteNumber);
self.quote_date(data[0].quote_date);
self.amount(data[0].amount);
self.business_name(data[0].business_name);
self.notes(data[0].notes);
self.client_id(data[0].client_id)
// Set Global Variable
gClientId = data[0].client_id;
// GO TO NEXT FUNCTION, GET CLIENT INFORMATION
self.getClient(gClientId);
});
};
self.getClient = function(clientId){
return fetch(apiCustomersOne + gClientId, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then(handleErrors)
.then(function(response) {
return response.json();
}).then(function(data) {
// Populate Observables
console.log(data);
self.first_name(data[0].first_name);
self.last_name(data[0].last_name);
self.email(data[0].email);
self.phone(data[0].phone);
self.address(data[0].address);
self.city(data[0].city);
self.state(data[0].state)
self.zip(data[0].zip)
// GO TO NEXT FUNCTION, GET ITEMS
self.getItems();
});
}
self.getItems = function(quoteId){
return fetch(apiItems + gQuoteNumber, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then(handleErrors)
.then(function(response) {
return response.json();
}).then(function(data) {
// Populate Items Array
var subtotal;
$.each(data,
function (key, val) {
//console.log(val);
subtotal = val.quantity * val.item_price;
gGrandTotal = gGrandTotal + subtotal;
self.grand_total(gGrandTotal);
self.items.push(new ItemsModel(val.item_number,val.item_name, val.item_price, val.quantity, val.manufacturer, subtotal ));
});
});
}
// Kick it off
self.getQuote(gQuoteNumber);
}
ko.applyBindings(new ViewQuoteViewModel());
</code></pre>
<p>...here is my helper function to grab query string parameters:</p>
<pre><code>function $_GET(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
</code></pre>
<p>I got this working by calling one function from inside another. It just feels like "cheating". It feels like bad code.</p>
<p>Could anyone point me in the right direction to clean this up a bit? I am thinking the three calls to the API can be really chained.</p>
<p>Thank you for looking.</p>
<p>PS. I am using KNOCKOUTJS as my MVVM pattern, in case that changes anything.</p>
<p>John</p>
|
[] |
[
{
"body": "<p>Regarding the <code>self</code> \"trick\", don't use it, just switch to arrow functions which preserve <code>this</code>:</p>\n\n<pre><code> this.fullName = ko.computed(() => this.first_name() + ' ' + this.last_name(), this);\n</code></pre>\n\n<p>Regarding the main concern, simply call those functions via .then and pass the data via <code>return</code> in the previous .then handler:</p>\n\n<p>Passing of data:</p>\n\n<pre><code> this.getQuote = quoteNumber => fetchJson(/*foo*/).then(data => {\n // ...............\n return data[0].client_id;\n });\n\n this.getClient = clientId => fetchJson(/*bar*/).then(data => {\n // ................\n return /*bar*/;\n });\n\n this.getItems = quoteId => {\n // ................\n return /*whatever*/;\n };\n</code></pre>\n\n<p>Calling/chaining:</p>\n\n<pre><code> this.getQuote(gQuoteNumber)\n .then(this.getClient) // this is an arrow function that preserves `this`\n .then(this.getItems);\n</code></pre>\n\n<p>fetchJson could be something like:</p>\n\n<pre><code>function fetchJson(url, options) {\n return fetch(url, options).then(r => r.json(), handleErrors);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T05:36:21.463",
"Id": "235938",
"ParentId": "234696",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T14:35:42.807",
"Id": "234696",
"Score": "4",
"Tags": [
"javascript",
"knockout.js"
],
"Title": "Performing asynchronous fetch-es that rely on each's response"
}
|
234696
|
<p>I've become a bit rusty in Java. This is an attempt at brushing up my skills.</p>
<blockquote>
<p>In computer science, merge sort is an efficient, general-purpose,
comparison-based sorting algorithm.</p>
</blockquote>
<h3>Questions</h3>
<ul>
<li>How can I improve my test cases? (TestNG)</li>
<li>I've used Java-11 here, can I use better idioms?</li>
<li>Can this implementation improved for performance?</li>
<li>Can style / readability improved?</li>
</ul>
<h3>Code</h3>
<p><strong>Sorting.java</strong></p>
<pre><code>import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
public class Sorting {
/**
* Day 08 - Merge Sort
*
* @param data data array
* @param comparator comparator of given data type
* @param ascending sort order
* @param <T> data type
* @return sorted array (in place)
*/
public static <T> T[] mergeSort(T[] data, Comparator<T> comparator, boolean ascending) {
Objects.requireNonNull(data);
Objects.requireNonNull(comparator);
if (data.length <= 1) return data;
var actualComparator = ascending ? comparator : comparator.reversed();
return mergeSort(data, actualComparator, 0, data.length - 1);
}
private static <T> T[] mergeSort(T[] data, Comparator<T> comparator, int start, int stop) {
if (start >= stop) return data;
int pivot = start + (stop - start) / 2;
mergeSort(data, comparator, start, pivot);
mergeSort(data, comparator, pivot + 1, stop);
return merge(data, comparator, start, pivot, stop);
}
private static <T> T[] merge(T[] data, Comparator<T> comparator, int start, int pivot, int stop) {
T[] left = Arrays.copyOfRange(data, start, pivot + 1);
T[] right = Arrays.copyOfRange(data, pivot + 1, stop + 1);
int lPos = 0;
int rPos = 0;
int pos = start;
while (lPos < left.length && rPos < right.length) {
if (comparator.compare(left[lPos], right[rPos]) <= 0) {
data[pos++] = left[lPos++];
} else {
data[pos++] = right[rPos++];
}
}
while (lPos < left.length) {
data[pos++] = left[lPos++];
}
while (rPos < right.length) {
data[pos++] = right[rPos++];
}
return data;
}
}
</code></pre>
<p><strong>TestMergeSorting.java</strong></p>
<pre><code>import org.testng.Assert;
import org.testng.annotations.Test;
public class TestMergeSorting {
@Test
public void testMergeSort() {
Assert.assertEquals(asc(6, 5, 9, 3, 2, 1), ar(1, 2, 3, 5, 6, 9));
Assert.assertEquals(asc(1, 1, 1, 1, 2, 1), ar(1, 1, 1, 1, 1, 2));
Assert.assertEquals(asc(2, 1, 1, 1, 1, 2, 1), ar(1, 1, 1, 1, 1, 2, 2));
Assert.assertEquals(asc(1, 1, 1, 1, 1, 2, 1), ar(1, 1, 1, 1, 1, 1, 2));
Assert.assertEquals(asc(3, 2, 1), ar(1, 2, 3));
Assert.assertEquals(asc(1, 2, 3), ar(1, 2, 3));
Assert.assertEquals(asc(2, 0, -1, 2, 1), ar(-1, 0, 1, 2, 2));
Assert.assertEquals(dsc(1, 2, 3), ar(3, 2, 1));
Assert.assertEquals(dsc(3, 2, 1), ar(3, 2, 1));
Assert.assertEquals(dsc(2, 0, -1, 2, 1), ar(2, 2, 1, 0, -1));
Assert.assertEquals(asc(2, 1), ar(1, 2));
Assert.assertEquals(asc(1), ar(1));
Assert.assertEquals(asc(), ar());
Assert.assertEquals(dsc(1), ar(1));
Assert.assertEquals(dsc(), ar());
}
@Test(expectedExceptions = {NullPointerException.class})
public void testNullExcept() {
Sorting.mergeSort(null, Integer::compare, true);
}
private static Integer[] ar(Integer... objects) {
return objects;
}
private static Integer[] asc(Integer... objects) {
return Sorting.mergeSort(objects, Integer::compare, true);
}
private static Integer[] dsc(Integer... objects) {
return Sorting.mergeSort(objects, Integer::compare, false);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>One thing I noticed, the sorting routine is modifying the array and returning the array. I would suggest either make the functions <code>void</code> or create a new array to do the merge in. A sort function with a <code>void</code> return type automatically tells the user that the sort is in place. Where as, a return type of an array, tells the user that a new array is created, but that the original array isn't touched.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T00:12:53.133",
"Id": "234711",
"ParentId": "234698",
"Score": "6"
}
},
{
"body": "<h2>Naming</h2>\n\n<p>Prefer to use conventional names. That is, the same names used by the\n<a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html\" rel=\"nofollow noreferrer\"><code>Arrays</code></a>\nclass in the Java standard library:</p>\n\n<ul>\n<li><code>data => a</code></li>\n<li><code>comparator => c</code></li>\n<li><code>start => fromIndex</code></li>\n<li><code>stop => toIndex</code></li>\n</ul>\n\n<p>I've never seen the center element in merge sort being referred to as\nthe <code>pivot</code>. I think a more fitting name is <code>mid</code>.</p>\n\n<h2>Inclusive start, exclusive end</h2>\n\n<p>It is better to use inclusive start indices and exclusive stop\nindices, matching the convention established by\n<a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#sort(T%5B%5D,int,int,java.util.Comparator)\" rel=\"nofollow noreferrer\"><code>Arrays.sort</code></a>\nand many other array functions in the Java standard library.</p>\n\n<p>This way, if you make your other <code>mergeSort</code> overload public:</p>\n\n<pre><code>public static <T> void mergeSort(T[] a,\n int fromIndex, int toIndex,\n Comparator<T> c) {\n</code></pre>\n\n<p>It becomes very easy for people to use it because the signature\nmatches the <code>Arrays.sort(T[], int, int, Comparator)</code> function.</p>\n\n<h2>Garbage generation</h2>\n\n<p>The two calls to <code>Arrays.copyOfRange</code> in <code>merge</code> creates temporary\narrays which causes unnecessary garbage collection pressure. It is\nmore efficient to preallocate a temporary buffer and then pass that\none around.</p>\n\n<p>I've rewritten your <code>merge</code> function to use such a temporary\nbuffer. It makes the code a little more complex, but I think it is\nworth it.</p>\n\n<p>Modified code with comments removed:</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.Objects;\n\npublic class Sorting {\n public static <T> void mergeSort(T[] a,\n Comparator<? super T> c,\n boolean ascending) {\n Comparator<? super T> actualComparator = ascending ? c : c.reversed();\n mergeSort(a, 0, a.length, actualComparator);\n }\n public static <T> void mergeSort(T[] a,\n int fromIndex, int toIndex,\n Comparator<? super T> c) {\n Objects.requireNonNull(a);\n Objects.requireNonNull(c);\n if (fromIndex > toIndex) {\n throw new IllegalArgumentException(\n \"fromIndex(\" + fromIndex + \") > toIndex(\" + toIndex + \")\");\n }\n if (fromIndex < 0) {\n throw new ArrayIndexOutOfBoundsException(fromIndex);\n }\n if (toIndex > a.length) {\n throw new ArrayIndexOutOfBoundsException(toIndex);\n }\n T[] buf = Arrays.copyOf(a, a.length);\n mergeSortInternal(a, fromIndex, toIndex, c, buf);\n }\n private static <T> void mergeSortInternal(T[] a,\n int fromIndex, int toIndex,\n Comparator<? super T> c,\n T[] buf) {\n if (toIndex - fromIndex <= 1)\n return;\n int mid = fromIndex + (toIndex - fromIndex) / 2;\n mergeSortInternal(a, fromIndex, mid, c, buf);\n mergeSortInternal(a, mid, toIndex, c, buf);\n merge(a, fromIndex, mid, toIndex, c, buf);\n }\n private static <T> void merge(T[] a,\n int fromIndex, int mid, int toIndex,\n Comparator<? super T> c,\n T[] buf) {\n System.arraycopy(a, fromIndex, buf, fromIndex, toIndex - fromIndex);\n int lPos = fromIndex;\n int rPos = mid;\n int lEnd = mid;\n int rEnd = toIndex;\n int pos = fromIndex;\n while (lPos < lEnd && rPos < rEnd) {\n if (c.compare(buf[lPos], buf[rPos]) <= 0) {\n a[pos++] = buf[lPos++];\n } else {\n a[pos++] = buf[rPos++];\n }\n }\n while (lPos < lEnd) {\n a[pos++] = buf[lPos++];\n }\n while (rPos < rEnd) {\n a[pos++] = buf[rPos++];\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T20:05:58.813",
"Id": "459164",
"Score": "0",
"body": "Are you really proposing to rename the perfectly fine `comparator` to the meaningless `c` because in one implementation of the standard library they did the same? I assume he should also introduce the age-old overflow error they had for over a decade in the standard library as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T21:17:39.733",
"Id": "459171",
"Score": "0",
"body": "Yes. One letter names are fine if it is clear what they mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T22:26:36.133",
"Id": "459173",
"Score": "0",
"body": "I like your answer but I don't like `a` and `c` :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T23:01:18.757",
"Id": "459179",
"Score": "0",
"body": "@Björn So what *does* `a` stand for then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T23:18:57.353",
"Id": "459180",
"Score": "0",
"body": "a is the array to merge sort."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T02:16:19.423",
"Id": "234714",
"ParentId": "234698",
"Score": "4"
}
},
{
"body": "<ul>\n<li>If you are going to provide more than one variant of the method, then I recommend that you provide every possible variant. The indices are there or not (and defaults to the whole array). The comparator is optional (and defaults to the natural comparator). The ascending flag is optional (and defaults to true). Eight variants, or 16 if you want copying and in-place versions.</li>\n<li>I believe the \"right\" array is unneeded. The original data is can't be overwritten.</li>\n<li>It is worth remembering that below some size, bubble sort (or variations thereof) can be the fastest sort! (This may not matter as an exercise in brushing up skills, but it you want to actually use it...)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T16:05:10.963",
"Id": "459147",
"Score": "0",
"body": "I think newer versions of Java comes with timsort which is better. :) This is only an exercise anyway "
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T03:20:52.580",
"Id": "234716",
"ParentId": "234698",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T15:39:10.510",
"Id": "234698",
"Score": "4",
"Tags": [
"java",
"mergesort"
],
"Title": "Merge Sort in Java with Test cases"
}
|
234698
|
<p>I've written some code in Excel VBA that does the following:</p>
<ul>
<li>Finds a cell ("O") in a range (C3 to Z26)</li>
<li>Looks at an adjacent cell. This cell is located through "OFFSET_ROW"
and "OFFSET_COLUMN" (defined in a separate public variable) and contains a text string that is split into an array (using the "\" character as a delimiter)</li>
<li>Then, based on values in this array (e.g. "-100"), either:
<ul>
<li>Changes the values in two other "sets" of cells:
<ul>
<li><strong>Set 1:</strong> Four cells in one sheet ("DISP_SHEET")</li>
<li><strong>Set 2:</strong> Four cells in another sheet ("DIR_SHEET")</li>
</ul></li>
<li>Or, if changing the Set 1 and Set 2 cell values would result in <em>any</em> of them going below 0, shows a message box.</li>
</ul></li>
</ul>
<p>NB: The exact changes made to the sets of cells are dependent on whether the 19th array value ("ARR(18)") is 0 or something else.</p>
<p>Here's the code:</p>
<pre><code>Private Sub optChoice1_Click()
Dim O As Range
Dim DISP_SHEET As Worksheet
Dim DIR_SHEET As Worksheet
Dim TEXT As String
Dim ARR() As String
Dim X As Integer
'Set the range (Sheet1, C3 to Z26) in which to search for "O")
Set O = Sheet1.Range("C3:Z26").Find(WHAT:="O", LookAt:=xlWhole, MatchCase:=True)
Set DISP_SHEET = Sheet1
Set DIR_SHEET = Sheet4
TEXT = O.Offset(OFFSET_ROW, OFFSET_COLUMN)
ARR = Split(TEXT, "\")
'If the 19th array value is 0...
If ARR(18) = 0 Then
'If enacting the choice wouldn't make any of the Set 1 or Set 2 cell values go below 0...
If _
DISP_SHEET.Range(ARR(14)).Value + ARR(20) >= 0 And _
DISP_SHEET.Range(ARR(15)).Value + ARR(21) >= 0 And _
DISP_SHEET.Range(ARR(16)).Value + ARR(22) >= 0 And _
DISP_SHEET.Range(ARR(17)).Value + ARR(23) >= 0 And _
DIR_SHEET.Range(ARR(134)).Value + ARR(24) >= 0 And _
DIR_SHEET.Range(ARR(135)).Value + ARR(25) >= 0 And _
DIR_SHEET.Range(ARR(136)).Value + ARR(26) >= 0 And _
DIR_SHEET.Range(ARR(137)).Value + ARR(27) >= 0 Then
'Show the message in ARR(19)
MsgBox ARR(19)
For X = 0 To 3
'Enact the changes on the four Set 1 cells
DISP_SHEET.Range(ARR(X + 14)).Value = DISP_SHEET.Range(ARR(X + 14)).Value + ARR(X + 20)
'Enact the changes on the four Set 2 cells
DIR_SHEET.Range(ARR(X + 134)).Value = DIR_SHEET.Range(ARR(X + 134)).Value + ARR(X + 24)
Next X
'Otherwise, if enacting the choice would make one or more of the Set 2 cell values below 0.
ElseIf _
DIR_SHEET.Range(ARR(134)).Value + ARR(24) < 0 Or _
DIR_SHEET.Range(ARR(135)).Value + ARR(25) < 0 Or _
DIR_SHEET.Range(ARR(136)).Value + ARR(26) < 0 Or _
DIR_SHEET.Range(ARR(137)).Value + ARR(27) < 0 Then
'Show the message in ARR(138)
'(This states that the choice cannot be made because one or more of the Set 2 cell values would go below 0.)
MsgBox ARR(138)
Else
'Otherwise show the message in ARR(139)
'(This states that the choice cannot be made because one or more of the Set 1 cell values would go below 0.)
MsgBox ARR(139)
End If
'Otherwise (if the 19th array value isn't 0)
Else
If _
DISP_SHEET.Range(ARR(14)).Value + ARR(38) >= 0 And _
DISP_SHEET.Range(ARR(15)).Value + ARR(39) >= 0 And _
DISP_SHEET.Range(ARR(16)).Value + ARR(40) >= 0 And _
DISP_SHEET.Range(ARR(17)).Value + ARR(41) >= 0 And _
DIR_SHEET.Range(ARR(134)).Value + ARR(42) >= 0 And _
DIR_SHEET.Range(ARR(135)).Value + ARR(43) >= 0 And _
DIR_SHEET.Range(ARR(136)).Value + ARR(44) >= 0 And _
DIR_SHEET.Range(ARR(137)).Value + ARR(45) >= 0 Then
MsgBox ARR(37)
For X = 0 To 3
DISP_SHEET.Range(ARR(X + 14)).Value = DISP_SHEET.Range(ARR(X + 14)).Value + ARR(X + 38)
DIR_SHEET.Range(ARR(X + 134)).Value = DIR_SHEET.Range(ARR(X + 134)).Value + ARR(X + 42)
Next X
ElseIf _
DIR_SHEET.Range(ARR(134)).Value + ARR(42) < 0 And _
DIR_SHEET.Range(ARR(135)).Value + ARR(43) < 0 And _
DIR_SHEET.Range(ARR(136)).Value + ARR(44) < 0 And _
DIR_SHEET.Range(ARR(137)).Value + ARR(45) < 0 Then
MsgBox ARR(138)
Else
MsgBox ARR(139)
End If
End If
End Sub
</code></pre>
<p>As you can see, there's a fair amount of repetition in the lines beginning "DISP_SHEET.Range" or "DIR_SHEET.Range". I've tried to implement some sort of loop here but haven't had much luck.</p>
<p>I'm having difficulties here, probably because:</p>
<ul>
<li><em>All</em> of the conditions have to be true (e.g. in order to enact the changes, <em>all</em> of the values have to remain above 0).</li>
<li>The changes have to take place across <em>two</em> different sheets. </li>
<li>There is already another loop that exists in my code (using "X").</li>
</ul>
<p>It's probably a simple solution but I'm getting confused trying to balance these three things. Any help improving this or clearing it up would be much appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T17:13:00.067",
"Id": "459083",
"Score": "1",
"body": "Two things that pop out at me: 1) the unqualified Range items are referring to the active worksheet; suggest you explicitly qualify which sheet. 2) your comment says \"If the 18th array value...\" ARR(18) is the 19th value - ARR is a zero-based array IIRC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T18:25:23.970",
"Id": "459085",
"Score": "0",
"body": "Thank you - both very good points. I've made the edits above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:51:45.610",
"Id": "459146",
"Score": "0",
"body": "Providing example data will yield better reviews. Can you provide sample text so that we can split it and see what `ARR()` does? It seems like some parts of `ARR()` contain cell references while other parts contain values. What is the logic behind the pattern? Why are elements `14-17,134-137` address and `20-27` values?"
}
] |
[
{
"body": "<p>Qualify your variables. I read your post and after copying/pasting the code I created a standard module named <code>GlobalVariables</code> so that I had <code>O.Offset(GlobalVariables.OFFSET_ROW, GlobalVariables.OFFSET_COLUMN)</code> that identified where those variables came from. This helps future-you or another coder reading your know where things are located.</p>\n\n<p>Your wall of declarations at the top can be removed. I prefer having my variables declared just before their use. This aids in refactoring later and helps eliminate variables that are no longer being used. If left at the top it's not immediately apparent when a variable is no longer being referenced.</p>\n\n<pre><code>Dim sourceArea As Range\nSet sourceArea as = InputSheet.Range(\"InputArea\")\n</code></pre>\n\n<p>No need to yell. IE your variables are in SCEAM_CASE. Convention in VBA usually has variables in camel casing as in <code>worksheetThatHasSourceInformation</code> where the first variables letter is lowercased and the first letter thereafter of each new word is upper cased. Pascal case is used for Subs/Function and members of a class module.</p>\n\n<p>Use of <code>_</code> (underscores) in variable names. Using an underscore is how the <a href=\"https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/implements-statement\" rel=\"nofollow noreferrer\">Implements statement</a> handles when an interface is implemented. <code>InterfaceName_Member</code> is the eventual syntax. Reserve underscores for when that keyword is used to make it easier to learn when you start implementing interfaces.</p>\n\n<p>Compile time references. You have <code>Set dispSheet = Sheet1</code> and <code>set dirSheet = Sheet4</code>. No need to do that. Instead rename the <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.codename\" rel=\"nofollow noreferrer\">Worksheet.CodeName</a> property of those worksheet objects by right clicking on the variable <code>Sheet1</code> or <code>Sheet4</code> in the IDE and, from the context menu, choosing Definition. That will take you to the code behind of that worksheet. From the menu at the top choose View>Properties Window (Hotkey: <code>F4</code>) and renaming the (Name) property to a descriptive name. That leads to the next item for review.</p>\n\n<p>We've all been there. Naming is hard at best. Use descriptive variable names. <code>O</code> is a letter. <code>O</code> by itself doesn't help me understand what it's representing. An excessively long-winded name could be <code>firstCellOnTheSearchedSheetFoundToContainTheLetterO</code> and it a lot more helpful stating what that variable's there for. In the absence of understanding what that \"O\" searched for represents that's the best I can name it. The same goes for <code>dispWorkSheet</code>, ¿displayWorksheetSheet?, or <code>dirWorkSheet</code>, ¿directorySheet?, are not descriptive either. Future-you will thank you for giving your variables descriptive names so that 6months+ when you come back to it you're not head scratching over what they mean.</p>\n\n<p>Variable reuse: it's like trying to reuse toilet paper. Don't. You're using <code>X</code> in two different locations. Rename <code>X</code> and create a new descriptively named variable where you use it again below. This helps prevent accidental cross-contamination.</p>\n\n<p>The use of <code>Integer</code> when <code>X</code> is declared can be replaced with <code>Long</code>. You're less likely to have an overflow and IIRC internally a <code>Long</code> is used.</p>\n\n<p>Static cell address. <code>Range(\"C3:Z26\")</code> is a ticking time bomb waiting to go off. You add a row above row 3 or a column in front of column C and <strong>BARF</strong> the code is no longer searching within where you wanted it to. Use a named range. From Excel under the Formulas tab>Defined Names group>Name Manager button will display the Name Manager dialog. Click the New button to display the New Name dialog window. Enter in a name for that range, limit the scope to dispWorksheet (Renamed from Sheet1). Now you search within that range with <code>dispWorksheet.Names(\"AdequatelyNamedRange\").RefersToRange.Find(...)</code>. Adding a row/column will no longer adversely affect where you're searching. The same is true for deleted row/column in the named range.</p>\n\n<p>Magic numbers. 14, 15, 16, 17, etc... What do those numbers <em>mean</em>, <em>why</em> are they there. A <code>Const DescriptiveVaribleNameFor14 as long = 14</code> will aide to make the code self documenting.</p>\n\n<p>IMO The use of MsgBox can be removed. The reason for this is that you're providing information to the user without a way for them to abort.</p>\n\n<p>As you code becomes self documenting it becomes a lot clearer what's going on.</p>\n\n<hr>\n\n<p>Above were the easier issues to address. What remains requires in depth refactoring to increase the abstraction level. As the abstraction increases the code should be a lot more readable.</p>\n\n<p>The boolean checks are checking both dispWorksheet and dirWorksheet and that feels odd. I suggest separating them into their own individual appropriately named properties for each worksheet. Once you have that it should become simpler to tease apart what you're doing.</p>\n\n<p><strong>Warning: This is air coding and is only to give an idea as to how to proceed. Variable names are ludicrous but also help to show what is implicitly being done because of the static numbers.</strong> </p>\n\n<pre><code>'Module1\nPrivate Sub optChoice1_Click()\n Dim ARR() As String\n If dispWorksheet.NineteenthElementInArrayContainsAZero(\"O\", \"\\\", ARR) Then\n If dispWorksheet.Values14Through17Plus20Through23AreGreaterThanZero(ARR) _\n And dirWorksheet.Values134Through137Plus24Through27AreGreaterThanZero(ARR) Then\n MsgBox ARR(19)\n dispWorksheet.UpdateValuesForSet1Using20Through23 ARR\n dirWorksheet.UpdateValuesForSet2Using24Through27 ARR\n ElseIf dirWorksheet.Values134Through137Plus24Through27AreGreaterThanZero(ARR) Then\n MsgBox ARR(138)\n Else\n MsgBox ARR(139)\n End If\n Else\n If dispWorksheet.Values14Through17Plus38Through41AreGreaterThanZero(ARR) _\n And dirWorksheet.Values134Through137Plus42Through45AreGreaterThanZero(ARR) Then\n MsgBox ARR(37)\n dispWorksheet.UpdateValuesForSet1Using38Through41 ARR\n dirWorksheet.UpdateValuesForSet2Using42Through45 ARR\n ElseIf dirWorksheet.Values134Through137Plus42Through45AreGreaterThanZero(ARR) Then\n MsgBox ARR(138)\n Else\n MsgBox ARR(139)\n End If\n End If\nEnd Sub\n</code></pre>\n\n<p>The user defined worksheet properties</p>\n\n<pre><code>'dirWorksheet\nPublic Function Values134Through137Plus24Through27AreGreaterThanZero(ByRef splitArray() As String) As Boolean\n Values134Through137Plus24Through27AreGreaterThanZero = Me.Range(splitArray(134)).Value + splitArray(24) >= 0 _\n And Me.Range(splitArray(135)).Value + splitArray(25) >= 0 _\n And Me.Range(splitArray(136)).Value + splitArray(26) >= 0 _\n And Me.Range(splitArray(137)).Value + splitArray(27) >= 0\nEnd Function\n\nPublic Function Values134Through137Plus42Through45AreGreaterThanZero(ByRef splitArray() As String) As Boolean\n Values134Through137Plus42Through45AreGreaterThanZero = Me.Range(splitArray(134)).Value + splitArray(42) >= 0 _\n And Me.Range(splitArray(135)).Value + splitArray(43) >= 0 _\n And Me.Range(splitArray(136)).Value + splitArray(44) >= 0 _\n And Me.Range(splitArray(137)).Value + splitArray(45) >= 0\nEnd Function\n\nPublic Sub UpdateValuesForSet2Using24Through27(ByRef splitArray() As String)\n Dim counter As Long\n For counter = 0 To 3\n dirWorksheet.Range(splitArray(counter + 134)).Value = dirWorksheet.Range(splitArray(counter + 134)).Value + splitArray(counter + 24)\n Next counter\nEnd Sub\n\nPublic Sub UpdateValuesForSet2Using42Through45(ByRef splitArray() As String)\n Dim counter As Long\n For counter = 0 To 3\n dirWorksheet.Range(splitArray(counter + 134)).Value = dirWorksheet.Range(splitArray(counter + 134)).Value + splitArray(counter + 42)\n Next\nEnd Sub\n</code></pre>\n\n<p>and</p>\n\n<pre><code>'dispWorksheet\nPublic Function NineteenthElementInArrayContainsAZero(ByVal searchCharacter As String, _\n ByRef delimitingCharacter As String, _\n ByRef outArrayValues() As String) As Boolean\n Dim firstCellOnTheSearchedSheetFoundToContainTheLetterO As Range\n Set firstCellOnTheSearchedSheetFoundToContainTheLetterO = AdequatelyNamedRange.Find(WHAT:=searchCharacter, LookAt:=xlWhole, MatchCase:=True)\n\n Dim valueToSplit As String\n valueToSplit = firstCellOnTheSearchedSheetFoundToContainTheLetterO.Offset(PublicVariables.OFFSET_ROW, PublicVariables.OFFSET_COLUMN).Value2\n outArrayValues = Split(valueToSplit, delimitingCharacter)\nEnd Function\n\nPrivate Property Get AdequatelyNamedRange() As Range\n Set AdequatelyNamedRange = Me.Names(\"AdequatelyNamedRange\").RefersToRange\nEnd Property\n\n\nPublic Function Values14Through17Plus20Through23AreGreaterThanZero(ByRef splitArray() As String) As Boolean\n Values14Through17Plus20Through23AreGreaterThanZero = Me.Range(splitArray(14)).Value + splitArray(20) >= 0 _\n And Me.Range(splitArray(15)).Value + splitArray(21) >= 0 _\n And Me.Range(splitArray(16)).Value + splitArray(22) >= 0 _\n And Me.Range(splitArray(17)).Value + splitArray(23) >= 0\nEnd Function\n\nPublic Function Values14Through17Plus38Through41AreGreaterThanZero(ByRef splitArray() As String) As Boolean\n Values14Through17Plus38Through41AreGreaterThanZero = Me.Range(splitArray(14)).Value + splitArray(38) >= 0 _\n And Me.Range(splitArray(15)).Value + splitArray(39) >= 0 _\n And Me.Range(splitArray(16)).Value + splitArray(40) >= 0 _\n And Me.Range(splitArray(17)).Value + splitArray(41) >= 0\nEnd Function\n\nPublic Sub UpdateValuesForSet1Using20Through23(ByRef splitArray() As String)\n Dim counter As Long\n For counter = 0 To 3\n Me.Range(splitArray(counter + 14)).Value = Me.Range(splitArray(counter + 14)).Value + splitArray(counter + 20)\n Next\nEnd Sub\n\nPublic Sub UpdateValuesForSet1Using38Through41(ByRef splitArray() As String)\n Dim counter As Long\n For counter = 0 To 3\n Me.Range(splitArray(counter + 14)).Value = Me.Range(splitArray(counter + 14)).Value + splitArray(counter + 38)\n Next\nEnd Sub\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T23:20:46.683",
"Id": "234708",
"ParentId": "234700",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T16:21:55.937",
"Id": "234700",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Loop with multiple conditions that need to be true, across two different sheets"
}
|
234700
|
<p>I decided to redo a program that I did awhile ago that encodes text as an image.</p>
<p>For example, here's the entirety of <a href="https://github.com/clojure/clojure/blob/master/src/clj/clojure/core.clj" rel="nofollow noreferrer"><code>clojure/core.clj</code></a>, Clojure's standard library:</p>
<pre><code>encode_text(clojure_core_text, int(5e4))
</code></pre>
<p><a href="https://i.stack.imgur.com/9PJz0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9PJz0.png" alt="enter image description here"></a></p>
<p>And here's the source for the program itself (with a lower multiplier to make it more blue):</p>
<p><a href="https://i.stack.imgur.com/y47Ll.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y47Ll.png" alt="enter image description here"></a></p>
<p>It's interesting that it's able to make use of PNG's image compression. The original text is 257KB, while the encoded image is only 148KB.</p>
<p>Basically is works by taking each letter from the string, getting its character code, multiplying it by a multiplier (for better color distribution), then turning it into a base-256 number in the form of a tuple of digits. That "number tuple" is then readily usable as a color tuple to be used in Pillow. It writes the pixels left-to-right, top-down, and attempts to make the resulting image as square as possible.</p>
<p>It's in two files. The first is helpers that handle turning a number to and from tuple representations:</p>
<pre><code>>>> decimal_to_places(123, 2) # 123 to binary
[1, 1, 1, 1, 0, 1, 1]
>>> decimal_to_places(98765, 16) # 98765 to hexadecimal
[1, 8, 1, 12, 13]
# Then back again
>>> places_to_decimal([1, 1, 1, 1, 0, 1, 1], 2)
123
>>> places_to_decimal([1, 8, 1, 12, 13], 16)
98765
</code></pre>
<p>And the second is the encoder/decoder.</p>
<p>My main concerns:</p>
<ul>
<li><p>Use of Pillow. I have very little experience with the library, so I'd like to know if anything about my use here can be improved.</p></li>
<li><p>The base conversions. Is there a clean alternative to <code>decimal_to_places</code> that's less "manual"?</p></li>
<li><p>And similarly with the encode/decode functions. They're both using fairly verbose "manual" looping.</p></li>
</ul>
<p>I welcome critique regarding anything else though.</p>
<p>At the very bottom, I have a <code>test_encoding_decoding</code> function that I used to do super-quick-and-dirty testing. It's far from my main concern, but I'd be open to comments on it as well.</p>
<blockquote>
<p>base_conversion.py</p>
</blockquote>
<pre><code>from typing import Sequence, List
import math
def decimal_to_places(dec: int, base: int) -> List[int]:
"""Converts a decimal number into a list of digits in the given base.
123, 10 -> [1, 2, 3]
9, 2 -> [1, 0, 0, 1]"""
remaining = dec
max_power = int(math.log(dec, base))
acc = []
for power in range(max_power, -1, -1):
cur, remaining = divmod(remaining, base ** power)
acc.append(cur)
return acc
def places_to_decimal(places: Sequence[int], base: int) -> int:
"""Converts a list of digits in the given base to decimal.
[1, 2, 3], 10 -> 123
[1, 0, 0, 1], 2 -> 9"""
return sum(place * (base ** power)
for power, place in enumerate(reversed(places)))
</code></pre>
<blockquote>
<p>encoder.py</p>
</blockquote>
<pre><code>from typing import Tuple, Iterator, List
from PIL import Image, ImageDraw
import math
import base_conversion as bc
EMPTY_PLACEHOLDER = (255, 255, 255)
COLOR_BASE = 256
ALPHALESS_TUPLE_LENGTH = 3
def _square_dimensions(text_len: int) -> Tuple[int, int]:
width = math.ceil(math.sqrt(text_len))
height = math.ceil(text_len / width)
return width, height
def _coordinates_in(width: int, height: int) -> Iterator[Tuple[int, int]]:
for y in range(height):
for x in range(width):
yield x, y
def _pad_color_list(color: List[int]) -> List[int]:
needed = ALPHALESS_TUPLE_LENGTH - len(color)
padded = [0] * needed
padded.extend(color)
return padded
def encode_text(text: str, magnitude_multiplier: int = 1) -> Image.Image:
"""Returns an image where each character from the message is encoded as a colored pixel.
Travels left-right, top-down. Will attempt to make the image as square as possible.
magnitude_multiplier as multiplied by each character code prior to encoding."""
width, height = _square_dimensions(len(text))
img = Image.new("RGB", (width, height), EMPTY_PLACEHOLDER)
graph = ImageDraw.Draw(img)
for char, position in zip(text, _coordinates_in(width, height)):
code = ord(char) * magnitude_multiplier
color = bc.decimal_to_places(code, COLOR_BASE)
padded_color = _pad_color_list(color)
graph.point(position, tuple(padded_color))
return img
def decode_image(img: Image.Image, magnitude_multiplier: int = 1) -> str:
"""Decodes an image produced by encode_text back into text.
Each character code is divided by magnitude_multiplier after decoding."""
width, height = img.size
decoded = []
for position in _coordinates_in(width, height):
color = img.getpixel(position)
if color == EMPTY_PLACEHOLDER:
break
else:
decoded_char_code = bc.places_to_decimal(color, COLOR_BASE) // magnitude_multiplier
decoded.append(chr(decoded_char_code))
return "".join(decoded)
SAMPLE_TEXT = "./clojure_core.clj"
ENCODED_SAVE_PATH = "./encoded.png"
# This is just a quick, messy way to test encoding/decoding
def test_encoding_decoding(magnitude_multiplier: int,
text_path: str = SAMPLE_TEXT,
image_save_path: str = ENCODED_SAVE_PATH
) -> None:
with open(text_path) as f:
lines = f.readlines()
orig_text = "\n".join(lines)
img = encode_text(orig_text, magnitude_multiplier)
img.show()
decoded_text = decode_image(img, magnitude_multiplier)
if orig_text == decoded_text:
print("PASSED ENCODING")
img.save(image_save_path)
loaded_image = Image.open(ENCODED_SAVE_PATH)
decoded_loaded = decode_image(loaded_image, magnitude_multiplier)
if orig_text == decoded_loaded:
print("PASSED LOADED DECODING")
else:
print("Failed loaded decoding...", len(orig_text), len(decoded_text))
else:
print("Failed decoding...", len(orig_text), len(decoded_text))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T20:10:43.733",
"Id": "459089",
"Score": "0",
"body": "Whoops, I actually meant to rename `graph`. That's left over from me thinking about this like I was using a `Graphics` Java object."
}
] |
[
{
"body": "<p>This is a really nice problem, thanks for sharing your solution!</p>\n\n<p>One of the really nice things about this problem is that if you use Python 3, you can use binary data natively. In my code below, I use Python 3's binary data capabilities heavily. </p>\n\n<hr>\n\n<p>The most important thing to note:</p>\n\n<p><em>Base 256 in Python is binary data.</em> </p>\n\n<p>While Python does have natural <code>bin</code>, <code>oct</code>, and <code>hex</code> methods, what we really want to do here is translate our strings to bytes arrays. If there were no other requirements, then this problem could be solved in one function-- it's that simple. However, the multiplier requires some internal conversion, and so the code below will account for that using the same structure in the original code. </p>\n\n<p>Some minor things:</p>\n\n<ul>\n<li>Nice generator function. Fortunately, we can replicate the same behavior by importing <code>itertools.product</code> and carefully arranging the indices. </li>\n<li>In line with the bytes discussion above, we no longer need the functions from <code>base_conversion.py</code>. Everything can be logically contained in one file. </li>\n<li>In the original code, the string read from the file contained newlines <code>'\\n'</code>. However, it was also using <code>\"\\n\".join(arr)</code>; meaning the resulting string had twice as many newlines. So if you immediately notice the images being different, I would imagine this is why. </li>\n<li>There are two functions for encoding the text, <code>encode_text_orig</code> which retains the spirit of the original <code>encode_text</code> function and <code>encode_text_np</code> which utilizes <code>numpy</code> to structure the bytes array. I'll leave it up to you which one to use, both are functional. </li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Tuple\nimport math\nfrom itertools import product\nimport numpy as np\n\nfrom PIL import Image, ImageDraw\n\nEMPTY_PLACEHOLDER = (255, 255, 255)\nALPHALESS_TUPLE_LENGTH = len(EMPTY_PLACEHOLDER)\n\n\ndef _square_dimensions(text_len: int, difference=False) -> Tuple[int, int]:\n width = math.ceil(math.sqrt(text_len))\n height = math.ceil(text_len / width)\n\n return width, height\n\n\ndef encode_text_orig(text: str, magnitude_multiplier: int = 1) -> Image.Image:\n \"\"\"Returns an image where each character from the message is encoded as a colored pixel.\n Travels left-right, top-down. Will attempt to make the image as square as possible.\n magnitude_multiplier as multiplied by each character code prior to encoding.\"\"\"\n width, height = _square_dimensions(len(text))\n\n img = Image.new(\"RGB\", (width, height), EMPTY_PLACEHOLDER)\n graph = ImageDraw.Draw(img)\n\n for char, (x, y) in zip(text, product(range(height), range(width))):\n code = ord(char) * magnitude_multiplier\n color = code.to_bytes(ALPHALESS_TUPLE_LENGTH, 'big')\n\n graph.point((y, x), tuple(color))\n\n return img\n\n\ndef encode_text_np(text: str, magnitude_multiplier: int = 1) -> Image.Image:\n \"\"\"Returns an image where each character from the message is encoded as a colored pixel.\n Travels left-right, top-down. Will attempt to make the image as square as possible.\n magnitude_multiplier as multiplied by each character code prior to encoding.\"\"\"\n width, height = _square_dimensions(len(text))\n\n arr = np.full((width, height, 3), 255, dtype=np.uint8)\n\n for char, (x, y) in zip(text, product(range(width), range(height))):\n code = char * magnitude_multiplier\n color = code.to_bytes(ALPHALESS_TUPLE_LENGTH, 'big')\n\n arr[x, y] = tuple(color)\n\n return Image.fromarray(arr)\n\n\ndef decode_image(img: Image.Image, magnitude_multiplier: int = 1) -> str:\n \"\"\"Decodes an image produced by encode_text back into text.\n Each character code is divided by magnitude_multiplier after decoding.\"\"\"\n\n decoded = []\n for color in img.getdata():\n if color == EMPTY_PLACEHOLDER:\n break\n\n decoded.append((int.from_bytes(color, 'big') // magnitude_multiplier).to_bytes(1, 'big'))\n\n return b''.join(decoded)\n\n\nSAMPLE_TEXT = \"./clojure_core.clj\"\nENCODED_SAVE_PATH = \"./encoded.png\"\n\n\n# This is just a quick, messy way to test encoding/decoding\ndef test_encoding_decoding(magnitude_multiplier: int,\n text_path: str = SAMPLE_TEXT,\n image_save_path: str = ENCODED_SAVE_PATH\n ) -> None:\n with open(text_path, 'rb') as f:\n orig_text = f.read()\n\n img = encode_text_np(orig_text, magnitude_multiplier)\n\n img.show()\n\n decoded_text = decode_image(img, magnitude_multiplier)\n\n if orig_text == decoded_text:\n print(\"PASSED ENCODING\")\n\n img.save(image_save_path)\n\n loaded_image = Image.open(ENCODED_SAVE_PATH)\n decoded_loaded = decode_image(loaded_image, magnitude_multiplier)\n\n if orig_text == decoded_loaded:\n print(\"PASSED LOADED DECODING\")\n\n else:\n print(\"Failed loaded decoding...\", len(orig_text), len(decoded_text))\n\n else:\n print(\"Failed decoding...\", len(orig_text), len(decoded_text))\n\n\nif __name__ == '__main__':\n test_encoding_decoding(10)\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T23:44:57.423",
"Id": "459097",
"Score": "2",
"body": "Ha, `to_bytes` + `tuple` is great. I can't believe I didn't know about that. Thanks. I'm going to leave this a couple days before I accept, but I appreciate the review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T23:36:20.223",
"Id": "234709",
"ParentId": "234702",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "234709",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T16:48:47.513",
"Id": "234702",
"Score": "8",
"Tags": [
"python",
"python-3.x"
],
"Title": "Encoding and decoding text; to and from an image"
}
|
234702
|
<p>For the Below code want to know whether the correct procedure is followed
for the java code , are there any missing points according to the java standards ?</p>
<pre><code> import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class CodeReviewTest {
volatile Integer totalAge = 0;
CodeReviewTest(PersonDatabase<Person> personPersonDatabase) {
Person[] persons = null;
try {
persons = personPersonDatabase.getAllPersons();
} catch (IOException e) {
}
List<Person> personsList = new LinkedList();
for (int i = 0; i <= persons.length; i++) {
personsList.add(persons[i]);
}
personsList.parallelStream().forEach(person -> {
totalAge += person.getAge();
});
List<Person> males = new LinkedList<>();
for (Person person : personsList) {
switch (person.gender) {
case "Female": personsList.remove(person);
case "Male" : males.add(person);
}
}
System.out.println("Total age =" + totalAge);
System.out.println("Total number of females =" + personsList.size());
System.out.println("Total number of males =" + males.size());
}
}
class Person {
private int age;
private String firstName;
private String lastName;
String gender;
public Person(int age, String firstName, String lastName) {
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object obj) {
return this.lastName == ((Person)obj).lastName;
}
}
interface PersonDatabase<E> {
Person[] getAllPersons() throws IOException;
}
</code></pre>
<p><strong>Questions</strong> </p>
<ul>
<li>Does the above code follow the standards by java ?</li>
<li>Can I use better idioms? </li>
<li>Can this implementation be improved for performance? </li>
<li>Can the style / readability be improved?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T01:18:34.813",
"Id": "459100",
"Score": "0",
"body": "First thing I see is that \"Java\" is a proper noun and therefore should be capitalized. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T01:20:24.900",
"Id": "459101",
"Score": "4",
"body": "Ugh, NEVER catch and ignore an exception. It's super poor style. If you don't know what to do with an exception, you should probably not catch it at all and just let it propagate up the call stack. Catching and ignoring `IOException` like you do is especially pernicious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T13:51:46.173",
"Id": "459125",
"Score": "1",
"body": "The title should indicate what the code does rather than what you want out of the code review. The code should be a real implementation of something and not hypothetical. A class or method name like `CodeReviewTest()` may indicate to some reviewers that this is a hypothetical question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T19:47:07.517",
"Id": "459163",
"Score": "0",
"body": "Can you put a different title explaining what you are trying to do here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T06:01:38.823",
"Id": "459198",
"Score": "0",
"body": "The title is changed , need reviews on the code implementation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T17:23:32.753",
"Id": "459342",
"Score": "0",
"body": "`for(Person person : personList) { ... personList.remove(person); ... }` should crash with a `ConcurrentModificationException`. Was this code ever run? Or is it really just a test of the Code Review site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-31T08:35:05.317",
"Id": "459409",
"Score": "0",
"body": "The code does not break on parallel stream , but i wanted to know whether including parallel stream is correct or not"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T20:28:17.343",
"Id": "505091",
"Score": "0",
"body": "the for loop is wrong, i <= persons.length must be i < persons.length, otherwise you get ArrayIndexOutOfBoundsException because length returns the number of elements, but since arrays are zero indexed you should iterate till n-1"
}
] |
[
{
"body": "<h1>Errors</h1>\n\n<ol>\n<li><p><strong>Modify variable inside lambda expression:</strong><br>\nYou sure this code passes compilation? you have a lambda expression (<code>forEach()</code>) that modifies a variable. all variables that are used inside lambda expression are considered <code>final</code>.\nby the way, the whole calculation of <code>totalAge</code> can be converted to stream() processing using <code>map()</code> and <code>sum()</code></p></li>\n<li><p><strong>The <code>switch</code> statement:</strong><br>\nthere is no <code>break;</code> between the <code>case</code>s, so every female will also be counted as male. </p></li>\n</ol>\n\n<h1>Standards</h1>\n\n<ol>\n<li><strong>gender:</strong><br>\nAny reason why this property has no getter method?</li>\n</ol>\n\n<h1>Best Practices</h1>\n\n<ol>\n<li><p><strong>equals():</strong><br>\ndoes not protect from <code>NullPointerException</code> or <code>ClassCastException</code></p></li>\n<li><p><strong>Use enum :</strong><br>\nwhenever you have a finite closed set of valid <code>String</code> values. (like gender in your case). the advantages are that the literal value is specified only once, typos are getting detected by the compiler, and you can add properties and behaviors (=methods) to the enum values. in this case, perhaps the display message <code>\"Total number of...</code> can be added as property?</p></li>\n<li><p><strong>Converting array<code>[]</code> to <code>List</code>:</strong><br>\nno need to iterate over the array. Use <code>Arrays.asList()</code> .</p></li>\n<li><p><strong>Single responsibility principle:</strong><br>\nThe constructor of <code>CodeReviewTest</code> is doing all the calculations and printing the results. this breaks the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single responsibility principle</a>. meaning, there are multiple factors that require modifying the code in that one method: adding a new value to gender (yes, it's possible in today PC culture), sending the results in to another destination (for example, storing in DB), there are more.</p></li>\n</ol>\n\n<h1>Readability</h1>\n\n<ol>\n<li><p><strong>Using <code>personsList</code> to hold all females:</strong><br>\nThis is confusing. imagine you are part of a dev team. your team member might need to modify the code you've written. they will assume that <code>personsList</code> holds all person objects.</p></li>\n<li><p><strong>Using constructor to perform logic:</strong><br>\nconstructor has a fixed name that does not say what the method does. it is intended to initialize the object (= populate properties). even if your class has only one method, it is better to have a non constructor method with clear descriptive name. </p></li>\n<li><p><strong>Comments:</strong><br>\nthere are none. nough said.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T19:00:23.603",
"Id": "459350",
"Score": "0",
"body": "Yes, the `totalAge` lambda code would compile, because it a member variable (`this.totalAge += ...`), and `this` is final. (But the code is still horribly broken.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-31T08:39:29.023",
"Id": "459410",
"Score": "0",
"body": "The code does not break on parallel stream , but i wanted to know whether including parallel stream is correct or not"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T07:44:29.343",
"Id": "234724",
"ParentId": "234703",
"Score": "5"
}
},
{
"body": "<p>Issues Sharon Ben Asher did not mention:</p>\n\n<p>Because you're not using the index variable i to anything other than indexing the array you should use the for-each variant of the for loop to make the code cleaner. LinkedList is the wrong data type. Since you're only adding and never modifying the list and know the size you should use an ArrayList with correct initial size. Variables that are not changed should be marked final:</p>\n\n<pre><code>final List<Person> personsList = new ArrayList(persons.length);\n\nfor (Person person: persons) {\n personsList.add(person);\n}\n</code></pre>\n\n<p>(Or better yet use the Arrays.asList for this particular use case).</p>\n\n<p>The totalAge field is pointlessly volatile. It is accessed only in the constructor which means it can only ever be accessed by one thread.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T09:37:56.833",
"Id": "459113",
"Score": "1",
"body": "it is also pointlessly defined `Integer`. should be defined as the primitive type"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T19:09:30.627",
"Id": "459352",
"Score": "1",
"body": "The `totalAge` field isn’t pointlessly volatile. The `.parallelStream().forEach(...)` statement will run the lambdas in separate threads. However, `volatile` doesn’t fix the problem, since the code will still be doing read-modify-write operations in different threads; atomic operations would need to be used. Or simply using proper stream methods like `.sum()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-02T06:47:45.887",
"Id": "459595",
"Score": "0",
"body": "so is it fine to use volatile or not ?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T09:19:59.440",
"Id": "234726",
"ParentId": "234703",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "234724",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T19:59:53.933",
"Id": "234703",
"Score": "-2",
"Tags": [
"java",
"object-oriented"
],
"Title": "volatile variables and parallel streams in Java"
}
|
234703
|
<p>I have created a Python 3 password manager for API keys and social media passwords on local storage. The script is 500 lines and PEP8/PYLINT compliant, each definition contains a docstring and the code is well commented. It is purposefully in "procedural" instead of "object" style.</p>
<ul>
<li>The cryptography definitions all begin with <code>crypto</code></li>
<li>The main loop definitions begin with <code>wallet</code></li>
<li>The menu option definitions begin with <code>option</code></li>
</ul>
<p>The only non-standard python library is <a href="https://github.com/Legrandin/pycryptodome" rel="nofollow noreferrer">here</a>.</p>
<p>I am seeking review on the overall security of my cryptography implementation, as well as, any insight to back doors or other threats.</p>
<p>The end goal is you enter site and user such as:</p>
<pre><code>input site: stackexchange
input user: litepresence
</code></pre>
<p>Then your site password is transferred to the clipboard for 10 seconds for authentication to the site. Security is key, I want to be able to use and distribute this app for financial applications.</p>
<p>I am maintaining the code <a href="https://github.com/litepresence/CypherVault" rel="nofollow noreferrer">here</a>.</p>
<p><a href="https://i.stack.imgur.com/Roo1s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Roo1s.png" alt="enter image description here"></a></p>
<p>Key Features:</p>
<pre><code>"""
writes site login to clipboard w/ xclip; auto deletes in 10 seconds
reads/writes AES CBC encrypted password JSON to text file along with current salt
new salt generated after every successful login, password change, return to main menu, and exit
salt is 16 byte and generated in crypto secure manner via os.urandom
master password stretched to several hundred megabytes to prevent GPU attacks
master password hashed iteratively via traditional salted pbkdf sha512
master password rehashed iteratively via non traditional method (for fun learning experience mostly)
includes password suggestion utility
"""
</code></pre>
<p>References:</p>
<pre><code>"""
https://stackoverflow.com/questions/43860227/python-getting-and-setting-clipboard-data-with-subprocesses
https://www.quickprogrammingtips.com/python/aes-256-encryption-and-decryption-in-python.html
https://datalocker.com/what-is-the-difference-between-ecb-mode-versus-cbc-mode-aes-encryption
https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.blockalgo-module.html
https://docs.oracle.com/cd/E11223_01/doc.910/e11197/app_special_char.htm
https://docs.python.org/3/library/hashlib.html
https://crackstation.net/hashing-security.htm
https://en.wikipedia.org/wiki/PBKDF2
https://www.owasp.org
"""
</code></pre>
<p>Code:</p>
<pre><code># STANDARD PYTHON MODULES
import os
import sys
import time
import struct
import traceback
from hashlib import sha512
from hashlib import blake2b as blake
from hashlib import sha3_512 as sha3
from hashlib import pbkdf2_hmac as pbkdf
from hashlib import shake_256 as shake256
from base64 import b64encode, b64decode
from json import loads as json_loads
from json import dumps as json_dumps
from subprocess import Popen, PIPE
from random import seed, randint
from binascii import hexlify
from getpass import getpass
from pprint import pprint
# THIRD PARTY MODULES
from Crypto import Random
from Crypto.Cipher import AES
# USER DEFINED SECURITY CONSTANTS
# WARNING: when you change these parameters your CypherVault will need to be deleted
MEGABYTES = 400
ITERATIONS = 1000000
# CURRENT RELEASE ID
VERSION = 0.00000003
def it(style, text):
"""
colored text in terminal
"""
emphasis = {
"red": 91,
"green": 92,
"yellow": 93,
"blue": 94,
"purple": 95,
"cyan": 96,
}
return ("\033[%sm" % emphasis[style]) + str(text) + "\033[0m"
def trace():
"""
Stack trace report upon exception
"""
return "\n\n" + str(time.ctime()) + "\n\n" + str(traceback.format_exc()) + "\n\n"
def doc_write(document, text):
"""
write a dictionary to file
"""
with open(document, "w+") as handle:
handle.write(text)
handle.close()
def doc_read(document):
"""
read dictionary from file
"""
with open(document, "r") as handle:
text = handle.read()
handle.close()
return text
def clip_get():
"""
read from clipboard
"""
clip = Popen(["xclip", "-selection", "clipboard", "-o"], stdout=PIPE)
clip.wait()
return clip.stdout.read().decode()
def clip_set(data):
"""
write to clipboard
"""
clip = Popen(["xclip", "-selection", "clipboard"], stdin=PIPE)
clip.stdin.write(data.encode())
clip.stdin.close()
clip.wait()
def crypto_pad(msg):
"""
pad if length is not a multiple of 128 else unpad as required
"""
return (
(msg + (128 - len(msg) % 128) * chr(128 - len(msg) % 128))
if len(msg) % 128
else msg[0 : -msg[-1]]
)
def crypto_100():
"""
cryptographically secure 100 digit string formatted integer generator
"""
str_random = ""
while len(str_random) != 100:
set_random = struct.unpack("QQQQQQ", os.urandom(48))
str_random = ""
for integer in set_random:
str_random += str(integer)
str_random = str(int(str_random[-100:]))
return str_random
def crypto_wacky_digest(msg_digest, salt):
"""
never roll your own... except as a backup plan and fun learning experience!
random amount of multiple hashing types to impose novelty restraint
"""
shaken_salt = shake256(salt.encode()).digest(16)
# randomized iteration count
for _ in range(int(salt[-4:])):
# for each up to 10 iterations; 1 in 10 no skip
for _ in range(int(salt[-1])):
# salted 512 chacha stream cipher with permuted input block copy
msg_digest = hexlify(blake(msg_digest, salt=shaken_salt).digest())
for _ in range(int(salt[-2])):
# keccak 512 sponge construction
msg_digest = sha3(msg_digest).digest()
for _ in range(int(salt[-3])):
# standard sha512
msg_digest = sha512(msg_digest).digest()
return msg_digest
def crypto_digest(password):
"""
iterative rounds of hashing to impose time restraint
expanded password length to impose memory restraint
"""
# any scheme which uses more than a few hundred MB of RAM
# is almost certainly inefficient for GPU or FPGA implementations
password *= max(1, int(MEGABYTES * 10 ** 6 / len(password)))
# shake and digest the salt to 16 bytes
salt = doc_read("cyphervault.txt").split("$", 1)[0]
shaken_salt = shake256(salt.encode()).digest(16)
# many iterations of salted 512 password based key derivation function (PBKDF)
msg_digest = hexlify(pbkdf("sha512", password.encode(), shaken_salt, ITERATIONS))
# multiple types of hashing to impose novelty restraint
msg_digest = crypto_wacky_digest(msg_digest, salt)
# final format to sha256 for 32 byte output
return shake256(msg_digest).digest(32)
def crypto_cypher(vector, password):
"""
AES encryption method in CBC mode
"""
return AES.new(crypto_digest(password), AES.MODE_CBC, vector, segment_size=256)
def crypto_encrypt(message, password):
"""
encryption routine
"""
vector = Random.new().read(AES.block_size)
cypher = crypto_cypher(vector, password)
recursion = cypher.encrypt(crypto_pad(message))
return b64encode(vector + recursion)
def crypto_decrypt(cyphertext, password):
"""
decryption routine
"""
vector = b64decode(cyphertext)
cypher = crypto_cypher(vector[:16], password)
recursion = cypher.decrypt(vector[16:])
return crypto_pad(recursion).decode()
def crypto_indite(passwords):
"""
\nencrypting the CypherVault...
"""
print(it("purple", crypto_indite.__doc__))
cyphersalt = crypto_100()
cyphervault = doc_read("cyphervault.txt").split("$", 1)[1]
doc_write(
"cyphervault.txt", cyphersalt + "$" + cyphervault,
)
cyphervault = crypto_encrypt(
json_dumps(passwords), passwords["master"]["master"]
).decode()
doc_write(
"cyphervault.txt", cyphersalt + "$" + cyphervault,
)
def wallet_main(master=None, passwords=None):
"""
******************************************
*** Welcome to CypherVault v"""
msg = "***\n ******************************************\n"
print("\033c", it("green", wallet_main.__doc__ + ("%.8f " % VERSION) + msg))
if passwords is None:
passwords = wallet_initialize(master)
crypto_indite(passwords)
choice = wallet_choices(passwords["master"]["master"], passwords)
if choice == 0:
option_get(passwords)
elif choice == 1:
option_post(passwords)
elif choice == 2:
option_delete(passwords)
elif choice == 3:
option_suggest(passwords)
elif choice == 4:
option_print(passwords)
elif choice == 5:
option_print_full(passwords)
elif choice == 6:
crypto_indite(passwords)
sys.exit()
def wallet_initialize(master):
"""
initialize password dictionary and prompt for master password
"""
# read password dictionary if none exists create a new encrypted cyphervault
# all passwords are in format >>> passwords[site][user]
try:
cyphervault = doc_read("cyphervault.txt").split("$", 1)[1]
assert len(cyphervault) > 0
except Exception:
print("\nCypherVault not found, intitializing new...")
doc_write("cyphervault.txt", (crypto_100() + "$n"))
passwords = {"master": {"master": "password"}}
crypto_indite(passwords)
cyphervault = doc_read("cyphervault.txt").split("$", 1)[1]
print(it("purple", "\nyour default password is has been set to:"))
print(it("green", "\npassword\n"))
if master is None:
master = getpass("Enter your master password: ")
# attempt to decrypt the cyphervault with the supplied password
decrypted = False
try:
passwords = json_loads(crypto_decrypt(cyphervault, master))
decrypted = True
except Exception:
trace()
print(it("green", "\ninvalid master password, press Enter to try again..."))
input("\npress Enter to return to main menu")
wallet_main() # recursion
if decrypted:
# after every successful login create a new salt
crypto_indite(passwords)
print(it("green", "\n login successful!"))
# warn if password is default
if master == "password":
print(it("purple", "\nyou should change default password immediately!"))
print("\nyour master password is: ", it("green", master))
# perform some tests on the password
audit(master)
return passwords
def wallet_choices(master, passwords):
"""
1: ENTER A NEW PASSWORD OR EDIT A PASSWORD
2: DELETE A PASSWORD
3: SUGGEST A PASSWORD
4: PRINT SITE/USER LIST
5: PRINT SITE/USER/PASSWORD LIST
6: EXIT
"""
print(it("green", wallet_choices.__doc__))
choice = input("input choice or press Enter to GET A PASSWORD: ")
if not choice:
choice = 0
try:
choice = int(choice)
assert 0 <= choice <= 6
except Exception:
print("\033cinvalid choice (", choice, ") try again")
time.sleep(2)
wallet_main(master, passwords)
return choice
def option_get(passwords):
"""
the password has been copied to the clipboard
\nyou only have 10 seconds to paste it via ctrl+V
"""
site, user = input_site_user()
found = False
if site in passwords.keys():
if user in passwords[site].keys():
found = True
clip_set(passwords[site][user])
print(it("purple", option_get.__doc__))
time.sleep(10)
clip_set("")
print("clipboard has been cleared")
time.sleep(2)
if not found:
print("\nsite/user not found in wallet")
response = input("\nwould you like to add this site/user? (y/n): ")
if response in ["", "y", "Y"]:
option_post(passwords, site, user)
input("\npress Enter to return to main menu")
wallet_main(passwords["master"]["master"], passwords)
def option_post(passwords, site=None, user=None):
"""
post a new or updated password to the cyphervault
"""
def update(passwords, site, user):
print(it("purple", "\nsite/user:"), site, user, "\n")
# double Enter the new password
new_pass = getpass("\ninput password: ")
if new_pass == getpass("\ninput new password again: "):
audit(new_pass)
if site not in passwords.keys():
passwords[site] = {}
passwords[site][user] = new_pass
crypto_indite(passwords)
print(it("green", "\nCypherVault has been updated"))
else: # recursion
print(it("purple", "\npasswords do not match, try again..."))
time.sleep(2)
update(passwords, site, user)
if site is None:
site, user = input_site_user()
create_new = True
# update a password if it already exists
if site in passwords.keys():
if user in passwords[site].keys():
print("\nsite:", site, "\nuser:", user)
print(it("purple", "\nWARN: site/user already exists"))
response = input("\nwould you like to overwrite this site/user? (y/n):")
if response not in ["", "y", "Y"]:
create_new = False
if create_new:
update(passwords, site, user)
# return to main menu
input("\npress Enter to return to main menu")
wallet_main(passwords["master"]["master"], passwords)
def option_delete(passwords):
"""
remove a user from the cyphervault
"""
print("\nEnter the site and user you would like to delete")
site, user = input_site_user()
if site != "master":
found = False
# check if the site/user exists in the passwords
if site in passwords.keys():
if user in passwords[site].keys():
found = True
if found:
# remove the user
del passwords[site][user]
if passwords[site] == {}:
# if there are no other users at that site, remove the site as well
del passwords[site]
crypto_indite(passwords)
print(it("purple", "\nsite/user has been deleted"))
time.sleep(2)
else:
# return to the main menu
print(it("purple", "\nsite/user was not found"))
else:
print(it("purple", "you cannot delete the master password!"))
input("\npress Enter to return to main menu")
wallet_main(passwords["master"]["master"], passwords)
def option_print(passwords):
"""
print all site/user combinations in the cyphervault
"""
print("")
for site, logins in passwords.items():
for user, _ in logins.items():
print(it("green", site + " : " + user))
input("\npress Enter to return to main menu")
wallet_main(passwords["master"]["master"], passwords)
def option_print_full(passwords):
"""
\n\n
WARNING: YOU ARE ABOUT TO EXPOSE YOUR UNENCRYPTED CYPHERVAULT
Make sure you are in a private location!\n
WARNING: DO NOT PRINT THIS TO PAPER
CypherVault contents will be exposed on your printer hard drive\n
WARNING: DO NOT SAVE THIS TO FILE
CypherVault contents will be exposed on your local hard drive\n
USE THIS FUNCTION ONLY TO INSPECT OR COPY - BY HAND - TO PAPER\n\n
"""
print("\033c", it("purple", option_print_full.__doc__))
msg = "\nare you sure you want to print your unencrypted CyperVault (y/n): "
response = input(it("green", msg))
if response in ["y", "Y"]:
msg = "\npress Enter to expose the CypherVault\npress Enter again to exit\n"
print(it("green", msg))
input()
print("\033c\n\n\n")
pprint(passwords)
input(it("green", "\npress Enter to return to main menu"))
wallet_main(passwords["master"]["master"], passwords)
def option_suggest(passwords, length=10):
"""
press Enter to suggest another secure random password
or any number 10 to 500, then Enter to change the length
or any other key, then Enter to return to main menu\n
"""
response = ""
while not response:
chars = "0123456789"
chars += "abcdefghijklmnopqrstuvwxyz"
chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
chars += "?%^*+~-=[]{}:,.#_" # Oracle approved symbols
legit = False
while not legit:
seed(int(crypto_100()))
password = ""
for _ in range(length):
password += str(chars[randint(0, len(chars) - 1)])
legit = audit(password, display=False)
print("\033c\n ", it("green", password), "\n")
response = input(option_suggest.__doc__)
print("")
if response.isdigit():
response = int(response)
if response < 10:
input("minimum suggested length is 10, press Enter to continue")
length = 10
if response >500:
input("maximum supported length is 500, press Enter to continue")
length = 500
else:
length = response
response = ""
elif response:
wallet_main(passwords["master"]["master"], passwords)
def input_site_user():
"""
routine to input site and user name
"""
site = input("\nEnter site name: ")
if site == "master":
user = "master"
else:
user = input("\nEnter user name: ")
print("")
return site, user
def audit(password, display=True):
"""
\nyour password is weak, you should change it!
\naim for length greater or equal to 10
\nand 2 each unique uppers, lowers, digits, symbols\n
"""
uppers = []
lowers = []
digits = []
others = []
for item in [c for c in password]:
if item.isupper():
uppers.append(item)
elif item.islower():
lowers.append(item)
elif item.isdigit():
digits.append(item)
else:
others.append(item)
length = len(password)
uppers = len(list(set(uppers)))
lowers = len(list(set(lowers)))
digits = len(list(set(digits)))
others = len(list(set(others)))
review = {
"length": length,
"unique uppers": uppers,
"unique lowers": lowers,
"unique digits": digits,
"unique symbols": others,
}
legit = True
if not ((length >= 10) and (min(uppers, lowers, digits, others) >= 2)):
legit = False
if display:
print(it("purple", audit.__doc__), it("green", "audit:"), review)
return legit
if __name__ == "__main__":
wallet_main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:06:07.170",
"Id": "459134",
"Score": "1",
"body": "Please do not update the question after it has been answered, especially the code. See https://codereview.stackexchange.com/help/someone-answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:08:01.797",
"Id": "459135",
"Score": "0",
"body": "I made no changes to the original code; I get the moving target concept. I \"added\" an update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:10:37.427",
"Id": "459137",
"Score": "0",
"body": "Yes, which is why I didn't roll the question back to the previous version and up voted the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:14:02.777",
"Id": "459138",
"Score": "0",
"body": "can we agree it is ok if I continue to \"add updates\" on a definition by definition basis as long as I do not \"revise\" anything in the original? I'm want to keep this conversation as interactive as possible without losing history."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:16:46.977",
"Id": "459139",
"Score": "0",
"body": "Yes, just be aware that edits to questions that have been answered are automatically flagged in The 2nd Monitor https://chat.stackexchange.com/rooms/8595/the-2nd-monitor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T17:37:49.177",
"Id": "459237",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T17:38:23.777",
"Id": "459238",
"Score": "1",
"body": "@litepresence No. We can't, since every reviewer has to see the same version of the code or the thread won't make sense. Consider asking a follow-up question linking back to this one instead. Feel free to add a link to this question to your next one. All that is ok. What's not ok, is updating the code. That creates a mess."
}
] |
[
{
"body": "<p>I know very little about cryptography, so I'm not even going to attempt to comment on that aspect of it.</p>\n\n<p>I do see the odd thing that can be improved though.</p>\n\n<hr>\n\n<pre><code>if choice == 0:\n option_get(passwords)\n\nelif choice == 1:\n option_post(passwords)\n. . .\n</code></pre>\n\n<p>This has a lot of redundancy. The common pattern is you're dispatching on <code>choice</code>, then passing <code>passwords</code> to the given function (with the unfortunate exception of <code>exit</code>). This can be made more streamline either by using a list, or dictionary. Since you're using numbers 0 to 6 as \"keys\", this is arguably more appropriate as a list, but a dictionary would be more explicit:</p>\n\n<pre><code>MENU_DISPATCH = \\\n {0: option_get,\n 1: option_post\n 2: option_delete,\n . . .\n 6: lambda _: sys.exit}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>MENU_DISPATCH = \\\n [option_get,\n option_post,\n option_delete,\n . . .,\n lambda _: sys.exit]\n</code></pre>\n\n<p>Then, in either case:</p>\n\n<pre><code>f = MENU_DISPATCH[choice]\nf(passwords)\n</code></pre>\n\n<p>The dictionary has the benefit that you can easily do error checking:</p>\n\n<pre><code>f = MENU_DISPATCH.get(choice, None) # None on a bad option\n\nif f:\n f(passwords)\n\nelse:\n print(\"Bad option\")\n</code></pre>\n\n<hr>\n\n<p>I find it odd that <code>wallet_main</code> and <code>wallet_choices</code> are mutually recursive. Not only does this open you up to <code>RecursionError</code>s (if somehow they enter bad input ~1000 times), it makes the code harder to follow because execution is jumping back and forth between the functions. Do you actually need the <code>if passwords is None:</code> and the rest of that code to run every time they make an error?</p>\n\n<p>I'd make <code>wallet_choices</code> handle input completely. I'd also introduce a <code>parse_int</code> function so you don't need to wrap calls to <code>int</code> with a <code>try</code>, and get rid of the catching of the <code>AssertionError</code>. I think catching an assert error like you are here is an abuse of <code>assert</code>.</p>\n\n<pre><code>from typing import Optional\n\n\ndef parse_int(text_num: str) -> Optional[int]:\n \"\"\"Returns the parsed number, or None if the parse failed.\"\"\"\n try:\n return int(text_num)\n\n except ValueError:\n return None\n\ndef wallet_choices(master, passwords):\n \"\"\"\n 1: ENTER A NEW PASSWORD OR EDIT A PASSWORD\n 2: DELETE A PASSWORD\n 3: SUGGEST A PASSWORD\n 4: PRINT SITE/USER LIST\n 5: PRINT SITE/USER/PASSWORD LIST\n 6: EXIT\n \"\"\"\n print(it(\"green\", wallet_choices.__doc__))\n\n while True: # Imperative loop instead of recursion\n choice = input(\"input choice or press Enter to GET A PASSWORD: \")\n choice = choice or \"0\" # That check can be reduced down by taking advantage of `or`\n\n choice = parse_int(choice)\n\n if choice is not None and 0 <= choice <= 6: # Just use if instead of assert to jump to error handling\n return choice\n\n else:\n print(\"\\033cinvalid choice (\", choice, \") try again\")\n time.sleep(2)\n # Will loop back to the top from here\n</code></pre>\n\n<hr>\n\n<p>Just a heads up, you can use <a href=\"https://pypi.org/project/colorama/\" rel=\"noreferrer\">Colorama</a> instead of your <code>it</code> function.</p>\n\n<hr>\n\n<p>In <code>doc_write</code>, you have:</p>\n\n<pre><code>with open(document, \"w+\") as handle:\n handle.write(text)\n handle.close()\n</code></pre>\n\n<p>This defeats the purpose of using <code>with</code> though. <code>handle</code> is automatically closed when <code>with</code> is exited and the <code>TextIOWrapper</code>'s <code>__exit__</code> method is called. You just need:</p>\n\n<pre><code>with open(document, \"w+\") as handle:\n handle.write(text)\n</code></pre>\n\n<p>And then the same with <code>doc_read</code>.</p>\n\n<hr>\n\n<p>In <code>trace</code>, you have:</p>\n\n<pre><code>\"\\n\\n\" + str(time.ctime()) + \"\\n\\n\" + str(traceback.format_exc()) + \"\\n\\n\"\n</code></pre>\n\n<p>This can be neatened up using f-strings:</p>\n\n<pre><code>f\"\\n\\n{time.ctime()}\\n\\n{traceback.format_exc()}\\n\\n\"\n</code></pre>\n\n<p>Or maybe using <code>join</code> if you want to reduce the duplicated double-newlines:</p>\n\n<pre><code>\"\\n\\n\".join([time.ctime(), traceback.format_exc()])\n</code></pre>\n\n<p>And then similarly in <code>it</code>:</p>\n\n<pre><code>\"\\033[%sm\" % emphasis[style]) + str(text) + \"\\033[0m\"\n</code></pre>\n\n<p>This can be:</p>\n\n<pre><code>f\"\\033[{emphasis[style]}m{text}\\033[0m\"\n</code></pre>\n\n<p>f-strings are often preferable over <code>format</code> or <code>%</code>.</p>\n\n<hr>\n\n<p>Instead of:</p>\n\n<pre><code>for user, _ in logins.items():\n</code></pre>\n\n<p>You can just do:</p>\n\n<pre><code>for user in logins.keys():\n</code></pre>\n\n<hr>\n\n<pre><code>chars = \"0123456789\"\nchars += \"abcdefghijklmnopqrstuvwxyz\"\nchars += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nchars += \"?%^*+~-=[]{}:,.#_\"\n</code></pre>\n\n<p>This whole bit could be neatened up using <code>string.printable</code>, or another member from <a href=\"https://docs.python.org/3.8/library/string.html\" rel=\"noreferrer\"><code>string</code></a>. That module contains strings to be used for purposes like this:</p>\n\n<pre><code>import string\n\n>>> string.printable\n'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~ \\t\\n\\r\\x0b\\x0c'\n</code></pre>\n\n<p>If there's stuff in there you don't want, you could either filter it, or just use a more narrow set of constants from that module:</p>\n\n<pre><code>>>> string.ascii_letters + string.digits + \"?%^*+~-=[]{}:,.#_\"\n'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789?%^*+~-=[]{}:,.#_'\n</code></pre>\n\n<p>Either way, that's far less verbose</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T01:22:04.667",
"Id": "459102",
"Score": "0",
"body": "re: colorama, want to avoid 3rd party utilities; security, re: double recursion & passwords=None and choices/main... yes I do think those two definitions need to be combined; it just broke every time I've tried so far (only day 3), will put on todo list. re: string.ascii_letters cute! will do!; re f-string... hesitant as many users still <3.6, but yes cleaner; re: handle.close() I've actually seen that fail in race conditions without; so just needless habit here&now; re: login.keys(), yes!; re: dict(MENU), nice!; re: assert will look into cleaning that up. Thanks! v4.0 coming soon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:02:05.747",
"Id": "459133",
"Score": "0",
"body": "all of your suggestions (except colorama) have been implemented. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:08:46.987",
"Id": "459136",
"Score": "0",
"body": "@litepresence No problem. Glad to help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:19:24.127",
"Id": "459140",
"Score": "0",
"body": "btw... TIL definition values can be functions! I had never considered such a thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:25:29.507",
"Id": "459141",
"Score": "0",
"body": "@litepresence What do you mean? That functions can be put into a dictionary? Functions are *first class* citizens in Python. They are objects that can be passed around and stored like other objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:37:35.617",
"Id": "459143",
"Score": "0",
"body": "Until now, I had only ever used dictionaries for values supported by JSON: str, int, float, list, dict, bool, None. You taught me something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T15:45:22.600",
"Id": "459144",
"Score": "0",
"body": "@litepresence Ah. Any object can be a value in a dictionary, so they're pretty wide in what they can store. Only hashable (and usually immutable) objects can be keys however."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T00:48:24.597",
"Id": "234713",
"ParentId": "234705",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T21:45:35.067",
"Id": "234705",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"security",
"cryptography",
"aes"
],
"Title": "CypherVault - Command Line Password Manager"
}
|
234705
|
<p>Hangman game coded in Java (at a beginner's level) where Hangman.java can be run with one or more arguments.</p>
<p>Hangman.java:</p>
<pre><code>package hangman;
import hangman.Game;
import hangman.Prompter;
public class Hangman {
public static String normalizeArgs(String[] array) {
String result = "";
switch (array.length) {
case 0:
System.out.println("Usage: java Hangman <answer>");
System.err.println("answer is required");
System.exit(1);
break;
case 1:
result = array[0];
break;
default:
for (int i = 0; i < array.length; i++) {
result += array[i];
if (i != array.length-1) {
result += ' ';
}
}
}
return result;
}
public static void main(String[] args) {
Game game = new Game(normalizeArgs(args));
Prompter prompter = new Prompter(game);
while (game.getRemainingTries() > 0 && !game.isWon()) {
prompter.displayProgress();
prompter.promptForGuess();
}
prompter.displayOutcome();
}
}
</code></pre>
<p>Prompter.java:</p>
<pre><code>package hangman;
import java.util.Scanner;
public class Prompter {
private Game game;
public Prompter(Game game) {
this.game = game;
}
public boolean promptForGuess() {
Scanner scanner = new Scanner(System.in);
boolean isHit = false;
boolean isAcceptable = false;
do {
System.out.printf("Enter a letter: ");
String guessInput = scanner.nextLine().toLowerCase();
try {
isHit = game.applyGuess(guessInput);
isAcceptable = true;
} catch (IllegalArgumentException iae) {
System.out.printf("%s. Please try again. %n",
iae.getMessage());
}
} while (!isAcceptable);
return isHit;
}
public void displayProgress() {
System.out.printf("You have %d tries left to solve: %s%n",
game.getRemainingTries(),
game.getCurrentProgress());
}
public void displayOutcome() {
if (game.isWon()) {
System.out.printf("Congratlations! You won with %d tries left.%n", game.getRemainingTries());
} else {
System.out.printf("Bummer! The word was %s. :(%n", game.getAnswer());
}
}
}
</code></pre>
<p>Game.java:</p>
<pre><code>package hangman;
public class Game {
public static final int MAX_TRIES = 7;
private String answer;
private String hits;
private String misses;
public Game(String answer) {
this.answer = answer.toLowerCase();
hits = "";
misses = "";
}
private char normalizeGuess(char letter) {
if (!Character.isLetter(letter)) {
throw new IllegalArgumentException("Guess is not a letter");
}
if (hits.indexOf(letter) != -1 || misses.indexOf(letter) != -1) {
throw new IllegalArgumentException("Letter already guessed");
}
return letter;
}
public boolean applyGuess(String letters) {
if (letters.length() == 0) {
throw new IllegalArgumentException("No letters found");
}
return applyGuess(letters.charAt(0));
}
public boolean applyGuess(char letter) {
normalizeGuess(letter);
boolean isHit = answer.indexOf(letter) != -1;
if (isHit) {
hits += letter;
} else {
misses += letter;
}
return isHit;
}
public int getRemainingTries() {
return MAX_TRIES - misses.length();
}
public String getCurrentProgress() {
String progress = "";
for (char letter : answer.toCharArray()) {
if (hits.indexOf(letter) != -1) {
progress += letter;
} else if (letter == ' ') {
progress += ' ';
} else {
progress += '-';
}
}
return progress;
}
public boolean isWon() {
return getCurrentProgress().indexOf('-') == -1;
}
public String getAnswer() {
return answer;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Nice code overall, doesnt feel like beginner. A few points:</p>\n\n<ul>\n<li><p>case for single argument in your <code>normalizeArgs</code> switch can be covered by <code>default</code> branch</p></li>\n<li><p>I don't like your main game loop conditions. Basically first half compares number of remaining tries, that effectively means asking if game is lost. Second half asks if game is won. Then can change to checking for joined win/loss conditions, but you can put it one step further and make boolean method in Game, that will tell you, if game still runs/continues and use that as your loop condition.</p></li>\n<li><p>feels like Strings for <code>displayProgress</code> and <code>displayOutcome</code> should be in class <code>Game</code>. Create something like <code>progressMessage</code> and <code>outcomeMessage</code> methods there, that will return <code>String</code>. <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.util.Locale,%20java.lang.String,%20java.lang.Object...)\" rel=\"nofollow noreferrer\">String.format</a> has same functionality as <code>printf</code>. Then you are more flexible and correct class has the responsibility. You just print messages in <code>Prompt</code> class.</p></li>\n<li><p>Not sure about using <code>System.err</code> that one time, while not using it to display exception messages. But I cant really say if its good or bad.</p></li>\n<li><p>Too many public methods in <code>Game</code> class. I'd leave only single method for <code>applyGuess</code> - the one that accepts char. It describes more what you want - single character and is cleaner API. Other one also accepts strings longer than one char and imho that functionality shouldn't be here, but in prompter - it is input checking. Extracting that loop condition (mentioned above) also allows more methods to be possibly private.</p></li>\n<li><p>max tries could be constructor parameter to add more flexibility.</p></li>\n<li>Excellent exception usage imho.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T05:22:15.663",
"Id": "234721",
"ParentId": "234706",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T22:08:01.363",
"Id": "234706",
"Score": "1",
"Tags": [
"java",
"beginner",
"programming-challenge",
"hangman"
],
"Title": "Hangman game in beginning Java"
}
|
234706
|
<p>I am working on moving a save system from loose files to a (spatial sqlite) database.</p>
<p>The user places objects from a library in a 3d simulation. Scenarios are "what-ifs", what if we place 5 wind turbines over here, what if we placed 10 racks of solar panels instead etc. They are mutually exclusive within a "group".</p>
<p>Items are prototype objects that can be instantiated by the user. Wind turbines and solar panel racks are specializations of items with extra data.</p>
<p>This is the first time I've done SQL outside of trivial school projects so please don't hold back on pointing out best practices / tips.</p>
<p>Do my FKs make sense?</p>
<p>Is it proper in form?</p>
<p>Thanks in advance.</p>
<p>interactive version: <a href="https://dbdiagram.io/d/5e04aa5eedf08a25543f6bc5" rel="nofollow noreferrer">https://dbdiagram.io/d/5e04aa5eedf08a25543f6bc5</a>
you can export SQL from there if that is easier to read.</p>
<p>pseudo sql below.</p>
<pre><code>//a mutually exclusive group of scenarios
Table group
{
group_id int [pk, increment]
name text [unique, not null]
active_scenario_id int [ref: - scenario.scenario_id]
is_active bool
}
//a user created arrangment of item instances
Table scenario
{
scenario_id int [pk, increment]
group_id int [ref: > group.group_id]
name text [not null]
}
//an item is a prototype. an object that can be repeated many times.
//the name identifies a prefab in the application
Table item
{
item_id int [pk, increment]
name text [unique, not null]
}
//an instance of an item prototype in the world
Table instance
{
instance_id int [pk, increment]
scenario_id int [ref: < scenario.scenario_id]
item_id int [ref: - item.item_id]
position PointZ [not null]
rotationX float [default: 0]
rotationY float [default: 0]
rotationZ float [default: 0]
scaleX float [default: 1]
scaleY float [default: 1]
scaleZ float [default: 1]
active_date datetime [null]
inactive_date datetime [null]
}
//a LineString created by the user.
Table user_path
{
instance_id int [pk, increment, ref: - instance.instance_id]
win3d_style_id int [ref: < win3d_style.win3d_style_id]
path LineStringZ
viewPath LineStringZ
float duration [note: 'duration if this path is an animation']
}
//a polygon created by the user
Table user_polygon
{
instance_id int [pk, increment, ref: - instance.instance_id]
name text [not null]
geometry PolygonZ
win3d_sytle_id int [ref: < win3d_style.win3d_style_id]
}
//a wind turbine is a kind of item with extra data
Table wind_turbine
{
item_id int [pk, increment, ref: - item.item_id]
rotor_diameter float
shaft_height float
shaft_base_diameter float
shaft_neck_diameter float
min_wind_speed float [note: 'wind speed in m/s at which the blades starts spinning']
max_wind_speed float [note: 'wind speed in m/s at which the blades reaches peak rotations per minute']
off_speed float [note: 'wind speed in m/s at which the blades is stopped for safety']
min_rotations_per_minute float [note: 'rpm at which the blades spin when the wind speed equals min_wind_speed']
max_rotations_per_minute float [note: 'rpm at which the blades spins when the wind speed equals max_wind_speed']
watt_min long [note: 'Watt produced at the min_wind_speed']
watt_max long [note: 'Watt produced at the max_wind_speed']
}
Enum solar_panel_rack_kind
{
poles
praxiz
}
Enum solar_panel_facing
{
south
east_west
}
//a solar panel rack is a kind of item with extra data.
//a solar panel rack is an arrangement of solar panels
Table solar_panel_rack
{
item_id int [pk, increment, ref: - item.item_id]
solar_panel_id int [ref: - solar_panel.solar_panel_id]
num_columns int
num_rows int
column_gap int [note: 'centimeters between each column']
row_gap int [note: 'centimeters between each row']
kind solar_panel_rack_kind
facing solar_panel_facing
}
Enum solar_panel_kind{
polycrystalline
monocrystalline
bifacial
}
Table solar_panel
{
solar_panel_id int [pk, increment]
width int [note: 'centimeters']
height int [note: 'centimeters']
watt_peak long
kind solar_panel_kind
}
Table win3d_style
{
win3d_style_id int [pk, increment]
primary_color uint32 [default: 4294967295, note: 'default is opaque white']
secondary_color uint32 [default: 4294967295, note: 'default is opaque white']
}
Table point_of_view
{
point_of_view_id int [pk, increment]
scenario_id int [ref: < scenario.scenario_id]
name text
position PointZ [not null]
rotationX float [default: 0]
rotationY float [default: 0]
rotationZ float [default: 0]
field_of_view float [default: 30]
thumbnail blob [note:'jpg encoded image']
}
</code></pre>
<p><a href="https://i.stack.imgur.com/R3Zl7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R3Zl7.png" alt="image of schema"></a></p>
|
[] |
[
{
"body": "<p>few comments: </p>\n\n<ul>\n<li>avoid data type float, unless you don't care about not accurate rounding. </li>\n<li>Solar_panel_rack, solar_panel and wind_turbine I would change structure:merge solar panel with solar_panel_rack if possible also would probably join wind turbine with solar panel_rack. It could potencialy have columsn like:\nItemId, ItemTypeId(wind turbine or solar), ItemName, other characteristics. \nYour current architecture would complicate future queries.</li>\n<li>remove item table as it is just smaller version of wind turbine and solar panel</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T12:21:06.190",
"Id": "235007",
"ParentId": "234707",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T22:28:28.007",
"Id": "234707",
"Score": "1",
"Tags": [
"sql",
"database",
"sqlite"
],
"Title": "Scenario creator database design"
}
|
234707
|
<p>I am trying to find a way to convert printable data types into a string in the fastest way possible.</p>
<p>I originally read that a static variable of <code>stringstream</code> that does all of the formatting is one of the fastest ways, since constantly constructing temporary variables of <code>stringstream</code> is slow.</p>
<p>The problem with using <code>stringstream.str()</code> is because it creates a copy of the entire string, which may lead to performance issues, so I made this function to get rid of the need of <code>stringstream.str()</code>.</p>
<pre><code>#include <iostream>
#include <sstream>
#include <streambuf>
#include <vector>
#include <string>
#define ALL(c) (c).begin(), (c).end()
stringstream str_buffer;
string extract()
{
streambuf& buffer = *str_buffer.rdbuf();
vector<char> sequence(str_buffer.tellp());
buffer.sgetn(sequence.data(), str_buffer.tellp());
str_buffer.seekp(0);
buffer.pubseekpos(0);
return string(ALL(sequence));
}
</code></pre>
<p>To use this function, just do <code>str_buffer << var; string as_str = extract();</code> to get var as a string.</p>
<p>However, I have not yet compared timing benchmark results of this function and simply using <code>stringstream.str()</code>, so I hope that my function is faster if it is in theory. Any suggestions to further improve?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T01:04:02.477",
"Id": "459098",
"Score": "0",
"body": "So and `return string(ALL(sequence));` doesn't take a copy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T13:01:34.840",
"Id": "459118",
"Score": "1",
"body": "you might want to have a look at <charconv> or <format> from C++20"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T20:39:30.833",
"Id": "459167",
"Score": "1",
"body": "Go and benchmark your code right now. We can have all the theoretical discussions you want, but it's very hard to predict what the fastest way is, especially with compilers as good at optimizing as they are today."
}
] |
[
{
"body": "<p>Your function modifies the get/put position of the buffer. I think this is a bug, and it makes benchmarks misleading. Try calling <code>extract</code> twice in a row -- you'll get different results. You set the put position after calling <code>sgetn</code> but you should have set the get position. This should be intuitive. After a read, you \"undo\" your reading. Fix the bug with something like this:</p>\n\n<pre><code>string extract() {\n streambuf& buffer = *str_buffer.rdbuf();\n vector<char> sequence(str_buffer.tellp());\n auto g = str_buffer.tellg();\n buffer.sgetn(sequence.data(), str_buffer.tellp());\n str_buffer.seekg(g); // seekg to the original position\n // as far as I can work out, buffer.pubseekpos is not necessary here?\n return string(ALL(sequence));\n}\n</code></pre>\n\n<p>Your function still does not compute the same thing as <code>str</code>. <code>str</code> returns the entire buffer. Your function returns from the input position to the output position. These are different -- try calling <code>str_buffer.seekg(3)</code> before comparing the output of the two functions if you want to see for yourself. You could <code>seekg(0)</code> before you call <code>sgetn</code>:</p>\n\n<pre><code> auto g = str_buffer.tellg();\n str_buffer.seekg(0);\n buffer.sgetn(sequence.data(), str_buffer.tellp());\n str_buffer.seekg(g);\n</code></pre>\n\n<p>I think this implementation is now correct enough to benchmark. I tried the updated version vs <code>str</code> on <a href=\"http://quick-bench.com\" rel=\"nofollow noreferrer\">http://quick-bench.com</a>. I used clang-9 and libstdc++(GNU). I tried a <code>stringstream</code> with 1000 characters and also 10,000 characters.</p>\n\n<p>This implementation is about 130 times slower than <code>str</code> with no optimizations and with -O1/Clang, and it is and 3.5 times slower with -O2/Clang.</p>\n\n<hr>\n\n<p>How can you speed up your function? Well the easiest way is to use <code>str</code>! But let's make some small improvements. You copy the buffer into a <code>vector<char></code> and then copy the vector into a string. What if we only have one string?</p>\n\n<pre><code>string extractOneString() {\n std::string sequence;\n sequence.resize(str_buffer.tellp());\n auto g = str_buffer.tellg();\n str_buffer.seekg(0);\n str_buffer.rdbuf()->sgetn(sequence.data(), str_buffer.tellp());\n str_buffer.seekg(g);\n return sequence;\n}\n</code></pre>\n\n<p>Now the unoptimized version is 3.5 times slower -- just like the optimized version before. As it turns out, the Clang's -O2 was already making this change for you.</p>\n\n<p>Still, 3 times slower is not good.</p>\n\n<p>This is maybe not obvious, but if you look at the assembly (perhaps using <a href=\"http://godbolt.org\" rel=\"nofollow noreferrer\">http://godbolt.org</a>), you'll notice that <code>resize</code> calls memset to set the new buffer to zero. That's not necessary since you're about to overwrite the buffer anyway. There's no easy way to get around this (unless you count using <code>str</code>). I think this contributes to the 3x slowdown (not sure and I don't think it's worth confirming).</p>\n\n<hr>\n\n<p>A few notes about your code:</p>\n\n<ol>\n<li><p>Don't use <code>using namespace std</code>. People have written about this in lots of places so I won't here.</p></li>\n<li><p>The <code>ALL</code> macro is ugly and unnecessary. If you cannot stand to write iterators, look into the new ranges library.</p></li>\n</ol>\n\n<hr>\n\n<p>It's worth learning sooner rather than later not to spend time optimizing the wrong thing. You wrote this code and then (I) measured it. Next time, measure your code first and then decide whether it's worth changing. This has the added advantage that you're already set up to measure the code post change.</p>\n\n<p>I think it's also worth focusing on the basic semantics of your program before worrying too much about measured performance. An experienced C++ dev would see right away that your <code>extract</code> function has a unnecessary copies and would most likely fix that before profiling. Learning to avoid copies and other idioms will help you avoid having to measure every little thing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T05:41:55.270",
"Id": "240026",
"ParentId": "234710",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T00:09:57.327",
"Id": "234710",
"Score": "3",
"Tags": [
"c++",
"performance",
"strings",
"c++11"
],
"Title": "Fast Stream Formatting Into String"
}
|
234710
|
<p>I wrote code that takes the value of the progress bar in my Android app which influences what is displayed on the UI. If the user's progress bar value is above or below a certain number, data will be either displayed or not displayed. Here is the following code:</p>
<pre class="lang-java prettyprint-override"><code> public class DetailsFirstTabFragment extends Fragment {
private DetailsFirstTabViewModel viewModel;
private RecyclerView recentThings;
private TextView progressTextView;
final RecentThings adapter = new RecentThings();
private List<ThingEntity> thingEntities;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel =
ViewModelProviders.of(this).get(DetailsFirstTabViewModel.class);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_first_page_expense_details, container, false);
recentThings = root.findViewById(R.id.recycler_view_recent_things);
recentThings.setLayoutManager(new LinearLayoutManager(getContext()));
recentThings.setHasFixedSize(true);
recentThings.setAdapter(adapter);
final float[] totalSum = {0};
final TextView textViewTotalSum = root.findViewById(R.id.textViewStuffTotalSum);
SeekBar seekBar = root.findViewById(R.id.seekBarStuffDetails);
seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
progressTextView = root.findViewById(R.id.textViewProgress);
viewModel.getAllThings().observe(this, new Observer<List<ThingEntity>>() {
@Override
public void onChanged(List<ThingEntity> thingEntities) {
for (ThingEntity thing : thingEntities) {
totalSum[0] = totalSum[0] + thing.getThingAmount();
}
textViewTotalSum.setText(String.valueOf(totalSum[0]));
adapter.setThingEntityList(thingEntities);
setThingEntities(thingEntities);
}
});
return root;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
Bundle args = getArguments();
}
public void setThingEntities(List<ThingsEntity> thingEntities) {
this.thingEntities = thingEntities;
}
SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
int progressValue = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String progressText = "Date " + String.valueOf(progress);
progressValue = progress;
progressTextView.setText(progressText);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
List<ThingEntity> shownThings = new ArrayList<>();
for (ThingEntity entity : thingEntities) {
if (entity.getThingAmount() > progressValue) {
shownThings.add(entity);
}
}
adapter.setThingEntityList(shownThings);
}
};
}
</code></pre>
<p>So I am wondering if I am treating this need in a good way. I am not sure if getting all the entities and then looping over them to see if the condition is met to display is a good implementation. Additionally, I am wondering if the rest of the code makes sense. I am also not sure if I am creating viewmodels and observers in a resource-mindful manner. Any insight to these concerns (or ones I have not observed) would be very much appreciated (I am a beginner :))</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T02:40:57.690",
"Id": "234715",
"Score": "1",
"Tags": [
"java",
"android",
"sqlite"
],
"Title": "Uses SeekBar to adjust the data displayed in UI from my Room database"
}
|
234715
|
<p>i'm using an external API that posts products and orders into a marketplace, and it provides a class that in each request i have to specify an <code>endpoint</code>, <code>user</code> and <code>password (token)</code>, it's something like this:</p>
<pre><code>if($env == 'testing') {
$endpoint = 'testing';
$user = 'testing';
$pass = 'testing';
} else {
$endpoint = 'production';
$user = 'production';
$pass = 'production';
}
$itemSender = new ItemSender($endpoint, $user, $pass);
$orderSender = new OrderSender($endpoint, $user, $pass);
</code></pre>
<p>my first thought was to use the <strong>strategy pattern</strong> so i can have both <strong>testing</strong> and <strong>production</strong> environment, or even others environments, implementing an <strong>interface</strong>, i built something lie this:</p>
<pre><code>interface EnviromentInterface () {
function getEndpoint();
function getUser();
function getPassword();
}
class TestingEnvironment implements EnviromentInterface {
private $endpoint;
private $user;
private $password;
function getEndpoint() {
return $this->endpoint;
// return getFromConfigFile('API_ENDPOINT_TESTING');
}
function getUser() {
return $this->user;
}
function getPassword() {
return $this->password;
}
}
class ProductionEnviroment implements EnviromentInterface {
private $endpoint;
private $user;
private $password;
function getEndpoint() {
return $this->endpoint;
// return getFromConfigFile('API_ENDPOINT_PRODUCTION');
}
function getUser() {
return $this->user;
}
function getPassword() {
return $this->password;
}
}
</code></pre>
<p>and i would overwrite the parent's class <code>construct</code> to use the environment object, something like this:</p>
<pre><code>class CustomItemSender extends ItemSender
{
function __construct(EnviromentInterface $env)
{
parent::__construct($env->getEndpoint(), $env->getUser(), $env->getPassword());
}
}
</code></pre>
<p>the problem is: how can i switch between these environment objects? i thought about using a <code>switch/case</code>, but if i need to implement more environments i have to add another if to the switch/case statment.</p>
<p>what would be a good aproach in this case? </p>
<p><strong>important</strong>: all info/credentials about the testing and production environments are inside a config file, that in this case is an <code>.env</code> file</p>
|
[] |
[
{
"body": "<p>You are probably looking for factory method pattern, instead of strategy pattern.</p>\n\n<p>The <code>CustomItemSender</code> class is a good indicator of this.\nWhenever you extend a class to only override the constructor, you probably need a factory instead. It means you need somewhat more complex way of constructing the object and that implies creational pattern. Strategy is a behavioral pattern (and in fact, your code does not implement this pattern).</p>\n\n<p>The <code>EnvironmentInterface</code> is basicaly a data structure, it is immutable which is good, but it has no behaviour, which is not so good. It is just a tuple. Maybe you don't really need this structure and stay with tripplet of arguments.</p>\n\n<p>Polymorphism only makes sense to abstract varying behaviour, not data. Anyway polymorphism won't help you avoid ifs/switches entirely. It will help you reduce the amount of them to minimum. You might still need some ifs in the creational part, but once a polymorhic object is created, it no longer repeats those ifs because it encapsulates the beforehand chosen branch.</p>\n\n<p>Sometimes ifs/switches can be replaced by key-value maps though (such a map could be owned by a factory...).</p>\n\n<p>Getting config values from a file using global function like yours <code>getFromConfigFile(string $key)</code> is not very wise btw. Because it either loads the file again on every request for a key. Or it loads it only once but stores the loaded data to a global variable thus having side effects on globle state which is a bad practice. You might want to load all config from the file to lets say array (possibly encapsulated in an objet) and serve the individual config values from it. And btw the function knows the location of the config file globally/magically and that is also not very good. You might need a factory for the config object, which will load the config from a given a file.</p>\n\n<pre><code>function loadConfigFromJsonFile(string $filename): array\n{\n // add error handling\n return json_decode(file_get_contents($filename), true);\n}\n\nclass SenderFactory\n{\n\n private string $endpoint;\n private string $user;\n private string $password;\n\n public function __construct(string $endpoint, string $user, string $password)\n {\n $this->endpoint = $endpoint;\n $this->user = $user;\n $this->password = $password;\n }\n\n public function createOrderSender(): OrderSender\n {\n return new OrderSender($this->endpoint, $this->user, $this->password);\n }\n\n public function createItemSender(): ItemSender\n {\n return new ItemSender($this->endpoint, $this->user, $this->password);\n }\n}\n\nfunction createSenderFactory(string $env, array $config): SenderFactory\n{\n // the if has to go somewhere anyway\n // add some error handling too (missing config keys, unknown $env, etc.)\n if ($env === 'testing') {\n return new SenderFactory($config['API_ENDPOINT_TESTING'], 'testing', 'testing');\n } else {\n return new SenderFactory($config['API_ENDPOINT_PRODUCTION'], 'production', 'production'); \n }\n}\n\n\n// ...\n\n\n$config = loadConfigFromJsonFile($configPath);\n$factory = createSenderFactory($env, $config);\n$orderSender = $factory->createOrderSender();\n$itemSender = $factory->createItemSender();\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T23:48:27.280",
"Id": "459182",
"Score": "0",
"body": "i see, i'm going to read more about the factory pattern, but could you make an example using code? so i can have a better idea, and what would make this a strategy pattern?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T00:00:07.683",
"Id": "459183",
"Score": "1",
"body": "@NBAYoungCode Yep, I have added the factories examples.Anyway, I don't think you should try to turn it to strategy pattern. Characteristic of strategy object is that it is held by the consumer for its entire lifetime (because the consumer's methods require the strategy's methods), not just used in constructor and then discarded."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T00:06:09.400",
"Id": "459184",
"Score": "0",
"body": "i think i got it, also gonna take a deep look about the strategy pattern. but, hypothetically, so if i had more methods in my class using the methods of the strategy object, it would be a strategy pattern? this idea of \"controlling the lifetime\" means using features that the object provides, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T00:10:44.277",
"Id": "459185",
"Score": "1",
"body": "@NBAYoungCode Yes. If you needed to override behaviour of (some) method(s) of lets say ItemSender, and this override can itself be different under different circumstances, then yes - a strategy may drive those differences. You gotta remember that patterns may cross. For example factory is creational pattern. But its ability to create something is a behviour and so for example a factory may own a strategy that tells it how the creation of objects should be done. Which is actualy not very far from another creational pattern - the builder..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T23:25:01.507",
"Id": "234765",
"ParentId": "234717",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T03:39:30.170",
"Id": "234717",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"design-patterns"
],
"Title": "strategy pattern, good practices on how to switch between classes"
}
|
234717
|
<blockquote>
<p>I have a folder containing thousands of files and directories. I
would like to move all the files that are not contained in a sub
directory into a directory and name it the file name, while leaving
the files already inside of directories alone, ie:</p>
<p>create 'newdir' ; move 123.mp4 ; into 'newdir' ; change name 'newdir' to
'123' ; repeat . </p>
</blockquote>
<p>In response to the mentioned question, I posted an <a href="https://apple.stackexchange.com/questions/377654/terminal-command-to-move-all-loose-files-into-a-directory-with-the-file-name/377692#377692">answer</a> with the following script.</p>
<pre><code>#%%
import os
# %%
source = "/Users/me/Desktop/folder" # notice the missing last "/"
filenames = next(os.walk(source))[2]
filenames = [ x for x in filenames if not ".DS_Store" in x]
#%%
dirpaths = [os.path.splitext(file)[0] for file in filenames]
# %%
def making(directory,source=source):
directory = os.path.join(source,directory+"/")
os.makedirs(directory)
a = [making(directory) for directory in dirpaths] #list comprehension could be faster than loops.
# %%
def movingfiles(onefile, source=source):
os.rename(source + "/" + onefile, source + "/" + os.path.splitext(onefile)[0] + "/" + onefile )
b = [movingfiles(onefile) for onefile in filenames] #useless list again.
</code></pre>
<p>I want to know whether list comprehensions are better the way I used them. Also, I know that I can avoid the directory list and making a lot of empty directories at once by putting them in one function (and make "the" directory on the spot), but can anything else be improved? For e.g., I had to put a note to avoid putting <code>/</code> in <code>source</code>. Also, is this way of using lists to perform a function actually helpful?</p>
|
[] |
[
{
"body": "<p>Like you noticed, no need to use multiple loops when you can do everything in one function and loop only once.</p>\n\n<p>Aside from that, there are many small things that can be improved with this script:</p>\n\n<ul>\n<li>This script doesn't work if the script is not in the same directory as the source directory. Correct if me I am wrong, but this is what I encountered when I tested the code. To allow for this flexibility (of using this script at any arbritary location), it is necessary to use absolute paths.</li>\n<li>We should probably check if the directory we're about to create already exists. It may be possible that two images may have the same basename but different extensions. For this case, using <code>os.path.exists</code> will save us down the road and is simple to implement.</li>\n<li>I noticed you excluded <code>.DS_Store</code> from filenames. I took it a step further and excluded all hidden files and files that started with <code>__</code> (like Python build directories/files). </li>\n<li>When using a loop comprehension for the sake of the for loop and not for the results, there's no need to store the output. For example, when using <code>a = [making(directory) for directory in dirpaths]</code>, it is more useful to only write <code>[making(directory) for directory in dirpaths]</code> on that line. Storing it as a result implies that the output is being used somewhere later in the script, when in this case, it is not useful in the final version.</li>\n<li>It is better to use <code>shutil.move</code> for the <code>movingfiles</code> function. Under the hood, Python will decide whether to use <code>os.rename</code> or if a copy-remove operation is neccesary (see <a href=\"https://docs.python.org/3/library/shutil.html#shutil.move\" rel=\"nofollow noreferrer\">shutil.move</a> for more information).</li>\n<li>Using <code>os.makedirs</code> is overkill for this example here. <code>os.makedirs</code> is meant for <strong>recursively creating directories</strong>, not for single-level directory creation. The similiarily named <code>os.mkdir</code> is more appropriate here and probably will be more performant.</li>\n<li>It is not necessary to check if the source directory string contains a <code>'/'</code>. On the <a href=\"https://docs.python.org/3/library/os.path.html#os.path.join\" rel=\"nofollow noreferrer\">documentation</a>, <code>os.path.join</code> verifies that the result will have \"exactly one directory seperator\". Therefore, we don't have worry about extra logic.</li>\n<li>Normally, I wouldn't bother with optimization when the context of the script is for running a few files. In the case of the thousands of objects, however, it is <strong>crucial</strong> to reduce how many loops we run. In the code below, you see implicit use of <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generators</a>. Specifically, we will lazily evaluate our list of filenames upto the point we process each filename. This means we only run through our list of filenames once(!)</li>\n<li>On the topic of performance, when we have a custom function defined (read: not <code>lambda</code>), it almost always better to use <code>map</code> when we don't require storing the output. On Python2, the advantage was neglible, but on Python3, the difference is noticable. So we will use <code>map</code> below. (<code>map</code> is very much faster when using builtin Python functions that call on C code. Why? Because <code>map</code> also reaches down to C, meaning you get a barebones C loop for those operations. Looping in Python is unintuitively bloated compared to C.)</li>\n<li>The use <code>os.path.splitext</code> is correct for this script. However, there is a slight performance cost to using this function, and so I opted for the leaner <code>.split('.', 1)[0]</code> which is faster. As long as the filenames don't contain <code>'.'</code> other than at the end as an extension, we'll be fine. </li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\nimport os\nimport shutil\nimport argparse\nimport functools\n\n\ndef mkdir_move_file(file, source):\n directory = file.split('.', 1)[0] \n if not os.path.exists(directory):\n os.mkdir(directory)\n shutil.move(file, directory)\n\n\ndef mkdir_move_all_files(source):\n if not os.path.exists(args.source):\n raise Exception('Source folder cannot be found or does not exist!')\n filenames = (os.path.join(source, x) for x in next(os.walk(source))[2]\n if not x.startswith('.') and not x.startswith('__'))\n\n # basically the same as [mkdir_move_file(file, source) for file in filenames]\n map(functools.partial(mkdir_move_file, source=source), filenames)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Make folders for loose files in folder.')\n parser.add_argument('source', action='store', type=str, help='The source directory to process.')\n\n args = parser.parse_args()\n\n mkdir_move_all_files(args.source)\n</code></pre>\n\n<p>Some further notes, beyond the initial scope of the question:</p>\n\n<ul>\n<li>Python makes it simple to create scripts-- the key is using the <code>argparse</code> library. This library lets us parse arguments given through the command line, which can then be passed along the functions internally. Simply add parsing to your script and you can use the executable script from the command line!</li>\n<li>If our <code>mkdir_move_all_files</code> function was more complicated/intensive, we could use asynchronous programming to speed up our overall program. That way we can fire off multiple evaluations without waiting for the result to complete. However, I don't see it being hugely beneficial for this case.</li>\n</ul>\n\n<p>If you have any questions let me know.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-31T21:13:20.580",
"Id": "234883",
"ParentId": "234719",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "234883",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T04:43:47.987",
"Id": "234719",
"Score": "2",
"Tags": [
"python",
"file-system",
"macos"
],
"Title": "Moving files from a directory to multiple with names same as file"
}
|
234719
|
<p>I’ve just created Minesweeper game, which work perfectly fine (for me).
Any suggestions on how to improve this code would be greatly appreciate, in terms of:</p>
<ul>
<li>Object-oriented</li>
<li>Array</li>
<li>Error handling</li>
<li>Function</li>
<li>More efficient approach</li>
<li>Others: Style(PEP8), comments, clean code, recursion, etc</li>
</ul>
<p>Explanation of game:</p>
<ul>
<li>Minesweeper is an array(table) of hidden mines and non-mine cells.</li>
<li>You can reveal any cells, one by one. Once you found the mines, you lose.</li>
<li>If you can revealed all non-mine cells, you win.</li>
<li>Each non-mine cell show you number of neighbor cell that contain mines.</li>
<li>Read more <a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)" rel="nofollow noreferrer">Wikipedia</a>, or you can try it on your computer.</li>
</ul>
<p>My approach:</p>
<ul>
<li>First revealed cell can’t be a mine</li>
<li>Keyboard input only</li>
<li>Text-based game</li>
<li>Example: <a href="https://streamable.com/9pokq" rel="nofollow noreferrer">Running on Pythonista (iPad)</a></li>
</ul>
<p>Clean version</p>
<pre class="lang-py prettyprint-override"><code>
import random
class Minesweeper:
def __init__(self,width=9,height=10,mine_numbers=12):
self.width = width
self.height = height
self.mine_numbers = mine_numbers
self.table = [None]*self.width*self.height
self.user_cell = False
self.user_row = False
self.user_column = False
self.user_reveal = []
def game_create(self):
print(f'Default size is {self.width}*{self.height}, {self.mine_numbers} mines')
default_size = input('Play default size?(Y/N): ')
if default_size.lower() == 'n':
correct_input = False
while not correct_input:
try:
self.width = int(input('Enter width: '))
self.height = int(input('Enter height: '))
self.mine_numbers = int(input('Enter number of mines: '))
if self.mine_numbers >= self.width*self.height or self.mine_numbers == 0:
print('ERROR: Number of mines can not be 0 or equal/exceed table size')
elif self.width > 99 or self.height > 99:
print('ERROR: Maximum table size is 99*99')
else:
self.table = [None]*self.width*self.height
self.user_reveal = []
correct_input = True
return self.width,self.height,self.mine_numbers,self.table,self.user_reveal
except ValueError:
print('ERROR: Try again, number only')
else:
self.table = [None]*self.width*self.height
self.user_reveal = []
return self.width,self.height,self.mine_numbers,self.table,self.user_reveal
def user_input(self):
correct_input = False
while not correct_input:
try:
self.user_cell = input('Enter {[column][row]} in 4 digits eg. 0105: ')
int(self.user_cell)
if len(self.user_cell) != 4:
print('ERROR: Only 4 digits allowed')
elif int(self.user_cell[2:]) > self.height or self.user_cell[2:] == '00':
print('ERROR: Row out of range')
elif int(self.user_cell[:2]) > self.width or self.user_cell[:2] == '00':
print('ERROR: Column of range')
elif self.user_cell in self.user_reveal:
print('ERROR: Already revealed')
else:
correct_input = True
except ValueError:
print('ERROR: Try again, number only')
if self.user_cell:
self.user_row = int(self.user_cell[2:])
self.user_column = int(self.user_cell[:2])
self.user_reveal.append(self.user_cell)
return self.user_cell,self.user_row,self.user_column
def mines_generator(self):
user_location = ((self.user_row-1)*self.width)+self.user_column-1
possible_location = [i for i in range(self.width*self.height) if i != user_location]
mines_location = random.sample(possible_location,self.mine_numbers)
for i in mines_location:
self.table[i] = 9
return self.table
def two_dimension_array(self):
for i in range(self.height):
self.table[i] = self.table[0+(self.width*i):self.width+(self.width*i)]
del self.table[self.height:]
return self.table
def complete_table(self):
temporary_table = [[None for _ in range(self.width)] for _ in range(self.height)]
for i in range(self.height):
for j in range(self.width):
if self.table[i][j] == 9:
temporary_table[i][j] = 9
continue
else:
counter = 0
for k in range(i-1,i+2):
if 0 <= k <= self.height-1:
for l in range(j-1,j+2):
if 0 <= l <= self.width-1:
if self.table[k][l] == 9:
counter += 1
continue
temporary_table[i][j] = counter
self.table = temporary_table
return self.table
def adjacent_zero(self,zero_cell):
if self.table[int(zero_cell[2:])-1][int(zero_cell[:2])-1] == 0:
for i in range(int(zero_cell[2:])-1-1,int(zero_cell[2:])-1+2):
if 0 <= i < self.height:
for j in range(int(zero_cell[:2])-1-1,int(zero_cell[:2])-1+2):
if 0 <= j < self.width:
if str(j+1).zfill(2)+str(i+1).zfill(2) not in self.user_reveal:
self.user_reveal.append(str(j+1).zfill(2)+str(i+1).zfill(2))
if self.table[i][j] == 0:
self.adjacent_zero(str(j+1).zfill(2)+str(i+1).zfill(2))
return self.user_reveal
def first_turn(self):
self.user_input()
self.mines_generator()
self.two_dimension_array()
self.complete_table()
self.adjacent_zero(self.user_cell)
def print_table(self):
print('\n'*10)
for row in range(self.height+1):
cell = '|'
for column in range(self.width+1):
if row == 0:
cell += f'{column:2}|'
continue
elif column == 0:
cell += f'{row:2}|'
continue
elif str(column).zfill(2)+str(row).zfill(2) in self.user_reveal:
cell += f'{self.table[row-1][column-1]:2}|'
continue
else:
cell += '{:>3}'.format('|')
print(cell)
def end_game(self):
def reveal_mine():
for i,j in enumerate(self.table):
for k,l in enumerate(j):
if l == 9:
self.table[i][k] = ‘XX’
if str(k+1).zfill(2)+str(i+1).zfill(2) not in self.user_reveal:
self.table[i][k] = ‘**’
self.user_reveal.append(str(k+1).zfill(2)+str(i+1).zfill(2))
if self.user_cell:
if self.table[self.user_row-1][self.user_column-1] == 9:
end_game = True
reveal_mine()
self.print_table()
print('YOU LOSE!')
elif len(self.user_reveal) == (self.width*self.height)-self.mine_numbers:
end_game = True
reveal_mine()
self.print_table()
print('YOU WIN!')
else:
end_game = False
else:
end_game = False
return end_game
def restart_game(self):
restart = input('Restart?(Y/N): ')
if restart.lower() == 'y':
return True
else:
return False
def main():
minesweeper = Minesweeper()
while True:
minesweeper.game_create()
minesweeper.print_table()
minesweeper.first_turn()
while not minesweeper.end_game():
minesweeper.print_table()
minesweeper.user_input()
minesweeper.adjacent_zero(minesweeper.user_cell)
if not minesweeper.restart_game():
break
if __name__ == '__main__':
main()
</code></pre>
<p>Comment version</p>
<pre class="lang-py prettyprint-override"><code>
import random
class Minesweeper:
def __init__(self,width=9,height=10,mine_numbers=12):
# Table generate: change via tables_ize()
self.width = width
self.height = height
self.mine_numbers = mine_numbers
self.table = [None]*self.width*self.height
# User cell input
self.user_cell = False
self.user_row = False
self.user_column = False
self.user_reveal = []
'''
{user_reveal} is changed by
- {game_create()}: reset user_reveal
- {user_input()}: append input cell, cannot reveal all adjacent 0 here (first turn - table not yet generated)
- {adjacent_zero()}: reveal all adjacent 0
- {end_game()}: append all mines
'''
'''
{*_user_*},{user_cell} = {[column][row]}, index is 1 more than {*_cell_*} index
{*_cell_*} = {[row][column]}, index is 1 less than {*_user_*} index
'''
def game_create(self):
print(f'Default size is {self.width}*{self.height}, {self.mine_numbers} mines')
default_size = input('Play default size?(Y/N): ')
if default_size.lower() == 'n':
correct_input = False
while not correct_input:
try:
self.width = int(input('Enter width: '))
self.height = int(input('Enter height: '))
self.mine_numbers = int(input('Enter number of mines: '))
if self.mine_numbers >= self.width*self.height or self.mine_numbers == 0:
print('ERROR: Number of mines can not be 0 or equal/exceed table size')
elif self.width > 99 or self.height > 99:
print('ERROR: Maximum table size is 99*99')
else:
self.table = [None]*self.width*self.height
self.user_reveal = []
correct_input = True
return self.width,self.height,self.mine_numbers,self.table,self.user_reveal
except ValueError:
print('ERROR: Try again, number only')
else:
self.table = [None]*self.width*self.height
self.user_reveal = []
return self.width,self.height,self.mine_numbers,self.table,self.user_reveal
def user_input(self):
correct_input = False
while not correct_input:
try:
self.user_cell = input('Enter {[column][row]} in 4 digits eg. 0105: ')
int(self.user_cell)
if len(self.user_cell) != 4:
print('ERROR: Only 4 digits allowed')
elif int(self.user_cell[2:]) > self.height or self.user_cell[2:] == '00':
print('ERROR: Row out of range')
elif int(self.user_cell[:2]) > self.width or self.user_cell[:2] == '00':
print('ERROR: Column of range')
elif self.user_cell in self.user_reveal:
print('ERROR: Already revealed')
else:
correct_input = True
except ValueError:
print('ERROR: Try again, number only')
self.user_row = int(self.user_cell[2:])
self.user_column = int(self.user_cell[:2])
if self.user_cell:
self.user_reveal.append(self.user_cell)
return self.user_cell,self.user_row,self.user_column
def mines_generator(self):
# Exclude first cell from mines generator
user_location = ((self.user_row-1)*self.width)+self.user_column-1
possible_location = [i for i in range(self.width*self.height) if i != user_location]
mines_location = random.sample(possible_location,self.mine_numbers)
# Assign 'Location with mine' with 9
for i in mines_location:
self.table[i] = 9
return self.table
def two_dimension_array(self):
# Save table into 2D array
for i in range(self.height):
self.table[i] = self.table[0+(self.width*i):self.width+(self.width*i)]
# Remove unnessessary elements
del self.table[self.height:]
return self.table
def complete_table(self):
# Create temporary 2D array
temporary_table = [[None for _ in range(self.width)] for _ in range(self.height)]
# For every table[i][j]
for i in range(self.height):
for j in range(self.width):
# If table[i][j] is bomb, continue
if self.table[i][j] == 9:
temporary_table[i][j] = 9
continue
else:
counter = 0
# For every adjacent neighbor arrays
for k in range(i-1,i+2):
# Error handling: list index out of range
if 0 <= k <= self.height-1:
for l in range(j-1,j+2):
# Error handling: list index out of range
if 0 <= l <= self.width-1:
# Count every adjacent mines
if self.table[k][l] == 9:
counter += 1
continue
temporary_table[i][j] = counter
self.table = temporary_table
return self.table
def adjacent_zero(self,zero_cell):
# If value is 0
if self.table[int(zero_cell[2:])-1][int(zero_cell[:2])-1] == 0:
# For all neighbor elements
for i in range(int(zero_cell[2:])-1-1,int(zero_cell[2:])-1+2):
# Error handling: index out of range
if 0 <= i < self.height:
for j in range(int(zero_cell[:2])-1-1,int(zero_cell[:2])-1+2):
if 0 <= j < self.width:
# If neighbor element of 0 is not yet append, append all adjacent element
if str(j+1).zfill(2)+str(i+1).zfill(2) not in self.user_reveal:
self.user_reveal.append(str(j+1).zfill(2)+str(i+1).zfill(2))
# If neighbor is also 0, do a recursion
if self.table[i][j] == 0:
self.adjacent_zero(str(j+1).zfill(2)+str(i+1).zfill(2))
def first_turn(self):
self.user_input()
self.mines_generator()
self.two_dimension_array()
self.complete_table()
self.adjacent_zero()
def print_table(self):
# Clear UI
print('\n'*10)
for row in range(self.height+1):
cell = '|'
for column in range(self.width+1):
# Top-row label
if row == 0:
cell += f'{column:2}|' # (Note: try 02 instead of 2)
continue
# First column label
elif column == 0:
cell += f'{row:2}|'
continue
# Revealed cell
elif str(column).zfill(2)+str(row).zfill(2) in self.user_reveal:
cell += f'{self.table[row-1][column-1]:2}|'
continue
# Not yet revealed cell
else:
cell += '{:>3}'.format('|')
print(cell)
def end_game(self):
# If end: reveal all mines, nested function
def reveal_mine():
for i,j in enumerate(self.table):
for k,l in enumerate(j):
if l == 9:
self.table[i][k] = ‘XX’
if str(k+1).zfill(2)+str(i+1).zfill(2) not in self.user_reveal:
self.table[i][k] = ‘**’
self.user_reveal.append(str(k+1).zfill(2)+str(i+1).zfill(2))
# If user choose cell: check if end
if self.user_cell:
if self.table[self.user_row-1][self.user_column-1] == 9:
end_game = True
reveal_mine()
self.print_table()
print('YOU LOSE!')
elif len(self.user_reveal) == (self.width*self.height)-self.mine_numbers:
end_game = True
reveal_mine()
self.print_table()
print('YOU WIN!')
else:
end_game = False
# If no cell selected: end = False
else:
end_game = False
return end_game
def restart_game(self):
restart = input('Restart?(Y/N): ')
if restart.lower() == 'y':
return True
else:
return False
def main():
minesweeper = Minesweeper()
while True:
minesweeper.game_create()
minesweeper.print_table()
minesweeper.first_turn()
while not minesweeper.end_game():
minesweeper.print_table()
minesweeper.user_input()
minesweeper.adjacent_zero(minesweeper.user_cell)
if not minesweeper.restart_game():
break
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T10:03:30.507",
"Id": "459114",
"Score": "1",
"body": "I don't have time for a full review, but one thing I notice is that you're using strings as comments. If you have a comment (something to help explain why the code is what it is) use a `#` character to start it. The weird `\"\"\"` sections in Python are intended for docstrings, which should only exist once at the start of the function and tell the function what it is for and how to use it. They are not comments and importantly, *are not ignored by python*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T10:45:54.453",
"Id": "459210",
"Score": "0",
"body": "@Josiah Thank you. I will leave it like this to remind me. And since no one reply to my post, it would be great if you could give me a full review (whenever is ok) :)"
}
] |
[
{
"body": "<p>I think implementing a game is a good way to learn a new programming\nlanguage. If you are up for it, you could try coding a graphical\nversion of Minesweeper using a game library such as\n<a href=\"https://www.pygame.org/news\" rel=\"nofollow noreferrer\">Pygame</a> or\n<a href=\"http://arcade.academy/\" rel=\"nofollow noreferrer\">Arcade</a> to learn even more about the\nlanguage.</p>\n\n<p>Below are my suggestions for improvements, in no particular order:</p>\n\n<h3>Comments</h3>\n\n<p>When I review code, I read the code and the comments in tandem. The\ncomments should help me understand what the code does. But for this\ncode I don't think they do, because they are on a quite low\nlevel. Comments that tells me essentially the same thing as the code\nitself aren't very interesting. What the comments instead should\ncommunicate is the <em>intent</em> of the code. The <em>why</em> not the <em>how</em>.</p>\n\n<p>I suggest instead of putting comments on individual lines, delete them\nall and replace them with a big comment on top of the module where you\ndescribe the architecture of the <code>Minesweeper</code> class:</p>\n\n<pre><code>import random\n\n# Minesweeper\n# -----------\n# Minesweeper is a solitaire game in which the goal is to reveal all\n# mines on a board. The Minesweeper class implements the game. It has\n# the following attributes:\n#\n# * width: width of board\n# ...\n# * table: board representation\n#\n# This example shows how the class should be used:\n#\n# ms = Minesweeper()\n# while True:\n# ms.game_create()\n# ...\n</code></pre>\n\n<p>It gives the reader an overview of what the code is all about.</p>\n\n<h3>Yes/no prompts</h3>\n\n<p>A convention expressed in <a href=\"https://stackoverflow.com/a/3041990/189247\">this Stackoverflow\nanswer</a> is to let the\ndefault choice in a yes/no prompt be capitalized. So if the prompt is</p>\n\n<pre><code>Play default size? [Y/n]:\n</code></pre>\n\n<p>the user knows that by just pressing return, the default size is\nchoosen. Yes, I know it is a \"small detail\" but to make great software\nyou have to consider these little things.</p>\n\n<h3>Integer prompt function</h3>\n\n<p>If the user does not want to use the default size, he or she is\nprompted for the width, height and the number of mines. Consider\nmaking a function encapsulating the prompting code:</p>\n\n<pre><code>def prompt_int(name, lo, hi):\n while True:\n s = input(f'Enter {name} [{lo}..{hi}]: ')\n try:\n v = int(s)\n except ValueError:\n print('ERROR: Try again, number only')\n continue\n if not (lo <= v <= hi):\n print('ERROR: Allowed range %d..%d' % (lo, hi))\n continue\n return v\n</code></pre>\n\n<h3>Unused return values</h3>\n\n<p>The return value of the <code>game_create</code>, <code>user_input</code> and\n<code>mines_generator</code> methods are unused.</p>\n\n<h3>Only initialize attributes in one place</h3>\n\n<p>The attributes <code>table</code>, <code>width</code>, <code>height</code> and <code>mine_numbers</code> are\ninitialized both in the constructor and in the <code>game_create</code>\nmethod. Better to put the <code>game_create</code> code in the constructor so\nthat the initialization only happens once. After all, it is a\nconstructor so it makes sense that the game is created in it.</p>\n\n<h3>Avoid magic numbers</h3>\n\n<p>It looks like if a cell contains 9 it is a mine. It is better to avoid\nmagic numbers and to use constants instead. Declare</p>\n\n<pre><code>class Minesweeper:\n CLEAR = 0\n MINE = 9\n</code></pre>\n\n<p>and then to check if a cell contains a mine write</p>\n\n<pre><code>self.table[i][j] == Minesweeper.MINE\n</code></pre>\n\n<h3>Board representation</h3>\n\n<p>It is unclear to me why the board representation (<code>table</code>) is\ninitialized as a one-dimensional array and then changed to a\ntwo-dimensional one. Why not make it two-dimensional from the start?</p>\n\n<h3>Counting mines with <code>min</code> and <code>max</code></h3>\n\n<p>Use <code>min</code> and <code>max</code> to count mines in the following way:</p>\n\n<pre><code>def complete_table(self):\n width, height, table = self.width, self.height, self.table\n for i in range(height):\n for j in range(width):\n if table[i][j] == Minesweeper.MINE:\n continue\n table[i][j] = 0\n for i2 in range(max(0, i - 1), min(i + 2, height)):\n for j2 in range(max(0, j -1), min(j + 2, width)):\n if table[i2][j2] == Minesweeper.MINE:\n table[i][j] += 1\n</code></pre>\n\n<p>This usage of <code>min</code> and <code>max</code> for bounds-checking is a common\npattern. The first line is just to make the code shorter - so that\n<code>self</code> doesn't have to be repeated everywhere.</p>\n\n<h3>Perfer storing data in a machine friendly format</h3>\n\n<p>If some input has to be converted in some way to become usable by the\ncomputer, then it should be stored in the converted format. That way,\nthe conversion doesn't have to be repeated each time the data is used.</p>\n\n<p>For example, <code>user_column</code> and <code>user_row</code> are inputted using 1-based\nindexing. Which is fine because that makes sense for humans. But for\nPython, 0-based indexing is more convenient so the values should be\nconverted as soon as they are read from the user. The conversion\nsimply means subtracting 1 from them.</p>\n\n<p>The same goes for the <code>user_reveal</code> attribute. It stores a sequence\nlike this:</p>\n\n<pre><code>['0101', '0201', '0404']\n</code></pre>\n\n<p>but it should be stored in a Python-friendly format, like this:</p>\n\n<pre><code>[(0, 0), (1, 0), (3, 3)]\n</code></pre>\n\n<h3>Don't store data twice</h3>\n\n<p><code>user_row</code> and <code>user_column</code> are after the first turn the same as the\nlast element of the <code>user_reveal</code> list. This allows us to remove the\n<code>user_row</code> and <code>user_column</code> attributes and instead get the same data\nby referring to <code>user_reveal[-1]</code>.</p>\n\n<h3>Don't delay returns</h3>\n\n<p>In <code>end_game</code> there is the following:</p>\n\n<pre><code>if ...:\n end_game = True\n ...\nelif ...:\n end_game = True\n ...\nelse:\n end_game = False\n</code></pre>\n\n<p>It is better to express it as follows</p>\n\n<pre><code>if ...:\n ...\n return True\nif ...:\n ...\n return True\nreturn False\n</code></pre>\n\n<p>because it makes the code flow \"straighter.\"</p>\n\n<h3>Avoid nested functions</h3>\n\n<p>Nested functions have their uses, but they also makes the code harder\nto follow. IMO, they should be avoided.</p>\n\n<h3>Names</h3>\n\n<p>Last but not least, the names of many objects can be improved. For\nmethods and functions, it is preferable to include a verb to make the\nname \"active.\" Here are the renames I suggest:</p>\n\n<ul>\n<li><code>first_turn => run_first_turn</code></li>\n<li><code>print_table => print_minefield</code></li>\n<li><code>mines_generator => place_mines</code></li>\n<li><code>mine_numbers => mine_count</code></li>\n<li><code>user_input => read_location</code></li>\n<li><code>end_game => is_game_over</code></li>\n<li><code>user_reveal => revealed_locations</code> (for collection types, you want\nthe name to end with an S)</li>\n<li><code>adjacent_zero => reveal_safe_locations</code></li>\n<li><code>reveal_mine => reveal_all_mines</code></li>\n<li><code>complete_table => place_mine_counts</code></li>\n<li><code>table => minefield</code></li>\n</ul>\n\n<h3>Final code</h3>\n\n<pre><code>import itertools\nimport random\n\n# Minesweeper\n# -----------\n# Minesweeper is a solitaire game in which the goal is to reveal all\n# mines on a board. The Minesweeper class implements the game. It has\n# the following attributes:\n#\n# * width: width of board\n# ...\n# * minefield: board representation\n#\n# This example shows how the class should be used:\n#\n# ms = Minesweeper()\n# while True:\n# ms.game_create()\n# ...\n\ndef prompt_int(name, lo, hi):\n while True:\n s = input(f'Enter {name} [{lo}..{hi}]: ')\n try:\n v = int(s)\n except ValueError:\n print('ERROR: Try again, number only')\n continue\n if not (lo <= v <= hi):\n print('ERROR: Allowed range %d..%d' % (lo, hi))\n continue\n return v\n\nclass Minesweeper:\n CLEAR = 0\n MINE = 9\n def __init__(self, width = 9, height = 10, mine_count = 12):\n self.revealed_locations = []\n print(f'Default size is {width}*{height}, {mine_count} mines')\n default_size = input('Play default size? [Y/n]: ')\n if default_size.lower() == 'n':\n self.width = prompt_int('width', 0, 99)\n self.height = prompt_int('height', 0, 99)\n self.mine_count = prompt_int('number of mines',\n 0, self.width * self.height - 1)\n else:\n self.width = width\n self.height = height\n self.mine_count = mine_count\n self.minefield = [[Minesweeper.CLEAR] * self.width\n for _ in range(self.height)]\n\n def read_location(self):\n while True:\n s = input('Enter {[column][row]} in 4 digits eg. 0105: ')\n if len(s) != 4:\n print('ERROR: Only 4 digits allowed')\n continue\n try:\n row = int(s[2:]) - 1\n column = int(s[:2]) - 1\n except ValueError:\n print('ERROR: Try again, number only')\n continue\n if not (0 <= row < self.height):\n print('ERROR: Row out of range')\n elif not (0 <= column < self.width):\n print('ERROR: Column of range')\n elif (row, column) in self.revealed_locations:\n print('ERROR: Already revealed')\n else:\n break\n self.revealed_locations.append((row, column))\n\n def place_mines(self):\n locs = set(itertools.product(range(self.height), range(self.width)))\n locs -= {self.revealed_locations[-1]}\n locs = random.sample(locs, self.mine_count)\n for row, column in locs:\n self.minefield[row][column] = Minesweeper.MINE\n\n def place_mine_counts(self):\n width, height, minefield = self.width, self.height, self.minefield\n for i in range(height):\n for j in range(width):\n if minefield[i][j] == Minesweeper.MINE:\n continue\n minefield[i][j] = Minesweeper.CLEAR\n for i2 in range(max(0, i - 1), min(i + 2, height)):\n for j2 in range(max(0, j -1), min(j + 2, width)):\n if minefield[i2][j2] == Minesweeper.MINE:\n minefield[i][j] += 1\n\n def reveal_safe_locations(self, row, column):\n width, height, minefield = self.width, self.height, self.minefield\n if minefield[row][column] == Minesweeper.CLEAR:\n for i in range(max(0, row - 1), min(row + 2, height)):\n for j in range(max(0, column - 1), min(column + 2, width)):\n if (i, j) not in self.revealed_locations:\n self.revealed_locations.append((i, j))\n if minefield[i][j] == Minesweeper.CLEAR:\n self.reveal_safe_locations(i, j)\n\n def run_first_turn(self):\n self.read_location()\n self.place_mines()\n self.place_mine_counts()\n row, column = self.revealed_locations[-1]\n self.reveal_safe_locations(row, column)\n\n def print_minefield(self):\n print('\\n'*10)\n for row in range(self.height + 1):\n cell = '|'\n for column in range(self.width + 1):\n if row == 0 and column == 0:\n cell += ' .|'\n elif row == 0:\n cell += f'{column:2}|'\n elif column == 0:\n cell += f'{row:2}|'\n elif (row - 1, column - 1) in self.revealed_locations:\n cell += f'{self.minefield[row-1][column-1]:2}|'\n else:\n cell += '{:>3}'.format('|')\n print(cell)\n\n def reveal_all_mine(self):\n for i in range(self.height):\n for j in range(self.width):\n if self.minefield[i][j] == Minesweeper.MINE:\n self.minefield[i][j] = 'XX'\n if (i, j) not in self.revealed_locations:\n self.minefield[i][j] = '**'\n self.revealed_locations.append((i, j))\n\n def is_game_over(self):\n row, column = self.revealed_locations[-1]\n if self.minefield[row][column] == Minesweeper.MINE:\n self.reveal_all_mines()\n self.print_minefield()\n print('YOU LOSE!')\n return True\n unmined_locations_count = self.width * self.height - self.mine_count\n if len(self.revealed_locations) == unmined_locations_count:\n self.reveal_all_mines()\n self.print_minefield()\n print('YOU WIN!')\n return True\n return False\n\n def restart_game(self):\n restart = input('Restart? [y/N]: ')\n return restart.lower() == 'y'\n\ndef main():\n while True:\n ms = Minesweeper()\n ms.print_minefield()\n ms.run_first_turn()\n while not ms.is_game_over():\n ms.print_minefield()\n ms.read_location()\n row, column = ms.revealed_locations[-1]\n ms.reveal_safe_locations(row, column)\n if not ms.restart_game():\n break\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-02T16:21:33.627",
"Id": "459646",
"Score": "0",
"body": "IMO, the module docstring should be above the imports and I'd also use ```\"\"\" Module docstring here. \"\"\"``` instead of multiple `#`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-03T08:36:07.037",
"Id": "459722",
"Score": "0",
"body": "First of all, thank you. But when the user restart, I want user_input() become default_size so that they don’t have to configure the setting every time. But in your suggestion, we have only init(), and in main(): Minesweeper is also in a while loop. How should I solve this problem? (That’s why I have game_create() separated from init(), and in main(): Minesweeper is placed outside the while loop. But I feel that my solution is not the right one.) // I’ve read your comment 2-3 times, but I need some more times to really understand them all :))"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-02T15:14:34.950",
"Id": "234953",
"ParentId": "234725",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "234953",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T08:18:22.180",
"Id": "234725",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"recursion",
"error-handling",
"minesweeper"
],
"Title": "Minesweeper - Python 3 (beginner)"
}
|
234725
|
<p>I wrote a utility class that has simple methods for:</p>
<ul>
<li>En/decrypting data with 256-bit AES-GCM using a password</li>
<li>Generating RSA keypair</li>
<li>Saving RSA keypair and storing private key encrypted</li>
<li><p>En/decrypting data with RSA (data with AES-GCM & random key, key with RSA)</p>
<pre><code>import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
public class GCM {
private final int SALT_LENGTH = 256/8;
private final int IV_LENGTH = 12;
private final int KEY_LENGTH = 256;
private final int GCM_TAG_LENGTH = 16;
private KeyPair keyPair;
public GCM() { }
private SecretKeySpec generateKey(char[] password, byte[] salt)
throws InvalidKeySpecException, NoSuchAlgorithmException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(/*"PBKDF2WithHmacSHA3-512"*/"PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password, salt, 65536, KEY_LENGTH);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKeySpec = new SecretKeySpec(tmp.getEncoded(), "AES");
return secretKeySpec;
}
public void generateKeyPair() //generate 4096-bit RSA keypair
throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(4096, new SecureRandom());
keyPair = kpg.genKeyPair();
}
public void loadKeyPair(char[] password) { //loads RSA keypair from file
try {
byte[] publicKeyBytes = Files.readAllBytes(Paths.get("public.key"));
byte[] privateKeyBytes = decrypt(Files.readAllBytes(Paths.get("private.key")), password);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
this.keyPair = new KeyPair(publicKey, privateKey);
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveKeyPair(char[] password) { //saves currently used keypair to file
try {
FileOutputStream fos = new FileOutputStream("private.key");
fos.write(encrypt(keyPair.getPrivate().getEncoded(), password));
fos.close();
fos = new FileOutputStream("public.key");
fos.write(keyPair.getPublic().getEncoded());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] getPublicKey() { //returns currently used public key
return keyPair.getPublic().getEncoded();
}
public byte[] encrypt(byte[] data, char[] password) { //encrypts data with password-generated key
byte[] salt = new byte[SALT_LENGTH];
byte[] iv = new byte[IV_LENGTH];
byte[] result = null;
new SecureRandom().nextBytes(salt);
new SecureRandom().nextBytes(iv);
try {
SecretKeySpec secretKeySpec = generateKey(password, salt);
byte[] encrypted = encrypt(data, secretKeySpec, iv);
result = new byte[encrypted.length + salt.length + iv.length];
System.arraycopy(salt, 0, result, 0, salt.length);
System.arraycopy(iv, 0, result, salt.length, iv.length);
System.arraycopy(encrypted,0, result, salt.length + iv.length, encrypted.length);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public byte[] encrypt(byte[] data, byte[] publicKey) { //encrypts data with recipient public key
byte[] iv = new byte[IV_LENGTH];
byte[] result = null;
new SecureRandom().nextBytes(iv);
try {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256, new SecureRandom());
SecretKey secretKey = keyGen.generateKey();
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
byte[] encrypted = encrypt(data, secretKeySpec, iv);
Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA3-512AndMGF1Padding");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePublic(keySpec));
byte[] symmetricKey = cipher.doFinal(secretKeySpec.getEncoded());
result = new byte[encrypted.length + iv.length + symmetricKey.length];
System.arraycopy(symmetricKey, 0, result, 0, symmetricKey.length);
System.arraycopy(iv, 0, result, symmetricKey.length, iv.length);
System.arraycopy(encrypted,0, result, iv.length + symmetricKey.length, encrypted.length);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private byte[] encrypt(byte[] data, SecretKeySpec secretKeySpec, byte[] iv) //encryption utility method
throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException,
NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmParameterSpec);
return cipher.doFinal(data);
}
public byte[] decrypt(byte[] data, char[] password) { //decrypts data with password-generated key
byte[] salt = Arrays.copyOfRange(data, 0, SALT_LENGTH);
byte[] iv = Arrays.copyOfRange(data, SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
byte[] encryptedData = Arrays.copyOfRange(data, SALT_LENGTH + IV_LENGTH, data.length);
byte[] result = null;
try {
SecretKeySpec secretKeySpec = generateKey(password, salt);
result = decrypt(encryptedData, secretKeySpec, iv);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public byte[] decrypt(byte[] data) { //decrypts data with currently loaded private key
byte[] symmetricKey = Arrays.copyOfRange(data, 0, 4096/8);
byte[] iv = Arrays.copyOfRange(data, 4096/8, 4096/8 + IV_LENGTH);
byte[] encryptedData = Arrays.copyOfRange(data, 4096/8 + IV_LENGTH, data.length);
byte[] decrypted = null;
try {
Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA3-512AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
byte[] decryptedSymmetricKey = cipher.doFinal(symmetricKey);
SecretKeySpec secretKeySpec = new SecretKeySpec(decryptedSymmetricKey, "AES");
decrypted = decrypt(encryptedData, secretKeySpec, iv);
} catch (Exception e) {
e.printStackTrace();
}
return decrypted;
}
private byte[] decrypt(byte[] data, SecretKeySpec secretKeySpec, byte[] iv)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
InvalidKeyException, BadPaddingException, IllegalBlockSizeException { //decryption utility method
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);
return cipher.doFinal(data);
}
}
</code></pre></li>
</ul>
<p>The IV, and either RSA-encrypted symmetric key or salt used for key derivation are prepended to the output byte[].</p>
<p>It is used as follows:</p>
<pre><code>GCM gcm = new GCM();
//symmetric encryption
byte[] encrypted = gcm.encrypt(byte[] data, char[] password);
byte[] decrypted = gcm.decrypt(byte[] encrypted, char[] password);
//asymmetric encryption
gcm.generateKeyPair();
gcm.saveKeyPair(char[] password);
gcm.loadKeyPair(char[] password);
byte[] encrypted = gcm.encrypt(byte[] data, byte[] publicKey);
byte[] decrypted = gcm.decrypt(byte[] data);
</code></pre>
<p>Since it is to be used in a closed system, compatibility isn't all that important (for example with key storage), but feel free to suggest alternatives.</p>
<p>Now I have the following questions about my code:</p>
<ul>
<li>Does it have any security flaws?</li>
<li>Are AES-GCM's features used properly (eg. Authenticated Encryption)?</li>
<li>Is the IV generation random enough to use with AES-GCM?</li>
<li>Does it follow best practices?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:58:02.920",
"Id": "461337",
"Score": "0",
"body": "I'll try and comment on the security parts tomorrow, I'm just too tired now, end of day is near."
}
] |
[
{
"body": "<h2>Pokémon error handling \"Catch them all\"</h2>\n\n<p>Never (ever!) write code like this:</p>\n\n<pre><code>try {\n ...\n} catch (Exception e) {\n ...\n}\n</code></pre>\n\n<p>It allows the program to continue executing even if fatal errors are\nencountered which is very bad. Only catch errors that you can\nhandle. In practice, that means that you almost never catch anything.</p>\n\n<h2>File handling</h2>\n\n<p>Saving and loading the key to the process' current working directory\nis not nice. Better to let the user pass a <code>Path</code> specifying the\ndirectory to use in the <code>GCM</code> constructor:</p>\n\n<pre><code>public GCM(Path path) {\n this.path = path;\n}\n</code></pre>\n\n<p>It is also a good idea to store the filenames in constants because it\nguards against spelling errors:</p>\n\n<pre><code>private final String PUBLIC_KEY = \"public.key\";\nprivate final String PRIVATE_KEY = \"private.key\";\n</code></pre>\n\n<p>So to get the path to \"public.key\", you write <code>path.resolve(PUBLIC_KEY)</code>.</p>\n\n<p>Mixing Java NIO with old style IO is not nice. Your code for writing\nthe keypair to file can be replaced with Java NIO calls:</p>\n\n<pre><code>byte[] encodedPrivateKey = keyPair.getPrivate().getEncoded();\nbyte[] privateKeyBytes = encrypt(encodedPrivateKey, password);\nFiles.write(path.resolve(PRIVATE_KEY), privateKeyBytes);\nbyte[] publicKeyBytes = keyPair.getPublic().getEncoded();\nFiles.write(path.resolve(PUBLIC_KEY), publicKeyBytes);\n</code></pre>\n\n<h2>Code organization</h2>\n\n<p>While reviewing your class I realized that it does two things; it\nhandles key pairs and it encrypts/decrypts data. Ideally, each class\nshould only do one job. Therefore I think a better way to organize the\ncode is to have one class for the key pair handling and one for\nencryption/decryption.</p>\n\n<p>Furthermore, the only state in your class is the <code>keyPair</code> variable\nwhich is not referenced in many of the methods. As a rule of thumb, if\na method doesn't access any state then it should be made into a static\nmethod (a function). While refactoring that, I realized that your\nwhole API can be better expressed as two static classes without any\nstate.</p>\n\n<h2>Comments</h2>\n\n<p>If I were reviewing your code for a real project, I'd definitely\ncomplain about the lack of comments. There's a lot of things in there\nthat is not obvious when reading the code. For example, what is an IV?\nWhere does the number 4096 come from? What is <code>GCM_TAG_LENGTH</code>? And so\non.</p>\n\n<h2>Result</h2>\n\n<p>With comments removed:</p>\n\n<pre><code>import javax.crypto.*;\nimport javax.crypto.spec.GCMParameterSpec;\nimport javax.crypto.spec.PBEKeySpec;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.io.IOException;\nimport java.nio.file.*;\nimport java.security.*;\nimport java.security.spec.*;\nimport java.util.Arrays;\n\nclass GCM {\n private final static int SALT_LENGTH = 256/8;\n private final static int IV_LENGTH = 12;\n private final static int KEY_LENGTH = 256;\n private final static int GCM_TAG_LENGTH = 16;\n\n private static SecretKeySpec generateKey(char[] password, byte[] salt)\n throws InvalidKeySpecException, NoSuchAlgorithmException {\n SecretKeyFactory factory = SecretKeyFactory.getInstance(\"PBKDF2WithHmacSHA256\");\n KeySpec spec = new PBEKeySpec(password, salt, 65536, KEY_LENGTH);\n SecretKey tmp = factory.generateSecret(spec);\n SecretKeySpec secretKeySpec =\n new SecretKeySpec(tmp.getEncoded(), \"AES\");\n return secretKeySpec;\n }\n public static byte[] decrypt(byte[] data, KeyPair keyPair)\n throws GeneralSecurityException {\n byte[] symmetricKey = Arrays.copyOfRange(data, 0, 4096/8);\n byte[] iv = Arrays.copyOfRange(data, 4096/8, 4096/8 + IV_LENGTH);\n byte[] encryptedData = Arrays.copyOfRange(data, 4096/8 + IV_LENGTH,\n data.length);\n Cipher cipher = Cipher.getInstance(\n \"RSA/NONE/OAEPWithSHA3-512AndMGF1Padding\");\n cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());\n byte[] decryptedSymmetricKey = cipher.doFinal(symmetricKey);\n\n SecretKeySpec secretKeySpec =\n new SecretKeySpec(decryptedSymmetricKey, \"AES\");\n return decrypt(encryptedData, secretKeySpec, iv);\n }\n private static byte[] decrypt(byte[] data,\n SecretKeySpec secretKeySpec,\n byte[] iv)\n throws GeneralSecurityException {\n Cipher cipher = Cipher.getInstance(\"AES/GCM/NoPadding\");\n GCMParameterSpec gcmParameterSpec =\n new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);\n cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);\n\n return cipher.doFinal(data);\n }\n public static byte[] decrypt(byte[] data, char[] password)\n throws GeneralSecurityException {\n byte[] salt = Arrays.copyOfRange(data, 0, SALT_LENGTH);\n byte[] iv =\n Arrays.copyOfRange(data, SALT_LENGTH, SALT_LENGTH + IV_LENGTH);\n byte[] encryptedData =\n Arrays.copyOfRange(data, SALT_LENGTH + IV_LENGTH, data.length);\n\n SecretKeySpec secretKeySpec = generateKey(password, salt);\n return decrypt(encryptedData, secretKeySpec, iv);\n }\n public static byte[] encrypt(byte[] data, byte[] publicKey)\n throws GeneralSecurityException {\n byte[] iv = new byte[IV_LENGTH];\n new SecureRandom().nextBytes(iv);\n\n KeyGenerator keyGen = KeyGenerator.getInstance(\"AES\");\n keyGen.init(256, new SecureRandom());\n SecretKey secretKey = keyGen.generateKey();\n SecretKeySpec secretKeySpec =\n new SecretKeySpec(secretKey.getEncoded(), \"AES\");\n byte[] encrypted = encrypt(data, secretKeySpec, iv);\n\n Cipher cipher =\n Cipher.getInstance(\"RSA/NONE/OAEPWithSHA3-512AndMGF1Padding\");\n X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePublic(keySpec));\n byte[] symmetricKey = cipher.doFinal(secretKeySpec.getEncoded());\n\n byte[] result = new byte[encrypted.length + iv.length\n + symmetricKey.length];\n System.arraycopy(symmetricKey, 0, result, 0, symmetricKey.length);\n System.arraycopy(iv, 0, result, symmetricKey.length, iv.length);\n System.arraycopy(encrypted,0, result, iv.length + symmetricKey.length, encrypted.length);\n return result;\n }\n public static byte[] encrypt(byte[] data, char[] password)\n throws GeneralSecurityException {\n byte[] salt = new byte[SALT_LENGTH];\n byte[] iv = new byte[IV_LENGTH];\n new SecureRandom().nextBytes(salt);\n new SecureRandom().nextBytes(iv);\n\n SecretKeySpec secretKeySpec = generateKey(password, salt);\n byte[] encrypted = encrypt(data, secretKeySpec, iv);\n byte[] result = new byte[encrypted.length + salt.length + iv.length];\n System.arraycopy(salt, 0, result, 0, salt.length);\n System.arraycopy(iv, 0, result, salt.length, iv.length);\n System.arraycopy(encrypted, 0, result, salt.length + iv.length, encrypted.length);\n return result;\n }\n private static byte[] encrypt(byte[] data,\n SecretKeySpec secretKeySpec,\n byte[] iv)\n throws GeneralSecurityException {\n Cipher cipher = Cipher.getInstance(\"AES/GCM/NoPadding\");\n GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);\n cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmParameterSpec);\n return cipher.doFinal(data);\n }\n}\nclass KeyPairs {\n private final static String PUBLIC_KEY = \"public.key\";\n private final static String PRIVATE_KEY = \"private.key\";\n\n public static KeyPair generate() throws NoSuchAlgorithmException {\n KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"RSA\");\n kpg.initialize(4096, new SecureRandom());\n return kpg.genKeyPair();\n }\n public static KeyPair load(Path path, char[] password)\n throws IOException, GeneralSecurityException {\n Path publicKeyPath = path.resolve(PUBLIC_KEY);\n byte[] publicKeyBytes = Files.readAllBytes(publicKeyPath);\n Path privateKeyPath = path.resolve(PRIVATE_KEY);\n byte[] privateKeyBytes = GCM.decrypt(\n Files.readAllBytes(privateKeyPath),\n password);\n X509EncodedKeySpec x509EncodedKeySpec =\n new X509EncodedKeySpec(publicKeyBytes);\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);\n PKCS8EncodedKeySpec pkcs8EncodedKeySpec =\n new PKCS8EncodedKeySpec(privateKeyBytes);\n PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);\n return new KeyPair(publicKey, privateKey);\n }\n public static void save(Path path, KeyPair keyPair, char[] password)\n throws IOException, GeneralSecurityException {\n byte[] encodedPrivateKey = keyPair.getPrivate().getEncoded();\n byte[] privateKeyBytes = GCM.encrypt(encodedPrivateKey, password);\n Files.write(path.resolve(PRIVATE_KEY), privateKeyBytes);\n byte[] publicKeyBytes = keyPair.getPublic().getEncoded();\n Files.write(path.resolve(PUBLIC_KEY), publicKeyBytes);\n }\n}\n</code></pre>\n\n<p>I think your usage of the Java Crypto API is correct, but I'm no\nexpert.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T10:29:37.520",
"Id": "459209",
"Score": "0",
"body": "Thank you for your answer. The code is indeed not for a real project. I'll wait with accepting your answer for now, in case there will be another answer, especially one concering the crypto API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:57:36.963",
"Id": "461336",
"Score": "0",
"body": "WRT to exception handling, you may want to take at my post [here](https://stackoverflow.com/a/15712409/589259)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T23:40:43.063",
"Id": "234767",
"ParentId": "234727",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234767",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T10:11:59.253",
"Id": "234727",
"Score": "2",
"Tags": [
"java",
"security",
"cryptography",
"aes"
],
"Title": "Java RSA / AES-GCM encryption utility"
}
|
234727
|
<p>Could you review my usart driver wrapper please?</p>
<p>It contains the C language Xilinx usart driver, but I write C++ programs and need to C++ usart driver. How it was designed correctly and what I have to chage or add in the one on your view? </p>
<p>I will be thankful for your the strictest appraisal.</p>
<p>Thank you.</p>
<pre><code>//**********************************************************************
// name: usart.hpp
//
// test: non.
//
// description: a usart driver wrapper.
//
// author: Artyom Shimko
//
// contact: soikadigital@gmail.com
//
// created: 28.12.19
//
// release: 28.12.19
//
// changes: non.
//
#ifndef USART_HPP
#define USART_HPP
#include "platform.h" // Platform depending settings.
#include "xuartps_hw.h" // The Xilinx header file for XUartPs device.
namespace UsartSapce {
enum usartNumber { usart0 = XPAR_PS7_UART_0_BASEADDR,
usart1 = XPAR_PS7_UART_1_BASEADDR};
}
template <typename T>
class Usart : public Platform {
private:
u32 usartNumber;
public:
Usart(u32 usartNumber); // The set usart number method.
status transmit(T *pData, u32 dataValue);
status receive (T *pData, u32 dataValue);
void reset(void);
};
//**********************************************************************
// The class constructor definition, it sets the usart number.
//**********************************************************************
// id: A required usart number.
//
template <typename T>
Usart<T>::Usart (u32 usartNumber ) {
this->usartNumber = usartNumber;
}
//**********************************************************************
// The usart reset method.
//**********************************************************************
// parameters: non.
//
// return: non.
//
template <typename T>
void Usart<T>::reset(void) {
XUartPs_ResetHw(usartNumber);
}
//**********************************************************************
// The data transmit usart method.
//**********************************************************************
// pData: The pointer to transmited data.
//
// dataValue: Value of transmited data.
//
// return: ok aka 0 or error aka -1. The error occurs then pData
// is equal to nullptr or/and dataValue is equal to null.
//
template <typename T>
status Usart<T>::transmit(T *pData, u32 dataValue) {
u8 *pByteData = nullptr;
if(parameterCheck_(pData,dataValue) != StatusSpace::ok) {
return StatusSpace::error;
}
pByteData = reinterpret_cast<u8*>(pData);
for(u32 byteCounter = 0; byteCounter < dataValue; ++byteCounter) {
XUartPs_SendByte(usartNumber, *(pByteData + byteCounter));
}
return StatusSpace::ok;
}
//**********************************************************************
// The data receive usart method.
//**********************************************************************
// pData: The pointer to an array for received data.
//
// dataValue: Value of received data.
//
// return: ok aka 0 or error aka -1. The error occurs then pData
// is equal to nullptr or/and dataValue is equal to null.
//
template <typename T>
status Usart<T>::receive(T *pData, u32 dataValue) {
u8 *pByteData = nullptr;
if(parameterCheck_(pData,dataValue) != StatusSpace::ok) {
return StatusSpace::error;
}
pByteData = reinterpret_cast<u8*>(pData);
for(u32 byteCounter = 0; byteCounter < dataValue; ++byteCounter) {
*(pByteData + byteCounter) = XUartPs_RecvByte(usartNumber);
}
return StatusSpace::ok;
}
#endif
</code></pre>
|
[] |
[
{
"body": "<h1>Consider using <code>enum class</code></h1>\n\n<p>Instead of having a regular <code>enum</code> inside its own <code>namespace</code>, use an <code>enum class</code>:</p>\n\n<pre><code>enum class UsartSpace: u32 {\n usart0 = XPAR_PS7_UART_0_BASEADDR,\n usart1 = XPAR_PS7_UART_1_BASEADDR,\n};\n</code></pre>\n\n<p>Then, to ensure someone cannot instantiate a <code>Usart</code> with the wrong base address, make the constructor take this <code>enum</code> as a parameter:</p>\n\n<pre><code>template <typename T>\nUsart<T>::Usart(UsartSpace usartSpace): usartNumber(static_cast<u32>(usartSpace)) {\n}\n</code></pre>\n\n<p>Also, \"Space\" is a bit of a generic word that doesn't say much, but you can't call the enum <code>Usart</code> since you already have <code>class Usart</code>. Consider moving the enum to inside <code>class Usart</code>, and since it refers to a port, just call it <code>Port</code>. And perhaps keep the distinction between port number and address clear:</p>\n\n<pre><code>template <typename T>\nclass Usart: public Platform {\nprivate:\n u32 baseAddress;\n static const u32 addresses[] = {\n XPAR_PS7_UART_0_BASEADDR,\n XPAR_PS7_UART_1_BASEADDR,\n };\n\npublic:\n enum class Port {\n usart0,\n usart1,\n };\n\n Usart(Port port);\n ...\n};\n\n...\n\ntemplate <typename T>\nUsart<T>::Usart(Port port):\n baseAddress(addresses[static_cast<size_t>(port)])\n{\n}\n</code></pre>\n\n<p>In code that uses this class, you would then write:</p>\n\n<pre><code>Usart<sometype> usart(Usart::Port::usart0);\n</code></pre>\n\n<h1>Use better names</h1>\n\n<p>What you call a <code>usartNumber</code> looks like an base address to me, so call it <code>baseAddress</code> instead. In any case, don't repeat the name of the class in the member variable names.</p>\n\n<p>Also, <code>dataValue</code> is not the value of some piece of data, it's the size of the data you want to read or write. So call it <code>size</code>, and if possible use <code>size_t</code> as its type:</p>\n\n<pre><code>status transmit(T *pData, size_t size);\nstatus receive (T *pData, size_t size);\n</code></pre>\n\n<h1>Is it <code>status</code> or <code>StatusSpace</code>?</h1>\n\n<p>I feel this is another case of an <code>enum</code> in its own <code>namespace</code> being used as a way to declare constants of another type. I would instead define:</p>\n\n<pre><code>enum class Status {\n ok,\n error,\n ...\n};\n</code></pre>\n\n<h1>Use array notation where appropriate</h1>\n\n<p>Instead of writing <code>*(pByteData + byteCounter)</code>, just write the more ideomatic <code>pByteData[byteCounter]</code>.</p>\n\n<h1>Use <code>const</code> where appropriate</h1>\n\n<p>You wouldn't expect the function <code>transmit()</code> to modify the data that you want to send. So make this explicit:</p>\n\n<pre><code>template <typename T>\nclass Usart: public Platform {\n ...\n status transmit(const T *pdata, size_t size);\n ...\n}\n</code></pre>\n\n<h1>Consider templating <code>transmit()</code> and <code>receive()</code> instead of the whole <code>class</code></h1>\n\n<p>The only things that depend on the template parameter <code>T</code> are the <code>transmit()</code> and <code>receive()</code> functions. By making the <code>class</code> templated, you basically lock the type of data you can send and receive when you instantiate the class. Consider instead templating just those two functions, so you can send and receive different data types on the same UART without having to reinstantiate the class:</p>\n\n<pre><code>class Usart: public Platform {\n ...\n template <typename T>\n status transmit(const T *pData, size_t size);\n\n template <typename T>\n status receive(T *pData, size_t size);\n ...\n};\n</code></pre>\n\n<h1>Use Doxygen to document your code</h1>\n\n<p>You are documenting your code, which is good practice, but consider doing it in <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">Doxygen</a>'s format, so you can have Doxygen create cross-referenced documentation in HTML, PDF and other forms. Doxygen can also check that you documented all the functions and all the parameters to the functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T16:33:46.807",
"Id": "235079",
"ParentId": "234728",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T10:51:49.117",
"Id": "234728",
"Score": "2",
"Tags": [
"c++",
"template",
"wrapper",
"device-driver"
],
"Title": "usart driver wrapper"
}
|
234728
|
<p>I have tried going back to C++ after long time of mainly doing C#. I realize that the code is far from perfect, however I would really appreciate if someone could point of what exactly is wrong and how to fix it, so I can learn how things should be done. (just for code design, not asking to fix any logic errors)</p>
<p>What it does, is generating a Mesh from noise data (minecraft like game terrain) and creating chunks on runtime through threading. It has basic lightning and texture arrays implemented.</p>
<p>Files that were not written by me and shouldn't be reviewed:</p>
<ul>
<li><p>anything that starts with imgui</p></li>
<li><p>glsl.h/cpp</p></li>
</ul>
<p>I will be very thankful on your opinions how to fix this codes design.</p>
<p><a href="https://github.com/AleCie/NGine" rel="noreferrer">https://github.com/AleCie/NGine</a></p>
<p>Now, I don't know if it is allowed to ask for a review of code on github, but I hope this won't be an issue, since it is asking me to input at least three lines of code here, I will post Chunk.h file to give you some idea what you will be dealing with.</p>
<p>Edit: Including code for review over here as suggested with posting guidelines:</p>
<p>Chunk.h</p>
<pre><code>#pragma once
#include <memory>
#include <glm/glm.hpp>
#include "Shader.h"
#include "Texture.h"
#include "Mesh.h"
#include <thread>
#include <future>
class Camera;
class Chunk
{
public:
Chunk();
~Chunk();
void Create(glm::vec3 position, std::shared_ptr<Shader> shader);
void Update(Camera* cam, float dt);
void Render(Camera *cam);
//void RebuildMesh();
glm::vec3 GetPosition();
glm::mat4 GetWorldMatrix();
static const int ChunkSize = 16;
float NoiseTreshold = 0.0f;
float NoiseScale = 1.0f;
static int GlobalChunkVertexCount;
bool ShouldBeDeleted = false;
int Data[ChunkSize][ChunkSize][ChunkSize];
std::weak_ptr<Chunk> TopChunk;
std::weak_ptr<Chunk> BottomChunk;
std::weak_ptr<Chunk> LeftChunk;
std::weak_ptr<Chunk> RightChunk;
std::weak_ptr<Chunk> FrontChunk;
std::weak_ptr<Chunk> BackChunk;
bool ShouldRebuild = false;
private:
void Create();
void CleanMesh();
void CreateVoxelData();
void CreateMesh();
void CreateOpenGLMesh();
void CreateChunkThreadFunc(bool& result, std::atomic<bool>& shouldTerminate, std::atomic<bool>& wasTerminated);
bool ShouldAddTop(int x, int y, int z);
bool ShouldAddBottom(int x, int y, int z);
bool ShouldAddLeft(int x, int y, int z);
bool ShouldAddRight(int x, int y, int z);
bool ShouldAddFront(int x, int y, int z);
bool ShouldAddBack(int x, int y, int z);
void AddTopFace(int x, int y, int z, int& idx);
void AddBottomFace(int x, int y, int z, int& idx);
void AddFrontFace(int x, int y, int z, int& idx);
void AddBackFace(int x, int y, int z, int& idx);
void AddLeftFace(int x, int y, int z, int& idx);
void AddRightFace(int x, int y, int z, int& idx);
std::unique_ptr<Mesh> ChunkMesh;
std::shared_ptr<Shader> ChunkShader;
glm::vec3 Position = glm::vec3(0);
bool IsChunkEmpty = true;
bool DidThreadFinish = false;
bool WasMeshCreated = false;
std::thread ChunkThread;
std::atomic<bool> ShouldTerminateThread = false;
std::atomic<bool> WasThreadTerminated = false;
};
</code></pre>
<p>Chunk.cpp</p>
<pre><code>#include "Chunk.h"
#include <functional>
#include "Camera.h"
#include "ChunkManager.h"
#include "Filepath.h"
#include <glm/ext/matrix_transform.hpp>
#include "FastNoiseSIMD/FastNoiseSIMD.h"
//#include <pthread.h>
int Chunk::GlobalChunkVertexCount = 0;
Chunk::Chunk()
{
}
Chunk::~Chunk()
{
//pthread_cancel(ChunkThread);
}
void Chunk::CreateChunkThreadFunc(bool &result, std::atomic<bool>& shouldTerminate, std::atomic<bool>& wasTerminated)
{
if (ShouldTerminateThread == true)
{
wasTerminated = true;
return;
}
CreateVoxelData();
if (ShouldTerminateThread == true)
{
wasTerminated = true;
return;
}
CreateMesh();
if (ShouldTerminateThread == true)
{
wasTerminated = true;
return;
}
wasTerminated = true;
result = true;
}
void Chunk::Create(glm::vec3 position, std::shared_ptr<Shader> shader)
{
Position = position;
ChunkShader = shader;
/*auto f = [&](bool &b) {
CreateVoxelData();
CreateMesh();
b = true;
};*/
//std::thread t1(&Chunk::CreateChunkThreadFunc, std::ref(DidThreadFinish));
//std::thread t1([this, &DidThreadFinish]() { this->CreateChunkThreadFunc(DidThreadFinish); });
//std::thread t1(std::mem_fun(&Chunk::CreateChunkThreadFunc), this, std::ref(DidThreadFinish)));
ChunkThread = std::thread([this]() { this->CreateChunkThreadFunc(this->DidThreadFinish, this->ShouldTerminateThread, this->WasThreadTerminated); });
ChunkThread.detach();
//t1.join();
//ChunkShader = std::unique_ptr<Shader>(new Shader((fp::ShadersFolder + shaderName + fp::ExtVertex).c_str(), (fp::ShadersFolder + shaderName + fp::ExtFragment).c_str()));
}
void Chunk::Update(Camera *cam, float dt)
{
if (DidThreadFinish == true && WasMeshCreated == false)
{
CreateOpenGLMesh();
//std::cout << "Vertex count: " << Chunk::GlobalChunkVertexCount << std::endl;
WasMeshCreated = true;
}
// get distance
glm::vec3 distance = Position - cam->GetPosition();
bool shouldDelete = false;
if (distance.x > ChunkManager::ChunkGenRadius * Chunk::ChunkSize)
{
shouldDelete = true;
}
if (distance.y > ChunkManager::ChunkGenRadius * Chunk::ChunkSize)
{
shouldDelete = true;
}
if (distance.z > ChunkManager::ChunkGenRadius * Chunk::ChunkSize)
{
shouldDelete = true;
}
// flags for object deletion
// erase if too big (first terminate thread
if (shouldDelete)
{
//ShouldBeDeleted = true;
ShouldTerminateThread = true;
//ChunkThread.join();
}
if (WasThreadTerminated == true && shouldDelete)
{
ShouldBeDeleted = true;
}
//flags for mesh rebuild
if (ShouldRebuild)
{
if (WasThreadTerminated == false || DidThreadFinish == false)
{
//ShouldTerminateThread = true;
}
else
{
CleanMesh();
Create();
ShouldRebuild = false;
}
}
}
void Chunk::Render(Camera *cam)
{
if (IsChunkEmpty == false && DidThreadFinish == true && WasMeshCreated == true)
{
ChunkMesh->Render(ChunkShader.get(), cam);
}
}
/*void Chunk::RebuildMesh()
{
IsChunkEmpty = true;
ChunkMesh->Vertices.clear();
ChunkMesh->Indices.clear();
ChunkMesh->Normals.clear();
ChunkMesh->UVs.clear();
ChunkMesh.reset();
CreateVoxelData();
CreateMesh();
}*/
glm::vec3 Chunk::GetPosition()
{
return Position;
}
glm::mat4 Chunk::GetWorldMatrix()
{
return ChunkMesh->WorldMatrix;
}
void Chunk::Create()
{
ChunkThread = std::thread([this]() { this->CreateChunkThreadFunc(this->DidThreadFinish, this->ShouldTerminateThread, this->WasThreadTerminated); });
ChunkThread.detach();
}
void Chunk::CleanMesh()
{
IsChunkEmpty = true;
ChunkMesh->Vertices.clear();
ChunkMesh->Indices.clear();
ChunkMesh->Normals.clear();
ChunkMesh->UVs.clear();
ChunkMesh.reset();
}
void Chunk::CreateVoxelData()
{
FastNoiseSIMD* myNoise = FastNoiseSIMD::NewFastNoiseSIMD();
// Get a set of 16 x 16 x 16 Simplex Fractal noise
float* noiseSet = myNoise->GetSimplexFractalSet(Position.x, Position.y, Position.z, ChunkSize, ChunkSize, ChunkSize, NoiseScale);
int noiseIdx = 0;
for (int x = 0; x < ChunkSize; x++)
{
for (int y = 0; y < ChunkSize; y++)
{
for (int z = 0; z < ChunkSize; z++)
{
if (noiseSet[noiseIdx] > NoiseTreshold)
{
Data[x][y][z] = 0;
}
else
{
Data[x][y][z] = -1;
}
noiseIdx++;
/*if (y < 8)
{
if (x < 6 && z < 6)
{
Data[x][y][z] = 0;
}
else
{
Data[x][y][z] = 1;
}
}
else if ( y > 8)
{
Data[x][y][z] = -1;
}
if (y == 9 || y == 10)
{
if (x > 4 && x < 12 && z > 4 && z < 12)
{
Data[x][y][z] = 1;
}
}*/
}
}
}
FastNoiseSIMD::FreeNoiseSet(noiseSet);
}
void Chunk::CreateMesh()
{
ChunkMesh = std::unique_ptr<Mesh>(new Mesh());
ChunkMesh->IndicesEnabled = true;
ChunkMesh->UVsEnabled = true;
ChunkMesh->UVsAttribute = 1;
ChunkMesh->NormalsEnabled = true;
ChunkMesh->NormalsAttribute = 2;
ChunkMesh->TexIDEnabled = true;
ChunkMesh->TexIDAttribute = 3;
int idx = 0;
for (int x = 0; x < ChunkSize; x++)
{
for (int y = 0; y < ChunkSize; y++)
{
for (int z = 0; z < ChunkSize; z++)
{
if (Data[x][y][z] >= 0) // voxel exists
{
if (ShouldAddTop(x, y, z)) AddTopFace(x, y, z, idx);
if (ShouldAddBottom(x, y, z)) AddBottomFace(x, y, z, idx);
if (ShouldAddFront(x, y, z)) AddFrontFace(x, y, z, idx);
if (ShouldAddBack(x, y, z)) AddBackFace(x, y, z, idx);
if (ShouldAddLeft(x, y, z)) AddLeftFace(x, y, z, idx);
if (ShouldAddRight(x, y, z)) AddRightFace(x, y, z, idx);
}
//if (ShouldAddTop(x, y, z)) AddTopFace(x, y, z, idx);
}
}
}
}
void Chunk::CreateOpenGLMesh()
{
GlobalChunkVertexCount += ChunkMesh->Vertices.size();
if (ChunkMesh->Vertices.size() > 0)
{
ChunkMesh->Create(ChunkShader.get());
IsChunkEmpty = false;
}
else
{
IsChunkEmpty = true;
}
ChunkMesh->WorldMatrix = glm::translate(ChunkMesh->WorldMatrix, Position);
}
bool Chunk::ShouldAddTop(int x, int y, int z)
{
if (y + 1 >= ChunkSize)
{
// out of bounds, decide if should display quad, or fetch data from child chunk if exists
if (auto tch = TopChunk.lock()) //top chunk exist, check value from there
{
if (tch->Data[x][0][z] >= 0) // voxel in top chunk is full, dont display
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
if (Data[x][y + 1][z] >= 0) // if Data is greater than zero, means there is a voxel there, so should not add that face
{
return false;
}
else
{
return true;
}
}
bool Chunk::ShouldAddBottom(int x, int y, int z)
{
if (y - 1 < 0)
{
// out of bounds, decide if should display quad, or fetch data from child chunk if exists
if (auto bch = BottomChunk.lock()) //top chunk exist, check value from there
{
if (bch->Data[x][Chunk::ChunkSize - 1][z] >= 0) // voxel in top chunk is full, dont display
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
if (Data[x][y - 1][z] >= 0) // if Data is greater than zero, means there is a voxel to display
{
return false;
}
else
{
return true;
}
}
bool Chunk::ShouldAddLeft(int x, int y, int z)
{
if (x - 1 < 0)
{
// out of bounds, decide if should display quad, or fetch data from child chunk if exists
if (auto lch = LeftChunk.lock()) //top chunk exist, check value from there
{
if (lch->Data[Chunk::ChunkSize - 1][y][z] >= 0) // voxel in top chunk is full, dont display
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
if (Data[x - 1][y][z] >= 0) // if Data is greater than zero, means there is a voxel to display
{
return false;
}
else
{
return true;
}
}
bool Chunk::ShouldAddRight(int x, int y, int z)
{
if (x + 1 >= ChunkSize)
{
// out of bounds, decide if should display quad, or fetch data from child chunk if exists
if (auto rch = RightChunk.lock()) //top chunk exist, check value from there
{
if (rch->Data[0][y][z] >= 0) // voxel in top chunk is full, dont display
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
if (Data[x + 1][y][z] >= 0) // if Data is greater than zero, means there is a voxel to display
{
return false;
}
else
{
return true;
}
}
bool Chunk::ShouldAddFront(int x, int y, int z)
{
if (z + 1 >= ChunkSize)
{
// out of bounds, decide if should display quad, or fetch data from child chunk if exists
if (auto fch = FrontChunk.lock()) //top chunk exist, check value from there
{
if (fch->Data[x][y][Chunk::ChunkSize - 1] >= 0) // voxel in top chunk is full, dont display
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
if (Data[x][y][z + 1] >= 0) // if Data is greater than zero, means there is a voxel to display
{
return false;
}
else
{
return true;
}
}
bool Chunk::ShouldAddBack(int x, int y, int z)
{
if (z - 1 < 0)
{
// out of bounds, decide if should display quad, or fetch data from child chunk if exists
if (auto bch = BackChunk.lock()) //top chunk exist, check value from there
{
if (bch->Data[x][y][0] >= 0) // voxel in top chunk is full, dont display
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
if (Data[x][y][z - 1] >= 0) // if Data is greater than zero, means there is a voxel to display
{
return false;
}
else
{
return true;
}
}
void Chunk::AddTopFace(int x, int y, int z, int& idx)
{
// top face verts
ChunkMesh->Vertices.push_back(1 + x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(1 + z);
ChunkMesh->Vertices.push_back(1 + x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(0 + z);
ChunkMesh->Vertices.push_back(0 + x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(0 + z);
ChunkMesh->Vertices.push_back(0 + x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(1 + z);
// indices
ChunkMesh->Indices.push_back(idx + 0); ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 3);
ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 2); ChunkMesh->Indices.push_back(idx + 3);
idx += 4;
// normals
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(1); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(1); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(1); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(1); ChunkMesh->Normals.push_back(0);
// uvs
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(1);
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(1);
// texid
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
}
void Chunk::AddBottomFace(int x, int y, int z, int& idx)
{
// bottom face
ChunkMesh->Vertices.push_back(1 + x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(1 + z);
ChunkMesh->Vertices.push_back(1 + x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(0 + z);
ChunkMesh->Vertices.push_back(0 + x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(0 + z);
ChunkMesh->Vertices.push_back(0 + x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(1 + z);
// bottom
ChunkMesh->Indices.push_back(idx + 3); ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 0);
ChunkMesh->Indices.push_back(idx + 3); ChunkMesh->Indices.push_back(idx + 2); ChunkMesh->Indices.push_back(idx + 1);
idx += 4;
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(-1); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(-1); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(-1); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(-1); ChunkMesh->Normals.push_back(0);
// uvs
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(1);
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(1);
// texid
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
}
void Chunk::AddFrontFace(int x, int y, int z, int& idx)
{
// front face verts
ChunkMesh->Vertices.push_back(1 + x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(z + 1);
ChunkMesh->Vertices.push_back(1 + x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(z + 1);
ChunkMesh->Vertices.push_back(0 + x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(z + 1);
ChunkMesh->Vertices.push_back(0 + x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(z + 1);
// indices
ChunkMesh->Indices.push_back(idx + 3); ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 0);
ChunkMesh->Indices.push_back(idx + 3); ChunkMesh->Indices.push_back(idx + 2); ChunkMesh->Indices.push_back(idx + 1);
idx += 4;
// normals
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(1);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(1);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(1);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(1);
// uvs
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(1);
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(1);
// texid
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
}
void Chunk::AddBackFace(int x, int y, int z, int& idx)
{
// back face
ChunkMesh->Vertices.push_back(1 + x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(z);
ChunkMesh->Vertices.push_back(1 + x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(z);
ChunkMesh->Vertices.push_back(0 + x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(z);
ChunkMesh->Vertices.push_back(0 + x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(z);
// back
ChunkMesh->Indices.push_back(idx + 0); ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 3);
ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 2); ChunkMesh->Indices.push_back(idx + 3);
idx += 4;
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(-1);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(-1);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(-1);
ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(-1);
// uvs
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(1);
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(1);
// texid
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
}
void Chunk::AddLeftFace(int x, int y, int z, int& idx)
{
// left face
ChunkMesh->Vertices.push_back(x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(z + 1);
ChunkMesh->Vertices.push_back(x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(z + 1);
ChunkMesh->Vertices.push_back(x); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(z);
ChunkMesh->Vertices.push_back(x); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(z);
// left
ChunkMesh->Indices.push_back(idx + 3); ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 0);
ChunkMesh->Indices.push_back(idx + 3); ChunkMesh->Indices.push_back(idx + 2); ChunkMesh->Indices.push_back(idx + 1);
idx += 4;
ChunkMesh->Normals.push_back(-1); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(-1); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(-1); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(-1); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0);
// uvs
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(1);
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(1);
// texid
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
}
void Chunk::AddRightFace(int x, int y, int z, int& idx)
{
// right face
ChunkMesh->Vertices.push_back(x + 1); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(z + 1);
ChunkMesh->Vertices.push_back(x + 1); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(z + 1);
ChunkMesh->Vertices.push_back(x + 1); ChunkMesh->Vertices.push_back(y); ChunkMesh->Vertices.push_back(z);
ChunkMesh->Vertices.push_back(x + 1); ChunkMesh->Vertices.push_back(1 + y); ChunkMesh->Vertices.push_back(z);
// right
ChunkMesh->Indices.push_back(idx + 0); ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 3);
ChunkMesh->Indices.push_back(idx + 1); ChunkMesh->Indices.push_back(idx + 2); ChunkMesh->Indices.push_back(idx + 3);
idx += 4;
ChunkMesh->Normals.push_back(1); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(1); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(1); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0);
ChunkMesh->Normals.push_back(1); ChunkMesh->Normals.push_back(0); ChunkMesh->Normals.push_back(0);
// uvs
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(0);
ChunkMesh->UVs.push_back(1); ChunkMesh->UVs.push_back(1);
ChunkMesh->UVs.push_back(0); ChunkMesh->UVs.push_back(1);
// texid
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
ChunkMesh->TexIDs.push_back((float)Data[x][y][z]);
}
</code></pre>
<p>ChunkManager.h</p>
<pre><code>#pragma once
/*template<typename T> struct matrix
{
matrix(unsigned m, unsigned n) : m(m), n(n), vs(m* n) {}
T& operator ()(unsigned i, unsigned j) {
return vs[i + m * j];
}
private:
unsigned m;
unsigned n;
std::vector<T> vs;
};
//column-major/opengl: vs[i + m * j], row-major/c++: vs[n * i + j]
*/
#include <memory>
#include <unordered_map>
#include <map>
#include "Chunk.h"
#include <glm/glm.hpp>
#include <glm/gtx/hash.hpp>
class Shader;
class Camera;
class ChunkManager
{
public:
ChunkManager();
~ChunkManager();
void CreateFixedWorld(int width, int height, int depth, std::shared_ptr<Shader> shader);
void Update(Camera* camera, float dt);
void Render(Camera* camera);
static int ChunkGenRadius;
private:
int Width = 0, Height = 0, Depth = 0;
Chunk* Chunks;
std::shared_ptr<Shader> ChunkShader;
std::unordered_map<glm::vec3, std::shared_ptr<Chunk>> ChunkMap;
};
</code></pre>
<p>ChunkManager.cpp</p>
<pre><code>#include "ChunkManager.h"
#include "Shader.h"
#include "Camera.h"
#include <chrono>
#include <iostream>
int ChunkManager::ChunkGenRadius = 5;
ChunkManager::ChunkManager()
{
}
ChunkManager::~ChunkManager()
{
}
void ChunkManager::CreateFixedWorld(int width, int height, int depth, std::shared_ptr<Shader> shader)
{
Width = width;
Height = height;
Depth = depth;
ChunkShader = shader;
// Record start time
auto start = std::chrono::high_resolution_clock::now();
Chunks = new Chunk[width * height * depth];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
for (int z = 0; z < depth; z++)
{
Chunks[x + width * (y + depth * z)].Create(glm::vec3(x * Chunk::ChunkSize, y * Chunk::ChunkSize, z * Chunk::ChunkSize), shader);
}
}
}
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "Elapsed time: " << elapsed.count() << " s\n";
std::cout << "Vertex count: " << Chunk::GlobalChunkVertexCount << std::endl;
}
void ChunkManager::Update(Camera* camera, float dt)
{
//figure out chunk where camera is
glm::vec3 camChunkPos = camera->GetPosition() / glm::vec3(Chunk::ChunkSize, Chunk::ChunkSize, Chunk::ChunkSize);
camChunkPos = glm::vec3(floorf(camChunkPos.x) * Chunk::ChunkSize, floorf(camChunkPos.y) * Chunk::ChunkSize, floorf(camChunkPos.z) * Chunk::ChunkSize);
// loop for theoretical chunks around camera
for (int x = -ChunkGenRadius; x < ChunkGenRadius; x++)
{
for (int y = -ChunkGenRadius; y < ChunkGenRadius; y++)
{
for (int z = -ChunkGenRadius; z < ChunkGenRadius; z++)
{
// check if chunk exists
glm::vec3 posToCheck = camChunkPos + glm::vec3(x * Chunk::ChunkSize, y * Chunk::ChunkSize, z * Chunk::ChunkSize);
auto result = ChunkMap.find(posToCheck);
if (result == ChunkMap.end()) // if doesn't exist (iterator looped through everything)
{
//create chunk
std::shared_ptr<Chunk> newChunk = std::shared_ptr<Chunk>(new Chunk());
// check surrounding chunks;
auto topResult = ChunkMap.find(posToCheck + glm::vec3(0, Chunk::ChunkSize, 0));
if (topResult != ChunkMap.end())
{
newChunk->TopChunk = topResult->second;
topResult->second->BottomChunk = newChunk;
topResult->second->ShouldRebuild = true;
}
auto bottomResult = ChunkMap.find(posToCheck + glm::vec3(0, -Chunk::ChunkSize, 0));
if (bottomResult != ChunkMap.end())
{
newChunk->BottomChunk = bottomResult->second;
bottomResult->second->TopChunk = newChunk;
bottomResult->second->ShouldRebuild = true;
}
auto leftResult = ChunkMap.find(posToCheck + glm::vec3(-Chunk::ChunkSize, 0, 0));
if (leftResult != ChunkMap.end())
{
newChunk->LeftChunk = leftResult->second;
leftResult->second->RightChunk = newChunk;
leftResult->second->ShouldRebuild = true;
}
auto rightResult = ChunkMap.find(posToCheck + glm::vec3(Chunk::ChunkSize, 0, 0));
if (rightResult != ChunkMap.end())
{
newChunk->RightChunk = rightResult->second;
rightResult->second->LeftChunk = newChunk;
rightResult->second->ShouldRebuild = true;
}
auto frontResult = ChunkMap.find(posToCheck + glm::vec3(0, 0, Chunk::ChunkSize));
if (frontResult != ChunkMap.end())
{
newChunk->FrontChunk = frontResult->second;
frontResult->second->BackChunk = newChunk;
frontResult->second->ShouldRebuild = true;
}
auto backResult = ChunkMap.find(posToCheck + glm::vec3(0, 0, -Chunk::ChunkSize));
if (backResult != ChunkMap.end())
{
newChunk->BackChunk = backResult->second;
backResult->second->FrontChunk = newChunk;
backResult->second->ShouldRebuild = true;
}
//create and assign
newChunk->Create(posToCheck, ChunkShader);
//ChunkMap.insert(std::make_pair<glm::vec3, Chunk>(posToCheck, newChunk));
ChunkMap[posToCheck] = std::move(newChunk);
}
}
}
}
for (auto it = ChunkMap.begin(); it != ChunkMap.end(); )
{
if(it->second != nullptr)
if (it->second->ShouldBeDeleted)
{
it = ChunkMap.erase(it);
}
else
{
it->second->Update(camera, dt);
++it;
}
}
}
void ChunkManager::Render(Camera* camera)
{
for (auto& [key, val] : ChunkMap)
{
val->Render(camera);
}
}
</code></pre>
<p>Application.h</p>
<pre><code>#pragma once
// third party
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
// system
#include <memory>
// custom
#include "Color.h"
#include "Camera.h"
#include "Mesh.h"
#include "CoordsGizmo.h"
#include "Texture.h"
#include "Chunk.h"
#include "ChunkManager.h"
struct DestroyGLFWwnd {
void operator()(GLFWwindow* ptr) {
glfwDestroyWindow(ptr);
}
};
typedef std::unique_ptr<GLFWwindow, DestroyGLFWwnd> sptr_GLFWwindow;
class Shader;
class glShaderManager;
class Application
{
public:
Application(int windowWidth, int windowHeight);
~Application();
void Run();
private:
void Init();
void MainLoop();
void Release();
void ProcessInput();
void UpdateLogic();
void Render();
void RenderUI();
void InitGLFW();
void InitGLEW();
void InitOGL();
void InitIMGUI();
void GLFWFramebufferSizeCallback(GLFWwindow* window, int width, int height);
void GLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
void CalculateDeltaTime();
void SaveLastDeltaTime();
void ClearColor();
void SwapBuffersPollEvents();
void CloseOnEsc();
void EnableCursor();
void DisableCursor();
sptr_GLFWwindow Window;
Color BackgroundColor;
int WindowWidth;
int WindowHeight;
float DeltaTime;
float LastTime;
//test
void InitTestCode();
void RenderTestCode();
unsigned int VAO;
std::unique_ptr<Shader> Sh;
Camera MainCamera;
bool IsMouseLookEnabled = true;
bool IsWireframeEnabled = false;
std::unique_ptr<Shader> ColorShader;
std::unique_ptr<Shader> TextureArrayShader;
std::shared_ptr<Shader> TexArrLightShader;
std::unique_ptr<Texture> TestTexture;
std::unique_ptr<Texture> TestTexture2;
//Mesh coordsMesh;
CoordsGizmo CoordsObj;
GLuint TextureArray;
Chunk chunk, chunk2, chunk3, chunk4;
ChunkManager ChMgr;
};
</code></pre>
<p>Application.cpp</p>
<pre><code>#include "Application.h"
#include <iostream>
#include "Shader.h"
#include "glsl.h"
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
using namespace std;
Application::Application(int windowWidth, int windowHeight)
: MainCamera(60.0f, 4.0f / 3.0f, 0.1f, 1000.0f)
{
WindowWidth = windowWidth;
WindowHeight = windowHeight;
BackgroundColor = Color(0.25f, 0.5f, 1, 1);
DeltaTime = 0;
LastTime = 0;
}
Application::~Application()
{
glfwTerminate();
}
void Application::Run()
{
Init();
MainLoop();
Release();
}
void Application::Init()
{
InitGLFW();
InitGLEW();
InitOGL();
InitIMGUI();
InitTestCode();
}
void Application::MainLoop()
{
while (!glfwWindowShouldClose(Window.get()))
{
CalculateDeltaTime();
ProcessInput();
UpdateLogic();
Render();
SaveLastDeltaTime();
}
}
void Application::Release()
{
}
void Application::ProcessInput()
{
CloseOnEsc();
MainCamera.HandleInput(Window.get(), DeltaTime, WindowWidth, WindowHeight);
if (IsMouseLookEnabled)
{
MainCamera.MouseLook(Window.get(), DeltaTime, WindowWidth, WindowHeight);
}
}
void Application::UpdateLogic()
{
MainCamera.Update(DeltaTime);
}
void Application::Render()
{
RenderUI();
ClearColor();
RenderTestCode();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SwapBuffersPollEvents();
}
float cpos[3], tpos[3];
float noiseTreshold = 0;
float noiseScale = 1;
void Application::RenderUI()
{
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
/*ImGui::Begin("Terrain Gen");
ImGui::SliderFloat ("treshold", &noiseTreshold, -1.0f, 1.0f);
ImGui::SliderFloat("scale", &noiseScale, 0.0f, 100.0f);
if (ImGui::Button("generate")) // Buttons return true when clicked (most widgets return true when edited/activated)
{
chunk.NoiseTreshold = noiseTreshold;
chunk2.NoiseTreshold = noiseTreshold;
chunk3.NoiseTreshold = noiseTreshold;
chunk4.NoiseTreshold = noiseTreshold;
chunk.NoiseScale = noiseScale;
chunk2.NoiseScale = noiseScale;
chunk3.NoiseScale = noiseScale;
chunk4.NoiseScale = noiseScale;
chunk.RebuildMesh();
chunk2.RebuildMesh();
chunk3.RebuildMesh();
chunk4.RebuildMesh();
}
ImGui::End();*/
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
{
static float f = 0.0f;
static int counter = 0;
static bool hasTarget = false;
ImGui::Begin("Camera"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("position");
ImGui::InputFloat3("pos", cpos);
ImGui::Checkbox("target", &hasTarget);
if (hasTarget)
{
ImGui::InputFloat3("dir", tpos);
}
if (ImGui::Button("Move")) // Buttons return true when clicked (most widgets return true when edited/activated)
{
MainCamera.SetPosition(glm::vec3(cpos[0], cpos[1], cpos[2]));
if (hasTarget)
{
glm::vec3 target = glm::vec3(cpos[0] - tpos[0], cpos[1] - tpos[1], cpos[2] - tpos[2]);
MainCamera.SetDirection(glm::normalize(target));
}
}
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
// Rendering
ImGui::Render();
}
void Application::InitGLFW()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // consider switching to 2.1 with extensions for release
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
Window = sptr_GLFWwindow(glfwCreateWindow(WindowWidth, WindowHeight, "LearnOpenGL", NULL, NULL));
if (Window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
//return -1;
}
glfwMakeContextCurrent(Window.get());
glfwSwapInterval(1);
// Ensure we can capture the escape key being pressed below
glfwSetInputMode(Window.get(), GLFW_STICKY_KEYS, GL_TRUE);
// Hide the mouse and enable unlimited mouvement
glfwSetInputMode(Window.get(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
//callbacks
glfwSetWindowUserPointer(Window.get(), this);
auto framebufferFunc = [](GLFWwindow* w, int width, int height)
{
static_cast<Application*>(glfwGetWindowUserPointer(w))->GLFWFramebufferSizeCallback(w, width, height);
};
glfwSetFramebufferSizeCallback(Window.get(), framebufferFunc);
auto keyFunc = [](GLFWwindow* w, int key, int scancode, int action, int mods)
{
static_cast<Application*>(glfwGetWindowUserPointer(w))->GLFWKeyCallback(w, key, scancode, action, mods);
};
glfwSetKeyCallback(Window.get(), keyFunc);
}
void Application::InitGLEW()
{
glewExperimental = GL_TRUE;
//init glew after the context have been made
glewInit();
// enable experimental?
GLint GlewInitResult = glewInit();
if (GLEW_OK != GlewInitResult)
{
std::cout << "GLEW INIT FAILED";
}
}
void Application::InitOGL()
{
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
// Cull triangles which normal is not towards the camera
glEnable(GL_CULL_FACE);
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_LINE);
auto ogldebugfunc = [](GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam) {
cout << "---------------------opengl-callback-start------------" << endl;
cout << "message: " << message << endl;
cout << "type: ";
switch (type) {
case GL_DEBUG_TYPE_ERROR:
cout << "ERROR";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
cout << "DEPRECATED_BEHAVIOR";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
cout << "UNDEFINED_BEHAVIOR";
break;
case GL_DEBUG_TYPE_PORTABILITY:
cout << "PORTABILITY";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
cout << "PERFORMANCE";
break;
case GL_DEBUG_TYPE_OTHER:
cout << "OTHER";
break;
}
cout << endl;
cout << "id: " << id << endl;
cout << "severity: ";
switch (severity) {
case GL_DEBUG_SEVERITY_LOW:
cout << "LOW";
break;
case GL_DEBUG_SEVERITY_MEDIUM:
cout << "MEDIUM";
break;
case GL_DEBUG_SEVERITY_HIGH:
cout << "HIGH";
break;
}
cout << endl;
cout << "---------------------opengl-callback-end--------------" << endl;
};
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(ogldebugfunc, nullptr);
GLuint unusedIds = 0;
glDebugMessageControl(GL_DONT_CARE,
GL_DONT_CARE,
GL_DONT_CARE,
0,
&unusedIds,
true);
}
void Application::InitIMGUI()
{
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForOpenGL(Window.get(), true);
ImGui_ImplOpenGL3_Init("#version 330");
}
void Application::GLFWFramebufferSizeCallback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
void Application::GLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_I && action == GLFW_PRESS)
{
MainCamera.SetAngles(0, 3.14f);
}
if (key == GLFW_KEY_O && action == GLFW_PRESS)
{
IsMouseLookEnabled = !IsMouseLookEnabled;
if (IsMouseLookEnabled)
{
DisableCursor();
}
else
{
EnableCursor();
}
}
if (key == GLFW_KEY_P && action == GLFW_PRESS)
{
IsWireframeEnabled = !IsWireframeEnabled;
if (IsWireframeEnabled)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//glPolygonMode(GL_BACK, GL_LINE);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
}
}
void Application::CalculateDeltaTime()
{
DeltaTime = float((float)glfwGetTime() - LastTime);
}
void Application::SaveLastDeltaTime()
{
LastTime = DeltaTime;
}
void Application::ClearColor()
{
glClearColor(BackgroundColor.GetR(), BackgroundColor.GetG(), BackgroundColor.GetB(), BackgroundColor.GetA());
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Application::SwapBuffersPollEvents()
{
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(Window.get());
glfwPollEvents();
}
void Application::CloseOnEsc()
{
if (glfwGetKey(Window.get(), GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(Window.get(), true);
}
void Application::EnableCursor()
{
glfwSetInputMode(Window.get(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
void Application::DisableCursor()
{
glfwSetInputMode(Window.get(), GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
void Application::InitTestCode()
{
Sh = std::unique_ptr<Shader>(new Shader("test.v", "test.f"));
TextureArrayShader = std::unique_ptr<Shader>(new Shader("Data//Shaders//texturearray.v", "Data//Shaders//texturearray.f"));
TexArrLightShader = std::shared_ptr<Shader>(new Shader("Data//Shaders//texarrlight.v", "Data//Shaders//texarrlight.f"));
TestTexture = std::unique_ptr<Texture>(new Texture("Data//Textures//dirt.jpg", GL_TEXTURE_2D));
TestTexture2 = std::unique_ptr<Texture>(new Texture("Data//Textures//stone.png", GL_TEXTURE_2D));
/*chunk.Create(glm::vec3(0), TexArrLightShader);
chunk2.Create(glm::vec3(16, 0, 0), TexArrLightShader);
chunk3.Create(glm::vec3(16, 0, 16), TexArrLightShader);
chunk4.Create(glm::vec3(0, 0, 16), TexArrLightShader);*/
int size = 8;
ChMgr.CreateFixedWorld(size, size, size, TexArrLightShader);
ColorShader = std::unique_ptr<Shader>(new Shader("Data//Shaders//color.v", "Data//Shaders//color.f"));
CoordsObj.Create(ColorShader.get());
MainCamera.SetSpeed(0.1f);
MainCamera.SetPosition(glm::vec3(0, 0, 5));
glGenTextures(1, &TextureArray);
glBindTexture(GL_TEXTURE_2D_ARRAY, TextureArray);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA8, 512, 512, 2);//last three numbers are size of images and array
int dw, dh, sw, sh;
unsigned char* image1 = SOIL_load_image("Data//Textures//dirt.jpg", &dw, &dh, NULL, SOIL_LOAD_RGBA);
unsigned char* image2 = SOIL_load_image("Data//Textures//stone.png", &sw, &sh, NULL, SOIL_LOAD_RGBA);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, dw, dh, 1, GL_RGBA, GL_UNSIGNED_BYTE, image1);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 1, sw, sh, 1, GL_RGBA, GL_UNSIGNED_BYTE, image2);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void Application::RenderTestCode()
{
CoordsObj.Render(ColorShader.get(), &MainCamera);
//TestTexture->bind(0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D_ARRAY, TextureArray);
TexArrLightShader->bind(); // this should be done once and somewhere else
GLint modelLoc = glGetUniformLocation(TexArrLightShader->id(), "M"); //dont do that in main loop
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(glm::mat4(1)/*chunk.GetWorldMatrix()*/));
GLint lightPosLoc = glGetUniformLocation(TexArrLightShader->id(), "lightPos"); //dont do that in main loop
GLint objectColorLoc = glGetUniformLocation(TexArrLightShader->id(), "objectColor"); //dont do that in main loop
GLint lightColorLoc = glGetUniformLocation(TexArrLightShader->id(), "lightColor"); //dont do that in main loop
GLint ambientStrenghtLoc = glGetUniformLocation(TexArrLightShader->id(), "ambientStrenght"); //dont do that in main loop
GLint camPosLoc = glGetUniformLocation(TexArrLightShader->id(), "camPos"); //dont do that in main loop
GLint cusDirLightLoc = glGetUniformLocation(TexArrLightShader->id(), "cusDirLight"); //dont do that in main loop
glUniform3f(lightPosLoc, -5.0f, 5.0f, 5.0f);
glUniform3f(objectColorLoc, 0.0f, 1.0f, 0.0f); //since it doesnt change could be done outside main loop
glUniform3f(lightColorLoc, 1.0f, 1.0f, 1.0f); //since it doesnt change could be done outside main loop
glUniform1f(ambientStrenghtLoc, 0.5f); //since it doesnt change could be done outside main loop
glUniform3f(camPosLoc, MainCamera.GetPosition().x, MainCamera.GetPosition().y, MainCamera.GetPosition().z);
glUniform3f(cusDirLightLoc, 0.5f, -1, 0.5f);
ChMgr.Update(&MainCamera, DeltaTime);
ChMgr.Render(&MainCamera);
/*chunk.Render(&MainCamera);
chunk2.Render(&MainCamera);
chunk3.Render(&MainCamera);
chunk4.Render(&MainCamera);*/
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T13:14:39.600",
"Id": "459119",
"Score": "0",
"body": "Welcome to code review. It is fine to show us a repository as background, but anything you actually want reviewed need to be posted here in the question. More facts about asking good questions can be found at https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask."
}
] |
[
{
"body": "<h1>Avoid forward declarations</h1>\n\n<p>Why is there a forward declaration of <code>class Camera</code> near the top? If <code>class Camera</code> is declared elsewhere, just add <code>#include <Camera.h></code> instead. The problem with forward declarations is that you are unnecessarily repeating things, and make it easier to introduce errors.</p>\n\n<p>If you really need forward declarations to avoid <code>#include</code> loops, then put those forward declarations in a separate header file, and then <code>#include</code> that header file both in the place where you originally needed the forward declarations, <em>and</em> in the header files that have the full class definitions. This way, if you make a mistake with the forward declarations, the compiler will catch it when compiling the classes.</p>\n\n<h1>Make the constructor useful</h1>\n\n<p>I see you have a member function names <code>Create()</code>, and a constructor which takes no parameters. This leads me to believe your constructor doesn't fully construct <code>Chunk</code>s, and that you need to call <code>Create()</code> to fully create a <code>Chunk</code>. If so, why not let the constructor do everything <code>Create()</code> does?</p>\n\n<h1>Why does updating and rendering depend on the camera?</h1>\n\n<p>When rendering using OpenGL, the geometry you build from your objects is normally independent of the camera position. The latter only influences the model-view-projection matrix. I would expect these functions to not depend on the camera. If there is some functionality in them that does, could that perhaps be split out into a separate function, or avoided altogether?</p>\n\n<h1>Getters should be <code>const</code></h1>\n\n<p>Functions with names that start with <code>Get</code> probably don't change any of the member variables, only read them. Therefore these should be marked <code>const</code>, like so:</p>\n\n<pre><code>glm::vec3 GetPosition() const;\n</code></pre>\n\n<p>This helps the compiler optimize your code, and will also create helpful error messages if you do accidentily change some member variables within a getter function.</p>\n\n<h1>Make as much <code>private</code> as possible</h1>\n\n<p>You generally should hide as many member variables as possible. Does other code really need to write or read to <code>ShouldBeDeleted</code> or <code>GlobalChunkVertexCount</code>? If they only need to either read or write, writing a get- or set-function would ensure no accidents happen.</p>\n\n<p>Similarly, <code>Data[][][]</code> should be private, and some functions should be added to read and write to individual voxels. The reason is that in the future, you might want to change how this data is stored, and it is much easier to just update the getter and setter functions than to change all the places that directly manipulate <code>Data</code>.</p>\n\n<h1>Avoid repetition</h1>\n\n<p>You have a lot of functions that are specialized for top/bottom/left/right/front/back. This adds a lot of repetition, which might be avoidable. How about defining an <code>enum</code> to denote neighbor direction?</p>\n\n<pre><code>enum class Neighbour {\n TOP,\n BOTTOM,\n LEFT,\n RIGHT,\n FRONT,\n BACK,\n COUNT\n};\n</code></pre>\n\n<p>And then use this to make an array out of the pointers to neighboring chunks:</p>\n\n<pre><code>std::weak_ptr<Chunk> Neighbors[std::static_cast<size_t>(Neighbor::COUNT)];\n</code></pre>\n\n<p>And of some of the member functions:</p>\n\n<pre><code>bool ShouldAddFace(int x, int y, int z, Neighbor neighbor);\nvoid AddFace(int x, int y, int z, int &idx, Neighbor neighbor);\n</code></pre>\n\n<h1>Avoid too many flags</h1>\n\n<p>You have lots of flag variables. Some of them, like <code>IsChunkEmpty</code>, I can imagine are a form of optimization. That's fine. But there's a lot of <code>DidThreadFinish</code>, <code>WasThreadTerminated</code> and so on, that sound like they are there to work around issues that might be solved in other ways.</p>\n\n<p>Flags like these sound like they might be checked repeatedly, which is inefficient. Maybe there is something else that can be checked than the flag itself, or maybe you can guarantee some order so that the flag is unnecessary. For example, if you always ensure <code>CreateMesh()</code> is called before <code>Render()</code>, I'm sure you don't need <code>WasMeshCreated</code>.</p>\n\n<p>Similarly, if you always ensure to call <code>ChunkThread.join()</code> before doing things that currently check <code>WasThreadTerminated</code>, then you could get rid of that flag as well.</p>\n\n<h1>Using atomics</h1>\n\n<p>Atomics are good to have for multi-threaded code. They are no substitute for locks though. Also, changing multiple atomics doesn't mean they all are changed together in an atomic way. Having so many flags raises questions. What if the thread terminates before <code>ShouldTerminateThread</code> is called? Why are there both <code>DidThreadFinish</code> and <code>WasThreadTerminated</code>, and why is the former not an atomic variable?</p>\n\n<h1>Don't include unnecessary headers</h1>\n\n<p>Why is there an <code>#include <future></code>, if no futures are used in <code>Chunk.h</code>? Remove unneeded <code>#include</code>s.</p>\n\n<h1>Remove commented-out code</h1>\n\n<p>You already mentioned you have your code in a git repository. That means git will take care of remembering the history for you. So you shouldn't merely comment out code you no longer use, but remove it entirely. So this line should go:</p>\n\n<pre><code>//void RebuildMesh();\n</code></pre>\n\n<p>This keeps the code clean. If you ever need it back, git will be able to find it for you.</p>\n\n<h1>Use <code>{}</code> for value initialization</h1>\n\n<p>For member variables with a more complex type that you want to ensure are initialized to their default value, use <code>{}</code>. This can sometimes avoid repeating their type. For example:</p>\n\n<pre><code>glm::vec3 Position = {};\n</code></pre>\n\n<h1>Don't write <code>this-></code> unnecessarily</h1>\n\n<p>Member functions and variables can be accessed directly from other class members, you almost never need to add <code>this-></code>.</p>\n\n<p>Similarly, in member functions of <code>class Chunk</code>, you don't need to write <code>Chunk::</code> in front of static member constants.</p>\n\n<h1>Don't detach threads</h1>\n\n<p>You almost never have to detach a thread. If you detach a thread, you no longer have full control over it. Just keep it attached to your program, and don't forget to call <code>join()</code> to clean it up.</p>\n\n<h1>Building meshes asynchronously</h1>\n\n<p>You want to build meshes in the background, and have them pop onto the screen when they are finished. You don't want to potentially have one thread per chunk, as there might be a lot of chunks suddenly coming in to view, which would all spawn threads. Instead, you probably want only a few threads dedicated to chunk building, so they don't take all the CPU time necessary for rendering the already built chunks.</p>\n\n<p>The way to do this is to create a work queue: if a chunk becomes visible, but it hasn't been built yet, add a pointer to this chunk to the queue. One or more threads are waiting for items to be added to this queue, and once there is something in it they can dequeue it and start building the chunks refered to. When a thread is finished with a chunk, it can somehow signal that it is done building, and can then check the queue if there is more work.</p>\n\n<p>For this to work, you need to have an atomic queue, so multiple threads can add and remove from it. A simple solution is to use a <code>std::queue</code> guarded by a <code>std::mutex</code>, and a <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable\" rel=\"noreferrer\"><code>std::condition_variable</code></a> (that link contains an example of a very simple worker thread) so the worker threads can go to sleep if there is nothing to be done, but can be woken up once another threads adds something to the queue. </p>\n\n<h1>Make better use of GLM</h1>\n\n<p>In <code>Chunk::update()</code>, you calculate the difference vector between the chunk's position and the camera position, and then look at the <code>x</code>, <code>y</code> and <code>z</code> components separately to determine whether it should be deleted. This can be greatly simplified by writing:</p>\n\n<pre><code>bool shouldDelete = glm::distance(Position, cam->GetPosition()) > ChunkManager::ChunkGenRadius * ChunkSize;\n</code></pre>\n\n<p>There's a slight difference; the above code will actually delete chunks outside of a sphere instead of a box, but that's probably fine.</p>\n\n<p>In <code>ChunkManager::Update()</code>, you can get the integer chunk position simply using:</p>\n\n<pre><code>glm::vec3 camChunkPos = glm::floor(camera->GetPosition() / ChunkSize);\n</code></pre>\n\n<p>Make better use of GLM, this results in shorter, more readable code with less errors. Every time you are doing something component-wise, check if there might not already be a function that does what you want for all components of a vector in one go.</p>\n\n<h1>Avoid duplicating data unnecessarily</h1>\n\n<p>It looks like <code>ChunkManager</code> has a <code>ChunkShader</code>, which is passed to all <code>Chunk</code>s created by it, and each <code>Chunk</code> also stores a copy. This seems unnecessary. Why not pass the <code>ChunkShader</code> as a parameter to the <code>Render()</code> functions?</p>\n\n<h1>Avoid bare pointers</h1>\n\n<p>Whenever possible use a proper container to manage object storage, instead of calling <code>new</code> and storing a bare pointer. STL containers ensure the storage gets deleted properly.</p>\n\n<p>In <code>ChunkManager</code>, use <code>std::vector<Chunk> Chunks</code> to store chunks. In <code>CreateFixedworld()</code>, simply allocate the right amount of space with:</p>\n\n<pre><code>Chunks.resize(width * height * depth);\n</code></pre>\n\n<p>You never called <code>delete</code>, so this change will fix a memory leak.</p>\n\n<h1>Use C++17's <code>if</code>-statements with initializers</h1>\n\n<p>Especially when trying to find something in a container, <code>C++17</code> allows you to simplify getting an interator and doing something only when it didn't point to the end. For example, in <code>ChunkManager::Update()</code>, you can write:</p>\n\n<pre><code>if (auto result = ChunkMap.find(posToCheck); result == ChunkMap.end) {\n ...\n}\n</code></pre>\n\n<h1>Use <code>std::make_shared()</code> and <code>std::make_unique()</code></h1>\n\n<p>Instead of writing <code>std::shared_ptr<Chunk>(new Chunk)</code>, write <code>std::make_shared<Chunk>()</code>. This avoids some repetition. Also, when assigning to a <code>std::shared_ptr<></code> variable, there is no need to first cast a new object to a <code>std::shared_ptr<></code>. So instead of:</p>\n\n<pre><code>std::shared_ptr<Chunk> newChunk = std::shared_ptr<Chunk>(new Chunk());\n</code></pre>\n\n<p>You could write:</p>\n\n<pre><code>std::shared_ptr<Chunk> newChunk = new Chunk();\n</code></pre>\n\n<p>However, it's generally best to avoid <code>new</code> and thus to use <code>std::make_shared<></code>. Note that you can use <code>auto</code> to avoid more repetition:</p>\n\n<pre><code>auto newChunk = std::make_shared<Chunk>();\n</code></pre>\n\n<p>The same goes for <code>std::make_unique<></code>.</p>\n\n<p>Note that in <code>ChunkManager::Update()</code>, it's better to make <code>newChunk</code> a <code>std::unique_ptr<></code>, since it's not being shared at that moment, and then hand over ownership to <code>ChunkMap</code> simply by writing:</p>\n\n<pre><code>ChunkMap[posToCheck] = newChunk;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T14:30:27.543",
"Id": "459131",
"Score": "0",
"body": "I really appreciate your input, thank you for spending your time for this reply. I have also updated my question with more source. Regarding forward declarations, In the past I have ran into include loops, even when using #pragma once, I understood that forward declarations are a good way of avoiding it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T16:51:55.843",
"Id": "459152",
"Score": "0",
"body": "That's indeed one way of avoiding include loops. However, if you need to resort to something, it is better to create a separate header file that has the forward declarations, and then include it both in the place where you would need it *and* in the header file that has the full class definitions. That way, if you make a mistake with the forward declarations, the compiler will spot the mistake when it tries to compile those classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T09:55:47.203",
"Id": "459963",
"Score": "0",
"body": "I disagree with avoiding forward declarations. Using forward declarations instead of includes where it is possible reduces compile times and it prevents indirect including of headers that you dont use in that translation unit. The only unnessecary repetition is the class name once instead of an include."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T19:40:39.550",
"Id": "460026",
"Score": "0",
"body": "@Eric: if you do want to reduce compile times, then I'd still suggest putting the forward declarations into a separate header file (just like `<iosfwd>`), and `#include` that one in both the `.cpp` files that uses them *and* in the header file with the full declarations; the latter to ensure you don't accidentily have a mismatch between the forward declarations and the full ones."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T14:06:27.520",
"Id": "234737",
"ParentId": "234730",
"Score": "10"
}
},
{
"body": "<h2>Avoid <code>using namespace std;</code></h2>\n\n<p>In <code>Application.cpp</code> the statement <code>using namespace std;</code> is used. 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\n<h2>Use Source Control Properly</h2>\n\n<p>There are several places in the source code where code is commented out, this is generally an indication that the code is not ready for review. It seems that the IDE in use is Visual Studio 2019, which means that the IDE supports the use of GIT for source control. Since GIT is readily available code that is commented out can be removed from source code and easily restored if the code is needed after all. This makes the code easier to read and maintain.</p>\n\n<h2>Commenting Versus Self-Documenting Code and DRY Code</h2>\n\n<p>In <code>Chunk.cpp</code> there are 6 functions (<code>bool ShouldAddTop()</code>, <code>bool ShouldAddBottom(),</code> ...) of similar format that generally have the same comments, in at least 3 of the functions at least one comment is incorrect.</p>\n\n<pre><code> if (auto bch = BackChunk.lock()) //top chunk exist, check value from there\n</code></pre>\n\n<p>All of these functions could be simplified, when the inner if statement is changed to :</p>\n\n<pre><code> return (bch->Data[x][y][0] >= 0); // Condition is different in each function\n</code></pre>\n\n<p>versus</p>\n\n<pre><code> if (bch->Data[x][y][0] >= 0) // voxel in top chunk is full, dont display\n {\n return false;\n }\n else\n {\n return true;\n }\n</code></pre>\n\n<p>As mentioned in the review by @G.Sliepen it is best to find a way to remove code that repeats itself.</p>\n\n<h2>Magic Numbers</h2>\n\n<p>There are Magic Numbers in the following code:</p>\n\n<pre><code>Application::Application(int windowWidth, int windowHeight)\n : MainCamera(60.0f, 4.0f / 3.0f, 0.1f, 1000.0f)\n{\n WindowWidth = windowWidth;\n WindowHeight = windowHeight;\n\n BackgroundColor = Color(0.25f, 0.5f, 1, 1);\n\n DeltaTime = 0;\n LastTime = 0;\n}\n</code></pre>\n\n<p>it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.</p>\n\n<pre><code>constexpr double Left = 60.0f; // This might be Top rather than left\n</code></pre>\n\n<p>I couldn't even guess at what the RGB values are for <code>Color()</code>.</p>\n\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T22:24:54.587",
"Id": "234763",
"ParentId": "234730",
"Score": "6"
}
},
{
"body": "<p>OpenGL is quickly losing relevance, and Apple is not going to be supporting it on their OSes. Prefer a low-level cross platform rendering engine or Vulkan/Metal/DirectX12.</p>\n\n<hr>\n\n<p>There's many ways to render this faster. The entire construction including noise generation can be done on the GPU and rendering voxels like this is extremely inefficient. Simply drawing a ton of instanced cubes that pull from an instance buffer with no face culling would probably be faster. </p>\n\n<p>Off the top of my head you could try this:</p>\n\n<ul>\n<li>Generate/examine the density volume in a compute shader</li>\n<li>Compact non-empty voxels on the GPU with a parallel reduction into a single ID buffer</li>\n<li>Map the dense list of voxels to a 0-6 faces depending on neighbors and camera position</li>\n<li>Compact the faces in another parallel reduction</li>\n<li>Render the resultant mesh with a single <code>drawIndexedIndirect</code> call, or maybe a few if you want more sophisticated culling or something.</li>\n</ul>\n\n<p>I would estimate being able to render a few million voxels at 60fps on a modern desktop GPU like this, depending on the volume density.</p>\n\n<hr>\n\n<p>Commented out code hurts readability</p>\n\n<hr>\n\n<p>Chunks should not know about rendering and definitely not hold shared pointers to shaders. They should be plain data and have a chunk renderer that owns shaders and uses things with a chunk interface. The only reason not to is if the chunks are going to all be heterogenous which would be bizarre and slow.</p>\n\n<hr>\n\n<p>Using <code>std::future</code>s <em>may</em> be preferrable to threads. I think they definitely would be if there were continuation support in C++, since that's what's functionally being expressed. Testing atomics is brittle and I have yet to see a valid use of them that isn't writing low-level library code. </p>\n\n<hr>\n\n<pre><code>MainCamera(60.0f, 4.0f / 3.0f, 0.1f, 1000.0f)\n</code></pre>\n\n<p>This is perfectly readable to me without seeing the camera class. Should probably be width/height instead of 4.0f/3.0f though. I think this is safe because understanding the domain specific semantics of a 3D camera is a reasonable expectation for understanding this code.</p>\n\n<p>Similarly</p>\n\n<pre><code>Color(0.25f, 0.5f, 1, 1);\n</code></pre>\n\n<p>is also reasonable to expect r, g, b, a values in floating point form. It would only be unreadable if this isn't actually what they represent. </p>\n\n<hr>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-07T00:45:48.170",
"Id": "235199",
"ParentId": "234730",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T12:20:14.173",
"Id": "234730",
"Score": "7",
"Tags": [
"c++",
"comparative-review",
"c++17",
"opengl"
],
"Title": "C++/Opengl voxel renderer"
}
|
234730
|
<p>I've wrote a Sudoku-Solver in Java, which also contains a GUI, so you can just enter the Sudoku, press "OK" and it will solve the Sudoku using backtracking.</p>
<p>Here's the code:</p>
<pre class="lang-java prettyprint-override"><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static javax.swing.WindowConstants.EXIT_ON_CLOSE;
public class SudokuSolver {
public static void main(String[] args) {
int[][] board = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
board = getSudoku(board);
boolean solve = solver(board);
if(solve) {
display(board);
}
else {
JOptionPane.showMessageDialog(null,"Not solvable.");
}
}
//Backtracking-Algorithm
public static boolean solver(int[][] board) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
for (int n = 1; n < 10; n++) {
if (checkRow(board, i, n) && checkColumn(board, j, n) && checkBox(board, i, j, n)) {
board[i][j] = n;
if (!solver(board)) {
board[i][j] = 0;
}
else {
return true;
}
}
}
return false;
}
}
}
return true;
}
public static boolean checkRow(int[][] board, int row, int n) {
for (int i = 0; i < 9; i++) {
if (board[row][i] == n) {
return false;
}
}
return true;
}
public static boolean checkColumn(int[][] board, int column, int n) {
for (int i = 0; i < 9; i++) {
if (board[i][column] == n) {
return false;
}
}
return true;
}
public static boolean checkBox(int[][] board, int row, int column, int n) {
row = row - row % 3;
column = column - column % 3;
for (int i = row; i < row + 3; i++) {
for (int j = column; j < column + 3; j++) {
if (board[i][j] == n) {
return false;
}
}
}
return true;
}
public static int[][] getSudoku(int[][] board) {
JFrame frame = new JFrame();
frame.setSize(800, 700);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JPanel subpanel1 = new JPanel();
subpanel1.setPreferredSize(new Dimension(500,500));
subpanel1.setLayout( new java.awt.GridLayout( 9, 9, 20, 20 ) );
JTextArea[][] text = new JTextArea[9][9];
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
text[i][j] = new JTextArea();
text[i][j].setText("0");
text[i][j].setEditable(true);
Font font = new Font("Verdana", Font.BOLD, 40);
text[i][j].setFont(font);
subpanel1.add(text[i][j]);
}
}
JPanel subpanel2 = new JPanel();
JButton button = new JButton("OK");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
String s = text[i][j].getText();
board[i][j] = Integer.valueOf(s);
helper(1);
}
}
}
});
subpanel2.add(button);
panel.add(subpanel1, BorderLayout.WEST);
panel.add(subpanel2, BorderLayout.EAST);
frame.add(panel);
frame.setVisible(true);
while(helper(0)) {
}
frame.dispose();
return board;
}
public static void display(int[][] board) {
JFrame frame = new JFrame();
frame.setSize(700,700);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout (9,9, 3 ,3));
JTextArea[][] text = new JTextArea[9][9];
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
text[i][j] = new JTextArea();
text[i][j].setText("" + board[i][j]);
text[i][j].setEditable(false);
Font font = new Font("Verdana", Font.BOLD, 40);
text[i][j].setFont(font);
panel.add(text[i][j]);
}
}
frame.add(panel);
frame.setVisible(true);
}
private static boolean test = true;
public static boolean helper(int x) {
if(x == 1) {
test = false;
}
System.out.print("");
return test;
}
}
</code></pre>
<p>Do you have any suggestions on how to improve the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T22:37:06.220",
"Id": "459266",
"Score": "0",
"body": "Follow-up question can be found at https://codereview.stackexchange.com/questions/234801/sudoku-solver-follow-up."
}
] |
[
{
"body": "<h1>Solver</h1>\n\n<p>Your back-tracking algorithm to find the solution to the puzzle is fine, although it is fairly inefficient.</p>\n\n<ul>\n<li>On each recursive call, the algorithm must search for the position of the next unknown, which means starting at <code>[0][0]</code> and searching over the same locations over and over on each call. You could improve it by creating an <code>ArrayList<></code> of unknown positions, and directly indexing to the unknown corresponding to the current search depth. Or you could pass the current board position <code>(i, j)</code> as a starting point for the next level of the search.</li>\n<li>You could use a <code>Set<></code>, such as a <code>BitSet</code>, to store the unused numbers in each row, column, and box. When processing each cell, you could \"and\" those sets together to create a much smaller set of candidate values to try.</li>\n</ul>\n\n<p>But these optimizations are only necessary if your solver algorithm isn't fast enough. I haven't tried it.</p>\n\n<p>An organizational improvement might be to move the Sudoku Solver code into its own class, so it could be used in other projects. For instance, you could make a JavaFX, or an SWT version of your program, and reuse the solver code ... if it was a stand-alone class.</p>\n\n<h1>GUI</h1>\n\n<p>Your GUI is where a lot of work is absolutely needed. This code is just plain awful.</p>\n\n<h2>Minor</h2>\n\n<p>Starting with the easiest to fix items:</p>\n\n<ul>\n<li><p>the <code>getSudoku()</code> method creates a <code>JFrame</code> and sets <code>EXIT_ON_CLOSE</code>, but the <code>display()</code> method creates a <code>JFrame</code> without <code>EXIT_ON_CLOSE</code>. If the user closes the second frame, the program will not immediately terminate.</p></li>\n<li><p><code>JTextArea</code> is a multiline text edit window. You are creating 81 of these in a 9x9 grid. Surely you wanted to use the much lighter weight <code>JTextField</code> ... or even the <code>JLabel</code> when displaying the solution.</p></li>\n<li><p>You create 81 identical <code>Font</code> objects, one for each <code>JTextArea</code>. You should create just one, and set the font of each <code>JTextArea</code> (or <code>JTextField</code>/<code>JLabel</code>) to this common <code>Font</code> object. Simply move the statement out of the double loop.</p></li>\n<li><p><code>public static int[][] getSudoku(int[][] board)</code> is this method allocating a new board and returning it, or is it just modifying the board it was given? Why have both an input parameter <code>board</code> and a return value, if the board that it is given is the board that is returned?</p></li>\n</ul>\n\n<p>But the most <strong>SERIOUS</strong> problem is you are creating and manipulating Swing GUI objects from threads other than the <strong><em>Event Dispatching Thread</em></strong> (EDT). Swing is <strong>NOT</strong> thread safe. It is a convenience, and a thorn, that Swing allows you to build the GUI on the main thread. Swing goes to great lengths to allow it ... once. After the realization of any Swing GUI object, or after any <code>Timer</code> is started, all interaction must be performed on the EDT, or unexplainable, hard-to-debug behaviour -- up to and including application crashes -- are possible. So up to this line, which realizes the GUI components:</p>\n\n<pre><code> frame.setVisible(true);\n</code></pre>\n\n<p>you are safe. However, it is followed by:</p>\n\n<pre><code> while(helper(0)) {\n\n }\n frame.dispose();\n</code></pre>\n\n<p>which is a recipe for disaster. It is bad that this is an empty spin loop on the main application thread, but <code>frame.dispose()</code> is the violation about touching live Swing objects from threads other than the EDT. Then, the code returns to the <code>main()</code> function where <code>display()</code> is called, and more Swing GUI items are created on not the EDT.</p>\n\n<h2>Working on the EDT</h2>\n\n<p>First, you should divorce yourself from the main thread, and create your GUI on the EDT:</p>\n\n<pre><code>public class SudokuSolver {\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n void run() {\n createGUI();\n }\n });\n }\n\n private static void createGUI() {\n /* Create JFrame, JPanel, etc here */\n frame.setVisible(true); \n }\n\n ...\n}\n</code></pre>\n\n<p>Or, if you are comfortable with lambdas and method references:</p>\n\n<pre><code>public class SudokuSolver {\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(SudokuSolver::createGUI);\n }\n\n private static void createGUI() {\n /* Create JFrame, JPanel, etc here */\n frame.setVisible(true); \n }\n\n ...\n}\n</code></pre>\n\n<p>The <code>invokeLater()</code> method takes a runnable, switches to the Event Dispatching Thread, and runs the runnable. So this create all GUI objects on the EDT. The final step is the frame is made visible. And then execution ends. Nothing else happens. The main thread has already reached the end of <code>main()</code> and has terminated; nothing else happens there, either. The application has become purely an event driven GUI application. It is now waiting for the user to interact with the GUI elements.</p>\n\n<h2>Working off the EDT</h2>\n\n<p>Once the user has entered their grid, the press the <code>\"OK\"</code> button, and the <code>actionPerformed</code> method is called.</p>\n\n<p>Note that this method called <code>helper(1)</code> a total of 81 times. At any point after this method was called once, and before it had been called the last time, the <code>board[][]</code> would have contained an incomplete starting point for the solution, but the main thread could start attempting to solve the grid, since the <code>test</code> flag would have been cleared! Just one more danger of multithreaded processing.</p>\n\n<p>Instead, after both loops in the <code>actionPerformed</code> method, a <a href=\"https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html\" rel=\"nofollow noreferrer\"><code>SwingWorker</code></a> should be created and given a copy of the <code>board</code>. This worker could solve the <code>board</code> in its background thread, and then in its <a href=\"https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html#done()\" rel=\"nofollow noreferrer\"><code>done()</code></a> method, which is run once again on the EDT, the solved board could be displayed in the GUI.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T20:38:58.323",
"Id": "459166",
"Score": "0",
"body": "First of all, thanks for your reply. Do you also have some concrete tips to improve the UI?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T22:32:37.007",
"Id": "459176",
"Score": "0",
"body": "I’m busy at the moment; I’ll update my answer later, if still necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T19:49:30.187",
"Id": "459261",
"Score": "0",
"body": "That would be great, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T22:35:38.543",
"Id": "459265",
"Score": "0",
"body": "I've just posted a follow-up question, which you can find at https://codereview.stackexchange.com/questions/234801/sudoku-solver-follow-up"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T23:01:22.720",
"Id": "459269",
"Score": "0",
"body": "Nice followup question; I'll post my UI improvements there."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T19:39:06.620",
"Id": "234754",
"ParentId": "234731",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "234754",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T12:32:52.203",
"Id": "234731",
"Score": "4",
"Tags": [
"java",
"swing",
"gui",
"sudoku"
],
"Title": "Sudoku-Solver with GUI in Java"
}
|
234731
|
<p>Hello there and beforehand a huge thank you to everybody for dedicating their time to help others.</p>
<p>This is my first post here, so I hope I comply to the guidelines. Maybe a bit background to myself: I do not have a formal education in computer science except for some basic introductory level courses at university. I have worked as a trainee in software development for a year until the whole team was dismissed due to management decisions. During that time, I mainly did some programming for the company's ERP system. As ERP development differs from "conventional" programming a lot, the few things I (think I) know are self taught, so they're pretty error-prone. Now I'm working at an insurance company in a non-IT-role, but thought of doing some programming finger exercises related to my new job resulting in a small class library for actuarial claims reserving with the chain-ladder method, others might be added as well. The whole repository can be found at <a href="https://github.com/jb262/ActuarialMaths.NonLife" rel="nofollow noreferrer">my github</a>.</p>
<p>Well, to my questions:</p>
<p><strong>Namespaces</strong>: Currently I have split the source files by topic, e.g. Exceptions, Reserving methods and the underlying model.</p>
<pre class="lang-cs prettyprint-override"><code>namespace ActuarialMaths.NonLife.ClaimsReserving.Model
namespace ActuarialMaths.NonLife.ClaimsReserving.Methods
namespace ActuarialMaths.NonLife.ClaimsReserving.Exceptions
</code></pre>
<p>While the split does make sense inside the project, to me the namespaces seem too granular for a library that would be used by another project. On the other hand, throwing the exceptions, the model and the methods into one single namespace, it might become too cluttered at some point. What would be the better solution in this situation?</p>
<p><strong>Data structures</strong>: I took some inspiration from the .NET stack implementation and modelled the run-off triangles, respectively the underlying paid claims with a jagged two-dimensional array, which has an initial capacity which is doubled when needed.</p>
<pre class="lang-cs prettyprint-override"><code>public abstract class Triangle
{
private const int initialCapacity = 8;
protected decimal[][] claims;
private int capacity;
protected Triangle(int periods)
{
capacity = initialCapacity;
while (capacity < periods)
{
capacity *= 2;
}
claims = new decimal[capacity][];
for (int i = 0; i < capacity; i++)
{
claims[i] = new decimal[capacity - i];
}
Periods = periods;
}
public virtual void AddClaims(IEnumerable<decimal> values)
{
Periods++;
if (capacity < values.Count())
{
capacity *= 2;
Array.Resize(ref claims, capacity);
for (int i = 0; i < capacity; i++)
{
Array.Resize(ref claims[i], capacity - i);
}
}
}
</code></pre>
<p>The idea was that first, the array is only there to store the values. No fancy overhead of e.g. a List is needed. The values just need to be set and retrieved by some indices, be it by row, column, both or diagonal.
On the other hand, modelling a triangle as a list of other lists which represent the diagonals would make basic operations on the triangle a lot easier such as simply setting/returning/adding a collection at a given index instead of fiddling around with for-/foreach-loops and incrementing/decrementing indices.
Is the current implementation a valid idea or does readability beat leaving out unneccessary overhead here?</p>
<p><strong>Interfaces</strong>: In the job mentioned above, I somehow developed the (bad?) habit of creating an interface for everything, so the initial version of my code had an additional interface on top:</p>
<pre class="lang-cs prettyprint-override"><code>public interface ITriangle : ISliceable<decimal>, ICloneable
{
int Periods { get; }
void AddClaims(IEnumerable<decimal> values);
}
</code></pre>
<p>The abstract class Triangle then implemented the interface ITriangle. Halfway through I realized that there is basically no other way of implementing a base run-off triangle in this specific domain and deleted the interface,
thus removing a layer of abstraction. While there is no inherent need for the reserving method to know how the triangle is implemented as long as it provides the neccessary methods and properties, is there really a need to <strong>always</strong> program against an interface when dealing with objects containing some logic, although there is no (at least obvious) possibility that it could be implemented in another way than already done?
The same goes for the "run-off square" where not even an abstract class would be needed.</p>
<p><strong>Naming of methods</strong>: While e.g. <code>GetColumn(int column)</code> and <code>SetColumn(IEnumerable<decimal> values, int column)</code> in the ISliceable interface need their leading adjectives to be able to tell anyone what they are doing, I left them out when naming the methods to retrieve calculated values when dealing with reserving methods, e.g. the method to retrieve the total reserve is called <code>TotalReserve()</code> instead of <code>GetTotalReserve()</code>. I thought that adding "Get"s in front of everything would clutter the code, but now, it somewhat seems to me that this somehow obfuscates what the methods are actually doing.
Are there supposed to be "clearer" names althought it's impossible to manually set these values and it should be clear that these methods are meant to retrieve the values?</p>
<p><strong>Placement of methods</strong>: While the <code>CalculateReserves()</code> and <code>CalculateCashflows()</code> methods actually make sense on the square since they only need the values stored inside a square, they make no sense at all when the claims/losses strored in the sqaure have not been developed from a triangle by a reserviong method. Again on the other hand, putting that inside a reserving method, even inside an abstract base class, would lead to code duplications when I added simulation based methods.
Is it better to place the method on the object "it's working on" or on the class that provides the logic that makes the meaningful execution of the method possible?</p>
<p><strong>Memoization</strong>: Inside the reserving methods, basically everything is memoized, e.g.:</p>
<pre class="lang-cs prettyprint-override"><code>public Square Projection()
{
if (projection == null)
{
projection = CalculateProjection();
}
return projection;
}
</code></pre>
<p>While this makes sense for more complicated stuff like the projection above, it seems a bit off to me for some calculations, e.g.</p>
<pre class="lang-cs prettyprint-override"><code>public IEnumerable<decimal> CalculateCashflows()
{
for (int i = 0; i < Periods - 1; i++)
{
int diagonal = Periods + i;
yield return GetDiagonal(diagonal)
.Take(Periods - 1 - i)
.Zip(GetDiagonal(diagonal - 1), (x, y) => x - y).Sum();
}
}
</code></pre>
<p>I'd say it would make sense if the column was long, but given the domain, it's rarely longer than 20 elements, making recalculating it every time it's needed not too expensive. So, is it sensible to store the calculated values inside a private class array instead of recalculating it?</p>
<p>Thanks in advance! If anyone wants to look at the entire code code and notices something off there as well, I'd really appreciate constructive criticism.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T13:27:23.680",
"Id": "459120",
"Score": "3",
"body": "Welcome to code review where we review working code and provide suggestions on how the code can be reviewed. While we really do appreciate information about the project to help with the review, anything you want reviewed must be posted in the question. Within the post, anything in code that implies that some of the code is hidden such as `...` will make the question off-topic because that implies that it is hypothetical code rather than real code. If the project is large you can post it in separate questions as long as the code in any one question supports itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T13:29:07.180",
"Id": "459121",
"Score": "2",
"body": "Code review guidelines can be found at https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T15:23:47.410",
"Id": "459327",
"Score": "1",
"body": "On top of the links provided by pacmaninbw, we have a very shiny [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915), which may help improve your (future) questions."
}
] |
[
{
"body": "<p>the namespace Models is fine, but methods and exceptions should not be in the namespaces. \nExceptions, should be handled for each class. So, if you moved all exceptions under one namespace <code>Exceptions</code>, this means <code>Exceptions</code> namespace will be referenced in all classes (entire project). So, it'll be better to avoid doing that. For the methods namespace, not sure what do you intent to use it for, but surely, rename it to something more specific will be better, for instance, if you meant <code>Methods</code> as extensions or helper methods, you could rename it to <code>Util</code> or <code>Utility</code> or anything meaningful.\nFor the beginning on the project, don't think too much about it as you'll have a better idea on what namespace should be there. </p>\n\n<p>For the abstract class, i don't have a full understand on the actual usage of it other than the provided logic, but converting it to <code>List<IEnumerable<decimal>></code> seems the right one for you. It will give you more advantages than the current 2D array. Firstly, it'll eliminate the need of the maintaining the capacity. Secondly, it will short things up and let's you focus on your actual logic on managing the data. So, if you convert it to list, and add the basic functionality to your abstract it should give you something like this : </p>\n\n<pre><code>public abstract class Triangle : IEnumerable<IEnumerable<decimal>>\n{\n private readonly List<IEnumerable<decimal>> claims = new List<IEnumerable<decimal>>();\n\n protected Triangle()\n {\n // since you're using List<IEnumerable<decimal>>, there is no need to maintain the capacity, unless if you need a fixed capacity\n }\n\n public IEnumerable<decimal> this[int index]\n {\n get => claims[index];\n set => claims[index] = value;\n }\n\n public int Count => claims.Count;\n\n\n public void Add(IEnumerable<decimal> values)\n {\n claims.Add(values);\n }\n\n public void Clear()\n {\n claims.Clear();\n }\n\n public bool Contains(IEnumerable<decimal> values)\n {\n return claims.Contains(values);\n }\n\n public void Insert(int index, IEnumerable<decimal> values)\n {\n claims.Insert(index, values);\n }\n\n public void Remove(int index)\n {\n claims.RemoveAt(index);\n }\n\n public int RemoveAll(Predicate<IEnumerable<decimal>> match)\n {\n return claims.RemoveAll(match);\n }\n\n public IEnumerator<IEnumerable<decimal>> GetEnumerator()\n {\n return claims.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return claims.GetEnumerator();\n }\n}\n</code></pre>\n\n<p>I've chosen to implement <code>IEnumerable<IEnumerable<decimal>></code> interface, to empower the class with the use of <code>foreach</code> loop and <code>Linq</code> extensions. </p>\n\n<p>However, you shouldn't remove your interface as implementing an interface is never a bad habit, actually, it's recommend to use interfaces on all classes that might be reused with other classes (concrete or abstract). For instance, if other developers wants to implement a class that would inherit <code>Triangle</code>, they either its interface, abstract, or concrete class. Sometime, the class needs to inherit multiple classes, and there is no straight forward way to inherit them all unless we use their interfaces. So, always keep an interface for your classes, and implement it on your classes as well. You should also keep the interface with the minimum required functionality. You can implement other interfaces in your class or implement them on your interface and then implement your interface on your class. Both options are valid options. </p>\n\n<p>For the naming convention, sometimes, you'll need to wrap functions under new naming convention to make it understandable and clearer for other developers as well. So, there is nothing wrong using <code>Get</code> or <code>Set</code> prefixes as naming convention, and it makes things more readable for most of the time, but sometimes the implementation would forces you to use a different naming convention based on the business logic requirement, in this case, you might want to keep the required naming public, and it it could have a callback to private setter and getter methods .. for instance, you can do something like this : </p>\n\n<pre><code>public abstract class Triangle\n{\n public IEnumerable<decimal> this[int index] \n {\n get => GetColumn(index);\n set => SetColumn(value, index);\n }\n\n public void Add(IEnumerable<decimal> values, int index)\n {\n SetColumn(IEnumerable<decimal> values, int index);\n }\n\n protected IEnumerable<decimal> GetColumn(int index) { ... }\n\n protected void SetColumn(IEnumerable<decimal> values, int index) { ... }\n}\n</code></pre>\n\n<p>then it can be used like : </p>\n\n<pre><code>var test = new Triangle(); \nvar column = new List<decimal> { 4.7m, 68.36m, 889.14m };\n\ntest[0] = column;\n// or \ntest.Add(column);\n</code></pre>\n\n<p>For the placement of the methods. If you see there is a method is off the class functionality (like CalculateReserves()), you can move it to another class that is linked to the current one (for instance, you can create a calculation class, as an extension class that would have all the calculations methods, and you can sort them out. (for instance, <code>test.Calculate().Cashflows().Sum()</code>). this API would be applied on all Triangle, Square, ..etc. So, yes it's possible and also doable. </p>\n\n<blockquote>\n <p>So, is it sensible to store the calculated values inside a private\n class array instead of recalculating it?</p>\n</blockquote>\n\n<p>Yes, and it's also possible to have a private property where it holds the total sum of the added values, so in your <code>Add()</code> method, you can add every new value in the private property <code>_total += value;</code> and retrieve it where you need it. This method would speed things up for the calculations part. If you have mutliple totals (say cashflow, expenses, ..etc. to sum, you might store them in a List or Array or A Dictionary. If these are few sums (say you have only 5 different types of sums to store) then use 5 variables (one for each) to avoid using extra collections. </p>\n\n<p>just use your good judgement on your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T14:27:05.357",
"Id": "459323",
"Score": "0",
"body": "Thank you very much for your helpful answer. I applied your suggestions considering the namespaces (Methods was meant to be something like ReservingMethods, so I changed it to that, I moved the Exceptions to the namespace they apply to) re-added the interfaces and implemented the Calculations-extension class. I does make more sense to move it to the ReservingMethods namespace, thank you. However, although I really liked your approach of letting Triangle implement IEnumerable, I couldn't think of a sensible implementation for the Remove-method considering the domain. I keep that in mind though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-30T15:01:00.960",
"Id": "459324",
"Score": "0",
"body": "@jb262 for the Remove method it's just a habit where I always provide the basic functions (add, edit, remove, search). You can remove whatever functionality that don't fit under your business requirement. However, considering this would be used by other developers as well, I would leave it for them as they might need it in their implementations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T05:15:58.880",
"Id": "234774",
"ParentId": "234733",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "234774",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T13:05:58.077",
"Id": "234733",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Actuarial claims reserving with the chain-ladder method"
}
|
234733
|
<p>I just started working on a little project to help me study for a course I'm taking. </p>
<p>Is there anything I can do to improve code readability / bad practices?</p>
<p>I had to remove most of the labels and buttons (due to stack-overflow posting rules) but I kept one of everything just so you can sus out how I programmed those features.</p>
<pre><code> import tkinter as tk
import pandas as pd
import datetime as datetime
import random
#Global Variables
labelH1 = ("Verdana", 20)
labelH2 = ("Verdana", 17)
labelParagraph = ("Verdana", 13)
labelButton = ("Verdana", 11)
########################################################################
class GUI:
""""""
def __init__(self, root):
"""Constructor"""
self.root = root # root is a passed Tk object
#Custom Window Height
#TODO! change to ratio
window_height = 700
window_width = 1000
#Get User Screen Info
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#Center GUI
x_cordinate = int((screen_width/2) - (window_width/2))
y_cordinate = int((screen_height/2) - (window_height/2))
#Set the Window's Position and dimensions
root.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
########################################################################
#LANDING PAGE
def mainMenu(self):
self.frame = tk.Frame(self.root)
self.frame.pack()
self.lastPage = "Main Menu"
#TEXT/LABELS
header = tk.Label(self.frame, text="Welcome to a quiz", font=labelH1 )
header.grid(row=0, column = 3, ipady =20)
SBJMath = tk.Label(self.frame, text="Math", font=labelH2 )
SBJMath.grid(row=1, column = 3)
#BUTTONS
#MATHS QUIZZES
BTN_BasicMath = tk.Button(self.frame, text="Primer Statistics", font=labelButton, command = lambda: self.quizInstructions("BasicMath"))
BTN_BasicMath.grid(row=2,column=2, pady=10)
#EXTRA BUTTONS
BTNQuit = tk.Button(self.frame, text="Quit", font=labelButton, command =root.destroy)
BTNQuit.grid(row=13, column=0)
########################################################################
#ABOUT QUIZ PAGE
def quizInstructions(self, quizName):
self.removethis()
self.lastPage = "Quiz About"
quizHeader = ""
quizAbout = ""
chooseQuiz = ""
if quizName == "BasicMath":
quizHeader = "Primer Statistics"
quizAbout = """big line"""
chooseQuiz = ""
self.frame = tk.Frame(self.root)
self.frame.pack()
tk.Label(self.frame, text=quizHeader, font=labelH1 ).grid(row=0, column=3, pady = 20)
tk.Label(self.frame, text=quizAbout, font=labelParagraph, wraplength=600,anchor="n" ).grid(row=1, column=3, pady = 30)
tk.Button(self.frame, text="Go Back", font=labelButton, command=self.returnToLastFrame).grid(row=2, column=3, sticky = tk.W)
tk.Button(self.frame, text="Start Quiz", font=labelButton, command=self.quiz ).grid(row=2, column=3, sticky = tk.E)
########################################################################
#QUIZ GUI
def quiz(self):
self.lastPage = "Quiz"
self.removethis()
self.frame = tk.Frame(self.root)
self.frame.pack()
self.quizLogic()
########################################################################
#QUIZ LOGIC
def quizLogic(self):
pass
def removethis(self):
self.frame.destroy()
#Go back
def returnToLastFrame(self):
self.removethis()
if self.lastPage == "Main Menu":
pass
if self.lastPage == "Quiz About":
self.mainMenu()
if self.lastPage == "Quiz":
self.quizInstructions()
else:
pass
#----------------------------------------------------------------------
if __name__ == "__main__":
root = tk.Tk()
window = GUI(root).mainMenu()
root.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>If talking about code readability, I'd recommend you to read PEP-8 at first, for example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def one():\n pass\ndef two():\n pass\n</code></pre>\n\n<p>This is how you <strong>don't want</strong> your code to look like. Instead, it should look like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def one(): # you can add hints for this function here\n pass\n\ndef two():\n '''\n or if it's documentation, you can leave it here\n '''\n pass\n</code></pre>\n\n<p>Also, it's better to have newlines between blocks of code and blocks of comments. Don't stack everything in one pile:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.root = root # root is a passed Tk object\n\n#Custom Window Height\n#TODO! change to ratio\n\nwindow_height = 700\nwindow_width = 1000\n\n#Get User Screen Info\nscreen_width = root.winfo_screenwidth()\nscreen_height = root.winfo_screenheight()\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T01:49:39.130",
"Id": "459187",
"Score": "0",
"body": "ill check out PEP-8 thanks for telling me about it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T17:34:31.900",
"Id": "234747",
"ParentId": "234734",
"Score": "4"
}
},
{
"body": "<p>1.\nInstead of:</p>\n\n<pre><code>def __init__(self, root):\n \"\"\"Constructor\"\"\"\n self.root = root # root is a passed Tk object\n</code></pre>\n\n<p>do:</p>\n\n<pre><code>def __init__(self, root: tkinter.Tk) -> None:\n self.root = root\n</code></pre>\n\n<p>Python 3 has built in support for type annotations, so there's no reason to use comments to say what the type of a variable is. If you use <code>mypy</code> (and if you're writing Python in the modern era <strong>you should be using mypy</strong>) type annotations will help you catch the majority of bugs before you even run your code. If there's only one thing you take away from this answer, it should be <strong>use type annotations and use mypy</strong>. That on its own will instantly start to push you into habits that will make your code easier to read and maintain.</p>\n\n<p>Any reader who knows Python will know that <code>__init__</code> is a constructor; no need for a docstring that just says <code>\"Constructor\"</code> (although you could have one that briefly summarizes what state the freshly constructed object is in if it's not adequately evident from skimming the code).</p>\n\n<ol start=\"2\">\n<li><p>As @finally said, add line breaks between your code blocks. Think of them like paragraphs; you don't mash all your sentences together into a single blob, you add paragraph breaks so that the reader can quickly see where one thought ends and another begins before they've parsed each individual sentence.</p></li>\n<li><p>All of your member variables should be declared (even if they aren't initialized) in your <code>__init__</code> function. But more importantly, variables that don't need to be member variables should not be declared as such. I'm looking particularly at <code>self.frame</code>, which is declared in your methods but not in your constructor -- but its value does not persist beyond any given method call as far as I can tell, so it shouldn't be <code>self.frame</code>, it should just be a local variable <code>frame</code>. You can just do a find+replace of <code>self.frame</code> to <code>frame</code> and I don't think it'd change the functioning of this code at all, but it frees the reader of having to read through every method to figure out how the <code>self.frame</code> set by one method call might impact another.</p></li>\n<li><p>For an example of a member variable that you can't convert to a local variable, <code>self.lastPage</code> is one that should be declared in the constructor. (Also, it should be snake_case rather than camelCase, since that's the Python convention for variable names.) If it doesn't have a useful default value, you can use None:</p></li>\n</ol>\n\n<pre><code> self.last_page: Optional[str] = None\n</code></pre>\n\n<ol start=\"5\">\n<li>If a string is only ever used internally to track changes in state, it's better to use an Enum, since it's impossible to mess those up via a typo, and there's a single source of truth that enumerates all of the possible values, so you don't have to hunt through all the places where it gets set to know what cases your code needs to handle. A <code>Page</code> class that enumerates all of the possible pages in your UI might look like:</li>\n</ol>\n\n<pre><code> from enum import auto, Enum\n\n class Page(Enum):\n NONE = auto()\n MAIN_MENU = auto()\n QUIZ = auto()\n QUIZ_ABOUT = auto()\n</code></pre>\n\n<p>(Note that to build this list I had to read through all of your code, and I'm not 100% positive that I didn't miss something -- this is the exact sort of annoyance that's avoided if you use an enum from the get-go!)</p>\n\n<p>Now in your constructor you can say:</p>\n\n<pre><code> self.last_page = Page.NONE\n</code></pre>\n\n<p>and in your other functions you can use <code>Page.MAIN_MENU</code>, etc. Your \"quiz name\" seems like it also might be a good candidate for conversion into a <code>Quiz(Enum)</code> that enumerates all of the possible quizzes.</p>\n\n<ol start=\"6\">\n<li><p>Break up long lines. Instead of:</p>\n\n<pre><code>tk.Label(self.frame, text=quizHeader, font=labelH1 ).grid(row=0, column=3, pady = 20)\ntk.Label(self.frame, text=quizAbout, font=labelParagraph, wraplength=600,anchor=\"n\" ).grid(row=1, column=3, pady = 30)\ntk.Button(self.frame, text=\"Go Back\", font=labelButton, command=self.returnToLastFrame).grid(row=2, column=3, sticky = tk.W)\ntk.Button(self.frame, text=\"Start Quiz\", font=labelButton, command=self.quiz ).grid(row=2, column=3, sticky = tk.E) \n</code></pre></li>\n</ol>\n\n<p>try:</p>\n\n<pre><code> tk.Label(\n self.frame, \n text=quizHeader, \n font=labelH1,\n ).grid(\n row=0, \n column=3, \n pady=20,\n )\n\n tk.Label(\n self.frame, \n text=quizAbout, \n font=labelParagraph, \n wraplength=600,\n anchor=\"n\",\n ).grid(\n row=1, \n column=3, \n pady=30,\n )\n\n tk.Button(\n self.frame, \n text=\"Go Back\", \n font=labelButton, \n command=self.returnToLastFrame,\n ).grid(\n row=2, \n column=3, \n sticky=tk.W,\n )\n\n tk.Button(\n self.frame, \n text=\"Start Quiz\", \n font=labelButton, \n command=self.quiz,\n ).grid(\n row=2, \n column=3, \n sticky=tk.E,\n ) \n</code></pre>\n\n<p>This does require more vertical scrolling to read, but now it's very easy to visually compare the parameters of each <code>Button</code> and <code>grid</code> call. Notice that I also made the whitespace consistent: no whitespace around the <code>=</code> in a keyword parameter call, and every function call in this block follows the same convention of one argument per line, with a trailing comma, so that the arguments are all lined up in neat columns and each has the same punctuation style.</p>\n\n<ol start=\"7\">\n<li>Look for opportunities to turn boilerplate code into utility functions. Taking the above example, if you end up having a lot of labels and buttons to create, put the complexity of setting up the Tk widgets into helper functions so that it's easier to read the code that actually defines the menu.</li>\n</ol>\n\n<p>Here's a quick attempt at rewriting the entire <code>quizInstructions</code> function in a way that would make it easier (I think) to add other quiz types and other widgets:</p>\n\n<pre><code>from enum import auto, Enum\nfrom typing import Callable\nimport tkinter as tk\n\nclass Page(Enum):\n NONE = auto()\n MAIN_MENU = auto()\n QUIZ = auto()\n QUIZ_ABOUT = auto()\n\nclass Quiz(Enum):\n BASIC_MATH = auto()\n\ndef _make_header(frame: tk.Frame, row: int, column: int, text: str) -> None:\n tk.Label(\n frame,\n text=text,\n font=labelH1,\n ).grid(\n row=row,\n column=column,\n pady=20,\n )\n\ndef _make_pgraph(frame: tk.Frame, row: int, column: int, text: str) -> None:\n tk.Label(\n frame,\n text=text,\n font=labelParagraph,\n wraplength=600,\n anchor=\"n\"),\n ).grid(\n row=row,\n column=column,\n pady=30,\n )\n\ndef _make_button(\n frame: tk.Frame,\n row: int, \n column: int, \n sticky: str,\n text: str, \n command: Callable[[], None], \n) -> None:\n tk.Button(\n frame, \n text=text, \n font=labelButton, \n command=command\n ).grid(\n row=row, \n column=column, \n sticky=sticky\n )\n\n\ndef quiz_instructions(self, quiz: Quiz) -> None:\n \"\"\"About Quiz page\"\"\"\n self.removethis()\n self.last_page = Page.QUIZ_ABOUT\n\n quiz_descriptions = {\n Quiz.BASIC_MATH: (\n \"Primer Statistics\", \n \"\"\"big line\"\"\"\n ),\n # Quiz.SOMETHING_ELSE: (\n # \"Something Else\", \n # \"\"\"another big line\"\"\"\n # ),\n # etc.\n }\n header, about = quiz_descriptions[quiz]\n\n frame = tk.Frame(self.root)\n frame.pack()\n\n _make_header(frame, 0, 3, header)\n _make_pgraph(frame, 1, 3, about)\n _make_button(frame, 2, 3, tk.W, \"Go Back\", self.returnToLastFrame)\n _make_button(frame, 2, 3, tk.E, \"Start Quiz\", self.quiz)\n\n</code></pre>\n\n<p>Note that I used a bit of artifice in my function definitions to make the calling code as easy to read as possible -- I anticipate that when I read the code that sets up a widget, I'm going to need to visualize where each widget is in the grid, so I deliberately set up <code>row</code> and <code>col</code> as the first arguments to make them easy to spot.</p>\n\n<p>I also changed the code that sets up the quiz descriptions from what was presumably going to grow into a long <code>if</code> chain into a single dict; this dict could easily be defined elsewhere and then imported or passed into this function if you wanted to, say, separate the definition of these strings from the layout code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T01:48:06.333",
"Id": "459186",
"Score": "0",
"body": "WOW! thank you so much. I have a question with point 6 though I'm going to have about 40 or so buttons and labels so if I use the convention that you have talked about I would end up with around 400ish lines. is that okay?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T02:16:58.410",
"Id": "459188",
"Score": "0",
"body": "If you have that much code in a single function it's a little problematic and scrunching complex statements onto single lines so it's technically fewer lines isn't the way to fix that (even if it'll trick some linters). :) My advice is still to break those complex statements up for readability, but when you have 40 buttons you might want to group them into separate functions -- presumably your menu is going to have visual groupings, so that'd be a logical way to split out the functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T02:20:13.600",
"Id": "459189",
"Score": "0",
"body": "I'd also look at whether it makes sense to put some of the common code into utility functions -- anything that you find yourself copying and pasting is a good candidate. I'll add a simple example to this answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T02:52:59.473",
"Id": "459191",
"Score": "0",
"body": "I have decided to start over, reusing some functionality. I will have a base class (GUI) all menus will inherit from the class GUI. I'm trying to figure out how to cut down on the use of buttons and labels because that's where most of the readability issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T03:05:35.293",
"Id": "459194",
"Score": "0",
"body": "Check out the edit I just submitted; I think identifying your common usage patterns and then turning those into functions will make it a lot easier to define more complex menus in a more concise way."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T20:28:15.617",
"Id": "234756",
"ParentId": "234734",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-28T13:09:46.500",
"Id": "234734",
"Score": "9",
"Tags": [
"python",
"tkinter",
"quiz",
"user-interface"
],
"Title": "GUI for a quiz tool or game"
}
|
234734
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.