body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have a list of files that conform to a template like this:</p>
<pre><code>XXX_{project}_{variation}---XXX.html
</code></pre>
<p>and</p>
<pre><code>XXX_{project}_{variation}.html
</code></pre>
<p>The <code>variation</code> is not always present, so there are also files like this: <code>XXX_{project}---XXX.html</code> and <code>XXX_{project}.html</code></p>
<p>What I want to do is to check if all these files have the same <code>project</code> and <code>variation</code> then return <code>{project}_{variation}</code>, if not, then to check if they all have the same <code>project</code> and return <code>{project}</code> else return <code>"Mixed"</code>.</p>
<p>I have the following code, which works, but it looks too long:</p>
<pre><code>let mixed = [
"V50_A_X---100.html",
"V20_A_X---101.html",
"V50_B_X---102.html",
"V50_A_Y---103.html",
"V20_B---104.html",
"V50_A_X.html",
]
let sameProject = [
"V50_A_X---100.html",
"V20_A_X---101.html",
"V50_A_Y---102.html",
"V50_A_Y---103.html",
"V20_A---104.html",
"V50_A_X.html",
]
let sameProjectAndVariation = [
"V50_A_X---100.html",
"V20_A_X---101.html",
"V50_A_X---102.html",
"V50_A_X---103.html",
"V50_A_X.html",
]
const getPackageName = function(files) {
files = files.map(f => f.replace('.html', '').split('---')[0]);
let filesProjectAndVariation = files.map((file) => {
return {
project: file.split('_')[1],
variation: file.split('_')[2] || '',
}
})
let packageName = null;
let projectAndVariationAreSame = filesProjectAndVariation.every( (val, i, arr) => JSON.stringify(val) === JSON.stringify(arr[0]) );
if (projectAndVariationAreSame) {
packageName = filesProjectAndVariation[0].project + "_" + filesProjectAndVariation[0].variation
} else {
let projectAreSame = filesProjectAndVariation.every( (val, i, arr) => val.project === arr[0].project );
if (projectAreSame) {
packageName = filesProjectAndVariation[0].project;
} else {
packageName = "MIXED";
}
}
return packageName;
}
getPackageName(mixed)
getPackageName(sameProject)
getPackageName(sameProjectAndVariation)
</code></pre>
|
[] |
[
{
"body": "<p>Personally I don't think it's too long. It was fairly easy to read, especially with the good names.</p>\n<p>Here's a few things that could improve it:</p>\n<ul>\n<li>Use early returns instead of nested if's. This makes it even easier to read. Also, you don't need the packageName variable</li>\n<li>Use const instead of let. That way I don't have to wonder if the variable will be mutated later on.</li>\n<li>Handle the case where the array of files is empty</li>\n<li>If none of the files have a variation you will have an empty variation. E.g. A_</li>\n</ul>\n<p>Here's my attempt:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const getPackageName = (files) => {\n files = files.map(f => f.replace('.html', '').split('---')[0])\n\n const fileInfos = files.map(file => ({\n project: file.split('_')[1],\n variation: file.split('_')[2],\n }))\n const projects = [...new Set(fileInfos.map(f => f.project))]\n const variations = [...new Set(fileInfos.map(f => f.variation).filter(v => !!v))]\n\n if (projects.length === 1 && variations.length === 1) {\n return projects[0] + '_' + variations[0]\n }\n if (projects.length === 1) {\n return projects[0]\n }\n return 'MIXED'\n}\n</code></pre>\n<p>Changed it to check projects and variations separately, which resulted in a little bit less code (or actually just simpler models), and a bit easier to handle the edge cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T09:23:32.067",
"Id": "520097",
"Score": "0",
"body": "Thanks a lot for your review"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T19:19:56.710",
"Id": "263424",
"ParentId": "263406",
"Score": "2"
}
},
{
"body": "<p>Just some smaller remarks:</p>\n<p>Personally I don't like declaring "top level" functions using a function expression (or arrow expressions). I prefer normal function declarations for two reasons: It makes them optically distinct from "normal" variable declarations and hoists the function allowing it to be used before the declaration.</p>\n<p><code>file.split('_')</code> shouldn't be repeated.</p>\n<p>Using <code>JOSN.stringify</code> to compare objects leaves a bad taste and may even be dangerous. Historically neither JS(*) nor JSON properties have an defined order, so there is no guaranty that the JSON representations two objects (or for the matter of the fact two different JSON representations of one object) will have the same order of properties.</p>\n<p>(*) This has changed for JS, but not for JSON.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T15:23:45.727",
"Id": "263457",
"ParentId": "263406",
"Score": "0"
}
},
{
"body": "<ul>\n<li><p>You are iterating over the <code>files</code> (or same length) array at least three times, when one time would suffice.</p>\n</li>\n<li><p>You can avoid a lot of clutter with destructuring assignments.</p>\n</li>\n<li><p>The <code>JSON.stringify</code>’s are superfluous and expensive (as already mentioned).</p>\n</li>\n<li><p>A <code>RegExp</code> could fit better for splitting.</p>\n</li>\n</ul>\n<p>Below is some code illustrating the above points:</p>\n<pre><code>const separator = /[_.]|-{3}/\n\nconst sameName = (acc, fileName) => {\n const [_, project, variation] = fileName.split(separator)\n const [prevProject, prevVariation] = acc.split(separator)\n\n return (variation == prevVariation && project == prevProject)\n ? `${project}_${variation}`\n : project == prevProject\n ? project\n : "Mixed"\n}\n\nconst getPackageName = ([first, ...rest]) =>\n rest.reduce(sameName, first.split(separator).slice(1, 3).join('_'))\n</code></pre>\n<p>(Using a <code>for</code> loop would be able to return earlier.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-15T10:18:32.997",
"Id": "521518",
"Score": "1",
"body": "Just fyi: This breaks when files is an empty array. The variation can end up as \"html\" if you lack a real variation. The prevProject will be \"Mixed\" in case you had a mixed acc. Both project and variation will be set to undefined in multiple cases. What happens if a real project is called \"Mixed\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-16T08:04:43.270",
"Id": "521605",
"Score": "0",
"body": "@MagnusJeffsTovslid good point on empty array, thanks. Since the end result of the function is one of three strings, I wanted to highlight that (so it doesn't matter what part ends up as what, as long as they're different/same from each other). If a project is called \"Mixed\", it would be indistinguishable by definition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-16T08:11:42.943",
"Id": "521606",
"Score": "0",
"body": "@MagnusJeffsTovslid the project doesn't get set as undefined on any of the given example cases."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T05:35:15.120",
"Id": "263854",
"ParentId": "263406",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "263424",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T12:52:09.613",
"Id": "263406",
"Score": "2",
"Tags": [
"javascript",
"strings"
],
"Title": "Check if array of strings have the same substring"
}
|
263406
|
<p>I have some code I've written which I need a review of (if possible) as I know I have a bug somewhere. Most likely due to my (lack) of understanding of some concepts in ElasticSearch and Spring.</p>
<p>For context:
I have a simple Spring boot API which allows students to add their college projects. These projects are stored in ES which I'm trying to make searchable.</p>
<p>FWIW, From a use case POV, a user can search for a project with a query string which is based on a projectName or a hashtag for the project i.e. "Java".</p>
<p>Right now with the code below, if I search for projects which have a given hashtag I can retrieve them no problem. I get exactly the results I'm looking for.</p>
<p>However...once I try to add a second query whereby I want to limit the results to only students who have a userId contained in a ArrayList my search fails. By Fails I mean it returns everything from the index.</p>
<pre><code>private Iterable<UserProjects> searchCollegeProjects(Integer page, Integer size, List<String> hashtags, List<String> studentUserIds) {
PageRequest pageRequest = PageRequest.of(page, size);
QueryBuilder projectQueryBuilder = null;
if (hashtags != null) {
projectQueryBuilder =
QueryBuilders
.multiMatchQuery(hashtags.toString(), "projectName", "projectHashtag")
.fuzziness(Fuzziness.AUTO);
}
BoolQueryBuilder userIdQueryBuilder = null;
if(studentUserIds!=null) {
userIdQueryBuilder = QueryBuilders.boolQuery()
.must(QueryBuilders.termsQuery("userId.keyword", studentUserIds));
}
Query searchQuery = new NativeSearchQueryBuilder()
.withQuery(projectQueryBuilder)
.withQuery(userIdQueryBuilder)
.withFilter(boolQuery()
.mustNot(QueryBuilders.termsQuery("isDraft", true)))
.withPageable(PageRequest.of(page, size))
.build();
SearchHits<UserProjects> projectHits;
try {
projectHits =
elasticsearchOperations
.search(searchQuery, UserProjects.class,
IndexCoordinates.of(elasticProjectsIndex));
} catch (Exception ex) {
logger.error("Error unable to perform search query" + ex);
throw new GeneralSearchException(ex.toString());
}
List<UserProjects> projectMatches = new ArrayList<>();
projectHits.forEach(srchHit -> {
projectMatches.add(srchHit.getContent());
});
long totalCount = projectHits.getTotalHits();
Page<UserProjects> resultPage = PageableExecutionUtils.getPage(
projectMatches,
pageRequest,
() -> totalCount);
return resultPage;
}
</code></pre>
<p>Also below is my POJO for UserProjects:</p>
<pre><code>@Getter
@Setter
@Document(indexName = "college.userprojects")
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserProjects {
@Id
@Field(type = FieldType.Auto, name ="_id")
private String projectId;
@Field(type = FieldType.Text, name = "userId")
private String userId;
@Field(type = FieldType.Text, analyzer = "autocomplete_index", searchAnalyzer = "lowercase" ,name = "projectName")
private String projectName;
@Field(type = FieldType.Auto, name = "projectHashTag")
private List<String> projectHashTag;
@Field(type = FieldType.Boolean, name = "isDraft")
private Boolean isDraft;
}
</code></pre>
<p>EDIT: Just to be clear, if I remove this line from the native query:</p>
<pre><code> .withQuery(userIdQueryBuilder)
</code></pre>
<p>I get back projects (Correctly) which contain the query text in either their projectName or projectHashtag fields. Putting the above line back in will cause the search to return everything.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T14:08:11.777",
"Id": "263410",
"Score": "1",
"Tags": [
"java",
"spring",
"elasticsearch"
],
"Title": "Spring Boot Elastic Seemingly ignoring second Query"
}
|
263410
|
<p>I share an algorithm that I have written myself. It is useful for incrementing any digit of a decimal number. That way, a conversion to decimal is not necessary.</p>
<p>Please excuse the mistakes. I am learning assembler and x86 architecture. I am sure that it is possible to improve and optimize it (thank you). This code obviously uses recursion. But it doesn't go through the unnecessary digits. Following the advice of <a href="https://stackoverflow.com/a/61481672/11688616">Peter Cordes</a>. I think the algorithm is very readable thanks to the labels. It is written using the NASM syntax. Tested on Intel i3 x86-64 CPU and Linux operating system.</p>
<pre><code>section .data
number db "////////////////////////////////////////////////////////////////";For 64-digits integers
countN dd 0
section .bss
index resb 1
section .text
global CMAIN
INCREMENT:
;xor rax, rax
;mov eax, [index]
cmp byte[number+eax], "9"
jz EQUAL
jmp checkNEWdigit
EQUAL:
mov byte[number +eax],"0"
dec eax
jmp INCREMENT
NEWdigit:
mov byte[number + eax],"1"
inc byte[countN]
jmp FINISH
checkNEWdigit:
cmp byte[number + eax],"/" ;check if the position is empty
jz NEWdigit
inc byte[number+eax]
FINISH:
ret
CMAIN:
;Set the number to be increased- For example:
mov byte[number+59],"9"; Ten thousands
mov byte[number+60],"9"; Thousands
mov byte[number+61],"9"; Hundreds
mov byte[number+62],"9"; Tens
mov byte[number+63],"9"; Ones
;Until 64 digits
mov byte[countN],5 ;Set the number of digits that the number has at the beginning.
mov [index],byte 63 ;Set the position to be increased(63-ones;62-Tens;61-Hundreds..etc..),
xor rax, rax
mov eax, [index];the use of the variable "index" is for readability only.
call INCREMENT
;the next instructions are needed to calculate the position to be printed
mov rbx, 64 ;total of digits
sub rbx, [countN] ;sub number of digits used
add rbx,number;add the base
;print
xor rax,rax
mov rax, 1
mov rdi, 1
mov rsi, rbx
mov rdx, [countN]
syscall
;exit
mov rax,60
mov rdi, 2
syscall
</code></pre>
|
[] |
[
{
"body": "\n<blockquote>\n<p>This code obviously uses recursion.</p>\n</blockquote>\n<p>That's not the case. For recursion your <em>INCREMENT</em> routine would have to <code>call</code> itself which it doesn't. The <em>INCREMENT</em> subroutine simply iterates over the characters in the text.</p>\n<p>You're right that there is room for improvement. I'll share these observations with you.</p>\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>xor rax,rax\nmov rax, 1\n</code></pre>\n</blockquote>\n<p>It's not useful to clear <code>RAX</code> right before loading it with a value that is going to overwrite the whole qword anyway.<br />\nWriting to the low dword of a 64-bit register will automatically zero out the high dword.</p>\n<p>The above code simply becomes <code>mov eax, 1</code>. You can apply this several times using different registers.</p>\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mov byte[countN],5\nsub rbx, [countN]\nmov rdx, [countN]\nmov eax, [index]\n</code></pre>\n</blockquote>\n<p>You have defined <em>countN</em> as a <strong>dword</strong> variable but the program is using it both as a <strong>byte</strong> and as a <strong>qword</strong>!<br />\nYou have reserved a single <strong>byte</strong> for the <em>index</em> variable but your program is also using it as a <strong>dword</strong>!<br />\nAlways use your variables for what size they really have. Don't count on the fact that your <em>index</em> variable happens to be the last item in the .BSS and that your program worked well because of this.</p>\n<hr />\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mov byte[number+59],"9"; Ten thousands\nmov byte[number+60],"9"; Thousands\nmov byte[number+61],"9"; Hundreds\nmov byte[number+62],"9"; Tens\nmov byte[number+63],"9"; Ones\n</code></pre>\n</blockquote>\n<p>You can initialize the integer number "99999" using fewer instructions:</p>\n<pre class=\"lang-none prettyprint-override\"><code>mov rax, "///99999" (*)\nmov [number+56], rax\n</code></pre>\n<p>(*) The x86-64 architecture only allows 64-bit immediates on register loads. See <a href=\"https://stackoverflow.com/questions/62771323/why-we-cant-move-a-64-bit-immediate-value-to-memory/62772299?r=SearchResults&s=10%7C36.9102#62772299\">this SO answer</a> for more info.</p>\n<hr />\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>mov rbx, 64 ;total of digits\nsub rbx, [countN] ;sub number of digits used \nadd rbx,number;add the base \n</code></pre>\n</blockquote>\n<p>Calculating the address where the number starts only needs these 2 instructions, and because you need this in <code>RSI</code>, why not calculate it in <code>RSI</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>lea esi, [number+64]\nsub esi, [countN]\n</code></pre>\n<hr />\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code> jz EQUAL\n jmp checkNEWdigit\nEQUAL:\n</code></pre>\n</blockquote>\n<p>Code like this should use the opposite condition and shave off the extra jump:</p>\n<pre class=\"lang-none prettyprint-override\"><code> jnz checkNEWdigit\nEQUAL:\n</code></pre>\n<hr />\n<blockquote>\n<p>I think the algorithm is very readable thanks to the labels.</p>\n</blockquote>\n<p>You're right that it is readable, but then again it is also some kind of spaghetti code with all that jumping around!</p>\n<p>If you can accept using another character like "<strong>:</strong>" for the non-occupied positions, then your <em>INCREMENT</em> subroutine would only need 1 comparison instead of the current 2.\nThe trick is to choose a character that is above the character "9" in the ASCII set.<br />\nBelow is my rewrite that reduces the number of instructions that are needed:</p>\n<pre class=\"lang-none prettyprint-override\"><code>INCREMENT:\n cmp byte [number+rax], "9" ; "0123456789:"\n jb .Increment\n mov byte [number+rax], "0"\n ja .NewDigit\n dec eax\n jmp INCREMENT\n.NewDigit:\n inc dword [countN]\n.Increment:\n inc byte [number+rax]\n ret\n</code></pre>\n<p>Please notice that creating a new digit happens in 2 steps: first "0" is written over the ":" and then that zero is incremented. Because creating a new digit happens rarely, this can't possibly make the code any worse. It does however produce clean code.</p>\n<p>You've done well to not include code that checks for an overflow after the 64th digit. Who would still be around to see that happen?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T10:42:40.020",
"Id": "520212",
"Score": "0",
"body": "Thank you. I will apply the changes. I thought I could name recursion. I only use the basic instructions because I have a lot to learn.Thank you very much also for this \":\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T11:41:53.423",
"Id": "520220",
"Score": "0",
"body": "I have needed to use this to get it to work, `mov rax, \":::19999\" mov qword [number+56],rax` To what is due? Is it better to use this to maintain 32bit compatibility? `mov eax, \":::9\" mov dword [number+56],eax mov eax, \"9999\" mov dword [number+60],eax` –"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T11:59:49.933",
"Id": "520222",
"Score": "0",
"body": "By the way, now I'm using 32-bit registers, and initialized _countN_ with **dd**. and reserving _index_ with **resd**. It is right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T12:13:31.210",
"Id": "520225",
"Score": "0",
"body": "Thanks, a much better code has been left. I have verified that everything works. Instead of modifying it in the question. I have marked your answer as valid so that the improvements can be appreciated. I didn't know how to nest labels. The basis of the OOP resides in this anination mechanism?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T15:54:53.480",
"Id": "520234",
"Score": "0",
"body": "@FER31 Sorry you had to change `mov qword [number+56], \"///99999\"` . It was my mistake. It had slipped my mind that x86-64 can only use 64-bit immediates on register loads and not eg. on moves to memory. And about using 4 `EAX` instructions vs 2 `RAX` instructions, I would choose `RAX` in this case. Also using `resd` is correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T19:15:30.163",
"Id": "520413",
"Score": "3",
"body": "@Sep: *Writing to the low dword of a 64-bit register will automatically zero out the high dword if the value is at most 2GB-1.* - You seem to be mixing up two things. Writing the low 32 bits, like `mov eax, -1`, will *always* zero-extend and clear the high bits of RAX, allowing 64-bit values of 0..4G-1. [Why do x86-64 instructions on 32-bit registers zero the upper part of the full 64-bit register?](https://stackoverflow.com/q/11177137). Writing the whole 64-bit register with a value between 0 and 2^31-1 will zero the high half. So NASM can optimize `mov rax, 1` into `mov eax, 1` for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T21:16:08.757",
"Id": "520423",
"Score": "0",
"body": "@PeterCordes Thank you for noticing my mistake. It shows I'm not an x86-64 guru, although the 1st revision had it right in this respect :-)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T21:23:32.600",
"Id": "520424",
"Score": "1",
"body": "Also, `[number+eax]` should be `[number+rax]`. When you know EAX is already zero-extended into RAX, there's no advantage to override the addressing to 32-bit instead of the default 64-bit. (@FER31). Although I probably would have used a pointer, instead of hard-coding the address of static storage into the increment function, not least because then it's usable in a PIE executable or on MacOS, not dependent on `number`'s absolute address fitting into a sign-extended disp32."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T11:11:50.173",
"Id": "520474",
"Score": "0",
"body": "@PeterCordes Are you referring to a pointer to `[number]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T15:55:27.760",
"Id": "520503",
"Score": "0",
"body": "@FER31: Yeah, you could have the caller use `lea`, and pass a pointer to the least-significant digit. And pass `countN` in a register, to be returned in EAX. So the same program could use this function for two different counters easily if it wanted to."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T22:34:16.193",
"Id": "263499",
"ParentId": "263411",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263499",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T14:23:18.200",
"Id": "263411",
"Score": "6",
"Tags": [
"algorithm",
"converting",
"assembly",
"x86",
"nasm"
],
"Title": "Assembler. Algorithm for incrementing a decimal number"
}
|
263411
|
<p>This is only one of the first apps I've built with Node, React and TypeScript. I was wondering what could be made better. This is at this point the best I've been able to come up with, but I'm not sure if there's code here that could be difficult for another developer to read, could be improved, or anything else really. Or even stuff that could be added to this app.</p>
<p>I'd appreciate any kind of feedback on the entirety of my code.</p>
<p><em>Backend</em></p>
<p>app.ts</p>
<pre><code>import { mySqlConnect } from "./utils/mySqlConnect"
const NUM_GAMES = 50
const app = express()
app.use(cors())
const db = mysql.createConnection(mySqlConnect)
db.connect(function (err) {
if (err) {
console.error("failed connection:" + err.stack)
return
}
console.log("Connected.")
})
app.get("/api/games", (req, res) => {
const teamId = req.query.team_id
const offset = req.query.offset
let sql = ` SELECT * FROM games
WHERE team = '${teamId}'
ORDER BY date DESC
LIMIT ${NUM_GAMES} OFFSET ${offset}
`
db.query(sql, (err, results) => {
if (err) throw err
const response = results.map((game: { payload: string }) => JSON.parse(game.payload))
res.send(response)
})
})
</code></pre>
<p>mySqlConnect.ts</p>
<pre><code>import * as dotenv from "dotenv"
dotenv.config()
const config = {
host: process.env.HOSTNAME,
user: process.env.USERNAME,
password: process.env.PASSWORD,
port: process.envPORT,
database: process.env.DB_NAME,
}
type RemoveUndefinedFields<T> = {
[P in keyof T]: Exclude<T[P], undefined>
}
export const mysqlConnect = config as RemoveUndefinedFields<typeof config>
</code></pre>
<p><em>Frontend</em></p>
<p>App.js</p>
<pre><code>const App = () => {
return (
<div>
<GlobalStyle />
<NavBar />
<Games />
</div>
)
}
</code></pre>
<p>Games.tsx</p>
<pre><code>const OFFSET_GAMES = 10
const TEAM_ID = "team_id_here"
const Games = () => {
const [games, setGames] = useState<Game[]>([])
const [numFetches, setNumFetches] = useState(OFFSET_GAMES)
const [isLoading, setIsLoading] = useState(false)
useEffect(() => {
setIsLoading(prev => !prev)
fetch(`https://localhost:3402/api/games/?team_id=${TEAM_ID}&offset=${numFetches}`)
.then((res) => res.json())
.then((res) => {
setGames((prevGames) => [...prevGames, ...res])
setIsLoading(prev => !prev)
})
}, [numFetches])
const fetchGames = () => setNumFetches((prev) => prev + OFFSET_GAMES)
const displayGames = () => {
const datesShown: string[] = []
return games.map(game => {
const date = parseDate(game.date)
let showDate = true
if (datesShown.includes(date)) {
showDate = false
} else {
datesShown.push(date)
}
return (
<>
{showDate && <Date date={date}/>}
<Game
id={game.id}
game_type={game.game_type}
date={game.date}
observations={game.observations}
/>
</>
)
})
}
return (
<div>
{games.length ? (
<GamesContainer>
{displayGames()}
<Button
text="Load more games"
onClick={fetchGames}
isLoading={isLoading}
/>
</GamesContainer>
) : null}
{(!games.length || isLoading) && <Loader text={"Loading games..."} />}
</div>
)
}
</code></pre>
<p>GameCard.tsx</p>
<pre><code>export type Game = {
id: string
game_type: string
date: string
observations?: string[] | undefined
}
const GameCard: React.FC<Game> = ({
id,
game_type,
date,
observations,
}) => {
const gameMap = new Map(Object.entries(gameDictionary))
return (
<GameCardContainer key={id}>
<h3>{parseDate(date)}</h3>
<h4>{gameMap.get(game_type)}</h4>
{observations?.map((obs) => (
<h5>{obs}</h5>
))}
</GameCardContainer>
)
}
</code></pre>
<p>gameDictionary.ts</p>
<pre><code>export const gameDictionary = {
football: "Football match, the derby!",
basketball: "Basketball game. Looking for MJ?",
tennis: "Nadal X Federer? Tennis match!",
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T18:12:39.370",
"Id": "520176",
"Score": "0",
"body": "What do you want to achieve? Do you want to improve the code somehow? Consider adding a paragraph explaining what you tried, and specifying what you would like to improve or fix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T22:03:06.750",
"Id": "520201",
"Score": "0",
"body": "I have done that. hope it helps. It really is the case that this is one of the few apps I've built with Node, TypeScript or React, and I wanted to make sure I'm following best practices, there isn't anything that stinks... etc."
}
] |
[
{
"body": "<h2>general</h2>\n<h3>a</h3>\n<p>You want to use <code>typescript</code> this is a good practice to use type for your function or const or state.</p>\n<p>Example :</p>\n<pre><code>function something (a: string, b: boolean): void {\n // ....\n}\n\nconst something: void = (a: string, b: boolean) => {\n // ....\n}\n\nconst a: number = 0;\n\nconst [a, setA] = useState<boolean>(false);\n</code></pre>\n<h3>b</h3>\n<p>This is a good practice too to have some comment on your code. A simply way to add it (in my opinion) is the <a href=\"https://jsdoc.app/about-getting-started.html\" rel=\"nofollow noreferrer\">jsdoc</a>.</p>\n<h3>c</h3>\n<p>I don't know if you have this kind of stuff but if you want to have a quality standard on your code read about <a href=\"https://eslint.org/\" rel=\"nofollow noreferrer\">eslint</a> (<a href=\"https://github.com/palantir/tslint/issues/4534\" rel=\"nofollow noreferrer\">now eslint handle the tslint</a>).</p>\n<h2>api</h2>\n<h3>a</h3>\n<blockquote>\n<p>console.log</p>\n</blockquote>\n<p>My opinion</p>\n<ul>\n<li>use a logger instead of the console.log command like <a href=\"https://getpino.io/#/\" rel=\"nofollow noreferrer\">pino</a>, the advantage of that is to have a production ready logger.</li>\n</ul>\n<p>For example :</p>\n<ul>\n<li>when the NODE_ENV is set to production the log is writen on a single line</li>\n<li>this kind of stuff provide multiple level of log, this is useful because you have the ability to set different log for different environment, in dev you set the level to debug, in prod to error and so on.</li>\n</ul>\n<h3>b</h3>\n<blockquote>\n<p><code>if (err) throw err</code></p>\n</blockquote>\n<p>My opinion :</p>\n<p>this is a bad practice to throw the db error from the api, if some user want to use your api for bad reason this <em>log</em> possibly tell us some useful information about your database or data model</p>\n<ul>\n<li>throw custom error if the <code>teamId</code> doesn't exist (like http 404)</li>\n<li>if db error throw custom error too (maybe http 500)</li>\n</ul>\n<h3>c</h3>\n<blockquote>\n<p><code>port: process.envPORT</code></p>\n</blockquote>\n<p>replace by <code>port: process.env.PORT</code></p>\n<h3>d</h3>\n<p>This is purely personal ^^ but I don't see the value of putting <code>/api</code> into your url. In general we put this on the url via a sub domain name (for example app is todo.io and api api.todo.io)</p>\n<h2>app</h2>\n<h3>a</h3>\n<blockquote>\n<p><code>GlobalStyle</code></p>\n</blockquote>\n<p>What contain this file ?</p>\n<h3>b</h3>\n<blockquote>\n<p><code>https://localhost:3402</code></p>\n</blockquote>\n<p>put this kind of information into a <code>.env</code> file is more powerful if you want to have more than one environment (dev, staging, prod for example)</p>\n<p>and this will save you a lot of time if the url or the port change (this is a pain to refactor 100 fetch not to refactor one .env file :) )</p>\n<h3>c</h3>\n<blockquote>\n<p><code>setIsLoading(prev => !prev)</code></p>\n</blockquote>\n<p>My opinion :</p>\n<p>In general you know when you want the loading is true or false. I think this is more <em>strong</em> to have directly the right value into the <code>set</code> function (example: setIsLoading(false)). In some case, when the code failed or do not what you want to do, the <code>!boolean</code> can put the wrong value</p>\n<h3>d</h3>\n<blockquote>\n<p><code><></></code></p>\n</blockquote>\n<p>My opinion :\nPersonally I prefer to use <code><Fragment></Fragment></code>, this do the same thing but I find it more readable</p>\n<p><strong>but</strong> in the most of the case a <code>div</code> handle this kind of stuff too.</p>\n<p><a href=\"https://reactjs.org/docs/fragments.html\" rel=\"nofollow noreferrer\">More info here.</a></p>\n<h3>e</h3>\n<blockquote>\n<p><code>{games.length ? </code></p>\n</blockquote>\n<p>I think you don't need to have a ternary here, a <code>games.length &&</code> is sufficient.</p>\n<h3>f</h3>\n<blockquote>\n<p><code>{observations?</code></p>\n</blockquote>\n<p>Personally I prefer to use</p>\n<pre><code>{(observations && observations.length) && \n observations.map((obs) => (\n <h5>{obs}</h5>\n ))\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T16:03:03.747",
"Id": "263518",
"ParentId": "263413",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T15:24:07.253",
"Id": "263413",
"Score": "2",
"Tags": [
"node.js",
"react.js",
"typescript"
],
"Title": "TypeScript, React and Node app to get 'games' data from a database and display them on a frontend"
}
|
263413
|
<p>I am writing a Settlers of Catan server in Haskell for fun. Currently I am passing around state manually. I want to learn more about the State monad and want to incorporate it into my project.</p>
<p>However, my GameState has multiple data constructors that I pattern match on to yield different functionality. Three of such data constructors are for the WaitingLobby (when people can still join over the internet), the SetupPhase (before the game has really started and people have to build their initial settlements), and one for the RunningGame (when you can play the game turn by turn normally). Code:</p>
<pre><code>data GameState = WaitingLobby ... | SetupPhase ... | RunningGame ...
</code></pre>
<p>Lots of functions pattern match on the type of data constructor used. For example the function that handles building a settlement after it has been decided that the player is indeed allowed to do so:</p>
<pre><code>doConstructBuilding :: GameState -> Building -> VertexCoordinate -> GameState
doConstructBuilding gs@(SetupPhase _ _ board _ _ _) building coord = gs { board = placeBuilding building coord board,
_placedSettlement = True }
doConstructBuilding gs@(RunningGame playerList cur board _) building coord = gs { board = placeBuilding building coord board,
playerList = map payIfCur playerList}
where payIfCur p | cur == playerId p = playerPays p $ constructionCost building
| otherwise = p
</code></pre>
<p>So the different GameState dataconstructors have different implementations: In the SetupPhase the building is placed and it is noted that the player has placed a settlement in the state, while in the RunningGame the building is also placed, but here the player also pays resources for it.</p>
<p><strong>The question: My understanding is that with the state monad you only pull out the state once you're in the monadic context on the right side of the =. So How would I implement something like this?</strong></p>
<p>Note: Maybe there are other solutions for this particular method, but I have a lot of these data constructor pattern match cases.</p>
|
[] |
[
{
"body": "<p>In general, you would extract the state using <code>get</code> and then case-match on it, like so:</p>\n<pre><code>type Game = State GameState\n\ndoConstructBuilding :: Building -> VertexCoordinate -> Game ()\ndoConstructBuilding building coord = do\n gs <- get\n case gs of\n SetupPhase _ _ board _ _ _ -> do\n put $ gs { board = placeBuilding building coord board\n , _placedSettlement = True }\n RunningGame playerList cur board _ -> do\n let payIfCur p | cur == playerId p = playerPays p $ constructionCost building\n | otherwise = p\n put $ gs { board = placeBuilding building coord board\n , playerList = map payIfCur playerList }\n</code></pre>\n<p>There are various ways to make this more succinct. For example, both of your cases involve a single <code>State</code> action that modifies the state, so it can be rewritten in terms of <code>modify</code>:</p>\n<pre><code>doConstructBuilding' :: Building -> VertexCoordinate -> Game ()\ndoConstructBuilding' building coord = modify go\n where go gs@(SetupPhase _ _ board _ _ _)\n = gs { board = placeBuilding building coord board\n , _placedSettlement = True }\n go gs@(RunningGame playerList cur board _)\n = gs { board = placeBuilding building coord board\n , playerList = map payIfCur playerList }\n where payIfCur p | cur == playerId p = playerPays p $ constructionCost building\n | otherwise = p\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T21:40:38.433",
"Id": "263432",
"ParentId": "263414",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263432",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T16:37:57.867",
"Id": "263414",
"Score": "1",
"Tags": [
"haskell",
"state",
"pattern-matching"
],
"Title": "State monad and pattern matching on data constructors"
}
|
263414
|
<p>As a part of coursework, I had to build an UPGMA tree from a given distance matrix and a list of species names. As a beginner/intermediate in python I saw this as a good opportunity to learn about classes. The code is as follows:</p>
<pre><code>"""
UPGMA - Unweighted pair group method using arithmetic averages
Takes as input the distance matrix of species as a numpy array
Returns tree either as a dendrogram or in Newick format
"""
#%% import modules
import numpy as np
import itertools
#%% class for nodes
class Node:
"""
Data structure to store node of a UPGMA tree
"""
def __init__(self, left=None, right=None, up_height=0.0, down_height=0.0):
"""
Creating a node.
For a single taxon, set taxon name as self.left, leave right as none.
For an operational taxonomic unit(OTU) set left and right to child nodes.
Parameters
----------
left : default = none, taxon label
right : default = none, taxon label
up_height : float, default = 0.0, dist to parent node, if any
down_height : float, default = 0.0, dist to child node, if any
"""
self.left = left
self.right = right
self.uh = up_height
self.dh = down_height
def leaves(self) -> list:
"""
Method to find the taxa under any given node, effectively equivalent to
finding leaves of a binary tree. Only lists original taxa and not OTUs.
Returns a list of node names, not nodes themselves.
"""
if self == None:
return []
if self.right == None:
return [self.left]
leaves = self.left.leaves() + self.right.leaves()
return leaves
def __len__(self) -> int:
"""
Method to define len() of a node.
Returns the number of original taxa under any given node.
"""
return sum(1 for taxa in self.leaves())
def __repr__(self) -> str:
"""
Method to give readable print output
"""
return "-".join(self.leaves())
#%% class for UPGMA
class UPGMA:
def __init__(self, dist_matrix: np.ndarray, taxa: list):
"""
Initialize an UPGMA class.
Takes a nxn distance matrix as input. A list of n taxon id is required
in the same order as the distance matrix row/column
Parameters
----------
dist_matrix : numpy array, distance matrix of species
taxa : list of int or str to identify taxa
"""
self.distances = dist_matrix
self.taxa = taxa
self.build_tree(self.distances, self.taxa)
def build_tree(self, dist_matrix: np.ndarray, taxa: list) -> Node:
"""
Method to construct a tree from a given distance matrix and taxa list.
Parameters
----------
dist_matrix : np.ndarray of pairwise distances
taxa : list of taxa id. Elements of lists have to be unique
Returns the root node for constructed tree.
"""
# creating node for each taxa
nodes = list(Node(taxon) for taxon in taxa)
# dictionary row/column id -> node
rc_to_node = dict([i, j] for i, j in enumerate(nodes))
# dictionary taxa -> row/column id
taxa_to_rc = dict([i, j] for j, i in enumerate(taxa))
# make copy of dist matrix to work on
work_matrix = dist_matrix
# set all diagonal elements to infinity for ease of finding least distance
work_matrix = np.array(work_matrix, dtype=float)
np.fill_diagonal(work_matrix, np.inf)
# loop
while len(nodes) > 1:
# finding (row, col) of least dist
least_id = np.unravel_index(work_matrix.argmin(), work_matrix.shape, "C")
least_dist = work_matrix[least_id[0], least_id[1]]
# nodes corresponding to (row, col)
node1, node2 = rc_to_node[least_id[0]], rc_to_node[least_id[1]]
# add OTU with node1 and node2 as children. set heights of nodes
new_node = Node(node2, node1)
nodes.append(new_node)
node1.uh = least_dist / 2 - node1.dh
node2.uh = least_dist / 2 - node2.dh
new_node.dh = least_dist / 2
nodes.remove(node1)
nodes.remove(node2)
# create new working distance matrix
work_matrix = self.update_distance(dist_matrix, nodes, taxa_to_rc)
# update row/col id -> node dictionary
rc_to_node = dict([i, j] for i, j in enumerate(nodes))
# set tree to root
self.tree = nodes[0]
def update_distance(
self, dist_matrix: np.ndarray, nodes: list, taxa_to_rc: dict
) -> np.ndarray:
"""
Method to make a new distance matrix with newer node list.
Parameters
----------
dist_matrix : np.ndarray of pairwise distances for all taxa
nodes : list of updated nodes
taxa_to_rc : dict for taxa -> row/col id
Returns np.ndarray of pairwise distances for updated nodes
"""
# dictionary for node -> row/col id
node_to_rc = dict([i, j] for j, i in enumerate(nodes))
rc = len(nodes)
new_dist_matrix = np.zeros((rc, rc), dtype=float)
for node1 in nodes:
row = node_to_rc[node1]
for node2 in nodes:
node_pairs = list(itertools.product(node1.leaves(), node2.leaves()))
col = node_to_rc[node2]
new_dist_matrix[row, col] = sum(
dist_matrix[taxa_to_rc[i], taxa_to_rc[j]] for i, j in node_pairs
) / len(node_pairs)
np.fill_diagonal(new_dist_matrix, np.inf)
return new_dist_matrix
def tree_to_newick(t) -> str:
"""
Function to convert tree to Newick, slightly modified form of the tree.py version.
Takes the root node of an UPGMA tree as input
"""
if t.right == None:
return t.left + ":" + str(t.uh)
else:
return (
"("
+ ",".join([tree_to_newick(x) for x in [t.left, t.right]])
+ "):"
+ str(t.uh)
)
#%% main
if __name__ == "__main__":
# data from table 3 of Fitch and Margoliash, Construction of Phylogenetic trees
taxa = ["Turtle", "Human", "Tuna", "Chicken", "Moth", "Monkey", "Dog"]
distances = np.array(
[
[0, 19, 27, 8, 33, 18, 13],
[19, 0, 31, 18, 36, 1, 13],
[27, 31, 0, 26, 41, 32, 29],
[8, 18, 26, 0, 31, 17, 14],
[33, 36, 41, 31, 0, 35, 28],
[18, 1, 32, 17, 35, 0, 12],
[13, 13, 29, 14, 28, 12, 0],
]
)
x = UPGMA(distances, taxa).tree
print(tree_to_newick(x))
</code></pre>
<p>Please suggest improvements where possible.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T17:21:02.167",
"Id": "263416",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "UPGMA tree building in python"
}
|
263416
|
<p>This code calculates the probability of a runner finishing 3rd and it works like expected. I'm pretty sure though that is woefully inefficient. How could this code be transformed in a much more cleaner and performance efficient way?
My focus is the nested fors and and the if handlings.</p>
<pre><code>def Trd(mylist=[]):
third=[]
for thirds in range(len(mylist)):
sum=0
for seconds in range(len(mylist)):
sum_first=0
if seconds==thirds:
pass
else:
for firsts in range(len(mylist)):
if firsts==thirds:
pass
elif firsts==seconds:
pass
else:
frsts=mylist[firsts]*(mylist[seconds]/(1-mylist[firsts]))*(mylist[thirds]/(1-mylist[firsts]-mylist[seconds]))
sum_first+=frsts
sum+=sum_first
third.append(sum)
print(third)
list=[0.4,0.3,0.2,0.1]
Trd(list)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T19:06:32.267",
"Id": "520054",
"Score": "4",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T17:22:26.783",
"Id": "263417",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Calculating Probabilities"
}
|
263417
|
<p>My attempt at multiple linear regression.</p>
<p>I am trying to make a qualified guess about a user's rating of a movie, through machine learning. I am new to this, so my judgement isn't the best. And I am also getting a result but I have no idea if it is the result I want.</p>
<p>The code is setting up a finite selection of genres, which then are one-hotencoded and standardized. This will become the X for fitting the model and the same with previous average values, which will become the Y in the fit.</p>
<p>After the fit, I am emulating a new movie choice by the user <code>x_user = ["Action", "Thriller",]</code>. This is applied to the prediction and the result is being printed.</p>
<p>I need this to be reviewed so I know if I've done it correctly or not. And also if there are improvements to be made for this code.</p>
<pre><code># create main dataframe df and set first column "avg"
df = pd.DataFrame()
col1 = np.random.uniform(low=1.0, high=5.0, size=(100,))
df = pd.DataFrame(col1, columns=['avg']).round(2)
# create secondary and disposable dataframe df_tmp to set up genres for df
df_tmp = pd.DataFrame()
# list of genres
genres = [
"Action",
"Adventure",
"Biography",
"Comedy",
"Crime",
"Erotica",
"Fantasy",
"Historical fiction",
"Horror",
"Mystery",
"Romance",
"Satire",
"Scifi",
"Speculative",
"Thriller",
"Western",
]
# create three genre columns with values chosen at random so one avg can be decided by multiple genres
df_tmp['Genres1'] = np.random.choice(genres, df.shape[0])
df_tmp['Genres2'] = np.random.choice(genres, df.shape[0])
df_tmp['Genres3'] = np.random.choice(genres, df.shape[0])
# concatinate the collection of genres into Total column
df_tmp['Total'] = df_tmp['Genres1'] + "," + df_tmp['Genres2'] + "," + df_tmp['Genres3']
# remove duplicates from genre collection
data = []
for i in df_tmp.Total:
tmp = i.split(",")
tmp2=set(tmp)
tmp3 = ",".join(tmp2)
data.append(tmp3)
# add the genre set to df
df['Genres'] = pd.DataFrame(data)
# convert categorical data to one-hotencode data
df = pd.concat(
[df.drop('Genres', 1), df['Genres'].str.get_dummies(sep=",")], 1)
# standardize lambda expression
standarize = lambda q: (q-q.mean())/q.std()
# standardize the dataset
df_st = standarize(df)
from sklearn import linear_model
# divide df with avg as dependent variable and genres as independent variables
Y = df.avg
X = df.drop('avg', 1)
# do a linear regression fit
clf = linear_model.LinearRegression()
clf.fit(X, Y)
# print values
print(f'Intercept: {clf.intercept_}')
print(f'Coefficients: {clf.coef_}')
# the genres of the movie chosen by the user
x_user = ["Action", "Thriller",]
# create the array to be utilized for the prediction. A bool list of genres matching at indext because the prediction method does not accept strings or an array shorter or longer than X
X_pred = []
cat = X.columns
for i in cat:
if i in x_user:
X_pred.append(1)
else:
X_pred.append(0)
# get avg prediction for a new genre combination
print(f'Predicted avg rating: {clf.predict([X_pred])}')
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T17:22:44.207",
"Id": "263418",
"Score": "0",
"Tags": [
"python",
"statistics",
"machine-learning"
],
"Title": "Predicting with multiple independent hot-encoded variables"
}
|
263418
|
<h1>Problem</h1>
<p>A function solution(w, h, s) that takes 3 integers and returns the number of unique, non-equivalent configurations that can be found on a grid w blocks wide, h blocks tall and s possible states.</p>
<p>Equivalency is defined as above: any two grids each with same state where the actual order of the rows and columns do not matter (and can thus be freely swapped around).</p>
<p>Grid standardization means that the width and height of the grid will always be between 1 and 12, inclusive. The number of states is between 2 and 20, inclusive.</p>
<p>Return it as a decimal string.</p>
<h3>Example Cases</h3>
<ul>
<li>Case 1: w=2, h=2, s=2; answer:7</li>
<li>Case 2: w=2, h=3, s=4; answer:430</li>
</ul>
<h1>Solution</h1>
<p>The solution can be built based on Group Theory, specifically from Pólya Enumeration theorem.</p>
<h3>Brief Theory Description</h3>
<p>The Pólya enumeration theorem is a generalization of Burnside's lemma which provides a more convenient tool for finding the number of equivalence classes.</p>
<p>Burnside’s Lemma is also sometimes known as orbit counting theorem. It is one of the results of group theory. It is used to count distinct objects with respect to symmetry. It basically gives us the formula to count the total number of combinations, where two objects that are symmetrical to each other with respect to rotation or reflection are counted as a single representative.</p>
<p>There is a set (the whole set of h x w-matrices, where the entries can take any of s different values) and a group of permutations that transforms some matrices in others. In the problem the group consists of all permutations of rows and/or columns of the matrices.</p>
<p>The set of matrices gets divided into classes of matrices that can be transformed into one another. The goal of the problem is to count the number of these classes. In technical terminology the set of classes is called the quotient of the set by the action of the group, or orbit space.</p>
<p>The good thing is that there is a powerful theorem (with many generalizations and versions) that does exactly that. That is Polya's enumeration theorem. The theorem expresses the number of elements of the orbit space in terms of the value of a polynomial known in the area as Cycle Index. Now, in this problem the group is a direct product of two special groups the group of all permutations of h and w elements, respectively. The Cycle Index polynomials for these groups are known, and so are formulas for computing the Cycle Index polynomial of the product of groups in terms of the Cycle Index polynomials of the factors.</p>
<p>Maybe a comment worth making that motivates the name of the polynomial is the following: Every permutation of elements can be seen as cycling disjoint subsets of those elements. For example, a permutation of (1,2,3,4,5) and can be (2,3,1,5,4), where we mean that 2 moved to the position of 1, 3 moved to the position of 2, 1 to the position of 3, 5 to the position of 4 and 4 to the position of 5. The effect of this permutation is the same as cycling 1-> 3 -> 2 and 2 back to 1, and cycling 4 -> 5 and 5 back to 4. Similar to how natural numbers can be factored into a product of prime factors, each permutation can be factored into disjoint cycles. For each permutation, the cycles are unique in a sense for each permutation. The Cycle Index polynomial is computed in terms of the number of cycles of each length for each permutation in the group.</p>
<h3>Pseudocode Overview</h3>
<ul>
<li>Partitions of a number</li>
<li>Greatest common divisors (gcd) of many numbers.</li>
<li>Factorials of many numbers.</li>
</ul>
<h1>Code</h1>
<pre><code>from collections import Counter
def solution(w, h, s):
grid=0
for pw in partitions(w):
for ph in partitions(h):
m=count(pw, w)*count(ph, h)
grid+=m*(s**sum([sum([gcd(i, j) for i in pw]) for j in ph]))
return str(grid//(factorial(w)*factorial(h)))
def count(c, n):
cnt=factorial(n)
for a, b in Counter(c).items():
cnt//=(a**b)*factorial(b)
return cnt
def partitions(n, i=1):
yield [n]
for i in range(i, n//2 + 1):
for p in partitions(n-i, i):
yield [i] + p
def gcd(x,y):
while y:
x,y=y,x%y
return x
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T18:33:59.487",
"Id": "263421",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"mathematics"
],
"Title": "Applied Solution Based On Polya Enumeration Theorem"
}
|
263421
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263289/231235">Two dimensional bicubic interpolation implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/263024/231235">Two dimensional gaussian image generator in C</a>. Based on <a href="https://codereview.stackexchange.com/a/263320/231235">user673679's answer</a>, another file <code>image_operations.h</code> is created for those non-member helper functions for image operations implementation. Moreover, the two dimensional gaussian image generator <code>gaussianFigure2D</code> and <code>gaussianFigure2D2</code> is implemented as below.</p>
<ul>
<li><p><code>Image</code> template class implementation (<code>image.h</code>):</p>
<pre><code>/* Develop by Jimmy Hu */
#ifndef Image_H
#define Image_H
#include <algorithm>
#include <array>
#include <chrono>
#include <complex>
#include <concepts>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <numeric>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
#include "basic_functions.h"
#include "image_operations.h"
namespace TinyDIP
{
template <typename ElementT>
class Image
{
public:
Image()
{
}
Image(const size_t width, const size_t height):
width(width),
height(height),
image_data(width * height) { }
Image(const int width, const int height, const ElementT initVal):
width(width),
height(height),
image_data(width * height)
{
this->image_data = recursive_transform<1>(this->image_data, [initVal](ElementT element) { return initVal; });
return;
}
Image(const std::vector<ElementT>& input, size_t newWidth, size_t newHeight)
{
this->width = newWidth;
this->height = newHeight;
this->image_data = recursive_transform<1>(input, [](ElementT element) { return element; }); // Deep copy
}
Image(const std::vector<std::vector<ElementT>>& input)
{
this->height = input.size();
this->width = input[0].size();
for (auto& rows : input)
{
this->image_data.insert(this->image_data.end(), std::begin(input), std::end(input));
}
return;
}
constexpr ElementT& at(const unsigned int x, const unsigned int y) { return this->image_data[y * width + x]; }
constexpr ElementT const& at(const unsigned int x, const unsigned int y) const { return this->image_data[y * width + x]; }
constexpr size_t getWidth()
{
return this->width;
}
constexpr size_t getHeight()
{
return this->height;
}
std::vector<ElementT> const& getImageData() const { return this->image_data; } // expose the internal data
void print()
{
for (size_t y = 0; y < this->height; y++)
{
for (size_t x = 0; x < this->width; x++)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
std::cout << +this->at(x, y) << "\t";
}
std::cout << "\n";
}
std::cout << "\n";
return;
}
Image<ElementT>& operator+=(const Image<ElementT>& rhs)
{
for (size_t y = 0; y < this->height; y++)
{
for (size_t x = 0; x < this->width; x++)
{
this->at(x, y) += rhs.at(x, y);
}
}
return *this;
}
Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign
Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign
Image(const Image<ElementT> &input) = default; // Copy Constructor
Image(Image<ElementT> &&input) = default; // Move Constructor
private:
size_t width;
size_t height;
std::vector<ElementT> image_data;
};
}
#endif
</code></pre>
</li>
<li><p><code>image_operations.h</code>: non-member helper functions for image operations.</p>
<pre><code>/* Develop by Jimmy Hu */
#ifndef ImageOperations_H
#define ImageOperations_H
#include "base_types.h"
#include "image.h"
namespace TinyDIP
{
// Forward Declaration class Image
template <typename ElementT>
class Image;
template<class ElementT>
Image<ElementT> copyResizeBicubic(Image<ElementT> const& image, size_t width, size_t height)
{
auto output = Image<ElementT>(width, height);
auto ratiox = (float)image.getWidth() / (float)width;
auto ratioy = (float)image.getHeight() / (float)height;
for (size_t y = 0; y < height; y++)
{
for (size_t x = 0; x < width; x++)
{
float xMappingToOrigin = (float)x * ratiox;
float yMappingToOrigin = (float)y * ratioy;
float xMappingToOriginFloor = floor(xMappingToOrigin);
float yMappingToOriginFloor = floor(yMappingToOrigin);
float xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor;
float yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor;
ElementT ndata[4 * 4];
for (int ndatay = -1; ndatay <= 2; ndatay++)
{
for (int ndatax = -1; ndatax <= 2; ndatax++)
{
ndata[(ndatay + 1) * 4 + (ndatax + 1)] = image.at(
std::clamp(xMappingToOriginFloor + ndatax, 0.0f, image.getWidth() - 1.0f),
std::clamp(yMappingToOriginFloor + ndatay, 0.0f, image.getHeight() - 1.0f));
}
}
output.at(x, y) = bicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac);
}
}
return output;
}
template<class ElementT, class InputT>
constexpr static auto bicubicPolate(const ElementT* const ndata, const InputT fracx, const InputT fracy)
{
auto x1 = cubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx );
auto x2 = cubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx );
auto x3 = cubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx );
auto x4 = cubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx );
return std::clamp(cubicPolate( x1, x2, x3, x4, fracy ), 0.0f, 255.0f);
}
template<class InputT1, class InputT2>
constexpr static auto cubicPolate(const InputT1 v0, const InputT1 v1, const InputT1 v2, const InputT1 v3, const InputT2 frac)
{
auto A = (v3-v2)-(v0-v1);
auto B = (v0-v1)-A;
auto C = v2-v0;
auto D = v1;
return D + frac * (C + frac * (B + frac * A));
}
// single standard deviation
template<class InputT>
constexpr static Image<InputT> gaussianFigure2D(
const size_t xsize, const size_t ysize,
const size_t centerx, const size_t centery,
const InputT standard_deviation)
{
return gaussianFigure2D2(xsize, ysize, centerx, centery, standard_deviation, standard_deviation);
}
// multiple standard deviations
template<class InputT>
constexpr static Image<InputT> gaussianFigure2D2(
const size_t xsize, const size_t ysize,
const size_t centerx, const size_t centery,
const InputT standard_deviation_x, const InputT standard_deviation_y)
{
auto output = TinyDIP::Image<InputT>(xsize, ysize);
auto row_vector_x = TinyDIP::Image<InputT>(xsize, 1);
for (size_t x = 0; x < xsize; x++)
{
row_vector_x.at(x, 0) = normalDistribution1D(static_cast<InputT>(x) - static_cast<InputT>(centerx), standard_deviation_x);
}
auto row_vector_y = TinyDIP::Image<InputT>(ysize, 1);
for (size_t y = 0; y < ysize; y++)
{
row_vector_y.at(y, 0) = normalDistribution1D(static_cast<InputT>(y) - static_cast<InputT>(centery), standard_deviation_y);
}
for (size_t y = 0; y < ysize; y++)
{
for (size_t x = 0; x < xsize; x++)
{
output.at(x, y) = row_vector_x.at(x, 0) * row_vector_y.at(y, 0);
}
}
return output;
}
float normalDistribution1D(const float x, const float standard_deviation)
{
return expf(-x * x / (2 * standard_deviation * standard_deviation));
}
double normalDistribution1D(const double x, const double standard_deviation)
{
return exp(-x * x / (2 * standard_deviation * standard_deviation));
}
long double normalDistribution1D(const long double x, const long double standard_deviation)
{
return expl(-x * x / (2 * standard_deviation * standard_deviation));
}
float normalDistribution2D(const float xlocation, const float ylocation, const float standard_deviation)
{
return expf(-(xlocation * xlocation + ylocation * ylocation) / (2 * standard_deviation * standard_deviation)) / (2 * M_PI * standard_deviation * standard_deviation);
}
double normalDistribution2D(const double xlocation, const double ylocation, const double standard_deviation)
{
return exp(-(xlocation * xlocation + ylocation * ylocation) / (2 * standard_deviation * standard_deviation)) / (2 * M_PI * standard_deviation * standard_deviation);
}
}
#endif
</code></pre>
</li>
<li><p><code>basic_functions.h</code>: The basic functions</p>
<pre><code>/* Develop by Jimmy Hu */
#ifndef BasicFunctions_H
#define BasicFunctions_H
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
namespace TinyDIP
{
template<typename T>
concept is_back_inserterable = requires(T x)
{
std::back_inserter(x);
};
template<typename T>
concept is_inserterable = requires(T x)
{
std::inserter(x, std::ranges::end(x));
};
// recursive_invoke_result_t implementation
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>>&&
std::ranges::input_range<Container<Ts...>>&&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
// recursive_transform implementation (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T, class F>
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t<F, T> output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return f(input);
}
}
// recursive_transform implementation (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t<F, T> output{};
std::mutex mutex;
// Reference: https://en.cppreference.com/w/cpp/algorithm/for_each
std::for_each(execution_policy, input.cbegin(), input.cend(),
[&](auto&& element)
{
auto result = recursive_transform<unwrap_level - 1>(execution_policy, element, f);
std::lock_guard lock(mutex);
output.emplace_back(std::move(result));
}
);
return output;
}
else
{
return f(input);
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_array_generator<dim - 1, times>(input);
std::array<decltype(element), times> output;
std::fill(std::ranges::begin(output), std::ranges::end(output), element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_deque_generator<dim - 1>(input, times);
std::deque<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_list_generator<dim - 1>(input, times);
std::list<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
}
#endif
</code></pre>
</li>
<li><p><code>base_types.h</code>: The base types</p>
<pre><code>/* Develop by Jimmy Hu */
#ifndef BASE_H
#define BASE_H
#include <cmath>
#include <cstdbool>
#include <cstdio>
#include <cstdlib>
#include <string>
#define MAX_PATH 256
#define FILE_ROOT_PATH "./"
typedef unsigned char BYTE;
typedef struct RGB
{
unsigned char channels[3];
} RGB;
typedef BYTE GrayScale;
typedef struct HSV
{
long double channels[3]; // Range: 0 <= H < 360, 0 <= S <= 1, 0 <= V <= 255
}HSV;
#endif
</code></pre>
</li>
</ul>
<p><strong>The full testing code</strong></p>
<pre><code>/* Develop by Jimmy Hu */
#include "base_types.h"
#include "basic_functions.h"
#include "image.h"
#include "image_operations.h"
void gaussianFigure2DTest();
int main()
{
gaussianFigure2DTest();
return 0;
}
void gaussianFigure2DTest()
{
auto image1 = TinyDIP::gaussianFigure2D2(10, 10, 5, 5, 3.0, 1.0);
image1.print();
auto image2 = TinyDIP::gaussianFigure2D(10, 10, 5, 5, 3.0);
image2.print();
return;
}
</code></pre>
<p>The output of the testing code above:</p>
<pre><code>9.29249e-07 1.53207e-06 2.26033e-06 2.98407e-06 3.52526e-06 3.72665e-06 3.52526e-06 2.98407e-06 2.26033e-06 1.53207e-06
8.36483e-05 0.000137913 0.000203468 0.000268617 0.000317334 0.000335463 0.000317334 0.000268617 0.000203468 0.000137913
0.00277005 0.00456705 0.00673795 0.00889539 0.0105087 0.011109 0.0105087 0.00889539 0.00673795 0.00456705
0.0337462 0.055638 0.082085 0.108368 0.128022 0.135335 0.128022 0.108368 0.082085 0.055638
0.15124 0.249352 0.367879 0.485672 0.573753 0.606531 0.573753 0.485672 0.367879 0.249352
0.249352 0.411112 0.606531 0.800737 0.945959 1 0.945959 0.800737 0.606531 0.411112
0.15124 0.249352 0.367879 0.485672 0.573753 0.606531 0.573753 0.485672 0.367879 0.249352
0.0337462 0.055638 0.082085 0.108368 0.128022 0.135335 0.128022 0.108368 0.082085 0.055638
0.00277005 0.00456705 0.00673795 0.00889539 0.0105087 0.011109 0.0105087 0.00889539 0.00673795 0.00456705
8.36483e-05 0.000137913 0.000203468 0.000268617 0.000317334 0.000335463 0.000317334 0.000268617 0.000203468 0.000137913
0.0621765 0.102512 0.15124 0.199666 0.235877 0.249352 0.235877 0.199666 0.15124 0.102512
0.102512 0.169013 0.249352 0.329193 0.388896 0.411112 0.388896 0.329193 0.249352 0.169013
0.15124 0.249352 0.367879 0.485672 0.573753 0.606531 0.573753 0.485672 0.367879 0.249352
0.199666 0.329193 0.485672 0.64118 0.757465 0.800737 0.757465 0.64118 0.485672 0.329193
0.235877 0.388896 0.573753 0.757465 0.894839 0.945959 0.894839 0.757465 0.573753 0.388896
0.249352 0.411112 0.606531 0.800737 0.945959 1 0.945959 0.800737 0.606531 0.411112
0.235877 0.388896 0.573753 0.757465 0.894839 0.945959 0.894839 0.757465 0.573753 0.388896
0.199666 0.329193 0.485672 0.64118 0.757465 0.800737 0.757465 0.64118 0.485672 0.329193
0.15124 0.249352 0.367879 0.485672 0.573753 0.606531 0.573753 0.485672 0.367879 0.249352
0.102512 0.169013 0.249352 0.329193 0.388896 0.411112 0.388896 0.329193 0.249352 0.169013
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/263289/231235">Two dimensional bicubic interpolation implementation in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/263024/231235">Two dimensional gaussian image generator in C</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>Based on <a href="https://codereview.stackexchange.com/a/263320/231235">user673679's answer</a>, another file <code>image_operations.h</code> is created for those non-member helper functions for image operations implementation. Moreover, I am attempting to build the two dimensional gaussian image generator functions in C++.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
<h3>Reference</h3>
<ul>
<li><p>Multivariate normal distribution</p>
<p><a href="https://en.wikipedia.org/wiki/Multivariate_normal_distribution" rel="noreferrer">https://en.wikipedia.org/wiki/Multivariate_normal_distribution</a></p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T22:58:04.437",
"Id": "520524",
"Score": "0",
"body": "You mean \"developed by Jimmy Hu\"."
}
] |
[
{
"body": "<p>You are obviously on a fantastic quest to understand how to implement image processing operations in all sorts of languages. The tag <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinventing-the-wheel'\" rel=\"tag\">reinventing-the-wheel</a> tells me that you know that you should use an established image processing library as the basis of any serious work.</p>\n<p>Here are some comments on your C++ implementation.</p>\n<h1>image.h</h1>\n<p>Proper English spelling would be "Develop<strong>ed</strong> by Jimmy Hu".</p>\n<p>This file includes headers that you don't use. You should only include headers that you actually need.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Image()\n {\n }\n</code></pre>\n<p>This should be</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Image() = default;\n</code></pre>\n<p>This constructor initializes the array with a constant value:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Image(const int width, const int height, const ElementT initVal):\n width(width),\n height(height),\n image_data(width * height)\n {\n this->image_data = recursive_transform<1>(this->image_data, [initVal](ElementT element) { return initVal; });\n return;\n }\n</code></pre>\n<p>Use the <code>std::vector</code> constructor for this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Image(const int width, const int height, const ElementT initVal):\n width(width),\n height(height),\n image_data(width * height, initVal) {}\n</code></pre>\n<p>If you further add a default value to the last parameter (<code>const ElementT initVal = {}</code>) then you don't need the previous constructor (<code>Image(const size_t width, const size_t height)</code>).</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Image(const std::vector<ElementT>& input, size_t newWidth, size_t newHeight)\n {\n this->width = newWidth;\n this->height = newHeight;\n this->image_data = recursive_transform<1>(input, [](ElementT element) { return element; }); // Deep copy\n }\n</code></pre>\n<p>This constructor can be easily implemented in terms of <code>std::copy</code>. You do need to add a test here to verify that the input array has the right number of elements considering <code>newWidth</code> and <code>newHeight</code>.</p>\n<p>The implementation of <code>at</code> doesn't check bounds. I would suggest adding <code>assert</code> statements for bounds, to catch bugs in debug mode. A release build would then not test bounds.</p>\n<p><code>operator+=</code> should really test that the sizes of the second image match those of the first. You can then simply iterate over the two arrays without worrying about <code>x</code> and <code>y</code> coordinates. If sizes don't match, the operation should fail.</p>\n<p>It is not necessary to use <code>this-></code> to access members. Some people like it, but I think it is superfluous.</p>\n<p>The standard way to increment in C++ is <code>++x</code>, not <code>x++</code>. For an <code>int</code> it doesn't make any difference, but for more complex objects it could be very wasteful. <code>++x</code> increments the variable, then returns its value. <code>x++</code> makes a copy of the value of the variable, increments the variable, then returns the copy. If you are not using the value of the expression, use the pre-increment to avoid the unnecessary copy.</p>\n<h1>image_operations.h</h1>\n<p>You don't need to forward declare <code>class Image</code>. You include its header file, so the class is already declared.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>auto ratiox = (float)image.getWidth() / (float)width;\n</code></pre>\n<p>Please get used to the C++ way of casting:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>auto ratiox = static_cast<float>(image.getWidth()) / static_cast<float>(width);\n</code></pre>\n<p>It is a more obvious cast and makes your code more readable.</p>\n<p>Your functions <code>gaussianFigure2D</code> and <code>gaussianFigure2D2</code> don't need different names. I would argue the library would be easier to use if they had the same name. The compiler will pick the one or the other function depending on the arguments passed.</p>\n<p><code>std::exp</code> is implemented for all three floating-point types. Consequently, <code>normalDistribution1D</code> can be implemented as a template:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> template<typename T>\n T normalDistribution1D(const T x, const T standard_deviation)\n {\n return std::exp(-x * x / (2 * standard_deviation * standard_deviation));\n }\n</code></pre>\n<p>The same is true for <code>normalDistribution2D</code>.</p>\n<p>Functions here are declared out of order: functions use other functions that are declared later in the file. Somehow this works for you, I think, because templates are instantiated when used. It would be better practice to declare <code>normalDistribution1D</code> before <code>gaussianFigure2D</code>, and <code>gaussianFigure2D2</code> before <code>gaussianFigure2D</code>. Note that class methods can be declared in any order -- the compiler will first collect all member names (collect the full definition of the class) before attempting to compile each of the function bodies. The same is not true for free functions such as the ones we're talking about here.</p>\n<h1>basic_functions.h</h1>\n<p>Again you have way too many headers included here.</p>\n<p>This is very complex code, which seems out of place with the relatively straight-forward C++ code elsewhere. With the changes suggested above, you don't need this file at all.</p>\n<h1>base_types.h</h1>\n<p>You should not be using <code><cstdbool></code>. <a href=\"https://en.cppreference.com/w/cpp/header/cstdbool\" rel=\"nofollow noreferrer\">It is deprecated in C++17 and removed in C++20.</a> The other <code><c...></code> headers should not be needed either. Use the C++ library, not the C library.</p>\n<p>Instead of <code>#define MAX_PATH 256</code>, use <code>constexpr int MAX_PATH = 256</code>. Preprocessor macros are nice to generate code, but they should not be used for things that you can do with native C++ constructs.</p>\n<p>Likewise, instead of the C construct <code>typedef unsigned char BYTE</code>, use <code>using BYTE = unsigned char</code>, which is, to me, much more readable.</p>\n<p>This is also a C thing:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>typedef struct RGB\n{\n unsigned char channels[3];\n} RGB;\n</code></pre>\n<p>In C++ it is just</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct RGB\n{\n unsigned char channels[3];\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:06:53.293",
"Id": "520309",
"Score": "0",
"body": "Thank you for the answering. _Your functions `gaussianFigure2D` and `gaussianFigure2D2` don't need different names. I would argue the library would be easier to use if they had the same name. The compiler will pick the one or the other function depending on the arguments passed._ I found a thing is that the compiler (`g++-11 11.1.0`) says \"error: no matching function for call to 'gaussianFigure2D(const size_t&, const size_t&, const size_t&, const size_t&, const double&, const double&)'\" if those functions with same name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:09:42.133",
"Id": "520311",
"Score": "0",
"body": "However, if the single standard deviation version definition is put _after_ the multiple standard deviations version definition, there is no error occurred."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:30:58.153",
"Id": "520317",
"Score": "1",
"body": "@JimmyHu: Wow, that’s weird. What compiler do you use? I would logically place the function that contains the actual code first, and the “aliases” with different inputs after, but the order shouldn’t matter for the compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:55:07.273",
"Id": "520320",
"Score": "0",
"body": "g++ under MacOS:\n\ng++-11 (Homebrew GCC 11.1.0_1) 11.1.0\nCopyright (C) 2021 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T17:11:21.777",
"Id": "520326",
"Score": "1",
"body": "@JimmyHu: Thanks, I have the same compiler on macOS, I want to play with this to see if I can figure out the reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T18:02:16.173",
"Id": "520328",
"Score": "0",
"body": "Thank you for trying. If you figure out the reason, please let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T21:52:37.650",
"Id": "520344",
"Score": "1",
"body": "@JimmyHu When you first mentioned the issue with the order, I had forgotten that we're not talking about class member functions, but free functions. Things are different there. I have added some text to this respect in the answer, I hope that clarifies things. If you make sure to compile with `-Wall`, the compiler will warn you about lots of things that are not really OK, but it can work around. You get best code when you fix all warnings generated by this flag."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T06:17:01.687",
"Id": "520540",
"Score": "1",
"body": "I don't find C++ casts particularly readable. But I'd argue that's a good thing - it encourages us to really question which casts really are necessary, and eliminate the rest. It may even make me write that one as `1.0f * image.getWidth() / width` to use standard conversions instead. C++ casts are _safer_ than C casts, because it's clearer which aspects you intend to change (e.g. you can't accidentally cast away `const`)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T18:09:10.450",
"Id": "263492",
"ParentId": "263422",
"Score": "8"
}
},
{
"body": "<p><code>"error: no matching function for call to 'gaussianFigure2D(const size_t&, const size_t&, const size_t&, const size_t&, const double&, const double&)'"</code></p>\n<p>Here is how your code defines it:</p>\n<pre><code>template<class InputT>\n constexpr static Image<InputT> gaussianFigure2D(\n const size_t xsize, const size_t ysize,\n const size_t centerx, const size_t centery,\n const InputT standard_deviation)\n</code></pre>\n<p>and the other form just has one more parameter.</p>\n<p>Here's where it is called:\n<code>auto image1 = TinyDIP::gaussianFigure2D2(10, 10, 5, 5, 3.0, 1.0);</code></p>\n<p>That looks like it should work just fine. Since there are a different number of parameters, it will pick the one with 6 parameters and not get confused as to which you meant. The template argument deduction and conversions would not be any different when this is overloaded.</p>\n<p>Having the second form simply supply the 6th argument automatically duplicating the 5th is a perfect use case for overloading!</p>\n<p>I think your problem is that you defined them in the wrong order. The 6-argument form goes <em>first</em>, so the 5-argument form can call it. It worked as-written, even though <code>gaussianFigure2D2</code> is not declared yet, because this is a template body and the call involves something of type <code>T</code>, so it puts off resolving the symbol until <em>phase 2</em>, when the template is instantiated.</p>\n<hr />\n<p>Besides the <code>struct</code>s that you apparently copied out of a C header file, as mentioned by Cris, you also have</p>\n<p><code>typedef BYTE GrayScale;</code></p>\n<p>Don't use <code>typedef</code> anymore, at all. For type alises, use <code>using</code>. And we have <code>std::byte</code> which is not spelled in all caps, so don't declare your own.</p>\n<p><code>using GrayScale = std::byte;</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T07:01:13.713",
"Id": "520547",
"Score": "2",
"body": "`std::byte` doesn’t implement arithmetic, which would make it hard to use as a pixel value (which is how I presume OP would use it). `std::uint8_t` would be more suitable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T23:23:44.153",
"Id": "263650",
"ParentId": "263422",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263492",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T18:40:12.713",
"Id": "263422",
"Score": "7",
"Tags": [
"c++",
"reinventing-the-wheel",
"image",
"template",
"c++20"
],
"Title": "Two dimensional gaussian image generator in C++"
}
|
263422
|
<p>I have written some javascript code for a multilanguage site. The code works great but I feel like I have a lot of duplicate code. I was wondering if someone can explain how I can make this simpler or minimized. I have tried to use a <code>forEach(function (item, index)</code> but it does not seem to be working.</p>
<p>This is the original code that works....</p>
<pre><code>(function () {
var lang1 = "/en/"; //default language
var lang2 = "/fr/"; //second language
var lang3 = "/es/"; //third language
var languageSwitcher = document.querySelectorAll("a[href='/languages']").forEach((el) => el.parentNode.classList.add("language-switcher"));
document.querySelector("[data-folder='/languages']").classList.add("language-switcher");
document.querySelectorAll(".language-switcher .header-nav-folder-item").forEach((el) => el.classList.add("languages"));
document.querySelectorAll(".language-switcher .header-menu-nav-item:not(:first-child)").forEach((el) => el.classList.add("languages"));
var languages = document.querySelectorAll(".languages");
var language1 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang1+"']");
var language2 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang2+"']")
var language3 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang3+"']")
var windowURL = window.location.href;
var pageURL = windowURL.split("/")[4];
if (pageURL == undefined) {
for (var i = 0; i < language1.length; i++) {
language1[i].onclick = function () {
var path = lang1 + "home";
this.href = path;
};
}
for (var i = 0; i < language2.length; i++) {
language2[i].onclick = function () {
var path = lang2 + "home";
this.href = path;
};
}
for (var i = 0; i < language3.length; i++) {
language3[i].onclick = function () {
var path = lang3 + "home";
this.href = path;
};
}
} else {
for (var i = 0; i < language1.length; i++) {
language1[i].onclick = function () {
var path = lang1 + pageURL;
this.href = path;
};
}
for (var i = 0; i < language2.length; i++) {
language2[i].onclick = function () {
var path = lang2 + pageURL;
this.href = path;
};
}
for (var i = 0; i < language3.length; i++) {
language3[i].onclick = function () {
var path = lang3 + pageURL;
this.href = path;
};
}
}
document.querySelectorAll(".header-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll('[data-folder="/languages"] .header-menu-nav-item a').forEach((el) => el.classList.remove("language"));
var languageLinks = document.querySelectorAll(".language");
for (var i = 0; i < languageLinks.length; i++) {
var navURL = languageLinks[i].href;
if (windowURL.indexOf(lang1) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
if (navURL.indexOf(lang1) != -1) {
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else if (windowURL.indexOf(lang2) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[1].classList.add("active");
if (navURL.indexOf(lang2) != -1) {
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else if (windowURL.indexOf(lang3) != -1) {
if (navURL.indexOf(lang3) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[2].classList.add("active");
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else {
if (navURL.indexOf(lang1) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
}
}
var active = document.querySelector(".language-switcher .active");
active.closest(".language-switcher").prepend(active);
document.querySelectorAll(".header a").forEach((el) => (el.style.visibility = "visible"));
languageSwitcher.style.display = "flex";
})();
</code></pre>
<p>I have attempted to use a forEach function and an array but it is not working.</p>
<blockquote>
<pre><code> (function () {
var lang = ["/en/", "/fr/", "/es/"];
document
.querySelectorAll("a[href='/languages']")
.forEach((el) => el.parentNode.classList.add("language-switcher"));
document
.querySelector("[data-folder='/languages']")
.classList.add("language-switcher");
document
.querySelectorAll(".language-switcher .header-nav-folder-item")
.forEach((el) => el.classList.add("languages"));
document
.querySelectorAll(
".language-switcher .header-menu-nav-item:not(:first-child)"
)
.forEach((el) => el.classList.add("languages"));
var languages = document.querySelectorAll(".languages"); //langauge switcher language options
document
.querySelectorAll(".header-nav-item:not(.language-switcher) a")
.forEach((el) => el.classList.add("language"));
document
.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a")
.forEach((el) => el.classList.add("language"));
document
.querySelectorAll('[data-folder="/languages"] .header-menu-nav-item a')
.forEach((el) => el.classList.remove("language"));
var languageLinks = document.querySelectorAll(".language"); // languages set in navigation links
var windowURL = window.location.href;
var pageURL = windowURL.split("/")[4];
var language = document.querySelectorAll(".language-switcher .languages a");
for (var i = 0; i < language.length; i++) {
lang.forEach(function (item, index) {
if (pageURL == undefined) {
language[index].onclick = function () {
var path = item + "home";
this.href = path;
};
} else {
language[index].onclick = function () {
var path = item + pageURL;
this.href = path;
};
}
});
}
for (var j = 0; j < languageLinks.length; j++) {
var navURL = languageLinks[j].href;
for (var k = 0; k < lang.length; k++) {
if (windowURL.indexOf(lang[k]) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[k].classList.add("active");
if (navURL.indexOf(lang[k]) != -1) {
languageLinks[j].closest("div").style.display = "block";
} else {
languageLinks[j].closest("div").style.display = "none";
}
} else {
if (navURL.indexOf(lang[0]) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
languageLinks[j].closest("div").style.display = "block";
} else {
languageLinks[j].closest("div").style.display = "none";
}
}
}
}
document.querySelector(".header").style.visibility = "visible";
var active = document.querySelector(".language-switcher .active");
active.closest(".language-switcher").prepend(active);
})();
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T08:53:12.110",
"Id": "520092",
"Score": "2",
"body": "What does your code attempt to do (tasks)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T16:27:30.817",
"Id": "520126",
"Score": "0",
"body": "It is for having multiple languages on a website. Each page has a prefix added to the url. For example all the English pages would be domainname.com/en/pagename. The code then matches the windowurl to the pagelinks and hides the pages that don't have that prefix.\n\nIt works well but I have a lot of if language1 do this.... if language2 do this... etc. I am wondering if there is a way to simplify that so that I don't have to have an if else for each language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T20:37:59.253",
"Id": "520149",
"Score": "0",
"body": "Hmm... (I don't know much of javascript but,) do you need other than find the \"windowurl\" language pointing string (\"/en/\", \"/fr/\", \"/es/\", ... ) and then insert it to the query string to pick pages ... (if your English pages are under \"domain.com/en/\", French pages under \"domain.com/fr/\", etc.)?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T18:56:19.950",
"Id": "263423",
"Score": "3",
"Tags": [
"javascript",
"i18n"
],
"Title": "Language switcher for a multilingual site"
}
|
263423
|
<p>Put together a <code>RadioMenu</code> class that can use a Enum to generate a Single-Selection Radio Button Menu. My main question is about whether there's a way to remove the need to pass in the Class of the Enum to the <code>generateButtonsFromEnum()</code> method. Otherwise, would appreciate any general pointers on ways to improve this system since I'm still pretty new when it comes to AWT/Swing features.</p>
<p><strong>RadioMenu</strong></p>
<pre><code>package tools;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.JMenu;
import javax.swing.JRadioButtonMenuItem;
public class RadioMenu<E extends Enum<E>> extends JMenu {
private static final long serialVersionUID = 1L;
private E currentState;
private JRadioButtonMenuItem selectedRadioButton;
private HashMap<E, JRadioButtonMenuItem> stateMap;
public RadioMenu() {
stateMap = new HashMap<E, JRadioButtonMenuItem>();
}
public RadioMenu(String name) {
super(name);
stateMap = new HashMap<E, JRadioButtonMenuItem>();
}
public void addRadioButton(E enumValue, JRadioButtonMenuItem radioButton) {
//Set default to first added button
if(stateMap.isEmpty()) {
currentState = enumValue;
radioButton.setSelected(true);
selectedRadioButton = radioButton;
}
add(radioButton);
stateMap.put(enumValue, radioButton);
radioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setState(enumValue);
}
});
}
public void generateButtonsFromEnum(Class<E> enumType) {
for(E enumValue : enumType.getEnumConstants()) {
addRadioButton(enumValue, new JRadioButtonMenuItem(enumValue.toString()));
}
}
public E getState() {
return currentState;
}
public void setState(E newState) {
currentState = newState;
selectedRadioButton.setSelected(false);
selectedRadioButton = stateMap.get(newState);
selectedRadioButton.setSelected(true);
}
}
</code></pre>
<p><strong>RadioMenuTest</strong></p>
<pre><code>package main;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import tools.RadioMenu;
public class RadioMenuTest implements Runnable {
public enum RadioOptions {
Forward, Backward, Left, Right
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new RadioMenuTest());
}
@Override
public void run() {
JFrame frame = new JFrame("RadioMenu Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
RadioMenu<RadioOptions> optionsMenu = new RadioMenu<RadioOptions>("Options");
optionsMenu.generateButtonsFromEnum(RadioOptions.class);
fileMenu.add(optionsMenu);
return menuBar;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T09:01:49.893",
"Id": "520095",
"Score": "1",
"body": "may i ask if you are allowed to use `RadioOptions[] values = RadioOptions.values();` ? doing so you could directly add all possible values (i don't know your assets)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T09:09:58.770",
"Id": "520096",
"Score": "1",
"body": "Doing so would result in the following lines int the `main` method: `optionsMenu.generateButtonsFromEnum(RadioOptions.values());`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T08:44:14.290",
"Id": "520370",
"Score": "1",
"body": "it is not possible to know the **`class T`** of the **`type T`** at compile time. hence you have to provide either the **class T** (as you did) or you provide one (or more) **instance(s)** of T as suggested by `enum.values()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T13:25:13.340",
"Id": "520382",
"Score": "0",
"body": "@MartinFrank Ah, figured that was the case but nice to hear confirmation. Yeah, if the method is going to require a parameter no matter what it would make more sense to just pass the Enum values directly huh? Was just hoping there might be a way to avoid a parameter since the generic would be referencing the Enum anyways and it's members should be static if I recall correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T07:46:44.250",
"Id": "520456",
"Score": "0",
"body": "very nice code at all"
}
] |
[
{
"body": "<h2>dependency injection</h2>\n<p>with the feedback from your comments i would provide those <code><T extends Enum<T>></code> that you want to use already in your constructor. That would remove the <em>not-so-handy</em> method <code>generateButtonsFromEnum</code>.</p>\n<pre><code>public enum RadioOptions {Forward, Backward, Left, Right}\nRadioMenu<RadioOptions> optionsMenu = new RadioMenu<>(RadioOptions.values());\noptionsMenu.setText("Options")\n</code></pre>\n<p>doing so it would also let you create a <strong>reduced</strong> menu if you don't want to use all enum values:</p>\n<pre><code>public enum RadioOptions {Forward, Backward, Left, Right}\nRadioOptions[] leftRight = {RadioOptions.Left, RadioOptions.Right} \nRadioMenu<RadioOptions> optionsMenu = new RadioMenu<>(leftRight);\noptionsMenu.setText("Options")\n</code></pre>\n<p>Such an constructor you would provide an instance of T (as suggested in the comments).</p>\n<h2>Note</h2>\n<p>have a look at <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/EnumMap.html\" rel=\"nofollow noreferrer\"><code>EnumMap</code></a> a specialized map for storing/accessings Enums.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T13:25:21.407",
"Id": "520489",
"Score": "1",
"body": "Hit a snag with `EnumMap` where it requires the Class in the constructor (but I still like it, thanks for the tip). As a result, ended up with a compromise based on this advise where I pass the Class to the constructor and keep a `generateButtons()` method with a `generateButtons(E[] enumValues)` overload variant for generating using a array to keep the flexibility of generating using a subset. Opted to keep a `generateButtons()` method because I prefer that being explicitly executed instead of assumed behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T14:05:52.410",
"Id": "520498",
"Score": "1",
"body": "you made some good points =) a Review is very valuable to those who want to improve their skills and very rarely there is a plain *right/wrong* answer - thanks for sharing your thoughts!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T04:09:07.793",
"Id": "263610",
"ParentId": "263425",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T19:48:00.380",
"Id": "263425",
"Score": "1",
"Tags": [
"java",
"swing",
"enum",
"awt"
],
"Title": "Generate and Control JMenu Radio Buttons Using An Enum"
}
|
263425
|
<p>I have a function which checks for a profile name and determines if it is in a tagged profile name.</p>
<pre><code>def check_profiles(request):
try:
# get all individual profiles
profiles = Profile.objects.all()
# get all individual tagged profiles
tagged_profiles = TaggedProfiles.objects.all()
# ids to exclude in adding dates
exclude_profiles = []
# for profile in profiles
for profile in profiles:
# for tagged in sdn list
for tagged_profile in tagged_profiles:
# if contains 1
if any(name in tagged_profile.name_breakdown() for name in profile.name_breakdown()):
# put in exclude
exclude_profiles.append(profile.pk)
profile.status = 'FOR REVIEW'
profile.save()
break
for profile in Profile.objects.all().exclude(pk__in = exclude_profiles):
cleared_dates = profile.cleared_dates
cleared_dates.append(
{
'date': datetime.now().strftime('%Y-%m-%d'),
'time': datetime.now().strftime('%I:%M %p')
})
logger.debug(cleared_dates)
profile.cleared_dates = cleared_dates
profile.save()
except Exception as e:
logger.error(e)
</code></pre>
<p>Basically, if a profile's name is <code>'firstname lastname'</code>, it's breakdown is <code>['firstname', 'lastname']</code>. And if <code>tagged_profiles</code> include either a <code>'firstname'</code> or a <code>'lastname'</code> in any of it's breakdowns, it's a hit.</p>
<p>But I'm doing it very inefficiently. How may I optimize it with any of django's built in functions?</p>
<p>You can see it <a href="https://www.online-python.com/NxH6svWAOJ" rel="nofollow noreferrer">here</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T19:50:28.657",
"Id": "263426",
"Score": "1",
"Tags": [
"performance",
"django"
],
"Title": "Check if Profile name is contained in Tagged Profile names: added link"
}
|
263426
|
<p>In order to reduce time complexity, instead of loading (and then dumping to use it for later) the whole file into an array (It would be O(n) with n=number of lines), I have saved it as array into a PHP file and included it</p>
<p><strong>index.php</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
include "english.php";
$test = new English("false_friend.php");
?>
</code></pre>
<p><strong>english.php</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
class English {
private $dict;
private $lib;
private $size;
private $f;
public function __construct($lib) {
include $lib; //instead of reading the whole text file I save it into an array which is saved in a PHP FILE
$this->lib = $lib;
$this->dict = $dict;
$this->size = filesize($lib);
$this->f = fopen($this->lib, "r+"); //it's a pointer in order to modify my "phisical" library for later
}
public function search($key) {} //future function
public function delete($key) {} //future function
public function insert($key, ...$values) {
if (!isset($this->dict[$key])) {
fseek($this->f, $this->size - 4);
$array = '" => [';
foreach ($values as $value) { $array = $array.'"'.$value.'",'; }
$array = substr_replace($array, "],", -1);
fwrite($this->f, ' "'.$key.$array.PHP_EOL.');?>');
$this->size = filesize($this->lib);
$this->dict[$key] = [...$values];
}
}
}?>
</code></pre>
<p><strong>false_friend.php</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
$dict = array(
"eventually" => ["alla fine","possibly"],
"commodity" => ["merce","comfort"],
);?>
</code></pre>
<p>In this way, since I use a pointer, insertion's time complexity is O(1) //I edit the last 4 bytes by adding the new content, I dont affect previous ones</p>
<p>search'complexity is O(1) as well, but a "delete() function" could have in worst case time complexity of O(n). If I had milions of lines, it would not be a great deal.
<strong>My goal is editing the array I've included instead of editing the file of included array</strong>, maybe implementing array as MinHeap which insertion, search and deletion have time complexity of O(logn)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T00:29:16.807",
"Id": "520068",
"Score": "2",
"body": "Splatpacking is not more efficient versus `array_values()`. https://stackoverflow.com/q/57725811/2943403 ...do you need to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T02:36:25.657",
"Id": "520072",
"Score": "0",
"body": "Any concerns regarding simultaneous file read/writing? https://stackoverflow.com/q/46016784/2943403 Am I reading your script correct that you are maintaining a persistent connection to file (`fopen()`) while other processes will determine what needs to happen to the file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T08:46:33.960",
"Id": "520089",
"Score": "0",
"body": "@mickmackusa the problem is: if I had to remove the first key, I would be forced to edit the whole file (=> O(n) ) since I don't know how to permamently edit the array I included. My goal is: taken (or included) an array, edit it without edit the file"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T08:51:40.160",
"Id": "520090",
"Score": "0",
"body": "@mickmackusa add this snippet in index.php `$test->insert(\"hello\",\"dog\"); print_r($test);` Refresh index.php and you'll notice you added `hello dog` in false_friend dict. But I didn't work on the array, I worked on the file. I'm trying to avoid it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T08:51:47.240",
"Id": "520091",
"Score": "1",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T20:59:41.300",
"Id": "263429",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"array"
],
"Title": "editing the array I've included instead of editing the file of included array php"
}
|
263429
|
<p>In a recruitment process, the company gives me a project to do in react native. I finished all the tasks. But company gave me a feedback and said that your project was good, but you did not <strong>apply best practices for using rest api</strong>. So we are not proceeding further with your application. I used redux with rest api. Below is the code of one screen. Please review it and suggest me how can I improve it</p>
<pre><code>import React, {useState} from 'react';
import {View, StyleSheet, Alert} from 'react-native';
import {IconButton, TextInput, FAB} from 'react-native-paper';
import {useDispatch} from 'react-redux';
import Header from '../components/Header';
function AddCityScreen({navigation}) {
const [cityName, setCityName] = useState('');
const API_KEY = '799acd13e10b7a3b7cf9c0a8da6e5394';
const dispatch = useDispatch();
const citiesReducer = city => dispatch({type: 'ADD_CITY', payload: city});
const onSaveCity = () => {
getWeatherOfCity(cityName);
navigation.goBack();
};
const getWeatherOfCity = async city => {
try {
const result = await fetch(
`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`,
);
if (result.status === 200) {
const data = await result.json();
citiesReducer(data);
} else {
Alert.alert('Error', 'Something went wrong while adding city', [
{text: 'OK'},
]);
}
} catch (ex) {
Alert.alert('Error', 'Something went wrong while adding city', [
{text: 'OK'},
]);
}
};
return (
<>
<Header navigation={navigation} titleText="Add a new city" />
<IconButton
icon="close"
size={25}
color="white"
onPress={() => navigation.goBack()}
style={styles.iconButton}
/>
<View style={styles.container}>
<TextInput
label="Add City Here"
value={cityName}
mode="outlined"
onChangeText={setCityName}
style={styles.title}
/>
<FAB
style={styles.fab}
small
icon="check"
disabled={cityName == '' ? true : false}
onPress={() => onSaveCity()}
/>
</View>
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingHorizontal: 20,
paddingVertical: 20,
},
iconButton: {
backgroundColor: 'rgba(46, 113, 102, 0.8)',
position: 'absolute',
right: 0,
top: 40,
margin: 10,
},
title: {
fontSize: 24,
marginBottom: 20,
},
text: {
height: 300,
fontSize: 16,
},
fab: {
position: 'absolute',
margin: 20,
right: 0,
top: 150,
},
});
export default AddCityScreen;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T00:06:03.220",
"Id": "520064",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/263431/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T20:06:52.847",
"Id": "520197",
"Score": "0",
"body": "I'm not sure what they could mean here with \"applying rest api best practices\". Maybe they mean not exposing `API_KEY` and storing this using something like [react-native-keychain](https://github.com/oblador/react-native-keychain). Either way the variable could be defined outside the functional component scope. Apart from that I don't really see much wrong with what you've shown. Are you sure they found problems with this code specifically and not in some other piece of code?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T21:18:53.223",
"Id": "263431",
"Score": "0",
"Tags": [
"interview-questions",
"react.js",
"rest",
"redux",
"react-native"
],
"Title": "REST API in react native"
}
|
263431
|
<p>This is a scraper written to do most of what had been attempted by another user in this question:</p>
<p><a href="https://codereview.stackexchange.com/questions/263390/how-can-i-optimise-this-webscraping-code">How can I optimise this webscraping code</a></p>
<p>I did the rewrite because I felt bad that the new user didn't get an opportunity to talk about their code (even though the off-topic closure was correct). Also the site, as with so many others, is badly designed enough to be an interesting challenge. The design objective of this code is to scrape an arbitrary number of years and pages from OddsPortal without needing to involve a browser (i.e. Selenium).</p>
<p>On the balance, there are advantages and disadvantages to using Requests: when I lose the layer of abstraction provided by Selenium, I gain speed but also the code is probably more fragile given some of the hoops I have to jump through to decode their timestamp and odds formats. Any feedback welcome.</p>
<pre><code>import json
import re
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from pprint import pprint
from typing import Dict, Any, Tuple, Optional, Iterable
from urllib.parse import urljoin
from requests import Session
from bs4 import BeautifulSoup, Tag
BASE = 'https://www.oddsportal.com'
TERRIBLE_TIMESTAMP_PAT = re.compile(r'^t(\d+)-')
def decode_terrible_timestamp_class(tag: Tag) -> datetime:
for cls in tag['class']:
match = TERRIBLE_TIMESTAMP_PAT.search(cls)
if match:
break
else:
raise ValueError(f'{tag} does not seem to contain a valid timestamp')
stamp = int(match[1])
return datetime.fromtimestamp(stamp, tz=timezone.utc)
# Refer to https://www.oddsportal.com/res/x/global-210609145530.js
# this.d = function (str)
ODDS_TABLE = str.maketrans(
'axcteopzf',
'1234567.|',
)
def decode_terrible_odds(decorated: Tag) -> Tuple[float, Optional[float]]:
odds = decorated['xodd'].translate(ODDS_TABLE).split('|')
if len(odds) == 1:
return float(odds), None
preferred, normal = odds
return float(normal), float(preferred)
@dataclass
class GameData:
sport: str
sport_path: str
country: str
country_path: str
season: str
season_path: str
when: datetime
path: str
home_team: str
away_team: str
home_team_won: bool
away_team_won: bool
home_score: int
away_score: int
home_odds: float
home_odds_preferred: float
draw_odds: float
draw_odds_preferred: float
away_odds: float
away_odds_preferred: float
bookmakers: int
@classmethod
def from_tags(
cls,
sport: Tag,
country: Tag,
season: Tag,
date_span: Tag,
time: Tag,
teams: Tag,
score: Tag,
home_odds: Tag,
draw_odds: Tag,
away_odds: Tag,
bookmakers: Tag,
):
home_score, away_score = score.text.split(':')
when = datetime.combine(
decode_terrible_timestamp_class(date_span).date(),
decode_terrible_timestamp_class(time).time(),
tzinfo=timezone.utc,
)
team_anchor = teams.find('a')
any_span = team_anchor.find('span')
if any_span:
home_team, away_team = (
t.text if isinstance(t, Tag) else t.strip('- ')
for t in team_anchor.children
)
home_team_won, away_team_won = (
isinstance(t, Tag)
for t in team_anchor.children
)
else:
home_team, away_team = team_anchor.text.split('-')
home_team_won, away_team_won = False, False
home_odds_norm, home_odds_pref = decode_terrible_odds(home_odds)
draw_odds_norm, draw_odds_pref = decode_terrible_odds(draw_odds)
away_odds_norm, away_odds_pref = decode_terrible_odds(away_odds)
game = cls(
sport=sport.text.strip(),
sport_path=sport['href'],
country=country.text.strip(),
country_path=country['href'],
season=season.text.strip(),
season_path=season['href'],
when=when,
path=team_anchor['href'],
home_team=home_team,
away_team=away_team,
home_team_won=home_team_won,
away_team_won=away_team_won,
home_score=int(home_score),
away_score=int(away_score),
home_odds=home_odds_norm,
home_odds_preferred=home_odds_pref,
draw_odds=draw_odds_norm,
draw_odds_preferred=draw_odds_pref,
away_odds=away_odds_norm,
away_odds_preferred=away_odds_pref,
bookmakers=int(bookmakers.text),
)
return game
def start_search(session: Session, year: int) -> Dict[str, Any]:
url = urljoin(BASE, f'/soccer/england/premier-league-{year}-{year+1}/results/')
with session.get(url) as resp:
resp.raise_for_status()
doc = BeautifulSoup(resp.text, 'lxml')
script_pat = re.compile(r'new PageTournament\(')
for script in doc.select('body > script'):
match = script_pat.search(script.string)
if match:
break
else:
raise ValueError('ID script not found')
start = match.end()
end = script.string.find('}', start) + 1
json_str = script.string[start: end]
ids = json.loads(json_str)
return ids
def get_page(session: Session, sid: int, id: str, page: int) -> Iterable[GameData]:
bookie_hash = 'X0'
use_premium = 1
timezone_offset = 0
archive_url = urljoin(
BASE,
f'/ajax-sport-country-tournament-archive'
f'/{sid}'
f'/{id}'
f'/{bookie_hash}'
f'/{use_premium}'
f'/{timezone_offset}'
f'/{page}'
f'/'
)
with session.get(archive_url) as resp:
resp.raise_for_status()
start = resp.text.find('{')
end = resp.text.rfind('}') + 1
json_str = resp.text[start: end]
html = json.loads(json_str)['d']['html']
doc = BeautifulSoup(html, 'lxml')
head = doc.find('th')
sport, country, season = head.find_all('a')
for tr in doc.find_all('tr'):
date_header = tr.select_one('th[colspan="3"]')
if date_header:
date_span = date_header.find('span')
continue
if tr.select_one('td.table-time'):
yield GameData.from_tags(
sport, country, season, date_span,
*tr.find_all('td'),
)
def main():
with Session() as session:
session.headers = {'User-Agent': 'Mozilla/5.0'}
ids = start_search(session, year=2020)
for page in range(1, 3):
for game in get_page(session, ids['sid'], ids['id'], page):
pprint(asdict(game))
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T18:38:38.257",
"Id": "520135",
"Score": "0",
"body": "What are your objectives? Your code looks quite WET, and the use of a single god class looks questionable. You could probably have more maintainable code by using `dataclasses.field` and a very 'meta programming' approach with untyped/partially typed input. However I think such an approach would conflict with your objectives."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T03:19:13.327",
"Id": "520952",
"Score": "0",
"body": "This is great however the code looks to be customised for just one URL. `f'/soccer/england/premier-league-{year}-{year+1}/results/'` While there are more than one competitions covered by the webiste. Can we edit the code to accomodate more than one competitions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T03:21:32.210",
"Id": "520953",
"Score": "0",
"body": "@PyNoob Yes - just add the path as a parameter to `start_search`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-24T22:27:42.993",
"Id": "263433",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"rags-to-riches"
],
"Title": "Scraping OddsPortal with requests only"
}
|
263433
|
<p>This is my first C program. The code works, however I'm not yet familiar with how to write <em>idiomatic</em> C. How should I improve this?</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define UNCLICKED 0
#define CLICKED 1
#define FLAGGED 2
#define NOT_BOMB 0
#define BOMB 1
struct piece {
char user_state, game_state, value;
};
int generate_rand();
int valid(int, int);
void print_board(struct piece[8][8], int);
int click(struct piece[8][8], int, int);
int game_over(struct piece[8][8]);
int main() {
struct piece board[8][8];
int i, j;
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
board[i][j].user_state = UNCLICKED;
board[i][j].game_state = NOT_BOMB;
board[i][j].value = 0;
}
}
srand(time(0));
int num_bombs = 10;
while (num_bombs > 0) {
int y, x;
do {
y = generate_rand();
x = generate_rand();
} while (board[y][x].game_state == BOMB);
board[y][x].game_state = BOMB;
int delta_row, delta_column;
for (delta_row = -1; delta_row <= 1; delta_row++) {
for (delta_column = -1; delta_column <= 1; delta_column++) {
if (valid(y + delta_row, x + delta_column)) {
board[y + delta_row][x + delta_column].value++;
}
}
}
num_bombs--;
}
print_board(board, 1);
while (1) {
char row, column, move_type;
printf("\nEnter a row: ");
row = getchar() - 48;
getchar();
printf("Enter a column: ");
column = getchar() - 48;
getchar();
if (!valid(row, column)) {
printf("Location is not on board. Try again: \n");
continue;
}
if (board[row][column].user_state == CLICKED) {
printf("That square is already open. Try again: \n");
continue;
}
printf("[C]lick or [F]lag? ");
move_type = getchar();
getchar();
printf("\n");
if (move_type == 'C') {
if (click(board, row, column)) {
printf("That was a bomb! \n");
print_board(board, 0);
break;
}
} else if (move_type == 'F') {
if (board[row][column].user_state == CLICKED) {
printf("That square is already open. Try again: \n");
continue;
} else {
board[row][column].user_state = FLAGGED;
}
} else {
printf("Enter either 'C' or 'F'. Try again: \n");
continue;
}
if (game_over(board)) {
printf("You win! \n");
print_board(board, 0);
break;
} else {
print_board(board, 1);
}
}
return 0;
}
int generate_rand() {
return (rand() % 8);
}
int valid(int row, int column) {
return row >= 0 && row < 8 && column >= 0 && column < 8;
}
void print_board(struct piece board[8][8], int in_game) {
int i, j;
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
if (in_game) {
if (board[i][j].user_state == CLICKED) {
printf("%d ", board[i][j].value);
} else if (board[i][j].user_state == FLAGGED) {
printf("F ");
} else {
printf("- ");
}
} else {
if (board[i][j].game_state == NOT_BOMB) {
if (board[i][j].user_state == FLAGGED) {
printf("X ");
} else {
printf("%d ", board[i][j].value);
}
} else {
printf("B ");
}
}
}
printf("\n");
}
}
int click(struct piece board[8][8], int row, int column) {
if (!valid(row, column) || board[row][column].game_state == BOMB || board[row][column].user_state == CLICKED) {
return 1;
}
board[row][column].user_state = CLICKED;
if (board[row][column].value == 0) {
int i, j;
for (i = -1; i <= 1; i++) {
for (j = -1; j <= 1; j++) {
click(board, row + i, column + j);
}
}
}
return 0;
}
int game_over(struct piece board[8][8]) {
int i, j;
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
if (board[i][j].game_state == NOT_BOMB && board[i][j].user_state == UNCLICKED) {
return 0;
}
}
}
return 1;
}
</code></pre>
<p>Would it make sense to put some of the code in a separate header file, or is that over complicating things?</p>
|
[] |
[
{
"body": "<p>One thing that strikes me immediately is that we pass <code>struct piece board[8][8]</code> around quite a lot. There's two things I would change there. The first is to use a typedef (or perhaps a small struct) to save all that typing. The other would be to give names to the dimensions.</p>\n<pre><code>#define BOARD_WIDTH 8\n#define BOARD_HEIGHT 8\n\ntypedef struct piece game_board[BOARD_HEIGHT][BOARD_WIDTH];\n</code></pre>\n<p>If we want to build the game for a different height and width, then there will be only one place to change (once the loop bounds are adjusted to use the defined macros instead of literal <code>8</code>). And we've made it easier if we ever want to transition to runtime-chosen board size in future (that's a more advanced exercise that you should try when you feel ready for it).</p>\n<p>The typedef means that instead of writing out function arguments like</p>\n<pre><code>void print_board(const struct piece board[BOARD_HEIGHT][BOARD_WIDTH], int in_game);\n</code></pre>\n<p>they can be shorter and clearer:</p>\n<pre><code>void print_board(const game_board board, int in_game);\n</code></pre>\n<hr />\n<p>There's some weaknesses here:</p>\n<blockquote>\n<pre><code> printf("\\nEnter a row: ");\n row = getchar() - 48;\n getchar();\n printf("Enter a column: ");\n column = getchar() - 48;\n getchar();\n</code></pre>\n</blockquote>\n<p>Remember that any call to <code>getchar()</code> can return <code>EOF</code>. If that happens, we'll probably want to terminate the program, as we can't expect any useful input from that point onwards.</p>\n<p>Secondly, the magic number <code>48</code> is specific to the character coding in use - we can make the program more portable by using <code>'0'</code> as is evidently intended.</p>\n<p>It's also quite fragile - we're expecting a single character and newline, but users make mistakes and might enter multiple characters (and we'd probably want to allow that if we make the board bigger than 10✕10).</p>\n<p>Thankfully, we have a better alternative to char-by-char input, and that's <em>formatted input</em> using <code>scanf()</code>. That would look something like</p>\n<pre><code> printf("\\nEnter a row and column: ");\n while (scanf("%hhd%hhd", &row, &column) != 2) {\n if (feof(stdin)) {\n /* scanf can never succeed now */\n fputs("Input failure\\n", stderr);\n return EXIT_FAILURE;\n }\n /* Discard any remaining input */\n scanf("%*[^\\n]"); /* ignore errors here */\n printf("Invalid input. Enter a row and column: ");\n }\n</code></pre>\n<p>That's not 100% robust, but it's an improvement.</p>\n<hr />\n<p>A small fix: these function declarations should be <em>prototypes</em>, i.e. specify what arguments they take:</p>\n<blockquote>\n<pre><code>int generate_rand();\n\nint main() {\n</code></pre>\n</blockquote>\n<p>The way we tell the compiler that they take no arguments at all (rather than unspecified arguments) is to write <code>void</code> between the parentheses:</p>\n<pre><code>int generate_rand(void);\n\nint main(void) {\n</code></pre>\n<hr />\n<p>The structure is a bit unbalanced. There are a few low-level functions, but most of the logic is in a huge <code>main()</code>. Try dividing it into high-level functions - perhaps <code>initialise_board()</code> could be one of them?</p>\n<hr />\n<p>There are more things that could be improved, but I hope this gives you some things to consider.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T12:59:06.427",
"Id": "520104",
"Score": "0",
"body": "What does `typedef struct piece game_board[BOARD_HEIGHT][BOARD_WIDTH];` do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T13:27:32.930",
"Id": "520110",
"Score": "0",
"body": "@ap It creates a type that you can use and that reduces the amount of code necessary in function declarations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T14:34:46.643",
"Id": "520113",
"Score": "1",
"body": "@ap: Yes, as pacmaninbw says, it makes the code shorter, and clearer - see latest edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T17:32:50.200",
"Id": "520408",
"Score": "1",
"body": "@ap see https://en.cppreference.com/w/c/language/typedef and bookmark that site so you can easily look things up in the future."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T08:39:10.047",
"Id": "263447",
"ParentId": "263436",
"Score": "4"
}
},
{
"body": "<p>Some style suggestions:</p>\n<ol>\n<li><p>Use enums instead of #defines.</p>\n<pre><code>enum {\n state_UNCLICKED,\n state_CLICKED,\n state_FLAGGED\n} ;\n</code></pre>\n</li>\n</ol>\n<p>Followed by <code>if (board[i][j].user_state == state_CLICKED)</code></p>\n<ol start=\"2\">\n<li>It's easier to understand structure definitions if each member is on its own line.</li>\n</ol>\n<pre><code>struct piece {\n char user_state;\n char game_state;\n char value;\n};\n</code></pre>\n<ol start=\"3\">\n<li><p>Generally it's nice to put argument names in function declarations. Then readers don't need to jump to the implementation to find out what the arguments mean.</p>\n</li>\n<li><p>I might refactor</p>\n</li>\n</ol>\n<pre><code> board[i][j].user_state = UNCLICKED;\n board[i][j].game_state = NOT_BOMB;\n board[i][j].value = 0;\n</code></pre>\n<p>into a <code>board_square_init(board, i,j)</code> function. I might also create a <code>square_place_bomb(board, i,j)</code> function that does the neighbor update.</p>\n<ol start=\"5\">\n<li><p>It's odd that <code>click</code> returns <code>1</code> for several unrelated things: out of bounds, already clicked, and bomb. You are getting away with it because you pre-test for clicked before calling this function, but it would be cleaner if you returned a different value for the different failures. Maybe add <code>state_INVALID</code> to the enum in comment 1, and return a member of the enum.</p>\n</li>\n<li><p>Many people dislike globals in C, and there are some good reasons for that. But unless you are planning on writing a program that manages multiple boards at once, you could just declare the single board once globally, and stop passing it to every single function. You trade a potentially useful future capability of multiple board support for simpler code today.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T00:18:08.667",
"Id": "263568",
"ParentId": "263436",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263447",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T00:59:41.120",
"Id": "263436",
"Score": "5",
"Tags": [
"beginner",
"c",
"minesweeper"
],
"Title": "Text Based Minesweeper in C"
}
|
263436
|
<p>Below is my implementation of a persistent red black tree in Rust.</p>
<p>I have a few questions about potential improvements.
Currently the data and nodes are stored in referenced counted pointers. Is this the best way to do it?</p>
<p>On a similar note, the pattern matching statements for the balance functions are quite verbose because of the use of rc. Is there a way to write it more concisely?</p>
<p>Also, because I use rc pointers, should I implement the drop trait?</p>
<pre class="lang-rust prettyprint-override"><code>#[allow(clippy::module_inception)]
pub mod red_black_tree {
use std::cmp::Ordering;
use std::rc::Rc;
pub enum RedBlackTree<T>
where
T: Ord,
{
Node {
color: Color,
data: Rc<T>,
left: Rc<RedBlackTree<T>>,
right: Rc<RedBlackTree<T>>,
},
Leaf,
}
#[derive(Clone)]
pub enum Color {
Red,
Black,
}
impl<T> RedBlackTree<T>
where
T: Ord,
{
pub fn new() -> Self {
RedBlackTree::Leaf
}
pub fn contains(&self, item: T) -> bool {
match self {
RedBlackTree::Node {
color: _,
data,
left,
right,
} => match item.cmp(&data) {
Ordering::Less => left.contains(item),
Ordering::Equal => true,
Ordering::Greater => right.contains(item),
},
RedBlackTree::Leaf => false,
}
}
pub fn insert(&self, item: T) -> Self {
match self {
RedBlackTree::Node {
color,
data,
left,
right,
} => match item.cmp(&data) {
Ordering::Less => RedBlackTree::Node {
color: color.clone(),
data: Rc::clone(data),
left: Rc::new(left.insert(item)),
right: Rc::clone(right),
}
.balance()
.make_black(),
Ordering::Equal => RedBlackTree::Node {
color: color.clone(),
data: Rc::clone(data),
left: Rc::clone(left),
right: Rc::clone(right),
}
.make_black(),
Ordering::Greater => RedBlackTree::Node {
color: color.clone(),
data: Rc::clone(data),
left: Rc::clone(left),
right: Rc::new(right.insert(item)),
}
.balance()
.make_black(),
},
RedBlackTree::Leaf => RedBlackTree::Node {
color: Color::Black,
data: Rc::new(item),
left: Rc::new(RedBlackTree::new()),
right: Rc::new(RedBlackTree::new()),
},
}
}
pub fn get(&self, item: &T) -> Option<Rc<T>> {
match self {
RedBlackTree::Node {
color: _,
data,
left,
right,
} => match item.cmp(&data) {
Ordering::Less => left.get(item),
Ordering::Equal => Option::from(Rc::clone(data)),
Ordering::Greater => right.get(item),
},
RedBlackTree::Leaf => Option::None,
}
}
fn make_black(&self) -> Self {
match self {
RedBlackTree::Node {
color: _,
data,
left,
right,
} => RedBlackTree::Node {
color: Color::Black,
data: Rc::clone(data),
left: Rc::clone(left),
right: Rc::clone(right),
},
RedBlackTree::Leaf => RedBlackTree::new(),
}
}
fn balance(self) -> Self {
if let RedBlackTree::Node {
color: Color::Black,
data: parent_data,
left: parent_left,
right: parent_right,
} = &self
{
if let RedBlackTree::Node {
color: Color::Red,
data: child_data,
left: child_left,
right: child_right,
} = Rc::as_ref(&parent_left)
{
if let RedBlackTree::Node {
color: Color::Red,
data: grandchild_data,
left: grandchild_left,
right: grandchild_right,
} = Rc::as_ref(&child_left)
{
return RedBlackTree::from(
grandchild_left,
grandchild_right,
child_right,
parent_right,
grandchild_data,
child_data,
parent_data,
);
} else if let RedBlackTree::Node {
color: Color::Red,
data: grandchild_data,
left: grandchild_left,
right: grandchild_right,
} = Rc::as_ref(&child_right)
{
return RedBlackTree::from(
child_left,
grandchild_left,
grandchild_right,
parent_right,
child_data,
grandchild_data,
parent_data,
);
}
} else if let RedBlackTree::Node {
color: Color::Red,
data: child_data,
left: child_left,
right: child_right,
} = Rc::as_ref(&parent_right)
{
if let RedBlackTree::Node {
color: Color::Red,
data: grandchild_data,
left: grandchild_left,
right: grandchild_right,
} = Rc::as_ref(&child_left)
{
return RedBlackTree::from(
parent_left,
grandchild_left,
grandchild_right,
child_right,
parent_data,
grandchild_data,
child_data,
);
} else if let RedBlackTree::Node {
color: Color::Red,
data: grandchild_data,
left: grandchild_left,
right: grandchild_right,
} = Rc::as_ref(&child_right)
{
return RedBlackTree::from(
parent_left,
child_left,
grandchild_left,
grandchild_right,
parent_data,
child_data,
grandchild_data,
);
}
}
}
self.clone()
}
#[allow(clippy::many_single_char_names)]
fn from(
a: &Rc<RedBlackTree<T>>,
b: &Rc<RedBlackTree<T>>,
c: &Rc<RedBlackTree<T>>,
d: &Rc<RedBlackTree<T>>,
x: &Rc<T>,
y: &Rc<T>,
z: &Rc<T>,
) -> RedBlackTree<T> {
RedBlackTree::Node {
color: Color::Red,
data: Rc::clone(y),
left: Rc::new(RedBlackTree::Node {
color: Color::Black,
data: Rc::clone(x),
left: Rc::clone(a),
right: Rc::clone(b),
}),
right: Rc::new(RedBlackTree::Node {
color: Color::Black,
data: Rc::clone(z),
left: Rc::clone(c),
right: Rc::clone(d),
}),
}
}
}
impl<T> Clone for RedBlackTree<T>
where
T: Ord,
{
fn clone(&self) -> Self {
match self {
RedBlackTree::Node {
color,
data,
left,
right,
} => RedBlackTree::Node {
color: color.clone(),
data: Rc::clone(data),
left: Rc::clone(left),
right: Rc::clone(right),
},
RedBlackTree::Leaf => RedBlackTree::new(),
}
}
}
impl<T> Default for RedBlackTree<T>
where
T: Ord,
{
fn default() -> Self {
RedBlackTree::<T>::new()
}
}
}
#[cfg(test)]
mod tests {
use super::red_black_tree::*;
use std::cmp::*;
struct Point {
x: i64,
y: i64,
}
impl Point {
fn new(x: i64, y: i64) -> Point {
Point { x, y }
}
fn magnitude_squared(&self) -> u64 {
(self.x as u64).pow(2) + (self.y as u64).pow(2)
}
}
impl PartialEq for Point {
fn eq(&self, other: &Self) -> bool {
self.magnitude_squared() == other.magnitude_squared()
}
}
impl Eq for Point {}
impl PartialOrd for Point {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Point {
fn cmp(&self, other: &Self) -> Ordering {
self.magnitude_squared().cmp(&other.magnitude_squared())
}
}
#[test]
fn test_empty() {
let tree = RedBlackTree::<i64>::new();
assert!(!tree.contains(0));
assert!(!tree.contains(5));
assert!(!tree.contains(-20));
}
#[test]
fn test_insert() {
let mut tree: RedBlackTree<char> = RedBlackTree::new();
assert!(!tree.contains('a'));
assert!(!tree.contains('b'));
assert!(!tree.contains('c'));
tree = tree.insert('a');
assert!(tree.contains('a'));
assert!(!tree.contains('b'));
assert!(!tree.contains('c'));
tree = tree.insert('b');
assert!(tree.contains('a'));
assert!(tree.contains('b'));
assert!(!tree.contains('c'));
}
#[test]
fn test_get() {
let mut tree: RedBlackTree<Point> = RedBlackTree::new();
tree = tree.insert(Point::new(0, 0));
tree = tree.insert(Point::new(1, 1));
tree = tree.insert(Point::new(2, 2));
tree = tree.insert(Point::new(3, 4));
assert_eq!(tree.get(&Point::new(0, 0)).unwrap().x, 0);
assert_eq!(tree.get(&Point::new(0, 0)).unwrap().y, 0);
assert_eq!(tree.get(&Point::new(0, 5)).unwrap().x, 3);
assert_eq!(tree.get(&Point::new(0, 5)).unwrap().y, 4);
}
}
</code></pre>
<p>Edit: the rebalancing function relies is based on this diagram (<a href="https://abhiroop.github.io/images/Insertion.jpg" rel="nofollow noreferrer">source</a>):</p>
<p><a href="https://i.stack.imgur.com/pLOKA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pLOKA.jpg" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T04:08:39.957",
"Id": "520158",
"Score": "0",
"body": "Is there a reason for `#[allow(clippy::module_inception)]`? Generally, when a lint is triggered, we fix the code rather than disable the lint. The same goes for `#[allow(clippy::many_single_char_names)]`. I'm scared at `from(a, b, c, d, x, y, z)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T15:43:01.113",
"Id": "520171",
"Score": "0",
"body": "@L.F. for module_inception, I'm relatively new to cargo and this structure was just for practice, so I thought it would be easier to just use the same name for the project and module. For the ```from(a, b, c, d, x, y, z)``` function, I was following various guides that all used that naming scheme. I've attached at image explaining it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T01:21:12.747",
"Id": "520205",
"Score": "0",
"body": "Right now you are defining `red_black_tree::red_black_tree::RedBlackTree`. The correct way is to simply remove the `mod` declaration (the file is automatically a module)."
}
] |
[
{
"body": "<p>In Rust, we don't usually create the style of object where the mutation functions return new objects. Even if the internal data structure is persistent, it fits better in Rust style to have mutating functions. So your insert function might be something more like this:</p>\n<pre><code> pub fn insert(&mut self, item: T) {\n match self {\n RedBlackTree::Node {\n color,\n data,\n left,\n right,\n } => match item.cmp(&data) {\n Ordering::Less => {\n Rc::make_mut(&mut self.left).insert(item);\n self.balance();\n self.make_black();\n }\n Ordering::Equal => {\n self.make_black();\n }\n Ordering::Greater => {\n Rc::make_mut(&mut self.right).insert(item)\n self.balance();\n self.make_black();\n }\n },\n RedBlackTree::Leaf => *self = RedBlackTree::Node {\n color: Color::Black,\n data: Rc::new(item),\n left: Rc::new(RedBlackTree::new()),\n right: Rc::new(RedBlackTree::new()),\n },\n }\n }\n</code></pre>\n<p>The special sauce here is <code>Rc::make_mut</code>. It takes a mutable reference to an <code>Rc<T></code> and gives you a <code>*mut T</code>. It modifies the exist item in place if it isn't shared, but if it shared it gives you a clone. This gives you the benefit of persistent data structures, clones are cheap, but still lets you avoid cloning when you don't need to.</p>\n<blockquote>\n<p>Currently the data and nodes are stored in referenced counted\npointers. Is this the best way to do it?</p>\n</blockquote>\n<p>If you need a persistent data structure,then probably yes.</p>\n<blockquote>\n<p>On a similar note, the pattern matching statements for the balance\nfunctions are quite verbose because of the use of rc. Is there a way\nto write it more concisely?</p>\n</blockquote>\n<p>A big thing that would help is to move RedBlackTree::Node into its own struct. Then you could match the struct as a whole instead of the individual fields.</p>\n<blockquote>\n<p>Also, because I use rc pointers, should I implement the drop trait?</p>\n</blockquote>\n<p>No, Rust will automatically implement the Drop trait, and the drop the rcs for you. Its pretty rare to want to implement Drop yourself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-14T03:56:40.040",
"Id": "264037",
"ParentId": "263438",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T01:06:58.223",
"Id": "263438",
"Score": "4",
"Tags": [
"beginner",
"algorithm",
"rust",
"memory-management"
],
"Title": "Rust Persistent Red Black Tree Implementation"
}
|
263438
|
<p>In the code below, the primary purpose of <code>class MyRNG</code> is to create a single method <code>getMyRandom()</code> that will return a random number from any of several very different distributions and generators. The actual distribution and generator will be determined by information read from a file, although in the test program below, the information is simply stated in <code>main()</code> at the point where the call to <code>MyRNG()</code> occurs. In the code as it stands, a line (read from a file, console or command line) is parsed to extract the type of RNG wanted and the parameters for the distribution. Distributions are limited in the sample code to a Gaussian distribution, uniform distribution, and random choice</p>
<p>I think that the code is <em><strong>horrible</strong></em> (not surprising given that I'm an OOP novice) in that I use an <code>enum</code> to signal which kind of RNG I really want, and then I use <code>switch</code> statements to ensure that <code>getMyRandom()</code> actually calls the correct kind of basic generator. I <em>think</em> I should be able to solve in another way! I have been reading about design patterns and I've convinced myself that it should be possible to greatly improve the code by using either Factory Method or Abstract Factory but I cannot see how to do it.</p>
<p>Questions that I'm struggling with ...</p>
<ul>
<li>What design pattern should I be focusing on?</li>
<li>Most importantly for my understanding, what would a sketch of that design pattern look like in the context of my problem</li>
<li>At the moment I have "this.rng = new Random()" within <code>class MyRNG</code> class where (I believe) it is called for each new MyRNG object. Does this make sense or should it be somewhere else, either in the code as it stands or in a relevant design pattern.</li>
<li>Where should the parsing of the RNG description go?</li>
</ul>
<pre><code>import java.util.Random;
class MyRNG {
// The DistributionType enum is used to keep track of the particular kind of RNG that
// we want so that the appropriate specific method can be called by the intermediary
// getMyRandom() method.
enum DistributionType {
UNIFORMDOUBLE, // Types of distribution to account for. ** VERY **Incomplete list.
GAUSSIAN,
CHOICE
};
Random rng;
DistributionType iAmThisTypeOfRNG; // Keeps track of what kind of RNG is ultimately called
String description;
// Constructor
public MyRNG (String description) {
this.rng = new Random();
this.description = description;
// Parse the description to determine what kind of RNG is really wanted
if (description.matches("UNIFORMDOUBLE +-?\\d+\\.?\\d+ +-?\\d+\\.?\\d+")) {
// For doubles on a unform distribution use UNIFORMDOUBLE lowerbound upperbound
// ... UNIFORMDOUBLE 18.3 22.2
this.iAmThisTypeOfRNG = DistributionType.UNIFORMDOUBLE;
} else if (description.matches("GAUSSIAN +\\d+\\.?\\d+ +\\d+\\.?\\d+")) {
// For Gaussian distribution use GAUSSIAN mean std
// ... GAUSSIAN 2.0 3.5
this.iAmThisTypeOfRNG = DistributionType.GAUSSIAN;
} else if (description.matches("CHOICE -?\\d+\\.?\\d+( +-?\\d+\\.?\\d+)*")) {
// For CHOICE distribution use CHOICE n1 n2 ...
// ... CHOICE 4.6 -2.35 1.8 -4.0 -1.9
this.iAmThisTypeOfRNG = DistributionType.CHOICE;
} else {
System.out.println("Error: Could not parse parameter string: " + description);
}
}
public double getMyRandom() {
double myRand;
double[] parameters = parametersFromDescription(description);
switch (iAmThisTypeOfRNG) {
case UNIFORMDOUBLE: // double on uniform distribution
myRand = myNextUniformDouble(rng, parameters);
// Next line for debugging info only
System.out.println("Parsed UNIFORMDOUBLE with description: " + description);
break;
case GAUSSIAN: // doubles from Gaussian distribution
myRand = myNextGaussian(rng, parameters);
// Next line for debugging info only
System.out.println("Parsed GAUSSIAN with description: " + description);
break;
case CHOICE: // Random choice from a list of doubles
myRand = myNextChoice(rng, parameters);
// Next line for debugging info only
System.out.println("Parsed CHOICE with description: " + description);
break;
default:
myRand = 0;
System.out.println("Non-existent kind of random string requested.");
}
return myRand;
}
public String toString() {
return "This MyRNG object has kind: " + iAmThisTypeOfRNG;
}
static double[] parametersFromDescription(String description) {
String[] parameterString = description.split("\s+");
double [] parameters = new double[parameterString.length - 1];
int j = 0;
for (int i = 1; i < parameterString.length; i++) {
parameters[j] = Double.parseDouble(parameterString[i]);
j++;
}
return parameters;
}
static double myNextUniformDouble(Random rng, double[] parameters) {
double lowerBound = parameters[0];
double upperBound = parameters[1];
return (upperBound-lowerBound) * rng.nextDouble() + lowerBound;
}
static double myNextChoice(Random rng, double[] parameters) {
int selection = rng.nextInt(parameters.length);
return parameters[selection];
}
static double myNextGaussian(Random rng, double[] parameters) {
double mean = parameters[0];
double standardDeviation = parameters[1];
return standardDeviation * rng.nextGaussian() + mean;
}
}
public class Main {
public static void main(String[] args) {
MyRNG rsA = new MyRNG("GAUSSIAN 5.66 1.2");
System.out.println(rsA);
System.out.println("Result of getMyRandom on rsA is : " + rsA.getMyRandom());
System.out.println();
MyRNG rsB = new MyRNG("UNIFORMDOUBLE -2.0 2.0");
System.out.println(rsB);
System.out.println("Result of getMyRandom on rsB is : " + rsB.getMyRandom());
System.out.println();
MyRNG rsC = new MyRNG("CHOICE 2.0 4.0 6.0 8.0 10.0 12.0");
System.out.println(rsC);
System.out.println("Result of getMyRandom on rsC is : " + rsC.getMyRandom());
System.out.println(rsC.getMyRandom());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A lot of the time, if you want to group some objects by a type, the cleanest approach is... well, making <em>types</em>. Classes.</p>\n<p>It seems natural to me to start without the <code>enum</code>, instead beginning with <code>MyRNG</code> as an <code>interface</code>. The <code>MyRNG</code> <em>type</em> doesn't know anything about generating random numbers, but it can still demand that any object belonging to that type <em>does</em> know how to generate random numbers. Then you can easily add various distributions like</p>\n<pre><code>class GaussianRNG implements MyRNG {\n private final double mean;\n private final double standardDeviation;\n private final Random rng = new Random();\n\n public GaussianRNG(double mean, double standardDeviation) {\n this.mean = mean;\n this.standardDeviation = standardDeviation;\n }\n\n @Override\n public double getMyRandom() {\n return standardDeviation * rng.nextGaussian() + mean;\n }\n}\n</code></pre>\n<p>And thanks to subtyping, you can just go <code>MyRNG rng = new GaussianRNG(5.66, 1.2);</code>, even though <code>MyRNG</code> has no idea <code>GaussianRNG</code> exists! And when you want another distribution, you just add another subtype, and nobody necessarily needs updating.</p>\n<p>Now, you'll notice I kind of dropped the ability to pick a distribution type at runtime. But there's nothing saying you can't have that too! You're definitely allowed to have factory methods à la</p>\n<pre><code>public static MyRNG createRNG(DistributionType distribution, double[] parameters) {\n switch (distribution) {\n case UNIFORM_DOUBLE:\n if (parameters.length != 2) throw new IllegalArgumentException();\n return new UniformDoubleRNG(parameters[0], parameters[1]);\n case GAUSSIAN:\n if (parameters.length != 2) throw new IllegalArgumentException();\n return new GaussianRNG(parameters[0], parameters[1]);\n case CHOICE:\n return new ChoiceRNG(parameters);\n }\n}\n</code></pre>\n<p>or a variant of that which parses a <code>String</code>. Or both! After all, if you have the string parsing and you have that <code>createRNG</code>, connecting the two together should be simple:</p>\n<pre><code>public static MyRNG createRNG(String description) {\n DistributionType distributionType = typeFromDescription(description);\n double[] parameters = parametersFromDescription(description);\n return createRNG(distributionType, parameters);\n}\n</code></pre>\n<p>Note that the <code>DistributionType</code> never makes it into the <code>MyRNG</code>s themselves - they <em>don't</em> need an external <code>enum</code> to tell them what their type is, because information about their type is contained in, well, their <em>type</em>.</p>\n<p>Finally, I would like to point out a few more things about the way your current approach is implemented:</p>\n<ul>\n<li>It seems a bit strange to me that you call <code>parametersFromDescription</code> each time you fetch a random number. Wouldn't it be easier to just do that once during construction and store the parameters? That way you can even check during construction to make sure they're valid.</li>\n<li>On a related note, the <code>MyRNG</code> constructor writes an error message to <code>System.out</code>... but it doesn't actually tell the <em>program</em> that anything went wrong. It returns just fine, and whoever called it ends up with a <code>MyRNG</code> object and will probably assume it's valid and usable. Instead of printing an error message (which might not be something you want to do!) you should <code>throw</code> an exception of some sort to let the caller know that it <em>isn't</em> going to get anything sensible and it should figure out a way to deal with that (which might mean just displaying an error message to the user). Same for <code>getMyRandom</code>, its job isn't to display error messages to the user, its job is to return a random number - if for some reason it can't, it should <em>make it obvious</em> that it failed so the caller can handle it in whatever manner is appropriate. <code>throw</code>ing exceptions is a good way to do that.</li>\n<li>I don't see why the <code>myNextWhatever</code> methods are <code>static</code>. If they weren't, you wouldn't need to pass the <code>Random</code> as a parameter since you'd have access to <code>this.rng</code>. And perhaps <code>this.parameters</code> if you were to save the parameters as well</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T08:36:33.523",
"Id": "520087",
"Score": "1",
"body": "Many thanks Sara. I have yet to try out all the suggestions that you have made but I shall. I really appreciate the time you've taken for the *very extensive* comments and sample code. One of the things that your example immediately highlighted was a place where I've come unstuck. I hadn't understood that an interface can not only be implemented but that a new object can be created as a member of the interface. You have, for example \"MyRNG rng = new GaussianRNG(5.66, 1.2);\" I'd looked at an example here ( https://www.w3schools.com/java/java_interface.asp ) ... continued."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T08:42:15.267",
"Id": "520088",
"Score": "2",
"body": "But in in the w3schools example, despite an interface `Animal` being defined and implemented by `class Pig` ... when it comes to creating the Pig, the example actually makes a call to Pig, as in `Pig myPig = new Pig();` . It wasn't clear to me that the example could have used a generic Animal which then *happened* to be a Pig ... as in `Animal myAnimal = new Pig();` The thing I'll do now is work steadily through your example and then perhaps return to codereview later."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T04:01:22.727",
"Id": "263442",
"ParentId": "263439",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "263442",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T01:41:13.807",
"Id": "263439",
"Score": "6",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "Using a generic call to access different variations of a method"
}
|
263439
|
<p>This is a follow-up of my question over <a href="https://codereview.stackexchange.com/a/262830/242934">here</a>.</p>
<p>I am extending the functionality of @Reinderien's suggested code to enable the automatic looping through of pages in the search result.</p>
<p>I've mainly modified the final <code>search()</code> function (originally <code>cnki_search</code>) and added a <code>number_of_articles_and_pages()</code> function to the <code>SearchResults</code> class.</p>
<p>There seems to be a minor bug related to the <code>ContentFilterPlugin</code> in @Reinderien original code. <code>MainPage.max_content</code> failed to register, so 20 instead of 50 items are retrieved at a time.</p>
<p>It can be considered as trivial because given the higher efficiency when using the plugin, all content would still be parsed, perhaps even in a shorter time, with the implementation of a loop through the pages.</p>
<h2>Issues:</h2>
<ol>
<li>I've moved <code>next_page</code> out of the <code>MainPage</code> class into the <code>SearchResults</code> class.</li>
<li>Tasks such as looping through the search result seem to be simpler when they are written in functions outside the classes.</li>
<li>Data that is yield from the generators can either be printed or written to file. If we want to do both concurrently or one after the other, the generator would have to be re-initiated each time.</li>
<li>Because I was limiting the maximum number of pages to be scraped, the <code>ContentFilterPlugin</code> bug had the effect of retrieving 180 articles instead of 424, which did not tally with what is printed on the console:</li>
</ol>
<pre><code>424 found. A maximum of 500 will be retrieved.
Scraping page 1/9
Navigating to Next Page
Scraping page 2/9
Navigating to Next Page
Scraping page 3/9
Navigating to Next Page
Scraping page 4/9
Navigating to Next Page
Scraping page 5/9
Navigating to Next Page
Scraping page 6/9
Navigating to Next Page
Scraping page 7/9
Navigating to Next Page
Scraping page 8/9
Navigating to Next Page
Scraping page 9/9
</code></pre>
<hr />
<h1>cnki.py</h1>
<pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager
from dataclasses import dataclass
from datetime import date
from pathlib import Path
from typing import Generator, Iterable, Optional, List, ContextManager, Dict
from urllib.parse import unquote
from itertools import chain, count
import re
import json
from math import ceil
# pip install proxy.py
import proxy
from proxy.http.exception import HttpRequestRejected
from proxy.http.parser import HttpParser
from proxy.http.proxy import HttpProxyBasePlugin
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
TimeoutException,
WebDriverException,
)
from selenium.webdriver import Firefox, FirefoxProfile
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import ProxyType
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
# from urllib3.packages.six import X
@dataclass
class Result:
title: str # Mozi's Theory of Human Nature and Politics
title_link: str # http://big5.oversea.cnki.net/kns55/detail/detail.aspx?recid=&FileName=ZDXB202006009&DbName=CJFDLAST2021&DbCode=CJFD
html_link: Optional[str] # http%3a%2f%2fkns.cnki.net%2fKXReader%2fDetail%3fdbcode%3dCJFD%26filename%3dZDXB202006009
author: str # Xie Qiyang
source: str # Vocational University News
source_link: str # http://big5.oversea.cnki.net/kns55/Navi/ScdbBridge.aspx?DBCode=CJFD&BaseID=ZDXB&UnitCode=&NaviLink=%e8%81%8c%e5%a4%a7%e5%ad%a6%e6%8a%a5
date: date # 2020-12-28
download: str #
database: str # Periodical
@classmethod
def from_row(cls, row: WebElement) -> 'Result':
number, title, author, source, published, database = row.find_elements_by_xpath('td')
title_links = title.find_elements_by_tag_name('a')
if len(title_links) > 1:
# 'http://big5.oversea.cnki.net/kns55/ReadRedirectPage.aspx?flag=html&domain=http%3a%2f%2fkns.cnki.net%2fKXReader%2fDetail%3fdbcode%3dCJFD%26filename%3dZDXB202006009'
html_link = unquote(
title_links[1]
.get_attribute('href')
.split('domain=', 1)[1])
else:
html_link = None
dl_links, sno = number.find_elements_by_tag_name('a')
published_date = date.fromisoformat(
published.text.split(maxsplit=1)[0]
)
return cls(
title=title_links[0].text,
title_link=title_links[0].get_attribute('href'),
html_link=html_link,
author=author.text,
source=source.text,
source_link=source.get_attribute('href'),
date=published_date,
download=dl_links.get_attribute('href'),
database=database.text,
)
def __str__(self):
return (
f'題名 {self.title}'
f'\n作者 {self.author}'
f'\n來源 {self.source}'
f'\n發表時間 {self.date}'
f'\n下載連結 {self.download}'
f'\n來源數據庫 {self.database}'
)
def as_dict(self) -> Dict[str, str]:
return {
'author': self.author,
'title': self.title,
'date': self.date.isoformat(),
'download': self.download,
'url': self.html_link,
'database': self.database,
}
class MainPage:
def __init__(self, driver: WebDriver):
self.driver = driver
def submit_search(self, keyword: str) -> None:
wait = WebDriverWait(self.driver, 50)
search = wait.until(
EC.presence_of_element_located((By.NAME, 'txt_1_value1'))
)
search.send_keys(keyword)
search.submit()
def switch_to_frame(self) -> None:
wait = WebDriverWait(self.driver, 100)
wait.until(
EC.presence_of_element_located((By.XPATH, '//iframe[@name="iframeResult"]'))
)
self.driver.switch_to.default_content()
self.driver.switch_to.frame('iframeResult')
wait.until(
EC.presence_of_element_located((By.XPATH, '//table[@class="GridTableContent"]'))
)
def max_content(self) -> None:
"""Maximize the number of items on display in the search results."""
max_content = self.driver.find_element(
By.CSS_SELECTOR, '#id_grid_display_num > a:nth-child(3)',
)
max_content.click()
# def get_element_and_stop_page(self, *locator) -> WebElement:
# ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
# wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions)
# elm = wait.until(EC.presence_of_element_located(locator))
# self.driver.execute_script("window.stop();")
# return elm
class SearchResults:
def __init__(self, driver: WebDriver):
self.driver = driver
def number_of_articles_and_pages(self) -> int:
elem = self.driver.find_element_by_xpath(
'//table//tr[3]//table//table//td[1]/table//td[1]'
)
n_articles = re.search("共有記錄(.+)條", elem.text).group(1)
n_pages = ceil(int(n_articles)/50)
return n_articles, n_pages
def get_structured_elements(self) -> Iterable[Result]:
rows = self.driver.find_elements_by_xpath(
'//table[@class="GridTableContent"]//tr[position() > 1]'
)
for row in rows:
yield Result.from_row(row)
def get_element_and_stop_page(self, *locator) -> WebElement:
ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions)
elm = wait.until(EC.presence_of_element_located(locator))
self.driver.execute_script("window.stop();")
return elm
def next_page(self) -> None:
link = self.get_element_and_stop_page(By.LINK_TEXT, "下頁")
try:
link.click()
print("Navigating to Next Page")
except (TimeoutException, WebDriverException):
print("Last page reached")
class ContentFilterPlugin(HttpProxyBasePlugin):
HOST_WHITELIST = {
b'ocsp.digicert.com',
b'ocsp.sca1b.amazontrust.com',
b'big5.oversea.cnki.net',
}
def handle_client_request(self, request: HttpParser) -> Optional[HttpParser]:
host = request.host or request.header(b'Host')
if host not in self.HOST_WHITELIST:
raise HttpRequestRejected(403)
if any(
suffix in request.path
for suffix in (
b'png', b'ico', b'jpg', b'gif', b'css',
)
):
raise HttpRequestRejected(403)
return request
def before_upstream_connection(self, request):
return super().before_upstream_connection(request)
def handle_upstream_chunk(self, chunk):
return super().handle_upstream_chunk(chunk)
def on_upstream_connection_close(self):
pass
@contextmanager
def run_driver() -> ContextManager[WebDriver]:
prox_type = ProxyType.MANUAL['ff_value']
prox_host = '127.0.0.1'
prox_port = 8889
profile = FirefoxProfile()
profile.set_preference('network.proxy.type', prox_type)
profile.set_preference('network.proxy.http', prox_host)
profile.set_preference('network.proxy.ssl', prox_host)
profile.set_preference('network.proxy.http_port', prox_port)
profile.set_preference('network.proxy.ssl_port', prox_port)
profile.update_preferences()
plugin = f'{Path(__file__).stem}.{ContentFilterPlugin.__name__}'
with proxy.start((
'--hostname', prox_host,
'--port', str(prox_port),
'--plugins', plugin,
)), Firefox(profile) as driver:
yield driver
def loop_through_results(driver):
result_page = SearchResults(driver)
n_articles, n_pages = result_page.number_of_articles_and_pages()
print(f"{n_articles} found. A maximum of 500 will be retrieved.")
for page in count(1):
print(f"Scraping page {page}/{n_pages}")
print()
result = result_page.get_structured_elements()
yield from result
if page >= n_pages or page >= 10:
break
result_page.next_page()
result_page = SearchResults(driver)
def save_articles(articles: Iterable, file_prefix: str) -> None:
file_path = Path(file_prefix).with_suffix('.json')
with file_path.open('w') as file:
file.write('[\n')
first = True
for article in articles:
if first:
first = False
else:
file.write(',\n')
json.dump(article.as_dict(), file, ensure_ascii=False, indent=4)
file.write('\n]\n')
def query(keyword, driver) -> None:
page = MainPage(driver)
page.submit_search(keyword)
page.switch_to_frame()
page.max_content()
def search(keyword):
with Firefox() as driver:
driver.get('http://big5.oversea.cnki.net/kns55/')
query(keyword, driver)
result = loop_through_results(driver)
save_articles(result, 'cnki_search_result.json')
if __name__ == '__main__':
search('古文尚書')
</code></pre>
<h2>Output (truncated):</h2>
<pre class="lang-json prettyprint-override"><code>[
{
"author": "王祥辰",
"title": "惠棟與吳派經學研究",
"date": "2020-06-10",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=jZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXS=0TQHZ0MWhmWhRlQsNUQWFkQD5WaMBzV5ZkM0MnUUtCVysSSGN3aCRnRy8kb0V1KKRVbiJkeSlWdrU&tablename=CDFDLAST2021&dflag=pdfdown",
"url": null,
"database": "博士"
},
{
"author": "余康",
"title": "章太炎《尚書》研究述論",
"date": "2017-05-01",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=jZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXS=0DNKtWZyolbytmRrJFbxgHbtBXY1glQIF2Kys2aKtCVysSSGN3aCRnRy8kb0V1KKRVbiJkeSlWdrU&tablename=CDFDLAST2020&dflag=pdfdown",
"url": null,
"database": "博士"
},
{
"author": "崔海鷹",
"title": "孔傳《古文尚書》淵源與成書問題探論",
"date": "2014-04-01",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=rUjZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXSStWd4JFVJhVQxRmNjZWWKxmZxZFUrg1asdzSV9CW5RTQT52TysSSGN3aCRnRy8kb0V1KKRVbiJkeSlWd&tablename=CDFD1214&dflag=pdfdown",
"url": null,
"database": "博士"
},
{
"author": "王祥辰",
"title": "清代吳派《尚書》學疑辨成就管窺——以《古文尚書考》為中心",
"date": "2018-03-20",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=rUjZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXSH1WQXdGTKNDdRR0VuNWTyVnT3BTel9meOlVO4lDavF1U5o0Q6djcmpWQodjRy8kb0V1KKRVbiJkeSlWd&tablename=CJFDLAST2018&dflag=pdfdown",
"url": null,
"database": "期刊"
},
{
"author": "蘆倩",
"title": "古文《尚書》復合詞研究",
"date": "2015-05-01",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=jZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXS=0DMFdWSDNjQYhXaMJEUKF3M5gzLxN1Y2MTOwUFZJR1UNZENChUUSZnRy8kb0V1KKRVbiJkeSlWdrU&tablename=CMFD201601&dflag=pdfdown",
"url": null,
"database": "碩士"
},
{
"author": "盧秀松",
"title": "古文《尚書》代詞研究",
"date": "2015-05-01",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=jZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXS=0TRQ9EaI1mQYhXaMJEUKF3M5gzLxN1Y2MTOwUFZJR1UNZENChUUSZnRy8kb0V1KKRVbiJkeSlWdrU&tablename=CMFD201601&dflag=pdfdown",
"url": null,
"database": "碩士"
},
{
"author": "嚴璐",
"title": "今古文《尚書》復音單純詞研究",
"date": "2013-05-01",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=rUjZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXSGNGdTd0ZwhGZpRTcGtCRw8yc0xke0NVcPhnSCNDdi90SoN1UNZENChUUSZnRy8kb0V1KKRVbiJkeSlWd&tablename=CMFD201401&dflag=pdfdown",
"url": null,
"database": "碩士"
},
{
"author": "史振卿",
"title": "清代《尚書》學若干問題研究",
"date": "2011-05-01",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=jZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXS=0zYqRla54EONFlUJdlYuRmQGlmd6JGa0c2K6tke4p2TysSSGN3aCRnRy8kb0V1KKRVbiJkeSlWdrU&tablename=CDFD0911&dflag=pdfdown",
"url": null,
"database": "博士"
},
{
"author": "丁鼎",
"title": "“偽《古文尚書》案”平議",
"date": "2010-03-25",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=jZVFjZ5UDZKVEUnFTSxUGcNJlNJBDZDxWeiNlez52az8GMBV1QLFlNStmQolUQxUjTzoUbyFmYjJXS=0TSG92ZrpGck9mR4Jzaw9yRRFjVURFbw0WZxgmM2EWOFRVZBtWVBNnRy8kb0V1KKRVbiJkeSlWdrU&tablename=CJFD2010&dflag=pdfdown",
"url": "http://kns.cnki.net/KXReader/Detail?dbcode=CJFD&filename=GJZL201002003",
"database": "期刊"
},
......
{
"author": "藏生",
"title": "《今文尚書》校詁(三)——《禹貢》《甘誓》《湯誓》四十二則",
"date": "1998-08-15",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=kN2d3UTbyI3d4MkRslmQzl1KvcEVK1UVTNTVYJzLkFVNGN0M6JURwgHbUJ2bEZFN4gHZ6BVdw9EawdUa3hmaPlWcOdWUapHeRBFUxpGWQZmZmhlSGNzTqRXWvsWMjN3SLRkQWRHb5FFZNFlazdUcDlGV3EzSvBlM&tablename=CJFD9899&dflag=pdfdown",
"url": null,
"database": "期刊"
},
{
"author": "劉起釪",
"title": "《尚書》的隸古定本、古寫本",
"date": "1980-06-29",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=2d3UTbyI3d4MkRslmQzl1KvcEVK1UVTNTVYJzLkFVNGN0M6JURwgHbUJ2bEZFN4gHZ6BVdw9EawdUa=0TU4tSav5GZDlGcUZzc50UTHlXdhRXYJVUYOd0S6VVRHh0MhZDbrUFZNFlazdUcDlGV3EzSvBlMkN&tablename=CJFD7984&dflag=pdfdown",
"url": null,
"database": "期刊"
},
{
"author": "劉起釪",
"title": "關于隸古定與河圖洛書問題",
"date": "1997-04-15",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=kN2d3UTbyI3d4MkRslmQzl1KvcEVK1UVTNTVYJzLkFVNGN0M6JURwgHbUJ2bEZFN4gHZ6BVdw9EawdUaUNmNxETO0AFR5A1bYZlamxkWw4Uc4FTSFlza1MXZzdWYWBHeN50ZRVnMwdFZNFlazdUcDlGV3EzSvBlM&tablename=CJFD9697&dflag=pdfdown",
"url": "http://kns.cnki.net/KXReader/Detail?dbcode=CJFD&filename=CTWH199702004",
"database": "期刊"
},
{
"author": "劉家和",
"title": "《史記》與漢代經學",
"date": "1991-05-01",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=2d3UTbyI3d4MkRslmQzl1KvcEVK1UVTNTVYJzLkFVNGN0M6JURwgHbUJ2bEZFN4gHZ6BVdw9EawdUa=0TQEJ1NLdEdzwkZWFHZ2F1bORjRVl2c69EO3c0S6VVRHh0MhZDbrUFZNFlazdUcDlGV3EzSvBlMkN&tablename=CJFD9093&dflag=pdfdown",
"url": "http://kns.cnki.net/KXReader/Detail?dbcode=CJFD&filename=SYSJ199102003",
"database": "期刊"
},
{
"author": "陸建初",
"title": "《尚書》史詩略考",
"date": "2009-03-18",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=kN2d3UTbyI3d4MkRslmQzl1KvcEVK1UVTNTVYJzLkFVNGN0M6JURwgHbUJ2bEZFN4gHZ6BVdw9EawdUaHZDWOBlbMhjaU10UBBFeGR1K19iSRZ3NRZ1QONEVsR1U0E2YLRkQWRHb5FFZNFlazdUcDlGV3EzSvBlM&tablename=CJFD2009&dflag=pdfdown",
"url": "http://kns.cnki.net/KXReader/Detail?dbcode=CJFD&filename=YNXS200902010",
"database": "期刊"
},
{
"author": "盂光宇",
"title": "《千字文》批注",
"date": "1974-06-15",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=2d3UTbyI3d4MkRslmQzl1KvcEVK1UVTNTVYJzLkFVNGN0M6JURwgHbUJ2bEZFN4gHZ6BVdw9EawdUa=0DNmN2VBJlVsR3YXBTQxQ3RtJUZaZEU0E3aYlDWOpmZvZ2MhZDbrUFZNFlazdUcDlGV3EzSvBlMkN&tablename=CJFD7984&dflag=pdfdown",
"url": null,
"database": "期刊"
},
{
"author": "金敏",
"title": "“法”的故事的另一種講法",
"date": "2018-12-15",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=2d3UTbyI3d4MkRslmQzl1KvcEVK1UVTNTVYJzLkFVNGN0M6JURwgHbUJ2bEZFN4gHZ6BVdw9EawdUa=0DOYF2dUp1bYtyMxMVcXZkWoZTbM9UOyZHbFJnQx0kZUtyY15UeaVFZNFlazdUcDlGV3EzSvBlMkN&tablename=CJFDLAST2019&dflag=pdfdown",
"url": "http://kns.cnki.net/KXReader/Detail?dbcode=CJFD&filename=FLPL201806021",
"database": "期刊"
},
{
"author": "趙穹天",
"title": "近出楚簡疑難字詞匯考",
"date": "2013-03-01",
"download": "http://big5.oversea.cnki.net/kns55/download.aspx?filename=3EzSvBlMkN2d3UTbyI3d4MkRslmQzl1KvcEVK1UVTNTVYJzLkFVNGN0M6JURwgHbUJ2bEZFN4gHZ6BVdw9EawdUa9cXUnJXTENWSGZXb0tmWroEd3p3MDZHehVlU5ZHczJzRvwkaXdUWRVzUTRXQBVWMIRnZnhzbYdFZNFlazdUcDlGV&tablename=CMFD201402&dflag=pdfdown",
"url": null,
"database": "碩士"
}
]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T16:32:46.437",
"Id": "520130",
"Score": "0",
"body": "Removed the original buggy code, should be more concise and clear now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T23:50:45.823",
"Id": "520204",
"Score": "0",
"body": "Your `as_dict` indentation is incorrect"
}
] |
[
{
"body": "<p>Most of the improvements are needed in <code>number_of_articles_and_pages</code>:</p>\n<ul>\n<li>The type hint is incorrect; you're not just returning a single integer but a tuple of them</li>\n<li>Your xpath expression is of a verbose and fragile form that relies overly on full tree traversal and position. This is a habit that you need to break out of. Read the DOM and look for class and ID names and other characteristics that better identify the target element.</li>\n<li>Your regex is much more complex than it needs to be; just match on a number.</li>\n<li>Do not hard code a page size of 50. The page itself tells you how big the pages are.</li>\n<li>For <code>n_articles</code> you were incorrectly returning a string when you should return an int.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>def number_of_articles_and_pages(self) -> Tuple[\n int, # articles\n int, # pages\n int, # page size\n]:\n articles_elem = self.driver.find_element_by_css_selector('td.TitleLeftCell td')\n n_articles = int(re.search(r"\\d+", articles_elem.text)[0])\n\n page_elem = self.driver.find_element_by_css_selector('font.numNow')\n per_page = int(page_elem.text)\n\n n_pages = ceil(n_articles / per_page)\n\n return n_articles, n_pages, per_page\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T00:14:47.567",
"Id": "263501",
"ParentId": "263443",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263501",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T04:01:37.090",
"Id": "263443",
"Score": "2",
"Tags": [
"python",
"web-scraping",
"selenium"
],
"Title": "Looping through search results in Selenium"
}
|
263443
|
<p>You can only kill off a given number of heads at each hit and corresponding number of heads grow back. The heads will not grow back if the <a href="https://en.wikipedia.org/wiki/Lernaean_Hydra" rel="noreferrer">hydra</a> is left with zero heads. For example:</p>
<pre><code>heads = [135]
hits = [25,67,1,62]
growths = [15,25,15,34]
</code></pre>
<p>Then you can kill off <code>hits[i]</code> heads but <code>growths[i]</code> heads grow back. My approach is to randomise the index of hits each time and it works but I don't think this is too efficient. Of course the time taken varies for every different array of hits, growths. We have to determine if the hydra is killable for a given limit on iterations.</p>
<pre><code>from timeit import default_timer as timer
start = timer()
import random
import time
heads = [88,135,192,152]
hits = [25,67,1,62]
growths = [15,25,15,34]
def hydra_killing():
iter_limit = 1000
for head in heads:
iters = 0 #Resets iters at every new 'hydra'
while head != 0:
iters += 1
if iters == iter_limit:
print("NO")
break
else:
i = random.randint(0,3) #Randomly choose a hit value
if head >= hits[i]:
head -= hits[i]
if head == 0:
print(f'''
YES...............................................{iters}
''')
else:
head += growths[i]
#print(head, hits[i], growths[i], iters)
else:
iters -= 1 #if the heads remaining are greater than
#hits[i], then this iteration is not counted
hydra_killing()
end = timer()
print(end - start, " seconds")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T05:43:06.297",
"Id": "520079",
"Score": "1",
"body": "Can you overkill a hydra? If the hydra has 20 heads can you cut off 26?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T05:58:11.777",
"Id": "520080",
"Score": "0",
"body": "imo no you can't"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T06:00:04.607",
"Id": "520081",
"Score": "0",
"body": "if the heads remaining are greater than hits[i], then we regenerate an i and that 'try' is not counted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T06:14:02.340",
"Id": "520082",
"Score": "0",
"body": "Try Lee algorithm. Imagine you're in a snakes-and-ladders labyrinth, with hydra head count is a cell number and possible moves are growth[i]-hits[i]. https://en.m.wikipedia.org/wiki/Lee_algorithm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T06:15:17.333",
"Id": "520083",
"Score": "0",
"body": "'It always gives an optimal solution, if one exists, but <<is slow and requires considerable memory>>'"
}
] |
[
{
"body": "<h3>Code feedback</h3>\n<ul>\n<li><strong>Use a linter!</strong> You have many inconsistencies in your code that suggests you are not using any type of autoformater for your code. This is strongly suggested. I like to use <code>black</code>, but there are many other variants.</li>\n<li><strong>Structure your code using functions</strong></li>\n<li>Remove unused imports using imports.</li>\n<li>Time only the relevant parts.</li>\n<li>Split the print from the hits</li>\n</ul>\n<p>Using the bullet points above a <em>starting point</em> for improving your code looks like this</p>\n<pre><code>from timeit import default_timer as timer\nimport random\n\n\ndef hydra_killing(head, hits, growths, iter_limit=1000):\n growths_ = dict(zip(hits, growths))\n\n iters = 0\n while (iters := iters + 1) < iter_limit:\n hit = random.choice(hits)\n if head < hit:\n continue\n head -= hit\n if head == 0:\n return True, iters\n head += growths_[hit]\n\n return False, iter_limit\n\n\nif __name__ == "__main__":\n\n heads = [88, 135, 192, 152]\n hits = [25, 67, 1, 62]\n growths = [15, 25, 15, 34]\n\n for head in heads:\n start = timer()\n is_hydra_dead, iters = hydra_killing(head, hits, growths)\n end = timer()\n print(end - start, " seconds")\n print(is_hydra_dead, iters)\n</code></pre>\n<p>Alternatively we could try a smaller hit value instead of calling <code>continue</code>. This would look like this</p>\n<pre><code>def hydra_killing(head, hits, growths, iter_limit=1000):\n growths_ = dict(zip(hits, growths))\n\n iters = 0\n while (iters := iters + 1) < iter_limit:\n hit = random.choice(hits)\n if head < hit:\n if small_hits := [hit for hit in hits if hit < head]:\n hit = random.choice(small_hits)\n else:\n return False, iters\n head -= hit\n if head == 0:\n return True, iters\n head += growths_[hit]\n\n return False, iter_limit\n</code></pre>\n<p>It will reduce the number of iterations quite a bit, but if this is something you want to implement is up to you. The <code>return</code> statement in the code above is added if for instance the hydra has <code>2</code> heads left, and we can only kill <code>3</code> or more heads. Then the hydra is not killable, and we return.</p>\n<h3>Suggestion 1 [We only want to know if the Hydra can be killed!]</h3>\n<p>So you have a very good starting point! Randomly picking a number of heads to kill is <em>not</em> a bad idea! However, to improve upon the code we need to introduce a few early exits.</p>\n<ul>\n<li><p>If <code>head</code> is in <code>hits</code> we return. This one is simple enough, if the hydra can be killed on the next turn, we return.</p>\n</li>\n<li><p>What if <code>hit - growth</code> is in <code>hits</code>? Concretely if\nheads = <code>72</code>, <code>diff := hit - growth = 25 - 15 = 10</code> then we _know the hydra is killable on the next turn. Because <code>heads - diff = 62</code> and <code>62</code> is in <code>hits</code>.</p>\n</li>\n<li><p>Similarly we can remove <code>diff</code> over and over again until we reach <code>hit</code>. So any multiple of <code>72</code> can be removed since. <code>92 - 10 - 10 = 62</code> for instance. And we know that the change in heads after adding and removing is <code>10</code>. Python has a clever way of checking this with the <code>%</code> operator (modulo) So we simply check if <code>head % diff</code> lies in <code>hits</code>.</p>\n</li>\n<li><p>If we are smart we check if a particular <code>hit</code> leaves us in the state above. Meaning we check if <code>head - hit % diff</code> lies in <code>hits</code>, and if it do, we return.</p>\n</li>\n<li><p>Even this code has problems when the number of heads grows large\nthe final trick is that we remove <code>chunks</code> instead of single hits. You can think of this as we do <code>n</code> hits, and then the hydra regrows <code>n</code> times.</p>\n<pre><code> chunk = max(1, head // chunk_size)\n head += (growths_[hit] - hit) * chunk\n</code></pre>\n</li>\n</ul>\n<h5>code 1</h5>\n<pre><code>from timeit import default_timer as timer\nimport random\n\n\ndef hydra_killing(head, hits, growths, iter_limit=10 ** 6):\n\n growths_ = dict(zip(hits, growths))\n positive_hits, differences = zip(\n *[(hit, hit - growth) for hit, growth in zip(hits, growths) if hit > growth]\n )\n chunk_size = 1000\n iters = 0\n while (iters := iters + 1) < iter_limit:\n\n if head in hits:\n return True, iters\n for diff in differences:\n if head % diff in positive_hits:\n return True, iters\n for h in positive_hits:\n if (head - (h + growths_[h])) % diff in positive_hits:\n return True, iters\n\n hit = random.choice(hits)\n\n if head < hit:\n if small_hits := [hit for hit in hits if hit < head]:\n hit = random.choice(small_hits)\n else:\n return False, iters\n chunk = max(1, head // chunk_size)\n head += (growths_[hit] - hit) * chunk\n\n return False, iter_limit\n\n\nif __name__ == "__main__":\n\n heads = [88, 135, 192, 98767892]\n # heads = [4321]\n hits = [25, 67, 1, 62]\n growths = [15, 25, 15, 34]\n\n for head in heads:\n start = timer()\n is_hydra_dead, iters = hydra_killing(head, hits, growths)\n end = timer()\n print(end - start, " seconds")\n print(is_hydra_dead, iters)\n</code></pre>\n<h3>Suggestion 2 [We want the optimal]</h3>\n<p>Unless you have a ton of heads I would recommend simply using <code>itertools</code>. Notice that until the very last hit, the <code>hit</code>\nand <code>growth</code> can occur at the same time. Meaning we can just hit the hydra down, and check if it can be killed in one hit.</p>\n<p><em>The hydra can be killed in one hit, if its heads is in <code>hits</code></em></p>\n<p>Then we just have to iterate over all possible hit values and return the first one that matches.</p>\n<h4>Code 2</h4>\n<pre><code>import itertools\n\ndef is_hydra_one_hit_from_death(total_heads, hits, number_of_hits, growths):\n """Checks if Hydra is 1 hit away from death after n hits"""\n heads_removed = sum(\n (hit - growth) * number\n for hit, number, growth in zip(hits, number_of_hits, growths)\n )\n return (total_heads - heads_removed) in hits\n\n\ndef kill_hydra_itertools(head, hits, growths):\n """Iterates over all possible number of hits, returns first '1 hit from death'"""\n for hydra_hits in itertools.product(*[range(head // 10) for _ in hits]):\n if is_hydra_one_hit_from_death(head, hits, hydra_hits, growths):\n return hydra_hits\n return ()\n\nif __name__ == "__main__":\n\n heads = [88, 135, 152, 1002]\n hits = [25, 67, 1, 62]\n growths = [15, 25, 15, 34]\n\n # Sorts hits and growths in ascending number of hydra heads killed\n # which speeds up the iteration somewhat\n hits, growths = zip(\n *sorted(zip(hits, growths), key=lambda sub: sub[1] - sub[0], reverse=True)\n )\n\n for head in heads:\n if hits_2_almost_kill := kill_hydra_itertools(head, hits, growths):\n print(hits_2_almost_kill)\n</code></pre>\n<h3>Example</h3>\n<p>For instance for <code>152</code> the code returns <code>(2, 0, 1, 3)</code> we can check that this is correct by doing</p>\n<pre><code>print(152 - (25 - 15) * 2 - (1 - 15) * 1 - (62 - 34) * 3)\n</code></pre>\n<p>Indeed, this returns <code>62</code> which is a number of heads we can strike of in the next turn. Notice that this already takes into consideration the growing back of heads.</p>\n<h3>Suggestion 3 [Mathematics]</h3>\n<p>We could also have used mathematics to obtain the results, this is somewhat fast for very large inputs. <strong>I would recommend going for one of the two other suggestions first though!</strong></p>\n<p>We know that every time we hit the hydra the <em>change in heads</em> is equal to</p>\n<pre><code>change_in_heads = [25-15, 67-25, 1-15, 62-34] = [10, 42, -14, 28]\n</code></pre>\n<p>This means in principle we are looking for the solution to the equation</p>\n<pre><code>10 r + 42 s - 14 t + 28 u = heads\n</code></pre>\n<p>This is known as a <a href=\"https://en.wikipedia.org/wiki/Diophantine_equation\" rel=\"nofollow noreferrer\">Diophantine equation</a> which <a href=\"https://docs.sympy.org/latest/modules/solvers/diophantine.html\" rel=\"nofollow noreferrer\"><code>sympy</code> knows how to solve</a>.</p>\n<p>Note that this returns the <em>general solution</em>, meaning for instance that the solution to</p>\n<pre><code>10 r + 42 s - 14 t + 28 u = 88\n</code></pre>\n<p>is written as</p>\n<pre><code>t_0, -35 t_0 + 7 t_1 + 132, t_0 + t_1 + t_2, -20 t_0 + 8 t_1 + 3 t_2 + 88\n</code></pre>\n<p>Where <code>t_0</code>, <code>t_1</code> and <code>t_2</code> are integers which we can change to generate as many solutions as we want. (Amongst the <a href=\"https://en.wikipedia.org/wiki/Mathematician\" rel=\"nofollow noreferrer\">nerds</a> we say that the solution can be written as a<a href=\"https://en.wikipedia.org/wiki/Parametric_equation\" rel=\"nofollow noreferrer\">parametric equation</a>.) So all we have do to is use <code>sympy</code> to solve the equation, and then check if we can find a particular solution with integer coefficients.</p>\n<p><strong>Noe 0:</strong> The explanation above is not <em>quite</em> right. Due to how you choose to calculate the hits and regrowth (hits before regrowth). We really need to hit the Hydra until it is one hit away from death. Meaning the Hydra's healthbar has to be in <code>hits</code> This is done by instead by checking if</p>\n<pre><code>10 x + 42 y - 14 z + 28 w = 88 - hit\n</code></pre>\n<p>has a solution for each <code>hit</code> in <code>hits</code>.</p>\n<p><strong>Note 1:</strong> that the switch <code>minimize</code> in the code below attempts to find the shortest or fastest way to kill the Hydra. If you only any solution set this boolean to false.</p>\n<p><strong>Note: 2:</strong> the code below is merely a <em>suggestion</em>. There are several improvements that could (and should be made to the code below). Such as, but not limited to</p>\n<h4>Work still to be done</h4>\n<ul>\n<li><p>Adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">PEP484 typing hints</a></p>\n</li>\n<li><p>Instead of using nested for loops to find the positive solution either:</p>\n<ul>\n<li><p>Use a recursive solution or use <code>itertools</code> as seen before.</p>\n</li>\n<li><p>The recurse solution would also benefit from adding restrictions from the general solution. As an example we have</p>\n<pre><code>t_0, -35 t_0 + 7 t_1 + 132, t_0 + t_1 + t_2, -20 t_0 + 8 t_1 + 3 t_2 + 88\n</code></pre>\n<p>For the first hydra. This means that <code>t_0>0</code>, <code>t_1 > (35 t_0 - 132)/7</code>,\nand for instance <code>t_2 > t_1 + t_2</code>. This could make the looping faster.</p>\n</li>\n</ul>\n</li>\n</ul>\n<h4>Code 3</h4>\n<pre><code>from sympy.solvers.diophantine import diophantine\nfrom sympy import symbols, solve\n\nr, s, t, u = symbols("r, s, t, u", integer=True)\n\n\ndef is_hydra_killable(heads, hits, growths, minimize_solution=False):\n change_in_heads = [hit - growth for hit, growth in zip(hits, growths)]\n equation = sum(d * var for d, var in zip(change_in_heads, [r, s, t, u]))\n\n min_hits_2_kill = [float("Inf")] * len(hits)\n for index, hit in enumerate(hits):\n try:\n [solution] = diophantine(equation - (heads - hit))\n except ValueError:\n continue\n hits_2_kill = hydra_hits_required(solution, minimize_solution)\n if sum(hits_2_kill) < float("Inf"):\n if minimize_solution:\n if sum(min_hits_2_kill) > sum(hits_2_kill):\n min_hits_2_kill = hits_2_kill\n else:\n return True, hits\n return sum(min_hits_2_kill) < float("Inf"), min_hits_2_kill\n\n\ndef hydra_hits_required(solution, minimize_solution=False, max_range=10):\n t_1, t_0, t_2 = solution[3].free_symbols\n\n length_solution = float("Inf")\n shortest = [float("Inf"), float("Inf"), float("Inf")]\n t0_start = int(nsolve(solution[0], 0) + 1)\n for t0 in range(t0_start, max_range + t0_start):\n sol1 = [expr.subs({t_0: t0}) for expr in solution]\n t1_start = int(nsolve(sol1[1], 0) + 1)\n for t1 in range(t1_start, max_range + t1_start):\n sol2 = [expr.subs({t_1: t1}) for expr in sol1]\n t2_start = max(int(nsolve(sol2[2], 0) + 1), int(nsolve(sol2[3], 0) + 1))\n for t2 in range(t2_start, t2_start + max_range):\n sol3 = [expr.subs({t_2: t2}) for expr in sol2]\n if min(sol3) > 0 and sum(sol3) < length_solution:\n shortest = sol3\n length_solution = sum(sol3)\n if not minimize_solution:\n return shortest\n return shortest\n\n\ndef is_hydra_one_hit_from_death(heads, hits, number_of_hits, growths):\n """Checks if Hydra is 1 hit away from death after n hits"""\n for hit, number, growth in zip(hits, number_of_hits, growths):\n heads = heads - (hit - growth) * number\n return heads in hits\n\n\nif __name__ == "__main__":\n\n heads = [88, 135, 192, 98765672]\n hits = [25, 67, 1, 62]\n growths = [15, 25, 15, 34]\n\n minimize = True\n\n for head in heads:\n is_dead, hits_2_kill = is_hydra_killable(head, hits, growths, minimize)\n print(hits_2_kill)\n print(is_hydra_one_hit_from_death(head, hits, hits_2_kill, growths))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T16:36:08.993",
"Id": "263490",
"ParentId": "263444",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T04:24:32.917",
"Id": "263444",
"Score": "5",
"Tags": [
"python-3.x"
],
"Title": "Killing a hydra"
}
|
263444
|
<p>Sum of 2 numbers, represented with linked lists, where digits are in backward order or forward order.</p>
<p><strong>Backward order Example</strong></p>
<ul>
<li>INPUT:(7->1->6) + (5->9->2) = 617+295</li>
<li>OUTPUT: 2->1->9 = 912</li>
</ul>
<p><strong>Forward order Example</strong></p>
<ul>
<li>INPUT:(7->1->6) + (5->9->2) = 716+592</li>
<li>OUTPUT: 1>-3->0->8 = 1308</li>
</ul>
<p>I'm starting with this method. I'm giving it list and size and I'm extrapolating each digit with base 10 notation.
Time complexity should be O(n) for each list, and Space complexity should be O(1). Am I right?</p>
<pre><code>public static int getNumber(LinkedList<Integer> num_list,int size){
int number= 0;
int pow = 0;//size-1 if it's in forward order
for (int d: num_list){
number += d * Math.pow(10.0, pow);
pow++;//pow-- if it's in forward order
}
return number;
}
</code></pre>
<p><strong>Main</strong></p>
<pre><code>LinkedList<Integer> num1 = new LinkedList<>();
LinkedList<Integer> num2 = new LinkedList<>();
int sum,temp;
int count_digit = 0;
num1.add(7);
num1.add(1);
num1.add(6);
num2.add(5);
num2.add(9);
num2.add(2);
sum = getNumber(num1,num1.size()) + getNumber(num2,num2.size());
temp = sum;
//Counting the number of digits
while(temp!=0){
temp /= 10;
count_digit++;
}
LinkedList<Integer> result = new LinkedList<>();
</code></pre>
<p><strong>Backward Solution</strong></p>
<p>In that case, Space complexity should be O(1) and time O(n). Right?</p>
<pre><code>for (int i = 0; i < count_digit;i++){
temp = sum % 10;
sum/= 10;
result.add(temp);
}
for(int d: result)
System.out.print(d);//Print node
System.out.println();
System.out.println(getNumber(result, result.size())); //print result
</code></pre>
<p><strong>Frontward Solution</strong></p>
<p>I didn't find any way to not implement another Structure. In that case, I changed <strong>getNumber</strong> method, using commented code.</p>
<pre><code>int[] digit = new int[count_digit];
for(int i = digit.length-1; i >= 0; i--){
temp = sum % 10;
digit[i]= temp;
sum/= 10;
}
for(int d: digit){
System.out.print(d);
result.add(d);
}
//Just checking
System.out.println();
for (int d: result)
System.out.println(d);
</code></pre>
<p>At the end time complexity should be O(3n) (first list+ second list + array population) and, if I'm right, it should be considered like O(n). Space complexity should be O(n). There is a way to reduce space complexity?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T08:59:38.730",
"Id": "520094",
"Score": "0",
"body": "Hello, are you sure your code is working as expected ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T09:44:13.850",
"Id": "520098",
"Score": "1",
"body": "@dariosicily I've fixed the code. Can you answer my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T10:45:28.743",
"Id": "520100",
"Score": "0",
"body": "You wrote *OUTPUT: 1>-3->0->8 = 1308*. This for me means you have to create a `List` as output, there's no trace of it in your code, if the output was just a number , there wouldn't need to specify the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T12:43:59.460",
"Id": "520103",
"Score": "0",
"body": "@dariosicily I'm sorry, but I didn't get what you mean. I've created the list **result** as output.\nIn backward, I've populated it during the extrapolation of each digit. In forward I've created in a first moment an array, and later I've filled the list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T15:09:44.280",
"Id": "520117",
"Score": "0",
"body": "To put it simply, I executed your code and it prints something traceable to what you expect. Have you code I can execute obtaining the expected output ? If not, Code Review users can review just working code as expected and at the moment this is not your case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-29T20:26:07.893",
"Id": "524458",
"Score": "0",
"body": "Are there limits on how long a list can be? If the number is too large, it will overflow when you try to convert it to an `int`."
}
] |
[
{
"body": "<p>There are two main suggestions I would recommend:</p>\n<ol>\n<li>Use separate methods to reuse code when able to.</li>\n<li>Take advantage of the tools already in the Java library.</li>\n</ol>\n<p><code>LinkedList</code> already has a method built in to return a <code>descendingIterator()</code> which can be used to handle the backwards read. You can also take advantage of various capabilities in the <code>String</code> and <code>Integer</code> classes to handle the combination and separation of list values.</p>\n<p>Here's an example of one way you could leverage the library tools and better take advantage of code reuse:</p>\n<pre><code>import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.LinkedList;\n\npublic class LinkedListTest {\n\n public static void main(String[] args) {\n //Build data\n var num1 = new LinkedList<Integer>(Arrays.asList(7, 1, 6));\n var num2 = new LinkedList<Integer>(Arrays.asList(5, 9, 2));\n \n //Convert list to whole integer\n var num1Forward = convertToInt(num1.iterator());\n var num2Forward = convertToInt(num2.iterator());\n \n //Sum integers and convert back to list\n var sumForward = convertToLinkedList(num1Forward + num2Forward);\n \n System.out.println("Forward: " + num1Forward + " + " + num2Forward + " = " + sumForward);\n \n //Convert list to whole integer in reverse order\n var num1Backward = convertToInt(num1.descendingIterator());\n var num2Backward = convertToInt(num2.descendingIterator());\n \n //Sum integers and convert back to list\n var sumBackward = convertToLinkedList(num1Backward + num2Backward);\n \n //Reverse the returned list using library tool\n Collections.reverse(sumBackward);\n \n System.out.println("Backward: " + num1Backward + " + " + num2Backward + " = " + sumBackward);\n }\n \n public static int convertToInt(Iterator<Integer> numberIterator) {\n var combine = "";\n \n //Concatenate values feed from iterator into a String\n while(numberIterator.hasNext())\n combine += numberIterator.next();\n \n //Use Integer class to parse the String back to a whole Integer\n return Integer.parseInt(combine);\n }\n \n public static LinkedList<Integer> convertToLinkedList(int value) {\n var list = new LinkedList<Integer>();\n \n //Convert value to String and use split() to break value into individual digits\n var splitValues = Integer.toString(value).split("");\n \n //Use Integer to parse digits into Integers and add to the list\n Arrays.stream(splitValues).map(Integer::parseInt).forEach(list::add);\n \n return list;\n }\n \n}\n</code></pre>\n<p>Output:</p>\n<pre><code>Forward: 716 + 592 = [1, 3, 0, 8]\nBackward: 617 + 295 = [2, 1, 9]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T18:31:50.667",
"Id": "263596",
"ParentId": "263446",
"Score": "0"
}
},
{
"body": "<p>(I've read the book, solved the problems and passed the interview)</p>\n<p>The purpose of this exercise is to use the properties of lists to your advantage, and show your understanding of them; as well as teaching you to ask the right questions: How big can the numbers be? Will they overflow an int/long? Can they be negative? Will both of the lists fit in memory? Is the input guaranteed to be well formed? Converting to int and back is kind of missing the point...</p>\n<p>For example here I do a solution for positive values where both lists and the output will fit in memory but overflow int/long:</p>\n<pre><code>List<Integer> revsum(Iterator<Integer> a, Iterator<Integer> b){\n var ans = new LinkedList<Integer>();\n int carry = 0;\n while(a.hasNext() || b.hasNext()){\n int A = a.hasNext() ? a.next() : 0;\n int B = b.hasNext() ? b.next() : 0;\n int S = A + B + carry;\n ans.add(S%10);\n carry = S /10;\n }\n if(carry > 0){\n ans.add(carry);\n }\n return ans;\n}\n\nList<Integer> forward(List<Integer> a, List<Integer> B){\n return revsum (a.descendingIterator(), b.descendingIterator()).reverse();\n}\n\nList<Integer> backward(List<Integer> a, List<Integer> B){\n return revsum (a.iterator(), b.iterator());\n}\n\n \n</code></pre>\n<p>You should practice and build a better version that can handle negative numbers and bad inputs as well.</p>\n<p>The best case conceivable time complexity is O(n) as you have to iterate all inputs. Likewise <em>additional</em> space complexity in addition to inputs and outputs is O(1) .</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T11:17:37.530",
"Id": "265547",
"ParentId": "263446",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265547",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T06:36:21.633",
"Id": "263446",
"Score": "1",
"Tags": [
"java",
"linked-list",
"complexity"
],
"Title": "SumList Cracking the coding Interview"
}
|
263446
|
<p>This is my implementation of the classic "Hangman" word-guessing game.</p>
<p>Class LePendu :</p>
<pre><code>public class LePendu {
// Variable
public static int NB_ERREURS_MAX=10;
static ArrayList<Character> playerGuess = new ArrayList<Character>();
static ArrayList <String> wrongGuess = new ArrayList<String>();
static ArrayList <String> playerWord = new ArrayList<String>();
static String penduDessin [][] = new String[10][10];
// Le Main :
public static void main(String args[]) throws FileNotFoundException {
Scanner sc = new Scanner (new File("C:/Users/admin/pendu.txt"));
Scanner charP = new Scanner (System.in);
while(sc.hasNext()) {
playerWord.add(sc.nextLine());
}
// Intitialisation Hangman :
initialize2dArray();
// Wordchoice :
Random motAleatoire = new Random();
String word = playerWord.get(motAleatoire.nextInt(playerWord.size()));
// Loop for the game :
int chance = 0;
while(true) {
penduEntier();
drawPendu(chance);
if (chance>word.length()) {
System.out.println("Perdu!!!!");
break;
}
displayWord(word, playerGuess);
if (!getPlayerChar(charP, word, playerGuess)) {
chance ++;
};
if(displayWord(word, playerGuess)) {
System.out.println("Victoire");
break;
}
System.out.println("Tentez votre chance pour le mot");
if(charP.nextLine().equals(word)) {
System.out.println("Victoire");
break;
} else {
System.out.println("Mot incorrect, veuillez réessayer");
}
}
}
// Méthode getPlayerChar :
private static boolean getPlayerChar(Scanner charP, String word, ArrayList<Character> playerGuess) {
System.out.println("Entrez une lettre svp");
String charPlayer = charP.nextLine();
playerGuess.add(charPlayer.charAt(0));
return word.contains(charPlayer);
}
// Méthode displayWord :
private static boolean displayWord(String word, ArrayList<Character> playerGuess) {
int count = 0;
for (int i = 0;i<word.length();i++) {
if(playerGuess.contains(word.charAt(i))) {
System.out.print(word.charAt(i));
count++;
}
else {
System.out.print("-");
}
}
System.out.println("");
return (word.length() == count);
}
// Draw Hangman Methode :
public static void penduEntier(){
// Loop through the entire 2D array to display Hangman image
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 10; column++) {
System.out.print(penduDessin[row][column]);
}
System.out.println();
}
}
// Tableau 2D Hangman :
public static void drawPendu(int chance) {
// The hangman will be erected from bottom to top, that is first gallos
// base will be made and then step by step hangman will be generated.
switch(chance) {
// we do not need add break in the cases because when players misses
// word after 8 chances then complete image of hangman is created.
case 8:
// Create legs of man
penduDessin[6][6] = "/";
penduDessin[7][5] = "/";
penduDessin[6][8] = "\\";
penduDessin[7][9] = "\\";
case 6:
// Create hands of man
penduDessin[4][6] = "/";
penduDessin[5][5] = "/";
penduDessin[4][8] = "\\";
penduDessin[5][9] = "\\";
case 5:
// Create tummy of man
for(int i = 3; i <= 5; i++)
penduDessin[i][7] = "|";
case 4:
// Create eyes and nose of man
penduDessin[2][6] = "*";
penduDessin[2][7] = "!";
penduDessin[2][8] = "*";
case 3:
// Create face of man
penduDessin[2][5] = "(";
penduDessin[2][9] = ")";
case 2:
// Create gallos
for(int i = 3; i <= 7; i++)
penduDessin[0][i] = "#";
penduDessin[1][7] = "#";
case 1:
// Create gallos
for(int i = 0; i <= 9; i++)
penduDessin[i][3] = "|";
case 0:
// Create base of gallos
for(int i = 0; i <= 8; i++)
penduDessin[8][i] = "_";
break;
default:
break;
}
}
// Initialize the hangman with space :
public static void initialize2dArray()
{
// Initialize the 2d array with blank spaces before printing the
// actual image of hangman.
for (int row = 0; row < 10; row++)
{
for (int column = 0; column < 10; column++)
{
penduDessin[row][column] = " ";
}
}
}
}
</code></pre>
<p>Thx for your help</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T13:14:57.820",
"Id": "520108",
"Score": "0",
"body": "thanks for moving it over from stackoverflow! seems to be better place here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T14:59:12.330",
"Id": "520114",
"Score": "0",
"body": "An user say me to move CodeReview. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T15:03:22.540",
"Id": "520115",
"Score": "0",
"body": "i read it - and upvoted that proposal =)"
}
] |
[
{
"body": "<h2>minor issues: language</h2>\n<p>source code is written in english. I don't speak english and many other don't do as well. that might be one reason why this review has no answers yet.</p>\n<ul>\n<li><code>NB_ERREURS_MAX</code></li>\n<li><code>String penduDessin</code></li>\n<li><code>Random motAleatoire</code></li>\n<li><code>penduEntier()</code></li>\n</ul>\n<h2>minor issue: hard-coded strings</h2>\n<p>as said that the source code is in english same applies for texts written. to handle such that you should use constants that provide an english name (but havin foreign content)</p>\n<p>instead of</p>\n<p><code>System.out.println("Victoire");</code></p>\n<p>you define a constant</p>\n<pre><code>static final String VICTORY_MESSAGE = "Victoire";\nstatic final String FAIL_MESSAGE = "Perdu!!!!";\n\n...\n\nif (chance>word.length()) {\n System.out.println(FAIL_MESSAGE);\n break;\n}\n</code></pre>\n<p>than everybody is able to understand the foreign text.</p>\n<p>Another important point is that would be a more "maintainable" code since you would have all String on one place and could easily translate them. (<code>open for enhancements</code> thats one part of S<strong>O</strong>LID)</p>\n<h2>minor issue: c-style array initialization</h2>\n<p>in java we declare arrays directly on the array type, instead of <code>String penduDessin [][]</code> we use <code>String[][] penduDessin</code></p>\n<h2>issue: single responsibility</h2>\n<p>your method <code>displayWord()</code> returns a boolean, because it does <strong>two</strong> things instead one. it</p>\n<ul>\n<li>displays the word</li>\n<li>checks if the word has been solved</li>\n</ul>\n<p>seperate them!</p>\n<p>the same applies for <code>getPlayerChar()</code> , this methods</p>\n<ul>\n<li>handles user input</li>\n<li>validates if it matches the secret word</li>\n</ul>\n<h2>major issue: objects and methods</h2>\n<p>you are using java but your code is not object orientated but procedural orientated. that leads to a lot of hard-to.read code.</p>\n<p>use objects: that's what first got into my mind, but you can decide different:</p>\n<ul>\n<li>HangmanGame (game logic)</li>\n<li>HangmanWord</li>\n<li>HangmanDisplay</li>\n<li>Dictionary</li>\n<li>Dictionary reader</li>\n<li>InputReader</li>\n</ul>\n<p>if you would split that code in such ways your code would be far more readable (maintainable)</p>\n<pre><code>public static void main(String args[]){\n Dictionary dic = new Dictionary(new FileDictReader().read(DICT_FILENAME));\n HangmanGame game = new HangmanGame(dict, new PlayerInputReader(), new HangmanDisplay());\n game.start();\n}\n</code></pre>\n<p>doing so you could clearly address tasks to object, for example getting a word from a given List:</p>\n<pre><code>HangmanWord wordToGuess = new HangManWord(dictionary.getRandom());\n</code></pre>\n<p>so we have a single responsibility for the dictionary: provide words!</p>\n<p>another example would be the dictionary reader:</p>\n<p>reading the dictionary from one source (file) and it's exception handling would be done by the DictionaryReader. you could also add another reader that lets you read URLs or any other source. The benefit would be that you don't have to change the dictionary for new readers.</p>\n<h2>major: seperate data from display</h2>\n<p>you should provide a data object for the state of your game: <code>HangmanWord</code>. this state would change whenever you add a letter to the HangmanWord.</p>\n<p><code>HangmanWord</code> is a data object and could provide all relevant information needed to play the game</p>\n<ul>\n<li><code>HangmanWord.isSolved()</code></li>\n<li><code>HangmanWord.isFailed()</code></li>\n<li><code>HangmanWord.getAmountFailures()</code></li>\n<li><code>HangmanWord.addCharacter()</code></li>\n<li><code>HangmanWord.getHiddenWord()</code></li>\n<li><code>HangmanWord.getGuesses()</code></li>\n</ul>\n<p>that would ease up the way your while-loop would look like</p>\n<h2>after-Thoughts</h2>\n<p>you should always try to avoid hard coupling, but hangman is a challenge. to avoid the direct dependency between <code>HangmanWord</code> and <code>HangmanPrinter</code> is not easily to achieve, since they are hardly connected by the amount of failures of the <code>HangmanWord</code> (and therefore the shape of the hangman). you already detected that dependency by using <code>NB_ERREURS_MAX</code> - i would really like to see a solution, where you (anyone) solved this dependency ^_^</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T06:46:14.693",
"Id": "520544",
"Score": "1",
"body": "Thx a lot for your response"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T07:15:48.180",
"Id": "520552",
"Score": "0",
"body": "you can accept the answer if you think it was helpful ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T05:53:23.673",
"Id": "263535",
"ParentId": "263448",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T10:15:43.350",
"Id": "263448",
"Score": "2",
"Tags": [
"java",
"hangman"
],
"Title": "Java hangman game"
}
|
263448
|
<p>I am building a WPF (Windows Presentation Foundation) application. And I'm trying to use the MVVM (Model–View–ViewModel) design pattern. It's fascinating and rewarding, even though it seems overly complex at times. I am new to programming, and I've only really dabbled in WinForms (Windows Forms) before.</p>
<p>I've been through so many changes and adaptations, by experimenting and trying to implement solutions, that I've sort of lost grip of everything I feel.</p>
<h2>Files</h2>
<p><strong>ViewModels</strong>:
<code>BaseViewModel.cs</code>
<code>MainViewModel.cs</code>
<code>AddViewModel.cs</code></p>
<p><strong>Models</strong>:
<code>ConnectionString.cs</code>
<code>LicenseHolder.cs</code>
<code>UserInfo.cs</code></p>
<p><strong>Views</strong>:
<code>HomeWindow.xaml</code>
<code>LicenseHolderProfileWindow.xaml</code>
<code>LicenseHoldersWindow.xaml</code>
<code>LoginScreenWindow.xaml</code>
<code>NewLicenseHolderWindow.xaml</code></p>
<h2>Application Flow</h2>
<p>The <code>LoginScreen</code> is the first window to open, which directs you to the <code>HomeWindow</code> when you log in.</p>
<p>The <code>HomeWindow</code> is basically an assortment of buttons leading to different parts of the application.
Currently only one part is under development at the moment, <code>LicenseHoldersWindow</code>.</p>
<p>The <code>LicenseHoldersWindow</code> contains a <code>DataGrid</code>; which is populated by a SQL server table, bound to an <code>ObservableCollection</code>.</p>
<h2>Concerns</h2>
<p>The <code>ObservableCollection</code> is where the tomfoolery begins.
At the moment I just want to do a few simple thing.
I could easily get things working with WinForms, howeer WPF is making things more challenging.</p>
<ol>
<li><p>I have the <code>DataGrid</code> automatically get the data from the server; without having to press any buttons.</p>
</li>
<li><p>I am able to delete rows by clicking a button.</p>
</li>
<li><p>I currently add rows, by:</p>
<ul>
<li>clicking a button,</li>
<li>opening a new window (<code>NewLicenseHolderWindow</code>),</li>
<li>filling out <code>TextBoxes</code> and clicking a save button (window closes), and</li>
<li>closing and re-opening the window (<code>LicensHoldersWindow</code>) (clunky way of doing things!)</li>
</ul>
</li>
</ol>
<p>I am also very interested in streamlining my application.<br />
I want it to fully adhere to the MVVM design pattern.
I want it to be slim, not bulky, I want it to be as <em>petite</em> as it possibly can be.
I feel like I am using far to much code-lines, and too many <code>.cs</code> files.
Is it possible to just use one <code>ViewModel</code>?
My <code>ConnectionString</code> and some arbitrary code to drag the entered <code>UserName</code> with me to correctly label the logout tag, which is the users e-mail address.
I feel it's not done properly.
Also, <code>LoginScreen.xaml</code> is placed in a the view, as you see, and that is not in line with MVVM principles.</p>
<h2>Code</h2>
<h3>Models</h3>
<p><code>ConnectionString.cs</code> - just my connection string.</p>
<p><code>LicenseHolder.cs</code> - my holder class, the getters/setters for the <code>DataGrid</code> columns.</p>
<pre><code>namespace Ridel.Hub.Model {
public class LicenseHolder {
public int ID { get; set; }
public string Foretaksnavn { get; set; }
public string Foretaksnummer { get; set; }
public string Adresse { get; set; }
public int Postnummer { get; set; }
public string Poststed { get; set; }
public string BIC { get; set; }
public string IBAN { get; set; }
public string Kontakt { get; set; }
public string Epost { get; set; }
public string Tlf { get; set; }
public string Kontonummer { get; set; }
}
}
</code></pre>
<p><code>UserInfo.cs</code> - simple class to bring with me the e-mail address of the logged in user to fill a label used as a 'Log out'-button.</p>
<pre><code>namespace Ridel.Hub {
public class UserInfo {
private const string userNameString = "";
public static string UserName { get; set; } = userNameString;
}
}
</code></pre>
<h3>ViewModels</h3>
<p><code>MainViewModel</code></p>
<pre><code>using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows;
using GalaSoft.MvvmLight.CommandWpf;
using Ridel.Hub.Model;
namespace Ridel.Hub.ViewModel {
public class MainViewModel : AddViewModel, INotifyPropertyChanged {
public MainViewModel() {
FillDataGridLicenseHolders();
}
// This method triggers when the user clicks the log out button (which is their e-mail address)
public static void CloseAllWindowsExceptLoginScreen() {
Application.Current.Windows
.Cast<Window>()
.Where(w => w is not LoginScreenWindow)
.ToList()
.ForEach(w => w.Close());
MainViewModel viewModel = new MainViewModel();
LoginScreenWindow loginScreen = new LoginScreenWindow(viewModel);
loginScreen.Show();
}
public void FillDataGridLicenseHolders() {
try {
using (SqlConnection sqlCon = new(ConnectionString.connectionString))
using (SqlCommand sqlCmd = new("select * from tblLicenseHolder", sqlCon))
using (SqlDataAdapter sqlDaAd = new(sqlCmd))
using (DataSet ds = new()) {
sqlCon.Open();
sqlDaAd.Fill(ds, "tblLicenseHolder");
foreach (DataRow dr in ds.Tables[0].Rows) {
// Adding the rows in the DataGrid to the ObservableCollection
LicenseHolders.Add(new LicenseHolder {
ID = Convert.ToInt32(dr[0].ToString()),
Foretaksnavn = dr[1].ToString(),
Foretaksnummer = dr[2].ToString(),
Adresse = dr[3].ToString(),
Postnummer = (int)dr[4],
Poststed = dr[5].ToString(),
BIC = dr[6].ToString(),
IBAN = dr[7].ToString(),
Kontakt = dr[8].ToString(),
Epost = dr[9].ToString(),
Tlf = dr[10].ToString(),
Kontonummer = dr[11].ToString()
});
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private static bool RemoveFromDB(LicenseHolder myLicenseHolder) {
string sqlString = $"Delete from tblLicenseHolder where ID = '{myLicenseHolder.ID}'";
if (MessageBox.Show("Er du sikker på at du ønsker å slette valgt løyvehaver?", "Slett løyvehaver", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes) {
try {
using (SqlConnection sqlCon = new(ConnectionString.connectionString))
using (SqlCommand sqlCmd = new(sqlString, sqlCon)) {
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
return true;
}
}
catch {
return false;
}
} else {
return false;
}
}
private void RemoveLicenseHolderExecute(LicenseHolder myLicenseHolder) {
bool result = RemoveFromDB(myLicenseHolder);
if (result)
LicenseHolders.Remove(myLicenseHolder);
}
private RelayCommand<LicenseHolder> _removeLicenseHoldersCommand;
public RelayCommand<LicenseHolder> RemoveLicenseHoldersCommand => _removeLicenseHoldersCommand
??= new RelayCommand<LicenseHolder>(RemoveLicenseHolderExecute, RemoveLicenseHolderCanExecute);
private bool RemoveLicenseHolderCanExecute(LicenseHolder myLicenseHolder) {
return LicenseHolders.Contains(myLicenseHolder);
}
}
}
</code></pre>
<p><code>AddViewModel</code> - this is newly added, based on some feed-back I got, and it was at this point I felt things really got out of hand</p>
<pre><code>using System;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Windows;
using System.Windows.Input;
using GalaSoft.MvvmLight.CommandWpf;
using Ridel.Hub.Model;
namespace Ridel.Hub.ViewModel {
public class AddViewModel : BaseViewModel {
public ObservableCollection<LicenseHolder> LicenseHolders { get; set; }
public ICommand RefreshCommand { get; private set; }
public AddViewModel() {
RefreshCommand = new RelayCommand(this.ExecuteRefreshCommand);
LicenseHolders = new ObservableCollection<LicenseHolder>();
}
private string _foretaksnavn;
public string Foretaksnavn {
get { return _foretaksnavn; }
set { SetValue(ref _foretaksnavn, value); }
}
private string _foretaksnummer;
public string Foretaksnummer {
get { return _foretaksnummer; }
set { SetValue(ref _foretaksnummer, value); }
}
private string _adresse;
public string Adresse {
get { return _adresse; }
set { SetValue(ref _adresse, value); }
}
private int _postnummer;
public int Postnummer {
get { return _postnummer; }
set { SetValue(ref _postnummer, value); }
}
private string _poststed;
public string Poststed {
get { return _poststed; }
set { SetValue(ref _poststed, value); }
}
private string _bic;
public string BIC {
get { return _bic; }
set { SetValue(ref _bic, value); }
}
private string _iban;
public string IBAN {
get { return _iban; }
set { SetValue(ref _iban, value); }
}
private string _kontakt;
public string Kontakt {
get { return _kontakt; }
set { SetValue(ref _kontakt, value); }
}
private string _epost;
public string Epost {
get { return _epost; }
set { SetValue(ref _epost, value); }
}
private string _tlf;
public string Tlf {
get { return _tlf; }
set { SetValue(ref _tlf, value); }
}
private string _kontonummer;
public string Kontonummer {
get { return _kontonummer; }
set { SetValue(ref _kontonummer, value); }
}
private void ExecuteRefreshCommand() {
string sqlString = "insert into tblLicenseHolder (Foretaksnavn, Foretaksnummer, Adresse, Postnummer, Poststed, BIC, IBAN, Kontakt, Epost, Tlf, Kontonummer) " +
"values (@Foretaksnavn, @Foretaksnummer, @Adresse, @Postnummer, @Poststed, @BIC, @IBAN, @Kontakt, @Epost, @Tlf, @Kontonummer)";
if (Foretaksnavn == null || Foretaksnummer == null || Adresse == null
|| Postnummer == 0 || Poststed == null || BIC == null || IBAN == null
|| Kontakt == null || Epost == null || Tlf == null || Kontonummer == null) {
MessageBox.Show("Fyll ut alle feltene.");
} else {
LicenseHolders = new ObservableCollection<LicenseHolder>();
LicenseHolders.Add(new LicenseHolder() { Foretaksnavn = "Foretaksnavn" });
LicenseHolders.Add(new LicenseHolder() { Foretaksnummer = "Foretaksnummer" });
LicenseHolders.Add(new LicenseHolder() { Adresse = "Adresse" });
LicenseHolders.Add(new LicenseHolder() { Postnummer = Postnummer });
LicenseHolders.Add(new LicenseHolder() { Poststed = "Poststed" });
LicenseHolders.Add(new LicenseHolder() { BIC = "BIC" });
LicenseHolders.Add(new LicenseHolder() { IBAN = "IBAN" });
LicenseHolders.Add(new LicenseHolder() { Kontakt = "Kontakt" });
LicenseHolders.Add(new LicenseHolder() { Epost = "Epost" });
LicenseHolders.Add(new LicenseHolder() { Tlf = "Tlf" });
LicenseHolders.Add(new LicenseHolder() { Kontonummer = "Kontonummer" });
try {
using (SqlConnection sqlCon = new(ConnectionString.connectionString))
using (SqlCommand sqlCmd = new(sqlString, sqlCon)) {
sqlCon.Open();
sqlCmd.Parameters.AddWithValue("@Foretaksnavn", Foretaksnavn.ToString());
sqlCmd.Parameters.AddWithValue("@Foretaksnummer", Foretaksnummer.ToString());
sqlCmd.Parameters.AddWithValue("@Adresse", Adresse.ToString());
sqlCmd.Parameters.AddWithValue("@Postnummer", Convert.ToInt32(Postnummer.ToString()));
sqlCmd.Parameters.AddWithValue("@Poststed", Poststed.ToString());
sqlCmd.Parameters.AddWithValue("@BIC", BIC.ToString());
sqlCmd.Parameters.AddWithValue("@IBAN", IBAN.ToString());
sqlCmd.Parameters.AddWithValue("@Kontakt", Kontakt.ToString());
sqlCmd.Parameters.AddWithValue("@Epost", Epost.ToString());
sqlCmd.Parameters.AddWithValue("@Tlf", Tlf.ToString());
sqlCmd.Parameters.AddWithValue("@Kontonummer", Kontonummer.ToString());
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Ny løyvehaver lagret.");
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
}
}
</code></pre>
<p>I am especially uncertain about how I've structured the <code>ExecuteRefreshCommand()</code>-method.
The addition to the server is no problem, but adding to the <code>ObservableCollection</code> is clunky, as I have to re-open the window. Hopefully, there is a way to simplify and compact those two tasks into one: add to server & update <code>ObservableCollection</code>. Also, the getters/setters strings seems redundant, can't I get and set what I need using the <code>LicenseHolder.cs</code> <code>model class</code>?</p>
<p><code>BaseViewModel</code></p>
<pre><code>using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Ridel.Hub.ViewModel {
public abstract class BaseViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
var handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected bool SetValue<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) {
if (Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
}
}
</code></pre>
<h3>Views</h3>
<p>I will omit the Windows which are irrelevant (at least to my understanding).
I am only posting the code-behind and the XAML from <code>LicenseHoldersWindow</code>, <code>NewLicenseHolderWindow</code> and <code>LicenseHolderProfileWindow</code>. I'll trim away some of the XAML to make it somewhat readable.</p>
<p><code>LicenseHoldersWindow</code></p>
<pre><code><Window
x:Class="Ridel.Hub.LicenseHoldersWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Ridel.Hub"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewmodel="clr-namespace:Ridel.Hub.ViewModel" d:DataContext="{d:DesignInstance Type=viewmodel:MainViewModel}"
ShowInTaskbar="False"
mc:Ignorable="d">
<Canvas Margin="10,10,10,10">
<Button
x:Name="btnLogOut"
Click="btnLogOut_Click"
Content="LoggedInUser"
Style="{DynamicResource ButtonWithOnlyText}" />
<Button
x:Name="btnProfile"
Background="#48bb88"
Content="Open profile"
Style="{DynamicResource ButtonWithRoundCornersGreen}"
Visibility="Visible" Click="btnProfile_Click" />
<Button
x:Name="btnNew"
Click="btnNew_Click"
Content="New licenseholder"
Style="{DynamicResource ButtonWithRoundCornersGreen}" />
<Button
x:Name="btnDelete"
Command="{Binding RemoveLicenseHoldersCommand}"
CommandParameter="{Binding SelectedItem, ElementName=dgLicenseHolder}"
Content="Delete licenseholder"
Style="{DynamicResource ButtonWithRoundCornersGreen}" />
<DataGrid
x:Name="dgLicenseHolder"
CanUserAddRows="False"
CanUserDeleteRows="False"
IsReadOnly="True"
SelectionChanged="dgLicenseHolder_SelectionChanged"
ItemsSource="{Binding LicenseHolders}"
SelectionMode="Single">
<DataGrid.Columns>
<DataGridTextColumn
Binding="{Binding Path=ID}"
Header="ID"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Width="310"
Binding="{Binding Path=Foretaksnavn}"
Header="Foretaksnavn"
HeaderStyle="{StaticResource CenterGridHeaderStyle}"
IsReadOnly="True"
Visibility="Visible" />
<DataGridTextColumn
Binding="{Binding Path=Foretaksnummer}"
Header="Foretaksnummer"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Binding="{Binding Path=Adresse}"
Header="Adresse"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Binding="{Binding Path=Postnummer}"
Header="Postnummer"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Width="*"
Binding="{Binding Path=Poststed}"
Header="Poststed"
HeaderStyle="{StaticResource CenterGridHeaderStyle}"
IsReadOnly="True"
Visibility="Visible" />
<DataGridTextColumn
Binding="{Binding Path=BIC}"
Header="BIC"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Binding="{Binding Path=IBAN}"
Header="IBAN"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Binding="{Binding Path=Kontakt}"
Header="Kontakt"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Binding="{Binding Path=Epost}"
Header="Epost"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Binding="{Binding Path=Tlf}"
Header="Tlf"
IsReadOnly="True"
Visibility="Collapsed" />
<DataGridTextColumn
Binding="{Binding Path=Kontonummer}"
Header="Kontonummer"
IsReadOnly="True"
Visibility="Collapsed" />
</DataGrid.Columns>
</DataGrid>
</Canvas>
</Window>
</code></pre>
<pre><code>using System.Windows;
using System.Windows.Controls;
using Ridel.Hub.ViewModel;
namespace Ridel.Hub {
public partial class LicenseHoldersWindow : Window {
public LicenseHoldersWindow(MainViewModel viewModel) {
InitializeComponent();
btnLogOut.Content = UserInfo.UserName;
DataContext = viewModel;
}
private void btnLogOut_Click(object sender, RoutedEventArgs e) {
if (MessageBox.Show("Er du sikker på at du ønsker å logge ut?", "Logg ut", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) {
MainViewModel.CloseAllWindowsExceptLoginScreen();
}
}
private void dgLicenseHolder_SelectionChanged(object sender, SelectionChangedEventArgs e) {
btnProfile.IsEnabled = true;
btnDelete.IsEnabled = true;
}
private void btnNew_Click(object sender, RoutedEventArgs e) {
NewLicenseHolderWindow nlhw = new NewLicenseHolderWindow();
nlhw.ShowDialog();
}
private void btnProfile_Click(object sender, RoutedEventArgs e) {
if (this.dgLicenseHolder.SelectedItems.Count == 1) {
LicenseHolderProfileWindow lpw = new LicenseHolderProfileWindow(null) { Owner = this, DataContext = dgLicenseHolder.SelectedItem };
lpw.ShowDialog();
}
}
}
}
</code></pre>
<p><code>NewLicenseHolderWindow</code></p>
<pre><code><Window
x:Class="Ridel.Hub.NewLicenseHolderWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewmodel="clr-namespace:Ridel.Hub.ViewModel" d:DataContext="{d:DesignInstance Type=viewmodel:AddViewModel}"
ResizeMode="NoResize"
ShowInTaskbar="False"
mc:Ignorable="d">
<Canvas Margin="10,10,42,10">
<Button
Name="btnLogOut"
Click="btnLogOut_Click"
Content="LoggedInUser"
Style="{DynamicResource ButtonWithOnlyText}" />
<TextBox
Name="txtKontakt"
Text="{Binding Path=Kontakt}"/>
<TextBox
Name="txtTlf"
Text="{Binding Path=Tlf}"/>
<TextBox
Name="txtEpost"
Text="{Binding Path=Epost}"/>
<TextBox
Name="txtForetaksnavn"
Text="{Binding Path=Foretaksnavn}" />
<TextBox
Name="txtForetaksnr"
Text="{Binding Path=Foretaksnummer}"/>
<TextBox
Name="txtAdresse"
Text="{Binding Path=Adresse}"/>
<TextBox
Name="txtPoststed"
Text="{Binding Path=Poststed}"/>
<TextBox
Name="txtPostnummer"
Text="{Binding Path=Postnummer}"/>
<TextBox
Name="txtBIC"
Text="{Binding Path=BIC}"/>
<TextBox
Name="txtIBAN"
Text="{Binding Path=IBAN}"/>
<TextBox
Name="txtKontonr"
Text="{Binding Path=Kontonummer}"/>
<Button
Name="btnSave"
Command="{Binding Path=RefreshCommand}"
Content="Save"
Style="{DynamicResource ButtonWithRoundCornersGreen}">
</Button>
</Canvas>
</Window>
</code></pre>
<pre><code>using System.ComponentModel;
using System.Linq;
using System.Windows;
using Ridel.Hub.ViewModel;
namespace Ridel.Hub {
public partial class NewLicenseHolderWindow : Window, INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
public NewLicenseHolderWindow() {
InitializeComponent();
btnLogOut.Content = UserInfo.UserName;
}
private void btnLogOut_Click(object sender, RoutedEventArgs e) {
if (MessageBox.Show("Er du sikker på at du ønsker å logge ut?", "Logg ut", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) {
MainViewModel.CloseAllWindowsExceptLoginScreen();
}
}
}
}
</code></pre>
<p><code>LicenseHolderProfileWindow</code></p>
<pre><code><Window
x:Class="Ridel.Hub.LicenseHolderProfileWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewmodel="clr-namespace:Ridel.Hub.ViewModel" d:DataContext="{d:DesignInstance Type=viewmodel:AddViewModel}"
mc:Ignorable="d">
<Canvas Margin="10,10,42,10">
<Button
Name="btnLogOut"
Click="btnLogOut_Click"
Content="LoggedInUser"
Style="{DynamicResource ButtonWithOnlyText}" />
<TextBox
Name="txtKontakt"
Text="{Binding Kontakt, Mode=TwoWay, FallbackValue=Kontakt}" />
<TextBox
Name="txtTlf"
Text="{Binding Tlf, Mode=TwoWay, FallbackValue=Tlf}" />
<TextBox
Name="txtEpost"
Text="{Binding Epost, Mode=TwoWay, FallbackValue=Epost}" />
<TextBox
Name="txtForetaksnavn"
Text="{Binding Foretaksnavn, Mode=TwoWay, FallbackValue=Foretaksnavn}" />
<TextBox
Name="txtForetaksnr"
Text="{Binding Foretaksnummer, Mode=TwoWay, FallbackValue=Foretaksnummer}" />
<TextBox
Name="txtAdresse"
Text="{Binding Adresse, Mode=TwoWay, FallbackValue=Adresse}" />
<TextBox
Name="txtPoststed"
Text="{Binding Poststed, Mode=TwoWay, FallbackValue=Poststed}" />
<TextBox
Name="txtPostnummer"
Text="{Binding Postnummer, Mode=TwoWay, FallbackValue=Postnummer}" />
<TextBox
Name="txtBIC"
Text="{Binding BIC, Mode=TwoWay, FallbackValue=BIC}" />
<TextBox
Name="txtIBAN"
Text="{Binding IBAN, Mode=TwoWay, FallbackValue=IBAN}" />
<TextBox
Name="txtKontonr"
IsReadOnly="True"
Text="{Binding Kontonummer, Mode=TwoWay, FallbackValue=Kontonummer}" />
<Button
Name="btnLagre"
Click="btnLagre_Click"
Command="{Binding RefreshCommand}"
Content="Lagre"
Style="{DynamicResource ButtonWithRoundCornersGreen}" />
</Canvas>
</Window>
</code></pre>
<pre><code>using System.Windows;
using Ridel.Hub.ViewModel;
namespace Ridel.Hub {
public partial class LicenseHolderProfileWindow : Window {
public LicenseHolderProfileWindow(AddViewModel viewModel) {
InitializeComponent();
DataContext = viewModel;
}
private void btnLogOut_Click(object sender, RoutedEventArgs e) {
if (MessageBox.Show("Er du sikker på at du ønsker å logge ut?", "Logg ut", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) {
MainViewModel.CloseAllWindowsExceptLoginScreen();
}
}
private void btnSave_Click(object sender, RoutedEventArgs e) {
btnAllowEdit.IsEnabled = true;
Close();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T09:43:24.817",
"Id": "520275",
"Score": "0",
"body": "I haven't received any pointers, please let me know if I am being unclear in the presentation of my project. Any perspective on improvement will still be very much appreciated."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T11:56:20.917",
"Id": "263450",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"wpf",
"mvvm",
"databinding"
],
"Title": "License-holder editing application"
}
|
263450
|
<p>This is a Python 3 script that statistically analyzes 105,230 words with a total of 913,935 characters, its results will be used for pseudoword generation purposes.</p>
<p>You will need <a href="https://drive.google.com/file/d/1kF-sK_RpcpIO3jxOUnJvnlctdaDRLI9o" rel="nofollow noreferrer">this file</a> for it to run.</p>
<p>This script analyzes the following things:</p>
<ul>
<li><p>1, How many words contains each of the 26 letters.</p>
</li>
<li><p>2, How many times each of the letters has occurred in the total characters of all the words.</p>
</li>
<li><p>3, How many words are of x length for all possible frequent lengths.</p>
</li>
<li><p>4, Given an integer from 1 to 5, for all possible combinations of the letters of the integer length, how many words start with each of these combinations (minus the infrequent ones).</p>
</li>
<li><p>5, Like the above, but count how many words ends with the combination instead.</p>
</li>
<li><p>6, In all the words, how many letters b has followed letter a for each b in the 26 letters for each a in the 26 letters.</p>
</li>
</ul>
<p>The outputs are in <code>.json</code> format.</p>
<p>Here is the script:</p>
<pre class="lang-py prettyprint-override"><code>import json
from collections import Counter
from itertools import product
from pathlib import Path
from string import ascii_lowercase
def process(obj):
obj = obj.most_common()
obj = [(k, v) for k, v in obj if v >= 20]
return dict(sorted(obj, key=lambda x: (-x[1], x[0])))
def writer(var):
Path(f'D:/corpus/{var}.json').write_text(json.dumps(eval(var), indent=4))
words = set(Path('D:/corpus/gcide_dict.txt').read_text().splitlines())
word_length = Counter(len(i) for i in words)
word_length = process(word_length)
writer('word_length')
letter_in_word = dict(Counter({i: sum(i in j for j in words) for i in ascii_lowercase}).most_common())
all_words = Counter(''.join(words))
len_all_words = len(''.join(words))
letter_frequency = all_words.most_common()
letter_frequency = {i[0]: {'count': i[1], 'frequency': i[1] / len_all_words} for i in letter_frequency}
writer('letter_in_word')
writer('letter_frequency')
for i in range(5):
prefix = Counter(j[:i + 1] for j in words if len(j) >= i + 1)
prefix = process(prefix)
suffix = Counter(j[::-1][:i + 1][::-1] for j in words if len(j) >= i + 1)
suffix = process(suffix)
vars().update({f'prefix_{i + 1}': prefix, f'suffix_{i + 1}': suffix})
for i in range(5):
writer(f'prefix_{i + 1}')
writer(f'suffix_{i + 1}')
letter_follow = {i: {j[1]: sum(k.count(''.join(j)) for k in words) for j in product(i, ascii_lowercase)} for i in ascii_lowercase}
letter_follow = {key: process(Counter(letter_follow[key])) for key in ascii_lowercase}
writer('letter_follow')
</code></pre>
<p>As usual, I want to ask about performance, are my implementations efficient?</p>
<p>What libraries I can use to help speed up the execution?</p>
<p>How can my code be optimized?</p>
<p>Then, I want to ask about data storage and retrieval, I can use SQL but I don't know how should the data be stored;</p>
<p>How many tables do I need?</p>
<p>How should I store nested dictionaries in a table?</p>
<p>How can I store the data most integrally?</p>
<p>I am looking for a <code>sqlite3</code> way to store the data.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T13:51:52.477",
"Id": "263452",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"statistics",
"data-mining"
],
"Title": "Python 3 script for statistiscal analysis of English vocabulary"
}
|
263452
|
<p>Second day coding so I'm new to this. I have made this simple calculator but I repeat the code in order to use the previous answer in the next calculation. I've been trying to simplify it but I can't seem to figure it out. Whatever I try breaks the code. Any feed back helps.
Here is the code</p>
<pre><code># Beginning calculator code
first_number = "a"
second_number = ""
carry_number = ""
operation = ""
while first_number == "a":
first_number = float(input("Enter your first number: "))
operation = input("You can enter c to exit calculator \nWhat operation? ")
second_number = float(input("What is your second number? "))
if operation == "+":
carry_number = (first_number + second_number)
elif operation == "-":
carry_number = (first_number - second_number)
elif operation == "/":
carry_number = (first_number / second_number)
elif operation == "*":
carry_number = (first_number * second_number)
print(first_number, operation, second_number, "=", carry_number)
first_number = carry_number
while True:
operation = input("You can enter c to exit calculator \nWhat operation? ")
if operation == "c":
quit()
second_number = float(input("What is your second number? "))
if operation == "+":
carry_number = (first_number + second_number)
elif operation == "-":
carry_number = (first_number - second_number)
elif operation == "/":
carry_number = (first_number / second_number)
elif operation == "*":
carry_number = (first_number * second_number)
print(first_number, operation, second_number, "=", carry_number)
first_number = carry_number
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T15:19:16.747",
"Id": "520118",
"Score": "1",
"body": "Welcome and thanks for joining CodeReview! I hope that you get some good feedback; this is a great first question."
}
] |
[
{
"body": "<ul>\n<li>Notice that you have a bunch of repeated code; let's reduce this</li>\n<li>There's no need to pre-initialize your variables in the first five lines of your code</li>\n<li>Your first <code>while</code> loop doesn't deserve to exist; the condition is only evaluated <code>True</code> once</li>\n<li>No need to surround your operations in parens</li>\n</ul>\n<p>There's a lot of other things you could do to improve this, but without getting too advanced, you could write this to be as simple as</p>\n<pre><code># Beginning calculator code\n\nfirst_number = float(input('Enter your first number: '))\n\nwhile True:\n print('You can enter c to exit calculator')\n operation = input('What operation? ')\n if operation == 'c':\n quit()\n \n second_number = float(input('What is your second number? '))\n if operation == '+':\n carry_number = first_number + second_number\n elif operation == '-':\n carry_number = first_number - second_number\n elif operation == '/':\n carry_number = first_number / second_number\n elif operation == '*':\n carry_number = first_number * second_number\n\n print(first_number, operation, second_number, '=', carry_number)\n first_number = carry_number\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T17:20:01.033",
"Id": "520131",
"Score": "0",
"body": "First off thank you for the explanation. It made sense to me right away when you wrote it like that. So when you said I don't need to pre-initialize the variables you meant the lines that I wrote \"first number = second number = etc..\". The program automatically can keep track of the values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T17:21:02.623",
"Id": "520132",
"Score": "1",
"body": "Lines like `first_number = \"a\"` that get overwritten before they're read."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T15:32:20.587",
"Id": "263458",
"ParentId": "263456",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263458",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T14:43:10.593",
"Id": "263456",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "Calculator for basic arithmetic operations"
}
|
263456
|
<p>I want to replace every <code>div</code> with the class <code>mention</code>. The text should then be parsed and all the parts with <code>@user</code> should be replaced with a link. Here is what I have:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function rstr(id){
text = id.innerHTML;
replace = text.replace(/@([a-z\d_]+)/ig, '<a target="_blank" href="https://twitter.com/$1">@$1</a>');
id.innerHTML = replace;
}
x = document.querySelectorAll("p, span");
for(i = 0; i < x.length; i++) {
has = x[i].querySelector("a, button, script, style") != null;
if(has){}else{
rstr(x[i]);
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>@StackOverflow what is up? Are you like @Quora</p>
<p>@Samsung, @Apple, @Google what is up y'all? Are you still hanging out with @BlackBerry</p>
<p><a href="https://example.com/@dontparsethis">just testing if it parses urls</a> @doesitwork</p></code></pre>
</div>
</div>
</p>
<p><strong>Is there any way I can optimize/speed up the javascript above, or is there a better way to do this?</strong></p>
<p>EDIT: I added my full code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T16:12:29.510",
"Id": "520124",
"Score": "0",
"body": "There are ways to write this to \"improve performance\". However, is performance really a concern for this snippet? Is it actually slow in the real world use case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T17:48:32.663",
"Id": "520133",
"Score": "0",
"body": "@Joseph, no it is not a big concern, although I am wondering, if I do this on all text on a page, will there be performance issues, or is it ok?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T15:39:33.450",
"Id": "520233",
"Score": "0",
"body": "Why not create a large page and see for yourself?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T15:35:43.257",
"Id": "263459",
"Score": "0",
"Tags": [
"javascript",
"performance",
"regex"
],
"Title": "Optimize Javascript User Mentioning"
}
|
263459
|
<p>Let's say I'm implementing a method that calculates the number of hours I'm billing a client. I only work in blocks of <code>K</code> hours:</p>
<pre><code>public static int billing(int hours, int k) {
return hours / k + (hours % k != 0 ? 1 : 0);
}
</code></pre>
<p>Is it possible to simplify this? I often find myself writing this same pattern of code but it somehow bothers me.</p>
<p>I could think of</p>
<pre><code>public static int billing(int hours, int k) {
return (int)Math.ceil((double)hours / (double)k);
}
</code></pre>
<p>but I'd prefer staying in the realm of integers if possible.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T16:31:07.917",
"Id": "520128",
"Score": "1",
"body": "What about `(hours+k-1)/k`?"
}
] |
[
{
"body": "<p>Given the integer operations available on a typical CPU, there's really no way to do it other than to determine whether the remainder is 0 and conditionally round up if it was not.</p>\n<p>However, since you often find yourself using this pattern, write it once. Not limited to "int hours", but the integer equiv. of ceiling, dividing but rounding up. Then you can use the clearly named function when you need it, <em>and</em> the code is only in one place so if you find a way to determine that the remainder is non-zero that's faster than actually doing the division, you can change it in one place.</p>\n<p>Note that since you are doing the division <em>anyway</em>, and the CPU instruction (on x86 at least; most work this way) deliver the div and remainder simultaneously, the optimizer should only do the operation once and get the remainder for free. A fancy number-theory way of finding out whether the remainder is non-zero (without caring what it actually is) would only be more operations to perform.</p>\n<hr />\n<p>Oh, I remember how I used to do it back in the day: Add one less than the denominator and that will force it to round up, but if the result would have been exact you didn't add enough to increase it at all.</p>\n<p><code>return (hours+k-1)/k;</code></p>\n<p>Again, if you encapsulate this with "ceiling division" call, you can figure out which was is faster and the code is only in one place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T18:45:09.440",
"Id": "520138",
"Score": "0",
"body": "Could you elaborate on \"didn't add enough to increase it at all\"? I don't see why that formula shouldn't work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T19:58:03.317",
"Id": "520145",
"Score": "2",
"body": "Yes, adding one less than the divisor is the standard way to get upwards-rounding division. Do be aware that the intermediate value could overflow where the plain division would not - in most cases, this is unlikely to be a practical problem, but it could be a concern when values are close to the limit of `int`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T13:54:33.407",
"Id": "520292",
"Score": "0",
"body": "@danzel if `hours` is a multiple of `k`, adding `k-1` will not increase the total enough to change the (truncated) quotient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T14:31:51.037",
"Id": "520296",
"Score": "0",
"body": "@JDlugosz that's exactly the expected behaviour. If `hours` is a multiple of `k`, the expected result is `hours/k` (not `(hours/k)+1`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T14:54:09.457",
"Id": "520301",
"Score": "0",
"body": "@danzel Of course it is; that's why it's a useful way to do it -- it gives the right answer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T16:39:23.060",
"Id": "263464",
"ParentId": "263463",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263464",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T16:16:09.017",
"Id": "263463",
"Score": "0",
"Tags": [
"java",
"algorithm"
],
"Title": "Calculate the minimum amount of billing hours"
}
|
263463
|
<p>I'm not sure if the problem here is how I'm wording the question or going about finding an answer, but I have what I think is a relatively trivial task: getting fact-check claims from the Google Fact Check API, saving them in a database and then using that database to get the counts of fact checked claims & who claimed them.</p>
<p>The project is available <a href="https://github.com/kcinnick/gfc" rel="nofollow noreferrer">here</a> and the specific piece of code I'm wondering about is <a href="https://github.com/kcinnick/gfc/blob/main/main.py#L85-L104" rel="nofollow noreferrer">here</a>. What I'm trying to accomplish here is basically getting a count of claims by the claimant and the claims themselves. Here's an output of that function:</p>
<pre><code>The Gateway Pundit
{'claims': [Says Joe Biden “imports oil from Iran.”], 'number_of_claims': 1}
~~~
Real Raw News, social media users
{'claims': [Hillary Clinton was hanged at Guantanamo Bay], 'number_of_claims': 1}
~~~
Posts on Facebook and Instagram
{'claims': [Donald Trump has been permitted to once again use the Facebook and Instagram accounts he used when US president.], 'number_of_claims': 1}
~~~
Donald Trump
{'claims': [Georgia didn’t update its voter rolls prior to the 2020 presidential election; “this means we (you!) won the presidential election in Georgia.”, “Thank you and congratulations to Laura Baigert of the Georgia Star News on the incredible reporting you have done. Keep going! The scam [in Fulton County, Georgia] is all unraveling fast.”, Twitter banned President Muhammadu Buhari, “Republican state senators” who started an audit of 2020 election results in Maricopa County are “exposing this fraud.”], 'number_of_claims': 4}
~~~
Joe Biden
{'claims': [“In my first four months in office, more than two million jobs have been created. That’s more than double the rate of my predecessor, and more than eight times the rate of President Reagan.”], 'number_of_claims': 1}
</code></pre>
<p>My question is: it seems there must be a much easier way to get what I'm after without doing the whole <code>defaultdict</code> dance we're doing in <a href="https://github.com/kcinnick/gfc/blob/main/main.py#L93-L97" rel="nofollow noreferrer">93-97</a> - I suspect there's a pretty easy way to do what I'm doing there with a more clever SQL query, but it's eluding me right now. Any ideas? Of course, any other comments on the code are very much appreciated as well!</p>
<p><code>main.py</code>:</p>
<pre><code>import datetime
import os
from collections import defaultdict
import requests
from sqlalchemy import create_engine, func
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from models import Claim, Claimant, claims, claimants
def create_db_session():
engine = create_engine(
f"postgresql+psycopg2://postgres:"
+ f"{os.getenv('POSTGRES_PASSWORD')}@127.0.0.1"
+ f":5432/gfc",
poolclass=NullPool,
)
Session = sessionmaker(bind=engine)
session = Session()
return session
def get_api_key():
API_KEY = os.getenv("API_KEY")
if API_KEY is None:
raise EnvironmentError(
"Need API_KEY to be set to valid Google Fact Check Tools API key.\n"
)
return API_KEY
def process_claim(claim, session):
claimant = Claimant(name=claim["claimant"])
session.add(claimant)
try:
session.commit()
except IntegrityError:
print(f'Claimant "{claimant.name}" is already in the database.')
session.rollback()
claimant = session.query(Claimant).where(Claimant.name == claimant.name).first()
claim = Claim(
text=claim["text"],
date=datetime.datetime.strptime(claim["claimDate"][:-10], '%Y-%m-%d').date(),
claimant=claimant
)
session.add(claim)
try:
session.commit()
except IntegrityError:
print(f'Claim "{claim.text}" is already in the database.')
session.rollback()
return claim
def search_query(API_KEY):
url = (
f"https://content-factchecktools.googleapis.com/v1alpha1/claims:search?"
f"pageSize=10&"
f"query=biden&"
f"maxAgeDays=30&"
f"offset=0&languageCode=en-US&key={API_KEY}"
)
r = requests.get(url, headers={"x-referer": "https://explorer.apis.google.com"})
data = r.json()
next_page_token = data.get("nextPageToken")
claims = data.pop("claims")
return claims
def main():
API_KEY = get_api_key()
claims = search_query(API_KEY=API_KEY)
session = create_db_session()
for claim in claims:
process_claim(claim, session)
def source_of_claims(session):
results = session.query(
claims._columns['claimant_id'], # id of claimant
func.count(claims._columns['claimant_id']) # number of claims claimant is responsible for
).group_by(
claims._columns['claimant_id']
).all() # returns tuple of claimant_id, # of instances
parsed_results = defaultdict(list)
for result in results:
claimant = session.query(Claimant).get(ident=result[0])
claims_ = session.query(Claim).where(Claim.claimant_id == claimant.id).all()
parsed_results[claimant] = dict(claims=claims_, number_of_claims=len(claims_))
for key, value in parsed_results.items():
print('~~~')
print(key)
print(value)
# TODO: build claim result stuff
return parsed_results
if __name__ == "__main__":
session = create_db_session()
source_of_claims(session=session)
</code></pre>
<p><code>models.py</code>:</p>
<pre><code>from sqlalchemy import Column, Date, ForeignKey, Integer, MetaData, Table, Text
from sqlalchemy.orm import declarative_base, relationship
Base = declarative_base()
metadata = MetaData()
class Claim(Base):
__tablename__ = "claims"
id = Column(Integer, primary_key=True)
text = Column(Text, unique=True)
date = Column(Date)
claimant_id = Column(Integer, ForeignKey("claimants.id"))
claimant = relationship("Claimant")
def __str__(self):
return f"{self.text}"
def __repr__(self):
return f"{self.text}"
class Claimant(Base):
__tablename__ = "claimants"
id = Column(Integer, primary_key=True)
name = Column(Text, unique=True)
def __str__(self):
return f"{self.name}"
claims = Table(
"claims", metadata,
Column('id', Integer, primary_key=True),
Column('text', Text, unique=True),
Column('date', Date),
Column('claimant_id', Integer, ForeignKey('claimants.id')),
)
claimants = Table(
"claimants", metadata,
Column('id', Integer, primary_key=True),
Column('name', Text, unique=True)
)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T20:56:08.257",
"Id": "520152",
"Score": "0",
"body": "Why use a database at all, if you're just doing counts? Can you count things streamed from the API?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T21:38:58.597",
"Id": "520153",
"Score": "0",
"body": "I could, and that would be sufficient for now, but I'd like to not have to constantly hit the API to do these kind of queries."
}
] |
[
{
"body": "<ul>\n<li>Could benefit from PEP484 type hints, e.g. <code>process_claim(claim: Dict[str, Any], session: Session) -> Claim:</code></li>\n<li>Is <code>strptime(claim["claimDate"][:-10], '%Y-%m-%d')</code> correct? You're saying that you're taking the whole string from the beginning up to ten characters before the end. Instead, wildly guessing, you either want the first ten characters or the last ten characters; this does neither.</li>\n</ul>\n<p>This:</p>\n<pre><code>url = (\n f"https://content-factchecktools.googleapis.com/v1alpha1/claims:search?"\n f"pageSize=10&"\n f"query=biden&"\n f"maxAgeDays=30&"\n f"offset=0&languageCode=en-US&key={API_KEY}"\n)\nr = requests.get(url, headers={"x-referer": "https://explorer.apis.google.com"})\n</code></pre>\n<p>is better-represented as</p>\n<pre><code>with get(\n "https://content-factchecktools.googleapis.com/v1alpha1/claims:search",\n params={\n 'pageSize': 10,\n 'query': 'biden',\n 'maxAgeDays': 30,\n 'offset': 0,\n 'languageCode': 'en-US',\n 'key': API_KEY,\n },\n headers={\n "X-Referer": "https://explorer.apis.google.com",\n }, \n) as r:\n r.raise_for_status()\n data = r.json()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T02:14:36.450",
"Id": "263476",
"ParentId": "263465",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263476",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T17:02:16.690",
"Id": "263465",
"Score": "1",
"Tags": [
"python",
"sqlalchemy"
],
"Title": "Linking a count to an object in SQLAlchemy"
}
|
263465
|
<p>This is a simple Java program I made that takes in any number, and when it gets to 0, it returns the quantity of the numbers, the min, max, sum, and average of the numbers. Are there any ways how I can make the code more readable or improve the performance?</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
public class Stats {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int size = 0;
double max = 0;
double min = 0;
double sum = 0;
double avg = 0;
String num = null;
do {
num = scan.nextLine();
try {
double n = Double.parseDouble(num);
if(!num.equals("0")){
if(size == 0){
max = n;
min = n;
sum = n;
avg = n;
} else {
max = Math.max(n, max);
min = Math.min(n, min);
sum += n;
avg = ((avg*size)+n)/(size+1);
}
size++;
}
} catch(NumberFormatException ex){
System.out.println("Please input a number, try again.");
}
} while(!num.equals("0"));
System.out.println("size: " + size +
"\nmin: " + min +
"\nmax: " + max +
"\nsum: " + sum +
"\navg: " + avg);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T15:34:01.733",
"Id": "520232",
"Score": "0",
"body": "That average calculation looks very inaccurate, given the nature of even double-precision floating point."
}
] |
[
{
"body": "<p>First of all, stop thinking about performance. This is not a tight loop, this is not a million numbers you crunch, the <em>only</em> concern you should have is readability and maintainability.</p>\n<p>Now, your code does all at once in a single method. You do input, calculation and output, calculating as you go along. This is basically spaghetti.</p>\n<p>You <em>should</em> aim to separate these concerns:</p>\n<ul>\n<li>Write a method that does the input and returns a list of numbers</li>\n<li>Write a method that does the calculation and returns some kind of statistics object, which contains your min/max/sum/avg</li>\n<li>Write a method that takes this statistics object, and performs the output</li>\n</ul>\n<p>As a template for further studies, something like this:</p>\n<pre><code>public class Statistics {\n private int min;\n private int max;\n private int sum;\n private int avg;\n\n ... construction, getters, setters\n}\n\n...\n\npublic static void main(String[] args) {\n List<Integer> numbers = readInput();\n Statistics statistics = computeStatistics(numbers);\n writeStatistics(statistics);\n}\n\n... add the methods referenced above\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T07:34:58.237",
"Id": "520271",
"Score": "0",
"body": "Good advice and answer. Except that I would have said `Statistics statistics = new Statistics(numbers);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T07:42:00.447",
"Id": "520272",
"Score": "2",
"body": "@gervais.b I actually thought about both ways. Either make a real business class from the statistics containing all logic, or use it as a dumb struct. In the end, I think I also would put the business logic into the statistics class IRL, but for the sake of \"learning the next step\" I think leaving the class simple will be a better answer for the OP."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T05:20:22.980",
"Id": "263479",
"ParentId": "263467",
"Score": "8"
}
},
{
"body": "<p>A few comments regarding style.</p>\n<pre><code> int size = 0;\n</code></pre>\n<p>In the Java standard libraries the name "size" refers to number of elements in a collection. The use here is misleading because you're not tracking the size of something. you're counting the number of values that has been entered, so a better name would be <code>count</code>.</p>\n<pre><code> double avg = 0;\n</code></pre>\n<p>The average of the input values is not needed during input processing so defining and updating it in in the loop is unnecessary. It is something that you can generate at the output phase from sum and count. You don't need the <code>avg</code> variable at all. If you would need it, just spell <code>average</code>. Unnecessary abbreviations just make code less readable.</p>\n<pre><code> avg = ((avg*size)+n)/(size+1);\n</code></pre>\n<p>Average is the sum of entries divided by number of entries. This is a much too complicated way to calculate the average and increases inaccuracy (floating point numbers are not precise so every unnecessary mathematical opration reduces accuracy).</p>\n<pre><code> double max = 0;\n double min = 0;\n double sum = 0;\n</code></pre>\n<p>By using primitive types and initializing them to zero you handily avoid the need to handle the special case where the user does not enter anything. But it doesn't make the program correct. If the user does not enter values, the minimum and maximum values were not zero, nor was the average. So you produce incorrect results. You have to use <code>Double</code> types initialized to null and make a check for <code>count</code> being zero when producing output.</p>\n<p>This looks like class room code so I suppose the requirement to use zero as an exit condition came from your teacher. In general it is not a good idea to use a value that could be interpreted as valid input as an exit condition. Right now you can input positive and negative values but not a zero and that is a bit weird. An empty line would have been a better choice in my opinion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T08:17:23.067",
"Id": "263540",
"ParentId": "263467",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263479",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T20:11:11.607",
"Id": "263467",
"Score": "1",
"Tags": [
"java",
"statistics"
],
"Title": "Java simple stats program"
}
|
263467
|
<p>I'm starting to learn React/NextJS and find the way to write conditional CSS very ugly compared to VueJS. I'm curious if someone could look over this code snippet and guide me in the right direction towards a cleaner way of designing my React code.</p>
<pre class="lang-html prettyprint-override"><code><Link key={link.text} href={link.to}>
<a className={`border-transparent border-b-2 hover:border-blue-ninja ${
activeClass === link.to ? 'active' : ''
}`}>
{link.text}
</a>
</Link>
</code></pre>
<p>Is this best practice?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T20:25:49.210",
"Id": "520342",
"Score": "0",
"body": "I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information"
}
] |
[
{
"body": "<p>You could use a conditional <em>className</em> utility. There are <a href=\"https://www.npmjs.com/package/classnames\" rel=\"nofollow noreferrer\">several</a> <a href=\"https://github.com/lukeed/obj-str\" rel=\"nofollow noreferrer\">solutions</a> in the ecosystem, but I would recommend <a href=\"https://github.com/lukeed/clsx#readme\" rel=\"nofollow noreferrer\"><code>clsx</code></a>.</p>\n<p>Your example would then be:</p>\n<pre><code><Link key={link.text} href={link.to}>\n <a className={clsx('border-transparent border-b-2 hover:border-blue-ninja', { active: activeClass === link.to } )}>\n {link.text}\n </a>\n</Link>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T16:00:42.063",
"Id": "263489",
"ParentId": "263469",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263489",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T21:56:34.940",
"Id": "263469",
"Score": "2",
"Tags": [
"beginner",
"css",
"react.js",
"jsx"
],
"Title": "ReactJS link with conditional CSS classes"
}
|
263469
|
<p>I am currently developing a terminal-based listview control, that uses ncurses for rendering.
The main goal for the listview was to be intuitive, performant, and reusable for other projects.</p>
<p>An example, is shown below:</p>
<p><a href="https://i.stack.imgur.com/keLMM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/keLMM.png" alt="" /></a></p>
<p><strong>listview.c</strong></p>
<pre class="lang-c prettyprint-override"><code>#include "listview.h"
#include <ncurses.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdarg.h>
listview *listview_new() {
listview *lv = malloc(sizeof(listview));
if (!lv) { return NULL; }
lv->rows = NULL;
lv->rows_count = 0;
lv->columns = NULL;
lv->column_count = 0;
lv->listview_max_width = 0;
lv->listview_max_height = 0;
lv->cell_padding = 2;
return lv;
}
void listview_add_column(listview *lv, char *text) {
lv->columns = realloc(lv->columns, (lv->column_count + 1) * sizeof(lv_column));
if (!lv->columns) { return; }
lv->columns[lv->column_count].text = text;
lv->columns[lv->column_count].alignment = left;
lv->columns[lv->column_count].width = (2 * lv->cell_padding) + strlen(text);
lv->column_count++;
}
int listview_set_column_alignment(listview *lv, int column_index, column_alignment alignment) {
if (column_index >= lv->column_count)
return -1;
lv->columns[column_index].alignment = alignment;
return 0;
}
void listview_render(WINDOW *win, listview *lv) {
// Define colors
wclear(win);
init_pair(10, COLOR_BLACK, COLOR_WHITE);
init_pair(20, COLOR_WHITE, COLOR_BLACK);
getmaxyx(win, lv->listview_max_height, lv->listview_max_width);
wattron(win, COLOR_PAIR(10));
// Render columns first
int cursor_pos = 0;
for (int i = 0; i < lv->column_count; i++) {
char *col_text = lv->columns[i].text;
int col_width = lv->columns[i].width;
int col_fill = col_width - (2 * lv->cell_padding) - strlen(col_text);
int extra_pad = lv->listview_max_width - cursor_pos - (lv->cell_padding + strlen(col_text) + lv->cell_padding);
if (i == lv->column_count - 1) {
mvwprintw(win, 0, cursor_pos, "%*s%s%*s%*s", lv->cell_padding, "", col_text, lv->cell_padding, "",
extra_pad, "");
cursor_pos = 0;
break;
} else {
if (lv->columns[i].alignment == left) {
mvwprintw(win, 0, cursor_pos, "%*s%s%*s%*s", lv->cell_padding, "", col_text, lv->cell_padding, "",
col_fill,
"");
} else if (lv->columns[i].alignment == right) {
mvwprintw(win, 0, cursor_pos, "%*s%*s%s%*s", lv->cell_padding, "", col_fill, "", col_text,
lv->cell_padding, "");
} else if (lv->columns[i].alignment == center) {
int col_fill_left = col_fill / 2;
int coll_fill_right = col_fill - col_fill_left;
mvwprintw(win, 0, cursor_pos, "%*s%*s%s%*s%*s", lv->cell_padding, "", col_fill_left, "", col_text,
coll_fill_right, "", lv->cell_padding, "");
}
}
cursor_pos += lv->cell_padding + strlen(col_text) + lv->cell_padding + col_fill;
}
wattron(win, COLOR_PAIR(20));
// Render rows
for (int i = 0; i < lv->rows_count; i++) {
for (int j = 0; j < lv->rows[i].cell_count; j++) {
char *cell_text = lv->rows[i].cells[j].text;
int col_width = lv->columns[j].width;
int col_fill = col_width - (2 * lv->cell_padding) - strlen(cell_text);
int extra_pad =
lv->listview_max_width - cursor_pos - (lv->cell_padding + strlen(cell_text) + lv->cell_padding);
int color_id = alloc_pair(lv->rows[i].cells[j].fg_color, lv->rows[i].cells[j].bg_color);
wattron(win, COLOR_PAIR(color_id));
if (j == lv->rows[i].cell_count - 1) {
mvwprintw(win, i + 1, cursor_pos, "%*s%s%*s%*s", lv->cell_padding, "", cell_text, lv->cell_padding,
"", extra_pad, "");
cursor_pos = 0;
break;
} else {
if (lv->columns[j].alignment == left) {
mvwprintw(win, i + 1, cursor_pos, "%*s%s%*s%*s", lv->cell_padding, "", cell_text, lv->cell_padding,
"", col_fill, "");
} else if (lv->columns[j].alignment == right) {
mvwprintw(win, i + 1, cursor_pos, "%*s%*s%s%*s", lv->cell_padding, "", col_fill, "", cell_text,
lv->cell_padding, "");
} else if (lv->columns[j].alignment == center) {
int col_fill_left = col_fill / 2;
int coll_fill_right = col_fill - col_fill_left;
mvwprintw(win, i + 1, cursor_pos, "%*s%*s%s%*s%*s", lv->cell_padding, "", col_fill_left, "",
cell_text, coll_fill_right, "", lv->cell_padding, "");
}
}
free_pair(color_id);
wattroff(win, COLOR_PAIR(color_id));
cursor_pos += lv->cell_padding + strlen(cell_text) + lv->cell_padding + col_fill;
}
}
}
int listview_delete_column(listview *lv, int column_index)
{
if(column_index >= lv->column_count)
return -1;
// Remove column
lv_column *new_cols = malloc(sizeof(lv_column) * (lv->column_count - 1));
memmove(new_cols, lv->columns, column_index * sizeof(lv_column));
memmove(&new_cols[column_index], &lv->columns[column_index + 1], (lv->column_count - column_index - 1) * sizeof(lv_column));
free(lv->columns);
lv->columns = new_cols;
// Remove effected cells in every row
for (int i = 0; i < lv->rows_count; i++)
{
lv_cell *new_cells = malloc(sizeof(lv_cell) * (lv->column_count - 1));
memmove(new_cells, lv->rows[i].cells, column_index * sizeof(lv_cell));
memmove(&new_cells[column_index], &lv->rows[i].cells[column_index + 1], (lv->column_count - column_index - 1) * sizeof(lv_cell));
free(lv->rows[i].cells);
lv->rows[i].cells = new_cells;
lv->rows[i].cell_count--;
}
lv->column_count--;
return 0;
}
int listview_update_cell_background_color(listview *lv, int row_index, int cell_index, lv_color bg_color)
{
if (bg_color < 0 || bg_color > 7)
return -1;
lv->rows[row_index].cells[cell_index].bg_color = bg_color;
return 0;
}
int listview_update_cell_foreground_color(listview *lv, int row_index, int cell_index, lv_color fg_color)
{
if (fg_color < 0 || fg_color > 7)
return -1;
lv->rows[row_index].cells[cell_index].fg_color = fg_color;
return 0;
}
void listview_add_row(listview *lv, ...) {
va_list argp;
va_start(argp, lv);
lv->rows = realloc(lv->rows, sizeof(lv_row) * (lv->rows_count + 1));
lv->rows[lv->rows_count].cells = calloc(lv->column_count, sizeof(lv_cell));
lv->rows[lv->rows_count].cell_count = lv->column_count;
for (int i = 0; i < lv->column_count; i++) {
char *text = va_arg(argp,
char*);
lv->rows[lv->rows_count].cells[i].text = text;
lv->rows[lv->rows_count].cells[i].bg_color = black;
lv->rows[lv->rows_count].cells[i].fg_color = white;
}
lv->rows_count++;
va_end(argp);
update_max_col_width(lv, lv->rows_count);
}
int listview_delete_row(listview *lv, int row_index) {
if (row_index > lv->rows_count)
return - 1;
lv_row *new_rows = malloc(sizeof(lv_row) * (lv->rows_count - 1));
if (new_rows == NULL)
return -2;
memmove(new_rows, lv->rows, row_index * sizeof(lv_row));
memmove(&new_rows[row_index], &lv->rows[row_index + 1], (lv->rows_count - row_index - 1) * sizeof(lv_row));
free(lv->rows);
lv->rows = new_rows;
lv->rows_count--;
update_max_col_width(lv, lv->rows_count);
return 0;
}
int listview_insert_row(listview *lv, int row_index, ...) {
if (row_index > lv->rows_count)
return -1;
va_list argp;
va_start(argp, row_index);
lv->rows = realloc(lv->rows, sizeof(lv_row) * (lv->rows_count + 1));
if(!lv->rows)
return -2;
if (row_index < lv->rows_count) {
int entries_to_move = (lv->rows_count - row_index);
memmove(&lv->rows[row_index + 1], &lv->rows[row_index], entries_to_move * sizeof(lv_row));
lv->rows[row_index].cells = (lv_cell *) malloc(sizeof(lv_cell) * lv->column_count);
for (int i = 0; i < lv->column_count; i++) {
lv->rows[row_index].cell_count = lv->column_count;
lv->rows[row_index].cells[i].text = va_arg(argp, char*);
lv->rows[row_index].cells[i].fg_color = white;
lv->rows[row_index].cells[i].bg_color = black;
}
} else if (row_index == lv->rows_count) {
lv->rows[row_index].cells = (lv_cell *) malloc(sizeof(lv_cell) * lv->column_count);
for (int i = 0; i < lv->column_count; i++) {
lv->rows[row_index].cell_count = lv->column_count;
lv->rows[row_index].cells[i].text = va_arg(argp, char*);
lv->rows[row_index].cells[i].fg_color = white;
lv->rows[row_index].cells[i].bg_color = black;
}
}
lv->rows_count++;
update_max_col_width(lv, lv->rows_count);
return 0;
}
int listview_update_cell_text(listview *lv, int row_index, int cell_index, char *text) {
if (row_index >= lv->rows_count || cell_index >= lv->column_count)
return -1;
if(text == NULL)
return -2;
lv->rows[row_index].cells[cell_index].text = text;
update_max_col_width(lv, lv->rows_count);
return 0;
}
void update_max_col_width(listview *lv, int row_index) {
// Make sure index is valid
if (row_index > lv->rows_count || row_index < 0)
return;
// Reset all max col width values
for (int i = 0; i < lv->column_count; i++) {
lv->columns[i].width = strlen(lv->columns[i].text) + (2 * lv->cell_padding);
}
// Recompute the max col width values for rows
for (int i = 0; i < lv->rows_count; i++) {
for (int j = 0; j < lv->rows[i].cell_count; j++) {
if (strlen(lv->rows[i].cells[j].text) + (2 * lv->cell_padding) > lv->columns[j].width)
lv->columns[j].width = strlen(lv->rows[i].cells[j].text) + (2 * lv->cell_padding);
}
}
}
void listview_free(listview *lv) {
// Free rows
free(lv->rows);
// Free headers
free(lv->columns);
// Free lv itself
free(lv);
}
</code></pre>
<p><strong>listview.h</strong></p>
<pre class="lang-c prettyprint-override"><code>#ifndef LISTVIEW_H
#define LISTVIEW_H
#include <stdint.h>
#include <stdlib.h>
#include <ncurses.h>
typedef enum lv_color {
black = COLOR_BLACK,
blue = COLOR_BLUE,
cyan = COLOR_CYAN,
green = COLOR_GREEN,
magenta = COLOR_MAGENTA,
red = COLOR_RED,
white = COLOR_WHITE,
yellow = COLOR_YELLOW,
} lv_color;
typedef enum column_alignment {
// Aligns the column text and the cells in that column to the left
left,
// Aligns the column text and the cells in that column centered
center,
// Aligns the column text and the cells in that column to the right
right
} column_alignment;
typedef struct lv_cell {
// The text in the cell
char *text;
short bg_color;
short fg_color;
} lv_cell;
typedef struct lv_column {
// The column text
char *text;
// The width of the column (depends on width of the row cells)
uint16_t width;
// Specifies the alignment of the text in entire column
column_alignment alignment;
} lv_column;
typedef struct lv_row {
// Holds all cells in the row
lv_cell *cells;
// Total amount of cells in the row
uint8_t cell_count;
} lv_row;
typedef struct listview {
// Holds all columns
lv_column *columns;
// Holds amount of columns
uint16_t column_count;
// Holds all rows
lv_row *rows;
// Holds amount of rows
uint16_t rows_count;
// Maximum window width the listview can occupy
uint16_t listview_max_width;
// Maximum window height the listview can occupy
uint16_t listview_max_height;
// Amount of spaces padded to the left and right of each cell
uint8_t cell_padding;
} listview;
listview *listview_new();
void listview_free(listview *lv);
void listview_add_column(listview *lv, char* text);
int listview_set_column_alignment(listview *lv, int column_index, column_alignment alignment);
int listview_insert_row(listview* lv, int row_index, ...);
int listview_delete_column(listview *lv, int column_index);
void listview_add_row(listview *lv, ...);
int listview_delete_row(listview *lv, int row_index);
int listview_update_cell_text(listview *lv, int row_index, int cell_index, char* text);
int listview_update_cell_background_color(listview* lv, int row_index, int cell_index, lv_color bg_color);
int listview_update_cell_foreground_color(listview* lv, int row_index, int cell_index, lv_color fg_color);
void listview_render(WINDOW *win, listview *lv);
void update_max_col_width(listview *lv, int row_index);
#endif
</code></pre>
<p><strong>main.c</strong></p>
<pre class="lang-c prettyprint-override"><code>#include "ui.h"
#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#include "listview.h"
int main()
{
// Setup stuff
initscr();
start_color();
clear();
noecho();
curs_set(0);
cbreak();
WINDOW* win = newwin(0, 0, 0, 0);
refresh();
// Create listview
listview* lv = listview_new();
listview_add_column(lv, "Country");
listview_add_column(lv, "Capital");
listview_add_column(lv, "Area");
listview_add_column(lv, "Population");
listview_add_column(lv, "Currency");
// Add some rows of data
listview_add_row(lv, "Germany", "Berlin", "357,022 km2", "83,190,556", "Euro");
listview_add_row(lv, "Japan", "Tokyo", "377,975 km2", "125,470,000", "Yen");
listview_add_row(lv, "Netherlands", "Amsterdam", "41,865 km2", "83,190,556", "Euro");
listview_add_row(lv, "China", "Beijing", "9,596,961 km2", "1,444,390,177", "Renminbi");
listview_add_row(lv, "France", "Paris", "640,679 km2", "67,413,000", "Euro");
listview_add_row(lv, "New Zealand", "Wellington", "268,021 km2", "5,123,760", "New Zealand Dollar");
listview_render(win, lv);
wgetch(win);
listview_update_cell_foreground_color(lv, 0, 0, red);
listview_update_cell_foreground_color(lv, 0, 2, green);
listview_update_cell_foreground_color(lv, 0, 4, blue);
listview_update_cell_background_color(lv, 1, 1, yellow);
listview_update_cell_background_color(lv, 1, 3, magenta);
listview_render(win, lv);
wgetch(win);
listview_insert_row(lv, 1, "United States of America", "Washington, D.C.", "9,525,067 km2", "331,449,281", "US Dollar");
listview_render(win, lv);
wgetch(win);
listview_delete_column(lv, 2);
listview_render(win, lv);
wgetch(win);
listview_free(lv);
delwin(win);
return 0;
}
</code></pre>
<p>Make sure to compile the example with <code>-lncurses</code>, to try it out.</p>
<p>While the listview works just fine it its current state, I am sure, there is lots of room for improvement. To me it seems that especially the render function can vastly be improved.
However, some feedback regarding my api-design and performance are also welcome :)</p>
|
[] |
[
{
"body": "<h1>General Observations</h1>\n<p>The code is solid, basically well written, fairly easy to maintain and the code is reusable. There are a few places where some software engineering principles could help, and while this is C rather than an object oriented language there could be a few places where object oriented concepts might decrease some maintenance efforts.</p>\n<h2>Self Documenting Code</h2>\n<p>Some of the comments, at least in <code>listview.h</code> are unnecessary. The code should be self documenting as much as possible. Comments such as <code>// Holds all columns</code> and <code>// Holds all rows</code> really aren't necessary. Where you might need comments is in listview.c at the beginning of a function to explain any design decsions that might not be clear just from the code. In listview.h you might want to explain why you are using <code>uint16_t</code> rather than <code>size_t</code> as the size of the <code>columns</code> array and the size of the <code>rows</code> array.</p>\n<h2>Possible Objects</h2>\n<p>The <code>listview</code> struct contains lists of <code>lv_row</code> and <code>lv_column</code>. Each of these lists are implemented as a pointer and a count, instead there could be container type of <code>lv_rows</code> and a container type for <code>lv_columns</code>, the container would have the pointer to the data and the count rather than the <code>listview</code> struct having the data. Each of these containers could have methods/functions to implement <code>add</code>, <code>delete</code> and <code>insert</code>. These methods <code>could be added</code> to the container structs using pointers to functions, they don't need to be. Depending on how important performance of adding, deleting and inserting rows and cells are, it might be better to use linked lists rather than arrays. I have not included pointers to functions in the following declarations.</p>\n<pre><code>typedef struct lv_row_container\n{\n lv_row* rows;\n uint16_t count;\n} lv_row_container;\n\ntypedef struct lv_column_container\n{\n lv_row* columns;\n uint16_t count;\n\n} lv_column_container;\n\ntypedef struct listview {\n lv_column_container columns;\n lv_row_container rows;\n uint16_t listview_max_width;\n uint16_t listview_max_height;\n uint8_t cell_padding;\n} listview;\n</code></pre>\n<h2>Function Naming and Grouping</h2>\n<p>Currently the code contains the following functions:</p>\n<pre><code>void listview_add_column(listview* lv, char* text);\nint listview_set_column_alignment(listview* lv, int column_index, column_alignment alignment);\nint listview_insert_row(listview* lv, int row_index, ...);\nint listview_delete_column(listview* lv, int column_index);\nvoid listview_add_row(listview* lv, ...);\nint listview_delete_row(listview* lv, int row_index);\n</code></pre>\n<p>I would suggest the following instead:</p>\n<pre><code>void listview_column_add(listview* lv, char* text);\nint listview_column_set_alignment(listview* lv, int column_index, column_alignment alignment);\nint listview_column_delete(listview* lv, int column_index);\nint listview_row_insert(listview* lv, int row_index, ...);\nvoid listview_row_add(listview* lv, ...);\nint listview_row_delete(listview* lv, int row_index);\n</code></pre>\n<p>The code for the rows and columns can then be broken up into their own headers and source files at some point in the future. Abstracting the row and column functions could make the <code>listview</code> code easier to maintain.</p>\n<h1>Nit-picks</h1>\n<h2>Inconsistent Use of <code>lv_color</code> Colors</h2>\n<p>The header file <code>listview.h</code> contains the definition of the enum <code>lv_color</code>. This is used inconsistently in <code>listview.c</code>. In the function <code>listview_insert_row()</code> the <code>lv_color</code> values are used, however, in the function <code>listview_render()</code> <code>COLOR_BLACK</code> and <code>COLOR_WHITE</code> are used. It would be best to stick with one definition throughout the file.</p>\n<h2>DRY Code</h2>\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. In the function <code>listview_render()</code> this code repeats itself in 2 different loops:</p>\n<pre><code> if (i == lv->column_count - 1) {\n mvwprintw(win, 0, cursor_pos, "%*s%s%*s%*s", lv->cell_padding, "", col_text, lv->cell_padding, "",\n extra_pad, "");\n cursor_pos = 0;\n break;\n }\n else {\n if (lv->columns[i].alignment == left) {\n mvwprintw(win, 0, cursor_pos, "%*s%s%*s%*s", lv->cell_padding, "", col_text, lv->cell_padding, "",\n col_fill,\n "");\n }\n else if (lv->columns[i].alignment == right) {\n mvwprintw(win, 0, cursor_pos, "%*s%*s%s%*s", lv->cell_padding, "", col_fill, "", col_text,\n lv->cell_padding, "");\n }\n else if (lv->columns[i].alignment == center) {\n int col_fill_left = col_fill / 2;\n int coll_fill_right = col_fill - col_fill_left;\n mvwprintw(win, 0, cursor_pos, "%*s%*s%s%*s%*s", lv->cell_padding, "", col_fill_left, "", col_text,\n coll_fill_right, "", lv->cell_padding, "");\n }\n }\n</code></pre>\n<p>It might be better to put that code into a function that needs to be written and debugged only once. This makes the code easier to maintain and more reusable as well.</p>\n<h2>Complexity</h2>\n<p>There are two functions that are too complex (does too much), <code>listview_render()</code> is one and <code>main()</code> is the other. As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>It is possible that the suggestion about <code>DRY Code</code> above will correct the issue in <code>listview_render()</code>, however the function could also be implemented by calling 2 additional functions, <code>render_columns()</code> and <code>render_rows()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T11:50:02.780",
"Id": "520476",
"Score": "0",
"body": "Thanks for the feedback, definitely some useful suggestions in there. However, I would love to get some more indepth-feedback on how I can improve specifically the rendering method. Outlining rendering of rows and columns in separate methods, wont really do that much. I feel like there is much more, that can be done. Especially, since `mvwprintw` gets called multiple times in there, but with different formatting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T06:44:40.793",
"Id": "520543",
"Score": "1",
"body": "@766F6964 It may not look like it does much, but it cleans up your code enough that it both shows the remaining problems and how to clean up those problems. Cleaning up those `mwprintw` starts with applying more of the same principles outlined in this answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T21:29:12.627",
"Id": "520686",
"Score": "0",
"body": "@Mast I have now extracted the rendering in two methods, one for the columns and one for the rows, however that still leaves me with 4 long `mvwprintw` calls. While I could outline the `mvwprintw` to a separate function too, that does just that, it wouldn't help much, because I would have to pass all the arguments through that I currently pass to the `mvwprintw` function, because they are all different. That makes it a bit tricky to refactor that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T22:08:57.797",
"Id": "263527",
"ParentId": "263470",
"Score": "7"
}
},
{
"body": "<p>You have a thorough review already; I'll just add some minor points.</p>\n<hr />\n<p>We have a pointer to <code>char</code> in the cell structure:</p>\n<blockquote>\n<pre><code>typedef struct lv_cell {\n // The text in the cell\n char *text;\n …\n} lv_cell;\n</code></pre>\n</blockquote>\n<p>However, we don't need to modify the contents of the string, and making it <code>const char*</code> (and updating function signatures to match) would allow us to pass string literals without the compiler warnings we currently get. (If you're not seeing warnings, then this should be a prompt to compile with maximal warnings enabled!)</p>\n<hr />\n<blockquote>\n<pre><code>listview *listview_new();\n</code></pre>\n</blockquote>\n<p>We should declare what arguments are accepted - in this case, don't allow any to be passed:</p>\n<pre><code>listview *listview_new(void);\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> listview *lv = malloc(sizeof(listview));\n</code></pre>\n</blockquote>\n<p>A good practice, that reduces the likelihood of bugs when the code is edited, is to use an expression, rather than a type, as argument to <code>sizeof</code>:</p>\n<pre><code> listview *lv = malloc(sizeof *lv);\n if (!lv) {\n /* caller must deal with failed allocation */\n return lv;\n }\n</code></pre>\n<hr />\n<p>We leak memory when <code>realloc()</code> returns a null pointer:</p>\n<blockquote>\n<pre><code>lv->columns = realloc(lv->columns, (lv->column_count + 1) * sizeof(lv_column));\nif (!lv->columns) { return; }\n</code></pre>\n</blockquote>\n<p>When the allocation fails, the memory is still allocated, but we've overwritten our pointer with null, so we are no longer able to <code>free()</code> it. We need to use a two-step reallocation:</p>\n<pre><code>void *new = realloc(lv->columns, (sizeof *lv->columns) * (lv->column_count + 1));\nif (!new) { return; }\nlv->columns = new;\n</code></pre>\n<p>We ought to return a value from this function, to tell the caller whether we were successful or not.</p>\n<p>There are other <code>malloc()</code> and <code>realloc()</code> calls with poor handling of failure; I won't list them all.</p>\n<hr />\n<p>There's needless allocation here:</p>\n<blockquote>\n<pre><code>lv_column *new_cols = malloc(sizeof(lv_column) * (lv->column_count - 1));\nmemmove(new_cols, lv->columns, column_index * sizeof(lv_column));\nmemmove(&new_cols[column_index], &lv->columns[column_index + 1], (lv->column_count - column_index - 1) * sizeof(lv_column));\nfree(lv->columns);\nlv->columns = new_cols;\n</code></pre>\n</blockquote>\n<p>We only need to shrink the existing allocation:</p>\n<pre><code>--lv->column_count;\nmemmove(lv->columns + column_index, lv->columns + column_index + 1,\n (sizeof *lv->columns) * (lv->column_count - column_index));\nlv->columns = realloc(lv->columns, (sizeof *lv->columns) * lv->column_count);\nassert(lv->columns); /* shrinking always succeeds */\n</code></pre>\n<p>There are some other instances of this pattern, which should also be adjusted.</p>\n<p>As this seems not to be clear, here's a full-program demonstration (using a local array in lieu of allocated memory):</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main(int argc, char **argv)\n{\n const char *a[] = {\n "zero", "one", "two", "three", "four",\n "five", "six", "seven", "eight", "nine",\n };\n size_t a_len = sizeof a / sizeof *a;\n for (char **s = argv + 1; a_len && *s; ++s) {\n char *e;\n long n = strtol(*s, &e, 0);\n if (e == *s) { n = 5; }\n if (n < 0) { n = 0; }\n if (n >= a_len) { n = a_len - 1; }\n\n printf("Removing element %li: ", n);\n {\n /* actually do it */\n --a_len;\n memmove(a+n, a+n+1, (sizeof *a) * (a_len - n));\n }\n\n for (size_t i = 0; i < a_len; ++i) {\n printf("%s ", a[i]);\n }\n puts("");\n }\n}\n</code></pre>\n<p>Example output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>./263470 2 3 0 10\nRemoving element 2: zero one three four five six seven eight nine \nRemoving element 3: zero one three five six seven eight nine \nRemoving element 0: one three five six seven eight nine \nRemoving element 6: one three five six seven eight \n</code></pre>\n<p>The replacement of <code>listview_delete_column()</code> is then:</p>\n<pre><code>int listview_delete_column(listview *lv, int column_index)\n{\n if (column_index >= lv->column_count && column_index < 0) {\n return -1;\n }\n\n lv->column_count--;\n // Remove column\n memmove(lv->columns + column_index, lv->columns + column_index + 1,\n (sizeof *lv->columns) * (lv->column_count - column_index));\n lv->columns = realloc(lv->columns, (sizeof *lv->columns) * lv->column_count);\n\n // Remove affected cell from each row\n for (int i = 0; i < lv->rows_count; ++i) {\n lv_row *const row = lv->rows + i;\n --row->cell_count;\n memmove(row->cells + column_index, row->cells + column_index + 1,\n (sizeof *row->cells) * (row->cell_count - column_index));\n row->cells = realloc(row->cells, (sizeof *row->cells) * row->cell_count);\n }\n return 0;\n}\n</code></pre>\n<hr />\n<p><code>listview_free()</code> ought to work if given a null pointer, to be consistent with standard library <code>free()</code>. As currently written, that triggers undefined behaviour.</p>\n<p>There's an omission from this function that's revealed when we run the program under Valgrind: we forgot to free each row's <code>cells</code>.</p>\n<pre><code>void listview_free(listview *lv)\n{\n if (!lv) return;\n\n // Free rows\n for (int i = 0; i < lv->rows_count; ++i) {\n free(lv->rows[i].cells);\n }\n free(lv->rows);\n\n // Free headers\n free(lv->columns);\n\n // Free lv itself\n free(lv);\n}\n</code></pre>\n<hr />\n<p>We're missing a call to <code>endwin()</code> before we return from <code>main()</code>. That's really irritating, as it leaves an xterm in the alternate screen with echoing disabled...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T22:07:40.740",
"Id": "520520",
"Score": "0",
"body": "Thanks for the feedback. I've now added proper error handling to the mallocs and reallocs. However, your suggestion with the \"needless allocation\" is incorrect. The temporary allocation is necessary because we need to delete an element in the middle of a dynamically allocated array - and hence preserve the part before and the part after. Hence all the two memmove calls. For example, the following unit tests would not work when using your suggestion: https://pastebin.com/Y1p8y0AU\nAll the other things I agree with. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T04:54:14.300",
"Id": "520536",
"Score": "1",
"body": "Perhaps I wasn't clear with the replacement code: to delete an element from the middle, we simply leave the \"before\" section untouched, and `memmove()` the \"after\" section one position down. If that's still not clear, I'll whip up a full program to demonstrate. (If you applied my change directly to the code, note that I moved the modification of `lv->column_count` to make the arithmetic simpler, and you'll need to account for that anywhere else it's used, or move it back down - and account for _that_)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T21:31:24.370",
"Id": "520687",
"Score": "0",
"body": "Well, yeah, maybe an example would help. I find my implementation with two memmove calls much easier to understand. I must be missing something than in your approach, because I can't really get it to work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T07:42:34.687",
"Id": "520712",
"Score": "1",
"body": "I've expanded the explanation of that part for you."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T12:44:38.823",
"Id": "263628",
"ParentId": "263470",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263527",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T22:02:17.183",
"Id": "263470",
"Score": "7",
"Tags": [
"c",
"ncurses",
"console",
"listview"
],
"Title": "Ncurses listview control"
}
|
263470
|
<p>I need to know if there is any way I can optimize my code so that it does not use 0.6% of my total memory - which is approx. 22.4MB. This is a really small script that runs for as long as the raspberry pi is ON. 22.4MB for this basic, simple, light code is too much. If less or no optimization is there, then please let me know how 22.4MB is justified.</p>
<p>I am pasting the htop screenshot and my full script.</p>
<p><a href="https://i.stack.imgur.com/XKwmP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XKwmP.png" alt="htop" /></a></p>
<pre><code>from gpiozero import CPUTemperature
from time import sleep, time
from requests import post
class TemperatureBot:
def __init__(self):
self.lastAlertSent = -1
self.chatId = "123"
self.botToken= "123"
self.temperatureThreshold = 60
self.alertInterval = 300
alertResp = self.sendAlertToUser(f"Initializing temperature bot for 123 - " \
f"your pi")
if alertResp is not True:
print("Could not initialize bot for 123. Try later.")
return
self.temperaturePolling()
def sendAlertToUser(self, alertMsg):
try:
url=f"https://api.telegram.org/bot{self.botToken}"\
f"/sendMessage?chat_id={self.chatId}&text={alertMsg}"
r = post(url,timeout=20)
if(r.status_code >=400):
print("Error sending alert. Here's the response: ", r.text)
return False
return True
except Exception as e:
raise e
def temperaturePolling(self):
try:
while(True):
currentTemp = CPUTemperature().temperature
if(currentTemp > self.temperatureThreshold):
if(time() - self.lastAlertSent > self.alertInterval):
alertResp = self.sendAlertToUser(f"Temperature Danger: "\
f"{currentTemp}°C. "\
f"Please cool your Stan "\
f"or it will burn!!")
if alertResp == True:
self.lastAlertSent = time()
else:
print("Could not send alert message.")
continue
sleep(30)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
TemperatureBot()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T23:51:13.083",
"Id": "520155",
"Score": "2",
"body": "I don't think it'll get much lower - at least on my system, `python -c 'import requests, time; time.sleep(600)' &` uses similar amounts of memory even though all it does is import `requests` and go to sleep"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T20:38:35.590",
"Id": "520418",
"Score": "0",
"body": "@SaraJ I thought there was something wrong in my code login which is taking too much memory but it's them libraries! Thanks for demonstration!"
}
] |
[
{
"body": "<ul>\n<li><code>chatId</code> -> <code>chat_id</code> and similar for other members and method names, by PEP8 standard</li>\n<li><code>f"Initializing temperature bot for 123 - "</code> does not need to be an f-string - it has no fields</li>\n<li>if <code>alertResp</code> is not true, you should be raising an exception, not early-returning</li>\n<li><code>if alertResp is not True</code> is equivalent to <code>if not alertResp</code></li>\n<li><code>temperaturePolling</code> should not be called from your constructor - the constructor is only for initialization</li>\n<li><code>post</code> returns a response that should be used in a <code>with</code> context manager</li>\n<li><code>status_code >= 400</code> can safely be replaced with <code>r.ok</code>, or better yet <code>r.raise_for_status()</code></li>\n<li><code>except Exception as e: raise e</code> should be deleted entirely</li>\n<li><code>except KeyboardInterrupt: pass</code> is fine <em>if</em> it's done at the upper level, but not in your polling routine</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:33:52.917",
"Id": "520188",
"Score": "0",
"body": "> \"except Exception as e: raise e should be deleted entirely\"\n.\n\nBut we have to catch after a try block, so how do we do that if we remove the block entirely?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:34:47.030",
"Id": "520189",
"Score": "1",
"body": "Remove the `try` as well. It's not helping you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:42:24.833",
"Id": "520192",
"Score": "0",
"body": "Thanks @Reinderien, have made the changes and made a note of the same for future. BTW, when I'm calling this polling routine at the upper level(say pollingCaller), the code gets stuck in the while loop of this polling routine and the code following the pollingCaller doesn't get executed. In your experience do you have any solutions to that? Or should I ask that as a separate question on stackexchange?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:43:19.557",
"Id": "520193",
"Score": "0",
"body": "Under what conditions does the polling loop end? What kind of code would execute after?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:52:23.093",
"Id": "520196",
"Score": "0",
"body": "This script I am planning to run it as a cron job on system reboot. @reboot thingy. So I don't think that the polling loop ever ends (as long as the system is ON). The code that is followed by the polling calling is telegram bot codes, basically some listeners, callbacks. Please have a glimpse here:\nhttps://pastebin.com/5y6Rs8xe"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T20:37:58.833",
"Id": "520199",
"Score": "0",
"body": "That doesn't make sense. If the polling loop never ends, why have code after it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T20:37:03.363",
"Id": "520417",
"Score": "0",
"body": "I resolved the problem by using two separate python scripts using cron job: One for pollingCaller and the second one for temperatureBot. Both do polling until system turns off and both are separated completely - no correlation anymore."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T02:01:41.703",
"Id": "263475",
"ParentId": "263471",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263475",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T22:14:08.803",
"Id": "263471",
"Score": "6",
"Tags": [
"python",
"memory-optimization",
"raspberry-pi",
"status-monitoring",
"telegram"
],
"Title": "Python script which sends telegram message if Raspberry Pi's temperature crosses 60 °C"
}
|
263471
|
<p>I wrote this simple app for creating a Stock Exchange platform.
It is written with a flask framework.</p>
<p>My main concerns are regarding the user_page route which feels too long and not DRY enough,
But on the other hand, I can't find a pythonic elegant way to clean it. I would really appreciate your comments.</p>
<p>I am not sure what are the best practices while using flask, Is it best practice to define more functions inside a route?</p>
<pre><code>from flask import Flask, render_template, request, redirect, url_for, flash
from forms import RegisterPlayers, SalesBids, BuyBids
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'password'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp/test.db'
db = SQLAlchemy(app)
# Setting players table
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_name = db.Column(db.String(80), unique=True, nullable=False)
number_of_shares = db.Column(db.Integer())
def __repr__(self):
return f"Users(user_name: '{self.user_name}', number_of_shares: '{self.number_of_shares}')"
# Setting bids Table
class TradeBids(db.Model):
id = db.Column(db.Integer, primary_key=True)
bid_type = db.Column(db.String(80), nullable=False)
price_per_share = db.Column(db.Integer())
share_amount = db.Column(db.Integer())
trader_name = db.Column(db.String(80), nullable=False)
bid_status = db.Column(db.String(80), nullable=False)
def __repr__(self):
return f"TradeBids(id: '{self.id}', bid type: '{self.bid_type}', price_per_share: '{self.price_per_share}', share_amount: '{self.share_amount}', trader_name: '{self.trader_name}')"
@app.route('/register', methods=['GET', 'POST'])
def register():
register_form = RegisterPlayers()
if register_form.validate_on_submit():
player = Users(user_name=register_form.user_name.data)
user_name = player.user_name
all = Users.query.all()
for name in all:
if player.user_name in name.user_name:
return redirect(url_for('user_page', user_name=user_name))
player.number_of_shares = 0
db.session.add(player)
db.session.commit()
return redirect(url_for('user_page', user_name=user_name))
return render_template('register.html', form=register_form)
@app.route('/user_page/<user_name>', methods=['GET', 'POST'])
def user_page(user_name):
user = Users.query.filter_by(user_name=user_name).first()
sales_bid_form = SalesBids()
buy_bids_form = BuyBids()
if buy_bids_form.validate_on_submit():
# Save the bid on memory
bid = TradeBids(bid_type='buy', price_per_share=buy_bids_form.buy_asking_price.data,
share_amount=buy_bids_form.buy_shares_amount.data,
trader_name=user.user_name,
bid_status='pending')
# handle the bid before it saves to data base
look_for_match = TradeBids.query.filter(TradeBids.bid_type == 'sell',
TradeBids.price_per_share <= bid.price_per_share,
TradeBids.share_amount >= bid.share_amount,
TradeBids.trader_name != user.user_name,
TradeBids.bid_status == 'pending'
).order_by(TradeBids.price_per_share).first()
# we dont have a deal save the bid
if not look_for_match:
db.session.add(bid)
db.session.commit()
return render_template('user_page.html', user=user, sell_form=sales_bid_form, buy_form=buy_bids_form)
# we have a deal !!!! exchange shares
if look_for_match:
diff = bid.share_amount
# Update the seller total share
Users.query.filter_by(user_name=look_for_match.trader_name).update(
dict(number_of_shares=look_for_match.share_amount - bid.share_amount))
db.session.commit()
# Update the buyer total share
Users.query.filter_by(user_name=user.user_name).update(
dict(number_of_shares=user.number_of_shares + bid.share_amount))
db.session.commit()
# Update the seller bid
bid_id_to_update = look_for_match.id
TradeBids.query.filter_by(id=bid_id_to_update).update(
dict(share_amount=look_for_match.share_amount - bid.share_amount))
if TradeBids.query.filter_by(id=bid_id_to_update).first().share_amount == 0:
TradeBids.query.filter_by(id=bid_id_to_update).update(
dict(bid_status='expired'))
db.session.commit()
if sales_bid_form.validate_on_submit():
if sales_bid_form.sell_shares_amount.data >= user.number_of_shares:
flash("insufficient number of shares", 'error')
return render_template('user_page.html', user=user, sell_form=sales_bid_form, buy_form=buy_bids_form)
# Save the bid to the memory
bid = TradeBids(bid_type='sell', price_per_share=sales_bid_form.sell_asking_price.data,
share_amount=sales_bid_form.sell_shares_amount.data,
trader_name=user.user_name,
bid_status='pending')
# Handle the bid before it saves to Database
look_for_match = TradeBids.query.filter(TradeBids.bid_type == 'buy',
TradeBids.price_per_share >= bid.price_per_share,
TradeBids.share_amount >= bid.share_amount,
TradeBids.trader_name != user.user_name,
TradeBids.bid_status == 'pending'
).order_by(TradeBids.price_per_share).first()
# We dont have a deal save the bid to DB
if not look_for_match:
db.session.add(bid)
db.session.commit()
return render_template('user_page.html', user=user, sell_form=sales_bid_form, buy_form=buy_bids_form)
# We have a deal !!!! exchange shares
if look_for_match:
# Update the buyer total share
buyer = Users.query.filter_by(user_name=look_for_match.trader_name).first()
Users.query.filter_by(user_name=look_for_match.trader_name).update(
dict(number_of_shares=buyer.number_of_shares + bid.share_amount))
db.session.commit()
# Update the seller total share
Users.query.filter_by(user_name=user.user_name).update(dict(number_of_shares=user.number_of_shares - bid.share_amount))
db.session.commit()
# Update the buyer bid
bid_id_to_update = look_for_match.id
TradeBids.query.filter_by(id=bid_id_to_update).update(dict(share_amount=look_for_match.share_amount - bid.share_amount))
if TradeBids.query.filter_by(id=bid_id_to_update).first().share_amount == 0:
TradeBids.query.filter_by(id=bid_id_to_update).update(
dict(bid_status='expired'))
db.session.commit()
return render_template('user_page.html', user=user, sell_form=sales_bid_form, buy_form=buy_bids_form)
@app.route('/users_and_bids_tables')
def users_and_bids_tables():
users = Users.query.all()
bids = TradeBids.query.all()
return render_template('all.html', users=users, bids=bids)
if __name__ == '__main__':
app.run(debug=True)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The best way to make it more pythonic is to apply the following changes:</p>\n<ol>\n<li><p>Factor out models into a separate module; usually we'd call that <code>models.py</code>. If there are a lot of models you can split them into submodules under the <code>models/</code> package.</p>\n<p>Example:</p>\n<ul>\n<li><code>models\\</code>\n<ul>\n<li><code>user.py</code></li>\n<li><code>trade.py</code></li>\n<li>etc.</li>\n</ul>\n</li>\n</ul>\n<p>Since your app is quite small, <code>models.py</code> would be enough.<br />\nFactor out <code>Users</code> and <code>TraderBids</code> (Usually classes called in the singular) in models.</p>\n</li>\n<li><p>Next, you need to simplify your <code>user_page()</code> function.</p>\n<p>I've made an example for you:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Setting bids Table\nclass TradeBids(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n bid_type = db.Column(db.String(80), nullable=False)\n price_per_share = db.Column(db.Integer())\n share_amount = db.Column(db.Integer())\n trader_name = db.Column(db.String(80), nullable=False)\n bid_status = db.Column(db.String(80), nullable=False)\n\n def __repr__(self):\n return f"TradeBids(id: '{self.id}', " \\\n f"bid type: '{self.bid_type}', " \\\n f"price_per_share: '{self.price_per_share}', " \\\n f"share_amount: '{self.share_amount}', " \\\n f"trader_name: '{self.trader_name}')"\n\n def try_to_deal(self, user) -> bool:\n # handle the bid before it saves to data base\n look_for_match = TradeBids.query.filter(TradeBids.bid_type == 'sell',\n TradeBids.price_per_share <= self.price_per_share,\n TradeBids.share_amount >= self.share_amount,\n TradeBids.trader_name != user.user_name,\n TradeBids.bid_status == 'pending'\n ).order_by(TradeBids.price_per_share).first()\n\n # we have a deal !!!! exchange shares\n if look_for_match:\n diff = self.share_amount\n # Update the seller total share\n Users.query.filter_by(user_name=look_for_match.trader_name).update(\n dict(number_of_shares=look_for_match.share_amount - diff))\n db.session.commit()\n\n # Update the buyer total share\n Users.query.filter_by(user_name=user.user_name).update(\n dict(number_of_shares=user.number_of_shares + diff))\n db.session.commit()\n\n # Update the seller bid\n bid_id_to_update = look_for_match.id\n TradeBids.query.filter_by(id=bid_id_to_update).update(\n dict(share_amount=look_for_match.share_amount - diff))\n\n if TradeBids.query.filter_by(id=bid_id_to_update).first().share_amount == 0:\n TradeBids.query.filter_by(id=bid_id_to_update).update(\n dict(bid_status='expired'))\n db.session.commit()\n else:\n db.session.add(self)\n db.session.commit()\n\n....\n\n@app.route('/user_page/<user_name>', methods=['GET', 'POST'])\ndef user_page(user_name):\n user = Users.query.filter_by(user_name=user_name).first()\n sales_bid_form = SalesBids()\n buy_bids_form = BuyBids()\n\n if buy_bids_form.validate_on_submit():\n # Save the bid on memory\n bid = TradeBids(bid_type='buy', price_per_share=buy_bids_form.buy_asking_price.data,\n share_amount=buy_bids_form.buy_shares_amount.data,\n trader_name=user.user_name,\n bid_status='pending')\n\n # we dont have a deal save the bid\n if not bid.try_to_deal(user):\n return render_template('user_page.html', user=user, sell_form=sales_bid_form,\n buy_form=buy_bids_form)\n\n....\n</code></pre>\n<p>As you can see I moved part of the logic to the <code>TradeBids</code> class. This will improve code readability and maintainability since the logic that belongs to the <code>TradeBid</code> is encapsulated in the class. So you can just trigger the needed method in the <code>user_page</code> function.<br />\nMove the code into classes, it will make your code more structured.\nI hope you get the point.</p>\n</li>\n<li><p>Use <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\"><code>typing</code></a> as this will make your life easier. Even basic stuff will increase code readability and maintainability .</p>\n</li>\n</ol>\n<p>I think that should be enough for the first step.<br />\nGood luck.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T20:19:12.113",
"Id": "265644",
"ParentId": "263472",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265644",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-25T23:42:39.187",
"Id": "263472",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"flask"
],
"Title": "Python app thats simulate simple Stock Exchange"
}
|
263472
|
<p>This is a follow-up of my group of scraper questions starting from <a href="https://codereview.stackexchange.com/q/262772/242934">here</a>.</p>
<p>I have thus far, with the help of @Reinderien, written 4 separate "modules" that expose a <code>search</code> function to scrape bibliographic information from separate online databases. Half of which use <code>Selenium</code>; the other <code>Requests</code>.</p>
<p>I would like to know the best way to put them together, possibly organizing into a single module that can be imported together, and/or creating a base class so that common code can be shared between them.</p>
<p>I would like the final App to be able to execute the <code>search</code> function for each database, when given a list of search keywords, together with a choice of databases to search on as arguments.</p>
<hr />
<h1>Update:</h1>
<p>Since there is still no answer to this question, I have drafted a working code that takes in a list of keywords together with the database to be searched in. If this is unspecified, the same set of keywords would be looped through all databases.</p>
<p>I would like to seek improvements to the code below, especially with respect to:</p>
<ol>
<li>Consolidating the search results to a single <code>.json</code> or <code>.bib</code> file when all databases are involved.</li>
<li>Reusing common code so that the whole code-base is less bulky and extensible.</li>
<li>More flexible search options, such as choosing 2 or 3 out of 4 databases to search in. (Possibly with the use of <code>*args</code> or <code>**kwargs</code> in the search function.)</li>
</ol>
<h2>main.py</h2>
<pre class="lang-py prettyprint-override"><code>import cnki, fudan, wuhan, qinghua
def db_search(keyword, db=None):
db_dict = {
"cnki": cnki.search,
"fudan": fudan.search,
"wuhan": wuhan.search,
"qinghua": qinghua.search,
}
if db == None:
for key in db_dict.keys():
yield db_dict[key](keyword)
elif db == "cnki":
yield db_dict["cnki"](keyword)
elif db == "fudan":
yield db_dict["fudan"](keyword)
elif db == "wuhan":
yield db_dict["wuhan"](keyword)
elif db == "qinghua":
yield db_dict["qinghua"](keyword)
def search(keywords, db=None):
for kw in keywords:
yield from db_search(kw, db)
if __name__ == '__main__':
rslt = search(['尹誥','尹至'])
for item in rslt:
print(item)
</code></pre>
<hr />
<h1>The Code:</h1>
<h2>cnki.py</h2>
<pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager
from dataclasses import dataclass
from datetime import date
from pathlib import Path
from typing import Generator, Iterable, Optional, List, ContextManager, Dict
from urllib.parse import unquote
from itertools import chain, count
import re
import json
from math import ceil
# pip install proxy.py
import proxy
from proxy.http.exception import HttpRequestRejected
from proxy.http.parser import HttpParser
from proxy.http.proxy import HttpProxyBasePlugin
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
TimeoutException,
WebDriverException,
)
from selenium.webdriver import Firefox, FirefoxProfile
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import ProxyType
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
# from urllib3.packages.six import X
@dataclass
class Result:
title: str # Mozi's Theory of Human Nature and Politics
title_link: str # http://big5.oversea.cnki.net/kns55/detail/detail.aspx?recid=&FileName=ZDXB202006009&DbName=CJFDLAST2021&DbCode=CJFD
html_link: Optional[str] # http%3a%2f%2fkns.cnki.net%2fKXReader%2fDetail%3fdbcode%3dCJFD%26filename%3dZDXB202006009
author: str # Xie Qiyang
source: str # Vocational University News
source_link: str # http://big5.oversea.cnki.net/kns55/Navi/ScdbBridge.aspx?DBCode=CJFD&BaseID=ZDXB&UnitCode=&NaviLink=%e8%81%8c%e5%a4%a7%e5%ad%a6%e6%8a%a5
date: date # 2020-12-28
download: str #
database: str # Periodical
@classmethod
def from_row(cls, row: WebElement) -> 'Result':
number, title, author, source, published, database = row.find_elements_by_xpath('td')
title_links = title.find_elements_by_tag_name('a')
if len(title_links) > 1:
# 'http://big5.oversea.cnki.net/kns55/ReadRedirectPage.aspx?flag=html&domain=http%3a%2f%2fkns.cnki.net%2fKXReader%2fDetail%3fdbcode%3dCJFD%26filename%3dZDXB202006009'
html_link = unquote(
title_links[1]
.get_attribute('href')
.split('domain=', 1)[1])
else:
html_link = None
dl_links, sno = number.find_elements_by_tag_name('a')
published_date = date.fromisoformat(
published.text.split(maxsplit=1)[0]
)
return cls(
title=title_links[0].text,
title_link=title_links[0].get_attribute('href'),
html_link=html_link,
author=author.text,
source=source.text,
source_link=source.get_attribute('href'),
date=published_date,
download=dl_links.get_attribute('href'),
database=database.text,
)
def __str__(self):
return (
f'題名 {self.title}'
f'\n作者 {self.author}'
f'\n來源 {self.source}'
f'\n發表時間 {self.date}'
f'\n下載連結 {self.download}'
f'\n來源數據庫 {self.database}'
)
def as_dict(self) -> Dict[str, str]:
return {
'author': self.author,
'title': self.title,
'date': self.date.isoformat(),
'download': self.download,
'url': self.html_link,
'database': self.database,
}
class MainPage:
def __init__(self, driver: WebDriver):
self.driver = driver
def submit_search(self, keyword: str) -> None:
wait = WebDriverWait(self.driver, 50)
search = wait.until(
EC.presence_of_element_located((By.NAME, 'txt_1_value1'))
)
search.send_keys(keyword)
search.submit()
def switch_to_frame(self) -> None:
wait = WebDriverWait(self.driver, 100)
wait.until(
EC.presence_of_element_located((By.XPATH, '//iframe[@name="iframeResult"]'))
)
self.driver.switch_to.default_content()
self.driver.switch_to.frame('iframeResult')
wait.until(
EC.presence_of_element_located((By.XPATH, '//table[@class="GridTableContent"]'))
)
def max_content(self) -> None:
"""Maximize the number of items on display in the search results."""
max_content = self.driver.find_element(
By.CSS_SELECTOR, '#id_grid_display_num > a:nth-child(3)',
)
max_content.click()
# def get_element_and_stop_page(self, *locator) -> WebElement:
# ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
# wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions)
# elm = wait.until(EC.presence_of_element_located(locator))
# self.driver.execute_script("window.stop();")
# return elm
class SearchResults:
def __init__(self, driver: WebDriver):
self.driver = driver
def number_of_articles_and_pages(self) -> int:
elem = self.driver.find_element_by_xpath(
'//table//tr[3]//table//table//td[1]/table//td[1]'
)
n_articles = re.search("共有記錄(.+)條", elem.text).group(1)
n_pages = ceil(int(n_articles)/50)
return n_articles, n_pages
def get_structured_elements(self) -> Iterable[Result]:
rows = self.driver.find_elements_by_xpath(
'//table[@class="GridTableContent"]//tr[position() > 1]'
)
for row in rows:
yield Result.from_row(row)
def get_element_and_stop_page(self, *locator) -> WebElement:
ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions)
elm = wait.until(EC.presence_of_element_located(locator))
self.driver.execute_script("window.stop();")
return elm
def next_page(self) -> None:
link = self.get_element_and_stop_page(By.LINK_TEXT, "下頁")
try:
link.click()
print("Navigating to Next Page")
except (TimeoutException, WebDriverException):
print("Last page reached")
class ContentFilterPlugin(HttpProxyBasePlugin):
HOST_WHITELIST = {
b'ocsp.digicert.com',
b'ocsp.sca1b.amazontrust.com',
b'big5.oversea.cnki.net',
}
def handle_client_request(self, request: HttpParser) -> Optional[HttpParser]:
host = request.host or request.header(b'Host')
if host not in self.HOST_WHITELIST:
raise HttpRequestRejected(403)
if any(
suffix in request.path
for suffix in (
b'png', b'ico', b'jpg', b'gif', b'css',
)
):
raise HttpRequestRejected(403)
return request
def before_upstream_connection(self, request):
return super().before_upstream_connection(request)
def handle_upstream_chunk(self, chunk):
return super().handle_upstream_chunk(chunk)
def on_upstream_connection_close(self):
pass
@contextmanager
def run_driver() -> ContextManager[WebDriver]:
prox_type = ProxyType.MANUAL['ff_value']
prox_host = '127.0.0.1'
prox_port = 8889
profile = FirefoxProfile()
profile.set_preference('network.proxy.type', prox_type)
profile.set_preference('network.proxy.http', prox_host)
profile.set_preference('network.proxy.ssl', prox_host)
profile.set_preference('network.proxy.http_port', prox_port)
profile.set_preference('network.proxy.ssl_port', prox_port)
profile.update_preferences()
plugin = f'{Path(__file__).stem}.{ContentFilterPlugin.__name__}'
with proxy.start((
'--hostname', prox_host,
'--port', str(prox_port),
'--plugins', plugin,
)), Firefox(profile) as driver:
yield driver
def loop_through_results(driver):
result_page = SearchResults(driver)
n_articles, n_pages = result_page.number_of_articles_and_pages()
print(f"{n_articles} found. A maximum of 500 will be retrieved.")
for page in count(1):
print(f"Scraping page {page}/{n_pages}")
print()
result = result_page.get_structured_elements()
yield from result
if page >= n_pages or page >= 10:
break
result_page.next_page()
result_page = SearchResults(driver)
def save_articles(articles: Iterable, file_prefix: str) -> None:
file_path = Path(file_prefix).with_suffix('.json')
with file_path.open('w') as file:
file.write('[\n')
first = True
for article in articles:
if first:
first = False
else:
file.write(',\n')
json.dump(article.as_dict(), file, ensure_ascii=False, indent=4)
file.write('\n]\n')
def query(keyword, driver) -> None:
page = MainPage(driver)
page.submit_search(keyword)
page.switch_to_frame()
page.max_content()
def search(keyword):
with Firefox() as driver:
driver.get('http://big5.oversea.cnki.net/kns55/')
query(keyword, driver)
result = loop_through_results(driver)
save_articles(result, 'cnki_search_result.json')
if __name__ == '__main__':
search('尹至')
</code></pre>
<h2>qinghua.py</h2>
<p><em>Search functionality is down at the moment. Planning the try out with <code>Requests</code> as soon as it is up and running.</em></p>
<pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager
from dataclasses import dataclass, asdict, replace
from datetime import datetime, date
from pathlib import Path
from typing import Iterable, Optional, ContextManager
import re
import os
import time
import json
# pip install proxy.py
import proxy
from proxy.http.exception import HttpRequestRejected
from proxy.http.parser import HttpParser
from proxy.http.proxy import HttpProxyBasePlugin
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
TimeoutException,
WebDriverException,
)
from selenium.webdriver import Firefox, FirefoxProfile
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import ProxyType
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
@dataclass
class PrimaryResult:
captions: str
date: date
link: str
@classmethod
def from_row(cls, row: WebElement) -> 'PrimaryResult':
caption_elems = row.find_element_by_tag_name('a')
date_elems = row.find_element_by_class_name('time')
published_date = date.isoformat(datetime.strptime(date_elems.text, '%Y-%m-%d'))
return cls(
captions = caption_elems.text,
date = published_date,
link = caption_elems.get_attribute('href')
)
def __str__(self):
return (
f'\n標題 {self.captions}'
f'\n發表時間 {self.date}'
f'\n文章連結 {self.link}'
)
class MainPage:
def __init__(self, driver: WebDriver):
self.driver = driver
def submit_search(self, keyword: str) -> None:
driver = self.driver
wait = WebDriverWait(self.driver, 100)
xpath = "//form/button/input"
element_to_hover_over = driver.find_element_by_xpath(xpath)
hover = ActionChains(driver).move_to_element(element_to_hover_over)
hover.perform()
search = wait.until(
EC.presence_of_element_located((By.ID, 'showkeycode1015273'))
)
search.send_keys(keyword)
search.submit()
def get_element_and_stop_page(self, *locator) -> WebElement:
ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions)
elm = wait.until(EC.presence_of_element_located(locator))
self.driver.execute_script("window.stop();")
return elm
def next_page(self) -> None:
try:
link = self.get_element_and_stop_page(By.LINK_TEXT, "下一页")
link.click()
print("Navigating to Next Page")
except (TimeoutException, WebDriverException):
print("No button with 「下一页」 found.")
return 0
# @contextmanager
# def wait_for_new_window(self):
# driver = self.driver
# handles_before = driver.window_handles
# yield
# WebDriverWait(driver, 10).until(
# lambda driver: len(handles_before) != len(driver.window_handles))
def switch_tabs(self):
driver = self.driver
print("Current Window:")
print(driver.title)
print()
p = driver.current_window_handle
chwd = driver.window_handles
time.sleep(3)
driver.switch_to.window(chwd[1])
print("New Window:")
print(driver.title)
print()
class SearchResults:
def __init__(self, driver: WebDriver):
self.driver = driver
def get_primary_search_result(self):
filePath = os.path.join(os.getcwd(), "qinghua_primary_search_result.json")
if os.path.exists(filePath):
os.remove(filePath)
rows = self.driver.find_elements_by_xpath('//ul[@class="search_list"]/li')
for row in rows:
rslt = PrimaryResult.from_row(row)
with open('qinghua_primary_search_result.json', 'a') as file:
json.dump(asdict(rslt), file, ensure_ascii=False, indent=4)
yield rslt
# class ContentFilterPlugin(HttpProxyBasePlugin):
# HOST_WHITELIST = {
# b'ocsp.digicert.com',
# b'ocsp.sca1b.amazontrust.com',
# b'big5.oversea.cnki.net',
# b'gwz.fudan.edu.cn',
# b'bsm.org.cn/index.php'
# b'ctwx.tsinghua.edu.cn',
# }
# def handle_client_request(self, request: HttpParser) -> Optional[HttpParser]:
# host = request.host or request.header(b'Host')
# if host not in self.HOST_WHITELIST:
# raise HttpRequestRejected(403)
# if any(
# suffix in request.path
# for suffix in (
# b'png', b'ico', b'jpg', b'gif', b'css',
# )
# ):
# raise HttpRequestRejected(403)
# return request
# def before_upstream_connection(self, request):
# return super().before_upstream_connection(request)
# def handle_upstream_chunk(self, chunk):
# return super().handle_upstream_chunk(chunk)
# def on_upstream_connection_close(self):
# pass
# @contextmanager
# def run_driver() -> ContextManager[WebDriver]:
# prox_type = ProxyType.MANUAL['ff_value']
# prox_host = '127.0.0.1'
# prox_port = 8889
# profile = FirefoxProfile()
# profile.set_preference('network.proxy.type', prox_type)
# profile.set_preference('network.proxy.http', prox_host)
# profile.set_preference('network.proxy.ssl', prox_host)
# profile.set_preference('network.proxy.http_port', prox_port)
# profile.set_preference('network.proxy.ssl_port', prox_port)
# profile.update_preferences()
# plugin = f'{Path(__file__).stem}.{ContentFilterPlugin.__name__}'
# with proxy.start((
# '--hostname', prox_host,
# '--port', str(prox_port),
# '--plugins', plugin,
# )), Firefox(profile) as driver:
# yield driver
def search(keyword) -> None:
with Firefox() as driver:
driver.get('http://www.ctwx.tsinghua.edu.cn/index.htm')
page = MainPage(driver)
# page.select_dropdown_item()
page.submit_search(keyword)
time.sleep(5)
# page.switch_tabs()
while True:
primary_result_page = SearchResults(driver)
primary_results = primary_result_page.get_primary_search_result()
for result in primary_results:
print(result)
print()
if page.next_page() == 0:
break
else:
pass
if __name__ == '__main__':
search('尹至')
</code></pre>
<h2>fudan.py</h2>
<pre class="lang-py prettyprint-override"><code># fudan.py
from dataclasses import dataclass
from itertools import count
from pathlib import Path
from typing import Dict, Iterable, Tuple, List, Optional
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from requests import Session
from datetime import date, datetime
import json
import re
BASE_URL = 'http://www.gwz.fudan.edu.cn'
@dataclass
class Link:
caption: str
url: str
clicks: int
replies: int
added: date
@classmethod
def from_row(cls, props: Dict[str, str], path: str) -> 'Link':
clicks, replies = props['点击/回复'].split('/')
# Skip number=int(props['编号']) - this only has meaning within one page
return cls(
caption=props['资源标题'],
url=urljoin(BASE_URL, path),
clicks=int(clicks),
replies=int(replies),
added=datetime.strptime(props['添加时间'], '%Y/%m/%d').date(),
)
def __str__(self):
return f'{self.added} {self.url} {self.caption}'
def author_title(self) -> Tuple[Optional[str], str]:
sep = ':' # full-width colon, U+FF1A
if sep not in self.caption:
return None, self.caption
author, title = self.caption.split(sep, 1)
author, title = author.strip(), title.strip()
net_digest = '網摘'
if author == net_digest:
return None, title
return author, title
@dataclass
class Article:
author: Optional[str]
title: str
date: date
download: Optional[str]
url: str
@classmethod
def from_link(cls, link: Link, download: str) -> 'Article':
author, title = link.author_title()
download = download.replace("\r", "").replace("\n", "").strip()
if download == '#_edn1':
download = None
elif download[0] != '/':
download = '/' + download
return cls(
author=author,
title=title,
date=link.added,
download=download,
url=link.url,
)
def __str__(self) -> str:
return(
f"\n作者 {self.author}"
f"\n標題 {self.title}"
f"\n發佈日期 {self.date}"
f"\n下載連結 {self.download}"
f"\n訪問網頁 {self.url}"
)
def as_dict(self) -> Dict[str, str]:
return {
'author': self.author,
'title': self.title,
'date': self.date.isoformat(),
'download': self.download,
'url': self.url,
}
def compile_search_results(session: Session, links: Iterable[Link], category_filter: str) -> Iterable[Article]:
for link in links:
with session.get(link.url) as resp:
resp.raise_for_status()
doc = BeautifulSoup(resp.text, 'html.parser')
category = doc.select_one('#_top td a[href="#"]').text
if category != category_filter:
continue
content = doc.select_one('span.ny_font_content')
dl_tag = content.find(
'a', {
'href': re.compile("/?(lunwen/|articles/up/).+")
}
)
yield Article.from_link(link, download=dl_tag['href'])
def get_page(session: Session, query: str, page: int) -> Tuple[List[Link], int]:
with session.get(
urljoin(BASE_URL, '/Web/Search'),
params={
's': query,
'page': page,
},
) as resp:
resp.raise_for_status()
doc = BeautifulSoup(resp.text, 'html.parser')
table = doc.select_one('#tab table')
heads = [h.text for h in table.select('tr.cap td')]
links = []
for row in table.find_all('tr', class_=''):
cells = [td.text for td in row.find_all('td')]
links.append(Link.from_row(
props=dict(zip(heads, cells)),
path=row.find('a')['href'],
))
page_td = doc.select_one('#tab table:nth-child(2) td') # 共 87 条记录, 页 1/3
n_pages = int(page_td.text.rsplit('/', 1)[1])
return links, n_pages
def get_all_links(session: Session, query: str) -> Iterable[Link]:
for page in count(1):
links, n_pages = get_page(session, query, page)
print(f'{page}/{n_pages}')
yield from links
if page >= n_pages:
break
def save_articles(articles: Iterable[Article], file_prefix: str) -> None:
file_path = Path(file_prefix).with_suffix('.json')
with file_path.open('w') as file:
file.write('[\n')
first = True
for article in articles:
if first:
first = False
else:
file.write(',\n')
json.dump(article.as_dict(), file, ensure_ascii=False, indent=4)
file.write('\n]\n')
def search(keyword):
with Session() as session:
links = get_all_links(session, query=keyword)
academic_library = '学者文库'
articles = compile_search_results(session, links, category_filter=academic_library)
save_articles(articles, 'fudan_search_result')
if __name__ == '__main__':
search('尹至')
</code></pre>
<h2>wuhan.py</h2>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, asdict
from itertools import count
from typing import Dict, Iterable, Tuple, List
from bs4 import BeautifulSoup
from requests import post
from datetime import date, datetime
import json
import os
import re
@dataclass
class Result:
author: str
title: str
date: date
url: str
publication: str = "武漢大學簡帛網"
@classmethod
def from_metadata(cls, metadata: Dict) -> 'Result':
author, title = metadata['caption'].split(':')
published_date = date.isoformat(datetime.strptime(metadata['date'], '%y/%m/%d'))
url = 'http://www.bsm.org.cn/' + metadata['url']
return cls(
author = author,
title = title,
date = published_date,
url = url
)
def __str__(self):
return (
f'作者 {self.author}'
f'\n標題 {self.title}'
f'\n發表時間 {self.date}'
f'\n文章連結 {self.url}'
f'\n發表平台 {self.publication}'
)
def submit_query(keyword: str):
query = {"searchword": keyword}
with post('http://www.bsm.org.cn/pages.php?pagename=search', query) as resp:
resp.raise_for_status()
doc = BeautifulSoup(resp.text, 'html.parser')
content = doc.find('div', class_='record_list_main')
rows = content.select('ul')
for row in rows:
if len(row.findAll('li')) != 2:
print()
print(row.text)
print()
else:
captions_tag, date_tag = row.findAll('li')
caption_anchors = captions_tag.findAll('a')
category, caption = [item.text for item in caption_anchors]
url = caption_anchors[1]['href']
date = re.sub("[()]", "", date_tag.text)
yield {
"category": category,
"caption": caption,
"date": date,
"url": url}
def remove_json_if_exists(filename):
json_file = filename + ".json"
filePath = os.path.join(os.getcwd(), json_file)
if os.path.exists(filePath):
os.remove(filePath)
def search(query: str):
remove_json_if_exists('wuhan_search_result')
rslt = submit_query(query)
for metadata in rslt:
article = Result.from_metadata(metadata)
print(article)
print()
with open('wuhan_search_result.json', 'a') as file:
json.dump(asdict(article), file, ensure_ascii=False, indent=4)
if __name__ == '__main__':
search('尹至')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T10:08:51.290",
"Id": "520976",
"Score": "2",
"body": "Hi Sati. 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. 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": "2021-07-07T10:57:57.280",
"Id": "520979",
"Score": "0",
"body": "I have posted a revised version of my code as a new answer over [here](https://codereview.stackexchange.com/q/263834/242934)"
}
] |
[
{
"body": "<p>I'm going to focus on <code>main.py</code> since the other modules have gotten reviews.</p>\n<ul>\n<li><code>db_dict</code> can be a module-level global constant <code>DB_DICT</code></li>\n<li>the convenient interface is to replace your <code>db</code> argument with <code>*args</code> taking one or more database names; then this:</li>\n</ul>\n<pre><code> elif db == "cnki":\n yield db_dict["cnki"](keyword)\n elif db == "fudan":\n yield db_dict["fudan"](keyword)\n elif db == "wuhan":\n yield db_dict["wuhan"](keyword)\n elif db == "qinghua":\n yield db_dict["qinghua"](keyword)\n</code></pre>\n<p>can be</p>\n<pre><code>for db in args:\n yield from db_dict[db](keyword)\n</code></pre>\n<ul>\n<li>Does this even run? Each of your module <code>search</code> methods does the wrong thing, either printing or saving to a file when it should be returning results. As such, any of your <code>yield db_dict[key](keyword)</code> statements will actually just be yielding <code>None</code>. I'd expect it to actually be <code>yield from db_dict[key](keyword)</code> so that <code>db_search</code> itself is a flat generator.</li>\n<li>There are no type hints to be seen in <code>main.py</code>; it could use them.</li>\n<li>Your model of spinning up and shutting down a Requests session or (much worse) a Selenium browser instance for every single keyword is not practical. It would be a better idea to class-ify any session-level state, and keep that state alive across multiple searches for a given database.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T09:35:43.253",
"Id": "520974",
"Score": "0",
"body": "I've updated my question to fix the bulk of the more trivial issues."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:49:59.007",
"Id": "263820",
"ParentId": "263474",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263820",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T01:09:51.073",
"Id": "263474",
"Score": "1",
"Tags": [
"python",
"web-scraping",
"modules"
],
"Title": "Organizing things together to form a minimum viable Scraper App"
}
|
263474
|
<p>This is my first post. I'm switching from Python to Java and I've been practicing on <code>HackerRank</code> for some time. Today I solved this problem in which you have to count the pairs of occurrences of the numbers in the ArrayList, symbolizing socks, and you have to count the pairs.</p>
<p>Can this be optimized in any way? Maybe I'm too used to Dictionaries' methods and syntax in Python. Anyway, any feedback is appreciated.</p>
<pre class="lang-java prettyprint-override"><code>public static int countPairs() {
HashMap<Integer,Integer> mapa = new HashMap<Integer,Integer>();
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(20);
list.add(10);
list.add(10);
list.add(30);
list.add(50);
list.add(10);
list.add(20);
int pairs=0;
for (int i = 0; i < list.size(); i++) {
if (!mapa.containsKey(list.get(i))) {
mapa.put(list.get(i), 1);
} else {
mapa.replace(list.get(i), mapa.get(list.get(i))+1);
}
}
int whole;
for (Integer key : mapa.keySet()) {
whole = (int)mapa.get(key)/2;
pairs=pairs+whole;
}
return pairs;
}
</code></pre>
|
[] |
[
{
"body": "<p>In your for-loop, you basically mimic <code>Map.computeIfAbsent</code>. For a given int <code>n</code>, you can use</p>\n<pre><code>map.computeIfAbsent(n, ignore -> 0);\n</code></pre>\n<p>to return 0 when the key is not present, and thus</p>\n<pre><code>map.put(n, map.computeIfAbsent(n, ignore -> 0) + 1);\n</code></pre>\n<p>as your calculation.</p>\n<p>Note that <code>ignore -> 0</code> is a lambda of the signature <code>Function<Integer, Integer></code>, which does not use its input parameter. Therefore I named it "ignore".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T11:52:01.123",
"Id": "520165",
"Score": "0",
"body": "Not sure if this is allowed in java, but the traditional name for a lambda parameter you ignore is `_`, as in `_ -> 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T18:45:12.210",
"Id": "520183",
"Score": "0",
"body": "Use `putIfAbsent` to avoid the lambda. Or, better, `getOrDefault` as the returned value is `put` in the map anyway."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T05:10:51.450",
"Id": "263478",
"ParentId": "263477",
"Score": "3"
}
},
{
"body": "<p>I noticed in your code the following definitions:</p>\n<pre><code>HashMap<Integer,Integer> mapa = new HashMap<Integer,Integer>();\nArrayList<Integer> list=new ArrayList<Integer>();\n</code></pre>\n<p>When it is possible it is better to use an interface than a class implementing the interface like below:</p>\n<pre><code>Map<Integer,Integer> mapa = new HashMap<Integer,Integer>();\nList<Integer> list=new ArrayList<Integer>();\n</code></pre>\n<p>So for example if you want to use <code>TreeMap</code> instead of <code>HashMap</code> you can just declare <code>Map<Integer,Integer> mapa = new TreeMap<Integer,Integer>();</code> without affecting the rest of the codebase.</p>\n<p>In the line <code>whole = (int)mapa.get(key)/2;</code> you can erase the cast to <code>int</code>, I think you added this because related to your Python programming practice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T07:40:51.120",
"Id": "263480",
"ParentId": "263477",
"Score": "4"
}
},
{
"body": "<p>In Java 8 introduced <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/Stream.html\" rel=\"nofollow noreferrer\">Streams</a>: have a look at them! Despite a somewhat verbose syntax, you might find things you're more familiar with in Python.</p>\n<p>You'll probably be interested in the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/Collectors.html#groupingBy(java.util.function.Function,java.util.function.Supplier,java.util.stream.Collector)\" rel=\"nofollow noreferrer\">groupingBy</a> Collector. And in <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#replaceAll(java.util.function.BiFunction)\" rel=\"nofollow noreferrer\">Map#replaceAll</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T18:42:03.183",
"Id": "263494",
"ParentId": "263477",
"Score": "0"
}
},
{
"body": "<p>Prefer assigning variables to the most generally applicable type. If it doesn't matter what kind of list you have, use <code>List</code>. If it doesn't matter what kind of map you have, use <code>Map</code>.</p>\n<p>Use whitespace consistently. <code>=</code>, <code>+</code>, and <code>/</code> should have whitespace on both sides.</p>\n<p>Code doesn't need to declare the generic type on the right hand side of an assignment. The compiler will infer it from what is declared on the left hand side. Use <code><></code> instead.</p>\n<p><code>Arrays.asList()</code> is probably easier to read than adding multiple values to the list. Do note that this type of list is fixed size after it is created.</p>\n<p><code>list</code> is not very descriptive, nor is <code>mapa</code>. Descriptive names are very important.</p>\n<p>It would be preferable for the code to use an enhanced for loop. Iterators are more efficient at going over some List types than calling <code>get()</code>. They are also easier to read.</p>\n<p>The if-else block could be replaced with a getOrDefault() call followed by a put.</p>\n<p>It would be preferable to iterate over the mapa values instead of keys. The keys don't matter except to separate out the counts.</p>\n<p>The declaration of pairs belongs closer to where it's actually used.</p>\n<p><code>whole</code> can be declared inside the loop.</p>\n<p>All the math can be done on one line inside the second loop.</p>\n<p>The logic can also be done more efficiently using a Set. Iterate over each sock. If it's in the set, remove it and increase the pair count. If it's not in the set, add it.</p>\n<p>If you made all these changes, your code might look like:</p>\n<pre><code>public static int countPairs() {\n Map<Integer, Integer> sockCounts = new HashMap<>();\n List<Integer> sockIds = Arrays.asList(10, 20, 20, 10, 10, 30, 50, 10, 20);\n\n for (int sockId : sockIds) {\n int currentCount = sockCounts.getOrDefault(sockId, 0);\n sockCounts.put(sockId, currentCount + 1);\n }\n\n int pairs = 0;\n for (int count : sockCounts.values()) {\n pairs += (count / 2);\n }\n return pairs;\n}\n\npublic static int countPairsWithSet() {\n List<Integer> sockIds = Arrays.asList(10, 20, 20, 10, 10, 30, 50, 10, 20);\n Set<Integer> unmatchedSocks = new HashSet<>();\n\n int pairs = 0;\n for (int sockId : sockIds) {\n if (unmatchedSocks.contains(sockId)) {\n unmatchedSocks.remove(sockId);\n pairs++;\n } else {\n unmatchedSocks.add(sockId);\n }\n }\n return pairs;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T21:08:43.957",
"Id": "520200",
"Score": "1",
"body": "You can also take advantage of the return value of `add` to optimize runtime performance slightly at the cost of readability: `if (!unmatchedSocks.add(sockId)) { unmatchedSocks.remove(sockId); pairs++; }` Experienced developers will recognize that, but it will probably confuse junior developers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T18:46:41.683",
"Id": "263495",
"ParentId": "263477",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263495",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T03:13:27.967",
"Id": "263477",
"Score": "4",
"Tags": [
"java",
"performance",
"beginner"
],
"Title": "HackerRank Sales by Match"
}
|
263477
|
<p>I have a table containing two versions of results for some predictors, one by human labeling and the other by machine predicting, and I want to calculate some metrics.</p>
<pre><code>CREATE TABLE log_table (
`id` VARCHAR(5),
`version` VARCHAR(15),
`result` FlOAT
);
INSERT INTO log_table
(`id`, `version`, `result`)
VALUES
('001', '2020-12-10', 0.8),
('002', '2020-12-10', 0.1),
('003', '2020-12-10', 0.2),
('004', '2020-12-10', 0.9),
('001', 'ground_truth', 1),
('002', 'ground_truth', 0),
('003', 'ground_truth', 1),
('004', 'ground_truth', 0),
('005', 'ground_truth', 1);
</code></pre>
<p>Here I tried to work out the <a href="https://en.wikipedia.org/wiki/Precision_and_recall" rel="nofollow noreferrer">recall and precision</a>.</p>
<pre><code>SELECT true_positive / ( true_positive + false_negative ) AS recall,
true_positive / ( true_positive + false_positive ) AS _precision
FROM (SELECT (SELECT Count(*) AS true_positive
FROM (SELECT id,
IF(result > 0.5, 1, 0) AS predict_result
FROM log_table
WHERE version = "2020-12-10") AS t_left
JOIN (SELECT id,
result
FROM log_table
WHERE version = "ground_truth"
AND result = 1) AS t_right
ON t_left.id = t_right.id
AND t_left.predict_result = t_right.result) AS
true_positive,
(SELECT Count(*) AS false_negative
FROM (SELECT id,
IF(result > 0.5, 1, 0) AS predict_result
FROM log_table
WHERE version = "2020-12-10") AS t_left
JOIN (SELECT id,
result
FROM log_table
WHERE version = "ground_truth"
AND result = 1) AS t_right
ON t_left.id = t_right.id
AND t_left.predict_result != t_right.result) AS
false_negative,
(SELECT Count(*) AS false_positive
FROM (SELECT id,
IF(result > 0.5, 1, 0) AS predict_result
FROM log_table
WHERE version = "2020-12-10") AS t_left
JOIN (SELECT id,
result
FROM log_table
WHERE version = "ground_truth"
AND result = 0) AS t_right
ON t_left.id = t_right.id
AND t_left.predict_result != t_right.result) AS
false_positive,
(SELECT Count(*) AS true_negative
FROM (SELECT id,
IF(result > 0.5, 1, 0) AS predict_result
FROM log_table
WHERE version = "2020-12-10") AS t_left
JOIN (SELECT id,
result
FROM log_table
WHERE version = "ground_truth"
AND result = 0) AS t_right
ON t_left.id = t_right.id
AND t_left.predict_result = t_right.result) AS
true_negative) AS metrics;
</code></pre>
<p>The code above seems not only complicated but also repetitive, then I wonder if it would be optimized and simplified? <a href="https://www.db-fiddle.com/f/brCyWqTTGwAjTgr7szWTu2/1" rel="nofollow noreferrer">Here</a> is its fiddle link.</p>
|
[] |
[
{
"body": "<p>Fundamentally you just need to rethink how your aggregation is done. The RDBMS you use - MySQL - <a href=\"https://modern-sql.com/feature/filter\" rel=\"nofollow noreferrer\">is broken and does not support</a> standard <a href=\"https://www.postgresql.org/docs/13/sql-expressions.html#SYNTAX-AGGREGATES\" rel=\"nofollow noreferrer\">aggregates</a>.</p>\n<p>Applying some <code>filter</code>s and replacing your conditional with a <code>round</code> makes this problem trivial if you're able to use PostgreSQL instead:</p>\n<pre><code>select cast(true_pos as real) / (true_pos + false_neg) as recall,\n cast(true_pos as real) / (true_pos + false_pos) as precision\nfrom (\n select\n count(*) filter(where t_act.result=0 and t_exp.result=1) as false_neg,\n -- count(*) filter(where t_act.result=0 and t_exp.result=0) as true_neg,\n count(*) filter(where t_act.result=1 and t_exp.result=0) as false_pos,\n count(*) filter(where t_act.result=1 and t_exp.result=1) as true_pos\n from (\n select id, round(result) as result\n from log_table\n where version = '2020-12-10'\n ) as t_act\n join log_table as t_exp\n on t_act.id = t_exp.id and t_exp.version = 'ground_truth'\n) as metrics;\n</code></pre>\n<p><a href=\"http://sqlfiddle.com/#!17/e3bb4/8\" rel=\"nofollow noreferrer\">sqlfiddle.com also supports this</a>.</p>\n<p>However, since you're stuck with MySQL you could use the <code>case</code> workaround proposed in that modern-sql site:</p>\n<pre><code>select true_pos / (true_pos + false_neg) as recall,\n true_pos / (true_pos + false_pos) as 'precision'\nfrom (\n select\n count(case when t_act.result=0 and t_exp.result=1 then 1 end) as false_neg,\n count(case when t_act.result=1 and t_exp.result=0 then 1 end) as false_pos,\n count(case when t_act.result=1 and t_exp.result=1 then 1 end) as true_pos\n from (\n select id, round(result) as result\n from log_table\n where version = '2020-12-10'\n ) as t_act\n join log_table as t_exp\n on t_act.id = t_exp.id and t_exp.version = 'ground_truth'\n) as metrics;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T13:31:59.167",
"Id": "520641",
"Score": "0",
"body": "The code is neat, but it seems not to work in MySQL."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T13:33:44.533",
"Id": "520642",
"Score": "0",
"body": "@Lnz right; which is why I mentioned that explicitly along with a workaround. Why are you using MySQL?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T13:35:08.930",
"Id": "520643",
"Score": "0",
"body": "We can only use MySQL in our company. :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T13:36:26.627",
"Id": "520644",
"Score": "0",
"body": "Facetiously: sounds like you need a new company. But anyway, the link above describes a workaround for MySQL."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T17:26:38.763",
"Id": "520729",
"Score": "0",
"body": "@Lnz done; and confirmed in db-fiddle.com"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T12:42:39.037",
"Id": "263485",
"ParentId": "263481",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263485",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T09:29:01.060",
"Id": "263481",
"Score": "1",
"Tags": [
"sql",
"mysql"
],
"Title": "SQL for precision and recall?"
}
|
263481
|
<p>I'm learning <code>Vue</code> and I would like an opinion to improve the form validation that I have implemented. This is my component:</p>
<pre><code><template>
<section class="p-0 d-flex align-items-center">
<div class="container-fluid">
<div class="row">
<!-- Right START -->
<div class="col-md-12 col-lg-8 col-xl-9 mx-auto my-5 position-relative">
<!-- Shape Decoration START -->
<!-- Shape 1 -->
<!-- Shape Decoration END -->
<div class="row h-100">
<div
class="
col-md-12 col-lg-10 col-xl-5
text-start
mx-auto
d-flex
align-items-center
"
>
<div class="w-100">
<h3>Sign up for your account!</h3>
<p>
Join us today! Create your account easily with less
information.
</p>
<!-- Form START -->
<form class="mt-4" @submit.prevent="submit">
<!-- Email -->
<div class="mb-3">
<label class="form-label" for="email">Email address</label>
<input
v-model="data.name"
v-bind:class="{ 'is-invalid': emailFailure }"
required
type="email"
class="form-control"
id="email"
aria-describedby="emailHelp"
placeholder="E-mail"
/>
<div class="invalid-feedback">
{{ emailFailureText }}
</div>
<small id="emailHelp" class="form-text text-muted"
>We'll never share your email with anyone else.</small
>
</div>
<!-- Username -->
<div class="mb-3">
<label class="form-label" for="email">Username</label>
<input
v-model="data.username"
v-bind:class="{ 'is-invalid': usernameFailure }"
required
type="text"
class="form-control"
id="username"
placeholder="Username"
/>
<div class="invalid-feedback">
{{ usernameFailureText }}
</div>
</div>
<!-- Password -->
<div class="mb-3">
<label class="form-label" for="password">Password</label>
<input
v-model="data.password"
v-bind:class="{ 'is-invalid': passwordFailure }"
required
type="password"
class="form-control"
id="password"
placeholder="*********"
/>
<div class="invalid-feedback">
{{ passwordFailureText }}
</div>
</div>
<!-- Password -->
<div class="mb-3">
<label class="form-label" for="password2"
>Confirm Password</label
>
<input
v-model="data.password2"
v-bind:class="{ 'is-invalid': password2Failure }"
type="password"
class="form-control"
id="password2"
placeholder="*********"
/>
<div class="invalid-feedback">
{{ password2FailureText }}
</div>
</div>
</form>
<!-- Form END -->
<div class="bg-dark-overlay-dotted py-2 my-4"></div>
</div>
</div>
</div>
</div>
<!-- Right END -->
</div>
</div>
</section>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { useRouter } from "vue-router";
export default defineComponent({
name: "Register",
setup(props) {
const data = reactive({
username: "",
email: "",
password: "",
password2: "",
});
const router = useRouter();
const emailFailure = ref(false);
const emailFailureText = ref("");
const usernameFailure = ref(false);
const usernameFailureText = ref("");
const passwordFailure = ref(false);
const passwordFailureText = ref("");
const password2Failure = ref(false);
const password2FailureText = ref("");
const submit = async () => {
emailFailure.value = false;
emailFailureText.value = "";
usernameFailure.value = false;
usernameFailureText.value = "";
passwordFailure.value = false;
passwordFailureText.value = "";
password2Failure.value = false;
password2FailureText.value = "";
const res = await fetch(`${process.env.VUE_APP_API_URL}/auth/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) {
const errors = await res.json();
emailFailure.value = true;
emailFailureText.value = "the email is invalid";
}
/*
if (res.text === 200) {
await router.push("/login");
}*/
};
return {
data,
emailFailure,
emailFailureText,
submit,
};
},
});
</script>
</code></pre>
<p>what I did so far is define inside the method <code>setup</code>, a <code>data</code> variable which will handle all the values that the user fill in the form. These values are passed to my <code>API</code> using the <code>fetch</code> method which is called in the <code>submit</code> function.</p>
<p>When the <code>API</code> call is completed, I check if the <code>response</code> was successfull or not by checking the <code>ok</code> property. If the response is unsuccessful I valorize all the property of each field manually to display the error on the proper field.</p>
<p>The code above just have the <code>emailFailure</code> implementation, and this is actually working fine, but my concern is about all the fields. Suppose that I have 20 fields, should I have create 20 property which handle the error, and other 20 which handle the error message?</p>
<p>There is a way to handle multiple fields without create all those properties?</p>
<p>Also, the <code>API</code> response return an array of objects like this:</p>
<pre><code>[{
location: "body",
msg: "invalid email",
param: "email",
value: ""
}, {
location: "body",
msg: "Password must be at least 8 characters",
param: "password",
value: ""
}]
</code></pre>
<p>as you can see I have the <code>param</code> field which is equal to the input name defined in the <code>Vue</code> component.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T09:34:14.770",
"Id": "263482",
"Score": "1",
"Tags": [
"vue.js"
],
"Title": "Vue form validation"
}
|
263482
|
<p>I'm trying to replicate <code>std::array</code> but with modifications that I should put the private data member to the public so the class template <code>fixed_array</code> will be a structural type that will be qualified as a non-type template parameter.</p>
<p>My goal here is to use the string literals and brace-init list as non-type template parameters where the ISO C++ standard may forbid it, so I created a wrapper for them to call the constructor that has corresponding types.</p>
<p>From class template <code>fixed_string</code>, I inherited the base class with more specialized member functions.</p>
<p>I applied some C++ 20 features which include string literal operator template, relaxed non-type template parameters, requires clause, spaceship operator, and ranges.</p>
<p>Note: From the definition of UDL <code>operator""fs</code>, I intended to use this even though ISO warns to declare with no starting underscores because, on my IDE (Code::Blocks), the syntax highlighting will disable the string literal color once I put an underscore.</p>
<pre class="lang-cpp prettyprint-override"><code>// headers needed
#include <iterator>
#include <algorithm> // copy_n, fill_n
#include <type_traits>
#include <stdexcept> // out_of_range
#include <tuple>
#include <iostream>
#include <ranges>
#include <numeric>
// class template
template <typename T, size_t N>
struct fixed_array {
// member type alias
using value_type = T;
using size_type = size_t;
using difference_type = ptrdiff_t;
using pointer = value_type*;
using const_pointer = const value_type*;
using reference = value_type&;
using const_reference = const value_type&;
using iterator = const value_type*;
using const_iterator = const value_type*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// make underlying data public
value_type data[N];
// constructors
constexpr fixed_array() noexcept {
std::fill_n(data, N, 0);
}
constexpr fixed_array(const value_type& fill_arg) noexcept {
std::fill_n(data, N, fill_arg);
}
constexpr fixed_array(const value_type(&arg)[N]) {
std::copy_n(arg, N, data);
}
constexpr fixed_array(const std::initializer_list<value_type>& args) noexcept {
std::copy_n(args.begin(), N, data);
}
constexpr fixed_array(const fixed_array& other) : fixed_array(other.data) {}
constexpr fixed_array(fixed_array&& other) : fixed_array(std::move(other.data)) {}
// destructors
constexpr ~fixed_array() {}
// assignment
constexpr fixed_array& operator=(const fixed_array& other) {
std::copy_n(other.data, N, data);
return *this;
}
constexpr fixed_array& operator=(fixed_array&& other) {
std::copy_n(std::move(other).data, N, data);
return *this;
}
constexpr fixed_array& operator=(const value_type(&arg)[N]) {
std::copy_n(arg, N, data);
return *this;
}
constexpr fixed_array& operator=(const std::initializer_list<value_type> args) {
std::copy_n(args.begin(), N, data);
return *this;
}
// iterator access
constexpr auto begin() const noexcept { return iterator{data}; }
constexpr auto end() const noexcept { return iterator{data + N}; }
constexpr auto cbegin() const noexcept { return const_iterator{data}; }
constexpr auto cend() const noexcept { return const_iterator{data + N}; }
constexpr auto rbegin() noexcept { return reverse_iterator{data}; }
constexpr auto rend() noexcept { return reverse_iterator{data + N}; }
constexpr auto crbegin() const noexcept { return const_reverse_iterator{data}; }
constexpr auto crend() const noexcept { return const_reverse_iterator{data + N}; }
// capacity
constexpr size_type size() const noexcept { return N; }
constexpr size_type max_size() const noexcept { return N; }
// element access
constexpr reference operator[](size_type pos) { return data[pos]; }
constexpr const_reference operator[](size_type pos) const { return data[pos]; }
constexpr reference at(size_type pos) {
if (!(pos < N)) {
throw std::out_of_range("indexing request is out of range...");
} else {
return data[pos];
}
}
constexpr const_reference at(size_type pos) const {
if (!(pos < N)) {
throw std::out_of_range("indexing request is out of range...");
} else {
return data[pos];
}
}
constexpr reference front() { return data[0]; }
constexpr const_reference front() const { return data[0]; }
constexpr reference back() { return data[N - 1]; }
constexpr const_reference back() const { return data[N - 1]; }
[[nodiscard]] constexpr bool empty() const { return N == 0; }
// equality
constexpr bool operator==(const fixed_array& other) const {
return std::equal(begin(), end(), other.begin());
}
constexpr auto operator<=>(const fixed_array& other) const = default;
// operations
constexpr void fill(const value_type& value) {
std::fill_n(data, N, value);
}
constexpr void swap(fixed_array& other) noexcept(std::is_nothrow_swappable_v<value_type>) {
std::swap_ranges(begin(), end(), other.begin());
}
template <size_t I>
constexpr value_type& get() & noexcept {
return data[I];
}
template <size_t I>
constexpr value_type&& get() && noexcept {
return std::move(data[I]);
}
template <size_t I>
constexpr const value_type& get() const& noexcept {
return data[I];
}
template <size_t I>
constexpr const value_type&& get() const&& noexcept {
return std::move(data[I]);
}
};
// deduction guides for fixed_array:
template <typename T, size_t N> fixed_array(const T(&)[N]) -> fixed_array<T, N>;
template <typename... Ts> fixed_array(Ts...) -> fixed_array<std::tuple_element_t<0, std::tuple<Ts...>>, sizeof...(Ts)>;
// specializing std::get, std::tuple_size, and std::tuple_element with fixed_array:
namespace std {
template <typename T, size_t N>
struct tuple_size<fixed_array<T, N>> : integral_constant<size_t, N> {};
template <size_t I, typename T, size_t N>
struct tuple_element<I, fixed_array<T, N>> : type_identity<T> {};
using std::get;
template <size_t I, typename T, size_t N>
constexpr T& get(fixed_array<T, N>& arr) noexcept {
return arr[I];
}
template <size_t I, typename T, size_t N>
constexpr T&& get(fixed_array<T, N>&& arr) noexcept {
return std::move(arr[I]);
}
template <size_t I, typename T, size_t N>
constexpr const T& get(const fixed_array<T, N>& arr) noexcept {
return arr[I];
}
template <size_t I, typename T, size_t N>
constexpr const T&& get(const fixed_array<T, N>&& arr) noexcept {
return std::move(arr[I]);
}
namespace ranges {
template <typename T, size_t N>
inline constexpr bool enable_view<fixed_array<T, N>> = true;
}
}
// maybe static polymorphism:
template <size_t N>
struct fixed_string : fixed_array<char, N + 1> {
using fixed_array<char, N + 1>::data;
constexpr fixed_string(const char(&str)[N + 1]) noexcept
requires (std::is_array_v<decltype(str)>) {
std::copy_n(str, N + 1, data);
}
constexpr fixed_string() noexcept {
std::fill_n(data, N + 1, 0);
}
constexpr fixed_string(const char* str) noexcept {
std::copy_n(str, N + 1, data);
}
std::string to_string() const {
return data;
}
// operations
constexpr fixed_string& to_lower() {
std::transform(data, data + N, data, ::tolower);
return *this;
}
constexpr fixed_string& to_upper() {
std::transform(data, data + N, data, ::toupper);
return *this;
}
// stream insert
friend std::ostream& operator<<(std::ostream& os, fixed_string<N> str) {
os << str.data;
return os;
}
};
// deduction guide for fixed_string
template <size_t N> fixed_string(const char(&)[N]) -> fixed_string<N - 1>;
// UDL
#pragma GCC diagnostic ignored "-Wliteral-suffix"
template <fixed_string FS>
constexpr auto operator""fs() {
return fixed_string{FS};
}
#pragma GCC diagnostic warning "-Wliteral-suffix"
// function tests
template <fixed_array Arr>
constexpr auto sum() -> decltype(Arr)::value_type {
return std::accumulate(Arr.begin(), Arr.end(), 0);
}
template <fixed_string S>
void fixed_print() {
for (const auto& i : S) {
std::cout << i << ' ';
} std::cout << '\n';
}
template <fixed_array Arr1, fixed_array Arr2>
constexpr bool is_equal() requires (Arr1.size() == Arr2.size()) {
return Arr1 == Arr2;
}
template <fixed_array Arr1, fixed_array Arr2>
constexpr bool is_not_equal() requires (Arr1.size() == Arr2.size()) {
return Arr1 != Arr2;
}
template <fixed_array Arr1, fixed_array Arr2>
constexpr bool is_less_than() requires (Arr1.size() == Arr2.size()) {
return Arr1 < Arr2;
}
template <fixed_array Arr1, fixed_array Arr2>
constexpr bool is_less_than_or_equal() requires (Arr1.size() == Arr2.size()) {
return Arr1 <= Arr2;
}
template <fixed_array Arr1, fixed_array Arr2>
constexpr bool is_greater_than() requires (Arr1.size() == Arr2.size()) {
return Arr1 > Arr2;
}
template <fixed_array Arr1, fixed_array Arr2>
constexpr bool is_greater_than_or_equal() requires (Arr1.size() == Arr2.size()) {
return Arr1 >= Arr2;
}
</code></pre>
<p>Main Function:</p>
<pre class="lang-cpp prettyprint-override"><code>int main() {
// test fixed_string:
std::cout << "Chapter 1: Preliminary" << '\n';
fixed_print<"Desmond Gold">();
std::cout << "Sum: " << sum<{1, 2, 3, 4, 5}>() << '\n';
static_assert(sum<{1, 2, 3, 4, 5}>() == 15);
// prelim
int c_arr_1[] = {8, 4, 3};
auto print = [](auto x){ std::cout << x << ' '; };
// testing 1: constructors
[[maybe_unused]] fixed_array arr_1 {1, 2, 3, 4}; // #4
[[maybe_unused]] fixed_array arr_2 = {9, 4, 2, 1, 7}; // #5
[[maybe_unused]] fixed_array arr_3 { arr_1 }; // #4
[[maybe_unused]] fixed_array arr_4 { std::move(arr_2) }; // #5
[[maybe_unused]] fixed_array arr_5 = c_arr_1; // #3
// testing 2: assignments
arr_1 = arr_1;
arr_2 = std::move(arr_2);
arr_3 = {0, 1, 2, 8, 9}; // same length
arr_5 = c_arr_1;
// testing 3: iterators
std::cout << "Chapter 2: Iterators" << '\n';
std::for_each(arr_1.begin(), arr_1.end(), print); std::cout << '\n';
std::for_each(arr_2.cbegin(), arr_2.cend(), print); std::cout << '\n';
// testing 4: element access
std::cout << "Chapter 3: Element Access" << '\n';
for (decltype(arr_5)::size_type i = 0; i < arr_5.size(); i++) {
std::cout << arr_5[i] << ' ';
} std::cout << '\n';
std::cout << "Front: " << arr_1.front() << '\n'
<< "Back: " << arr_1.back() << '\n';
// testing 5: operations
std::cout << "Chapter 4: Fill Operation" << '\n';
arr_5.fill(99);
for (const auto& i : arr_5) {
std::cout << i << ' ';
} std::cout << '\n';
// testing 6: range views
std::cout << "Chapter 5: Range Views" << '\n';
auto reverse_and_filter_array = std::views::reverse | std::views::filter([](auto x){ return x > 1; });
auto transform_array = std::views::transform([](auto x){ return x * x; });
for (const auto& elem : arr_1
| reverse_and_filter_array
| transform_array) {
std::cout << elem << ' ';
} std::cout << '\n';
// testing 7: structured binding
std::cout << "Chapter 6: Structured Binding" << '\n';
[[maybe_unused]] const auto& [x_1, x_2, x_3] = arr_5;
std::cout
<< "x_1: " << x_1 << '\n'
<< "x_2: " << x_2 << '\n'
<< "x_3: " << x_3 << '\n';
std::cout << "Tuple: "
<< std::get<0>(arr_1) << ' '
<< std::get<1>(arr_1) << ' '
<< std::get<2>(arr_1) << ' '
<< std::get<3>(arr_1) << '\n';
// testing 8: equality and lexicographical comparison (must be in the same length)
std::cout << std::boolalpha << "Chapter 7: Comparisons" << '\n';
std::cout
<< "Is equal? [1, 2, 3] and [1, 2, 3]: " << is_equal<{1, 2, 3}, {1, 2, 3}>() << '\n'
<< "Is not equal? [5, 5, 5] and [5, 4, 5]: " << is_not_equal<{5, 5, 5}, {5, 4, 5}>() << '\n'
<< "Is less than? [5, 4, 4] and [4, 4, 4]: " << is_less_than<{5, 4, 4}, {4, 4, 4}>() << '\n'
<< "Is less than or equal? [7, 6, 3] and [7, 7, 7]: " << is_less_than_or_equal<{7, 6, 3}, {7, 7, 7}>() << '\n'
<< "Is greater than? [6, 5, 1] and [1, 5, 6]: " << is_greater_than<{6, 5, 1}, {1, 5, 6}>() << '\n'
<< "Is greater than or equal? [19, 10, 17] and [14, 10, 13]: " << is_greater_than_or_equal<{19, 10, 17}, {14, 10, 13}>() << '\n';
// testing 9: fixed strings
auto string_1 = "First String"fs;
std::cout << "Chapter 8: Fixed Strings" << '\n'
<< string_1 << '\n';
static_assert("Hello"fs == "Hello"fs);
return 0;
}
</code></pre>
<p>Output:</p>
<pre><code>Chapter 1: Preliminary
D e s m o n d G o l d
Sum: 15
Chapter 2: Iterators
1 2 3 4
9 4 2 1 7
Chapter 3: Element Access
8 4 3
Front: 1
Back: 4
Chapter 4: Fill Operation
99 99 99
Chapter 5: Range Views
16 9 4
Chapter 6: Structured Binding
x_1: 99
x_2: 99
x_3: 99
Tuple: 1 2 3 4
Chapter 7: Comparisons
Is equal? [1, 2, 3] and [1, 2, 3]: true
Is not equal? [5, 5, 5] and [5, 4, 5]: true
Is less than? [5, 4, 4] and [4, 4, 4]: false
Is less than or equal? [7, 6, 3] and [7, 7, 7]: true
Is greater than? [6, 5, 1] and [1, 5, 6]: true
Is greater than or equal? [19, 10, 17] and [14, 10, 13]: true
Chapter 8: Fixed Strings
First String
</code></pre>
<p>So far, there are exactly 0 compilation errors (only in GCC, except for Clang (because it would reject my code using no-underscore UDL, brace-init-list from non-type template parameter, and some ranges-related errors. So it may lead to non-portable code), and no runtime errors with passing static assertions.</p>
<p>Is there anything I could improve?</p>
|
[] |
[
{
"body": "<p>Mainly this is pretty nice :)</p>\n<hr />\n<pre><code>constexpr fixed_array(const std::initializer_list<value_type>& args) noexcept {\n std::copy_n(args.begin(), N, data);\n}\n</code></pre>\n<p>We definitely need to check that the initializer_list is the correct size, and throw if it isn't.</p>\n<p>Note that initializer lists are lightweight (probably just a pair of pointers, or a pointer and a size), so can be passed by value, instead of <code>const&</code>.</p>\n<hr />\n<pre><code>constexpr fixed_array(const fixed_array& other) : fixed_array(other.data) {}\nconstexpr fixed_array(fixed_array&& other) : fixed_array(std::move(other.data)) {}\n\n// destructors\nconstexpr ~fixed_array() {}\n</code></pre>\n<p>These guys can all be <code>= default;</code></p>\n<pre><code>constexpr fixed_array& operator=(const fixed_array& other) {\n std::copy_n(other.data, N, data);\n return *this;\n}\n\nconstexpr fixed_array& operator=(fixed_array&& other) {\n std::copy_n(std::move(other).data, N, data);\n return *this;\n}\n</code></pre>\n<p>As can these.</p>\n<hr />\n<pre><code>constexpr bool operator==(const fixed_array& other) const {\n return std::equal(begin(), end(), other.begin());\n}\n</code></pre>\n<p>I believe the spaceship operator will define this for us.</p>\n<hr />\n<pre><code>namespace std {\n ...\n}\n</code></pre>\n<p>I <em>think</em> that specializing <code>std::tuple_size</code> and <code>std::tuple_element</code> in the <code>std</code> namespace is ok, <a href=\"https://stackoverflow.com/questions/16173902/enable-stdget-support-on-class\">but specializing <code>std::get</code> is technically not ok</a>.</p>\n<p>For <code>std::get</code>, we should define the <code>get</code> functions in the same namespace as the <code>fixed_array</code> class, so that they work correctly with ADL. i.e. the user can do:</p>\n<pre><code>using std::get;\nget<0>(a); // will find and use the `get` we defined in the same namespace if `a` is our fixed_array type, or std::get if `a` is a std type\n</code></pre>\n<hr />\n<pre><code>constexpr fixed_string(const char(&str)[N + 1]) noexcept\nrequires (std::is_array_v<decltype(str)>) {\n std::copy_n(str, N + 1, data);\n}\n</code></pre>\n<p>Hmm... I'm guessing that the <code>N + 1</code> size of <code>fixed_string</code> is so that we can always have a terminating null character. Here we're copying from a char array of N + 1 chars, with no guarantee that the last char is null.</p>\n<p>Perhaps we should only accept a size N array? (And manually add the null character).</p>\n<p>It might make sense to accept smaller array sizes too? (And fill the rest of the array with nulls).</p>\n<p>We probably need to think about other assignment operations here too, and make sure that we have a trailing null.</p>\n<p>Consider adding a <code>.c_str()</code> member too.</p>\n<p>I guess exactly what you do here depends on the intent. Is the class only for strings of size N exactly, or should it be for any string up to size N?</p>\n<hr />\n<pre><code>constexpr fixed_string(const char* str) noexcept {\n std::copy_n(str, N + 1, data);\n}\n</code></pre>\n<p>Eeep! We have no guarantee that <code>str</code> is long enough. We need to check and throw, or use something like <code>strncpy</code>.</p>\n<hr />\n<pre><code>constexpr fixed_string& to_lower() {\n std::transform(data, data + N, data, ::tolower);\n return *this;\n}\n</code></pre>\n<p>Technically, <a href=\"https://en.cppreference.com/w/cpp/string/byte/tolower\" rel=\"nofollow noreferrer\">we have to cast our chars to <code>unsigned char</code> when using <code>tolower</code></a> or <code>toupper</code>.</p>\n<p>Also, technically, these functions are in the <code>std::</code> namespace.</p>\n<hr />\n<pre><code>friend std::ostream& operator<<(std::ostream& os, fixed_string<N> str) {\n os << str.data;\n return os;\n}\n</code></pre>\n<p>We could pass the <code>fixed_string</code> by <code>const&</code> instead of by value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T09:02:39.943",
"Id": "263507",
"ParentId": "263486",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263507",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T13:24:15.437",
"Id": "263486",
"Score": "2",
"Tags": [
"c++",
"template-meta-programming",
"c++20"
],
"Title": "Creating a structural type array wrapper to be qualified as non-type template parameter C++"
}
|
263486
|
<p>I want to compare 2 images using <code>numpy</code>. This is what I have got so far.
One of the outputs should be a white image with black pixels where pixels are different.</p>
<p>I am sure it's possible to make it more efficient by better use of numpy, e.g. the <code>for</code> loop can be avoided. Or maybe there is a function/package that has implemented something similar already?</p>
<pre><code> import gc
import PIL
import numpy as np
def compare_images(image_to_test_filename, image_benchmark_filename):
print('comparing', image_to_test_filename, 'and', image_benchmark_filename)
image_benchmark = plt.imread(image_benchmark_filename)
image_to_test = plt.imread(image_to_test_filename)
assert image_to_test.shape[0] == image_benchmark.shape[0] and image_to_test.shape[1] == image_benchmark.shape[1]
diff_pixel = np.array([0, 0, 0], np.uint8)
true_array = np.array([True, True, True, True])
diff_black_white = np.zeros([image_benchmark.shape[0], image_benchmark.shape[1], 3], dtype=np.uint8) + 255
is_close_pixel_by_pixel = np.isclose(image_to_test, image_benchmark)
nb_different_rows = 0
for r, row in enumerate(is_close_pixel_by_pixel):
diff_indices = [c for c, elem in enumerate(row) if not np.all(elem == true_array)]
if len(diff_indices):
diff_black_white[r][diff_indices] = diff_pixel
nb_different_rows += 1
dist = np.linalg.norm(image_to_test - image_benchmark) / (image_to_test.shape[0] * image_to_test.shape[1])
if nb_different_rows > 0:
print("IS DIFFERERENT! THE DIFFERENCE IS (% OF ALL PIXELS)", dist * 100)
im = PIL.Image.fromarray(diff_black_white)
im.save(image_to_test_filename+'_diff.png')
del im
del image_benchmark
del image_to_test
del diff_black_white
gc.collect()
return dist, None
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T15:18:31.050",
"Id": "520170",
"Score": "0",
"body": "@Reinderien done!"
}
] |
[
{
"body": "<p>First, this of course depends on your definition of different. I believe right now that your comparison is far too strict, given the defaults for <code>isclose</code>. I did a trivial modification of a .jpg, and with one decode/encode pass it still produced 6% of pixels with an RGB distance of more than 20. <code>isclose</code> applies both a relative and absolute tolerance, but it's probable that for your purposes absolute-only is simpler.</p>\n<p>I find f-strings a more natural form of string formatting because the in-line field expressions remove any need of your eyes to scan back and forth between field placeholder and expression. This does not impact performance. Also note the use of <code>%</code> in this context removes the need to divide by 100.</p>\n<p>PEP484 type hinting also does not impact performance, but makes the code more legible and verifiable.</p>\n<p>Note that it's "almost never" appropriate to <code>del</code> and <code>gc</code> yourself. The garbage collector is there for a reason, and in the vast, vast majority of cases, will act reasonably to free nonreferenced memory without you having to intervene. The one thing you should be doing here that you aren't is moving the images to a <code>with</code> for context management, which will guarantee resource cleanup on scope exit.</p>\n<p>This problem is fully vectorizable so should see no explicit loops at all. Just calculate a black-and-white distance from an absolute threshold in one pass. Your original implementation was taking longer to execute than I had patience for, but the following suggestion executes in less than a second:</p>\n<pre><code>import numpy as np\nfrom PIL import Image\nfrom matplotlib.pyplot import imread\n\n\n# Maximum allowable Frobenius distance in RGB space\nEPSILON = 20\n\n\ndef compare_images(\n image_to_test_filename: str,\n image_benchmark_filename: str,\n) -> float:\n print(f'comparing {image_to_test_filename} and {image_benchmark_filename}')\n\n image_benchmark = imread(image_benchmark_filename)\n image_to_test = imread(image_to_test_filename)\n assert image_to_test.shape == image_benchmark.shape\n\n diff_black_white = (\n np.linalg.norm(image_to_test - image_benchmark, axis=2) > EPSILON\n ).astype(np.uint8)\n n_different = np.sum(diff_black_white)\n\n if n_different > 0:\n diff_fraction = n_different / image_benchmark.size\n print(f'IS DIFFERERENT! THE DIFFERENCE OF ALL PIXELS IS {diff_fraction:.2%}')\n im = Image.fromarray(diff_black_white * 255)\n im.save(f'{image_to_test_filename}_diff.png')\n\n dist = np.linalg.norm(image_to_test - image_benchmark) / image_benchmark.size\n return dist\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T10:48:55.167",
"Id": "520213",
"Score": "1",
"body": "Thanks! I have found one more actually: image_benchmark.shape[0] * image_benchmark.shape[1] out to be image_benchmark.size, right? (this is 1). )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T10:50:10.400",
"Id": "520214",
"Score": "0",
"body": "2. Could I ask why you prefer `print(f'comparing {i1} and {i2}')` over `print('comparing', i1, 'and', i2)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T10:51:04.847",
"Id": "520215",
"Score": "0",
"body": "3. What would be the benefit of typing the inputs - is it the performance improvement? Is it significant in this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T10:52:00.803",
"Id": "520216",
"Score": "0",
"body": "np.linalg.norm along axis 2 is brilliant, I did not know it can be used like this, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T13:12:04.693",
"Id": "520228",
"Score": "1",
"body": "Yes, `size` is better for this purpose; edited for the other points."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:31:02.993",
"Id": "263497",
"ParentId": "263487",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263497",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T14:30:43.343",
"Id": "263487",
"Score": "2",
"Tags": [
"python",
"numpy"
],
"Title": "Efficient Comparison Of Two Images Using Numpy"
}
|
263487
|
<p>I tried <a href="https://stackoverflow.com/questions/48446708/securing-spring-boot-api-with-api-key-and-secret">https://stackoverflow.com/questions/48446708/securing-spring-boot-api-with-api-key-and-secret</a>, but that didn't work for me (filter did nothing). Since I couldn't find any useful tutorial with API keys and Spring Boot I wrote my own filter:</p>
<pre><code>@Component
public class ApiKeyRequestFilter extends GenericFilterBean {
@Value("${espd.http.auth-token-header-name}")
private String principalRequestHeader;
@Value("${espd.http.auth-token}")
private String principalRequestValue;
private void returnNoAPIKeyError(ServletResponse response) throws IOException {
HttpServletResponse resp = (HttpServletResponse) response;
String error = "Nonexistent or invalid API KEY";
resp.reset();
resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentLength(error .length());
response.getWriter().write(error);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String apiKeyHeaderValue = httpRequest.getHeader(principalRequestHeader);
if(apiKeyHeaderValue != null) {
if(apiKeyHeaderValue.equals(principalRequestValue)) {
chain.doFilter(request, response);
}
else {
returnNoAPIKeyError(response);
}
}
else {
returnNoAPIKeyError(response);
}
}
}
</code></pre>
<p>Is it safe? What can be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T06:29:33.693",
"Id": "520206",
"Score": "1",
"body": "HI @TristanK. couldn't you just do `httpRequest.getHeaders(principalRequestHeader)` rather than looping over all of them? - see https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getHeaders(java.lang.String)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T09:45:27.123",
"Id": "520211",
"Score": "0",
"body": "oh sure thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T11:23:36.050",
"Id": "520284",
"Score": "1",
"body": "Why not `if(principalRequestValue.equals(apiKeyHeaderValue))` ? So that you combine the two ifs in one (and remove the nesting) because `equals` will take care of the null for you."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T15:21:47.827",
"Id": "263488",
"Score": "0",
"Tags": [
"java",
"security",
"spring",
"spring-mvc"
],
"Title": "Spring Boot API Key Filter"
}
|
263488
|
<p>I'm trying to write a function that tries to read a config and if fails, creates a new one and writes to the file "settings.ini". This feels really chunky and not particularly concise. Is this the supposed way of reading a configparser file?</p>
<pre><code>from configparser import ConfigParser
def getSettings(self):
try:
with open('settings.ini') as f:
return config.read_file(f)
except:
config['DEFAULT'] = {'Host': '127.0.0.1',
'Port': '5822'}
return config['DEFAULT']
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:07:13.963",
"Id": "520186",
"Score": "0",
"body": "I think admins will remove the question; it doesn't seem belong here. Meanwhile this is your app and your decision, but: 1) it will be very strange to have overwritten config after reading attempt, even if it was wrong; 2) there can be other exceptions, not only IOError; 3) second reading may fail as well. \nSo just write an error into log and return default config if reading failed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:41:07.010",
"Id": "520191",
"Score": "0",
"body": "Thank you for your advice; it's quite an hassle trying out new things. I will just stick with json file I guess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:49:46.040",
"Id": "520194",
"Score": "1",
"body": "I don't see anything wrong with the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T19:50:53.520",
"Id": "520195",
"Score": "4",
"body": "Other than - you need to include your definition of `config`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T08:47:05.980",
"Id": "520207",
"Score": "2",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T12:01:33.347",
"Id": "520223",
"Score": "3",
"body": "If the code is working then the question is on topic as long as the definition of config is added and the title is modified as @TobySpeight indicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T09:15:31.997",
"Id": "520554",
"Score": "0",
"body": "Thank you all. What exactly is the \"definition of config\" mentioned above?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T11:33:24.807",
"Id": "520556",
"Score": "1",
"body": "Now you have removed even more code, while there was already not enough for a review. The definition of config is where you define the configuration. What does the configuration look like? Just copy the configuration file into the question, after stripping it from sensitive data like passwords and API keys, and please provide a usage example. How are you actually using this code in your application? If there's no application yet, it's too early in the process for a review."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T18:36:33.147",
"Id": "263493",
"Score": "2",
"Tags": [
"python"
],
"Title": "Should i use a try catch statement for reading a configparser file when loading a setting?"
}
|
263493
|
<p>In my application, I only show users their own data. For that, I need to know in the backend, which user is requesting data. I use the username for that and therefore, I need to send the username as part of the GET request.</p>
<p>The method in question, located in MVC-controller:</p>
<pre><code>public async Task<IActionResult> Index()
{
////Here, I pass username. ApiClient is a HttpClient and has a configured BaseAddress.
var response = await ApiHelper.ApiClient.GetAsync("username?username=" + User.Identity.Name);
var result = await response.Content.ReadAsStringAsync();
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
List<MatchViewModel> match = JsonSerializer.Deserialize<List<MatchViewModel>>(result, options);
return View(match);
}
</code></pre>
<p>Points of interest for feedback:</p>
<ul>
<li>Is this a good/safe way to communicate with endpoint? Couldn't a hostile party just change the <code>username</code> parameter by calling the API directly, and get another user's data?</li>
<li>Does it make the method for confusing, that I instantiate a variable of <code>JsonSerializerOptions</code>?</li>
</ul>
<p>Whatever feedback, advice or critique you might have, I am interested. Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T08:48:33.850",
"Id": "520208",
"Score": "1",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T08:53:02.540",
"Id": "520209",
"Score": "0",
"body": "@TobySpeight Thanks for the heads up, I've tried to improve the title and a few points of interest for feedback. And thanks :)"
}
] |
[
{
"body": "<p>Few tips:</p>\n<ul>\n<li>respect <code>IDisposable</code> objects, apply <code>using</code> where necessary.</li>\n<li>if you encapsulating HTTP API logic into a helper class, do it completely</li>\n<li>exposing <code>HttpClient</code> outside isn't a good idea, what if you'll decide to change <code>HttpClient</code> for something else, either <code>HttpClientFactory</code> or something.</li>\n<li><code>JsonSerializerOptions</code> can be instantiated once and reused.</li>\n</ul>\n<p>Property getter/setter might help but why not expose the method that does exactly what needed? It would make the usage simpler like:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task<IActionResult> Index()\n{\n var query = new Dictionary<string, string>\n {\n ["username"] = User.Identity.Name\n };\n List<MatchViewModel> match = await ApiHelper.GetJsonAsync<List<MatchViewModel>>("username", query);\n return View(match);\n}\n</code></pre>\n<p>The example</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class ApiHelper\n{\n private static readonly HttpClient _client = new HttpClient();\n private static readonly JsonSerializerOptions _options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };\n\n public static async Task<T> GetJsonAsync<T>(string method, IEnumerable<KeyValuePair<string, string>> query)\n {\n string queryString = new FormUrlEncodedContent(query).ReadAsStringAsync().Result;\n using var response = await _client.GetAsync($"{method}?{queryString}", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);\n using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);\n return await JsonSerializer.DeserializeAsync<T>(stream, _options).ConfigureAwait(false);\n }\n}\n</code></pre>\n<p>The method can be simplified using <code>GetFromJsonAsync</code> extension.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static async Task<T> GetJsonAsync<T>(string method, IEnumerable<KeyValuePair<string, string>> query)\n{\n string queryString = new FormUrlEncodedContent(query).ReadAsStringAsync().Result;\n return await _client.GetFromJsonAsync<T>($"{method}?{queryString}", _options).ConfigureAwait(false);\n}\n</code></pre>\n<p>Finally, as here we have only one and the last <code>await</code>, then <code>async</code> state machine can be optimized out. There's no sense to launch the State Machine that has only one state, right? But be careful with this kind of optimization. Not sure - don't use. For example, it can break the method when the <code>await</code> is inside of the <code>using</code> or <code>try-catch</code> clause.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static Task<T> GetJsonAsync<T>(string method, IEnumerable<KeyValuePair<string, string>> query)\n{\n string queryString = new FormUrlEncodedContent(query).ReadAsStringAsync().Result;\n return _client.GetFromJsonAsync<T>($"{method}?{queryString}", _options);\n}\n</code></pre>\n<p>Converting key-value pairs to URL-encoded query looks a bit tricky but <code>new FormUrlEncodedContent(query).ReadAsStringAsync().Result;</code> does exactly that thing.</p>\n<p>I know that <code>ReadAsStringAsync</code> is <code>async</code> method but I know that content is already inside as I put the source directly to the constructor. Then the <code>ReadAsStringAsync</code> is completed synchronously here, then to save some resources I call <code>.Result</code> for the already completed <code>Task</code>, which isn't a bad practice. Only calling <code>.Result</code> for a not completed <code>Task</code> may lead to a problem with locked/deadlocked threads.</p>\n<p>Never use <code>.Result</code> or <code>.Wait()</code> or <code>.GetAwaiter().GetResult()</code> when you're not sure if the <code>Task</code> was already completed, use <code>await</code> instead (or always use <code>await</code>).</p>\n<p>About <code>ConfigureAwait(false)</code> you may read <a href=\"https://devblogs.microsoft.com/dotnet/configureawait-faq/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://blog.stephencleary.com/2012/02/async-and-await.html#avoiding-context\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T11:46:14.893",
"Id": "520221",
"Score": "1",
"body": "Wow, that was a lot of great points and examples. Thank you so much for such elaborate and great feedback, really appreciate it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T11:19:06.887",
"Id": "263509",
"ParentId": "263498",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263509",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T21:07:42.000",
"Id": "263498",
"Score": "1",
"Tags": [
"c#",
"mvc",
"asp.net-core-webapi",
".net-5"
],
"Title": "Best practices in regards to pass and deserialize data, when calling an API endpoint from a MVC-project?"
}
|
263498
|
<pre><code>class Person {
constructor(firstName, lastName, email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
returnObject() {
return { "firstName": this.firstName, "lastName": this.lastName, "email": this.email };
}
json() {
return JSON.stringify(this.returnObject());
}
}
</code></pre>
<p>Is this node.js class for returning a json well-written? This is a model class, and it's going to be used for validation and returning a json for a particular API endpoint. I am wondering if there's any improvement I can make or anything I should fix.</p>
|
[] |
[
{
"body": "<p>I'd get rid of the <code>json</code> function. Having it means you have to remember to use <code>somePerson.json()</code> instead of the usual <code>JSON.stringify(somePerson)</code>. If you need to control the JSON output to make sure your API stays the same even as your class changes, you can do that using a <code>toJSON</code> function - <code>JSON.stringify</code> will respect such a function if it exists. And you have a perfectly fine <code>toJSON</code> function already - you just called it <code>returnObject</code> instead.</p>\n<p>Though speaking of <code>returnObject</code>, it doesn't seem very useful in its current state. You take an object, and return an object that contain all the first object's fields. At that point, why not just return the first object itself? And once you have a function that essentially just reads <code>return this</code>, why have that function at all? You can't call the function without already having access to its return value anyway, right?<br />\nGranted, having it <em>does</em> serve to freeze the output of <code>json</code> (or, if you were to use this function as your <code>toJSON</code>, the output of <code>JSON.stringify</code>), which might help you avoid accidentally changing your API.</p>\n<p>All in all, I'd probably suggest simplifying to</p>\n<pre><code>class Person {\n constructor(firstName, lastName, email) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.email = email;\n }\n}\n</code></pre>\n<p>though if you want to be <em>sure</em> you don't accidentally change your JSON output by changing the class (and you don't trust your test to notice if you do) you might prefer</p>\n<pre><code>class Person {\n\n constructor(firstName, lastName, email) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.email = email;\n }\n\n\n toJSON() {\n return {\n "firstName": this.firstName,\n "lastName": this.lastName,\n "email": this.email\n };\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T06:55:49.473",
"Id": "263503",
"ParentId": "263502",
"Score": "5"
}
},
{
"body": "<p>It is kinda useless class.</p>\n<p>Why not just</p>\n<pre><code>function createPerson(firstName, lastName, email)\n{\n return { firstName, lastName, email }\n}\n</code></pre>\n<p>It is immediately json serializable, no need for a toJSON method.\nJust serialize it for the response</p>\n<pre><code>response.body = JSON.stringify(person)\n</code></pre>\n<p>unless a framework is already handling that for you, ie:</p>\n<pre><code>response.json = person\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T13:14:31.793",
"Id": "520289",
"Score": "0",
"body": "Why useless? Wouldn’t it make sense to get some typesafety? Like for instance if there is a function somewhere that should only work for objects of type Person (instead of having to validate the object in said function)..?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T18:39:58.407",
"Id": "520331",
"Score": "0",
"body": "@dingalapadum Any validations go into the createPerson function before the return statement. We're talking about node.js aka javascript here. Even if you have a named class Person, there is no guarantee that noone modifies it after its creation. If you want typesafety, write in typescript, then the Person is just a interface and you just trust the compiler that it detects any misuse as long as your code is properly typed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T22:02:08.673",
"Id": "520347",
"Score": "0",
"body": "Right. Sorry, I missed to mention that I was assuming typescript in the first place."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T06:59:52.533",
"Id": "263504",
"ParentId": "263502",
"Score": "4"
}
},
{
"body": "<p>"First name" and "Last name" can be problematic in code, as not everyone has two or more names (I know at least one person with just a single-word name, for example), and even for those who do, there's little utility in knowing their writing order, other than to reassemble back into the full name.</p>\n<p>Without some additional context, we don't know if either of those fields is a personal name, a family name, a patronymic or something else.</p>\n<p>It's generally better to store a single "name" field.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T10:39:25.307",
"Id": "263543",
"ParentId": "263502",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263503",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T04:06:04.823",
"Id": "263502",
"Score": "1",
"Tags": [
"node.js"
],
"Title": "Is this node.js class returning a json"
}
|
263502
|
<p><strong>TL;DR</strong> How to better avoid some of the colors in the gradient looking like brighter/darker lines and make them blend in with neighboring colors. Not too concerned with performance/color accuracy but don't like how my algorithm muddies up colors at higher blend settings.</p>
<p>Working example: <a href="https://www.shadertoy.com/view/ftB3Dc" rel="nofollow noreferrer">https://www.shadertoy.com/view/ftB3Dc</a></p>
<p><strong>Longer explanation</strong></p>
<p>I initially wrote a straight-forward gradient algorithm which linearly transitions between colors. This works fine however there was one aspect that I didn't like about the result: the points in the gradient where there is just the pure color stood out too much.</p>
<p>For example, on the image below the white color in the middle looks like a bright line - I would like to somehow soften this - going for aesthetics over color accuracy.</p>
<p><a href="https://i.stack.imgur.com/2wLOq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2wLOq.png" alt="enter image description here" /></a></p>
<p><strong>Idea behind algorithm attempt to smooth out "peaks"</strong></p>
<p>The simple linear case, assuming 2 colors, can be represented as a graph with the proportion of color 1 represented by a straight line going from (0, 1) to (1, 0) [y = 1 - x] and another one (color 2) going from (0, 0) to (1, 1) [y = x]. My idea is to limit the lowest and highest points, so that for example the lines become (0, 0.8) to (1, 0.1) and (0, 0.1) to (1, 0.8) and hence there is never just the single color shown. The top boundary is limited at 1 - (2 * bottom) because when there are more than 2 colors, the middle colors will have 2 neighbors.</p>
<p>The algorithm and resulting gradients are below. Even with high proportions of neighboring colors mixed in, I still think the "lines" (light red near the top, dark purple in the middle and light green near the bottom on the right sample) are too visible (this had an input of 10 colors, which my algorithm unfortunately also muddies up):</p>
<p><a href="https://i.stack.imgur.com/DiFQn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DiFQn.png" alt="enter image description here" /></a><a href="https://i.stack.imgur.com/8Pv41.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Pv41.png" alt="enter image description here" /></a></p>
<p>Is there a better approach to blur the boundaries? I thought about using a quadratic/curved function, but it seems like that will just lead to an even wider plateau, or a narrow but sharp peak depending on which way it's facing.</p>
<pre><code>#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 iResolution;
//input - array of colors
uniform vec3 iColors[10];
//input - actual number of colors in the array
uniform int iNumColors;
void main(void) {
// x, y co-ordinates, 0 to 1
vec2 uv = gl_FragCoord.xy / iResolution.xy;
// flip y axis so first color is on top
uv.y = 1.0 - uv.y;
float transparency = 1.0;
//if only one color, return uniform color
if (iNumColors == 1) {
gl_FragColor = vec4(iColors[0], transparency);
return;
}
// init to black - rgb channels 0 to 1
vec3 color = vec3(0.);
float colorWidth = 1.0 / float(iNumColors - 1);
for (int i = 0; i < iNumColors; i++) {
// location of "peak" of current color
float midPoint = float(i) * colorWidth;
float colorValue;
float overlap = 0.25;
float top = 1. - (overlap * 2.);
float bottom = overlap;
float height = top - bottom;
float gradient = height / colorWidth;
float yOffset;
if (uv.y >= midPoint) {
gradient *= -1.0;
yOffset = top + (height * float(i));
} else {
yOffset = bottom - (height * float(i - 1));
}
colorValue = yOffset + (gradient * uv.y);
color += iColors[i] * max(0., colorValue);
}
gl_FragColor = vec4(color, transparency);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T12:12:02.250",
"Id": "520224",
"Score": "0",
"body": "What programming language are you using? Where is the definition for vec3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T18:35:48.767",
"Id": "520241",
"Score": "0",
"body": "@pacmaninbw It's an openGL fragment shader. Here is a running example: https://www.shadertoy.com/view/ftB3Dc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T18:37:46.960",
"Id": "520242",
"Score": "0",
"body": "@pacmaninbw vec3 is a vector of 3 floats. I'm using it for rgb values. There are some shorthand initializers, vec3(0.0) is the same as vec3(0.0, 0.0, 0.0)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T18:50:06.410",
"Id": "520244",
"Score": "1",
"body": "From an internet search, `OpenGL is a C library, which means that it's made with and for C, so of course it works with C. The reason why it also works with C++ is because C++ is actually nothing else than C with some things added so any C code is also valid in C++. ` Please add C to your tags. Please also add any the #includes for the header files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T10:20:09.527",
"Id": "520276",
"Score": "0",
"body": "Looks like C, but not C: is `void main()` a fragment shader thing? Also wondering what's in those `vec3` values - are they YUV pixel data? Or perhaps RGB? I'd avoid RGB because it gives horrible muddy blending."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T10:22:08.057",
"Id": "520277",
"Score": "0",
"body": "@TobySpeight I was advised by previous poster to add C category. vec3 contains RGB but may be I should look into a different representation if it gives better blends."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T10:25:51.667",
"Id": "520279",
"Score": "1",
"body": "Actually, I think that [tag:glsl] is more correct than [tag:c] for this question (though I'm pretty ignoring in OpenGL, so don't trust me too much!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T10:32:10.613",
"Id": "520280",
"Score": "0",
"body": "s/ignoring/ignorant/"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T08:48:59.743",
"Id": "263506",
"Score": "0",
"Tags": [
"algorithm",
"opengl",
"glsl",
"color"
],
"Title": "\"Smoothing\" colors in mutliple-color gradient in fragment shader"
}
|
263506
|
<p>I'd like to plot an animation of <a href="https://en.wikipedia.org/wiki/Lissajous_curve" rel="nofollow noreferrer">Lissajous curves</a> using Python and matplotlib's <code>animate</code> library. I really do not have a lot of experience with Python, so rather than performance increasements, I'm looking for best practices to improve (and/or shorten) my code.</p>
<p>The following code produces a <code>.gif</code> file when evaluated as a <code>jupyter-lab</code> cell:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.animation import PillowWriter
x_data = []
y_data = []
max_range = 1.2
f1 = 3 # sets the frequency for the horizontal motion
f2 = 5 # sets the frequency for the vertical motion
d1 = 0.0 # sets the phase shift for the horizontal motion
d2 = 0.5 # sets the phase shift for the vertical motion
delta1 = d1 * np.pi # I define the phase shift like this in order to use
delta2 = d2 * np.pi # ...d1 and d2 in the export file name
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(4,4), gridspec_kw={'width_ratios': [6, 1], 'height_ratios': [1, 6]})
for i in [ax1, ax2, ax3, ax4]:
i.set_yticklabels([]) # in order to remove the ticks and tick labels
i.set_xticklabels([])
i.set_xticks([])
i.set_yticks([])
i.set_xlim(-max_range, max_range)
i.set_ylim(-max_range, max_range)
ax2.set_visible(False)
line, = ax3.plot(0, 0) # line plot in the lower left
line2 = ax3.scatter(0, 0) # moving dot in the lower left
linex = ax1.scatter(0, 0) # moving dot on top
liney = ax4.scatter(0, 0) # moving dot on the right
def animation_frame(i):
ax1.clear() # I tried to put this in a loop like this:
ax1.set_yticklabels([]) # for i in [ax1,ax3,ax4]:
ax1.set_xticklabels([]) # i.clear()
ax1.set_xticks([]) # (... etc.)
ax1.set_yticks([]) # but this didn't work
ax3.clear()
ax3.set_yticklabels([])
ax3.set_xticklabels([])
ax3.set_xticks([])
ax3.set_yticks([])
ax4.clear()
ax4.set_yticklabels([])
ax4.set_xticklabels([])
ax4.set_xticks([])
ax4.set_yticks([])
ax1.set_xlim(-max_range, max_range) # after ax.clear() I apparently have to re-set these
ax3.set_xlim(-max_range, max_range)
ax3.set_ylim(-max_range, max_range)
ax4.set_ylim(-max_range, max_range)
x_data.append(np.sin(i * f1 + delta1)) # for the line plot
y_data.append(np.sin(i * f2 + delta2))
x_inst = np.sin(i * f1 + delta1) # for the scatter plot
y_inst = np.sin(i * f2 + delta2)
line, = ax3.plot(x_data, y_data)
line2 = ax3.scatter(x_inst, y_inst)
linex = ax1.scatter(x_inst, 0)
liney = ax4.scatter(0, y_inst)
fig.canvas.draw()
transFigure = fig.transFigure.inverted() # in order to draw over 2 subplots
coord1 = transFigure.transform(ax1.transData.transform([x_inst, 0]))
coord2 = transFigure.transform(ax3.transData.transform([x_inst, y_inst]))
my_line1 = matplotlib.lines.Line2D((coord1[0],coord2[0]),(coord1[1],coord2[1]), transform=fig.transFigure, linewidth=1, c='gray', alpha=0.5)
coord1 = transFigure.transform(ax3.transData.transform([x_inst, y_inst]))
coord2 = transFigure.transform(ax4.transData.transform([0, y_inst]))
my_line2 = matplotlib.lines.Line2D((coord1[0],coord2[0]),(coord1[1],coord2[1]), transform=fig.transFigure, linewidth=1, c='gray', alpha=0.5)
fig.lines = my_line1, my_line2, # moving vertical and horizontal lines
return line, line2, linex, liney
animation = FuncAnimation(fig, func=animation_frame, frames=np.linspace(0, 4*np.pi, num=800, endpoint=True), interval=1000)
animation.save('lissajous_{0}_{1}_{2:.2g}_{3:.2g}.gif'.format(f1,f2,d1,d2), writer='pillow', fps=50, dpi=200)
# This takes quite long, but since I'd like to have a smooth, slow animation,
# ...I'm willing to accept a longer execution time.
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T11:41:36.600",
"Id": "263510",
"Score": "4",
"Tags": [
"python",
"animation",
"matplotlib",
"jupyter"
],
"Title": "Animating Lissajous curves with Python and matplotlib's animation library"
}
|
263510
|
<p>Basically I made this completely useless program that generates triangles inside triangles. Its not perfect yet but my question is about the structure. I am generally happy with it but I want to know if it could have been better. There are six files and here they are.</p>
<p>main.cpp</p>
<pre><code>#define OLC_PGE_APPLICATION
//Link to pixel game engine header file
//https://github.com/OneLoneCoder/olcPixelGameEngine/blob/master/olcPixelGameEngine.h
#include "pixelGameEngine.h"
#include "triangleProcessor.h"
class TriInsideTri : public olc::PixelGameEngine
{
public:
TriInsideTri(int sw, int sh) :
sw(sw), sh(sh)
{
sAppName = "TriInsideTri";
}
private:
int sw;
int sh;
TriangleProcessor triangleProcessor{ sw, sh };
public:
bool OnUserCreate() override
{
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
World::DragToChangeOffset(this);
World::WSToChangeScale(this);
triangleProcessor.Run(this);
triangleProcessor.Render(this);
return true;
}
};
int main()
{
int screenWidth = 600;
int screenHeight = 600;
int pixelSize = 1;
TriInsideTri tritnsidetri{ screenWidth / pixelSize, screenHeight / pixelSize };
if (tritnsidetri.Construct(screenWidth / pixelSize, screenHeight / pixelSize,
pixelSize, pixelSize))
{
tritnsidetri.Start();
}
}
</code></pre>
<p>Triangle.h</p>
<pre><code>#pragma once
#include "pixelGameEngine.h"
class Triangle
{
public:
Triangle() = default;
Triangle(olc::vf2d p1, olc::vf2d p2, olc::vf2d p3):
p1(p1), p2(p2), p3(p3)
{
}
private:
static constexpr float oneFourth = 0.25f;
static constexpr float half = 0.50f;
static constexpr float threeFourth = 0.75f;
private:
static olc::vf2d Lerp(const olc::vf2d& p1, const olc::vf2d& p2, const float alpha) noexcept
{
return p1 + (p2 - p1) * alpha;
}
public:
//Inner triangles for flat tops are generated differently
//to flat bottoms.
bool flatTop = false;
public:
//First and last are not Used. Just for messing around
//to make wierd triangles
//static olc::vf2d First(const olc::vf2d& p1, const olc::vf2d& p2) noexcept
//{
// return Lerp(p1, p2, oneFourth);
//}
static olc::vf2d Mid(const olc::vf2d& p1, const olc::vf2d& p2) noexcept
{
return Lerp(p1, p2, half);
}
//static olc::vf2d Last(const olc::vf2d& p2, const olc::vf2d& p1) noexcept
//{
// return Lerp(p1, p2, threeFourth);
//}
public:
//left and right and the same for flat top and
//bottom. FbTop is flat bottom's top point and
//Ftbottom is flat top's bottom point.
static olc::vf2d FbTop(olc::vf2d p1, olc::vf2d p2, olc::vf2d p3) noexcept
{
if (p1.y > p2.y) std::swap(p1, p2);
if (p2.y > p3.y) std::swap(p2, p3);
if (p1.y > p2.y) std::swap(p1, p2);
return p1;
}
static olc::vf2d FtBottom(olc::vf2d p1, olc::vf2d p2, olc::vf2d p3) noexcept
{
if (p1.y < p2.y) std::swap(p1, p2);
if (p2.y < p3.y) std::swap(p2, p3);
if (p1.y < p2.y) std::swap(p1, p2);
return p1;
}
static olc::vf2d Right(olc::vf2d p1, olc::vf2d p2, olc::vf2d p3) noexcept
{
if (p1.x > p2.x) std::swap(p1, p2);
if (p2.x > p3.x) std::swap(p2, p3);
if (p1.x > p2.x) std::swap(p1, p2);
return p1;
}
static olc::vf2d Left(olc::vf2d p1, olc::vf2d p2, olc::vf2d p3) noexcept
{
if (p1.x < p2.x) std::swap(p1, p2);
if (p2.x < p3.x) std::swap(p2, p3);
if (p1.x < p2.x) std::swap(p1, p2);
return p1;
}
public:
olc::vf2d p1{}, p2{}, p3{};
};
</code></pre>
<p>triangleProcessor.h</p>
<pre><code>#pragma once
#include <functional>
#include "pixelGameEngine.h"
#include "triangle.h"
#include "graphics.h"
#include "input.h"
#include "world.h"
class TriangleProcessor
{
public:
TriangleProcessor(const int sw, const int sh)
{
//Initialize the vector with the first triangle
vvTris.push_back
(//vvtris
{ //vtris
{ //triangle
{sw * 0.5f, 0.0f}, //olc::vf2d
{0.0f, sh * 1.0f}, //olc::vf2d
{sw * 1.0f, sh * 1.0f} //olc::vf2d
}
}
);
}
TriangleProcessor(const TriangleProcessor&) = delete;
TriangleProcessor& operator=(const TriangleProcessor&) = delete;
private:
using vTris = std::vector<Triangle>;
std::vector<vTris> vvTris;
Gfx gfx{};
Input input{};
private:
void GenerateMiddleTriangle(const Triangle& tri, vTris& newVTris) noexcept
{
Triangle midTri =
{
Triangle::Mid(tri.p1, tri.p2),
Triangle::Mid(tri.p2, tri.p3),
Triangle::Mid(tri.p3, tri.p1)
};
midTri.flatTop = true;
newVTris.push_back(midTri);
}
void GenerateFlatBottoms(const Triangle& tri, vTris& newVTris) noexcept
{
Triangle topTri =
{
Triangle::FbTop(tri.p1, tri.p2, tri.p3),
Triangle::Mid
(
Triangle::FbTop(tri.p1, tri.p2, tri.p3), Triangle::Left(tri.p1, tri.p2, tri.p3)
),
Triangle::Mid
(
Triangle::FbTop(tri.p1, tri.p2, tri.p3), Triangle::Right(tri.p1, tri.p2, tri.p3)
),
};
Triangle bottomLeftTri =
{
Triangle::Mid
(
Triangle::FbTop(tri.p1, tri.p2, tri.p3), Triangle::Left(tri.p1, tri.p2, tri.p3)
),
Triangle::Left(tri.p1, tri.p2, tri.p3),
Triangle::Mid
(
Triangle::Right(tri.p1, tri.p2, tri.p3), Triangle::Left(tri.p1, tri.p2, tri.p3)
),
};
Triangle bottomRightTri =
{
Triangle::Mid
(
Triangle::FbTop(tri.p1, tri.p2, tri.p3), Triangle::Right(tri.p1, tri.p2, tri.p3)
),
Triangle::Right(tri.p1, tri.p2, tri.p3),
Triangle::Mid
(
Triangle::Right(tri.p1, tri.p2, tri.p3), Triangle::Left(tri.p1, tri.p2, tri.p3)
),
};
newVTris.push_back(topTri);
newVTris.push_back(bottomLeftTri);
newVTris.push_back(bottomRightTri);
}
void GenerateFlatTops(const Triangle& tri, vTris& newVTris) noexcept
{
Triangle topLeftTri =
{
Triangle::Left(tri.p1, tri.p2, tri.p3),
Triangle::Mid
(
Triangle::Left(tri.p1, tri.p2, tri.p3), Triangle::FtBottom(tri.p1, tri.p2,tri.p3)
),
Triangle::Mid
(
Triangle::Left(tri.p1, tri.p2, tri.p3), Triangle::Right(tri.p1, tri.p2,tri.p3)
),
};
Triangle topRightTri =
{
Triangle::Right(tri.p1, tri.p2, tri.p3),
Triangle::Mid
(
Triangle::Right(tri.p1, tri.p2, tri.p3), Triangle::FtBottom(tri.p1, tri.p2,tri.p3)
),
Triangle::Mid
(
Triangle::Left(tri.p1, tri.p2, tri.p3), Triangle::Right(tri.p1, tri.p2,tri.p3)
),
};
Triangle bottomTri =
{
Triangle::FtBottom(tri.p1, tri.p2, tri.p3),
Triangle::Mid
(
Triangle::Right(tri.p1, tri.p2, tri.p3), Triangle::FtBottom(tri.p1, tri.p2,tri.p3)
),
Triangle::Mid
(
Triangle::Left(tri.p1, tri.p2, tri.p3), Triangle::FtBottom(tri.p1, tri.p2,tri.p3)
),
};
newVTris.push_back(topLeftTri);
newVTris.push_back(topRightTri);
newVTris.push_back(bottomTri);
}
public:
int GetCurrentIteration() const noexcept
{
return (int)vvTris.size() - 1;
}
const std::vector<vTris>& GetConstvvTris() const noexcept
{
return vvTris;
}
std::vector<vTris>& GetvvTris() noexcept
{
return vvTris;
}
void DoIteration() noexcept
{
//retrieve the last vector of triangles
vTris vtris = vvTris.back();
//holds the triangles generated in this
//iteration
vTris newVTris{};
//iterate through all the triangles in that vector
//and create new vector of inner triangles. Then
//add that vector to vvTris.
for (auto& tri : vtris)
{
//Each triangle generates four unqiue inner triangle
GenerateMiddleTriangle(tri, newVTris);
if (tri.flatTop)
{
GenerateFlatTops(tri, newVTris);
}
else
{
GenerateFlatBottoms(tri, newVTris);
}
}
//Add the vector that contains the triangles form this
//iteration to vvTris.
vvTris.push_back(newVTris);
}
void UndoIteration() noexcept
{
//Dont want to be able to remove the first
//triangle
if (vvTris.size() > 1)
{
vvTris.pop_back();
}
}
void Run(olc::PixelGameEngine* pge) noexcept
{
Input::OnDPress(pge, [this]() { this->DoIteration(); });
Input::OnAPress(pge, [this]() { this->UndoIteration(); });
}
void Render(olc::PixelGameEngine* pge) noexcept
{
Gfx::Clear(pge);
//Draw only the last iteration of the triangles + all
//the flat tops
for (auto& tri : vvTris.back())
{
Gfx::RenderTriangle(pge,
World::WorldToScreen(tri.p1),
World::WorldToScreen(tri.p2),
World::WorldToScreen(tri.p3)
);
}
for (auto& vtris : vvTris)
for (auto& tri : vtris)
{
if (tri.flatTop)
{
Gfx::RenderTriangle(pge,
World::WorldToScreen(tri.p1),
World::WorldToScreen(tri.p2),
World::WorldToScreen(tri.p3)
);
}
}
Gfx::RenderNIterations(pge, (const int)GetCurrentIteration());
}
};
</code></pre>
<p>graphics.h</p>
<pre><code>#pragma once
#include "pixelGameEngine.h"
class Gfx
{
public:
Gfx() = default;
Gfx(const Gfx&) = delete;
Gfx& operator=(const Gfx&) = delete;
public:
static void Clear(olc::PixelGameEngine* pge) noexcept
{
pge->Clear(olc::BLACK);
}
static void RenderTriangle(olc::PixelGameEngine* pge, const olc::vf2d& p1, const olc::vf2d& p2,
const olc::vf2d& p3, olc::Pixel c = olc::WHITE) noexcept
{
auto testInScreen = [pge](const olc::vf2d& point)
{
return (
point.x > 0 && point.x < pge->ScreenWidth() ||
point.y > 0 && point.y < pge->ScreenHeight()
);
};
if (testInScreen(p1) || testInScreen(p2) || testInScreen(p3))
{
pge->DrawTriangle(p1, p2, p3, c);
}
}
static void RenderNIterations(olc::PixelGameEngine* pge, const int nIterations) noexcept
{
pge->DrawString({ 10, 10 }, "Iterations: " + std::to_string(nIterations));
}
};
</code></pre>
<p>input.h</p>
<pre><code>#pragma once
#include "pixelGameEngine.h"
#include <functional>
class Input
{
public:
Input() = default;
Input(const Input&) = delete;
Input& operator=(const Input&) = delete;
public:
static void OnDPress(olc::PixelGameEngine* pge, std::function<void()> DoIteration) noexcept
{
if (pge->GetKey(olc::D).bPressed)
{
DoIteration();
}
}
static void OnAPress(olc::PixelGameEngine* pge, std::function<void()> UndoIteration) noexcept
{
if (pge->GetKey(olc::A).bPressed)
{
UndoIteration();
}
}
};
class WorldInput
{
public:
WorldInput() = default;
WorldInput(const WorldInput&) = delete;
WorldInput& operator=(const WorldInput&) = delete;
private:
static olc::vf2d startMousePan;
public:
static void Drag(olc::PixelGameEngine* pge, olc::vf2d& offset, const float scale)
{
olc::vf2d mousePos = pge->GetMousePos();
if (pge->GetMouse(0).bPressed)
{
startMousePan = mousePos;
}
if (pge->GetMouse(0).bHeld)
{
offset -= (mousePos - startMousePan) / scale;
startMousePan = mousePos;
}
}
static void Zoom(olc::PixelGameEngine* pge, float& scale)
{
if (pge->GetKey(olc::W).bHeld)
{
scale *= 1.01f;
}
if (pge->GetKey(olc::S).bHeld)
{
scale *= 0.99f;
}
olc::vf2d afterZoom;
}
};
olc::vf2d WorldInput::startMousePan{};
</code></pre>
<p>world.h</p>
<pre><code>#pragma once
#include "pixelGameEngine.h"
#include "input.h"
class World
{
public:
World() = default;
World(const World&) = delete;
World& operator=(const World&) = delete;
private:
static olc::vf2d offset;
static float scale;
static WorldInput input;
public:
static void SetOffset(const olc::vf2d& inoffset) noexcept
{
offset = inoffset;
}
static const olc::vf2d& GetOffset() noexcept
{
return offset;
}
static void SetScale(const float inscale) noexcept
{
scale = inscale;
}
static const float& GetScale() noexcept
{
return scale;
}
public:
static olc::vf2d ScreenToWorld(const olc::vf2d& v) noexcept
{
return (v / scale) + offset;
}
static olc::vf2d WorldToScreen(const olc::vf2d& v) noexcept
{
return (v - offset) * scale;
}
static void DragToChangeOffset(olc::PixelGameEngine* pge) noexcept
{
input.Drag(pge, offset, scale);
}
static void WSToChangeScale(olc::PixelGameEngine* pge) noexcept
{
olc::vf2d mousePos = pge->GetMousePos();
olc::vf2d mouseBeforeZoom = ScreenToWorld(mousePos);
input.Zoom(pge, scale);
olc::vf2d mouseAfterZoom = ScreenToWorld(mousePos);
offset += mouseBeforeZoom - mouseAfterZoom;
}
};
WorldInput World::input{};
olc::vf2d World::offset = { 0.0f, 0.0f };
float World::scale = 1.0f;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T12:00:25.637",
"Id": "520286",
"Score": "0",
"body": "It would be nice if you would provide a ZIP file of your source code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T13:57:27.117",
"Id": "520293",
"Score": "0",
"body": "@paladin [github](https://github.com/HippozHipos/triInsideTri)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T14:47:01.273",
"Id": "520300",
"Score": "0",
"body": "`pixelGameEngine.h` is missing in git - I see, you've an external header -> https://github.com/OneLoneCoder/olcPixelGameEngine/blob/master/olcPixelGameEngine.h"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T15:00:43.603",
"Id": "520304",
"Score": "0",
"body": "`wget https://raw.githubusercontent.com/OneLoneCoder/olcPixelGameEngine/master/olcPixelGameEngine.h` - next time please include all needed files"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T15:05:36.177",
"Id": "520306",
"Score": "0",
"body": "Another missing header: _pixelGameEngine.h:3146:11: fatal error: GL/gl.h: file or directory cannot be found_ `#include <GL/gl.h>` - you should check your dependencies and add them all to your post"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T15:07:31.777",
"Id": "520307",
"Score": "0",
"body": "@paladin pixelGameEngine uses openGl for rendering. I am using visual studio so it sorted all of that out for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T15:41:45.423",
"Id": "520308",
"Score": "1",
"body": "Is it that what you'll say to your customer? _\"To play this game you've to fix all needed dependencies on your own. Have fun!\"_ ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:08:18.893",
"Id": "520310",
"Score": "1",
"body": "@paladin But... but you are not a customer :). I am also not a professional, just doing this for fun So I didn't know people expect all the files to be in the github repo. Will keep that in mind next time, thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:16:38.440",
"Id": "520312",
"Score": "0",
"body": "Well known standard libraries can be expected to be installed, but device dependent libraries cannot be expected to be installed and should be provided or linked at runtime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:23:00.740",
"Id": "520315",
"Score": "0",
"body": "Looks pretty good. The use of C++ is much better than most of what gets posted here, so I don't have a list of things spotted on a quick reading."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T13:20:57.847",
"Id": "263511",
"Score": "2",
"Tags": [
"c++",
"computational-geometry",
"graphics"
],
"Title": "Structuring a project that generates triangles inside triangles"
}
|
263511
|
<p>I am building a little helper for the card game Bridge. The aim is to generate a "hand" of 13 randomly-dealt cards, and then to run various calculations on the hand to help a player with the "bidding" phase of the game. (<em>I'm hoping knowledge of Bridge is not required for this code review!</em>)</p>
<p>You will see that after creating the deck of cards and dealing 13 cards to make the hand, I put each suit's cards into a class for that suit. This enables me to deal with each suit's cards individually but also create global calculations that apply to the whole hand. Is this way using best practice / the most efficient way (this is my first coding project)?</p>
<pre><code>// Generate a pack of 52 cards, one of each value for each suit, into const cards
function deckBuilder() {
const values = [
"A",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J",
"Q",
"K",
];
const suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
const cards = [];
for (let s = 0; s < suits.length; s++) {
for (let v = 0; v < values.length; v++) {
const value = values[v];
const suit = suits[s];
cards.push({ value, suit });
}
}
return cards;
};
const cards = deckBuilder();
// create new Suit class
class Suit {
constructor(name, major) {
this.name = name;
this.cards = [];
this.major = major;
}
get length() {
return this.cards.length;
}
get HCPs() {
return this.calcHCPs();
}
get sortedCards() {
return this.cards.sort((x, y) => {
if ( !isNaN(x) && isNaN(y) ) {
return 1;
} else if ( isNaN(x) && isNaN(y) ) {
if ( x === "J" ) { return 1 }
else if (y === "J") { return -1 } else if ( x > y ) { return 1; }
else { return -1; }
} else if ( !isNaN(x) && !isNaN(y) ) {
if ( x === "10" ) { return - 1 }
else if (y === "10") { return 1 } else if ( x > y ) { return -1; }
else { return 1; }
} else {
return -1;
}
});
}
calcHCPs() {
let p = 0;
for (let card of this.cards ) {
if (card === 'A') { p += 4; }
else if (card === 'K') { p += 3; }
else if (card === 'Q') { p += 2; }
else if (card === 'J') { p++; }
// else { break; }
}
return p
}
};
// create the four empty suits, with properties, to be populated
const spades = new Suit('Spades', true);
const hearts = new Suit('Hearts', true);
const diamonds = new Suit('Diamonds', false);
const clubs = new Suit('Clubs', false);
// Get one deal - 13 random cards - from the deck of 52 - and push to each suit object
function randomCard(cards) {
const random = Math.floor(Math.random() * cards.length);
const cardValue = cards[random].value;
const cardSuit = cards[random].suit;
if (cardSuit === "Diamonds"){
diamonds.cards.push(cardValue);
} else if (cardSuit === "Hearts") {
hearts.cards.push(cardValue);
} else if (cardSuit === "Spades") {
spades.cards.push(cardValue);
} else {
clubs.cards.push(cardValue);
}
cards.splice(random, 1)
};
for (let counter = 0; counter < 13; counter++ ){
randomCard(cards)
};
let shape = [ spades.length, hearts.length, diamonds.length, clubs.length ];
let shapeSorted = shape.sort().reverse();
// Calculate high card points (HCPs)
let HCPs = spades.HCPs + hearts.HCPs + diamonds.HCPs + clubs.HCPs;
console.log("The high card points are: " + HCPs);
// DECK INFO FUNCTIONS
function isHandBalanced() {
shape.sort().reverse();
if ( shape[0] + shape[1] > 8 ) {
return false;
}
else {
return true;
}
};
function suggestedBid() {
if ( isHandBalanced() ) {
if (HCPs < 12) { return "Pass"; }
else if (HCPs >= 12 && HCPs <= 14) {
if (shape[0] == 5 || shape[1] == 5) { return "You have a 5 card suit!"; }
else { return "1NT"; }
}
if (HCPs >= 15 && HCPs <= 19) { return "Open at 1 level" }
}
else {
return "Not balanced";
}
};
</code></pre>
|
[] |
[
{
"body": "<h2>Abstractions</h2>\n<p>When coding we abstract the data we manipulate in such a way to make the code easy to write and efficient to execute. Abstracted data only contains what is relevant.</p>\n<p>Very often coders will forget the abstraction and focus on the irrelevant details a trap you have fallen into in this case.</p>\n<h2>Abstract cards</h2>\n<p>For a deck of cards the suit, and value can be abstracted to an array of 52 values from 0 to 51 (the <code>cardId</code>)</p>\n<p>The single value <code>cardId</code> holds all you need to...</p>\n<ul>\n<li>get the suit <code>cardSuit = cardId / 13 | 0;</code> a value from 0 - 3</li>\n<li>get the value <code>cardValue = cardId % 13;</code> a value from 0 - 12</li>\n<li>display the card using the <code>cardId</code> to locate an image or use the suit and value ids to lookup a string.</li>\n</ul>\n<p>The names of suits and values are only needed when you present the information to the user.</p>\n<p>Tracking details like the cards suit and value using the real world representations just complicates the code making it hard to modify, and maintain.</p>\n<p>A rule of coding is <em>"Keep it Simple"</em> and one method to simplify is via effective abstraction.</p>\n<h2>Rewrite</h2>\n<p>The following rewrite does the same as your code, with some added details.</p>\n<p>The <code>Deck</code> lets you create a deck. Picked cards are random, returned cards are placed on top. The deck can be reset.</p>\n<p>The <code>Hand</code> gets 13 cards from a deck, displays the cards in the console and uses your method to calculate the bid.</p>\n<p>The are 12 lines of code that are not needed, but I left them in to illustrate high level usage. Eg display cards, manage deck, pick random cards.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const VALS = \"2,3,4,5,6,7,8,9,10,J,Q,K,A\".split(\",\");\nconst SUITS = \"♠,♡,♣,♢\".split(\",\");\nconst VAL_HCP = [0,0,0,0,0,0,0,0,0,1,2,3,4];\n\nconsole.log(\"Hint: '\" + Hand(Deck()) + \"'\")\nfunction Deck() {\n const cards = new Array(52).fill(0).map((v, i)=> i);\n return {\n get remaining() { return cards.length },\n get card() { return cards.splice(Math.random() * cards.length | 0, 1)[0] },\n set card(card) { cards.push(card) },\n reset() { cards.length = 52; cards.map((v, i) => i) },\n };\n};\nfunction Shuffle(deck) { // example using deck to shuffle cards\n const shuffled = [];\n while (deck.remaining) { shuffled.push(deck.card) }\n while (shuffled.length) { deck.card = shuffled.pop() }\n return deck; \n}\nfunction Hand(deck) {\n const cards = [];\n while (cards.length < 13) { cards.push(deck.card) }\n const getSuit = suitIdx => cards.filter(c => (c / 13 | 0) === suitIdx);\n const suits = [getSuit(0), getSuit(1), getSuit(2), getSuit(3)];\n\n const suitHCP = (suit) => suit.reduce((hcp, c) => hcp + VAL_HCP[c % 13], 0);\n const HCPs = suits.reduce((hcps, suit) => hcps + suitHCP(suit), 0);\n const shapes = suits.map(suit => suit.length).sort((a,b)=>a-b);\n\n console.log(cards.sort((a,b)=>a-b).map(c => SUITS[c/13 | 0] + VALS[c%13]).join(\", \") + \" HCPS: \" + HCPs);\n\n if (shapes[2] + shapes[3] > 8) {\n if (HCPs < 12) { return \"Pass\" }\n if (HCPs >= 12 && HCPs <= 14) {\n if (shapes[2] === 5 || shapes[3] === 5) { return \"You have a 5 card suit!\" }\n return \"1NT\";\n }\n if (HCPs >= 15 && HCPs <= 19) { return \"Open at 1 level\" }\n } else { return \"Not balanced\" }\n return \"Unknown Play\";\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T20:59:44.507",
"Id": "520249",
"Score": "0",
"body": "I'm sorry, but I don't believe representing a card using just a integer is readable or \"simple\" (unless maybe it is completely hidden inside a card class, which it isn't). IMO having separate suit and value fields is a clear one-to-one representation of the real object which is much more obvious and comprehensible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T12:10:17.190",
"Id": "520287",
"Score": "1",
"body": "@RoToRa I must totally disagree as high level abstractions are a primary source of overly complex source code and poorly performing execution. Look at OPs getter `Suit.sortedCards` 16 lines of code that can be done in one `this.card.sort((a,b)=>a-b)` in a fraction of the time. Coders are the smart ones! Why does the coder need to know the SUIT and VALUE as irrelevant named items? They relational entities, \"is value greater / same / less\", \"is suit greater / same / less?\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T16:20:32.620",
"Id": "263519",
"ParentId": "263513",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263519",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T14:07:00.530",
"Id": "263513",
"Score": "4",
"Tags": [
"javascript",
"playing-cards"
],
"Title": "Deal and evaluate a Bridge hand"
}
|
263513
|
<p>I've written a C# program to generate a random maze, and then draw that maze in the Console mode using box-drawing characters, e.g. ─ │ ┌ ┐ ┬ ┼ etc. It works fine, as below, but I'm not convinced that the code used is remotely efficient, or that it couldn't be done better.</p>
<p><a href="https://i.stack.imgur.com/3m3NO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3m3NO.png" alt="enter image description here" /></a></p>
<p>I have a Maze class with the following members:</p>
<pre class="lang-cs prettyprint-override"><code>int Width { get; }
int Height { get; }
int DisplayWidth { get; }
int DisplayHeight { get; }
Cell[,] Cells;
char[,] DisplayCells;
bool[,] Visited;
Random Rnd;
</code></pre>
<p>And these methods:</p>
<ul>
<li>Public Maze [constructor]</li>
<li>Private Invert (params: Direction d; returns: Direction)</li>
<li>Private GetNeighbours (params: Coord current; returns: List)</li>
<li>Private GetDirection (params: Coord current, Coord neighbour, Direction dir; void)</li>
<li>Private Create (void)</li>
<li>Private SetDisplayGrid (void)</li>
<li>Public DrawDisplayGrid (params: Coord startPosition)</li>
</ul>
<p>Here's the code for Cell and Coord for context:</p>
<pre class="lang-cs prettyprint-override"><code>public struct Coord
{
public int x;
public int y;
public Coord(int y, int x)
{
this.x = x;
this.y = y;
}
}
public class Cell
{
public Cell()
{
north = true;
east = true;
south = true;
west = true;
icon = ' ';
}
public bool north;
public bool east;
public bool south;
public bool west;
public char icon;
}
</code></pre>
<p>I've omitted some fields and code because they're not relevant to the question.</p>
<p>When the user calls the Maze constructor, as in:</p>
<pre class="lang-cs prettyprint-override"><code>Maze m = new Maze(25, 12);
</code></pre>
<p>it initialises all fields, including the Cells 2D array, which is an array of Cell objects. A Cell has four "walls": north, east, south and west, and they're all initially set to true. The Maze constructor then calls the Create method, which traverses through each cell of the maze and "knocks down" walls until each cell has been visited, using the depth-first search algorithm outlined here: <a href="https://scipython.com/blog/making-a-maze/" rel="nofollow noreferrer">https://scipython.com/blog/making-a-maze/</a>.</p>
<p>Once this is done, the <strong>SetDisplayGrid</strong> method is then called by the Maze constructor. This takes a 2D char array, DisplayGrid - which has the size 2n + 1 for each dimension of the Cells array n (meaning that if the Cells array is 5 x 10, DisplayGrid will be 11 x 21) - and populates it with box characters, according to the "wall" boolean values in each cell. This is where I think my code may be inefficient, because I have so many conditionals.</p>
<p>Broadly, the approach is:</p>
<ol>
<li>For each cell, first set the north and west walls, then the upper-left corner</li>
<li>If the cell is the last one on its row, set the upper-right corner and the east wall</li>
<li>If the cell is the last one on its column, set the lower-left corner and the south wall</li>
<li>If the cell is the last cell in the table, set the lower-right corner</li>
</ol>
<p>Here's the code for this method:</p>
<pre class="lang-cs prettyprint-override"><code>private void SetDisplayGrid()
{
DisplayCells = new char[DisplayHeight, DisplayWidth];
Coord current = new Coord();
for (int h = 0; (h * 2) + 1 < DisplayHeight; h++)
{
for (int w = 0; (w * 2) + 1 < DisplayWidth; w++)
{
current.x = (w * 2) + 1;
current.y = (h * 2) + 1;
bool curNorth = Cells[h, w].north;
bool curWest = Cells[h, w].west;
bool curEast = Cells[h, w].east;
bool curSouth = Cells[h, w].south;
// The cell itself
DisplayCells[current.y, current.x] = Cells[h, w].icon;
// Orthogonal walls (NORTH AND WEST)
if (curNorth) { DisplayCells[current.y - 1, current.x] = '─'; } // NORTH WALL
if (curWest) { DisplayCells[current.y, current.x - 1] = '│'; } // WEST WALL
// UPPER-LEFT CORNER
if (current.y - 1 == 0 && current.x - 1 == 0) // Cell is at the top-left corner --> ┌
{
DisplayCells[current.y - 1, current.x - 1] = '┌';
}
else if (current.y - 1 == 0 && current.x - 1 > 0) // Cell is on the first row but not the first column
{
if (curWest) { DisplayCells[current.y - 1, current.x - 1] = '┬'; }
else { DisplayCells[current.y - 1, current.x - 1] = '─'; }
}
else if (current.y - 1 > 0 && current.x - 1 == 0) // Cell is on the first column but not the first row
{
if (curNorth) { DisplayCells[current.y - 1, current.x - 1] = '├'; }
else { DisplayCells[current.y - 1, current.x - 1] = '│'; }
}
else // Cell is in the middle (not the first column or row)
{
bool nextEast = Cells[h - 1, w - 1].east;
bool nextSouth = Cells[h - 1, w - 1].south;
char corner = '*';
if (curNorth && curWest && nextEast && nextSouth) { corner = '┼'; }
else if (curNorth && curWest && nextEast && nextSouth) { corner = '┼'; }
else if (curNorth && curWest && !nextEast && nextSouth) { corner = '┬'; }
else if (!curNorth && curWest && nextEast && nextSouth) { corner = '┤'; }
else if (curNorth && !curWest && nextEast && nextSouth) { corner = '┴'; }
else if (curNorth && curWest && nextEast && !nextSouth) { corner = '├'; }
else if (!curNorth && curWest && !nextEast && nextSouth) { corner = '┐'; }
else if (!curNorth && !curWest && nextEast && nextSouth) { corner = '┘'; }
else if (curNorth && !curWest && nextEast && !nextSouth) { corner = '└'; }
else if (curNorth && curWest && !nextEast && !nextSouth) { corner = '┌'; }
else if (curNorth && !curWest && !nextEast && nextSouth) { corner = '─'; }
else if (!curNorth && curWest && nextEast && !nextSouth) { corner = '│'; }
else if (!curNorth && !curWest && nextEast && !nextSouth) { corner = '│'; }
else if (curNorth && !curWest && !nextEast && !nextSouth) { corner = '─'; }
else if (!curNorth && curWest && !nextEast && !nextSouth) { corner = '│'; }
else if (!curNorth && !curWest && !nextEast && nextSouth) { corner = '─'; }
else { corner = '*'; }
DisplayCells[current.y - 1, current.x - 1] = corner;
}
// EAST WALLS AND UPPER RIGHT CORNERS
if (current.x + 1 == DisplayWidth - 1)
{
if (curEast) { DisplayCells[current.y, current.x + 1] = '│'; } // EAST WALL
// UPPER-RIGHT CORNER
if (current.y - 1 == 0 && current.x + 1 == DisplayWidth - 1) { DisplayCells[current.y - 1, current.x + 1] = '┐'; }
else
{
if (curNorth) { DisplayCells[current.y - 1, current.x + 1] = '┤'; }
else { DisplayCells[current.y - 1, current.x + 1] = '│'; }
}
}
// SOUTH WALLS AND LOWER-LEFT CORNERS
if (current.y + 1 == DisplayHeight - 1)
{
if (curSouth) { DisplayCells[current.y + 1, current.x] = '─'; } // SOUTH WALL
// LOWER-LEFT CORNER
if (current.x - 1 == 0) { DisplayCells[current.y + 1, current.x - 1] = '└'; }
else
{
if (curWest) { DisplayCells[current.y + 1, current.x - 1] = '┴'; }
else { DisplayCells[current.y + 1, current.x - 1] = '─'; }
}
}
// LOWER-RIGHT CORNER
if (current.x + 1 == DisplayWidth - 1 && current.y + 1 == DisplayHeight - 1)
{
DisplayCells[current.y + 1, current.x + 1] = Block;
}
}
}
}
</code></pre>
<p>As you can see, there are a lot of conditionals when I'm checking the upper-left corner in the middle of the table, because there are basically sixteen different possibilities for what character could occupy that space.</p>
<p>I'm not sure how I could simplify this code but would appreciate any suggestions - especially if there's any redundant calculations I've missed, or a way to make these checks without making so many conditional checks. If anything else jumps out, feel free to say so.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T07:13:24.347",
"Id": "520268",
"Score": "1",
"body": "You might be interested in looking at this: [Visualising Algorithms, maze generation](https://bost.ocks.org/mike/algorithms/#maze-generation)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T07:21:30.487",
"Id": "520269",
"Score": "0",
"body": "@RobH It doesn't address the problem I'm trying to solve in particular, but you're not wrong, that is a very interesting discussion with some beautiful gifs!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T10:22:11.710",
"Id": "520278",
"Score": "1",
"body": "yeah, I should have said it was only a \"you may find this interesting\" rather than a \"you may find it helpful\" :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T18:26:26.397",
"Id": "520330",
"Score": "0",
"body": "It might be better if you posted entire classes including the using `MODULE` statements."
}
] |
[
{
"body": "<p>There are different possible approaches to assign the wall characters. One uses the new C# 8.0 switch expressions together with the tuple pattern.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>char corner = (curNorth, curWest, nextEast, nextSouth) switch {\n (true, true, true, true) => '┼',\n (true, true, false, true) => '┬',\n (false, true, true, true) => '┤',\n (true, false, true, true) => '┴',\n // ... other cases ...\n _ => '*'\n};\n</code></pre>\n<p>Another possibility is to think of the wall parts as four digits in a binary number. e.g., north = 1, west = 2, east = 4, south = 8. Combined you get a number in the range 0 ... 15 (inclusive). You can use these numbers as index in a character array:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>char[] walls = {\n// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n '*', '─', '│', '┌', '│', '└', '│', '├', '─', '─', '┐', '┬', '┘', '┴', '┤', '┼' \n};\n\nint index = (curNorth ? 1 : 0) + \n (curWest ? 2 : 0) + \n (nextEast ? 4 : 0) + \n (nextSouth ? 8 : 0);\nchar corner = walls[index];\n</code></pre>\n<p>You could also get rid of many if-statements if you treated the surrounding walls separately. The nested loop would only be responsible for the core (middle) of the maze. Then a separate loop would create the top and the bottom walls. Another separate loop would create the left and right walls. The four corners need not to be in a loop at all.</p>\n<p>I am not sure if I got the characters right. It seems that you have north pointing to the right and west downwards. Usually north points upwards and east to the right on geography maps.</p>\n<hr />\n<p>Alternatively, instead of having four boolean fields, you could also use a flags enum.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[Flags]\npublic enum Direction\n{\n None = 0,\n North = 1,\n West = 2,\n East = 4,\n South = 8\n}\n</code></pre>\n<p>Now, you can combine directions like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Direction walls = Direction.North | Direction.East | Direction.South;\nint index = (int)walls;\n</code></pre>\n<p>See also:</p>\n<ul>\n<li><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum\" rel=\"nofollow noreferrer\">Enumeration types (C# reference)</a></li>\n<li><a href=\"https://stackoverflow.com/q/8447/880990\">What does the [Flags] Enum Attribute mean in C#?</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T18:34:01.050",
"Id": "520240",
"Score": "0",
"body": "Thanks Olivier, these are great suggestions. I like the idea of using binary encodings or tuple-switch statements for the central core section of the maze. I might try and do as you suggest and break out the loops as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T18:38:18.657",
"Id": "520243",
"Score": "1",
"body": "And yes, the way I've treated the characters does seem a bit confusing, I'll admit! So imagine you've got a current cell, and a neighbour which is the cell upper-left of current. To figure out what box character to put in the upper-left corner of your current cell, you need to check the north and west walls of the current cell, and the east and south walls of the cell to the upper-left. I hope that makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T18:40:49.073",
"Id": "520409",
"Score": "1",
"body": "@Lou if the answer was helpful, you may mark it accepted. The same for your previous question, you can find it on your profile page. Choose the most useful answer, then accept it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T17:56:31.927",
"Id": "263520",
"ParentId": "263517",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T15:46:42.820",
"Id": "263517",
"Score": "4",
"Tags": [
"c#",
"performance",
"array",
"console",
"ascii-art"
],
"Title": "More efficient way to create an ASCII maze using box characters"
}
|
263517
|
<h3>Background</h3>
<p>This question is inspired by the question: <a href="https://codereview.stackexchange.com/q/263444/61495">Killing a hydra</a>, and my response therein. I will restate the problem at hand in full so that this question is fully self contained</p>
<blockquote>
<p>You can only kill off a given number of heads at each hit and
corresponding number of heads grow back. The heads will not grow back
if the hydra is left with zero heads. For example:</p>
<pre><code>heads = [135]
hits = [25,67,1,62]
growths = [15,25,15,34]
</code></pre>
<p>Then you can kill off <code>hits[i]</code> heads but <code>growths[i]</code> heads grow back.</p>
</blockquote>
<p>The important restriction here is that:</p>
<blockquote>
<p><em>you have to leave the Hydra with <strong>exactly</strong> zero heads to win</em>.</p>
</blockquote>
<hr />
<p><strong>My own restriction in this post is that I want to try to minimize the number of hits necessary to kill</strong></p>
<hr />
<h3>Algorithm</h3>
<p>After some consideration I came up with the following strategy. <strong>Note:</strong> this strategy is <em>not</em> part of my answer on the original question.</p>
<ol>
<li><p>The difficult part is leaving the Hydra with <em>exactly</em> zero heads. So in order to accomplish this I wrote a short code that generates all optimal ways to leave the Hydra 1 hit from death. This is used as a lookup table for small number of heads.</p>
<ul>
<li><p>To create the lookup table fast, we create iterate over all possible <code>diffs</code> up to a certain magnitude. A <code>diff</code> is simply the change in heads after a hit and a regrow.
We then create a dict of these <code>diffs</code>
Each <code>diff</code> has multiple keys associated with them, which represents the number of heads reachable with 1 hit from that <code>diff</code>.</p>
<p><strong>Example</strong></p>
<pre><code>hits = [1, 25, 62, 67]
growths = [15, 15, 34, 25]
diff = [1, 4, 0, 0]
</code></pre>
<p>This corresponds to the number <code>1 * (1 - 15) + 4 * (25 - 15) = 26</code>. Which means that after applying <code>diff</code> to the Hydra, the Hydra has <code>26</code> fewer heads remaining. This also means that a Hydra with <code>88</code> heads is dead after <code>diff</code> heads have been removed. Why? Because <code>88 - 26 = 67</code> and <code>67</code> is in hits. In other words we create a dict which looks like</p>
<pre><code>hydra_dict = {26+1: diff, 26+25: diff, 26+62: diff, 26+67: diff}
</code></pre>
</li>
</ul>
</li>
<li><p>If our number of heads is greater than the largest value in our lookup dict,
we remove
values by picking the greatest <code>diff</code> and applying it <code>x</code> times to heads until we are in range. We overshoot a bit to make sure we are not at the very edge of our lookup dict.</p>
</li>
<li><p>If the number of heads lies in our <code>hydra_dict</code> we simply return this value.</p>
</li>
<li><p>Else we run a breadth first recursive search to either find a value in our dict, or a valid configuration of hits to kill the hydra.</p>
</li>
</ol>
<hr />
<h4>Questions</h4>
<p>I think I barely managed to make my code presentable, typing hints, using a class etc. However, my main issues is with the implementation</p>
<ul>
<li>How do I decide how big my lookup table should be? At the moment I just hardcoded that every <code>diff</code> can at most be <code>7</code>. I tried with a few lower values and a few higher, but not sure how I can properly find the best limit. <em>Do my diff limits have to be of same length</em>?</li>
<li>How do I decide how deep my recursive algorithm should go? At the moment it is hardcoded to be the same value as the size of my lookup table, which works. However, for smaller lookup tables I seem to need to use a bigger depth. <code>10</code> seems to always return something proper, again not sure how to find the proper value.</li>
<li>Instead of using a recursive solution I can "fill in the missing gaps" in my lookup table. This can be done by switching the switch<code>COMPLETE_HYDRA_DICT = False</code>. The benefits are that we always arrive at a lookup value after shaving off the too large values. The downside, is that it is resource heavy to fill in the table. Any thoughts?</li>
<li>My recursive function returns the solution with the <em>minimal</em> sum. I tried writing a recursive function that returns the first solution instead. Is this better? From some rudimentary testing it appears that these two (the return first recursive, and return minimal sum recursive) returns mostly the same values with a big enough lookup table.</li>
<li>Any other suggestions on improving the recursive function is welcome. I am not sure if it is possible to include any more early exits to speed up the code.</li>
</ul>
<hr />
<h3>Code</h3>
<pre><code>import itertools
from typing import Union
Head, Hit, Growth = int, int, int
Heads, Hits, Growths = list[Head], list[Hit], list[Growth]
HitGrowthDiff = Union[Hit, Growth]
HitGrowthDiffs = list[HitGrowthDiff]
HydraDict = dict[Head, HitGrowthDiffs]
MAX_LOOKUP = 7
RECURSIVE_DEPTH = MAX_LOOKUP
COMPLETE_HYDRA_DICT = False
COUNT_ITERS = 0
class Hydra:
"""Tries to find the minimal required hits to kill the hydra"""
def __init__(self, hits: Hits, growths: Growths, hydra_heads=0):
self._hits = hits
self._growths = growths
self.update_variables()
if hydra_heads > 0:
self._heads = hydra_heads
@property
def hits(self) -> Hits:
return self._hits
@hits.setter
def hits(self, hits):
self._hits = hits
self.update_variables()
@property
def growths(self) -> Growths:
return self._growths
@growths.setter
def growths(self, growths):
self._growths = growths
self.update_variables()
@property
def diffs(self) -> HitGrowthDiffs:
return self._diffs
@diffs.setter
def diffs(self, diffs):
self._diffs = diffs
self.update_variables()
@property
def head(self) -> Head:
return self._head
@head.setter
def head(self, head):
self._head = head
self.diffs_2_kill(head)
def update_variables(self) -> None:
hits = [0] * len(self.hits)
growths, diffs = hits.copy(), hits.copy()
for index, (hit, growth) in enumerate(
sorted(
zip(self.hits, self.growths),
key=lambda sub: sub[1] - sub[0],
reverse=True,
)
):
hits[index], growths[index], diffs[index] = hit, growth, hit - growth
self._hits, self._growths, self._diffs = hits, growths, diffs
self.generate_diffs_2_kill_hydra_lookup()
self.max_hydra = max(self.diffs_2_kill_)
self.max_diff = max(self.diffs)
self.max_diff_index = self.diffs.index(self.max_diff)
def generate_diffs_2_kill_hydra_lookup(
self,
limit: int = MAX_LOOKUP,
complete: bool = COMPLETE_HYDRA_DICT,
) -> None:
"""Generates a dictionary of optimal hit values for a large sample of heads"""
self.diffs_2_kill_ = dict()
for diffs_count in itertools.product(*[range(limit) for _ in self.diffs]):
hits = sum(d * count for d, count in zip(self.diffs, diffs_count))
if hits < 0:
continue
for final_hit in self.hits:
total_hits = hits + final_hit
if total_hits not in self.diffs_2_kill_:
self.diffs_2_kill_[total_hits] = list(diffs_count)
elif sum(self.diffs_2_kill_[total_hits]) > sum(diffs_count):
self.diffs_2_kill_[total_hits] = list(diffs_count)
if complete:
self.complete_diffs_2_kill_hydra_lookup()
def complete_diffs_2_kill_hydra_lookup(self) -> None:
"""Finds the missing head values in hydra_dict and fills them in manually"""
unreachable = sorted(
set(range(max(self.diffs_2_kill_) + 1)) - set(self.diffs_2_kill_.keys())
)
reachable_len = [0, 0]
for head, next_head in zip(unreachable[:-1], unreachable[1:]):
if next_head - head > reachable_len[1] - reachable_len[0]:
reachable_len = [head, next_head]
print(reachable_len)
for head in range(1, reachable_len[0]):
if head in self.diffs_2_kill_:
continue
self.diffs_2_kill_[head] = self.diffs_2_kill_iterative(head)
self.diffs_2_kill_ = dict(
[
(head, kill)
for head, kill in self.diffs_2_kill_.items()
if head < reachable_len[1]
]
)
def heads_removed(self, number_of_hits: list[int]) -> Head:
return sum(diff * number for diff, number in zip(self.diffs, number_of_hits))
def is_hydra_one_hit_from_death(self, total_heads: Head, number_of_hits) -> bool:
"""Checks if Hydra is 1 hit away from death after n hits"""
heads_left = total_heads - self.heads_removed(number_of_hits)
return heads_left in self.hits
def diffs_2_kill_iterative(
self,
head: Head,
nums: int = MAX_LOOKUP,
) -> HitGrowthDiffs:
"""Iterates over all possible number of hits, returns first 1 hit from death"""
for hydra_hits in itertools.product(*[range(nums) for _ in self.hits]):
if self.is_hydra_one_hit_from_death(head, list(hydra_hits)):
return list(hydra_hits)
return []
def diffs_2_kill(
self,
head: Head,
) -> None:
"""Low level function to check if a head is killable"""
extra_hits = [0] * len(self.diffs)
# Removes heads until we are in lookup range
if head > self.max_hydra:
times = int((head - self.max_hydra) / self.max_diff + 1)
head -= times * self.max_diff
extra_hits[self.max_diff_index] += times
if head in self.diffs_2_kill_:
final_hits = self.diffs_2_kill_[head]
else:
final_hits = self.diffs_2_kill_recursive(head)
heads = list(hits + extra for hits, extra in zip(final_hits, extra_hits))
self.final_hit = self.head - self.heads_removed(heads)
self.number_of_diffs_2_kill = heads
self.kill_hits = dict(zip(self.hits, self.number_of_diffs_2_kill))
def diffs_2_kill_recursive(
self,
head: Head,
diff: HitGrowthDiff = None,
new_hits: Hits = None,
diff_index: int = None,
depth: int = RECURSIVE_DEPTH,
) -> HitGrowthDiffs:
if new_hits is None:
new_hits = [0] * len(self.diffs)
if diff_index is not None:
new_hits[diff_index] += 1
if head == 0:
return new_hits
elif head in self.diffs_2_kill_:
heads_ = [
hit + extra for hit, extra in zip(self.diffs_2_kill_[head], new_hits)
]
return heads_
elif depth == 0:
return []
elif (diff is None) or (diff < head):
final_diffs = [
self.diffs_2_kill_recursive(
head - diff,
diff,
new_hits.copy(),
diff_index,
depth - 1,
)
for diff_index, diff in enumerate(self.diffs)
]
return min(list(filter(None, final_diffs)), key=sum, default=[])
return []
def __str__(self):
width = 60
string = "=" * width + "\n"
string += f"Hydra heads: {self.head}".center(width)
string += "\n" + "=" * width
head = self.head
for index, number_of_hits in enumerate(self.number_of_diffs_2_kill):
hit, growth = self.hits[index], self.growths[index]
if number_of_hits < 6:
for _ in range(number_of_hits):
string += f"\nWe kill {hit} heads of the hydra!"
string += f"\nOh no! {growth} heads regrew!"
head -= hit - growth
string += f"\n {head} heads remain!"
else:
string += f"\nWe kill {hit} heads of the hydra!"
string += f"\nOh no! {growth} heads regrew!"
head -= hit - growth
string += f"\n {head} heads remain!"
string += "\n ." * 3
string += f"\nThis is repeated {number_of_hits-2} times"
string += "\n ." * 3
head -= (hit - growth) * (number_of_hits - 2)
string += f"\nWe kill {hit} heads of the hydra!"
string += f"\nOh no! {growth} heads regrew!"
head -= hit - growth
string += f"\n {head} heads remain!"
string += "\n"
string += f"\nWe kill {self.final_hit} heads of the hydra!"
head -= self.final_hit
if head == 0:
string += "\n The Hydra is dead!"
string += "\n" + "~" * width + "\n"
return string
def main():
heads = [88, 135, 192, 4321, 98767893]
hits = [25, 67, 1, 62]
growths = [15, 25, 15, 34]
hydra = Hydra(hits, growths)
for head in heads:
hydra.head = head
print(hydra)
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T20:14:08.337",
"Id": "520246",
"Score": "1",
"body": "Please always tag Python questions with [tag:python] so the correct syntax highlighter is used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T07:02:36.010",
"Id": "520362",
"Score": "0",
"body": "If N heads is 10, the program prints: \"We kill 25 heads of the hydra! Oh no! 15 heads regrew! 0 heads remain!\". That doesn't make sense to me (how does one hit/kill 25 heads when only 10 existed) and it seems contrary to the spirit of the challenge -- namely, to exactly kill the hydra. Have I misunderstood or is that a previously unknown bug?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T11:11:38.870",
"Id": "520377",
"Score": "1",
"body": "@FMc *Unforseen bug, so sorry! I've worked a bit more on the code afterwards and the bug is fixed. I'll leave the question as is for now. But I probably will answer my own question in a week or two when things slow down at work. In the mean time feel free to answer the question if you want. (The code was, to the posters knowledge, working as intended when posted)"
}
] |
[
{
"body": "<p>This was an interesting puzzle and your question was framed very well. I have a\nfew code-review style comments. Those are followed by some discussion of, and\ncorresponding code for, a different algorithmic approach -- one that seems\neasier to follow, at least to my eye.</p>\n<p><strong>The Hydra class has a complex implementation</strong>. Its own internal state\nrequires fair bit of coordination, as evidenced primarily by the need to invoke\n<code>self.update_variables()</code> in various setters. Sometimes such dependencies are\nunavoidable, but one should generally view them as a potential warning sign. In this specific case,\nI think the warning is worth heeding. I don't think the complexity in the class\nis required.</p>\n<p><strong>A small symptom of the complexity</strong>. The Hydra class has bug. The API says\nyou can pass the N of <code>hydra_heads</code> as an argument: <code>Hydra(hits, growths, 2)</code>.\nBut if you do, <code>print(hydra)</code> fails because <code>_head</code> has not been set. The\nculprit is this line in the initializer: <code>self._heads = hydra_heads</code>.\nSuperficially, there is a typo (it should be <code>self._head</code> rather than\n<code>self._heads</code>). Of course, that mistake is natural because you have a plural\nthing (N of heads) but your code gives it a singular name (hence the\nconfusion). But all of that is the surface layer. The deeper problem is that\nthe initializer must use the setter, so that the object keeps its internal\nstate aligned: <code>self.head = hydra_heads</code>.</p>\n<p><strong>The Hydra class is over-eager</strong>. A good guideline is to keep object\ninitialization simple and lightweight: store the parameters and await further\ninstruction. Your implementation solves the whole problem immediately. In my\nexperience, lightweight initialization is usually better for testability,\ndebuggability, and flexibility in the face of evolving requirements. But that's\njust a guideline, and there can be valid exceptions. But notice that if we\ndecide to make <code>Hydra</code> eager during initialization, we could also decide to\ndesign the class to discourage mutation by users of the class. In other words,\nif the class solves the whole problem upon initialization, there's much less\nneed for a bunch of setters that carefully align internal state. Eager can\noften be paired with a policy of treating the objects as non-modifiable, at\nleast in spirit.</p>\n<p><strong>The Hydra class does not readily answer the primary question</strong>. Your stated\ngoal is to <em>minimize the number of hits necessary to kill the hydra</em>. But the\nclass does not appear to have a simple way to answer that question: how many\nhits were required? It also does not appear to have an easy way to see how many\nhits of each kind were required. Maybe there is a way and I overlooked it. In\nmy case, I looked for a while and then just reverse-engineered the <code>__str__()</code>\nmethod to get the information I wanted. During my early experimentation, I\nadded a few properties to your class to get what I needed.</p>\n<p><strong>Make debugging code data-oriented, not print-oriented</strong>. Your <code>__str__()</code>\nmethod is basically a debugging tool -- or at least that's the only use I can\nreally see for it, and it's how I used it -- but a big string of narrative text\nis not a good debugging mechanism. Much better is data: one or more\nmethods/properties to return the needed debugging facts. And even if you want\nthe debugging information to be converted to text for reading (for example, to\ntrace program logic), make the output data-oriented rather\nthan textual. The precise format can vary depending on the problem, but the key\nis to emit the data in a way that is easy to scan and navigate visually.\nSometimes tabular presentations work well (e.g., to see changes running down\na column), sometimes hierarchy/indentation works well (e.g., to convey changes as\nstate evolves through the program logic), and there are other possibilities.\nThe main point is to be systematic and focus on the data. When experimenting\nwith this problem I ended up writing a little debug function to print\nkeyword-style data at various indentation levels mirroring the structure of my\nalgorithm:</p>\n<pre><code>def debug(level, label, **kws):\n if False:\n msg = ' ' * level + label + ':'\n for k, v in kws.items():\n msg += f' {k}={v}'\n print(msg)\n</code></pre>\n<p><strong>A simpler optimization</strong>. A fair bit of your code is oriented toward creating\nand managing optimizations like a lookup table. But one only needs optimization\nfor large scale, which in this problem means a large number of heads. But when\nthe N of heads is very large, the problem requires no optimization, because\nthere is only one move to make: select the <code>Hit</code> with the largest positive\ndifference between the N of heads removed vs regrown. Only when the numbers get\nsmaller do we have to fuss over <code>Hit</code> selection so that we exactly kill the\nbeast. To take advantage of those observations, we need a way to draw a line\nbetween <em>very large</em> N of heads and everything else. Least common multiples\nprovide a convincing heuristic. In our case we have 4 <code>Hit</code> instances having\nthe following removed/regrown differences: -14, 10, 28, and 42. We can ignore\nthe negative value. The least common multiple of the other three differences is\n420. If you need to remove significantly more than 420 heads, the most efficient\nway to do it is with the big-hits: use 10 of the 42-diff <code>Hit</code> rather than 15\nof the 28-diff <code>Hit</code>, for example. I picked a conservative heuristic: any heads\nbeyond 5x of that LCM were removed immediately by repeated applications of the\n42-diff <code>Hit</code>. Since 5x the LCM is a tiny number, we don't really need to worry\nabout any further optimization.</p>\n<p><strong>A <code>Hit</code> dataclass</strong>. You have list of <code>hits</code> (heads removed) and a parallel\nlist of <code>growths</code> (heads regrown). I knew that I wanted to unify that data as a\nsingle list of <code>Hit</code> data objects. It was also handy to give that object a\nproperty for net head removal.</p>\n<pre><code>from dataclasses import dataclass\n\n@dataclass(frozen = True)\nclass Hit:\n removed: int\n regrown: int\n\n @property\n def net_removed(self):\n return self.removed - self.regrown\n</code></pre>\n<p><strong>A stack-based DFS algorithm, with guiding restrictions</strong>. I also expected\nthat my no-need-for-optimization algorithm could be a stack-based DFS search --\nbut one arranged to find the optimal solution first. That is achieved through\nthe interplay between two features of the algorithm. First, it tries bigger\n<code>Hit</code> instances before smaller, because we want the most efficient kill.\nSecond, and pulling in the opposite direction, it requires that the <code>Hit</code>\ninstances be selected in a monotonically increasing fashion. In other words, we\nmight prefer to use bigger hits, but selecting bigger hits comes with a cost:\nsmaller hits are disallowed on all subsequent selections. On a "representative"\nDFS traversal, the algorithm naively starts with big selections, but those\nreach a dead end if the solution requires some smaller hits too. The pathways\ninvolving smaller hits are put into the stack, so we will eventually explore\nthem and find a solution. But, again, on any specific selection, the algorithm\nprefers the biggest allowed hit, which ensures that we will choose the fewest\nsmall hits possible when reaching the solution. That's an intuitive explanation\nfor the logic. I think one could make a formal proof that these two features\nproduce a correct solution, but I basically convinced myself that they worked\nthrough old-fashioned experimentation. As always, I might be wrong.</p>\n<p><strong>A <code>State</code> dataclass</strong>. To simplify information management within stack or\nqueue based algorithms, it often helps to use a data object to represent\nprogram state. Here's what I ended up with:</p>\n<pre><code>@dataclass\nclass State:\n n_heads: int # N heads remaining.\n counts: list # Counts of Hits delivered so far.\n rng: range # Indexes of remaining candidate Hits.\n\n def __post_init__(self):\n # Ensure that each State gets an independent list of counts.\n self.counts = list(self.counts)\n</code></pre>\n<p><strong>Orchestration code</strong>. My own code evolved as I experimented toward a\nsolution, but here's a simplified setup:</p>\n<pre><code>import sys\n\ndef main(args):\n hits = [Hit(25, 15), Hit(67, 25), Hit(1, 15), Hit(62, 34)]\n n_heads = int(args[0])\n counts = hits_to_kill_hydra(n_heads, hits)\n print(n_heads, counts)\n\nif __name__ == "__main__":\n main(sys.argv[1:])\n</code></pre>\n<p><strong>Algorithm</strong>. And the algorithm ended up in one main function with two small\nhelpers. If one were feeling object-oriented, this code could be wrapped in a\n<code>HydraKiller</code> class or something, but I'm not convinced that would help too\nmuch with clarity. It might help if one had other goals or reporting needs in\nmind. I got interested in the puzzle mainly from the perspective of trying to\nwrite a solution that was as simple and intuitive as possible.</p>\n<pre><code>import math\n\ndef hits_to_kill_hydra(n_heads, hits):\n # Sort hits from small to large.\n hits = sorted(hits, key = lambda h: h.net_removed)\n\n # Set up initial n_heads and counts after quickly\n # removing any heads beyond the LCM-based threshold.\n n_heads, counts = rapid_head_removal(n_heads, hits)\n\n # Initialize stack with the starting State.\n limit = len(hits)\n s = State(n_heads, counts, range(0, limit))\n stack = [s]\n\n while stack:\n\n # Get current State.\n s = stack.pop()\n\n # Return a dict mapping hits to counts if we\n # can kill the hydra on the next Hit.\n i = immediate_kill(s.n_heads, hits)\n if i is not None:\n s.counts[i] += 1\n return dict(zip(hits, s.counts))\n\n # Otherwise, select the largest legal hit among those\n # specified by the current range of indexes.\n for i in reversed(s.rng):\n h = hits[i]\n if h.removed < s.n_heads:\n # In case hits[i] leads to a dead end, we need to put the\n # not-yet-considered alternatives (ie, Hits smaller than the\n # selected one) into the stack for later backtracking.\n if i > s.rng.start:\n s2 = State(s.n_heads, s.counts, range(s.rng.start, i))\n stack.append(s2)\n\n # Adjust state information based on selecting hits[i]. The\n # adjustments for n_heads and counts are straightforward. The\n # key part is the next State.rng: it ensures the the Hits will\n # be selected in a monotonically increasing fashion.\n s.counts[i] += 1\n n2 = s.n_heads - h.net_removed\n s2 = State(n2, s.counts, range(i, limit))\n stack.append(s2)\n break\n\n return None\n\ndef rapid_head_removal(n_heads, hits):\n # Compute N of heads beyond the 5x LCM threshold.\n net_removals = [h.net_removed for h in hits if h.net_removed > 0]\n surplus = n_heads - 5 * math.lcm(*net_removals)\n\n # Compute N of the biggest Hit to apply.\n big_hit = hits[-1]\n n_big = surplus // big_hit.net_removed\n\n # Use n_big to return the adjusted n_heads and counts.\n counts = [0 for _ in hits]\n if n_big > 0:\n counts[-1] += n_big\n n_heads -= n_big * big_hit.net_removed\n return (n_heads, counts)\n\ndef immediate_kill(n_heads, hits):\n # Return index of Hit that would immediately kill the hydra.\n for i, h in enumerate(hits):\n if n_heads == h.removed:\n return i\n return None\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T11:08:19.670",
"Id": "520473",
"Score": "0",
"body": "Fantastic answer! I might use this as a baseline to ask a follow up question implementing your suggestions. I 100% agree with you. My only question is how do you, from a hit list figure out what the final hit was? If the hits is applied randomly the hydra might be left with a negative number of heads. This is why I focused on the number of ways to leave the Hydra 1 hit away from death."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T16:40:27.860",
"Id": "520504",
"Score": "0",
"body": "@N3buchadnezzar The final is the biggest, due to the algorithm. But even with a different algorithm, one can derive it from the counts. Consider `n_heads=3`, which has solution `(3, 3, 0, 0)`. Total up the net removals to get -12. Subtract initial `n_heads` to get -15. The final hit is the one with a matching (positive) value for regrown. BTW, I was reminded that my function's return value isn't great because it returns the counts in order of the sorted hits. A better return would be `dict(zip(hits, s.counts))` so the user would not have to know about algorithm internals (edited accordingly)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T08:47:23.987",
"Id": "263621",
"ParentId": "263522",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263621",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T18:25:18.140",
"Id": "263522",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"recursion",
"dynamic-programming"
],
"Title": "Killing a Hydra - Overengineered"
}
|
263522
|
<p>For context, I wrote a function, <code>get_servers</code>, for the game <a href="https://bitburner.readthedocs.io/en/latest/" rel="nofollow noreferrer">Bitburner</a> which is usually played by writing JavaScript code. Instead, I used PureScript to write the function which is an implementation of something like the breadth-first search algorithm to get a list of all the servers in the game:</p>
<pre class="lang-hs prettyprint-override"><code>module Main (main) where
import Data.Array
import Data.Function.Uncurried
import Data.Maybe
import Effect
import Effect.Aff
import Effect.Class
import Effect.Uncurried
import Control.Promise
import Prelude
type NetscriptEnvironment = {
exit :: EffectFn1 Unit Unit,
getHostname :: Fn0 String,
scan :: Fn1 String (Array String),
tprint :: forall a. EffectFn1 a Unit
}
get_servers :: NetscriptEnvironment -> Array String
get_servers ns = sort $ get_servers' [] [runFn0 ns.getHostname] where
get_servers' :: Array String -> Array String -> Array String
get_servers' scanned unscanned =
if null unscanned then
scanned
else
get_servers' (concat [scanned, unscanned]) $ get_new unscanned where
get_new :: Array String -> Array String
get_new = get_new' [] where
get_new' :: Array String -> Array String -> Array String
get_new' accumulator servers =
case head servers of
Nothing -> accumulator
Just head -> let
get_new'' :: Array String -> String -> Array String
get_new'' accumulator' server =
if elem server accumulator' || elem server unscanned || elem server scanned then
accumulator'
else
snoc accumulator' server
in
case tail servers of
Nothing -> get_new' (foldl get_new'' accumulator $ runFn1 ns.scan head) []
Just tail -> get_new' (foldl get_new'' accumulator $ runFn1 ns.scan head) tail
main :: EffectFn1 NetscriptEnvironment (Promise Unit)
main = let
main' :: NetscriptEnvironment -> Effect (Promise Unit)
main' ns = let
exit :: Aff Unit
exit =
liftEffect $ do
runEffectFn1 ns.exit unit
tprint :: forall a. a -> Aff Unit
tprint input =
liftEffect $ do
runEffectFn1 ns.tprint input
pure unit
in
fromAff $ liftEffect $ launchAff_ do
tprint $ get_servers ns
exit
in
mkEffectFn1 main'
</code></pre>
<p>I'm still somewhat new to writing PureScript/Haskell-like code and so would appreciate some pointers on how I might refactor the above.</p>
<p>In particular, I don't like these about the current implementation:</p>
<ul>
<li>It seems like there's a lot of right-ward drift. Maybe this is normal with regards to PS/Haskell-like syntax, but I'm not sure.</li>
<li>In lines 43 and 44, I called <code>get_new'</code> essentially twice with almost the same arguments.</li>
<li>I also feel like I'm maybe not leveraging existing types/functions in the standard libraries and functional programming techniques (maybe point-free style?) to make the code more concise.</li>
</ul>
<p>So I want to know I might refactor the code such that:</p>
<ul>
<li>There's not so much right-ward drift.</li>
<li>There's less redundancies and the code is more concise in general. I'm thinking I could maybe accomplish this by leveraging some kind of standard library types or mapping/binding functions, but I'm not too familiar with the standard library and would appreciate recommendations on which types and functions I should familiarise myself with (with the aim of both improving the code above and my ability to write future PureScript code in general).</li>
<li>It's more idiomatic according to the common best practices of writing PureScript code. I'd also appreciate some reasoning for any changes you might suggest to help me understand them better.</li>
</ul>
<p>I also want to know:</p>
<ul>
<li>Is it fine when inter-operating with JS code to work with the standard JS data-types, or is it better to convert to some of the other PS types (e.g., from <code>Array</code> to <code>List</code> or <code>Sequence</code>), manipulate those, then convert back to JS types when needed? If so, when should the latter be done?</li>
<li>Aside from the standard library, are there other convenience libraries/tools (e.g. for error-handling, testing, linting, formatting, etc.) that I should look into using when working with PS code in general?</li>
</ul>
|
[] |
[
{
"body": "<p><strong>First</strong>, on rightward drift: you don't have to have every next function nested under the previous one, especially since none of them actually need access to the enclosing function's parameters. You can have everything bound under the same <code>where</code>. Except that <code>get_new''</code> wants access to <code>scanned</code> and <code>unscanned</code>, so it has to be bound inside <code>get_servers'</code> unfortunately. But everything else can be flat:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>get_servers :: NetscriptEnvironment -> Array String\nget_servers ns = sort $ get_servers' [] [runFn0 ns.getHostname] \n where\n get_servers' :: Array String -> Array String -> Array String\n get_servers' scanned unscanned =\n if null unscanned then\n scanned\n else\n get_servers' (concat [scanned, unscanned]) $ get_new unscanned\n where\n get_new :: Array String -> Array String\n get_new = get_new' []\n\n get_new' :: Array String -> Array String -> Array String\n get_new' accumulator servers =\n case head servers of\n Nothing -> accumulator\n Just head ->\n case tail servers of\n Nothing -> get_new' (foldl get_new'' accumulator $ runFn1 ns.scan head) []\n Just tail -> get_new' (foldl get_new'' accumulator $ runFn1 ns.scan head) tail\n\n get_new'' :: Array String -> String -> Array String\n get_new'' accumulator' server =\n if elem server accumulator' || elem server unscanned || elem server scanned then\n accumulator'\n else\n snoc accumulator' server\n</code></pre>\n<p><strong>Second</strong>, instead of functions like <code>head</code> and <code>null</code>, you can use pattern matching. It's looks better, and a bit faster too:</p>\n<pre class=\"lang-hs prettyprint-override\"><code> get_servers' :: Array String -> Array String -> Array String\n get_servers' scanned [] = scanned\n get_servers' scanned unscanned =\n get_servers' (scanned <> unscanned) (get_new unscanned)\n</code></pre>\n<p>Also note that I used operator <code><></code> instead of <code>concat []</code> to glue the two arrays together.</p>\n<p><strong>Third</strong>, the difference between the two <code>foldl</code> lines seems to be just that when the <code>tail servers == Nothing</code>, you turn it into an empty array, and otherwise you use the tail itself. Well, you can encode that idea directly with <code>fromMaybe</code>:</p>\n<pre><code> case head servers of\n Nothing -> accumulator\n Just head ->\n get_new' (foldl get_new'' accumulator $ runFn1 ns.scan head) (fromMaybe [] $ tail servers)\n</code></pre>\n<p><strong>Fourth</strong>, <code>get_new</code> seems to be called only once, so there is really no reason to keep it around just so you can pass an empty list to <code>get_new'</code>:</p>\n<pre><code> get_servers' scanned unscanned =\n get_servers' (scanned <> unscanned) (get_new' [] unscanned)\n</code></pre>\n<p><strong>And finally</strong>, I think you have structured the whole <code>get_new</code> logic in a very imperative style - essentially updating arrays as you go along. As far as I understand the idea, you should just (1) scan all <code>unscanned</code> servers, (2) concatenate all their results together, and then (3) subtract the already seen servers. The result of that should be newly discovered servers.</p>\n<pre><code>get_new :: Array String -> Array String\nget_new servers = concatMap (runFn1 ns.scan) servers \\\\ (scanned <> unscanned)\n</code></pre>\n<p>So your whole program becomes just this:</p>\n<pre><code>get_servers :: NetscriptEnvironment -> Array String\nget_servers ns = sort $ get_servers' [] [runFn0 ns.getHostname] \n where\n get_servers' scanned [] = scanned\n get_servers' scanned unscanned = \n get_servers' (scanned <> unscanned) $ \n concatMap (runFn1 ns.scan) unscanned \\\\ (scanned <> unscanned)\n</code></pre>\n<hr />\n<p>Also, a few stylistic notes, which are generally accepted in the community, but ultimately a question of personal choice:</p>\n<ol>\n<li><code>where</code>- and <code>let</code>-bound variables don't need type signatures. You can just omit them.</li>\n<li>Identifiers in PureScript are commonly camelCase, not snake_case. So <code>getNew</code> instead of <code>get_new</code>.</li>\n<li><code>Fn1</code> and <code>EffectFn1</code> are better kept at the very edges of FFI. Don't pass them around. Convert to normal function before passing.</li>\n</ol>\n<hr />\n<blockquote>\n<p>Is it fine when inter-operating with JS code to work with the standard JS data-types, or is it better to convert to some of the other PS types (e.g., from <code>Array</code> to <code>List</code> or <code>Sequence</code>), manipulate those, then convert back to JS types when needed? If so, when should the latter be done?</p>\n</blockquote>\n<p>Actually, <code>Array</code> is the default choice in PureScript, not <code>List</code>. <code>List</code>'s advantage over <code>Array</code> is linear cons/uncons operations, so you would generally use it when that matters for your algorithm. Similarly with <code>Sequence</code>. Otherwise - <code>Array</code> is the default choice, because it's default on the underlying platform, and therefore is optimized the hell out of.</p>\n<p>In general, as long as the JS type is "well-behaved" (i.e. doesn't have multi-typed or optional fields or some such), it's totally ok to use it from PureScript. That is, in fact, one of the selling points: zero-cost FFI.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T19:09:58.173",
"Id": "520412",
"Score": "0",
"body": "Thanks, this was exactly the kind of answer I was after! Regarding `get_new` though, I'm not sure your new version would work correctly if the `scan` output has nodes that share the same child nodes. I think it could cause duplicates in the final output, right? Wouldn't you need to either use `nub` to remove those (maybe before the `sort`), or use `foldl` instead of `concatMap` to track scan results and prevent duplicates from being added (this was what my version did). Also, is `concatMap` just an infix version of `>>=`, or are there other differences between them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T19:22:01.370",
"Id": "520414",
"Score": "0",
"body": "Sorry, I meant prefix instead of infix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T19:28:29.933",
"Id": "520415",
"Score": "1",
"body": "Yes, you're right: you do need to `nub` after the whole process to remove duplicates. Or, better yet, `nub` after each wave of scans. Less nubbing that way. And yes, `concatMap` is the same as `>>=`, but it's more understandable what's going on this way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T20:44:21.887",
"Id": "520419",
"Score": "0",
"body": "About using pattern matching in lieu of `head`, how would that work exactly? I thought I could only pattern match on the head and tail of `List`, but not of `Array`, since the latter doesn't use `Nil` and `Cons` constructors and instead maps to native JS arrays? And why would nubbing after each wave of scans result in less nubbing relative to nubbing once after the whole process?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T22:38:37.730",
"Id": "520437",
"Score": "0",
"body": "For arrays PureScript has special support - for both constructing values and pattern matching. Nubbing after each waves ought to result is smaller nubs, because each wave is presumably smaller than the total list of servers. Though I guess I could be wrong on that point. Depends on the network topology."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T16:03:17.527",
"Id": "263590",
"ParentId": "263523",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T20:08:34.920",
"Id": "263523",
"Score": "1",
"Tags": [
"beginner",
"algorithm",
"graph",
"breadth-first-search",
"purescript"
],
"Title": "PureScript breadth-first search implementation"
}
|
263523
|
<p>Basically, I'm trying to create a generic way to check if two shapes are colliding.</p>
<p>I think this is kind of a "double-dispatch" problem, but I'm unsure if there is a better way to solve it in Typescript / Javascript. This is the best I could come up with. Just assume the static helper functions are defined.</p>
<pre><code>abstract class Shape {
abstract collidesWith(shape: Shape): boolean;
}
class Circle extends Shape {
constructor(public x = 0, public y = 0, public r = 0) {
super();
}
collidesWith(shape: Shape) {
let circle = shape as Circle;
if (circle instanceof Circle) {
return Helpers.circlesCollide(this.x, this.y, this.r, circle.x, circle.y, circle.r);
}
let line = shape as LineSegment;
if (line instanceof LineSegment) {
return Helpers.lineIntersectsCircle(line.sX, line.sY, line.eX, line.eY, this.x, this.y, this.r);
}
return false;
}
}
class LineSegment extends Shape {
constructor(public sX = 0, public sY = 0, public eX = 0, public eY = 0) {
super();
}
collidesWith(shape: Shape) {
let line = shape as LineSegment;
if (line instanceof LineSegment) {
return Helpers.lineSegmentsIntersect(this.sX, this.sY, this.eX, this.eY, line.sX, line.sY, line.eX, line.eY);
}
let circle = shape as Circle;
if (circle instanceof Circle) {
return Helpers.lineIntersectsCircle(this.sX, this.sY, this.eX, this.eY, circle.x, circle.y, circle.r);
}
return false;
}
}
</code></pre>
<p>I don't really like this solution because there is a decent amount of code-duplication between all the classes. Imagine once rectangles and lines are added. Then again, I <em>also</em> want it to be as performant as possible. Any ideas on how to reduce the repetitiveness of this or increase the performance? Not really a fan of having to use <code>instanceof</code> and casting all over the place.</p>
|
[] |
[
{
"body": "<h2>Double dispatch</h2>\n<p>You can not avoid double dispatch as the collision type is unknown. The only way to avoid the double dispatch is to duplicate the collision tests for each object.</p>\n<p>Eg line check line circle and circle would check circle line</p>\n<pre><code>collidesWith(shape) { // implement for circle and line\n if (shape instanceof Circle) { \n /* code */ \n } else if (shape instanceof Line) { \n /* code */ \n } else ... and so on` \n\n</code></pre>\n<p>which in effect just hides the dispatch inline.</p>\n<h2>Language selection</h2>\n<blockquote>\n<p><em>"Then again, I also want it to be as performant as possible. Any ideas on how to reduce the repetitiveness of this or increase the performance?"</em></p>\n</blockquote>\n<p>Generally typescript can be a little slower depending on the style you use. It is most definitely a more verbose language than JS with the only advantage it has over JS is IDE integration.</p>\n<p>For the shortest source and best performance use JS.</p>\n<p>Please note I am very anti typescript.</p>\n<h2>Verbosity</h2>\n<blockquote>\n<p><em>"Not really a fan of having to use instanceof and casting all over the place."</em></p>\n</blockquote>\n<p>Begs the question "Why use typescript?" if you don't like casting.</p>\n<h2>Alternative to strong typing / classing</h2>\n<p>Good JavaScript OO code is polymorphic in nature, you can have as many object types as there are objects yet still have clearly defined behaviors.</p>\n<ul>\n<li><p>Drop the class syntax as it only limits Object design rather than improves it.</p>\n</li>\n<li><p>Use factories to define objects</p>\n</li>\n<li><p>Assign inherited properties to extend existing objects rather than build a static prototype chain.</p>\n</li>\n</ul>\n<h2>Example</h2>\n<p>Example source code implementing polymorphic <code>Shape</code> as <code>Point</code>, <code>Line</code>, <code>Circle</code></p>\n<ul>\n<li>Types are defined as an enum <code>TYPES</code></li>\n<li>Colliders are defined as named type pairs <code>Colliders</code></li>\n<li>The object <code>Shape</code> is assign the properties of a shape <code>Point</code>, <code>Line</code>, <code>Circle</code>.</li>\n<li>The object shape has the function <code>collidesWith</code> which check via the two shapes to test <code>type</code> if there is an assigned collider. If so it will call and return the result of the correct collider else false. To avoid duplication the function assumes that circle line collision is identical to line circle collision.</li>\n<li>Included a <code>toString</code> only for illustration and testing.</li>\n</ul>\n<p><strong>Notes</strong></p>\n<ul>\n<li><p><strong>Note</strong> that <code>Line</code> references <code>Point</code> <code>p1</code>, and <code>p2</code> but <code>Circle</code> becomes <code>Point</code> like. This was done partly to illiterate the different ways properties can be acquired and to reduce the complexity of the collision code (collision point line and point circle are very similar)</p>\n</li>\n<li><p><strong>NOTE</strong> The code may seam longer (verbose) but this is a simple example. Much of the factory's work can be automated.</p>\n</li>\n<li><p><strong>NOTE</strong> Be aware that property order can be important using this style. Ensure that the property assignments <code>{...obj}</code> do not overwrite type related properties</p>\n</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const TYPES = {\n circle: 1,\n point: 2,\n line: 3,\n};\n\nconst Colliders = {\n circleCircle(circle) { return circle.distFrom(this) <= circle.radius + this.radius },\n circlePoint(p) { return p.distFrom(this) <= this.radius },\n pointPoint(p) { return this.distFrom(p) < 0.5 },\n circleLine(line) {\n const v = line.asVec();\n const p1 = line.p1;\n const u = Math.max(0, Math.min(1, ((this.x - p1.x) * v.x + (this.y - p1.y) * v.y) / (v.y * v.y + v.x * v.x)));\n return (((p1.x + v.x * u) - this.x) ** 2 + ((p1.y + v.y * u) - this.y) ** 2) ** 0.5 < (this.radius ?? 0.5);\n },\n lineLine(line) { return false }, // todo \n};\n\nfunction Point(x, y) {\n const API = {\n distFrom(p) { return ((p.x - this.x) ** 2 + (p.y - this.y) ** 2) ** 0.5; },\n x, y,\n toString() { return \"Point: {x: \" + this.x + \", y: \" + this.y + \"}\" },\n type: TYPES.point,\n };\n API.colliders = {\n [TYPES.point]: Colliders.pointPoint.bind(API),\n [TYPES.line]: Colliders.circleLine.bind(API),\n };\n return API;\n}\nfunction Line(p1, p2) {\n const API = {\n asVec(v = Point()) {\n v.x = p2.x - p1.x;\n v.y = p2.y - p1.y;\n return v;\n },\n p1, p2,\n toString() { return \"Line : {p1: \" + this.p1 + \", p2: \" + this.p2 + \"}\" },\n type: TYPES.line, \n };\n API.colliders = { [TYPES.line]: Colliders.lineLine.bind(API) };\n return API;\n}\nfunction Circle(center, radius) {\n const API = {\n ...Point(center.x, center.y), // makes circle Point like\n radius,\n toString() { return \"Circle: {x: \" + this.x + \", y: \" + this.y + \", r: \" + this.radius + \"}\" },\n type: TYPES.circle,\n };\n API.colliders = {\n [TYPES.circle]: Colliders.circleCircle.bind(API),\n [TYPES.point]: Colliders.circlePoint.bind(API),\n [TYPES.line]: Colliders.circleLine.bind(API),\n };\n return API;\n}\nfunction Shape(shape) {\n return {\n collidesWith(cShape) { \n return this.colliders[cShape.type]?.(cShape) ?? cShape.colliders[this.type]?.(this) ?? false;\n },\n ...shape\n }; \n}\n\n\n//===========================================================================\n// TEST\n\nconst line = Shape(Line(Point(0,0), Point(100,100)));\nconst circle1 = Shape(Circle(Point(50, 0), 50));\nconst circle2 = Shape(Circle(Point(150, 0), 10));\nconst point = Shape(Point(50,25));\n\nlog(line + \"\");\nlog(circle1 + \"\");\nlog(circle2 + \"\");\nlog(point + \"\");\n\nlog(\"Line collides circle1: \" + line.collidesWith(circle1));\nlog(\"Point collides circle1: \" + point.collidesWith(circle1));\nlog(\"Line collides circle2: \" + line.collidesWith(circle2));\nlog(\"Point collides circle2: \" + point.collidesWith(circle2));\n\nlog(\"Circle1 collides line: \" + circle1.collidesWith(line));\nlog(\"Circle1 collides point: \" + circle1.collidesWith(point));\nlog(\"Circle2 collides line: \" + circle2.collidesWith(line));\nlog(\"Circle2 collides point: \" + circle2.collidesWith(point));\n\n\nfunction log(...a) { console.log(...a) }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T18:41:50.757",
"Id": "263562",
"ParentId": "263524",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T20:43:24.640",
"Id": "263524",
"Score": "1",
"Tags": [
"javascript",
"performance",
"typescript",
"casting"
],
"Title": "Checking if two shapes collide in TypeScript (double dispatch)"
}
|
263524
|
<pre><code>import axios from "axios";
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [count, setCount] = useState(1);
const [titles, setTitles] = useState([]);
useEffect(() => {
async function fetchData() {
const URL1 = `https://jsonplaceholder.typicode.com/todos/${count}`;
const URL2 = `https://jsonplaceholder.typicode.com/todos/${count + 1}`;
const apiData = await Promise.all([
axios.get(URL1),
axios.get(URL2)
]).then((res) => res.map((x) => x.data));
setTitles((prevTitles) => {
return [...prevTitles, ...apiData];
});
}
fetchData();
}, [count]);
const fetchMore = () => {
setCount(count + 2);
};
return (
<div className="App">
<div className="title">Fetch Todos</div>
<ul>
{titles &&
titles.map((x) => (
<li key={x.id}>
{x.id} - {x.title}
</li>
))}
</ul>
<button onClick={fetchMore}>Fetch More</button>
</div>
);
}
</code></pre>
<p>I am pretty sure that json calls are usually put in their own files, but I kinda forgot how to do it and what are the best practices concerning API calls.</p>
<p><a href="https://codesandbox.io/s/g8c7b?file=/src/App.js:0-1065" rel="nofollow noreferrer">https://codesandbox.io/s/g8c7b?file=/src/App.js:0-1065</a></p>
<p>I think where you put the json calls also depend on whether you use Redux or any other state management library.</p>
|
[] |
[
{
"body": "<p>I will first suggest some miscellaneous changes to the code and then answer your questions.</p>\n<h2>A better <code>count</code> handling</h2>\n<p>I think that naming the state <code>count</code> is a bit misleading because it is used as an offset to fetch the todos. This may count as a nit, but when you look at the code as a whole I think it is more accurate to use <code>offset</code> instead of <code>count</code>.</p>\n<p>Usually, when I have a bit of state that always mutates in the same way, I use <code>useReducer</code>. This way, the code looks a bit cleaner:</p>\n<pre><code>const [offset, doubleOffset] = useReducer((c) => c + 2, 1);\n...\n<button onClick={doubleOffset}>Fetch More</button>\n</code></pre>\n<p>In this particular case, we remove the need for a click handler. The updater function of <code>useReducer</code> is enough, and the code is more concise.</p>\n<hr />\n<h2>Space and unnecessary braces</h2>\n<p>This can also be a bit subjective, but I find that adding spaces and blank lines properly improves readability a lot. I would update your code to be like this, only adding blank lines and removing extra braces:</p>\n<pre><code> const [count, setCount] = useState(1);\n const [titles, setTitles] = useState([]);\n\n useEffect(() => {\n async function fetchData() {\n const URL1 = `https://jsonplaceholder.typicode.com/todos/${count}`;\n const URL2 = `https://jsonplaceholder.typicode.com/todos/${count + 1}`;\n\n const apiData = await Promise.all([\n axios.get(URL1),\n axios.get(URL2)\n ]).then((res) => res.map((x) => x.data));\n\n setTitles((prevTitles) => [...prevTitles, ...apiData]);\n }\n\n fetchData();\n }, [count]);\n\n const fetchMore = () => setCount(count + 2);\n</code></pre>\n<hr />\n<h2>Services</h2>\n<p>Usually, an easier way to think about interactions of your app with another app is to treat them as black boxes, which means trying to call functions so your component's logic is decoupled from other modules in your app, like handling API calls, or generating a pdf, or opening a WebSocket. This is called service because those functions provide <em>services</em> for your UI logic.</p>\n<p>This also means that it is easier to mock and test your code, so that is a plus. This allows for better code colocation, because usually, services group code that is related, so it is easier to have a wider view of the abstraction.</p>\n<p>I know that I am using somewhat subjective terms here, but I hope you'll understand what I mean with the code examples.</p>\n<h3>Todos API</h3>\n<p>In this particular example, the service would be the interface with the Todos API. So I think that it's fair to extract that logic to a separate file.</p>\n<p>Let's call the service <code>todosApi</code> and the containing file <code>todosApi.js</code>. Inside this file, we will define the functions that our service exposes and export an object for components to use.</p>\n<p>Usually, different services that are related are placed in the same folder, for example, say we have a <code>likes</code> API that we want to query besides our <code>todos</code> API. Then we would have an <code>index.js</code> re-exporting those services so that we have auto-import and autocomplete in our IDE.</p>\n<pre class=\"lang-js prettyprint-override\"><code>// todosApi.js\nimport axios from 'axios';\n\nconst getTodoById = id => { ... };\n\nexport const todosApi = {\n getTodoById\n};\n</code></pre>\n<h3>Using the service</h3>\n<p>Now that we have our service setup, we use it inside our component:</p>\n<pre class=\"lang-js prettyprint-override\"><code> // App.js\n useEffect(() => {\n async function fetchData() {\n const apiData = await todosApi.getTodoById(offset);\n ...\n }\n\n fetchData();\n }, [ ... ]);\n</code></pre>\n<p><em>Notice that this removes the need to import <code>axios</code> in our component</em>.</p>\n<hr />\n<h2>A better structure</h2>\n<p>Personally, I think that code split into simple, well-defined functions is a bit better than having logic pervading the codebase, so I polished the code until I was comfortable with it. My fork is <a href=\"https://codesandbox.io/s/two-apis-at-a-time-react-hooks-forked-h6qkq?file=/src/App.js\" rel=\"nofollow noreferrer\">here</a>.</p>\n<pre><code>// todosApi.js\nimport axios from "axios";\n\nconst getTodoById = (id) =>\n axios\n .get(`https://jsonplaceholder.typicode.com/todos/${id}`)\n .then((res) => res.data);\n\nconst fetchTodoPair = (offset) =>\n Promise.all([getTodoById(offset), getTodoById(offset + 1)]);\n\nexport const todosApi = {\n getTodoById,\n fetchTodoPair\n};\n</code></pre>\n<pre><code>// App.js\nimport { useEffect, useReducer, useState } from "react";\nimport { todosApi } from "./todosApi";\nimport "./styles.css";\n\nexport default function App() {\n const [offset, doubleOffset] = useReducer((c) => c + 2, 1);\n const [titles, setTitles] = useState([]);\n\n useEffect(() => {\n const fetchTodoPair = async () => {\n const newTitles = await todosApi.fetchTodoPair(offset);\n\n setTitles((prevTitles) => [...prevTitles, ...newTitles]);\n };\n\n fetchTodoPair();\n }, [offset]);\n\n return (\n <div className="App">\n <div className="title">Fetch Todos</div>\n <ul>\n {titles &&\n titles.map((x) => (\n <li key={x.id}>\n {x.id} - {x.title}\n </li>\n ))}\n </ul>\n <button onClick={doubleOffset}>Fetch More</button>\n </div>\n );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T01:38:29.387",
"Id": "263530",
"ParentId": "263525",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263530",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T20:58:14.757",
"Id": "263525",
"Score": "1",
"Tags": [
"react.js",
"api",
"jsx"
],
"Title": "React component with axios calls"
}
|
263525
|
<p>My hobby is Unix-like operating systems.</p>
<p>Recently I began writing my own sel4-based Posix compliant OS. Here's the code for internal signal handling functions which presents a kind of backend to help implement functions such as <code>do_kill</code> or <code>do_sigsuspend</code>.</p>
<p>I would like to know what you think about code quality, and any possible errors I've overlooked.</p>
<pre><code>#include "process_definitions.hxx"
#include <signal.h>
#include <array>
#include "signal_definitions.hxx"
#include <sys/types.h>
#include <unistd.h>
#include <kernel_glue.hxx>
using namespace process_methods;
std::array<int, 256> signal_num ;
std::array<pid_t, 256> receiver ;
sigset_t signals_methods::signal_queue::dump_pending(pid_t pid)
{
sigset_t retval;
for (int init = 256; init-- ;)
{
if (receiver[init] == pid )
{
int index = (signal_num[init] / sizeof(sigset_t));
*(retval.__val) = *(retval.__val) & (1 << signal_num[init]);
}
}
return retval;
}
void signals_methods::signal_queue::aggregate_signal_queue()
{
for (int init = 256 ; init--;)
{
send_signal(receiver[init], signal_num[init]);
receiver[init] = 0 ;
signal_num[init] = 0;
}
}
void signals_methods::signal_queue::put_signal_to_queue(pid_t pid, int signal)
{
for (int init = 256; init--;)
{
if (signal_num[init] == 0 && receiver[init] == 0)
{
signal_num[init] = signal;
receiver[init] = pid;
}
}
};
signal_data_struct *signals_methods::get_signal_info(pid_t pid)
{
return &get_process_info(pid)->signal_data;
}
signal_data_struct *signals_methods::get_signal_info()
{
return &get_process_info()->signal_data;
}
void signals_methods::send_signal(pid_t pid, int signal)
{
if (!(get_signal_info(pid)->signal_flags[signal] & (1 << SA_NOMASK)))
{
if (*(get_signal_info(pid)->blocked_mask.__val) & (1 << signal))
{
signals_methods::signal_queue::put_signal_to_queue(pid, signal); //signal is blocked so wait while it will be unblocked
return;
}
}
get_signal_info(pid)->blocked_mask = get_signal_info(pid)->signal_mask[signal];
if (get_signal_info(pid)->handler[signal] == SIG_DFL )
{
exec_default_signal_handler( pid, signal);
return;
}
if (get_signal_info(pid)->handler[signal] == SIG_IGN)
{
return;
}
if(get_signal_info(pid)->thread_suspend_lock)
{
thread_restore(pid);
}
if (get_signal_info(pid)->signal_flags[signal] & SA_SIGINFO)
{
exec_signal_handler_siginfo(pid, &get_signal_info(pid)->handler[signal], signal, &(get_signal_info(pid)->siginfo[signal]));
}
else
{
exec_signal_handler(pid, signal, &get_signal_info(pid)->handler[signal]);
}
}
void signals_methods::exec_default_signal_handler(pid_t pid, int signal)
{
#define dump 0
#define revoke 1
#define stop 2
#define cont 3
#define ign 4
int sigmode [] = {
[SIGABRT] = dump,
[SIGBUS] = dump,
[SIGFPE] = dump,
[SIGILL] = dump,
[SIGQUIT] = dump,
[SIGSEGV] = dump ,
[SIGSYS] = dump ,
[SIGTRAP] = dump ,
[SIGXCPU] = dump ,
[SIGXFSZ] = dump ,
[SIGALRM] = revoke,
[SIGHUP] = revoke,
[SIGINT] = revoke,
[SIGKILL] = revoke,
[SIGPIPE] = revoke,
[SIGTERM] = revoke,
[SIGUSR1] = revoke,
[SIGUSR2] = revoke,
[SIGPOLL] = revoke,
[SIGPROF] = revoke,
[SIGVTALRM] = revoke,
[SIGSTOP] = stop,
[SIGTSTP] = stop ,
[SIGTTIN] = stop,
[SIGTTOU] = stop,
[SIGCONT ] = cont,
[SIGURG] = ign
};
if (!(get_signal_info(pid)->signal_flags[signal] & SA_NOCLDSTOP))
{
signals_methods::signal_queue::put_signal_to_queue(SIGCHLD, get_process_info(pid)->parent_pid);
//get_signal_info(get_process_info(pid)->parent_pid)->siginfo[SIGCHLD]._sifields)
}
switch (sigmode[signal])
{
case dump:
thread_dump(pid);
break;
case revoke:
thread_revoke(pid);
break;
case stop:
thread_stop(pid);
break;
case cont:
thread_restore(pid);
default:
return;
break;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T22:22:47.863",
"Id": "520253",
"Score": "0",
"body": "no, my code is working how it must. me simply interesting how i can improve alghroritm"
}
] |
[
{
"body": "<p>What are the magic numbers 256 scattered all over the place? If they all mean the same thing (number of supported distinct signals?), then name a constant. If they have more than one meaning, then there's even more reason to use well-named constants.</p>\n<p>I don't like these:</p>\n<blockquote>\n<pre><code>#define dump 0\n#define revoke 1\n#define stop 2\n#define cont 3\n#define ign 4\n</code></pre>\n</blockquote>\n<p>We normally use ALL_CAPS for macros (since they require particular care and attention). But really there's no need to use the preprocessor for this. An ordinary <code>enum</code> is much more appropriate - for one thing, it allows the compiler to ensure that all cases are handled in the <code>switch</code> further on:</p>\n<pre><code> switch (sigmode[signal])\n {\n case dump:\n thread_dump(pid);\n break;\n case revoke:\n thread_revoke(pid);\n break;\n case stop:\n thread_stop(pid);\n break;\n case cont:\n thread_restore(pid);\n break;\n case ign:\n return;\n }\n</code></pre>\n<p>(I also removed the unreachable <code>break</code> statement that followed <code>return</code> there, and eliminated the fall-through that might catch out somebody adding another case in future.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T01:04:49.153",
"Id": "520357",
"Score": "0",
"body": "Thanks, that was very helpfully.\nAnd about \"magic 256\", is just a length for signal queue."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T12:53:07.817",
"Id": "263549",
"ParentId": "263526",
"Score": "2"
}
},
{
"body": "<p>Toby's answer mentioned the high use of the magic constant <code>256</code>.</p>\n<p>I think you should at the very least use <code>signal_num.size()</code> and the like, so that the number only appears in the array definition. Even then, since you have multiple arrays that are the same size, you should name a constant like <code>signal_count</code>.</p>\n<p>Where you are looping over the entire array, it would be better if you could use the range-based <code>for</code> statement. Combining the test and decrement with the test is odd enough. Since you seem to always be iterating backwards, perhaps you should store them in the opposite order? Then just transform the argument for the calls that get/set values by signal number.</p>\n<hr />\n<p><code>signal_data_struct *signals_methods::get_signal_info(pid_t pid)</code><br />\nIn C++, unlike C, it's orthodox to put the <code>*</code> <em>with the type</em> not with the variable (or function name in this case). Write <code>signal_data_struct* foo</code>. But why aren't you defining the functions to return references, rather than pointers?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:12:26.157",
"Id": "263554",
"ParentId": "263526",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T21:04:44.633",
"Id": "263526",
"Score": "3",
"Tags": [
"c++",
"posix",
"kernel",
"signal-handling"
],
"Title": "Posix signal implementation"
}
|
263526
|
<p>I have been working on this project for a little bit and it's my first major python program. It downloads information about current and upcoming weather warnings for Ireland and displays them with tkinter. Would be grateful of suggestions or critique!</p>
<p><a href="https://github.com/Sn4u/met-eireann-status/tree/master" rel="nofollow noreferrer">https://github.com/Sn4u/met-eireann-status/tree/master</a></p>
<p><strong>met_eireann_status.py</strong></p>
<pre><code>import requests
import json
import tkinter
from tkinter import ttk, messagebox
from datetime import datetime
import textwrap
from os import getcwd
from randomise_demo import randomise_demo_dates
# read json files with weather information
with open(getcwd() + '\\' + "region_codes.json", "r") as file:
REGION_CODES = json.loads(file.read())
with open(getcwd() + '\\' + "marine_codes.json", "r") as file:
MARINE_CODES = json.loads(file.read())
dimensions = {"width": "60", "height": "10", }
style_no_warning = {"foreground": "black", "background": "green", "font": "Helvetica 11 bold"}
style_bold = {"font": "Helvetica 9 bold"}
level_to_style = {
"Yellow": {"foreground": "Black", "background": "yellow"},
"Orange": {"foreground": "Black", "background": "orange"},
"Red": {"foreground": "Black", "background": "red"},
}
obj_dict = {} # Card:WarningInfo
class WarningInfo:
"""Stores necessary weather warning information"""
def __init__(self, json_data):
print(json_data)
self.cap_id = json_data['capId']
self.id = json_data['id']
self.type = json_data['type']
self.severity = json_data['severity']
self.certainty = json_data['certainty']
self.level = json_data['level']
self.issued = json_data['issued']
self.updated = json_data['updated']
self.onset = json_data['onset']
self.expiry = json_data['expiry']
self.headline = json_data['headline']
self.description = json_data['description']
self.regions = json_data['regions']
self.status = json_data['status']
self.delta = None
self.delta_msg = None
self.style = level_to_style[self.level]
if update_time(self) == 'expired':
print("warning is expired")
else:
Card().make(self)
class Card:
def __init__(self):
self.frame = tkinter.Frame(root, **dimensions, bg="#CDCDCD")
self.frame.pack(fill='both', expand=True)
self.primary = None
self.headline_label = None
self.primary_info_frame = None
self.certainty_frame = None
self.delta_frame = None
self.severity_frame = None
self.certainty_label = None
self.certainty_text = None
self.delta_label = None
self.delta_text = None
self.severity_label = None
self.severity_text = None
self.secondary = None
self.dates_frame = None
self.issued_text = None
self.issued_time = None
self.expiry_text = None
self.expiry_time = None
self.desclabel = None
def make(self, data: WarningInfo):
obj_dict[self] = data
self.primary = tkinter.Frame(self.frame, background=data.level, **dimensions)
self.primary.pack(fill='both', side='left')
self.primary.bind('<Button-1>', self.display_extra)
self.headline_label = tkinter.Label(self.primary, data.style, text=data.headline, justify='center',
wraplength=500, font=('Helvetica', 11, 'bold'), width=59)
self.headline_label.pack(side='top')
self.primary_info_frame = tkinter.Frame(self.primary, background=data.level)
self.certainty_frame = tkinter.Frame(self.primary_info_frame)
self.delta_frame = tkinter.Frame(self.primary_info_frame)
self.severity_frame = tkinter.Frame(self.primary_info_frame)
self.primary_info_frame.pack(side='left')
self.certainty_frame.pack(side='left')
self.delta_frame.pack(side='left')
self.severity_frame.pack(side='left')
self.certainty_label = tkinter.Label(self.certainty_frame, data.style, text="Certainty: ")
self.certainty_text = tkinter.Label(self.certainty_frame, data.style, font=('Helvetica', 9, 'bold'),
text=data.certainty)
self.certainty_label.pack(side='left')
self.certainty_text.pack(side='left')
self.delta_label = tkinter.Label(self.delta_frame, data.style, text=data.delta_msg)
self.delta_text = tkinter.Label(self.delta_frame, data.style, text=data.delta,
font=('Helvetica', 9, 'bold'))
self.delta_label.pack(side='left')
self.delta_text.pack(side='left')
self.severity_label = tkinter.Label(self.severity_frame, text="Severity: ")
self.severity_text = tkinter.Label(self.severity_frame, data.style, font=('Helvetica', 9, 'bold'),
text=data.severity)
self.headline_label.bind('<Button-1>', self.display_extra)
# secondary
self.secondary = tkinter.Frame(self.frame, **dimensions, relief=tkinter.SUNKEN, borderwidth=4)
self.dates_frame = tkinter.Frame(self.secondary)
self.issued_text = tkinter.Label(self.dates_frame, text='Issued: ')
self.issued_time = tkinter.Label(self.dates_frame, text=friendly_time(data.issued),
font=('Helvetica', 9, 'bold'))
self.expiry_text = tkinter.Label(self.dates_frame, text='Expiry: ')
self.expiry_time = tkinter.Label(self.dates_frame, text=friendly_time(data.expiry),
font=('Helvetica', 9, 'bold'))
self.dates_frame.pack(side='top')
self.issued_text.pack(side='left')
self.issued_time.pack(side='left')
self.expiry_text.pack(side='left')
self.expiry_time.pack(side='left')
self.desclabel = tkinter.Label(self.secondary, text=self.format_description(data),
height=4)
self.desclabel.pack(side='bottom')
self.secondary.visible = False
def delete(self):
self.frame.destroy()
def display_extra(self, _):
"""toggle secondary panel visibility"""
def forget_old():
self.certainty_frame.pack_forget()
self.delta_frame.pack_forget()
if self.secondary.visible is False:
self.secondary.pack(fill='both', side='right', expand=True)
forget_old()
self.certainty_frame.pack(side='top', anchor='w')
self.delta_frame.pack(side='top', anchor='w')
else:
self.secondary.pack_forget()
forget_old()
self.certainty_frame.pack(side='left')
self.delta_frame.pack(side='left')
self.secondary.visible = not self.secondary.visible
def format_description(self, warn: WarningInfo):
return textwrap.TextWrapper(max_lines=3).fill(text=warn.description)
def create_non_warning(self, message, style=None):
obj_dict[self] = None
if style is None:
style = style_no_warning
self.frame.configure(height=10, width=60)
self.headline_label = tkinter.Label(self.frame, style, text=message)
self.headline_label.pack(fill='both', expand=True)
def rdel():
"""recursively delete all Warning_info and Card objects"""
for card in obj_dict:
card.frame.destroy()
obj_dict.clear()
def download_json(selected_region):
if selected_region == "Demo":
with open(getcwd() + '\\' + "demo_weather_warning.json", "r") as f:
response = json.loads(f.read())
else:
if selected_region in REGION_CODES:
areacode = REGION_CODES[selected_region]
else:
areacode = MARINE_CODES[selected_region]
Card().create_non_warning(message="Feature Unsupported!")
return
met_url = f"https://www.met.ie/Open_Data/json/warning_{areacode}.json"
try:
response = requests.get(met_url).json() # downloads latest json from api with given region
except requests.exceptions.ConnectionError:
tkinter.messagebox.showerror(title='Warning_info',
message='Could not reach Met Eireann API. Please try again later')
return
return response
def friendly_time(date_input):
"""format time to be displayed on warning card
Example: 2021-02-21T14:45:06-00:00 -> Feb 21 At 14:45"""
date_object = datetime.strptime(date_input, '%Y-%m-%dT%H:%M:%S%z')
return date_object.strftime('%b %d At %H:%M')
def update_time(obj: WarningInfo):
"""For every warning object, compare current time to expiration time to check if warning is expired.
If expired, return 'expired'. Otherwise check if warning is in place or not in place yet
and assign time delta and correct label to the object attribute"""
t_format = '%Y-%m-%dT%H:%M:%S'
current_time = datetime.now()
# remove utc offset from times
onset_time = datetime.strptime(obj.onset[:-6], t_format)
expiry_time = datetime.strptime(obj.expiry[:-6], t_format)
if current_time > onset_time and current_time > expiry_time:
# we are past both the onset and the expiration
# destroy tkinter warning widgets and remove Warnings object.
return "expired"
elif current_time > onset_time:
# warning is in place but not expired
# display time until expiration
obj.delta = ':'.join(str(expiry_time - current_time).split(':')[:2])
obj.delta_msg = 'Time until expiration: '
else:
# warning is not in place yet
# display time until warning onset
obj.delta = ':'.join(str(onset_time - current_time).split(':')[:2])
obj.delta_msg = 'Time until onset: '
def flash_red():
"""Make the headline of warning card flash red and white"""
for card, info in obj_dict.items():
try:
if info.level == "Red":
if card.headline_label["background"] != '#be0000':
card.headline_label.configure(backgroun='#be0000')
else:
card.headline_label.configure(background='red')
except AttributeError:
pass
def refresh(_=None):
"""Called when refresh button is pressed. Deletes all card objects and displays new ones"""
rdel()
randomise_demo_dates()
selected_region = combox.get() # gets the selected region from combo box
response = download_json(selected_region)
if response is None:
return None
# if there are no warnings, display it as a message
if len(response) == 0:
Card().create_non_warning(message="There are no warnings for the selected region")
else:
create_object(response, selected_region)
def create_object(response, selected_region):
"""creates a WarningInfo class object for all warnings that match chosen location"""
for dict_entry in response:
if selected_region == 'Demo' or selected_region == "All counties":
WarningInfo(dict_entry)
elif REGION_CODES[selected_region] in dict_entry['regions']:
print(REGION_CODES[selected_region])
WarningInfo(dict_entry)
def update_combox_val():
"""Changes between marine zones and counties to be displayed on the combo box widget"""
sea_val = sea_box_val.get()
if sea_val == 1:
combox.configure(values=[i for i in MARINE_CODES.keys()])
location_label.configure(text="Select Marine Zone: ")
else:
combox.configure(values=[i for i in REGION_CODES.keys()])
location_label.configure(text="Select County: ")
def info_action():
info_window = tkinter.Toplevel()
info_window.title('Information')
info_window.iconbitmap("Assets/MetEireann logo-02.ico")
info_text = tkinter.Label(info_window, justify='left', wraplength=666)
with open(getcwd() + '\\' + "info.txt", "r") as text:
info_text['text'] = text.read()
info_text.pack()
info_btn['state'] = 'disabled'
info_btn['relief'] = 'sunken'
def info_close():
info_btn['state'] = 'normal'
info_btn['relief'] = 'raised'
info_window.destroy()
info_window.protocol("WM_DELETE_WINDOW", info_close)
# GUI
root = tkinter.Tk()
root.resizable(False, False)
root.title("Met Eireann Status")
root.iconbitmap("Assets/MetEireann logo-02.ico")
options_frame = tkinter.LabelFrame(root, relief=tkinter.RAISED, borderwidth=5)
options_frame.pack(fill='x')
location_label = tkinter.Label(options_frame, text="Select County:", width=14)
location_label.grid(column=0, row=0, padx=5, pady=4)
combox = tkinter.ttk.Combobox(options_frame, values=[i for i in REGION_CODES.keys()], state="readonly")
combox.current(27) # sets default for the combo box
combox.grid(column=1, row=0, padx=5, pady=4)
refresh_button = tkinter.Button(options_frame, text='Refresh', command=refresh)
refresh_button.grid(column=3, row=0, padx=4, pady=5)
root.bind('<Return>', refresh)
sea_box_val = tkinter.IntVar()
sea_check_box = tkinter.Checkbutton(options_frame, variable=sea_box_val, text="Search Marine Warnings",
command=update_combox_val)
sea_check_box.grid(column=4, row=0)
info_btn = tkinter.Button(options_frame, bitmap="info", width=25, command=info_action)
info_btn.grid(column=6, row=0, padx=4)
def tick():
root.after(1000, tick)
flash_red()
tick()
root.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T22:17:51.083",
"Id": "520251",
"Score": "1",
"body": "Welcome to Codereview, and great first question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T22:50:03.543",
"Id": "520254",
"Score": "0",
"body": "I'm worried that I didn't ask a specific enough question and included too much code. Let me know if this is the case and I will include more background information and my concerns regarding the project"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T22:15:22.847",
"Id": "263528",
"Score": "2",
"Tags": [
"python",
"tkinter",
"gui"
],
"Title": "Irish Weather Warnings App in Tkinter"
}
|
263528
|
<p>I have a class that is importing a CSV file into a Pandas DataFrame. However, this CSV has a multiline header that changes length seemingly at random. Sometimes it is 27 lines, sometimes 31, sometimes something else. It is just dirty data in so many other ways as well, look at the header separator.</p>
<p>As a result, the code that I have got working has this file being read three times. The first time is to check the length of the header, the second is to read the body of data into one DataFrame, and the third is to read the Header into another DataFrame (this is later parsed out into a dictionary, but it is super messy and I find it easiest to do it this way. The code I have is below (taken from a larger class, I can add more of the class if required.):</p>
<pre><code>"""
Program to import and process Valeport SVP files
"""
import pandas as pd
from dateutil import parser
from icecream import ic
class ValeportSVPImport:
"""
Importer Class for Valeport .000 format SVP files
The header header is parsed off the main body of data.
The data is added to a Pandas DataFrame
The processed header data is exported as a dictionary.
- Keys - Valeport Settings
- Values - Values from the profile
"""
def __init__(self, path):
"""
Set up for the
:param path: Filepath of the .000 file that is to be parsed
:return data: Pandas DataFrame containing the SVP Raw data.
:return header_dict: Dictionary containing the SVP header data.
"""
self.path = path
# Find header length, even if irregular
self.header_size = self.__header_size__()
# split data into the header and the import
self.data, self.header = self.__import_svp__()
# Parse the relevant information out of the header
self.header_dict = self.__parse_header__()
def __header_size__(self):
"""
Finds the header row for the data
The size of the header file in a .000 file can change, this code takes that into account
:return: number of header row
"""
with open(self.path, "r") as filename:
lines = filename.readlines()
i = 0
for line in lines:
split = line.split('\t')
if len(split) == 9:
break
else:
i = i + 1
return i
def __import_svp__(self):
"""
Parse the CSV files into Pandas DataFrames
:return: DataFrame (data) - RAW SVP Data, DataFrame (data_header) RAW Header Data
"""
i = self.header_size
# Import body of data
data = pd.read_csv(self.path, sep=r"\t", header=i, engine='python')
# Drop any columns that are completed void
data = data.dropna(axis=1, how='all')
# Import the header
data_header = pd.read_csv(self.path, sep=':\t', nrows=i - 1, header=None, engine='python')
return data, data_header
def __parse_header__(self):
"""
Strip out all of the relevant header material.
:return: Dictionary - {Setting: Value}
"""
df = self.header
df.columns = ['KEY', 'VALUE']
df['KEY'] = df['KEY'].str.strip(':')
df['KEY'] = df['KEY'].str.strip()
# Rows from the header that will be added into the header dictionary
required_data = ['Model Name', 'Site Information', 'Serial No.', 'Sample Mode',
'Tare Setting', 'Tare Time Stamp', 'Density', 'Gravity', 'Time Stamp']
# return a dict of {Key Name : [Line Number, Value]
header_dict = {x: [df[df['KEY'] == x].index[0], df['VALUE'].iloc[df[df['KEY'] == x].index[0]]]
for x in required_data}
# Turn timestamp into a DateTime string
header_dict['Time Stamp'][1] = parser.parse(header_dict['Time Stamp'][1])
# Process Tare Date/Time
header_dict['Tare Time Stamp'][1], header_dict['Tare Setting'][1] = self.__tare_time__(header_dict)
# Remove the line number out of the dictionary before it is returned
return {k: header_dict[k][1] for k in header_dict}
@staticmethod
def __tare_time__(header_dict):
"""
Process the Tare data out of the header.path
- Sometimes the Tare time and data is in with the settings, other times it is not.
- In both cases the Time and Date are parsed into DateTime format.
:param header_dict: Dictionary containing all header information.
:return: Tare DateTime, Tare Vale
"""
# If the
if header_dict['Tare Time Stamp'][1] is None and len(header_dict['Tare Setting'][1].split(';')) == 2:
tare_split = header_dict['Tare Setting'][1].split(';')
tare_dt = parser.parse(tare_split[1])
tare_setting = float(tare_split[0])
else:
tare_dt = parser.parse(header_dict['Tare Time Stamp'][1])
tare_setting = float(header_dict['Tare Setting'])
return tare_dt, tare_setting
if __name__ == '__main__':
svp = ValeportSVPImport(path=r"C:\Users\...")
ic(svp.header_dict)
ic(svp.data)
</code></pre>
<p>Below is an example of the data that I am trying to import:</p>
<pre><code>Previous File Location : 0
No of Bytes Stored in Previous File : 0
Model Name : MIDAS SVX2 3000
File Name : C:\....
Site Information : xxx
Serial No. : 41850
No. of Modules Connected :
Fitted Address List :
Parameters for each module :
User Calibrations :
Secondary Cal Used :
Gain :
Offset :
Gain Control Settings :
SD Selected Flag :
Average Mode : NONE
Moving Average Length: 1
Sample Mode : CONT
Sample Interval : 1
Sample Rate : 1
Sample Period : 1
Tare Setting : 10.822;15/06/2021 06:20:05
Tare Time Stamp :
Density :
Gravity :
Time Stamp : 15/06/2021 07:51:17
External PSU Voltage : 24.553
Date / Time SOUND VELOCITY;M/SEC PRESSURE;DBAR TEMPERATURE;C CONDUCTIVITY;MS/CM Calc. SALINITY;PSU Calc. DENSITY;KG/M3 Calc. SOUND VELOCITY;M/SEC
15/06/2021 07:51:17 0.000 0.006 24.021 0.002 0.012 -2.698 1494.063
15/06/2021 07:51:18 0.000 -0.002 24.023 0.002 0.012 -2.699 1494.069
15/06/2021 07:51:19 0.000 0.015 24.025 0.002 0.012 -2.699 1494.074
15/06/2021 07:51:20 0.000 0.019 24.025 0.002 0.012 -2.699 1494.074
15/06/2021 07:51:21 0.000 -0.012 24.026 0.002 0.012 -2.700 1494.077
15/06/2021 07:51:22 0.000 0.007 24.025 0.002 0.012 -2.699 1494.074
15/06/2021 07:51:23 0.000 0.008 24.028 0.002 0.012 -2.700 1494.082
15/06/2021 07:51:24 0.000 0.009 24.029 0.002 0.012 -2.700 1494.085
15/06/2021 07:51:25 0.000 0.002 24.028 0.002 0.012 -2.700 1494.082
15/06/2021 07:51:26 0.000 0.002 24.024 0.002 0.012 -2.699 1494.071
</code></pre>
<p>and</p>
<pre><code>Previous File Location : 786432
No of Bytes Stored in Previous File : 0
Model Name : MIDAS SVX2 3000
File Name : UNKNOWN
Site Information : xxxx
Serial No. : 29681
No. of Modules Connected : 3
Fitted Address List : 12;21;49;
Parameters for each module : 1;2;1;
User Calibrations :
15;0.000000e+00;0.000000e+00;0.000000e+00;0.000000e+00;1.000000e+00;0.000000e+00
15;0.000000e+00;0.000000e+00;0.000000e+00;0.000000e+00;1.000000e+00;0.000000e+00
15;0.000000e+00;0.000000e+00;0.000000e+00;0.000000e+00;1.000000e+00;0.000000e+00
15;0.000000e+00;0.000000e+00;0.000000e+00;0.000000e+00;1.000000e+00;0.000000e+00
Secondary Cal Used : 1;0;0;1;1;0;1;0;0;
Gain : 1000;0;0;10000;1000;0;500;0;0;
Offset : 0;0;0;0;-20000;0;-20000;0;0;
Gain Control Settings : 226;19;0;
SD Selected Flag : 1
Average Mode : NONE
Moving Average Length : 1
Sample Mode : CONT
Sample Interval : 60
Sample Rate : 1
Sample Period : 1
Tare Setting : 10.353
Tare Time Stamp : 15/06/2021 07:20:18
Density : 1027.355
Gravity : 9.807
Time Stamp : 15/06/2021 07:21:52
External PSU Voltage : 11
Date / Time SOUND VELOCITY;M/SEC PRESSURE;DBAR TEMPERATURE;C CONDUCTIVITY;MS/CM Calc. SALINITY; PSU Calc. DENSITY ANOMALY; KG/M3 [EOS-80] Calc. SOS; M/SEC
15/06/2021 07:21:52.000 0.000 0.019 24.309 0.000 0.012 -2.769 1494.852
15/06/2021 07:21:53.000 0.000 -0.002 24.310 0.000 0.012 -2.770 1494.855
15/06/2021 07:21:54.000 0.000 0.012 24.311 -0.002 0.012 -2.770 1494.858
15/06/2021 07:21:55.000 0.000 0.008 24.315 0.000 0.012 -2.771 1494.868
15/06/2021 07:21:56.000 0.000 0.006 24.325 0.000 0.012 -2.774 1494.896
15/06/2021 07:21:57.000 0.000 0.004 24.324 0.000 0.012 -2.773 1494.893
</code></pre>
<p>The program as a whole is starting to get quite large and is slowing down a bit, so I am going back over it to spot any choke points. Hoping this is one of them.</p>
<p>Any suggestions would be greatly welcomed.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T00:04:03.097",
"Id": "520255",
"Score": "1",
"body": "I think this would benefit from some sample data. Ideally, this would be done not in an attached file but just formatted as code, with as few headers and data as possible while still conveying the complexity as the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T00:22:01.153",
"Id": "520256",
"Score": "0",
"body": "@Kraigolas - Good point. Data examples now added"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T00:30:16.933",
"Id": "520258",
"Score": "0",
"body": "Other notes: 1) We would probably benefit from having the whole class. It would be nice to see the expected output or even be able to run the code ourselves. 2) \"So I am going back over it to spot any choke points. Hoping this is one of them.\" is a bad strategy. Python provides cProfile to profile your code. Always use a profiler to see where the choke points are instead of guessing, cProfile is not very difficult to get started with. It's made to be easy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T00:40:32.590",
"Id": "520259",
"Score": "1",
"body": "@Kraigolas - Thanks for the tip about cProfile, I will look into that. I have also added the entire class now, so hopefully, that will help. This is just one class in a larger program that is way too chunky to upload here (and I haven't uploaded it to GitHub yet, so can't add a link to that)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T04:38:05.920",
"Id": "520356",
"Score": "0",
"body": "The sample data doesn't appear to contain any `\\t`s in it. So the code doesn't parse the sample data correctly."
}
] |
[
{
"body": "<p>Per PEP 8, never use leading and trailing double underscores in names of your own functions or methods. They are for python's magic methods. If you want to indicate a method is protected (not the public API, but useable by subclasses), use a single leading underscore. To indicate it is private (not for use by a subclass) use a leading double underscore (but not trailing).</p>\n<p><code>open()</code> returns a file object; <code>filename</code> is a mis-descriptive variable name.</p>\n<p>Don't use <code>readlines()</code> to slurp the entire file into a list and then iterate over the list of lines. Iterate over the file directly.</p>\n<p>Use <code>enumerate()</code> instead of a loop counter. So, <code>__header_size__()</code> could be somethings like:</p>\n<pre><code>def _header_size(self):\n with open(self.path, "r") as datafile:\n for i, line in enumerate(datafile):\n parts = line.split('\\t')\n if len(parts) == 9:\n break\n return i\n</code></pre>\n<p>The first argument to <code>read_csv()</code> can be a file-like object, e.g an object with a <code>read()</code> method (like an open file or StringIO). So, the strategy for reading these data files in a single pass is to read the data file line-by-line parsing the header as you go. When you reach the line with the column names, parse the column names. Then let <code>read_csv()</code> parse the table.</p>\n<pre><code># These are the keys in the header that we care about\nHEADER_KEYS = ['Model Name', 'Site Information', 'Serial No.',\n 'Sample Mode', 'Tare Setting', 'Tare Time Stamp',\n 'Density', 'Gravity', 'Time Stamp']\n\n\nclass ValeportSVPImport:\n\n def __init__(self, path):\n self.header = dict.fromkeys()\n \n with open(path) as datafile:\n for line in datafile:\n # is this line the start of the data table?\n # original code used `if len(line.split('\\t') == 9:`\n if line.startswith('Date / Time'):\n columns = parse_column_names(line)\n break\n \n # is this part of a key : value pair?\n if ':' in line:\n key, value = line.split(':', maxsplit=1)\n key = key.strip()\n \n # is it a key we're interested in?\n if key in header:\n self.header[key] = value.strip()\n\n self.data = pd.read_csv(f, sep='\\s+', header=None, names=columns)\n</code></pre>\n<p>Note 1: I didn't implement <code>parse_column_names()</code> because the sample data appears to be missing the '\\t' characters.</p>\n<p>Note 2: If the line with the column names can be parsed with the data by <code>read_csv()</code> you could use <code>datafile.tell()</code> before reading every line and <code>datafile.seek()</code> to backup in the file and then let <code>read_csv()</code> read the column names and the data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T08:13:35.900",
"Id": "263576",
"ParentId": "263529",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T23:40:31.237",
"Id": "263529",
"Score": "0",
"Tags": [
"python",
"pandas",
"dynamic-loading",
"data-importer"
],
"Title": "Multiple CSV Imports with Pandas"
}
|
263529
|
<p>I'm a beginner in programming and I'm figuring out what is the best approach for my mini e commerce site project.</p>
<p>My current approach is</p>
<pre class="lang-html prettyprint-override"><code>{% for i in item %} <!-- where item = database fetchall -->
<h3> {{i[0]}} </h3> <!-- product name -->
<p> {{i[3]}} / kg</p> <!-- product price -->
<form action = "/send" method = "post">
<input type = "number" class = "form-control" min = 0 max = 100>
</input>
<button type = "submit" class = "btn btn-primary">Add to cart </button>
{% endfor %}
</code></pre>
<p>Something similar to that, and I'm doing all the work (shop, cart, checkout) with python and flask session.</p>
<p>This is my whole backend for storing session</p>
<pre class="lang-py prettyprint-override"><code>def sendPage():
if "iterate" in session:
pass
elif "iterate" not in session:
session["item"] = []
session["iterate"] = "no"
if request.method == "POST":
for i in result:
try:
if f"{i[0]}qty" in session:
session[f"{i[0]}qty"] += int(request.form[f"{i[0]}"])
print("Ping")
if f"{i[0]}" not in session["item"] and session[f"{i[0]}qty"] >= 1:
session["item"].append(f"{i[0]}")
else:
session[f"{i[0]}qty"] = int(request.form[f"{i[0]}"])
print("Pong")
if f"{i[0]}" not in session["item"] and session[f"{i[0]}qty"] >= 1:
session["item"].append(f"{i[0]}")
elif f"{i[0]}":
pass
</code></pre>
<p>Now that I am learning JavaScript, is it a better approach using it? Or flask session just works fine? What are the future problems this type of approach will face?</p>
<p>Any advice would be reallly really helpful~</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T03:19:13.280",
"Id": "520260",
"Score": "0",
"body": "I currently have it deployed on winmarimanzano.pythonanywhere.com but wondering it is due to my free subscription / internet connection or the code itself that is causing for it to load slowly. p.s the cartpage needs 'chayote' or 'carrots' or 'cabbage' for it to enter (since I haven't expanded my if statements yet)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T01:40:42.633",
"Id": "263531",
"Score": "1",
"Tags": [
"python",
"javascript",
"html5",
"flask"
],
"Title": "Flask Session + Jinja OR Javascript + Flask"
}
|
263531
|
<p>This is a problem-solving code for <a href="https://leetcode.com/problems/rank-transform-of-a-matrix/" rel="nofollow noreferrer">LeetCode 1632</a>.</p>
<blockquote>
<p>Given an <span class="math-container">\$m \times n\$</span> <code>matrix</code>, return a new matrix <code>answer</code> where
<code>answer[row][col]</code> is the rank of <code>matrix[row][col]</code>.</p>
<p>The rank is an integer that represents how large an element is
compared to other elements. It is calculated using the following
rules:</p>
<ul>
<li><p>The rank is an integer starting from <code>1</code>.</p>
</li>
<li><p>If two elements <code>p</code> and <code>q</code> are in the same row or column, then:</p>
<ul>
<li>If <code>p < q</code> then <code>rank(p) < rank(q)</code></li>
<li>If <code>p == q</code> then <code>rank(p) == rank(q)</code></li>
<li>If <code>p > q</code> then <code>rank(p) > rank(q)</code></li>
</ul>
</li>
<li><p>The rank should be as small as possible.</p>
</li>
</ul>
<p>It is guaranteed that answer is unique under the given rules.</p>
</blockquote>
<p>The code is translated from C++, which has several similar code blocks in the function <code>matrix_rank_transform</code>. It seems that we can simplify it but it's not very straightforward, for the first block it scans the matrix with row first, for the second one, it scans the matrix with column first, any suggestions will be welcome!</p>
<pre class="lang-rust prettyprint-override"><code>type LenthType = u32;
struct UnionFind {
ancestor: Vec<LenthType>,
size: Vec<LenthType>,
}
impl UnionFind {
pub fn new(n: usize) -> UnionFind {
UnionFind {
ancestor: (0..n as LenthType).collect(),
size: vec![1; n],
}
}
pub fn union(&mut self, index_1: usize, index_2: usize) {
let (root_1, root_2) = (self.root(index_1), self.root(index_2));
if root_1 == root_2 {
return;
}
if self.size[root_1] > self.size[root_2] {
self.ancestor[root_2] = root_1 as LenthType;
self.size[root_1] += self.size[root_2];
} else {
self.ancestor[root_1] = root_2 as LenthType;
self.size[root_2] += self.size[root_1];
}
}
pub fn root(&mut self, mut index: usize) -> usize {
while index != self.ancestor[index] as usize {
self.ancestor[index] = self.ancestor[self.ancestor[index] as usize];
index = self.ancestor[index] as usize;
}
index
}
}
use std::collections::{HashMap, VecDeque};
impl Solution {
pub fn matrix_rank_transform(matrix: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let (row, col) = (matrix.len(), matrix[0].len());
let mut union_find = UnionFind::new(row * col);
for i in 0..row {
let mut map = HashMap::new();
for j in 0..col {
map.entry(matrix[i][j])
.or_insert(Vec::new())
.push(i * col + j);
}
for (_key, val) in map {
for k in 0..(val.len() - 1) {
union_find.union(val[k], val[k + 1]);
}
}
}
for j in 0..col {
let mut map = HashMap::new();
for i in 0..row {
map.entry(matrix[i][j])
.or_insert(Vec::new())
.push(i * col + j);
}
for (_key, val) in map {
for k in 0..(val.len() - 1) {
union_find.union(val[k], val[k + 1]);
}
}
}
let mut adj_list = vec![Vec::new(); row * col];
let mut in_degree = vec![0; row * col];
for i in 0..row {
let mut vec_pair = vec![(0, 0); col];
for j in 0..col {
vec_pair[j] = (matrix[i][j], j);
}
vec_pair.sort();
for j in 0..(col - 1) {
if vec_pair[j].0 != vec_pair[j + 1].0 {
let u_root = union_find.root(i * col + vec_pair[j].1);
let v_root = union_find.root(i * col + vec_pair[j + 1].1);
adj_list[u_root].push(v_root);
in_degree[v_root] += 1;
}
}
}
for j in 0..col {
let mut vec_pair = vec![(0, 0); row];
for i in 0..row {
vec_pair[i] = (matrix[i][j], i);
}
vec_pair.sort();
for i in 0..(row - 1) {
if vec_pair[i].0 != vec_pair[i + 1].0 {
let u_root = union_find.root(vec_pair[i].1 * col + j);
let v_root = union_find.root(vec_pair[i + 1].1 * col + j);
adj_list[u_root].push(v_root);
in_degree[v_root] += 1;
}
}
}
let mut ans = vec![1; row * col];
let mut queue = VecDeque::new();
for i in 0..row * col {
if union_find.root(i) == i && in_degree[i] == 0 {
queue.push_back(i);
}
}
while let Some(node) = queue.pop_back() {
for &v in &adj_list[node] {
ans[v] = ans[v].max(ans[node] + 1);
in_degree[v] -= 1;
if in_degree[v] == 0 {
queue.push_back(v);
}
}
}
let mut result = vec![vec![0; col]; row];
for i in 0..row {
for j in 0..col {
result[i][j] = ans[union_find.root(i * col + j)];
}
}
result
}
}
struct Solution;
fn main() {
assert_eq!(
Solution::matrix_rank_transform(vec![vec![1, 2], vec![3, 4]]),
vec![vec![1, 2], vec![2, 3]]
);
assert_eq!(
Solution::matrix_rank_transform(vec![
vec![-37, -26, -47, -40, -13],
vec![22, -11, -44, 47, -6],
vec![-35, 8, -45, 34, -31],
vec![-16, 23, -6, -43, -20],
vec![47, 38, -27, -8, 43]
]),
vec![
vec![3, 4, 1, 2, 7],
vec![9, 5, 3, 10, 8],
vec![4, 6, 2, 7, 5],
vec![7, 9, 8, 1, 6],
vec![12, 10, 4, 5, 11]
]
);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T05:13:57.580",
"Id": "520261",
"Score": "1",
"body": "Can you add a description of the purpose of the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T05:16:22.180",
"Id": "520262",
"Score": "0",
"body": "@L.F. I have updated the details, thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T02:25:07.217",
"Id": "263532",
"Score": "4",
"Tags": [
"programming-challenge",
"matrix",
"rust"
],
"Title": "LeetCode 1632: Rank Transform of a Matrix in Rust"
}
|
263532
|
<p>The following command series is used to gather every bit of valuable information from <a href="https://etip.exodus-privacy.eu.org/trackers/all" rel="nofollow noreferrer">Exodus trackers</a>. The ultimate goal would be to get this all into one <code>jq</code> statement, and if that's not possible then to just simplify as much as possible.</p>
<p>I'm aware of the <code>sub</code> and <code>gsub</code> functions available in <code>jq</code>, and tried to use them in the statement that parses network signatures. However, operating on the backslashes (even though they were properly escaped) didn't work, hence the <code>sed</code> cop-out.</p>
<p>Feedback from any angle is welcome!</p>
<p><- <a href="https://etip.exodus-privacy.eu.org/trackers/export" rel="nofollow noreferrer"><strong>JSON Input</strong></a></p>
<p><em>Sample:</em></p>
<pre class="lang-json prettyprint-override"><code>{
"trackers": [
{
"name": "ACRCloud",
"code_signature": "com.acrcloud",
"network_signature": "acrcloud.com|hb-minify-juc1ugur1qwqqqo4.stackpathdns.com",
"website": "https://acrcloud.com/"
},
{
"name": "ADLIB",
"code_signature": "com.mocoplex.adlib.",
"network_signature": "adlibr\\.com",
"website": "https://adlibr.com"
},
{
"name": "ADOP",
"code_signature": "com.adop.sdk.",
"network_signature": "",
"website": "http://adop.cc/"
},
{
"name": "fullstory",
"code_signature": "com.fullstory.instrumentation.|com.fullstory.util.|com.fullstory.jni.|com.fullstory.FS|com.fullstory.rust.|com.fullstory.FSSessionData",
"network_signature": "",
"website": "https://www.fullstory.com/"
}
]
}
</code></pre>
<p>-> <a href="https://github.com/T145/black-mirror/releases/download/latest/exodus_domains.txt" rel="nofollow noreferrer"><strong>Domain Output</strong></a></p>
<p>-> <a href="https://github.com/T145/black-mirror/releases/download/latest/exodus_ips.txt" rel="nofollow noreferrer"><strong>IP Output</strong></a></p>
<p><strong>exodus.bash</strong></p>
<pre class="lang-bsh prettyprint-override"><code>curl -s 'https://etip.exodus-privacy.eu.org/trackers/export' -o trackers.json
jq -r '.trackers[].code_signature | split("|") | reverse | .[] | split(".") | reverse | join(".") | ltrimstr(".")' trackers.json >tmp.txt
jq -r '.trackers[].network_signature | split("|") | .[]' trackers.json | sed -e 's/\\\././g' -e 's/\\//g' -e 's/^\.//' >>tmp.txt
jq -r '.trackers[].website' trackers.json | mawk -F/ '{print $3}' >>tmp.txt
gawk '/^([[:alnum:]_-]{1,63}\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower($1)}' tmp.txt >exodus_domains.txt
gawk '/^([0-9]{1,3}\.){3}[0-9]{1,3}+(\/|:|$)/{sub(/:.*/,"",$1); print $1}' tmp.txt >exodus_ips.txt
rm trackers.json
rm tmp.txt
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T06:27:06.247",
"Id": "520264",
"Score": "1",
"body": "Would you mind adding example inputs and outputs to the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T13:59:03.087",
"Id": "520294",
"Score": "0",
"body": "@200_success Done!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T14:46:22.967",
"Id": "520299",
"Score": "0",
"body": "Does the order of the domains/IPs in the output files matter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T14:58:10.700",
"Id": "520303",
"Score": "0",
"body": "@SaraJ Not particularly, though a `sort -u` couldn't hurt."
}
] |
[
{
"body": "<p>Since you said the order of the outputs doesn't really matter, the first <code>reverse</code> in the <code>.code_signature</code> path seems useless - as far as I can tell, all it does is change the order of certain outputs (the second <code>reverse</code> on the other hand is useful).</p>\n<p>In <code>jq</code>, piping to <code>.[]</code> is fine, but maybe a bit awkward. <code>[]</code> can be applied on top of most simple filters, and I don't believe <code>split("|")[]</code> is any less clear than <code>split("|") | .[]</code>. But that's definitely a matter of opinion, and the <code>| .[]</code> approach is valid too.</p>\n<p>The first of your <code>sed</code> patterns seems a bit redundant. It replaces <code>\\\\.</code> with <code>.</code> - so basically it removes some <code>\\</code>s. But then the very next pattern removes <em>all</em> <code>\\</code>s anyway, so the first one does end up seeming a bit pointless.</p>\n<p>All you need to replicate the last two <code>sed</code> patterns in <code>jq</code> should be <code>replace("\\\\"; "") | ltrimstr(".")</code>. But if you <em>do</em> want that first pattern as well, <code>gsub("\\\\\\\\\\\\."; ".")</code> seems to work fine. Yes, that's a lot of <code>\\</code>s, but each <code>\\\\</code> pair in a string literal represents just a single <code>\\</code> in the actual string.</p>\n<p>The <code>mawk</code> call appears to just split its input on <code>/</code> and then take the 3rd item. We can do that as well without leaving <code>jq</code> by simply doing <code>split("/")[2]</code></p>\n<p>If you move both the <code>sed</code> and the <code>mawk</code> into <code>jq</code>, we then have 3 <code>jq</code> commands with a common source (<code>trackers.json</code>) and a common destination (<code>tmp.txt</code>). At that point, it becomes possible to combine the three commands into one - <code>,</code> seems like a good tool for that.</p>\n<p>Now, I'm fairly sure there are ways to do that without changing the order of the outputs, but since you said the order doesn't particularly matter, the following approach feels the most natural to me:</p>\n<pre><code>.trackers[] |\n (.code_signature | split("|")[] | split(".") | reverse | join("."))\n , (.network_signature | split ("|")[] | gsub("\\\\\\\\"; ""))\n , (.website | split("/")[2])\n | ltrimstr(".")\n</code></pre>\n<p>Having done that, we no longer need to save <code>trackers.json</code> - we can pipe <code>curl</code>'s output straight into <code>jq</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>curl -s 'https://etip.exodus-privacy.eu.org/trackers/export' |\n jq -r '.trackers[] |\n (.code_signature | split("|")[] | split(".") | reverse | join("."))\n , (.network_signature | split ("|")[] | gsub("\\\\\\\\"; ""))\n , (.website | split("/")[2])\n | ltrimstr(".")\n ' > tmp.txt\n</code></pre>\n<p>On a similar note, it's <em>also</em> possible to combine the <code>gawk</code>s into a single command. One possible approach might look like:</p>\n<pre><code>{ switch ($1) {\n case /^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/:\n print tolower($1) > "exodus_domains.txt"\n break\n case /^([0-9]{1,3}\\.){3}[0-9]{1,3}+(\\/|:|$)/:\n sub(/:.*/, "", $1)\n print $1 > "exodus_ips.txt"\n break\n} }\n</code></pre>\n<p>I'm sure there are cleaner ways to get similar results, but either way, if we end up making it a single command we can then go on to pipe our <code>jq</code> straight into that. That way we can get rid of <code>tmp.txt</code> as well:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>curl -s 'https://etip.exodus-privacy.eu.org/trackers/export' |\n jq -r '.trackers[] |\n (.code_signature | split("|")[] | split(".") | reverse | join("."))\n , (.network_signature | split ("|")[] | gsub("\\\\\\\\"; ""))\n , (.website | split("/")[2])\n | ltrimstr(".")\n ' |\n gawk '{ switch ($1) {\n case /^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/:\n print tolower($1) > "exodus_domains.txt"\n break\n case /^([0-9]{1,3}\\.){3}[0-9]{1,3}+(\\/|:|$)/:\n sub(/:.*/, "", $1)\n print $1 > "exodus_ips.txt"\n break\n } }'\n</code></pre>\n<p>And now we don't need to worry about creating and cleaning up temporary files, because all the action happens within a single pipeline.</p>\n<p>Though it does get a bit unwieldy. It might be worth it at this point to break the <code>jq</code> and <code>awk</code> scripts out into separate files and do something closer to</p>\n<pre class=\"lang-sh prettyprint-override\"><code>curl -s 'https://etip.exodus-privacy.eu.org/trackers/export' |\n jq -f parse-ETIP-hosts.jq -r |\n awk -f partition-domains-and-IPs.awk \\\n -v ip_file=exodus_ips.txt \\\n -v domain_file=exodus_domains.txt\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:47:22.447",
"Id": "520318",
"Score": "1",
"body": "There are some edge cases I've found, but I'll ask about that in a separate post. Thanks for the help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:20:55.167",
"Id": "263556",
"ParentId": "263533",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263556",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T03:29:00.517",
"Id": "263533",
"Score": "4",
"Tags": [
"json",
"bash",
"linux"
],
"Title": "Extracting domains and IPs from Exodus trackers JSON report"
}
|
263533
|
<p>This is my function that uses recursion to recursively delete a directory. I like my way of skipping entries <code>.</code> and <code>..</code>.</p>
<p>But should I be casting the name lengths to <code>unsigned int</code> because I am quite sure there will not be file paths longer than 4 gigacharacters? Or is storing the result of <code>strlen</code> in any type other than <code>size_t</code> bad practice?</p>
<p>Any other comments here?</p>
<p>Also is using VLAs in a recursive function risky, could it cause a stack overflow error? Is the VLA OK, or should I just use <code>malloc()</code> (I vehemently refuse to simply use a fixed size buffer that <em>should</em> be big enough, like <s><code>char Entry[1024]</code></s>)?</p>
<pre><code>int Remove(const char *const Object) {
DIR *const Dir = opendir(Object);
if (Dir) {
struct dirent *Dirent;
const unsigned int Len = (unsigned int)strlen(Object);
while ((Dirent = readdir(Dir))) {
const char *const Name = Dirent->d_name;
const unsigned int NameLen = (unsigned int)strlen(Name);
if (Name[0] == '.' && (NameLen == 1 || (Name[1] == '.' && NameLen == 2))) {
continue;
}
char Entry[Len+NameLen+2], *const CurrPtr = memcpy(Entry, Object, Len)+Len;
*CurrPtr = '/';
*(char *)(memcpy(CurrPtr+1, Name, NameLen)+NameLen) = 0;
if ((Dirent->d_type == DT_DIR? Remove : remove)(Entry)) {
return -1;
}
}
if (closedir(Dir)) {
return -1;
}
}
return remove(Object);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T17:02:52.867",
"Id": "520324",
"Score": "1",
"body": "Note that `d_type` is an optional optimization, and can be DT_UNKNOWN. See [Checking if a dir. entry returned by readdir is a directory, link or file. dent->d\\_type isn't showing the type](https://stackoverflow.com/q/23958040)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T00:55:39.383",
"Id": "520351",
"Score": "0",
"body": "https://godbolt.org/z/6441osr7G includes the necessary headers. Looks like it compiles efficiently, with GCC deallocating the VLA at the end of every inner loop."
}
] |
[
{
"body": "<p>We're missing the necessary headers for <code>struct dirent</code> and the Standard library string functions (<code>strlen</code>, <code>memcpy</code> etc).</p>\n<p>It's probably worth providing an explanatory comment that tells the user what the return values mean. It appears that it returns 0 on success, or -1 with <code>errno</code> set to a suitable value if it fails.</p>\n<p>I don't think it's a great idea to use a name that differs only in case from the Standard Library function <code>remove()</code>. Call it <code>remove_recursively()</code> or something instead.</p>\n<blockquote>\n<pre><code> const unsigned int Len = (unsigned int)strlen(Object);\n const unsigned int NameLen = (unsigned int)strlen(Name);\n</code></pre>\n</blockquote>\n<p>Why the cast? We should just keep them as <code>size_t</code>.</p>\n<p>I'm not a fan of the cutesy</p>\n<blockquote>\n<pre><code> *(char *)(memcpy(CurrPtr+1, Name, NameLen)+NameLen) = 0;\n</code></pre>\n</blockquote>\n<p>To be correct, we need to convert the return value of <code>memcpy()</code> to <code>char*</code> <em>before</em> adding <code>NameLen</code>:</p>\n<pre><code> *((char *)memcpy(CurrPtr+1, Name, NameLen)+NameLen) = 0;\n</code></pre>\n<p>But honestly, I'd avoid the casting entirely and write as a pair of much more readable lines:</p>\n<pre><code> memcpy(CurrPtr+1, Name, NameLen);\n CurrPtr[NameLen+1] = '\\0';\n</code></pre>\n<p>Or simpler still, get rid of the manual concatenation and let the library do it for us:</p>\n<pre><code> sprintf(Entry, "%s/%s", Object, Name);\n</code></pre>\n<blockquote>\n<pre><code> if ((Dirent->d_type == DT_DIR? Remove : remove)(Entry)) {\n</code></pre>\n</blockquote>\n<p><s>The conditional operator is unnecessary - just call our <code>Remove()</code>, which will get a null return from <code>opendir()</code> and then simply unlink the file.</s> Actually, the test is a good idea, as it prevents us following symlinks.</p>\n<blockquote>\n<pre><code> if ((Dirent->d_type == DT_DIR? Remove : remove)(Entry)) {\n return -1;\n }\n</code></pre>\n</blockquote>\n<p>Oops - we forgot to <code>closedir()</code> before returning, meaning that we leak a descriptor for every level of recursion.</p>\n<blockquote>\n<pre><code> if (closedir(directory)) {\n return -1;\n }\n</code></pre>\n</blockquote>\n<p>This check may be overkill - the only documented failure possibility is <code>EBADF</code> if we pass a directory that's e.g. already closed. We know the full history of the descriptor, so that can never happen.</p>\n<hr />\n<h1>Simplified version</h1>\n<pre><code>#include <sys/types.h>\n#include <dirent.h>\n\n#include <stdio.h>\n#include <string.h>\n\n\nint remove_recursive(const char *const path) {\n DIR *const directory = opendir(path);\n if (directory) {\n struct dirent *entry;\n while ((entry = readdir(directory))) {\n if (!strcmp(".", entry->d_name) || !strcmp("..", entry->d_name)) {\n continue;\n }\n char filename[strlen(path) + strlen(entry->d_name) + 2];\n sprintf(filename, "%s/%s", path, entry->d_name);\n int (*const remove_func)(const char*) = entry->d_type == DT_DIR ? remove_recursive : remove;\n if (remove_func(entry->d_name)) {\n closedir(directory);\n return -1;\n }\n }\n if (closedir(directory)) {\n return -1;\n }\n }\n return remove(path);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T17:02:15.617",
"Id": "520323",
"Score": "2",
"body": "The question (and your update) don't handle filesystems where d_type == DT_UNKNOWN. See [Checking if a dir. entry returned by readdir is a directory, link or file. dent->d\\_type isn't showing the type](https://stackoverflow.com/q/23958040)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T18:47:19.420",
"Id": "520333",
"Score": "1",
"body": "The reason I manually concatenate the string myself, is because I treat `strlen` to be a relatively expensive operation, and `sprintf` internally calls `strlen`. Also I get the length of the path outside of the loop because it will never change inside the loop. As for the return value of `closedir()` how does an `assert` sound?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T20:05:04.720",
"Id": "520338",
"Score": "0",
"body": "@user244272 It is possible that, when deleting directories, the time taken by disk operations will entirely dwarf the time taken by string operations. If you still feel this optimization is needed, measurement to back up that feeling could be useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T20:05:16.940",
"Id": "520339",
"Score": "0",
"body": "@user244272: I'd `perror` a warning on `closedir(2)` errors, but otherwise just continue. At worst it means you leak an FD. I don't think that can lead to a case where your program erroneously recurses into the wrong tree and deletes more than it should (like this buggy build script that used dead-reckoning `cd ../foo/bar` into stuff and `cd ../../..` back out, all without error checking: [I just deleted everything in my home directory. How? And why are some files still there?](https://unix.stackexchange.com/q/649408))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T20:09:33.683",
"Id": "520340",
"Score": "0",
"body": "@WayneConrad: System calls might pollute data and instruction caches, making bulky over-complicated code between calls even slower. sprintf has a pretty large code footprint. To be fair, path strings are never going to be huge, and strlen is pretty fast on modern systems, though, and system call overhead on modern CPUs (especially Intel with Spectre mitigation) is pretty big even compared to a few cache misses. Remember that modern OSes don't wait for the data to be updated on disk before `unlink` returns, though, so it's just updating metadata for eventual write-back of a batch of deletes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T20:10:54.380",
"Id": "520341",
"Score": "1",
"body": "@WayneConrad: But fortunately POSIX 2008 `unlinkat(2)` lets you use paths relative to an open directory FD, so you don't need any string manipulation. https://man7.org/linux/man-pages/man2/unlink.2.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T21:55:23.830",
"Id": "520345",
"Score": "0",
"body": "@PeterCordes I'm not arguing against optimization. Just against doing it before measurement shows there's a problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T21:58:48.807",
"Id": "520346",
"Score": "0",
"body": "I am also not arguing against this answer, which I think is good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T22:15:06.200",
"Id": "520348",
"Score": "0",
"body": "@WayneConrad: Yeah, but when it's possible to write obviously more efficient code without hurting human readability or robustness, that's always better. I dislike the idea of leaving obviously-slow code around just because the current speed is good enough for now. Especially when the difference is in cache footprint, the cost it imposes isn't fully visible in microbenchmarks, just in cache misses spread around the rest of the program. In this case the simplicity of sprintf might be worth it (although some of that goes out the window with buffer length checking)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T22:17:22.123",
"Id": "520349",
"Score": "0",
"body": "(My other point is that *if* you know a lot about how performance, and how CPUs and compilers work, you can make some reasonable estimates without having to measure every time. Microbenchmarking accurately is hard.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T07:14:14.400",
"Id": "520363",
"Score": "0",
"body": "@Peter, I'd completely forgotten that some filesystems return `DT_UNKNOWN`. Would you care to write an answer with that observation? I think it deserves more than just a comment here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T07:18:54.640",
"Id": "520364",
"Score": "1",
"body": "@user244272, why do you think `sprintf()` would call `strlen`? That part is just like `strcpy()` - just keep going until you see `\\0`. I would code for clarity and maintainability here anyway - there's no point micro-optimising code that's dwarfed by filesystem access. I considered recommending `assert(closedir(…) == 0)` - if it fails it's definitely a programming error you want your debug builds to diagnose."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T11:39:14.520",
"Id": "263546",
"ParentId": "263536",
"Score": "5"
}
},
{
"body": "<p>It might be possible to avoid copying the filenames, if it's okay for the function to change the working directory. We can <code>chdir</code> into the directory to be removed, remove all its content (using the relative names directly from the <code>dirent</code> structure), then change back when we're done. That keeps the per-frame overhead absolutely minimal.</p>\n<p>Actually we can avoid changing working directory if we're on a platform that provides <a href=\"https://man7.org/linux/man-pages/man2/unlink.2.html\" rel=\"nofollow noreferrer\"><code>unlinkat()</code></a> (thanks to Peter Cordes for suggesting this). The code then looks very simple:</p>\n<pre><code> int unlinkflags = entry->d_type == DT_DIR ? AT_REMOVEDIR : 0;\n if (unlinkat(dirfd(directory), entry->d_name, unlinkflags)) {\n closedir(directory);\n return -1;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T17:00:44.187",
"Id": "520322",
"Score": "1",
"body": "Or since this is already using `readdir`, use other POSIX functions like `unlinkat(dirfd, path, flags)` to allow using paths relative to a directory (https://man7.org/linux/man-pages/man2/unlink.2.html). (Instead of using ISO C stdio.h `remove(3)`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T07:28:37.637",
"Id": "520366",
"Score": "1",
"body": "Ah yes, I'd totally forgotten about `unlinkat()` - that's much better than modifying the process working directory. Answer updated, and thank you again!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T12:08:48.483",
"Id": "263548",
"ParentId": "263536",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T05:58:01.913",
"Id": "263536",
"Score": "7",
"Tags": [
"c",
"recursion",
"file-system"
],
"Title": "C delete files and directories, recursively if directory"
}
|
263536
|
<p>Here is another one of my simple beginner projects I did in my free time in under 30 minutes, a Rock, Paper, Scissors game in Python against a Computer (random module). As usual, I would like to know if there are any improvements/suggestions/criticism/feedback that you guys have about my code. Thanks in advance.</p>
<pre><code>import random
import os
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def lobby():
clear()
totalgames = len(history)
totalwins = 0
totallosses = 0
totalties = 0
for game in history:
if(game == 0):
totalties += 1
elif(game == 1):
totalwins += 1
elif(game == 2):
totallosses += 1
winrate = (2 * totalwins + totalties) / (2 * totalgames) * 100
winrate = round(winrate, 2)
print("Your Stats")
print("_________________________________________________\n")
print("TOTAL GAMES: " + str(totalgames))
print("WINS: " + str(totalwins))
print("LOSSES: " + str(totallosses))
print("TIES: " + str(totalties) + "\n")
print("YOUR WINRATE: " + str(winrate) + "%")
print("_________________________________________________\n")
def game():
clear()
computer = random.randint(0,2)
player = input("Rock, Paper or Scissors?\n").lower()
if(player[0] == 'r'):
playerInt = 0
elif(player[0] == 'p'):
playerInt = 1
elif(player[0] == 's'):
playerInt = 2
intToOption = [
"Rock",
"Paper",
"Scissors"
]
if(computer == playerInt):
result = 0
elif(computer == 0 and playerInt == 1):
result = 1
elif(computer == 1 and playerInt == 2):
result = 1
elif(computer == 2 and playerInt == 0):
result = 1
elif(computer == 0 and playerInt == 2):
result = 2
elif(computer == 1 and playerInt == 0):
result = 2
elif(computer == 2 and playerInt == 1):
result = 2
resultMessages = [
"It's a tie! Both of you chose " + str(intToOption[playerInt] + "."),
"Player Win! Player chose " + str(intToOption[playerInt] + " while Computer chose " + str(intToOption[computer]) + ". " + intToOption[playerInt] + " beats " + intToOption[computer] + "."),
"Computer Win! Player chose " + str(intToOption[playerInt] + " while Computer chose " + str(intToOption[computer]) + ". " + intToOption[computer] + " beats " + intToOption[playerInt] + ".")
]
print(resultMessages[result] +"\n")
input("Input any key to return to lobby.\n")
history.append(result)
return result
history = []
def main():
game()
lobby()
while(input("Would you like to play again? (Y/N)\n")).lower()[0] == 'y':
game()
lobby()
clear()
print("Thanks for playing darrance's Rock Paper Scissors game!")
input("Input any key to exit the program.\n")
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T01:05:13.733",
"Id": "520449",
"Score": "0",
"body": "I magically get pinged when such questions arise... I wonder why. ;)"
}
] |
[
{
"body": "<h1>Cleanup</h1>\n<p>For cleanliness:</p>\n<pre><code>if(computer == playerInt):\n result = 0\n\nelif(computer == 0 and playerInt == 1):\n result = 1\n\nelif(computer == 1 and playerInt == 2):\n result = 1\n\nelif(computer == 2 and playerInt == 0):\n result = 1\n\nelif(computer == 0 and playerInt == 2):\n result = 2\n\nelif(computer == 1 and playerInt == 0):\n result = 2\n\nelif(computer == 2 and playerInt == 1):\n result = 2\n</code></pre>\n<p>Can actually be replaced with just a single line:</p>\n<pre><code>result = (playerInt - computer) % 3\n</code></pre>\n<p>It's not always possible to find this one-liner in your code, but notice your code has to test so many scenarios. If in any one of those you made a mistake and accidentally wrote the wrong number for the result, it could be difficult the track down the problem. Of course, you would hopefully have unittests to handle all cases, but it still is extra code that can be avoided, so we do it here.</p>\n<h1>F-Strings</h1>\n<p>First, you called <code>intToOption</code> to get the player's and computer's choices a <em>lot</em> in your strings. It's better to store these in a temporary variable because it adds readability, and if you decide you want to change how a choice is selected (for example, maybe you'll want to show the integer too) you can change it in one place instead of 5 or 6.</p>\n<p>Second, try to use <code>f</code> strings. They make your code more condensed and easier to read:</p>\n<pre><code>playerChoice = intToOption[playerInt]\ncomputerChoice = intToOption[computer]\nresultMessages = [\n f"It's a tie! Both of you chose {playerChoice}.",\n f"Player Win! Player chose {playerChoice} while Computer chose {computerChoice}. {playerChoice} beats {computerChoice}.",\n f"Computer Win! Player chose {playerChoice} while Computer chose {computerChoice}. {computerChoice} beats {playerChoice}."\n]\n</code></pre>\n<h1>Simple error handling</h1>\n<p>If a player doesn't input rock, paper, or scissors, don't let the game crash, just ask them to input again:</p>\n<pre><code>while True:\n player = input("Rock, Paper or Scissors?\\n").lower()\n if(player[0] == 'r'):\n playerInt = 0\n break\n elif(player[0] == 'p'):\n playerInt = 1\n break\n elif(player[0] == 's'):\n playerInt = 2\n break\n else:\n print(f"{player} is not a valid input!")\n</code></pre>\n<p>You might implement something similar on your would you like to play again screen, although on that one the game doesn't crash if you put an invalid input, it just exits.</p>\n<h1>Enum</h1>\n<p>Another way to handle your choices is to define an <code>Enum</code>:</p>\n<pre><code>from enum import Enum\n\nclass Choice(Enum):\n Rock = 0\n Paper = 1\n Scissors = 2\n</code></pre>\n<p>Now, on input:</p>\n<pre><code>while True:\n player = input("Rock, Paper or Scissors?\\n").lower()\n if(player[0] == 'r'):\n player = Choice.Rock\n break\n elif(player[0] == 'p'):\n player = Choice.Paper\n break\n elif(player[0] == 's'):\n player = Choice.Scissors\n break\n else:\n print(f"{player} is not a valid input!")\n</code></pre>\n<p>You can drop <code>intToOption</code> entirely and write</p>\n<pre><code>result = (player.value - computer.value) % 3\n</code></pre>\n<p>The computer's choice is</p>\n<pre><code>computer = Choice(random.randint(0,2))\n</code></pre>\n<p>and for your <code>resultMessages</code></p>\n<pre><code>playerChoice = player.name\ncomputerChoice = computer.name\nresultMessages = [\n f"It's a tie! Both of you chose {playerChoice}.",\n f"Player Win! Player chose {playerChoice} while Computer chose {computerChoice}. {playerChoice} beats {computerChoice}.",\n f"Computer Win! Player chose {playerChoice} while Computer chose {computerChoice}. {computerChoice} beats {playerChoice}."\n]\n</code></pre>\n<p>Here we use <code>player.name</code>. Normally, if we had chosen <code>Rock</code>, <code>player</code> would appear as <code>Choice.Rock</code>, but <code>player.name</code> appears as <code>Rock</code> only. Using Enums is useful when you have a few unchanging values that you need to represent. Before, you had <code>intToOption</code> which was related to the choices made, but it is possible to alter <code>intToOption</code> without modifying the behaviour of the ints which could cause errors down the road. An <code>Enum</code> is more strict because it pairs the integer and name of an instance together in the class definition. <code>Enum</code>s also make the code and your intentions easier to understand.</p>\n<p>You could also create an enum for the result of <code>Win</code>, <code>Loss</code> or <code>Tie</code>.</p>\n<h1>Main</h1>\n<p>When defining and writing a main function, you probably want to call it as follows:</p>\n<pre><code>if __name__ == "__main__":\n main()\n</code></pre>\n<p>This says run <code>main()</code> if this module is run directly. What this means is <code>main()</code> will not be called if you decide to import these functions to another module, but still runs normally if you run this file.</p>\n<h1>Comments</h1>\n<p>Add comments to your code and especially your functions! You might not need inline comments to explain what is happening, but <a href=\"https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings\" rel=\"noreferrer\">docstrings</a> for functions make a big difference. First, they tell you what a function does, but the side benefit of that is they encourage you to write an enclosed function that makes sense. Sometimes, certain behaviours end up in the wrong function so that the code still works, but you end up with two functions not really making sense independently. Of course, you might only ever intend for a function to be used with another one, but the function alone should be summarizable: you should be able to say what a function does without needing information from another one. Your code is pretty good for having these independent functions, but you can still make a docstring like:</p>\n<pre><code>def lobby(): \n"""Update player statistics and display them to the user."""\n</code></pre>\n<p>In this case (though not always), you can give a brief oneline description of what is going on, and you can see this encourages you to think about what additional code might go in the lobby definition: if you add more, then update the docstring, but you'll still want the docstring to make sense when you do. The intention of a docstring is of course just to provide a summary of what is happening in a function, but especially for new programmers, it's a good way to make you think about if your functions make sense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T06:25:25.690",
"Id": "520358",
"Score": "5",
"body": "Most of your comments are on point, with the exception of the line `result = (player.value - computer.value) % 3`. Sure, it does get rid of a lot of error-prone boilerplate code, but it's relatively obscure, and hinges on the arbitrary mapping of user input to numeric values, and the arbitrary interpretation of the the value of `result`. Instead, I'd recommend using constants or enums to make this mapping and interpretation explicit but concise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T10:52:09.060",
"Id": "520375",
"Score": "0",
"body": "I agree with @Schmuddi, and I'll add that for such things often time a \"table\", whether array or dictionary, to encode the rules is more obvious (descriptive) than code. Also, when writing such tables, symmetry should be exploited, so here you would have: (1) if same choice, then draw, then (2) if WIN_OVER[x] == y, then player of x wins."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T12:02:35.993",
"Id": "520378",
"Score": "0",
"body": "@Schmuddi Would you be able to suggest an edit (or provide your own answer which I could then link in mine) to demonstrate what you mean? Reading your comment and knowing that later in my answer I introduce an `Enum` for `Choice`, I realize that if I also create an `Enum` called `Result`, I could create a method for `Choice` which returns a `Result`, which I think would really cutdown on the obscurity in the code, but I'm curious if you're suggesting that we remove the numeric representations entirely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T14:48:55.503",
"Id": "520399",
"Score": "1",
"body": "Yes, I indeed suggest removing the numeric representations entirely. What I'd do is to define a `Result` enum as you suggested, and also a dictionary that defines the winning condition for each possible choice: `win_condition = {Choice.Rock: Choice.Scissors, Choice.Paper: Choice.Rock, Choice.Scissors: Choice.Paper}`. Now, to determine the result of a match, I'd do something like `result = (Result.Win if win_condition[player] == computer else Result.Loss if win_condition[computer] == player else Result.Tie)`, which should be quite readable with proper line breaks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T13:01:59.833",
"Id": "263550",
"ParentId": "263537",
"Score": "34"
}
},
{
"body": "<p>You can create a list <code>outcomes</code>, and then your <code>for game in history</code> block can be simplified to either</p>\n<pre><code>for game in history:\n outcome[game] +=1\n</code></pre>\n<p>or</p>\n<pre><code>outcomes = [sum([game == i for game in history]) for i in range(3)]\n</code></pre>\n<p>Your winrate can be simplified with some math, but that math is easier if you reorder the results as loss = 0, tie = 1, win = 2. Then</p>\n<pre><code>winrate = 50*sum(history)/len(history)\n</code></pre>\n<p>When printing out the stats, they'll be easier to read with some padding, and you probably don't need full <code>float</code> precision:</p>\n<pre><code>print("Your Stats")\nprint("_________________________________________________\\n")\nprint("TOTAL GAMES: ".ljust(15) + str(len(history)).rjust(5))\nprint("WINS: ".ljust(15) + str(outcomes[2]).rjust(5))\nprint("LOSSES: ".ljust(15) + str(outcomes[0]).rjust(5))\nprint("TIES: ".ljust(15) + str(outcomes[1]).rjust(5) + "\\n")\nprint("YOUR WINRATE: ".ljust(15) + str(round(winrate,2).rjust(5) + "%")\nprint("_________________________________________________\\n")\n</code></pre>\n<p>Defining a dictionary making converting to an int simpler (note: you should define this dictionary outside the loop):</p>\n<pre><code>choice_lookup = {'r':0, 'p':1, 's':2}\n</code></pre>\n<p>Then inside the loop:</p>\n<pre><code>playerInt = choice_lookup[player[0]]\n</code></pre>\n<p>With my re-ordering of the results (that is, win = 2), <code>result</code> can be calculated as</p>\n<pre><code>result = (playerInt - computer + 1) % 3\n</code></pre>\n<p>Also defining, resultMessages in each iteration of the loop, and defining string you're not using, is a bit wasteful. Also, I don't see any matching parentheses for your elements in resultsMessages. Outside the loop, you can define intToOption and put:</p>\n<pre><code>def resultMessage(result, playerInt, computer):\n if result == 1:\n return "It's a tie! Both of you chose " + str(intToOption[playerInt] + "."\n choices_string = "Player chose " + str(intToOption[playerInt] + " while Computer chose " + str(intToOption[computer]) + ". " \n if result == 0:\n return "Computer Win! "+ \n choices_string + \n intToOption[computer] + \n " beats " + \n intToOption[playerInt] + \n "."\n return "Player Win! " + \n choices_string + \n intToOption[playerInt] + \n "beats " + \n intToOption[computer] + \n "."\n</code></pre>\n<p>Then in the loop put:</p>\n<pre><code>print(resultMessage(result, playerInt, computer) +"\\n")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T06:32:50.747",
"Id": "520359",
"Score": "0",
"body": "(1) Python format strings allow you to do the padding in a much more readable way. (2) As you noticed yourself, your line `result = (playerInt - computer + 1) % 3` depends on the arbitrary order of keys and values in `choice_lookup`. If you change the order, that line breaks. This line is also relatively obscure as it only works because you use magic numbers for the choices."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T04:18:06.300",
"Id": "263571",
"ParentId": "263537",
"Score": "0"
}
},
{
"body": "<p>I find that os.system can be a bit hit and miss depending on how you run it. It tend to look for alternatives.</p>\n<p>If you are only using one os.system and random command, it is probably better just to import the command rather than the whole module.</p>\n<p>totalgames = len(history) but I dont think you have defined history at that point or else you are using it as a global variable, which I would not recommend.</p>\n<p>I wouldn't normally advise you to use integers as the outcome and I would normally go with Kraigolas and use enumeration types or if you are not sure of them strings. However, the way you are using numbers you could make a "result matrix/ 2D jagged list" where the computers option was the row number and player option the column number. Then you don't need to do all those elifs for every case. Perhaps a better alternative to a 2D list would be a dictionary of dictionaries so you can index according to the rock, scissors stone rather than numbers.</p>\n<p>I would probably just ditch putting the code into the main method and then calling it. It doesn't really serve any function. As has been mentioned the main can be used to stop the code running from an imported module, but would you ever import this code?</p>\n<p>Hope it helps and all the best!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T09:02:27.300",
"Id": "263577",
"ParentId": "263537",
"Score": "1"
}
},
{
"body": "<h1>Choosing Options</h1>\n<p>This code block</p>\n<pre class=\"lang-py prettyprint-override\"><code> if(player[0] == 'r'):\n playerInt = 0\n elif(player[0] == 'p'):\n playerInt = 1\n elif(player[0] == 's'):\n playerInt = 2\n</code></pre>\n<p>would be better served to compare the whole string. In this case, <code>srock</code> would be interpreted as <code>scissors</code>. That doesn't seem right. Also, the conversion to <code>int</code> avoids magic numbers if you use a dictionary mapping. Last, you want to handle the case where the user doesn't give valid input with a helpful error message, and printing that message by catching a <code>KeyError</code> might make sense here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>choices = {\n 'rock': 0,\n 'paper': 1,\n 'scissors': 2\n}\n\nwhile True:\n player_choice = input("Rock, Paper or Scissors?\\n").strip().lower()\n \n try:\n player_int = choices[player_choice]\n except KeyError as e:\n print(\n (f"Did not get valid input, expected one of {', '.join(choices)}"\n f" got {player_choice}. Please try again")\n )\n\n</code></pre>\n<p>Alternatively, building on the Enum idea from @Kraigolas's answer:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Change the values to strings to avoid the conversions\nclass Choice(Enum):\n Rock = 'rock'\n Paper = 'paper'\n Scissors = 'scissors'\n\n\nwhile True:\n player_choice = input("Rock, Paper or Scissors?\\n").strip().lower()\n \n try:\n player_choice = Choice(player_choice)\n except ValueError: # an invalid choice will raise a ValueError\n print(\n ("Expected one of 'Rock', 'Paper', or 'Scissors', but got " \n f"{player_choice}. Please choose a valid option")\n )\n\ncomputer_choice = random.choice(('rock', 'paper', 'scissors'))\ncomputer_choice = Choice(computer_choice)\n</code></pre>\n<h1>Checking win condition</h1>\n<p>Using the enum idea makes this a lot more explicit, rather than a collection of magic number checking. Last, you only need to check for a draw scenario and the scenarios in which the player wins, the rest are losses:</p>\n<pre class=\"lang-py prettyprint-override\"><code>\nif player_choice == computer_choice:\n result = 0\nelif player_choice == Choice.Rock and computer_choice == Choice.Scissors:\n result = 1\nelif player_choice == Choice.Paper and computer_choice == Choice.Rock:\n result = 1\nelif player_choice == Choice.Scissors and computer_choice == Choice.Paper:\n result = 1\nelse:\n result = 2\n</code></pre>\n<p>Alternatively, reimagined as a <code>set</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code># The conditions under which the player wins, where\n# the tuples are (user, computer) choices\nwin_conditions = set(\n (Choice.Rock, Choice.Scissors),\n (Choice.Paper, Choice.Rock),\n (Choice.Scissors, Choice.Paper)\n)\n\nif user_choice == computer_choice:\n result = 0\nelif (user_choice, computer_choice) in win_conditions:\n result = 1\nelse:\n result = 2\n</code></pre>\n<h1>Updating Game History</h1>\n<p>As suggested in the comments, it might be better to use a <code>Counter</code> to track game history. This way you can return more concrete results such as <code>win</code>, <code>loss</code>, and <code>draw</code>, rather than <code>1</code>, <code>2</code>, and <code>0</code>, respectively:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\ngame_history = Counter({'win': 0, 'loss': 0, 'draw': 0})\n\ndef check_win(player_choice, computer_choice):\n """Checks the result of the game and returns either win, loss, or draw"""\n # The conditions under which the player wins, where\n # the tuples are (user, computer) choices\n win_conditions = set(\n (Choice.Rock, Choice.Scissors),\n (Choice.Paper, Choice.Rock),\n (Choice.Scissors, Choice.Paper)\n )\n \n if user_choice == computer_choice:\n result = 'draw'\n elif (user_choice, computer_choice) in win_conditions:\n result = 'win'\n else:\n result = 'loss'\n\n print(f'Your choice was {user_choice}, computer chose {computer_choice}. Player {result}!')\n \n return result\n\nresult = check_win(user_choice, computer_choice)\ngame_history[result] += 1\n</code></pre>\n<p>This aggregates your game history into something that can easily be summarized. Then, when summarizing your game, you can use the <code>Counter</code>, which is more explicit:</p>\n<pre class=\"lang-py prettyprint-override\"><code># explicitly take history as an argument so that you aren't\n# relying on a global variable here\ndef show_game_history(history):\n """Shows aggregated game statistics"""\n wins, draws = history['win'], history['draw']\n total_games = sum(history.values())\n\n win_rate = (2 * wins + draws) / (2 * total_games) * 100\n\n print("Your Stats")\n print("_________________________________________________\\n")\n print(f"TOTAL GAMES: {total_games}")\n print(f"WINS: {wins}")\n print(f"LOSSES: {history['loss']}")\n print(f"TIES: {draws}")\n print(f"YOUR WINRATE: {win_rate}%")\n print("_________________________________________________\\n")\n\n</code></pre>\n<p>f-strings also make this a bit more compact and more pythonic than string concatenation.</p>\n<h1>Updating your main function</h1>\n<p>With these changes in mind, your game history can be kept in <code>main</code>, rather than in global scope:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n game_history = Counter({'win': 0, 'loss': 0, 'draw': 0})\n\n while True:\n result = game()\n game_history[result] += 1\n show_game_history(game_history)\n \n choice = input('Would you like to play again? (Y/N)\\n').strip().lower()\n if choice == 'n':\n break\n elif choice == 'y':\n continue\n else:\n print('Invalid choice, quitting')\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T21:06:51.680",
"Id": "520422",
"Score": "2",
"body": "The set idea is so beautiful! +1 Is there a reason to map these to 0, 1 and 2 instead of using a default dict? `history = defaultdict(int)` and then `history('draw') += 1` is imho clearer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T12:54:57.387",
"Id": "520480",
"Score": "0",
"body": "@N3buchadnezzar No particular reason you couldn't, I just didn't review that specific part of the code. Good suggestion though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T20:56:41.417",
"Id": "520512",
"Score": "0",
"body": "Per your first point, if I were playing this, I'd likely discover early that I can type just `r`, `p` or `s` instead of typing out the whole word. As Homer Simpson once said after discovering he could type `y` instead of `yes`, I've tripled my productivity! Only more than that because these words are longer than 3 letters. (I guess if you typed `stone` expecting it to be the same as `rock` you might be surprised...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:12:21.607",
"Id": "521118",
"Score": "0",
"body": "@DarrelHoffman ultimately, a nice clear set of instructions makes either way work"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T20:55:57.370",
"Id": "263601",
"ParentId": "263537",
"Score": "3"
}
},
{
"body": "<p>One extra point which I don't think anyone has mentioned: when checking the start of an inputted string, don't use</p>\n<pre><code>if(player[0] == 'r'):\n</code></pre>\n<p>but rather</p>\n<pre><code>if(player[:1] == 'r'):\n</code></pre>\n<p>These will function identically unless <code>player</code> is the empty string, in which case the first will give an <code>IndexError</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T09:38:53.933",
"Id": "263623",
"ParentId": "263537",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "263550",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T07:15:00.077",
"Id": "263537",
"Score": "15",
"Tags": [
"python",
"rock-paper-scissors"
],
"Title": "My Rock, Paper, Scissors Game in Python"
}
|
263537
|
<p>I've written a simple text-based (can be run in terminal) snake game in python. This is a personal project and also one of my very first projects in python. I appreciate any advice or suggestion that make my code more efficient and professional.</p>
<p><strong>main.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from game import Game
if __name__=="__main__":
game = Game()
game.new_game([15,15])
game.run()
</code></pre>
<p><strong>game.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from time import sleep
from threading import Thread
from snake import Snake
from board import Board
class Game:
def __init__(self):
pass
def new_game(self, board_dim = [10, 10], level = "EASY"):
self.snake = Snake(2, [[2,2],[2,3]], "UP", board_dim)
self.board = Board(board_dim[0], board_dim[1], self.snake.pos)
self.thrd = Thread(target=self.snake.check_arrow_keys)
self.score = 0
def finish_game(self):
print(f"Your score is {self.score}")
self.thrd.join()
exit()
def run(self):
self.thrd.start()
while True:
print('\033c')
if not self.snake.status:
break
self.board.food_process(self.snake.normalize_pos())
if self.board.eaten:
self.score += 1
self.snake.move_toward_direction(increment_size=True)
else:
self.snake.move_toward_direction()
self.board.board_init(self.snake.normalize_pos())
self.board.show_board(self.snake)
print(f"score:{self.score}")
sleep(.2)
self.finish_game()
</code></pre>
<p><strong>board.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from random import randint
class Board:
def __init__(self, columns, rows, fill):
self.board = [[0 for j in range(columns)] for i in range(rows)]
self.fill = fill
self.col = columns
self.rows = rows
self.first = fill[-1]
self.put_food(fill)
def board_init(self, fill):
self.board = [[0 for j in range(self.col)] for i in range(self.rows)]
self.fill = fill
self.first = fill[-1]
for i in self.fill:
if i == self.first:
self.board[i[0]%self.rows][i[1]%self.col] = 2
else:
self.board[i[0]%self.rows][i[1]%self.col] = 1
self.board[self.food[0]][self.food[1]] = 3
def food_process(self, fill):
if self.check_food(fill):
self.eaten = True
self.put_food(fill)
else:
self.eaten = False
def normalize_fill(self, fill):
return [[i[0]%self.rows, i[1]%self.col] for i in fill]
def check_food(self, fill):
if self.food in self.normalize_fill(fill):
return True
return False
def put_food(self, fill):
while True:
x,y = randint(0,self.col-1), randint(0, self.rows-1)
if [x,y] not in self.normalize_fill(fill):
self.board[x][y] = 3
self.food = [x,y]
return
def show_board(self, snake):
board_ = ""
for i in self.board:
for j in i:
if j==1:
board_ += "@|"
elif j==2:
if snake.dir == "UP":
board_ += "^|"
elif snake.dir == "LEFT":
board_ += "<|"
elif snake.dir == "RIGHT":
board_ += ">|"
elif snake.dir == "DOWN":
board_ += "˅|"
elif j==3:
board_ += "*|"
else:
board_ += " |"
board_ += "\n"
board_ += "".join(["_ "*self.col])
board_ += "\n"
print(board_)
</code></pre>
<p><strong>snake.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from random import choice
from threading import Thread
import sys
import select
import tty
import termios
class Snake:
def __init__(self, length, pos, direction, board_size):
if length != len(pos):
raise Exception("Length is not equal to the size of `pos`")
self.len = length
self.pos = pos
self.dir = direction
self.last = pos[-1]
self.first = pos[0]
self.columns= board_size[0]
self.rows = board_size[1]
self.init_l = length
self.status = True
def normalize_pos(self):
return [ [p[0]%self.rows, p[1]%self.columns] for p in self.pos]
def move_toward_direction(self, step = 1, increment_size=False):
temp = self.last[:]
if self.dir.upper() == "UP":
temp[0] -= 1
if self.check(temp):
self.pos.append(temp)
else:
self.__lost()
elif self.dir.upper() == "DOWN":
temp[0] += 1
if self.check(temp):
self.pos.append(temp)
else:
self.__lost()
elif self.dir.upper() == "RIGHT":
temp[1] += 1
if self.check(temp):
self.pos.append(temp)
else:
self.__lost()
elif self.dir.upper() == "LEFT":
temp[1] -= 1
if self.check(temp):
self.pos.append(temp)
else:
self.__lost()
else:
raise Exception(f"Direction not correct!: {self.dir}")
if not increment_size :
self.pos.remove(self.first)
self.first = self.pos[0]
else:
self.len += 1
self.first = self.pos[0]
self.last = self.pos[-1]
def check(self, tmp):
if tmp not in self.normalize_pos() and tmp not in self.pos:
return True
else:
return False
def rand_direction(self):
counter = 0
while True:
tmp = choice(["UP","RIGHT","LEFT","DOWN"])
#chcs = [i for i in ["UP","RIGHT","LEFT","DOWN"] if self.check(i)]
temp = self.last[:]
if tmp == "UP" :
temp[0] -= 1
elif tmp == "DOWN" :
temp[0] += 1
elif tmp == "RIGHT":
temp[1] += 1
elif tmp == "LEFT" :
temp[1] -= 1
else:
raise Exception(f"Direction not correct!: {tmp}")
if self.check(temp):
self.dir = tmp
return
counter += 1
if counter > 32:
raise Exception("No movement is possible")
def check_arrow_keys(self):
old_settings = termios.tcgetattr(sys.stdin)
try:
tty.setcbreak(sys.stdin.fileno())
while 1:
if self.__isData() or self.status:
c = sys.stdin.read(3)
if c == '\x1b[A':
if self.dir != "DOWN":
self.dir = "UP"
elif c == '\x1b[B':
if self.dir != "UP":
self.dir = "DOWN"
elif c == '\x1b[D':
if self.dir != "RIGHT":
self.dir = "LEFT"
elif c == '\x1b[C':
if self.dir != "LEFT":
self.dir = "RIGHT"
else:
pass
else:
return
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
def __isData(self):
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
def __lost(self):
self.status = False
</code></pre>
<p>also this is <a href="https://github.com/Riahiamirreza/snake_game" rel="nofollow noreferrer">link</a> of project on github. If you enjoyed the project, please give me star on github :D</p>
<p><strong>Edit:</strong>
I noticed that if I run the program on the tmux, it will looks very better (It does not blink).</p>
|
[] |
[
{
"body": "<p>First off, nice game! It plays pretty smoothly. The code looks decent as-is, which is why I'm going more in depth--high level, no improvements are really needed.</p>\n<p>I'll go through by file, since it's split up.</p>\n<h2>General comments</h2>\n<ul>\n<li>Read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.</li>\n<li>Be consistent about using blank lines. Don't leave a blank after a function <code>def</code>.</li>\n<li>Add type annotations</li>\n<li>Remove debugging code and commented-out code.</li>\n<li>I had trouble figuring out what functions did and didn't handle--I had to guess too much. Partly this is naming, partly it's lack of docstring or comments, and partly it's file organization. Also, it's just hard for a medium-sized game like this.</li>\n<li>Add docstrings to your methods to explain what each one does. Remember to explain the method in terms of "when would I want to call this?" rather than "what does it do inside?"</li>\n<li>In a couple places, you used <code>while True</code> loops. Try to use a more specific condition if you can, because then the reader can immediately read it and say "oh, the loop ends when..."</li>\n</ul>\n<h2>User Testing</h2>\n<p>I tested this out. Some notes:</p>\n<ul>\n<li>Very clean visuals (although not all the characters display in my font).</li>\n<li>Movement feels silky smooth on my computer.</li>\n<li>It seems like the heart is drawn over the snake for a while after you eat it</li>\n<li>Once you die, you have to press a key to exit.</li>\n<li>I managed to wiggle the snake around and get a score of 0 somehow at the start. There may be race conditions in the threading.</li>\n<li>Overall looks cool!</li>\n</ul>\n<h2>main.py</h2>\n<ul>\n<li>Looks good.</li>\n</ul>\n<h2>game.py</h2>\n<ul>\n<li>Pass the same parameters you would to <code>new_game</code> to <code>__init__</code> instead, and remove <code>new_game</code>.</li>\n<li>Take the entire contents of the <code>run</code> loop. Split these into <code>get_input</code>, <code>do_tick</code>, and <code>update_display</code>. Right now there is no input processing in <code>game.py</code> which is a little confusing for someone trying to understand how it gets done.</li>\n<li>Have <code>board.show_board</code> return a board, and print it here. Try to put all your print statements in one file.</li>\n<li>Change the <code>run</code> loop to <code>while self.snake.alive</code> for clarity (change from <code>.status</code> to <code>.alive</code> for this reason)</li>\n</ul>\n<h2>board.py</h2>\n<ul>\n<li>I would say this is the file that needs the most improvement, but I don't have great answers as to how.</li>\n<li>Generally, this could use more separation between displaying the board, vs tracking the game state.</li>\n<li>Add a docstring to each method. In particular: <code>board_init</code>, <code>food_process</code>, <code>normalize_fill</code>, <code>check_food</code>, <code>put_food</code> all need one to figure out what they do. Even <code>show_board</code> is a little fuzzy in that I don't know if it will clear the screen or print the score</li>\n<li>There are too many blank lines</li>\n<li>Don't use hardcoded values 1 to 3 for board contents. Instead, use an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a></li>\n<li>Initialization:\n<ul>\n<li>I don't know what <code>board.fill</code> is based on the name, or <code>board.first</code>.</li>\n<li>Rename <code>board.food</code> to <code>board.food_pos</code></li>\n</ul>\n</li>\n<li><code>board_init</code> sounds like it should be called exactly once, at startup, but instead it's called every game tick. I'm not sure what it does.</li>\n<li>I don't know what <code>board.normalize_fill</code> or <code>snake.normalize_pos</code> do based on the name.</li>\n<li>Rename <code>check_food</code> to <code>is_food_on_board</code>. Make it a one-liner.</li>\n<li>Rename <code>put_food</code> to <code>place_random_food</code>. This is a good use of <code>while True</code>.</li>\n<li>In <code>show_board</code>, use the names <code>x,y</code> or <code>row,column</code> instead of <code>i,j</code>.</li>\n</ul>\n<h2>snake.py</h2>\n<ul>\n<li>Define an ENUM of directions</li>\n<li>Your initialization process is good. The variables are clear, but I think they could be trimmed or renamed in some cases.\n<ul>\n<li>You don't need <code>self.init_l</code>.</li>\n<li>Change <code>snake.status</code> to <code>snake.alive</code>.</li>\n<li>Change <code>first</code> and <code>last</code> to <code>head</code> and <code>tail</code>, which are clear for a snake. Then delete <code>head</code> and <code>tail</code>, because it's bad to have two variables that can be out of sync--if you want, <code>@property</code> might be a good fit instead.</li>\n<li>Change <code>pos</code> to something like <code>occupied_squares</code> because it's not clear it's a list from the name.</li>\n</ul>\n</li>\n<li>Add a docstring to <code>normalize_pos</code> and <code>check</code>, and <code>__isData</code>.</li>\n<li><code>move_toward_direction</code> is too repetitive, shrink it. Remove the unused <code>step</code> parameter as well.</li>\n<li>Rename <code>self.__lost()</code> to <code>self.lose()</code> or <code>self.alive = False</code>. Prefer present tense action verbs for method names.</li>\n<li>Remove <code>rand_direction</code>, which looks like unused testing code.</li>\n<li>Move <code>check_arrow_keys</code> elsewhere, such as into <code>game.py</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-23T08:31:02.077",
"Id": "269286",
"ParentId": "263541",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "269286",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T09:11:20.217",
"Id": "263541",
"Score": "4",
"Tags": [
"python",
"snake-game"
],
"Title": "A simple text based snake game in python"
}
|
263541
|
<p>I have been working on a small script which scrapes a webpage and returns the information that has been scraped such as name, iamge, price etc etc.. However I am abit concern regarding my exceptions where I do not believe I am covering it correct or could improve it as well.</p>
<p>For now I have done something like this:</p>
<pre><code>import time
from typing import List, Optional
import attr
import requests
from loguru import logger
from requests.exceptions import (
ConnectionError,
ConnectTimeout,
ProxyError,
ReadTimeout,
ChunkedEncodingError,
SSLError,
RequestException,
Timeout
)
from selectolax.parser import HTMLParser
@attr.dataclass
class Info:
"""Scraped info about product"""
link: str = attr.ib(factory=str)
name: Optional[str] = attr.ib(factory=str)
price: Optional[str] = attr.ib(factory=str)
image: Optional[str] = attr.ib(factory=str)
# -------------------------------------------------------------------------
# Get all latest products found in the webpage
# -------------------------------------------------------------------------
def from_page(url) -> List[Info]:
while True:
try:
infos = []
proxies = {
"https": "http://1234:1242"
}
with requests.get(url, proxies=proxies, timeout=5) as rep:
if rep.status_code in (200, 404):
doc = HTMLParser(rep.text)
for product in doc.css('article.product-wrapper'):
name = product.css_first('div.product-image > a').attributes.get('title')
link = product.css_first('div.product-image > a').attributes.get('href')
image = product.css_first('div.product-image > a > img').attributes.get('data-original')
price = product.css_first('span.price-amount,')
infos.append(Info(
link=f"https://www.footish.se{link}",
name=name,
price=price.text(),
image=f"https://www.footish.se{image}"
))
return infos
rep.raise_for_status()
# Retry after 5 seconds
except ProxyError as err:
logger.info(f'Proxy Error | {proxies["https"]} | URL -> {url} | Exception -> {err}')
time.sleep(5)
continue
# Retry after 5 seconds
except (ReadTimeout, Timeout, ConnectTimeout, ConnectionError, ChunkedEncodingError, SSLError) as err:
logger.info(f'Timeout/Connection | {proxies["https"]} | URL -> {url} | Exception -> {err}')
time.sleep(5)
continue
# Should throw exception if its something we do not expect
except RequestException as err:
logger.info(f'RequestException | {proxies["https"]} | URL -> {url} | Exception -> {err}')
time.sleep(5)
continue
# Very serious if its something else than requests
except Exception as err:
logger.exception(f'Unexpected caught | {proxies["https"]} | URL -> {url}')
time.sleep(5)
raise
if __name__ == '__main__':
all_found_products = set()
URL = "https://www.footish.se/sneakers"
feed: List[Info] = from_page(url=URL)
for add_url in feed:
if add_url.link not in all_found_products:
all_found_products.add(add_url.link)
while True:
feed: List = from_page(url=URL)
for new_url in feed:
if new_url.link in all_found_products:
logger.info(f"Found new URL {new_url.link}")
all_found_products.add(new_url.link)
logger.info(
f'[Products Found: {len(feed)}]'
f'[Total Products Found: {len(all_found_products)}]'
)
time.sleep(120)
</code></pre>
<p>I would like a code review regarding the exceptions to see if I could do any better improvements from here :)</p>
<p>Regards,</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T11:22:17.030",
"Id": "263545",
"Score": "0",
"Tags": [
"python-3.x"
],
"Title": "Scrape website with exceptions"
}
|
263545
|
<p>Playing on leetcode coding problem: "Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses."</p>
<p>I realized that my understanding of Python was not so good. I always thought that: since list are mutable object they are kind of passed by reference; so i always try to make a copy of the list before feeding the function to avoid inappropriate behavour as i did below:</p>
<pre><code>class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
def add_parenthesis(l,o,f):
if len(l)==2*n:
res.append("".join(l))
return
if f<o:
return
if o>0:
lp = l.copy()
lp.append("(")
add_parenthesis(lp,o-1,f)
if f>0:
lm = l.copy()
lm.append(")")
add_parenthesis(lm,o,f-1)
add_parenthesis(['('],n-1,n)
return res
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T12:59:26.410",
"Id": "520288",
"Score": "0",
"body": "We can't review your friend's code here, nor do we explain how code works - you're expected to understand that if you wrote it! Additionally, your title should summarise the _problem being solved_ (e.g. \"Generate valid combinations of parentheses\") rather than the coding mechanism you used to achieve it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T13:27:55.013",
"Id": "520290",
"Score": "3",
"body": "Ok i will make some changes!"
}
] |
[
{
"body": "<p>In the future, for purposes for code review, please include an example case to run. This makes it easier for reviewers.</p>\n<pre><code>if __name__ == '__main__':\n all_solutions = Solution().generate_parentheses(4)\n print(all_solutions)\n</code></pre>\n<h2>Style</h2>\n<ul>\n<li>Your variable names are <code>l</code>, <code>o</code>, <code>f</code>, <code>p</code>, <code>m</code>, <code>lp</code>, <code>lm</code>, and <code>res</code>. Use descriptive names instead.</li>\n<li>Not all code needs comments, but algorithmic code usually does. Add an explanation of how this works.</li>\n<li>The <code>Solution</code> class doesn't do anything. Drop it, and just define your function directly.</li>\n</ul>\n<h2>Data structures</h2>\n<ul>\n<li>It's considered bad style to mutate variables not passed into the function. You're essentially using <code>res</code> as a global variable. Global variables are bad, for a variety of reasons. See if you can rewrite it without a global variable, and choose whichever you like better.</li>\n<li>Since you output a string at the end, go ahead and just pass around strings the whole time instead of lists. The main advantage of lists would be to avoid copying them, but you're already doing that everywhere.</li>\n<li>There are a <strong>lot</strong> of different ways to generate parentheses. You may consider writing a python <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator</a> instead, using <code>yield</code> or a generator expression. That way, you don't have to store a result list, which will matter for large values of <code>n</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-23T07:41:17.423",
"Id": "269284",
"ParentId": "263547",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T11:50:58.157",
"Id": "263547",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"balanced-delimiters"
],
"Title": "Generate valid combinations of parentheses"
}
|
263547
|
<p>I just want your opinion about that code! :)</p>
<pre><code>import random
class Error(Exception):
def __init__(self, error=None):
self.error = error
def __str__(self):
return str(self.error)
class HashTable(object):
def __init__(self):
self.length = 20
self.keys = []
self.table = [[] for _ in range(self.length)]
def __len__(self):
return self.length
def __setitem__(self, key, value):
self.keys.append(key)
hashed_key = self._hash(key)
self.table[hashed_key].append((value)) #Wartosc jest dodawana do listy pod hashowanym indeksem
def _hash(self, key) :
return hash(key) % self.length
def show_list(self):
return self.table
def __getitem__(self, key):
for el in self.table[self._hash(key)]:
if el[0] == key:
return el[1]
def __delitem__(self, key):
for el in self.table[self._hash(key)]:
if el[0] == key:
self.table[self._hash(key)].remove(el)
def __iter__(self):
def Generator(data):
mylist = [_ for _ in data]
for i in mylist:
yield i
return Generator(self.table)
L = HashTable()
content = []
with open("song.txt", 'r', encoding = 'utf8') as travis:
for line in travis:
for word in line.split():
content.append(word)
for c in content:
L[c] = c
for x in L:
print(x)
</code></pre>
<p>I've also will be really greateful for any tips and how to improve this one! :D</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T14:40:50.200",
"Id": "520398",
"Score": "1",
"body": "I'm going to assume that you're not using a built-in dictionary for learning purposes etc., but that would greatly simplify this code."
}
] |
[
{
"body": "<p>My opinion is that you should test better, before asking for code review.</p>\n<pre><code>line = " #Wartosc jest dodawana do listy pod hashowanym indeksem"\nfor word in line.split():\n content.append(word)\nfor c in content:\n L[c] = c\nprint(L["jest"])\n</code></pre>\n<p>Put a <code>print</code> statement inside each of your functions, for example <code>print('__getitem__ ran')</code>. Then keep modifying your test code until you see all of them. Right now you are not using all your methods.</p>\n<p>Edit: Also, this is not really something I will code review once tested. The correct review is to replace it with:</p>\n<pre><code>HashTable = dict\n</code></pre>\n<p>Both the readability and efficiency are miles better than yours!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T09:18:47.283",
"Id": "266580",
"ParentId": "263552",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T13:39:10.687",
"Id": "263552",
"Score": "1",
"Tags": [
"python",
"reinventing-the-wheel",
"hash-map"
],
"Title": "Hashing Table in Python"
}
|
263552
|
<p>I have this function:</p>
<pre class="lang-py prettyprint-override"><code>import re
def check_and_clean_sequence(sequence, alphabet):
"""
Function to check and clean up all ambiguous bases in a sequence.
Ambigous bases are bases that are not in the sequence
alphabet, ie. 'ACGT' for DNA sequences.
Inputs:
sequence - a string representing a DNA sequence.
alphabet - set/string representing the allowed
characters in a sequence.
Outputs:
cleaned_sequence - cleaned sequence or a string.
"""
if set(sequence).issubset(alphabet):
return sequence
else:
return cleaning_ambiguous_bases(sequence)
def cleaning_ambiguous_bases(sequence):
"""
Function to clean up all ambiguous bases in a sequence.
Ambiguous bases are bases that are not in the sequence
alphabet, ie. 'ACGT' for DNA sequences.
Inputs:
sequence - a string representing a DNA sequence.
Outputs:
integer - a new clean up string representing a DNA sequence
without any ambiguous characteres.
"""
# compile the regex with all ambiguous bases
pat = re.compile(r'[NRYWXSKM]')
# look for the ambiguous bases and replace by
# nothing
new_seq = re.sub(pat, '', sequence)
return new_seq
</code></pre>
<p>The performance in jupyter notebook with timeit is around:</p>
<pre class="lang-none prettyprint-override"><code>%timeit check_and_clean_sequence(seq, iupac_dna)
200 ms ± 436 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<p>This was calculated with a DNA sequence with 5539776 pb or 5539.776 kpb. The sequence can be downloaded from:
<a href="https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/005/845/GCF_000005845.2_ASM584v2/GCF_000005845.2_ASM584v2_genomic.fna.gz" rel="nofollow noreferrer">E. coli genome</a></p>
<p>The function receive a big string and check if there are any characters that
are not in the allowed alphabet (in the case the IUPAC DNA = 'ACGT').
If the sequence has they are cleaned up and the function returns a new sequence,
otherwise return the original one.</p>
<p>Are there are tips or tricks to improve this time?</p>
<p>Toy example:</p>
<pre><code>>>> import re
>>> alphabet = 'ACGT'
>>> toy_sequence = 'AGCTAGGGACATTGAGGACCACCACAXYXMAAAAAA'
>>> check_and_clean_sequence(toy_sequence, alphabet)
'AGCTAGGGACATTGAGGACCACCACAAAAAAA'
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T17:23:38.417",
"Id": "520327",
"Score": "6",
"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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T21:23:38.340",
"Id": "520425",
"Score": "2",
"body": "Like I said before - please stop modifying (including adding) code in your post. If you have an updated version then you can create a new post and [edit] to add a link to it."
}
] |
[
{
"body": "<p>Perhaps there aren't enough test cases here, because I don't see why you can't just use:</p>\n<pre><code>pattern = re.compile(r"[^ACGT]")\nprint(pattern.sub("", toy_sequence))\n</code></pre>\n<p>Which says replace all characters that are not in <code>ACGT</code> with blanks. Thus, you do not need to know which characters are illegal, only those which are legal. This should be very fast, doesn't require a function definition because compiling <code>pattern</code> really serves as your function, which you now call with <code>pattern.sub</code>, and is a lot easier to read.</p>\n<h1>Redundant functions</h1>\n<p>If this is a satisfactory answer, I'd like to say that</p>\n<pre><code>def check_and_clean_sequence(sequence, alphabet):\n</code></pre>\n<p>is not a valuable function even if my solution did not work. <code>cleaning_ambiguous_bases</code> will achieve the same result and it will not be any slower. Checking first will at <em>best</em> perform the same as just calling <code>cleaning_ambiguous_bases</code> because regardless, you need to check every character. However, if you check first, you will iterate through the sequence potentially twice: once to check, and then once to replace. It's faster to just walk through once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:54:42.897",
"Id": "520319",
"Score": "0",
"body": "when you get so involved in coding that sometimes this kind of redundancy escape from the eyes...Thanks a lot!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:56:44.847",
"Id": "520321",
"Score": "1",
"body": "@PauloSergioSchlogl Don't worry about it! It's happened to all of us before, that's why we're here. Glad I could help :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T15:35:51.253",
"Id": "520402",
"Score": "0",
"body": "@PauloSergioSchlogl: I did some testing with sequences that don't need cleaning, e.g. `\"AGCTAGGGACATTGAGGACCACCACAAAAAAAAGCTAGGGACATTGAGGACCACCACAAAAAAA\"`. With this string, `check_and_clean_sequence()` is twice as fast as `cleaning_ambiguous_bases()` on my system (it is still slower than the suggested `pattern.sub()` solution, though). The reason for this is that turning the string into a set greatly reduces the comparisons that need to be made. I'd argue, then, that we can't just assume that the check is redundant as it depends on the length and the messiness of the input."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:16:27.330",
"Id": "263555",
"ParentId": "263553",
"Score": "13"
}
},
{
"body": "<p>There's an inconsistency between the two functions. <code>check_and_clean_sequence()</code> has an <code>alphabet</code> parameter, but this isn't used by the inner function, which has a hard-coded list of invalid characters to remove.</p>\n<p>The <code>check_and_clean_sequence()</code> function doesn't add value - all it does is add overhead of an extra pass through the string (<code>re.sub()</code> will just do a single pass and return the original string if there's nothing to change).</p>\n<p>In the docstrings, there are many (different!) misspellings of the word "ambiguous". I know it's not an easy word for a non-native speaker, but it shouldn't be hard to fix those.</p>\n<p>You could possibly use <code>filter()</code> to keep only the characters in <code>alphabet</code>, but my guess is that it's unlikely to beat <code>re</code> for speed. <code>re.compile()</code> creates a simple, fast, DFA (discrete finite automaton) that's highly optimised for matching. The best improvement you could make is to compile the regex just once, rather than every call. And then as Kraigolas suggest, replace the function call with a simple <code>pattern.sub()</code> (I guess you could bind the empty-string first argument, to get a function that accepts just the sequence).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T17:04:06.877",
"Id": "520325",
"Score": "0",
"body": "Thank you for your clarification! I will check for the misspellings! 8)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T16:22:36.050",
"Id": "263557",
"ParentId": "263553",
"Score": "8"
}
},
{
"body": "<p>From the bioinformatics side, not the python one: Your return will be non-useful for further processing whenever an ambiguous base has been present, because it changes index locations! You'll want to fix that before worrying about how long it takes to run...</p>\n<p>DNA and RNA are themselves a form of coding language: three base units ('codons') describe amino acids. Whenever a base is deleted, a 'frameshift' occurs: every codon after that point now starts a space sooner than it should. (In vivo, a single frameshift mutation is usually sufficient to completely shut off one - or more! - genes. In other words, this is not a trivial situation.) <strong>You cannot <em>interpret</em> genetic sequences correctly if you change the index location of the bases!</strong></p>\n<p>There are three paths to usefully 'cleaning' your genome information, depending on why you wanted to do that in the first place:</p>\n<ol>\n<li><p>If space is at a premium:</p>\n<p>Drawing from Kraigolas: use the code as described, but rather than replacing with the empty string, replace with a uniform "this base is ambiguous" marker, thus maintaining index locations. ('N' is the standard for this specific application.)</p>\n<pre><code> pattern = re.compile(r"[^ACGT]")\n print(pattern.sub("N", toy_sequence))\n</code></pre>\n<p>Another solution in this vein is to store bases as tuples of (index [type:int], base type [could handle a number of ways]) but this is probably space-inefficient</p>\n</li>\n<li><p>If neither space nor preprocessing are an optimization concern: Don't do any deletion or substitution of these characters at all.</p>\n<p>Look at the documentation related to the source of your sequences; there will either be an interpretation key for their specific method <a href=\"https://genomevolution.org/wiki/index.php/Ambiguous_nucleotide\" rel=\"nofollow noreferrer\">or they'll be using the standard lookup table</a>.\nWhen a subsequent step will be to interpret a sequence into an amino acid string (likely application) or to look for "similar" sequences in a database (also a likely application), knowing the difference between the code that means "either A or T" and the code that means "either C or G" will <em>save</em> you processing time and/or get less ambiguous <em>results</em>.</p>\n</li>\n<li><p>If preprocessing is a concern:</p>\n<p>As in 2, refer to the appropriate <a href=\"https://genomevolution.org/wiki/index.php/Ambiguous_nucleotide\" rel=\"nofollow noreferrer\">lookup table</a> for what ambiguous codes mean.\nRead your sequence into a [length of sequence]x4 array of binary values.\nColumn 1 is "can be A?", column 2 is "can be T?", etc. -</p>\n<p>Example: AGCCNCS would become</p>\n<pre><code> 1 0 0 0\n 0 0 1 0\n 0 0 0 1\n 0 0 0 1\n 1 1 1 1\n 0 0 0 1\n 0 0 1 1\n</code></pre>\n<p>As appropriate codon matches (there are almost always more than one) for specific amino acids can be easily described in the same way, it's relatively trivial to use this format for a variety of purposes, and it removes assorted other headaches with accurately interpreting the ambiguous codes.</p>\n<p>(For examples of how to apply them - treating the bin as if they're integers, if the dot product of each row in two sequence matrixes is at least 1, you have a 'match' of codes!)</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T20:32:54.567",
"Id": "520416",
"Score": "0",
"body": "Man you totally right I just having a hard time coding this kmers count functions efficiently. I know there are a lot of tools out there but I am learning python them I need to code to learn! Then I am write my own code! But some times some obvious details get out of control. Thanks to you I avoid a big mistake. Thank you a lot. I will go back to basics and use something like if set(kmer).issubset(set(alphabet)) to avoid ambiguous kmers in the final counts. This way I will keep all the indexes corrects. Thank you a lot! Its better a slow and correct code than a quick and wrong one. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T16:02:03.740",
"Id": "263589",
"ParentId": "263553",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "263589",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T14:30:27.030",
"Id": "263553",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"regex",
"bioinformatics"
],
"Title": "Filter out ambiguous bases from a DNA sequence"
}
|
263553
|
<p>I created a fairly simple hangman program as a little side project. Could you please tell me of any improvements/suggestions/criticism/feedback that you have about my code? Thank you in advance.</p>
<pre><code>import tkinter as tk
import turtle
import string
from functools import partial
from draw_hangman import drawHangman
from random import randint
intro = tk.Tk()
intro.title('Menu')
intro_text = tk.Label(intro, text = 'Welcome to Hangman\nPlease choose your\ndifficulty rating:')
easy = tk.Button(intro, text = 'Hard (3-5 letters)', command = lambda: difficulty(3, 5))
medium = tk.Button(intro, text = 'Medium (5-10 letters)', command = lambda: difficulty(5, 10))
hard = tk.Button(intro, text = 'Easy (10-15 letters)', command = lambda: difficulty(10, 15))
intro_text.grid(row = 0, column = 0)
easy.grid(row = 1, column = 0, sticky = 'news')
medium.grid(row = 2, column = 0, sticky = 'news')
hard.grid(row = 3, column = 0, sticky = 'news')
def enable():
easy.config(state = 'normal')
hard.config(state = 'normal')
medium.config(state = 'normal')
root.destroy()
def disableButtons():
for w in root.winfo_children():
if 'button' in str(w):
w.configure(state="disabled")
def whenGuessed():
win = ''
global drawRate
if entry.get().lower() == word:
win = 'You win!'
lab.config(text = word)
disableButtons()
t.clear()
else:
trash = draw[drawRate]
exec(trash)
drawRate+=1
if drawRate > len(draw)-1:
win = 'You lose!'
lab.config(text = word)
disableButtons()
t.clear()
if win != '':
entry.delete(0, tk.END)
entry.insert(0, win)
def whenPressed(button, text):
global drawRate
win = ''
button.config(state = 'disabled')
ind = []
local_word = list(word)
for i in local_word :
if i == text:
trash = local_word.index(i)
ind.append(trash)
local_word.pop(trash)
local_word.insert(trash, '-')
if len(ind) != 0:
for i in ind:
shown_text.pop(i)
shown_text.insert(i, text)
lab.config(text = ''.join(shown_text))
for i in shown_text:
if i == '-':
trash = True
if trash != True:
win = 'You win!'
disableButtons()
t.clear()
else:
trash = draw[drawRate]
exec(trash)
drawRate+=1
if drawRate > len(draw)-1:
win = 'You lose!'
lab.config(text = word)
disableButtons()
t.clear()
if win != '':
entry.delete(0, tk.END)
entry.insert(0, win)
def difficulty(minimum, maximum):
global word, lab, root, shown_text, drawRate, draw, t, entry
file = open(r"C:\Users\d_j_d\Desktop\words.txt", 'r').read().split('\n')
word = ''
while len(word) < minimum or len(word) >= maximum:
word = file[randint(0, len(file)-1)]
shown_text = list('-'*len(word))
draw = drawHangman()
drawRate = 0
root = tk.Tk()
root.title('Hangman 3.0')
t = turtle.Turtle()
easy.config(state = 'disabled')
hard.config(state = 'disabled')
medium.config(state = 'disabled')
root.protocol("WM_DELETE_WINDOW", enable)
length = tk.Label(root, text = 'Length: '+str(len(word)))
length.place(relx = 1, rely = 1)
alphabet = list(string.ascii_lowercase)
lab = tk.Label(root, text = '-'*len(word), font = (None, 15), width = 30)
lab.grid(row = 0, columnspan = 13, column = 0)
entry = tk.Entry(root)
entry.grid(row = 3, columnspan = 10, sticky = 'news', column = 0)
button = tk.Button(root, text = 'Enter', command = whenGuessed)
button.grid(row = 3, columnspan = 3, sticky = 'news', column = 10)
for i in alphabet:
btn = tk.Button(root, text=i)
command = partial(whenPressed, btn, i)
btn.config(command=command)
row = (alphabet.index(i) // 13)+1
column = alphabet.index(i) % 13
btn.grid(row=row, column=column, sticky="news")
</code></pre>
<p><code>drawHangman</code> function:</p>
<pre><code>import turtle
t = turtle.Turtle()
draw = [
'''t.speed(10)
t.penup()
t.fd(200)
t.rt(90)
t.fd(200)
t.down()
t.lt(270)
t.fd(400)''',
'''t.rt(90)
t.fd(400)''',
'''t.rt(90)
t.fd(300)''',
'''t.rt(90)
t.fd(75)
t.dot(75)''',
't.fd(100)',
'''t.lt(90)
t.fd(60)
t.back(120)
t.fd(60)
t.rt(90)''',
'''t.fd(75)
t.lt(30)
t.fd(100)''',
'''t.back(100)
t.rt(60)
t.fd(100)''']
def drawHangman():
return draw
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T18:10:40.027",
"Id": "263560",
"Score": "1",
"Tags": [
"python-3.x",
"tkinter",
"hangman"
],
"Title": "Hangman program (python)"
}
|
263560
|
<p>I am inserting data from a dict type object into three different tables in the SQL database. I am using Sqlalchemy as my ORM. My code is working but I think it is not very readable, is it any way to make it more readable or maybe simpler? I am using a lot of <code>try except</code> because I don't want my code to fail in the middle and also because all the three tables are related to each other.</p>
<p>My code is below:</p>
<pre><code>def upload_fpb_data(data, project_id):
fpb_count = len(data)
fpb_added_count = 0
fpb_children_count = sum(map(lambda x : x['count'], data))
fpb_children_added_count = 0
fpb_children_base_color_count = sum([sum(map(lambda x: x['count'], i['children'])) for i in data])
fpb_children_base_color_added_count = 0
for parent in data:
parent_data = parent['data']
add_fpb = FPB(stockCode=parent_data[0], description=parent_data[1],
longDescription=parent_data[2], altKey=parent_data[3],
project=project_id)
db.session.add(add_fpb)
try:
db.session.commit()
fpb_added_count += 1
for child1 in parent['children']:
child1_data = child1['data']
add_fpb_children = FpbChildrenAssociation(ParentPart=child1_data['ParentPart'],
Component=child1_data['Component'], qty=child1_data['ComponentQtyPer'])
db.session.add(add_fpb_children)
try:
db.session.commit()
fpb_children_added_count+=1
fpb_children_association_id = add_fpb_children.id
for child2 in child1['children']['data']:
add_fpb_children_base_colors = FpbChildrenBaseColorAssociation(
fpbChildrenAssociationId=fpb_children_association_id,
baseColor=child2,
)
db.session.add(add_fpb_children_base_colors)
try:
db.session.commit()
fpb_children_base_color_added_count +=1
except:
db.session.rollback()
except Exception as e:
db.session.rollback()
except Exception as e:
db.session.rollback()
return {'fpb':f"Rows Appended {fpb_added_count}/{fpb_count}",
'fpbChildrenAssociation':f"Rows Appended {fpb_children_added_count}/{fpb_children_count}",
'fpbChildrenBaseColorAssociation':f"Rows Appended {fpb_children_base_color_added_count}/{fpb_children_base_color_count}"}
</code></pre>
<p>if you want to see the data I am working with then here it is:</p>
<pre><code>data = [{'table': 'fpb',
'data': ('XPB.20.001.07.200.01', 'SSLDX STERN BOX', '', '20SX200'),
'children': [{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'DID-1828A-50-V1.20.001.00', 1.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'RFH0136SLV', 1.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'RFN0019', 4.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'RFN0036', 4.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'RFN0043', 4.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'RFN0046B', 4.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'RFN0091', 4.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'RFN0126', 1.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'RPP0134', 4.0],
'count': 3,
'children': {'table': 'fpbChildrenBaseColorAssociation',
'data': ['00', '60', '90']}},
{'table': 'fpbChildrenAssociation',
'data': ['XPB.20.001.07.200.01', 'X.001.07.44579', 1.0],
'count': 1,
'children': {'table': 'fpbChildrenBaseColorAssociation', 'data': ['60']}}],
'count': 10}]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T07:23:13.670",
"Id": "520365",
"Score": "0",
"body": "@BCdotWEB i have changed the title. Thanks"
}
] |
[
{
"body": "<p>If you are concerned about <strong>data integrity,</strong> that's what <strong>transactions</strong> are for. I don't really see the point of nested try/catch blocks. A single block for the whole procedure would be sufficient.</p>\n<p>So, at the start of your try block, you start an explicit transaction using <code>session.begin()</code>, you do your stuff and finally you <strong>commit</strong> at the end, or <strong>rollback</strong> in case of exception. That's it.</p>\n<p>As an example:</p>\n<pre><code># verbose version of what a context manager will do\nwith Session(engine) as session:\n session.begin()\n try:\n session.add(some_object)\n session.add(some_other_object)\n except:\n session.rollback()\n raise\n else:\n session.commit()\n</code></pre>\n<p>The source (recommended): <a href=\"https://docs.sqlalchemy.org/en/14/orm/session_basics.html\" rel=\"nofollow noreferrer\">SQLAlchemy - Session Basics</a></p>\n<p>If you want an all or nothing operation that's what you should be doing. Presently, you are doing regular commits, and it's perfectly possible that the code will fail in the middle. Thus some tables can be populated without matching records in the other related tables.</p>\n<p>Just removing those nested blocks should increase readability. Then consider adding some <strong>comments</strong>. And line spacing. The code is a bit terse. Regarding the naming conventions, I am not sure about what kind of data you are handling but I am thinking the names could perhaps be more telling that child or children something ?</p>\n<p>Instead of incrementing a counter manually like this:</p>\n<pre><code>fpb_added_count += 1\n</code></pre>\n<p>you could use the <code>enumerate</code> function like this:</p>\n<pre><code>for fpb_added_count, child1 in enumerate(parent['children'], start=1):\n</code></pre>\n<p>But your objects may have a len() property already right. Do you really need to keep track of item counts separately ?</p>\n<p>This variable <code>child1_data</code> does not seem to be really useful:</p>\n<pre><code>child1_data = child1['data']\n</code></pre>\n<p>Why not simply just use <code>child1['data']</code>.</p>\n<p>Same for <code>fpb_children_association_id</code> etc, that makes the code harder to follow for no real benefit I think. There is no real improvement or simplification.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T02:49:11.797",
"Id": "520354",
"Score": "0",
"body": "Thanks for the answer. I am not looking to rollback the whole transaction if only one table fails. That's why I added them in a particular order. Do you there is an easier way to do that?\n\nYes, I would like to keep the track of the counts so that I can tell the user how many of the rows have been added out of the actual number of rows for each table."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T22:11:07.347",
"Id": "263567",
"ParentId": "263563",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T20:13:23.530",
"Id": "263563",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"sqlalchemy"
],
"Title": "Inserting Data to three linked table with SQLAlchemy"
}
|
263563
|
<p>For a Metal application, I would like to create and initalize texture object globally so it will not have to be optional, and will already be ready to use once <code>viewDidLoad</code> is called. To do this, I need a <code>MTLTextureDescriptor</code> with the correct values <em>inline</em>. It has to be inline because I do not want to create a global descriptor that will only be used once, and since this file is not <code>main.swift</code>, out of line code at the top level will not be accepted. I have:</p>
<pre><code>let Device = MTLCreateSystemDefaultDevice()!, TerrainTexture = Device.makeTexture(descriptor: ({
let Descriptor = MTLTextureDescriptor()
Descriptor.textureType = .type2DArray
Descriptor.arrayLength = TERRAIN_TEXTURES_COUNT
Descriptor.width = TERRAIN_TEXTURE_SIZE
Descriptor.height = TERRAIN_TEXTURE_SIZE
Descriptor.mipmapLevelCount = TERRAIN_TEXTURE_MIPMAP_LEVEL_COUNT
return Descriptor
})())!
</code></pre>
<p>I define a closure, and call it to get a descriptor to get a texture, all inline, since the initializer of <code>MTLTextureDescriptor</code> does not have parameters for these values, so I need to set them manually. But is making a closure inline and calling it really the cleanest way to simply initialize the values of a struct or class to constant values inline? Is there a nicer way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-12T17:07:40.153",
"Id": "528286",
"Score": "0",
"body": "Please forgive the unrelated observation, but in Swift, variable/property names always start with a lowercase letter (e.g. `terrainTexture` rather than `TerrainTexture`). Uppercase is reserved for type names (e.g. classes, structs, enum types, etc.). Also, the un-namespaced, screaming snake case of those constants (e.g. `TERRAIN_TEXTURE_SIZE` vs `Constants.terrainTextureSize` or whatever) is distinctly unswifty, too, feeling like it was inherited from an old ObjC codebase."
}
] |
[
{
"body": "<p>You said:</p>\n<blockquote>\n<p>It has to be inline because I do not want to create a global descriptor that will only be used once</p>\n</blockquote>\n<p>The provided pattern, where you call <code>makeTexture</code> with a parameter that is a closure is a bit hard to read. Instead, you can initialize the whole <code>MTLTexture</code> with a closure:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let device = MTLCreateSystemDefaultDevice()!\n\nlet terrainTexture: MTLTexture = {\n let descriptor = MTLTextureDescriptor()\n descriptor.textureType = .type2DArray\n descriptor.arrayLength = TERRAIN_TEXTURES_COUNT\n descriptor.width = TERRAIN_TEXTURE_SIZE\n descriptor.height = TERRAIN_TEXTURE_SIZE\n descriptor.mipmapLevelCount = TERRAIN_TEXTURE_MIPMAP_LEVEL_COUNT\n\n return device.makeTexture(descriptor: descriptor)!\n}()\n</code></pre>\n<p>That achieves the same thing, avoiding a global descriptor, but is a little more readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-12T15:36:43.663",
"Id": "267927",
"ParentId": "263566",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>According to <a href=\"https://www.swift.org/documentation/api-design-guidelines/#naming\" rel=\"nofollow noreferrer\">the Swift API Design Guidelines</a>, it's recommended to:</p>\n<ul>\n<li>Use camel case and start with a lowercase letter for the names of variables.</li>\n<li>Avoid including the type of the variable in its name</li>\n</ul>\n</li>\n</ul>\n<blockquote>\n<p>name variables [...] according to their roles, rather than their type constraints.</p>\n</blockquote>\n<p>So use <code>terrain</code> instead of <code>TerrainTexture</code>, and <code>device</code> instead of <code>Device</code>.</p>\n<ul>\n<li>Avoid force unwrapping Optionals unless you are sure it's never going to fail or if you really want the app to crash without providing you with any debugging information. Optional binding gives you the opportunity to give an alternate route to your code other than crashing. In this case, we could just throw an error using <code>assert()</code>, <code>assertFailiure()</code>, <code>precondition()</code>, <code>preconditionFailiure</code>, or <code>fatalError</code>. Let's use the latter because it allows us to print a string in the console before the app terminates, and it works for all app optimization levels in all build configurations.:</li>\n</ul>\n<pre class=\"lang-swift prettyprint-override\"><code>guard let device = MTLCreateSystemDefaultDevice() else {\n fatalError("Couldn't get a reference to the preferred default Metal device object.")\n}\n</code></pre>\n<ul>\n<li>To avoid using closures, you could define <code>terrain</code> as <a href=\"https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID259\" rel=\"nofollow noreferrer\">a computed property</a>:</li>\n</ul>\n<pre class=\"lang-swift prettyprint-override\"><code>var terrain: MTLTexture {\n //Do all the necessay configuration\n}\n</code></pre>\n<p>Another way to conceal the intermediate variables needed to build objects in your code base, is <a href=\"https://swiftcodeshow.com/blog/factory-method-design-patterns-in-swift/\" rel=\"nofollow noreferrer\">the Factory pattern </a>.</p>\n<ul>\n<li>For objects that take an empty initializer, like a <code>MTLTextureDescriptor</code>, you could use the <a href=\"https://refactoring.guru/design-patterns/builder/swift/example\" rel=\"nofollow noreferrer\"><strong>Builder Pattern</strong></a>. It emphasizes the separation between the phase of building the object to your liking and the phase of actually using it. You could define a custom convenience initializer, but the Builder pattern gives you more freedom in the number of properties to initialize and the order of assigning values to the different properties of the object.</li>\n</ul>\n<p>We could use this pattern to build the <code>descriptor</code>:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>extension MTLTextureDescriptor: Buildable {}\n\nlet descriptor = MTLTextureDescriptor.builder()\n .textureType(.type2DArray)\n .arrayLength(TERRAIN_TEXTURES_COUNT)\n .width(TERRAIN_TEXTURE_SIZE)\n .height(TERRAIN_TEXTURE_SIZE)\n .mipmapLevelCount(TERRAIN_TEXTURE_MIPMAP_LEVEL_COUNT)\n .build()\n\n</code></pre>\n<p>This is possible via the power of Protocols, Dynamic member lookup and Keypaths:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>@dynamicMemberLookup\nclass Builder<T> {\n private var value: T\n \n init(_ value: T) { self.value = value }\n \n subscript<U>(dynamicMember keyPath: WritableKeyPath<T, U>) -> (U) -> Builder<T> {\n {\n self.value[keyPath: keyPath] = $0\n return self\n }\n }\n \n func build() -> T { self.value }\n}\n\nprotocol Buildable { init() }\n\nextension Buildable {\n static func builder() -> Builder<Self> {\n Builder(Self())\n }\n}\n</code></pre>\n<p><a href=\"https://www.youtube.com/watch?v=20k3000Pn4s\" rel=\"nofollow noreferrer\">This talk</a> and <a href=\"https://gramer.dev/blog/2020-02-23-using-dynamic-member-lookup-implement-builder-pattern/\" rel=\"nofollow noreferrer\">this article</a> will help you understand this pattern better.</p>\n<p>For a more comprehensive implementation of the Builder pattern, refer <a href=\"https://github.com/hainayanda/Builder\" rel=\"nofollow noreferrer\">to this GitHub repository</a>.</p>\n<h1>Kintsugi time</h1>\n<p>With the Builder pattern in a separate file, it's time to put together all the above remarks.</p>\n<p>Here is how your code looks now after some much-needed makeover:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>extension MTLTextureDescriptor: Buildable {}\n\nvar terrain: MTLTexture {\n guard let device = MTLCreateSystemDefaultDevice() else {\n fatalError("Couldn't get a reference to the preferred default Metal device object.")\n }\n \n let descriptor = MTLTextureDescriptor.builder()\n .textureType(.type2DArray)\n .arrayLength(TERRAIN_TEXTURES_COUNT)\n .width(TERRAIN_TEXTURE_SIZE)\n .height(TERRAIN_TEXTURE_SIZE)\n .mipmapLevelCount(TERRAIN_TEXTURE_MIPMAP_LEVEL_COUNT)\n .build()\n \n guard let texture = device.makeTexture(descriptor: descriptor) else {\n fatalError("Couldn't make a new texture object.")\n }\n \n return texture\n}\n</code></pre>\n<p>This way your code is safer, better readable, and has stronger separation of concerns.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-12T19:15:46.163",
"Id": "270025",
"ParentId": "263566",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T22:10:40.673",
"Id": "263566",
"Score": "1",
"Tags": [
"swift",
"classes"
],
"Title": "Initialize Swift class or struct values inline"
}
|
263566
|
<p>I'm currently trying to implement a c shim which sits between the open function from the c standard library and a program.</p>
<p>the shim should transparently write all file paths being opened to a log within a directory defined by the environment variable <code>IO_SHIM_PREFIX</code></p>
<p>I have this working relatively well, but in order to achieve it I had to fake the fcntl.h header guards, and I think that there must be a better way.</p>
<p>If I include fcntl.h directly I get the following error</p>
<pre><code>gcc -shared -fPIC -o shim.so src/shim.c -ldl
src/shim.c:47:5: error: conflicting types for ‘open’
47 | int open(const char *pathname, int flags){
| ^~~~
In file included from src/shim.c:16:
/usr/include/fcntl.h:168:12: note: previous declaration of ‘open’ was here
168 | extern int open (const char *__file, int __oflag, ...) __nonnull ((1));
| ^~~~
make: *** [Makefile:3: all] Error 1
</code></pre>
<p>I'm guessing it has something to do with the <code>__nonnull ((1))</code> part at the end but I'm not much of a c programmer and I dont understand it.</p>
<h2>Makefile</h2>
<pre><code>CC=gcc
all: src/shim.c
$(CC) -shared -fPIC -o shim.so src/shim.c -ldl
</code></pre>
<h2>src/shim.c</h2>
<pre class="lang-c prettyprint-override"><code>// required for RTLD_NEXT
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <unistd.h>
#include <math.h>
#include <string.h>
// this bypasses the header guard in bits/fcntl.h
// its a terrible idea, but I don't know the right way to do this.
#define _FCNTL_H
#include <bits/fcntl.h>
#undef _FCNTL_H
typedef int (*open_fn_ptr)(const char*, int);
void write_to_log(const char* prefix, const char* pathname, open_fn_ptr original_open){
pid_t pid = getpid();
pid_t tid = gettid();
char* pattern;
if (prefix[strlen(prefix) -1] == '/'){
pattern = "%s%d_%d.log";
}
else{
pattern = "%s/%d_%d.log";
}
int path_len = snprintf(NULL, 0, pattern, prefix, pid, tid);
char* log_filepath = (char*) malloc(sizeof(char) * path_len);
sprintf(log_filepath, pattern, prefix, pid, tid);
int fd = original_open(log_filepath, O_WRONLY | O_APPEND | O_CREAT);
write(fd, pathname, strlen(pathname));
write(fd, "\n", sizeof(char));
close(fd);
free(log_filepath);
}
int open(const char *pathname, int flags){
// acquire a pointer to the original implementation of open.
open_fn_ptr original_open = dlsym(RTLD_NEXT, "open");
const char* prefix = getenv("IO_SHIM_PREFIX");
if (prefix != NULL) {
write_to_log(prefix, pathname, original_open);
}
return original_open(pathname, flags);
}
</code></pre>
<h2>Usage example</h2>
<pre><code>IO_SHIM_PREFIX=`realpath .` LD_PRELOAD=./shim.so brave-browser
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T00:49:41.230",
"Id": "520350",
"Score": "4",
"body": "I think the error is saying that you should make your `open` also take a variable argument list. Theoretically, you could just ignore it any extra args, but actually you should check if `flags` contain `O_CREAT` or `O_TMPFILE` and if so, read a `mode` argument from va_args and pass it on too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T00:59:52.640",
"Id": "520352",
"Score": "0",
"body": "ah! I didn't know c had variadic functions. thank you so much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T03:55:24.977",
"Id": "520355",
"Score": "0",
"body": "Any C function declaration ends with `, ...);` takes a variable length argument list. This question probably should have been asked on stack overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T08:38:31.307",
"Id": "520368",
"Score": "0",
"body": "If you just want to log calls, then perhaps `strace --trace=open` serves your needs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T01:26:48.717",
"Id": "520532",
"Score": "0",
"body": "@TobySpeight Thanks for the suggestion, I'm aware of strace, I dismissed it in favor of a shim becuse of the performance impact it has on the watched process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T01:29:08.837",
"Id": "520533",
"Score": "0",
"body": "@pacmaninbw perhaps, but I wanted general code review on this as I'm not a experienced C programmer."
}
] |
[
{
"body": "<blockquote>\n<pre><code> char* log_filepath = (char*) malloc(sizeof(char) * path_len);\n</code></pre>\n</blockquote>\n<p><code>malloc()</code> returns a <code>void*</code>, which in C converts to any object-pointer type (unlike in C++, if you're used to that). So the cast is unnecessary (it's slightly harmful, in that it distracts attention from more dangerous casts). Also, because <code>char</code> is the unit of size, <code>sizeof (char)</code> can only be 1, so the multiplication is pointless. That line should be simply</p>\n<pre><code> char* log_filepath = malloc(path_len + 1);\n</code></pre>\n<p>Note the <code>+1</code> there - the code had a bug because we forgot to allocate space for the null character that ends the string.</p>\n<p>There are other uses of <code>sizeof (char)</code> where plain old <code>1</code> would be more appropriate and easier to read.</p>\n<hr />\n<p>Here, we assign a string literal to a <code>char*</code>:</p>\n<blockquote>\n<pre><code> pattern = "%s%d_%d.log";\n</code></pre>\n</blockquote>\n<p>That's poor practice, as writes to <code>*pattern</code> are undefined behaviour. The best fix is to declare <code>pattern</code> to point to <code>const char</code>:</p>\n<pre><code> const char *pattern;\n</code></pre>\n<p>I don't think it's necessary to choose between the two patterns - the filesystem interface will ignore consecutive directory separators, so it's safe to always use <code>"%s/%d_%d.log"</code>.</p>\n<hr />\n<blockquote>\n<pre><code>// this bypasses the header guard in bits/fcntl.h\n// its a terrible idea, but I don't know the right way to do this.\n#define _FCNTL_H\n#include <bits/fcntl.h>\n#undef _FCNTL_H\n</code></pre>\n</blockquote>\n<p>Your intuition here is correct; we are relying on the compiler/platform innards here rather than the public interface. You should define <code>open_fn_ptr</code> to have the same signature as the library does:</p>\n<pre><code>int open(const char *pathname, int flags, ...)\n{\n</code></pre>\n<p>Then we can simply include the documented, supported POSIX header:</p>\n<pre><code>#include <fcntl.h>\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> // acquire a pointer to the original implementation of open.\n open_fn_ptr original_open = dlsym(RTLD_NEXT, "open");\n</code></pre>\n</blockquote>\n<p>That assignment is an invalid conversion in C - although <code>void*</code> can be assigned to any <em>object</em> pointer, that's not true for <em>function</em> pointers. It might be worth drawing attention here using an explicit cast, though GCC will still emit a warning - see <a href=\"//stackoverflow.com/q/31526876/4850040\">Casting when using <code>dlsym()</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T10:14:55.757",
"Id": "520374",
"Score": "0",
"body": "that was incredibly helpful, thank you so much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T07:58:04.860",
"Id": "263575",
"ParentId": "263569",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263575",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T00:41:36.140",
"Id": "263569",
"Score": "0",
"Tags": [
"c",
"linux"
],
"Title": "shimming the c open function on linux and logging its usage"
}
|
263569
|
<p>It's taking 2.4 MB of memory and 20 ms.
It's my solution for Two Sum problem on LeetCode. How can I make it better using closures and other stuff? Kindly review the code.</p>
<pre class="lang-rust prettyprint-override"><code>use std::convert::TryInto;
impl Solution {
pub fn two_sum(nums: Vec<i32>, target: i32) ->Vec<i32> {
let mut status:bool = false;
let mut result:Vec<i32> = Vec::with_capacity(2);
let rang = nums.len()-1;
if (nums.len() < 2 || nums.len() > 10_0000) && (target < -1000000000 || target > 1000000000){
panic!("Too few or too much values");
}else{
'outer: for (i, val) in nums.iter().enumerate() {
if nums[i] < -1000000000 || nums[i] > 1000000000{
panic!("Too large or too small value in vec");
}
'inner: for j in i+1..nums.len() {
// println!("{}", nums[i]);
if nums[i] + nums[j] == target {
// println!("Hanji paaji mil gye ney..");
status = true;
// result[0] = x.try_into().unwrap();
// result[1] = (x+1).try_into().unwrap();
result.push(i.try_into().unwrap());
result.push((j).try_into().unwrap());
// result
break 'outer;
}else{
continue;
}
}
}
}
if status{
result
}else{
panic!("Not found");
}
// result
}
}
</code></pre>
|
[] |
[
{
"body": "<h3>Proper name and description</h3>\n<p>Rename the question and give it proper description and tags according to <a href=\"https://codereview.stackexchange.com/help/how-to-ask\">https://codereview.stackexchange.com/help/how-to-ask</a></p>\n<h3>Indent the code</h3>\n<p>Unindented code looks ugly. Moreover, it has bad readability. Compare this</p>\n<pre><code> if status {\n result\n } else {\n panic!("Not found");\n }\n</code></pre>\n<p>with your code. See the difference? (Returning) result and panicking happen on the same level. Else is the counterpart of if, not its internal structure. I don't need to look for curly brackets to say that - indentation does it. You'll save your own time indenting the code.</p>\n<h3>Cleanup</h3>\n<p>You've done some debugging output. It's ok (btw check out the <code>dbg!</code> macro). But once the code is tested you don't need it anymore. It's ok to have commented out lines while debugging, but when it's done - remove them. Clean code is much better to read.\nThe same goes for unused variables. Rust even gives you a warning for that - don't ignore the warnings!</p>\n<h3>Validation and algorithm separation</h3>\n<p>While not always possible, it is a hood habit to validate data before the algorithm begins. I don't think you need validation here (it is stated that input data will be ok), but if you still want to validate - do it on the beginning. To have the same loop for validation and for searching reduces the readability. Also recheck the validation conditions - it looks like something is wrong there.</p>\n<h3>Labels</h3>\n<p><a href=\"https://homepages.cwi.nl/%7Estorm/teaching/reader/Dijkstra68.pdf\" rel=\"nofollow noreferrer\">Go To statement considered harmful</a>. Yes, this is break statement, which is much better, but once again - could you do any better? Yes, of course - when the answer is found, you can simply <strong>return</strong> it! No need to have labels ('inner is not needed even now) and status variable! That's simple!\nAlso in this case you should not create a result variable - just construct it on return.</p>\n<h3>Else after return/panic</h3>\n<p>Sometimes it's good, especially if you want to show that something else could happen instead of returning (like logging the error). Sometimes not. Right here it's increasing nesting and can be omitted.</p>\n<h3>Continue at the end of the loop</h3>\n<p>Unnecessary, the loop will continue anyway.</p>\n<h3>Unnecessary complication and includes</h3>\n<p>Try_into? <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>. You've just validated the data, indexes can't be out of 0..100_000 (btw check out this constraint - it looks like something wrong with it), so simple <strong>as</strong> is enough:</p>\n<pre><code>result.push(i as i32)\n</code></pre>\n<p>So, the code now goes as</p>\n<pre><code>impl Solution {\n pub fn two_sum(nums: Vec<i32>, target: i32) ->Vec<i32> {\n if (nums.len() < 2 || nums.len() > 10_0000) || (target < -1000_000_000 || target > 1000_000_000){\n panic!("Wrong input data");\n }\n for &val in nums.iter() {\n if val < -100_0000_000 || val > 1000_000_000{\n panic!("Too large or too small value in vec");\n }\n }\n \n for (i, val_i) in nums.iter().enumerate() {\n for j in i+1..nums.len() {\n if val_i + nums[j] == target {\n return vec![i as i32, j as i32];\n }\n }\n } \n panic!("Not found");\n }\n}\n</code></pre>\n<h3>Choosing better algorithm</h3>\n<p>You have <span class=\"math-container\">\\$O(n^2)\\$</span> complexity: n for choosing an element to check and n for looking up for its counterpart. You can do something with ...Set or ...Map, but the most obvious way is to build a sorted Vec (<span class=\"math-container\">\\$O(n \\ln(n))\\$</span>), then move from the both sides (<code>i</code> increasing from <code>0</code> if <code>v[i] + v[j]</code> is lower than the target, <code>j</code> decreasing from <code>nums.len() - 1</code> if <code>v[i] + v[j]</code> is higher) until a sum is found, and then search for indexes in the nums (<span class=\"math-container\">\\$O(n)\\$</span>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T08:42:15.603",
"Id": "520369",
"Score": "2",
"body": "Re `i as i32`: the [Rust cheatsheet](https://cheats.rs/#number-conversions), together with many Rust programmers, recommends `.try_into()` over `as`, since the former makes the fallible nature of type conversion explicit, whereas the latter silently produces bogus results in case of error. I wouldn't blame OP for using `.try_into()`. Of course, LeetCode was the one who introduced this conversion by using the wrong type in the first place :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T09:26:54.053",
"Id": "520372",
"Score": "1",
"body": "That's right - but here we validate data (vec size) before converting, so `as` will do. Without validation, of course, `try_into()` is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T12:33:50.327",
"Id": "520379",
"Score": "0",
"body": "now reduced to 16ms and 2.1MB ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T13:22:08.893",
"Id": "520381",
"Score": "0",
"body": "Have you done the last paragraph?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T13:25:59.033",
"Id": "520383",
"Score": "0",
"body": "```\nuse std::collections::HashMap;\n\nimpl Solution {\n pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {\n let mut num_to_idx: HashMap<i32, i32> = HashMap::new();\n \n for (idx, num) in nums.iter().enumerate(){\n match num_to_idx.get(&(target - *num)){\n Some(&idx2) => return vec![idx as i32, idx2],\n None => num_to_idx.insert(*num, idx as i32),\n };\n }\n \n vec![]\n }\n}\n``` \nTop solution from leetcode(speed wise), where constraints are being checked here?\nlike value < 1000000000"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T13:31:21.307",
"Id": "520385",
"Score": "0",
"body": "[github](https://github.com/zowhair/leetcode) link for that solution is not readable above pasted code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T13:32:31.273",
"Id": "520386",
"Score": "0",
"body": "where this code is validating/looking for provided constraints like: \n2 <= nums.length <= 104\n-109 <= nums[i] <= 109\n-109 <= target <= 109\nOnly one valid answer exists."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T07:30:02.277",
"Id": "263574",
"ParentId": "263572",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263574",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T06:23:53.277",
"Id": "263572",
"Score": "2",
"Tags": [
"programming-challenge",
"rust",
"k-sum"
],
"Title": "Solution to LeetCode Two Sum problem in Rust"
}
|
263572
|
<p>Consider the infinite sequence <code>u</code>, where <code>u</code> is defined as follows:</p>
<ul>
<li>The number <code>u(0) = 1</code> is the first one in <code>u</code>.</li>
<li>For every <code>x</code> in <code>u</code>, then <code>y = 2 * x + 1</code> and <code>z = 3 * x + 1</code> are also in <code>u</code>.</li>
<li>There are no other numbers in <code>u</code>.</li>
<li><code>u</code> is sorted in increasing order, with no duplicates</li>
</ul>
<h4>The sequence:</h4>
<blockquote>
<pre><code>u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, …… ]
</code></pre>
</blockquote>
<p>1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on...</p>
<h4>Task:</h4>
<p>Given parameter <code>n</code>, the function <code>dbl_linear</code> (or <code>dblLinear</code>...) returns the element <code>u(n)</code> of the ordered sequence <code>u</code>.</p>
<h1>The code:</h1>
<pre><code>def dbl_linear(n):
u = [1]
if n > 0:
y, z = 2*1+1, 3*1+1
u.append(y), u.append(z)
for i in range(1,n):
y, z = u[i]*2+1, u[i]*3+1
u.append(y), u.append(z)
u = sorted(u)
u = sorted(list(set(u)))
return u[n]
</code></pre>
<p>The code passed the initial tests, but failed others due to execution timing out. Can I optimize the code (or algorithm) to increase speed?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T06:52:29.067",
"Id": "520360",
"Score": "5",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<h1>Profiling</h1>\n<p>The first thing you should do when trying to optimize your code is profile. Don't guess what the problem is, Python makes profiling easy and you should use that to your advantage.</p>\n<p><a href=\"https://stackoverflow.com/a/582337/11659881\">This answer</a> will help you get started with profiling, and in combination with the comments on it, you can run the following in your terminal:</p>\n<pre><code>python -m cProfile -s time path_to_script.py\n</code></pre>\n<p>This is just one way to profile, and I'm new to using the profiler myself but this one line tells you a lot of information. What I have done, is appended the following to your script</p>\n<pre><code>n = 10_000\nresult = dbl_linear(n)\n</code></pre>\n<p>Running the script with the <code>cProfile</code> command as I have listed above sorts all of the function calls by the amount of time they took to run, and right at the top is your calls to <code>sorted</code>, with a <code>tottime</code> about 5 times longer than the next slowest function, which is your function <code>dbl_linear</code>. This tells us that our main priority should be to try to "speed up" <code>sorted</code> (in fact, we will try to remove sorted where possible).</p>\n<p><a href=\"https://stackoverflow.com/a/40404052/11659881\">This answer</a> explains the difference between <code>tottime</code> vs <code>cumtime</code>: <code>cumtime</code> is the total amount of time spent in a function, and <code>tottime</code> is the amount of time spent in a function but <em>not</em> in another function. So, for <code>dbl_linear</code>, the <code>tottime</code> does not include the time spent in <code>sorted</code>, but the <code>cumtime</code> does include the time spent in <code>sorted</code>.</p>\n<h1>Sorted vs Sort</h1>\n<p>A quick fix that helps a little is to use inplace sorting by calling <code>u.sort()</code>, as the <a href=\"https://docs.python.org/3/howto/sorting.html\" rel=\"nofollow noreferrer\">python docs</a> point out that it is slightly more efficient that <code>sorted</code>. However, this isn't going to be sufficient, it's just something to note.</p>\n<h1>Bisect</h1>\n<p>A better solution is to use the fact that you already have a sorted list and use the built-in <a href=\"https://docs.python.org/3/library/bisect.html\" rel=\"nofollow noreferrer\"><code>bisect</code></a> module. Then, you can replace <code>dbl_linear</code> with</p>\n<pre><code>def dbl_linear(n):\n u = [1]\n if n > 0:\n y, z = 2*1+1, 3*1+1\n bisect.insort_left(u, y)\n bisect.insort_left(u, z)\n for i in range(1, n):\n y, z = u[i]*2+1, u[i]*3+1\n bisect.insort_left(u, y)\n bisect.insort_left(u, z)\n u = sorted(list(set(u)))\n return u[n]\n</code></pre>\n<p><code>bisect.insort_left(a, x)</code> means insert <code>x</code> into <code>a</code> in sorted order. This cuts down on the execution time by a <em>lot</em> because now, instead of sorting each time, you are simply inserting an element in sorted order. The lengthy part of this process is just moving the elements back to create a space for your insertion.</p>\n<h1>Further improvements</h1>\n<p>If you remove this line</p>\n<pre><code>u = sorted(list(set(u)))\n</code></pre>\n<p>by checking for duplicates before inserting an element in sorted order, you don't have to insert it at all and you can avoid this duplicate elimination line. Then, you can make the adjustment:</p>\n<pre><code>for i in range(1, n):\n y, z = u[i]*2+1, u[i]*3+1\n if len(u) > n and u[n] < y:\n break\n insert_no_dups(u, y)\n insert_no_dups(u, z)\n</code></pre>\n<p>Because <code>y</code> is the largest number that can be inserted if <code>u</code> is always sorted. This allows you to avoid computing more values in <code>u</code> than necessary. As it is currently written, your code always computes more elements than necessary.</p>\n<p>Incorporating all of these adjustments, here is what I have created for final code:</p>\n<pre><code>import bisect\n\ndef insert_no_dups(a, x):\n """Insert x into a in sorted order if x isn't in a"""\n position = bisect.bisect_left(a, x)\n if position == len(a):\n a.append(x)\n elif a[position] == x:\n pass\n else:\n a.insert(position, x)\n\ndef dbl_linear(n):\n u = [1]\n if n > 0:\n y, z = 2*1+1, 3*1+1\n insert_no_dups(u, y)\n insert_no_dups(u, z)\n for i in range(1, n):\n y, z = u[i]*2+1, u[i]*3+1\n if len(u) > n and u[n] < y:\n break\n insert_no_dups(u, y)\n insert_no_dups(u, z)\n return u[n]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T13:33:15.827",
"Id": "263585",
"ParentId": "263573",
"Score": "3"
}
},
{
"body": "<h1>Algorithm</h1>\n<p>Because we keep all the duplicates until we've finished generating the list, we're doing much more work than we need to. For each number we reach, we generate two more, and since we're not merging duplicates at that time, that means our work scales as O(2ⁿ). Merging as we go (as <a href=\"/a/263585/75307\">recommended by Kraigolas</a>) reduces that, and reduces the storage required to O(n).</p>\n<h1>Implementation</h1>\n<p>Since there's only one sequence, but we may want to access it several times during the program, it's worth memoizing the work done so far, to avoid repeating the calculations. We just need to keep the sorted set of results, and the position up to which we have computed additional elements for.</p>\n<h1>Alternative algorithm</h1>\n<p>It might be worth considering working from the result set: consider every number in turn and decide whether it's a member of the sequence (<code>x</code> is a member only if either of <code>(x-1)/2</code> and <code>(x-1)/3</code> is a member). This requires only the members of the sequence up to <code>x</code> to be stored.</p>\n<p>That approach would look something like this:</p>\n<pre><code>import bisect\nimport itertools\n\nu = [1] # The sequence\n\ndef contains(a, x):\n """\n True if sorted list a contains element x\n >>> contains([1, 2, 3, 4], 2)\n True\n >>> contains([1, 2, 3, 4], 5)\n False\n """\n i = bisect.bisect_left(a, x)\n return i != len(a) and a[i] == x\n\ndef dbl_linear(n):\n """\n Finds the nth element from the list beginning with 1,\n where 2n+1 and 3n+1 are members for each n that's a member\n\n >>> dbl_linear(0)\n 1\n >>> dbl_linear(1)\n 3\n >>> dbl_linear(2)\n 4\n >>> dbl_linear(10)\n 22\n """\n global u\n if n < len(u):\n return u[n]\n for x in itertools.count(u[-1]+1):\n if contains(u, (x-1)/2) or contains(u, (x-1)/3):\n u += [x]\n if n < len(u):\n return u[n]\n\n\n\nif __name__ == "__main__":\n import doctest\n doctest.testmod()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T07:01:07.990",
"Id": "263613",
"ParentId": "263573",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T06:41:34.227",
"Id": "263573",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded"
],
"Title": "Compute members of the infinite series generated by 2n+1 and 3n+1"
}
|
263573
|
<h2>Code</h2>
<pre class="lang-cs prettyprint-override"><code>List<Element> elements = GetElementsList();
ISet<string> usedInnerElements = new HashSet<string>();
foreach (Element element in elements)
{
foreach (InnerElement innerElement in element.InnerCollection.InnerElements)
{
usedInnerElements.Add(innerElement.SomeValue);
}
}
class Element
{
public InnerCollection InnerCollection { get; set; }
}
class InnerCollection
{
public List<InnerElement> InnerElements { get; set; }
}
class InnerElement
{
public string SomeValue { get; set; }
}
</code></pre>
<p>This code scan inner collections of some other collection and save only unique values.</p>
<h2>Question</h2>
<p>Is there any way to present it in more fluent way using LINQ method syntax?</p>
|
[] |
[
{
"body": "<p>If we can assume that none of the values can be <code>null</code> then the simplest solution I can think of:</p>\n<pre><code>ISet<string> usedInnerElements = elements\n .SelectMany(coll => coll.InnerCollection.InnerElements\n .Select(elem => elem.SomeValue))\n .Distinct()\n .ToHashSet();\n</code></pre>\n<ol>\n<li>With <code>SelectMany</code> we are reducing the dimensions (flattening) from <code>IEnumerable<IEnumerable<string>></code> to <code>IEnumerable<string></code></li>\n<li>With <code>Select</code> we retrieve the <code>string</code> value from its wrapper class</li>\n<li>With <code>Distinct</code> we are making sure that we are getting rid of from all duplicates</li>\n<li>With <code>ToHashSet</code> we simply convert the <code>IEnumerable<string></code> to <code>ISet<string></code></li>\n</ol>\n<p>Test Input:</p>\n<pre><code>var elements = new List<Element>\n{\n new Element\n {\n InnerCollection = new InnerCollection\n {\n InnerElements = new List<InnerElement>\n {\n new InnerElement { SomeValue = "A" },\n new InnerElement { SomeValue = "C" },\n new InnerElement { SomeValue = "E" },\n }\n }\n },\n new Element\n {\n InnerCollection = new InnerCollection\n {\n InnerElements = new List<InnerElement>\n {\n new InnerElement { SomeValue = "E" },\n new InnerElement { SomeValue = "A" },\n new InnerElement { SomeValue = "B" },\n }\n }\n }\n};\n...\nConsole.WriteLine(string.Join(",", usedInnerElements));\n</code></pre>\n<p>Test output:</p>\n<pre><code>A,C,E,B\n</code></pre>\n<hr />\n<p>If you have to deal with null values then the query might look like this:</p>\n<pre><code>ISet<string> usedInnerElements = elements\n .Where(coll => coll != null\n && coll.InnerCollection != null\n && coll.InnerCollection.InnerElements != null)\n .SelectMany(coll => coll.InnerCollection.InnerElements\n .Where(elem => elem != null)\n .Select(elem => elem.SomeValue))\n .Distinct()\n .ToHashSet();\n</code></pre>\n<p>Test input</p>\n<pre><code>var elements = new List<Element>\n{\n null,\n new Element\n {\n InnerCollection = null\n },\n new Element\n {\n InnerCollection = new InnerCollection\n {\n InnerElements = null\n }\n },\n new Element\n {\n InnerCollection = new InnerCollection\n {\n InnerElements = new List<InnerElement>\n {\n new InnerElement { SomeValue = "E" },\n new InnerElement(),\n null\n }\n }\n }\n};\n</code></pre>\n<p>Test output</p>\n<pre><code>E,\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T10:31:05.603",
"Id": "263580",
"ParentId": "263579",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T10:16:07.260",
"Id": "263579",
"Score": "1",
"Tags": [
"c#",
"linq"
],
"Title": "Is there a nice way to add unique items from inner collections using LINQ method syntax"
}
|
263579
|
<p>I'm trying to write a <code>JSON.stringify</code> wrapper that never throws exceptions, and also <a href="https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify">includes properties like those on Error</a>.</p>
<p>I think this means it has to:</p>
<ul>
<li>handle cycles</li>
<li>handle <code>BigInt</code>s</li>
<li>catch exceptions thrown by a getter</li>
<li>use <code>Object.getOwnPropertyNames</code> to find all properties, not just enumerable properties</li>
</ul>
<p>I've had a go. I know <code>seen</code> is overkill and will remove duplicate objects, not just cyclical, but that's okay for my use case. The array detection will fire even if other properties have been set, causing them to be missed, which is undesirable. Wondering if there are any other issues I've overlooked?</p>
<pre class="lang-javascript prettyprint-override"><code>function stringifyResilient(value, space) {
const seen = [];
function replacer(_key, value) {
if (typeof value === "object" && value !== null) {
if ("toJSON" in value) {
try {
value = value.toJSON();
} catch {
value = null;
}
}
if (seen.includes(value)) {
return null;
}
seen.push(value);
const len = value.length;
if (typeof len === "number" && len >= 0 && Math.floor(len) === len && [...Array(len).keys()].every(i => i in value)) {
const ret = [];
for (let i = 0; i < len; i++) {
let propValue = null;
try {
propValue = value[i];
} catch {}
ret.push(propValue);
}
value = ret;
} else {
const ret = {};
Object.getOwnPropertyNames(value).forEach(propName => {
let propValue = null;
try {
propValue = value[propName];
} catch {}
ret[propName] = propValue;
});
value = ret;
}
} else if (typeof value === "bigint") {
value = value.toString();
}
return value;
}
return JSON.stringify(value, replacer, space);
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T11:49:53.607",
"Id": "263581",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Resilient JSON.stringify that never throws"
}
|
263581
|
<p>This code solves <a href="https://projecteuler.net/problem=35" rel="nofollow noreferrer">Project Euler problem 35</a>:</p>
<blockquote>
<p>The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million?</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>from collections import deque
def sieve(limit):
nums = [True] * (limit+1)
nums[0] = nums[1] = False
for i, is_prime in enumerate(nums):
if is_prime:
yield i
for n in range(i*i, limit+1, i):
nums[n] = False
def rotations(n):
l = deque(list(str(n)))
r = []
for _ in range(len(l)):
r.append(int("".join(list(l))))
l.rotate()
return r
def circular_prime(n):
cp = []
s = list(sieve(n))
for i in s:
r = rotations(i)
flags = [False] * len(r)
for k, j in enumerate(r):
if j in s:
flags[k] = True
if all(flags):
print(i)
cp.append(i)
return len(cp)
print(circular_prime(1000000))
</code></pre>
<p>How can I speed it up? It takes too long if I run it with standard Python interpreter. However, I am able to reduce execution time to 13 seconds by running in "pypy" interpreter.</p>
|
[] |
[
{
"body": "<h3>Don't check if there are even digits</h3>\n<p>Add</p>\n<pre><code>if n<10:\n return [n]\nif any(even in str(n) for even in "02468"):\n return []\n</code></pre>\n<p>into <code>rotations</code>, because every number (except for 2) with the last even digit will not be prime, there's no sense in generating rotations for those.</p>\n<h3>Avoid excessive conversions</h3>\n<p><code>l = deque(str(n))</code> - no <code>list</code> conversion needed\nAlso check string slices - you can do rotations just with them, not the deque.</p>\n<h3>Avoid changing the collection while you're iterating over it</h3>\n<pre><code>for i, is_prime in enumerate(nums):\n ...\n nums[n] = False\n</code></pre>\n<p>is bad. Refactor it - maybe into while loop.</p>\n<h3>Use list comprehensions</h3>\n<p><code>flags</code> variable is clearly a mess. Let's see...</p>\n<pre><code> flags = [False] * len(r)\n for k, j in enumerate(r):\n flags[k] = j in s #True for True, False for False\n if all(flags):\n</code></pre>\n<p>Ok, now move it into the initialization of flags.</p>\n<pre><code> flags = [j in s for k,j in enumerate(r)]\n if all(flags):\n</code></pre>\n<p>k is not needed. And flags too:</p>\n<pre><code> if all(j in s for j in r):\n</code></pre>\n<p>This looks better and works faster - because it stops after the first False. But now we don't need r:</p>\n<pre><code> if all(j in s for j in rotations(i)):\n</code></pre>\n<p>And now you can rewrite <code>rotations</code> to use <code>yield</code> instead of creating the list. This will be much faster.</p>\n<h3>Don't transform the sieve into the list</h3>\n<p>You spend time and memory for nothing. Work with the sieve, not with the list. Searching in the sieve will be <span class=\"math-container\">\\$O(1)\\$</span>, not <span class=\"math-container\">\\$O(n)\\$</span> (<code>if s[j]</code> instead of <code>if j in s</code>). The <code>for i</code> loop now will be over the whole range (2..n), skipping if not s[i].</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T14:03:54.000",
"Id": "520391",
"Score": "0",
"body": "Really appreciate the detailed review. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T04:16:59.823",
"Id": "520451",
"Score": "3",
"body": "Not only if there are even digits! A 5 is bad in any multi-digit, since rotations will eventually move the 5 to the end, and form a multiple of 5. The only viable digits are 1, 3, 7, and 9. Ie, `n < 10 or set(str(n)) <= {'1', '3', '7', '9'}`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T13:16:58.550",
"Id": "263584",
"ParentId": "263583",
"Score": "5"
}
},
{
"body": "<p>Consider the circular primes 197, 719, 971 given as an example. When 197 is reached, the current code checks the two rotations 719 and 971 to see if they are prime. Then when 719 is reached, 971 and 197 are tested. But we already know that the three numbers are circular primes from the first time they were tested. So the code is doing 6 rotations and checks when only the first two are needed. For a 6-digit circular prime that would be 30 rotations instead of only 5.</p>\n<p>Here's some code (untested) to show the idea.</p>\n<pre><code>def count_circular_primes(n):\n count = 0\n primes = list(sieve(n))\n\n for prime in primes:\n r = rotations(prime)\n\n # if they are circular primes, count them\n if all(primes[i] for i in r):\n count += len(r)\n\n # mark all the rotations as done\n for i in r:\n primes[i] = False\n\n return count\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T06:36:44.573",
"Id": "263612",
"ParentId": "263583",
"Score": "1"
}
},
{
"body": "<p><em>Disclaimer: This review will mention improvements to your code that have probably been provided by other answers. At the end, I will suggest a completely different algorithm to solve this problem.</em></p>\n<h2>Better usage of the sieve</h2>\n<p>Using a sieve is a good idea especially because we have a known upper-bound for the values we are interested in. However, the conversion from the sieve into a list makes it slower to use: it makes all other prime checks expensive as one need to perform a linear search in the list. A much faster alternative is to use it as is: an array mapping number to their primality.</p>\n<p>In practice, you just need to <code>return nums</code> from the sieve function and then:</p>\n<pre><code>def circular_prime(n):\n cp = []\n s = sieve(n)\n for i, is_prime in enumerate(s):\n if is_prime:\n r = rotations(i)\n flags = [False] * len(r)\n for k, j in enumerate(r):\n if s[j]:\n flags[k] = True\n if all(flags):\n print(i)\n cp.append(i)\n return len(cp)\n</code></pre>\n<p>This simple change leads to a huge performance improvement.</p>\n<h2>Flags</h2>\n<p>The logic involving flags can be simplified a lot and be: <code> if all(s[j] for j in rotations(i)):</code>.</p>\n<h2>Perform a smaller number of prime test</h2>\n<p>For every circular number found, we check all its rotations. Eventually, all numbers have been checked many times. A different strategy could be to check whether the number we are considering is the smallest among its rotations. If it is and if it is indeed a circular primes, all its rotations can be added to the result at once.</p>\n<pre><code> r = set(rotations(i))\n if i == min(r) and all(s[j] for j in r):\n print(r)\n cp.extend(r)\n</code></pre>\n<h2>A different algorithm</h2>\n<p>A few mathematical observations can be performed for the number (bigger than 9) we are looking for:</p>\n<ul>\n<li><p>primes numbers (bigger than 9) will not end in 0, 2, 4, 6, 8 or 5. This leads to a last digit being 1, 3, 7, 9.</p>\n</li>\n<li><p>thus, circular primes will not contain any of these numbers because they would correspond to the last digit of a rotation. Circular primes are only permutations of 1, 3, 7 and 9.</p>\n</li>\n</ul>\n<p>We can limit the search space by looking for these permutations: when considering numbers with n digits, you'll only consider 4ⁿ numbers instead of 10ⁿ (when n = 6 for instance, it makes the difference between 4096 and 100000).</p>\n<p>We get something like:</p>\n<pre><code>def circular_prime(nb_dig_max):\n cp = [2, 3, 5, 7]\n final_numbers = {'1', '3', '7', '9'}\n s = sieve(10 ** nb_dig_max)\n for l in range(2, nb_dig_max + 1):\n for p in itertools.product(final_numbers, repeat=l):\n p_int = int(''.join(p))\n perm = set(rotations(p_int))\n if p_int == min(perm) and all(s[n] for n in perm):\n cp.extend(perm)\n return len(cp)\n</code></pre>\n<p>At this stage, we've limited the number of prime checks to such a small number that using a sieve leads to performance no better than a simple prime check function:</p>\n<pre><code>def is_prime(n):\n """Checks if a number is prime."""\n if n < 2:\n return False\n return all(n % i for i in range(2, int(math.sqrt(n)) + 1))\n\n\ndef circular_prime(nb_dig_max):\n cp = [2, 3, 5, 7]\n final_numbers = {'1', '3', '7', '9'}\n for l in range(2, nb_dig_max + 1):\n for p in itertools.product(final_numbers, repeat=l):\n p_int = int(''.join(p))\n perm = set(rotations(p_int))\n if p_int == min(perm) and all(is_prime(n) for n in perm):\n cp.extend(perm)\n return len(cp)\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T07:28:13.937",
"Id": "263615",
"ParentId": "263583",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263584",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T12:21:38.283",
"Id": "263583",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"primes"
],
"Title": "Count prime numbers whose rotations are all prime"
}
|
263583
|
<p>I have written an application for lawyers' offices. There is an API to fetch info about court cases. I have implemented API calls for front end when user enters particular case; one tab is filled with info from this API about this case's state in court.</p>
<p>This code is run from a daily cron job; for all the cases in my application, it checks the <code>last updated filed</code> and matches it with last saved <code>last updated filed</code> in my DB. If they don't match, then the notification system in my app informs assigned people of the changes on that case.</p>
<p>So in short: automatic notification system about changes on all court cases in my app and email.</p>
<p>I'm a bit new to curl and PHP API calls, usually using JS, so bear with me.</p>
<p>I have some performance issues with this script. The DB call and loop is only around 70 times. And it's a bit slow. I'm afraid whether it will even work at all with bigger numbers.</p>
<p>Side note: API does not have option to fetch all data at once. I have to loop it so:</p>
<ol>
<li>First API call is made in <code>function eSudovi()</code> and data is saved <code>$eSudovi</code>.</li>
<li>There is a function <code>function findSudCode($val, $eSudovi)</code> to filter that data and get some info from it in loops.</li>
<li>DB get data is made and for each row one new API Call is made <code>with function ePredmeti($sud, $pred)</code> with <code>$epredmet = ePredmeti($sudCode, $sudBroj);</code> inside loop.</li>
<li>I stopped here because it is pretty slow. And I will need additional logic inside loop.</li>
</ol>
<p>As I'm new to curl in PHP I am looking for suggestions on improving this. I have been told something can be maybe done with opening and closing connections every time?</p>
<p>I have implemented checking of times, as recommended in <a href="https://stackoverflow.com/a/68181117/4850040">Trying to access array offset on value of type null & isset problem in API call loop</a>. It looks like the times are all over the place, not connected to type of response.</p>
<p>I'm using PHP version 7.4.</p>
<pre><code>// ONE API CURL CALL AT START
function eSudovi()
{
$endpoint = "xxx";
$qry = '{"query":"query{sudovi {id, sudNaziv}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// SAVE DATA FOR LATER USE
$eSudovi = eSudovi()["data"]["sudovi"];
//FILTER THAT DATA FROM LATER LOOP
function findSudCode($val, $eSudovi)
{
foreach ($eSudovi as $key => $value) {
if ($value["sudNaziv"] == $val) {
return $value["id"];
}
}
}
// 2nd API CURL CALL THAT IS USED IN LATER LOOP
function ePredmeti($sud, $pred)
{
$endpoint = "xxx";
$qry = '{"query":"query{ prvi:predmet(sud: ' . $sud . ', oznakaBroj: \"' . $pred . '\") {lastUpdateTime}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// DB GET DATA
$results = mysqli_query($con, "
SELECT DISTINCT predf_nas_br, predf_odv, predf_SUD, predf_SUDBROJ
FROM PREDMETIFView
WHERE predf_SUD <> '' AND predf_SUDBROJ <> '' AND predf_SUDBROJ NOT LIKE '% %'
UNION ALL
SELECT DISTINCT predp_nas_br, predp_odv, predp_SUD, predp_SUDBROJ
FROM PREDMETIPView
WHERE predp_SUD <> '' AND predp_SUDBROJ <> '' AND predp_SUDBROJ NOT LIKE '% %'
;");
while ($row = $results->fetch_assoc()) {
// LOOP THAT BD DATA
foreach ($row as $key => $value) {
if ($key == "predf_nas_br") {
$nas = $value;
}
if ($key == "predf_SUD") {
$sud = trim($value);
if (!empty($sud) && isset($sud)) {
$sudCode = findSudCode($sud, $eSudovi);
}
};
if ($key == "predf_SUDBROJ") {
$sudBroj = trim($value);
};
if (!empty($sudCode) && !empty($sudBroj) && isset($sudCode) && isset($sudBroj)) {
// echo $sudCode . "<br>";
// echo $sudBroj . "<br>";
$epredmet = ePredmeti($sudCode, $sudBroj);
print_r($epredmet);
echo "<br>";
if (isset($epredmet["data"]["prvi"]["lastUpdateTime"])) {
$lastUpdateTime = $epredmet["data"]["prvi"]["lastUpdateTime"];
$dateTime = str_replace("T", " ", $lastUpdateTime);
echo $nas . " - " . $dateTime . "<br>";
}
}
}
};
</code></pre>
<p><strong>EDIT:</strong></p>
<p>To address anwser ive got:</p>
<p>Mysql Query took 0.0002 seconds for 52 results, and I don't see how would that be problem, it is done once and I said there is only around 70 results per testing DB. Anyway everything is properly indexed etc...</p>
<p>I have added user agent to curl and have implemented <a href="https://stackoverflow.com/questions/68178645/trying-to-access-array-offset-on-value-of-type-null-isset-problem-in-api-call/68181117#68181117">stackoverflow</a> solution with class that should address reusing of curl connection.</p>
<p>I have also created code so you can all test it out with sample data and endpoints:</p>
<pre><code>$arr = [
["Županijski sud u Zagrebu", "13-Kir-t-us-330/20"],
["Općinski građanski sud u Zagrebu", "P-2315/96"],
["Upravni sud u Splitu", "Uslgr-66/2020"],
["Općinski građanski sud u Zagrebu", "P-2282/2018"],
["Općinski građanski sud u Zagrebu", "P-785/2020"],
["Općinski kazneni sud u Zagrebu", "K-1899/2019"],
["Općinski građanski sud u Zagrebu", "P-12107/2019"],
["Županijski sud u Osijeku", "K-Us-9/2019"],
["Županijski sud u Zagrebu", "K-Us-11/2018"],
["Općinski sud u Splitu", "Z-27820/20"],
["Općinski prekršajni sud u Zagrebu", "Pp-226/2020"],
["Općinski prekršajni sud u Zagrebu", "Pp-5211/2021"],
["Općinski prekršajni sud u Zagrebu", "Pp-5142/2021"],
["Upravni sud u Zagrebu", "Usl-348/20"],
["Općinski građanski sud u Zagrebu", "P-2931/2021"],
["Općinski građanski sud u Zagrebu", "Z-36742/2010"],
["Općinski građanski sud u Zagrebu", "Z-20259/2020"],
["Općinski građanski sud u Zagrebu, ZK odjel", "Z-29964/2020"],
["Općinski građanski sud u Zagrebu", "Pn-3651/2017"],
["Općinski radni sud u Zagrebu", "Pr-1676/2015"],
["Općinski građanski sud u Zagrebu", "P-1037/2008"],
["Općinski sud u Kutini", "Pn-160/2019"],
["Trgovački sud u Zagrebu", "Povrv-912/2018"],
["Trgovački sud u Zagrebu", "P-1637/2019"],
["Trgovački sud u Zagrebu", "P-1560/19"],
["Trgovački sud u Zagrebu", "P-1318/2018"],
["Trgovački sud u Zagrebu", "P-1477/2018"],
["Općinski građanski sud u Zagrebu, ZK odjel", "Z-58743/19"],
["Općinski građanski sud u Zagrebu, ZK odjel", "Z-49863/2019"],
["Općinski sud u Sesvetama, ZK odjel", "Z-440/2014"],
["Općinski građanski sud u Zagrebu", "Pn-2545/2018"],
["Općinski sud u Splitu, ZK odjel Supetar", "Z-20786/2019"],
["Općinski građanski sud u Zagrebu, ZK odjel", "Z-34316/2020"],
["Općinski građanski sud u Zagrebu, ZK odjel", "Z-34825/12"],
["Općinski građanski sud u Zagrebu, ZK odjel", "Z-55780/2013"],
["Općinski građanski sud u Zagrebu, ZK odjel", "Z-36302/2016"],
["Općinski građanski sud u Zagrebu", "Ovr-1465/2019"],
["Općinski građanski sud u Zagrebu", "P-766/2019"],
["Općinski građanski sud u Zagrebu", "Ovr-375/2020"],
["Općinski građanski sud u Zagrebu", "R1-555/2020"],
["Trgovački sud u Zagrebu", "R1-4/2021"],
["Općinski sud u Splitu", "P-4300/2020"],
["Općinski građanski sud u Zagrebu", "Z-52429/2019"],
["Općinski sud u Novom Zagrebu", "Z-22493/2019"],
["Općinski sud u Sesvetama", "Z-10836/2019"],
["Općinski sud u Sesvetama", "Z-10833/2019"],
["Općinski radni sud u Zagrebu", "Pr-3823/2021"],
["Općinski radni sud u Zagrebu", "Pr-3326/2021"],
["Općinski građanski sud u Zagrebu", "Z-5768/21"],
["Općinski radni sud u Zagrebu", "Pr-13210/2020"],
["Općinski radni sud u Zagrebu", "Pr-3936/2021-2"],
["Upravni sud u Zagrebu", "Usl-49/18"]
];
function eSudovi()
{
$endpoint = "https://e-predmet.pravosudje.hr/api/";
$qry = '{"query":"query{sudovi {id, sudNaziv}}"}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$ch = curl_init();
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)';
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$eSudovi = eSudovi()["data"]["sudovi"];
function findSudCode($val, $eSudovi)
{
foreach ($eSudovi as $key => $value) {
if ($value["sudNaziv"] == $val) {
return $value["id"];
}
}
}
class ePredmeti
{
public $epredmet;
private $curl, $ini_opt;
function __construct()
{
$endpoint = 'https://e-predmet.pravosudje.hr/api/';
$headers = ['Content-Type: application/json'];
$timeout = 30;
$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)';
$this->curl = curl_init();
$this->ini_opt = [
CURLOPT_USERAGENT => $agent,
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_TIMEOUT => $timeout
];
}
public function _exec($sud, $pred)
{
$start = microtime(true);
$query_opt = [
CURLOPT_POSTFIELDS =>
'{"query":"query{ prvi:predmet(sud: ' . $sud . ', oznakaBroj: \"' . $pred . '\") {lastUpdateTime}}"}'
];
curl_reset($this->curl);
curl_setopt_array($this->curl, $this->ini_opt);
curl_setopt_array($this->curl, $query_opt);
$ret = curl_exec($this->curl);
if (!curl_errno($this->curl)) {
if (curl_getinfo($this->curl, CURLINFO_HTTP_CODE) !== 200) {
echo 'HTTP error: ' . $http_code . '<br>';
$this->epredmet = null;
} else {
$this->epredmet = json_decode($ret, true);
}
} else {
echo curl_error($this->curl) . '<br>';
$this->epredmet = null;
}
echo 'Took: ' . (microtime(true) - $start) . '<br>';
}
}
$mycurl = new ePredmeti();
foreach ($arr as $value) {
$sudCode = findSudCode(trim($value[0]), $eSudovi);
$sudBroj = trim($value[1]);
if (!empty($sudCode) && !empty($sudBroj) && isset($sudCode) && isset($sudBroj)) {
// echo $sudCode . "<br>";
// echo $sudBroj . "<br>";
$mycurl->_exec($sudCode, $sudBroj);
// var_dump($mycurl->epredmet);
// echo "<br>";
if (isset($mycurl->epredmet["data"]["prvi"]) && !empty($mycurl->epredmet["data"]["prvi"])) {
if (isset($mycurl->epredmet["data"]["prvi"]["lastUpdateTime"]) && !empty($mycurl->epredmet["data"]["prvi"]["lastUpdateTime"])) {
$lastUpdateTime = $mycurl->epredmet["data"]["prvi"]["lastUpdateTime"];
$dateTime = str_replace("T", " ", $lastUpdateTime);
echo $dateTime . "<br>";
}
}
}
}
</code></pre>
<p>This testing script is a bit faster for some reason but still times varies from 0.01 to 5, 6 sometimes 7 sec. And in production I still get 504 Gateway Time-out on one DB.</p>
<p>Im afraid to do this on large number of records...</p>
<p>Any other suggestions welcomed.</p>
<p><strong>EDIT:</strong></p>
<p>It just got to my attention that this GraphQL APi does support multiple cases in one request, it just needs alias in front. So my problems are solved...</p>
|
[] |
[
{
"body": "<p>Tip: reusing the curl handle keeps the connection to the server open. Since you are marking repeated request against the same host, this should speed up things. Use <code>$ch = curl_init();</code> at the start of your code, out of the <code>ePredmeti</code> function in order to reuse your curl instance.</p>\n<p>But you are not saying what part of the code is slow. We cannot test it, or you should provide a public URL. I suggest that you add a few prints in your code and inside the functions, to spit out a timestamp and you will see where the bottlenecks are.</p>\n<p>Could be as simple as:</p>\n<pre><code>echo(date('d/m/Y H:i:s', time()));\n</code></pre>\n<p>Then you can figure out which part needs optimizations.</p>\n<p>The database query itself also could be taking a long time, because it is not optimized, and very likely does not take advantage of table <strong>indexes</strong> (if they even exist). You should measure the average time of that query separately, and use the query plan (use the <code>explain</code> command in Mysql) to try to make this query perform better, if you find that is indeed taking a long time to run. It mainly depends if you have lots of records in your table or a moderate number.</p>\n<p>It is also possible that the website applies some form of rate limiting and slowing you down. You should spoof the <strong>user agent</strong> to a mainstream browser (use <code>CURLOPT_USERAGENT</code>), because it is obvious to the website that your script is a bot. They can decide to penalize you and throttle traffic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T23:34:56.153",
"Id": "520442",
"Score": "1",
"body": "Please include that `!empty() && isset()` is an antipattern that shouldn't exist in anyone's application for any reason. https://stackoverflow.com/a/4559976/2943403"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T23:47:21.673",
"Id": "520444",
"Score": "0",
"body": "I have edited my question with test code and did address some points come up in this post. Thanks for answering."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T09:59:26.903",
"Id": "520466",
"Score": "0",
"body": "It just got to my attention that this GraphQL APi does support multiple cases in one request, it just needs alias in front. So my problems are solved..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T19:18:12.233",
"Id": "263597",
"ParentId": "263586",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T14:10:13.587",
"Id": "263586",
"Score": "1",
"Tags": [
"performance",
"php",
"api",
"curl"
],
"Title": "Automatic notification system about changes to court cases"
}
|
263586
|
<p>Hello I have this function that takes array of objects and takes a specific value from the object and creates array of strings that can make mapped to dropdown selector.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const value = {
Value: [{
"Activity Id": "04912309-35",
"Activity Name": "SCAFFOLD SUPPORT TEAM - CARPENTERS & LABORERS",
"Start Date ": "2021-06-29 08:45:21",
"End Date": "2021-06-30 08:45:21",
"Work Group Name": "PSCF",
"Unit ": "01",
Status: "READY",
crew: "FIN",
"Work Pln Factor": "F2 EN RS NR",
},
{
"Activity Id": "RHR*SWPUMPDSCHSTOP*Z",
"Activity Name": "MM 1E12-F332D CLEAN UP AFTER DISASSEMBLE/INSPECT/REPAIR VALVE",
"Start Date ": "2021-06-29 08:45:21",
"End Date": "2021-07-09 08:45:21",
"Work Group Name": "PME1",
"Unit ": "02",
Status: "WORKING",
crew: "FIN",
"Work Pln Factor": "F1 RM L2 NR",
},
{
"Activity Id": "01322927-01B",
"Activity Name": "2DG024 WALK C/O, DISASSEMBLE VALVE",
"Start Date ": "2021-06-29 08:45:21",
"End Date": "2021-06-29 16:45:21",
"Work Group Name": "ES MM",
"Unit ": "02",
Status: "H/APPR",
crew: "FIN",
"Work Pln Factor": "F2 WE RS NR L1 HS",
},
{
"Activity Id": "01881463-01Z",
"Activity Name": "MM 2CP40MD CLEAN UP AFTER REPLACE FILTER ELEMENT",
"Start Date ": "2021-06-29 08:45:21",
"End Date": "2021-06-29 20:45:21",
"Work Group Name": "PME1",
"Unit ": "01",
Status: "PLAN",
crew: "",
"Work Pln Factor": "F2 EN RS NR",
},
{
"Activity Id": "DG*VLV*BRIDGES*BN",
"Activity Name": "MM 2E22-S001 FILL ENGINE OIL",
"Start Date ": "2021-06-29 08:45:21",
"End Date": "2021-06-29 14:45:21",
"Work Group Name": "MM",
"Unit ": "01",
Status: "",
crew: "",
"Work Pln Factor": "RM",
},
{
"Activity Id": "04912309-3434",
"Activity Name": "MM 2E22-S001 FILL ENGINE OIL zzzz",
"Start Date ": "2021-06-29 08:45:21",
"End Date": "2021-06-29 08:45:21",
"Work Group Name": "PSCF",
"Unit ": "01",
Status: "",
crew: "",
"Work Pln Factor": "F2 WE RS NR L1 H",
},
];
}
const dataFilterArray = (data, str) => {
const value = _.uniqBy(data, str);
let newValue = value.map((each) => {
const data = each[str].split(' ');
return _.uniqBy(data, str);
});
newValue.push(`Select All`);
newValue = newValue.flat(1);
return newValue.filter((each) => each.length !== 0);
};
console.log(dataFilterArray(value.Value, 'Work Group Name'))
console.log(dataFilterArray(data, 'crew'))</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://raw.githubusercontent.com/lodash/lodash/4.17.15-npm/lodash.js"></script></code></pre>
</div>
</div>
</p>
<p>I'm wondering if there's a way to simplify the dataFilterArray. I feel like they are shouldn't be a reason to use flat method. This function also handles filtering out empty values. I would also like to remove lodash if that's possible.</p>
|
[] |
[
{
"body": "<p>What I want is a Set (a collection of unique elements).</p>\n<pre><code>const dataFilterArray = (data, str) => {\n let s = new Set();\n data.forEach(itm => {\n (itm[str] || '').split(' ').forEach(v => { \n if(v.length !== 0) s.add(v); \n });\n });\n return ['Select All'].concat([...s]);\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T17:21:19.063",
"Id": "520407",
"Score": "0",
"body": "While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T17:11:59.190",
"Id": "263593",
"ParentId": "263588",
"Score": "1"
}
},
{
"body": "<p>I think you do too much in one function. While yes, the function is relatively small, it isn't clear what it does when you look at it. Your naming is also generic and kind of misleading. For example dataFilterArray() actually returns the values that will be used in the dropdown.</p>\n<p>By taking the above into account, I came up with the following code:</p>\n<pre><code>function allWordsForKey(arr, key) {\n const values = arr.map((each) => each[key].split(' '));\n return values.flat(1)\n}\n\nfunction findUniqueWordsForKey(arr, key) {\n const words = allWordsForKey(arr, key)\n let uniqueWords = _.uniq(words);\n\n return uniqueWords.filter((each) => each && each.length !== 0);\n}\n\nfunction makeDropdownFrom(arr) {\n arr.unshift(`Select All`);\n return arr\n};\n\nfunction makeDropdownOfUniqueWordsForKey(arr, key) {\n const uniqueWords = findUniqueWordsForKey(arr, key)\n \n return makeDropdownFrom(uniqueWords)\n}\n</code></pre>\n<p>You use it like this:</p>\n<pre><code>console.log(makeDropdownOfUniqueWordsForKey(value.Value, 'Work Group Name'))\n\nconsole.log(makeDropdownOfUniqueWordsForKey(value.Value, 'crew'))\n</code></pre>\n<p>While the makeDropdownFromList() seems like a bit of an overkill it could be technically reused if you will be creating dropdowns like this in multiple places.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T12:15:46.783",
"Id": "263625",
"ParentId": "263588",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T15:53:50.193",
"Id": "263588",
"Score": "3",
"Tags": [
"javascript",
"performance",
"algorithm",
"node.js"
],
"Title": "Javascript best way to filter out empty values and simplify reusable function"
}
|
263588
|
<p>I have created Splash Screen Library in jQuery, The Splash Screen will display until the website completed loading all the images. I just wanted to review if there is any improvements for the code.</p>
<p>Here is the jQuery Code:</p>
<pre class="lang-js prettyprint-override"><code>(function (window, document, undefined) {
$.SplashScreen = function (options) {
var settings = $.extend(
{
id: "splashscreen",
desktop: true,
mobile: true,
forceLoader: false,
queryParameter: "loader",
progressCount: false,
progressCountId: "status",
progressBar: false,
progressBarId: "progress",
fadeEffect: true,
timeToFade: 1000, // In milliseconds (eg: 1000 = 1sec)
timeOut: 2000, // In milliseconds (eg: 2000 = 2sec)
},
options
);
function id(v) {
return document.getElementById(v);
}
function loadSplashScreen() {
var qstring = getQueryStringVars(window.location.href);
if (settings.forceLoader) {
settings.forceLoader =
qstring[settings.queryParameter] != null && qstring[settings.queryParameter] != "" && (qstring[settings.queryParameter] == "true" || qstring[settings.queryParameter] == "t" || qstring[settings.queryParameter] == "1")
? true
: false;
}
if (settings.mobile) {
settings.mobile = $.DetectMobile() != null ? $.DetectMobile() : false;
}
if (settings.mobile || settings.desktop || settings.forceLoader) {
var overly = id(settings.id),
img = document.images,
progCount = id(settings.progressCountId),
progBar = id(settings.progressBarId),
c = 0;
totalImages = img.length;
function imgLoaded() {
c += 1;
if (settings.progressBar) {
var percentage = (((100 / totalImages) * c) << 0) + "%";
progBar.style.width = percentage;
}
if (settings.progressCount) {
progCount.innerHTML = "Loading " + percentage;
}
if (c === totalImages) {
var element = document.getElementById(settings.id);
element.IntervalPageCompleted = setTimeout(function () {
return pageLoadCompleted();
}, settings.timeOut);
}
}
function pageLoadCompleted() {
if (settings.fadeEffect) fade(settings.id);
else {
overly.style.opacity = 0;
overly.style.display = "none";
}
}
for (var i = 0; i < totalImages; i++) {
var tImg = new Image();
tImg.onload = imgLoaded;
tImg.onerror = imgLoaded;
tImg.src = img[i].src;
}
} else {
id(settings.id).style.display = "none";
}
}
function getQueryStringVars(url) {
var vars = [],
hash;
var hashes = url.slice(url.indexOf("?") + 1).split("&");
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split("=");
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function animateFade(lastTick, eid) {
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var element = document.getElementById(eid);
if (element.FadeTimeLeft <= elapsedTicks) {
element.style.opacity = element.FadeState == 1 ? "1" : "0";
element.style.filter = "alpha(opacity = " + (element.FadeState == 1 ? "100" : "0") + ")";
element.FadeState = element.FadeState == 1 ? 2 : -2;
return;
}
element.FadeTimeLeft -= elapsedTicks;
var newOpVal = element.FadeTimeLeft / settings.timeToFade;
if (element.FadeState == 1) newOpVal = 1 - newOpVal;
element.style.opacity = newOpVal;
element.style.filter = "alpha(opacity = " + newOpVal * 100 + ")";
setTimeout(function () {
animateFade(curTick, eid);
}, 33);
}
function fade(eid) {
var element = document.getElementById(eid);
if (element.FadeState == null) {
if (element.style.opacity == null || element.style.opacity == "" || element.style.opacity == "1") element.FadeState = 2;
else element.FadeState = -2;
}
if (element.FadeState == 1 || element.FadeState == -1) {
element.FadeState = element.FadeState == 1 ? -1 : 1;
element.FadeTimeLeft = settings.timeToFade - element.FadeTimeLeft;
} else {
element.FadeState = element.FadeState == 2 ? -1 : 1;
element.FadeTimeLeft = settings.timeToFade;
setTimeout(animateFade(new Date().getTime(), eid), 33);
}
}
try {
document.addEventListener("DOMContentLoaded", loadSplashScreen(), false);
} catch (ex) {
console.log(ex.message);
}
};
// Detecting mobile phone
$.DetectMobile = function () {
var isMobile = {
Android: function () {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function () {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i);
},
any: function () {
return isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows();
},
};
return isMobile.any();
};
})(window, document);
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T16:55:25.287",
"Id": "263591",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Splash Screen Library in jQuery"
}
|
263591
|
<p>EDIT: Changed title, few mistakes in code were resolved (now working properly)</p>
<p>The GUI I am trying to make will be a simple QTabWidget, leading a user straightforwardly towards the end tab by tab.</p>
<p>For now, I have three *.py files - main.py, tab1.py, tab2.py. In main.py is the main window of the app and function to run the app like this (simplified just to focus on my question):</p>
<pre><code>import sys
import tab1
import tab2
import PyQt5.QtWidgets as qtw
def main():
app = qtw.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
class MainWindow(qtw.QmainWindow):
def __init__(self):
super().__init__()
self.tabwidget = qtw.QTabWidget()
self.setCentralWidget(self.tabwidget)
self.tab1 = tab1.Tab_1()
self.tab2 = tab2.Tab_2()
# This is how I now passing the information from tab1 to tab2
self.tab1.path_line.textChanged.connect(self.tab2.path_widget.setText)
self.tabwidget.addTab(self.tab1, 'tab1')
self.tabwidget.addTab(self.tab2, 'tab2')
if __name__ == '__main__':
main()
</code></pre>
<p>In the tab1.py is defined class for a tabwidget which will serve as an input data tab. There is a button to open filedialog, read filename, and write the path into QLineEdit widget:</p>
<pre><code>import PyQt5.QtWidgets as qtw
class Tab_1(qtw.QWidget):
def __init__(self):
super().__init__()
self.path_line = qtw.QLineEdit()
self.but = qtw.QPushButton('Open')
self.but.clicked.connect(self.openfile)
layout_1 = qtw.QVBoxLayout()
layout_1.addWidget(self.but)
self.setLayout(layout_1)
def openfile(self):
filename, _ = qtw.QFileDialog.getOpenFileName(self, 'Title', 'File types')
if filename:
self.path_line.setText(filename)
else:
self.path_line.setText('No file was selected!')
</code></pre>
<p>Now I want to in another file tab2.py use the path I got from qtw.OpenFileDialog. So the defined class Tab_2() looks like this:</p>
<pre><code>import PyQt5.QtWidgets as qtw
class Tab_2(qtw.QWidget):
def __init__(self):
super().__init__()
# Retrieving the information by QLabel widget
self.path_widget = qtw.QLabel()
# Transform the information into string variable
self.path_string = self.path_widget.text()
layout_2 = qtw.QVBoxLayout()
layout_2.addWidget(self.path_widget) # The path from QFileDialog (Tab1) should appered on Tab2
self.setLayout(layout_2)
</code></pre>
<p>My question is, is this the proper way to do it? Should I use MainWindow class as a "getter" and "passer" of the information like that or should that be implemented in the tab classes themselves? It works but I do not want to learn to do something bad way and eventually get used to it. I understand classes and their inheritance to some point (a lot of examples of dog classes or employee classes that I understand how it works but in my case I am confused). In combination with GUI, it messing up my head. Also, I want to have each tab as a separate class in a separate *.py file to make it clear and easy to add another one in the future. I see, that it might not be the right way to uses classes but each tab will have a different layout.</p>
|
[] |
[
{
"body": "<p>Basically your code works.</p>\n<p>To write the selected path, you use the <code>QLineEdit</code> widget of the <code>Tab_1</code> class.\nYou don't show the <code>path_line</code> widget itself anywhere, but use the <code>textChanged</code> signal.</p>\n<p>It is not clear why there is a <code>path_string</code> object in the <code>Tab_2</code> class that you are not using.</p>\n<p>I would suggest you:</p>\n<ul>\n<li><p>object <code>self.path_line = ''</code> declare in the <code>MainWindow</code> class.</p>\n</li>\n<li><p>use the <code>currentChanged</code> signal:</p>\n<p><code>self.tabwidget.currentChanged.connect(self.current_changed)</code></p>\n</li>\n<li><p>when creating instances of the <code>Tab_1</code> and <code>Tab_2</code> classes, pass <code>self</code> as an argument, which will allow you to have access to objects of the <code>MainWindow</code> class in these widgets, for example <code>path_line</code>.</p>\n</li>\n<li><p>In the slot <code>current_changed</code>, you can write logic,\nwhich you will need when the index of the current page changes.</p>\n</li>\n</ul>\n<hr />\n<pre><code>import sys\nimport PyQt5.QtWidgets as qtw\n\n#from tab1 import Tab_1\nclass Tab_1(qtw.QWidget):\n def __init__(self, parent=None): # + parent\n super().__init__()\n self.parent = parent # + parent\n\n self.but = qtw.QPushButton('Open')\n self.but.clicked.connect(self.open_file)\n\n layout = qtw.QVBoxLayout(self)\n layout.addWidget(self.but)\n\n def open_file(self):\n filename, _ = qtw.QFileDialog.getOpenFileName(self, 'Title', 'File types')\n if filename:\n self.parent.path_line = filename # + parent\n else:\n self.parent.path_line = '' # + parent\n \n \n#from tab2 import Tab_2\nclass Tab_2(qtw.QWidget):\n def __init__(self, parent=None):\n super().__init__()\n self.parent = parent\n\n self.path_widget = qtw.QLabel()\n \n layout = qtw.QVBoxLayout(self)\n layout.addWidget(self.path_widget) \n \n\nclass MainWindow(qtw.QMainWindow):\n def __init__(self):\n super().__init__()\n self.path_line = '' # + path_line\n \n self.tabwidget = qtw.QTabWidget()\n self.tabwidget.currentChanged.connect(self.current_changed) # + currentChanged\n self.setCentralWidget(self.tabwidget)\n \n self.tab1 = Tab_1(self) # + self\n self.tab2 = Tab_2(self) # + self\n\n self.tabwidget.addTab(self.tab1, 'Tab 1')\n self.tabwidget.addTab(self.tab2, 'Tab 2')\n \n def current_changed(self, index):\n if index == 0:\n self.statusBar().showMessage('Message in statusbar. '\n 'Select the file to read.', 5000)\n if index == 1:\n self.tab2.path_widget.setText(self.path_line)\n if not self.path_line:\n self.statusBar().showMessage(\n 'Go to the first tab and select the file to read.', 5000) \n \n\ndef main():\n app = qtw.QApplication(sys.argv)\n window = MainWindow()\n window.resize(400, 300)\n window.show()\n sys.exit(app.exec_())\n \nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/xWUdG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xWUdG.png\" alt=\"enter image description here\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T13:58:13.050",
"Id": "520786",
"Score": "0",
"body": "Thanks for your answer. Your suggestion is exactly what I was looking for!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T14:00:25.160",
"Id": "520787",
"Score": "0",
"body": "@roPe you are welcome"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T22:16:06.597",
"Id": "263707",
"ParentId": "263594",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "263707",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T18:03:13.300",
"Id": "263594",
"Score": "1",
"Tags": [
"python",
"gui",
"pyqt"
],
"Title": "Proper way to pass an infromation/variable across QTabWidgets?"
}
|
263594
|
<p>Is the following a proper way to write a class using Keras and TensorFlow to train a neural network?</p>
<pre><code>from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
from livelossplot import PlotLossesKeras
import numpy
class NeuralNet:
def __init__(self):
self.model = None
try:
self.model = keras.models.load_model("my_nn.h5")
print("Model loaded")
self.model.summary()
except Exception as ex:
print("No model found for loading!")
if self.model == None:
print("creating a new model.")
# create model
self.model = Sequential()
self.model.add(Dense(12, input_dim=8, activation='relu'))
self.model.add(Dense(8, activation='relu'))
self.model.add(Dense(1, activation='sigmoid'))
# Compile model
self.model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# END of if
# END of def __init__(self):
def train(self, X, Y):
# Fit the model
history = self.model.fit(
X, Y,
validation_split=0.33,
epochs=150,
batch_size=10,
verbose=1
)
self.model.save("my_nn.h5")
return history
# END of def train()
def plot(self):
# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
if __name__ == '__main__':
# load dataset
dataset = numpy.loadtxt("file.txt", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]
nn = NeuralNet()
history = nn.train(X, Y)
# list all data in history
print(history.history.keys())
</code></pre>
<p>If YES,</p>
<p>how can I accommodate <strong>validation</strong> and <strong>testing</strong> code here?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T21:14:53.690",
"Id": "263602",
"Score": "0",
"Tags": [
"python",
"neural-network",
"tensorflow",
"keras"
],
"Title": "Neural Network class in python"
}
|
263602
|
<p>I have implemented a correct version of DFS (with comments explaining the implementation):</p>
<pre><code>from lark import Lark, tree, Tree, Token
def dfs(root_node : Tree, f) -> Tree:
"""
To do DFS we need to implement a stack. In other words we need to go down the depth until the depth has been
fully processed. In other words what you want is the the current child you are adding to the dequeue to be processed
first i.e. you want it to skip the line. To do that you can append to the front of the queue (with append_left and
then pop_left i.e. pop from that same side).
:param root_node:
:param f:
:return:
"""
dq = deque([root_node])
while len(dq) != 0:
current_node = dq.popleft() # to make sure you pop from the front since you are adding at the front.
current_node.data = f(current_node.data)
# print(current_node.children)
for child in reversed(current_node.children):
dq.appendleft(child)
return root_node
</code></pre>
<p>with unit test:</p>
<pre><code> print()
# token requires two values due to how Lark works, ignore it
ast = Tree(1, [Tree(2, [Tree(3, []), Tree(4, [])]), Tree(5, [])])
# the key is that 3,4 should go first than 5 because it is DFS
dfs(ast, print)
</code></pre>
<p>the output is as I expected it:</p>
<pre><code>1
2
3
4
5
</code></pre>
<p>however, it looks rather strange to have a <code>reversed</code> in the code (plus it looks inefficient unless the list is implemented with a head and tail pointer list). How does one change this code so that it looks like the standard "append to the end and pop from the same end". Doing that blindly however for trees leads to wrong printing:</p>
<pre><code>def dfs_stack(ast : Tree, f) -> Tree:
stack = [ast]
while len(stack) != 0:
current_node = stack.pop() # pop from the end, from the side you are adding
current_node.data = f(current_node.data)
for child in current_node.children:
stack.append(child)
return ast
</code></pre>
<p>see output:</p>
<pre><code>1
5
2
4
3
</code></pre>
<p>note my second implementation is based on <a href="https://codereview.stackexchange.com/questions/247368/depth-first-search-using-stack-in-python?newreg=d2760a7347504f6ebadfd329d6f127ca">Depth First Search Using Stack in Python</a> which is for graphs. Perhaps the reason I need to reverse it is because I am traversing a tree where the children ordering matters but the children ordering does not matter in a graph and it makes that code look cleaner (so there is no clear way of how to add for a graph but the invariant of "traversing the children before the siblings" is respected just not in the order I'd expect for trees).</p>
<p>Is there a way to remove the <code>reversed</code> so that the code is still correct and it looks more similar to the standard DFS?</p>
|
[] |
[
{
"body": "<blockquote>\n<p>Doing that blindly however for trees leads to wrong printing</p>\n</blockquote>\n<p>No surprise here. In the initial version the deque functions like a stack, so when you change it to the honest-to-goodness stack nothing changes: you still need to push children nodes in the reverse order (stack is last-in-first-out, so the last child pushed will be processed first).</p>\n<p>There are few options avoid reversal.</p>\n<ul>\n<li><p>A plain old recursion.</p>\n</li>\n<li><p>If the goal is to not recurse, don't push a list of children. Push generators instead.</p>\n</li>\n</ul>\n<p>Edit:</p>\n<p>A quick-and-dirty example with generators:</p>\n<pre><code>def generate_children(node):\n for child in node.children:\n yield child\n\ndef dfs(node):\n print(node.data)\n stk = [generate_children(node)]\n\n while stk:\n try:\n child = next(stk[-1])\n print(child.data)\n stk.append(generate_children(child))\n except StopIteration:\n stk.pop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T22:56:14.520",
"Id": "520439",
"Score": "0",
"body": "how do you \"push generators\" or what does that mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T23:16:23.847",
"Id": "520440",
"Score": "0",
"body": "For every node you could define a generator, which `yield`s the node's children one by one in order. See edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T09:30:04.890",
"Id": "520462",
"Score": "0",
"body": "FWIW you'd need an iterator, which a generator is a subclass of. You can just replace `generate_children(child)` with `iter(child.children)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T17:44:45.980",
"Id": "520507",
"Score": "0",
"body": "@vnp thanks for the comment \"stack is last-in-first-out, so the last child pushed will be processed first\" that makes sense! I am glad that my reverse sorting is correct + efficient. Perhaps if I had a way to loop backwards without reversing that would be nice. I guess that is what `reversed` does since it returns an iterator."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T22:48:38.897",
"Id": "263606",
"ParentId": "263604",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T22:22:07.280",
"Id": "263604",
"Score": "1",
"Tags": [
"python",
"tree",
"depth-first-search"
],
"Title": "How does one write DFS in python with a Deque without reversed for Trees?"
}
|
263604
|
<p>I recently wrote a login function in my express application that does the following:</p>
<ol>
<li>Verifies the user's email and password are correct</li>
<li>Generates a JWT Access Token with a short expiry date, and then sends it back to the user</li>
<li>Generates a JWT Refresh Token with a long expiry date, and then saves it to MongoDB. I will then create a middleware to check if that access token still exists on each secured endpoint only if the Access token is expired. Then, I will send them a new Access Token.</li>
</ol>
<p>I am looking to improve the readability and maintainability for this login endpoint.</p>
<p>Here is the login endpoint</p>
<pre><code>// Login to the application
router.post('/login', loginRules, validate, async (req, res, next) => {
try{
// verify the email and password
let user = await Account.findOne({email: req.body.email}).exec();
if(user == null) {
return res.status(400).json({error: 'User not found'});
}
let isPasswordCorrect = await bcrypt.compareSync(req.body.password, user.password);
// login was successful
if(isPasswordCorrect) {
// generate a jwt token
let accessToken = jwt.sign({email: user.email}, process.env.JWT_SECRET_KEY,
{expiresIn: parseInt(process.env.JWT_ACCESS_TOKEN_EXPIRE_TIME)});
// generate a refresh token and store it into the database.
let userIPAddress = req.ip;
let userBrowser = req.headers['user-agent'];
let refreshToken = jwt.sign({email: user.email, ip_address: userIPAddress,
user_browser: userBrowser}, process.env.JWT_REFRESH_TOKEN_SECRET_KEY,
{expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRE_TIME});
const userDelegate = new Delegate({account: user.id,
refresh_token: refreshToken,
ip_address: userIPAddress,
browser: userBrowser});
await userDelegate.save();
// Send the jwt back to the caller if the login was sucessful
return res.status(200).json({token: accessToken});
}
// login was incorrect
else {
return res.status(400).json({error: 'Incorrect Login Credentials'});
}
}
catch(e) {
return res.status(400).json({error: 'Unexpected error happened'});
}
})
</code></pre>
<p>LoginRules middleware</p>
<pre><code>// validation-rules.js
// validation rules for logging into the application
const loginRules = [
check('email').exists({checkFalsy: true, checkNull: true}).not().isEmpty().isEmail().normalizeEmail(),
check('password').exists({checkFalsy: true, checkNull: true}).not().isEmpty().isString()
]
module.exports = {
loginRules
}
</code></pre>
<p>validate middleware</p>
<pre><code>// validator.js
const { validationResult } = require('express-validator');
// Check if there wasn't any errors when the user input was validated.
const validate = (req, res, next) => {
const errors = validationResult(req);
if(!errors.isEmpty()) {
return res.status(400).json({errors});
}
next();
}
module.exports = {validate};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T23:45:17.333",
"Id": "520443",
"Score": "0",
"body": "Why use `await` in `await bcrypt.compareSync(...)`? It's synchronous, right? It directly returns the value, not a promise, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T23:47:30.513",
"Id": "520445",
"Score": "0",
"body": "In your `try/catch`, you should log the actual exception in the `catch` because if it starts happening, you will need to know what is actually going wrong in order to troubleshoot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T00:22:51.990",
"Id": "520448",
"Score": "0",
"body": "@jfriend00 Yes you are 100% correct on both comments. Thank you for the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T14:32:13.570",
"Id": "520500",
"Score": "0",
"body": "@jfriend perhaps you were waiting for a response to the question in your first comment but please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment)."
}
] |
[
{
"body": "<p>I think your middleware is fine. The problem is that you do everything in the controller. The controller should just call the login function from your business layer.</p>\n<p>You had to comment the code to explain it. Treat this as a sign that the function is doing too much. You will see, that I have basically just split the code into the functions based on your comments. Everything else is basically just creation of the objects that will be handled by your business logic.</p>\n<p>From the controller's point of view all of the complexity is hidden away. Controller just calls the login function and responds with the result of that function.</p>\n<p>auth.controller.js:</p>\n<pre><code>import { login } from './auth.service.js'\n\nrouter.post('/login', loginRules, validate, async (req, res, next) => {\n try{\n const credentials = { email: req.body.email, password: req.body.password }\n const refreshTokenOpts = {\n ip: req.ip,\n browser: req.headers['user-agent']\n }\n\n const accessToken = await login(credentials, refreshTokenOpts)\n\n return res.status(200).json({ accessToken });\n }\n catch(e) {\n if(e.code === 'user_not_found' || e.code === 'incorrect_password') \n return res.status(400).json({error: 'Invalid username or password'})\n\n return res.status(500).json({error: 'Unexpected error happened'});\n }\n})\n</code></pre>\n<p>Above I have just defined the behavior of the login: it receives the credentials and parameters that will be used for refresh token, it returns the access token and throws "user not found" and "incorrect password".</p>\n<p>How I implement that is now down to auth service and not a concern of the controller.</p>\n<p>auth.service.js:</p>\n<pre><code>function verifyPassword(actual, expected){\n let isPasswordCorrect = bcrypt.compareSync(actual, expected)\n if(!isPasswordCorrect) throw new Error({code: 'incorrect_password'})\n}\n\nfunction verifyUserCredentials(credentials, user) {\n if(!user) throw new Error({code: 'user_not_found'})\n\n verifyPassword(credentials.password, user.password)\n}\n\nfunction generateToken(user) {\n const payload = { email: user.email }\n const options = { \n expiresIn: parseInt(process.env.JWT_ACCESS_TOKEN_EXPIRE_TIME)\n }\n\n return jwt.sign(\n payload,\n process.env.JWT_SECRET_KEY,\n options\n );\n}\n\nfunction generateRefreshToken(user, ip, browser) {\n const payload = { \n email: user.email,\n ip_address: ip,\n user_browser: browser\n }\n const options = { expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRE_TIME }\n\n return jwt.sign(\n payload,\n process.env.JWT_REFRESH_TOKEN_SECRET_KEY,\n options\n );\n}\n\nasync function saveRefreshToken(user, ip, browser, refreshToken) {\n new Delegate(\n {\n account: user.id,\n refresh_token: refreshToken,\n ip_address: ip,\n browser\n }\n )\n .save();\n}\n\nexport async function login(credentials, {ip, browser}) {\n const user = await Account.findOne({ credentials.email }).exec()\n verifyUserCredentials(credentials, user)\n\n const refreshToken = generateRefreshToken(user, ip, browser)\n await saveRefreshToken(user, ip, browser, refreshToken)\n\n return generateToken(user) \n}\n</code></pre>\n<p>This is just as far as the code refactoring goes.</p>\n<p>As login goes, it is not clear to me, why you are generating the refresh token, but not returning it to the user. And if you are not returning it to the user by design and not by accident, why are you saving it to the database instead of saving the actual data, that you would need to generate another access token.</p>\n<p>To me it seems like you are misusing the JWT, as it serves to ensure integrity of the client data not of the data that you have control over, otherwise you would be saving everything with JWT in the database.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T16:58:01.883",
"Id": "520573",
"Score": "0",
"body": "To answer your question, I was reading online that you aren't supposed to send the refresh token to the user. Rather, we only send the Access token to the user and then regenerate the new Access token when it's expired by using the refresh token that would be stored in the database. When generating a new access token, I verify that the expired token wasn't used in a CSRF attack by making sure the same IP address and browser that requested the original access token is still the same user. I could be completely wrong in my approach, so if you can send me on the right path that would be good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T16:58:16.920",
"Id": "520574",
"Score": "0",
"body": "Also thank you for the response it was very insightful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:07:45.927",
"Id": "520575",
"Score": "0",
"body": "If we sent both the refresh token and the access token to the user, then both the refresh token and access token could be exposed in a CSRF attack. Also, since the refresh token has a longer expiry time than an access token, an attacker could use that token for a way longer duration of time. Again, i could be wrong in this regard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:21:16.393",
"Id": "520579",
"Score": "0",
"body": "@Tony But you aren't storing the token in cookies. As far as I know CSRF only works if you store the token in cookies and that can be prevented by using \"same site cookie\" https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#samesite-cookie-attribute. Also, you are checking the IP and browser to make sure that the request was sent from the same client when you are refreshing the token, so even if someone stole it, he wouldn't be able to reproduce it I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:26:07.850",
"Id": "520580",
"Score": "0",
"body": "I think that in your case you don't even need a refresh token. Save the access token to the database and expiry time. You can then refresh the token by sending the refresh token to the server and checking if IP, browser and token are the same and if the \"right to refresh\" didn't expire. I'm not sure about it, but the refresh token is not used anywhere anyway. Also to have the token saved in the database at all might be useless :D I'm not a security expert though, so take everything I say regarding safety with a grain of salt :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:33:46.640",
"Id": "520581",
"Score": "0",
"body": "The problem with not using refresh token on the client is that whenever token expires you will not be able to refresh it anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:44:51.887",
"Id": "520582",
"Score": "0",
"body": "I was planning on creating another middleware for secured endpoints that checks if the access token is expired. If the token is expired, I am going to see if there was a refresh token saved in the database. If there is a refresh token, then i am going to check if it's expired or not. Any malicious users wouldnt be able to use the refresh token since it's never exposed. I rewrote my login endpoint recently that checked if there was a refresh token already in place upon login. If there was a refresh token, I deleted the previous refresh token and inserted a new one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:48:39.470",
"Id": "520583",
"Score": "0",
"body": "My thoughts stem from the OAuth article https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/ \"Refresh tokens are usually subject to strict storage requirements to ensure they are not leaked.\" Based on that quote, I decided not to send refresh tokens to users."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:29:42.190",
"Id": "520588",
"Score": "0",
"body": "The problem with that is that the front end will never get a new access token, so you are effectively having one long lived access token. Also, the purpose of having jwt is that you don't have to query your database, because it is slow. I think you are misusing refresh tokens, at least as far as I understand them - they are useful only if they are used by the client. But my advice is this: if you don't have an app that really needs high security, don't concern yourself too much about being hacked. If someone steals the access token you have bigger problems than the refresh token :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:33:30.593",
"Id": "520590",
"Score": "0",
"body": "The article talks about token storage in the database. If you check the diagram about refresh tokens you can see that the client sends the refresh token to the server and receives back a new access token. If someone steals the refresh token you have the option to revoke the refresh token in the database and thus limit the potential damage the bad guy might inflict. But remember, the guy still has the access token so he can still do the damage for the time being."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:55:26.823",
"Id": "520592",
"Score": "0",
"body": "You make a valid point. I am still unsure how would i restrict access to the refresh token if the refresh token isn't stored in the database. How would you suggest in re-implementing this? Should i send both the access and refresh token to the user, and then not save the refresh token in the database. Or, should i send both the access and refresh token to the user and then save the refresh token in the database, and then I would have to make a query to the database to check if the refresh token still exists for the particular user each time the refresh token endpoint is called."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:56:44.110",
"Id": "520593",
"Score": "0",
"body": "If the refresh token isn't saved to the database, I wouldn't know how to restrict access."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T16:19:05.570",
"Id": "263673",
"ParentId": "263608",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "263673",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T23:42:35.263",
"Id": "263608",
"Score": "1",
"Tags": [
"javascript",
"authentication",
"express.js",
"jwt"
],
"Title": "Making my login function more readable and maintainable"
}
|
263608
|
<p>This is my solution to <a href="https://leetcode.com/problems/course-schedule-ii/" rel="nofollow noreferrer">Leetcode #210, Course Schedule II</a>.</p>
<blockquote>
<p>There are a total of <code>numCourses</code> courses you have to take, labeled from
<code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where
<code>prerequisites[i] = [ai, bi]</code> indicates that you must take course <code>bi</code>
first if you want to take course <code>ai</code>.</p>
<p>Return the ordering of courses you should take to finish all courses.
If there are many valid answers, return any of them. If it is
impossible to finish all courses, return an empty array.</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>UNVISITED = 0
VISITING = -1
VISITED = 1
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
adj_list = {course: [] for course in range(numCourses)}
for course, prereq in prerequisites:
adj_list[prereq].append(course)
stack = []
found_loop = False
vertex_status = [UNVISITED] * numCourses
def topological_sort(course_vertex):
nonlocal found_loop
course_visit_status = vertex_status[course_vertex]
if course_visit_status == VISITING:
found_loop = True
return
elif course_visit_status == VISITED:
return
vertex_status[course_vertex] = VISITING
for neighbor in adj_list[course_vertex]:
topological_sort(neighbor)
stack.append(course_vertex)
vertex_status[course_vertex] = VISITED
for course_vertex in range(numCourses):
topological_sort(course_vertex)
if found_loop:
return []
return reversed(stack)
</code></pre>
<p>The function is mostly efficient; I am not worried about the complexity.</p>
<p>However, I feel like the nested function <code>topological_sort</code> is a bit of a hack, since it's using the <code>nonlocal</code> keyword. The function is really doing two things: manipulating the <code>stack</code> and also potentially changing the variable <code>found_loop</code>.</p>
<p>From a software engineering perspective, this doesn't seem like a very well factored piece of code. I could raise an exception instead, but that similarly seems to be a function that does two things.</p>
<p>How could I modularize this function better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T04:40:01.083",
"Id": "520452",
"Score": "2",
"body": "Getting rid of `nonlocal` seems trivial. Let `topological_sort` return a boolean."
}
] |
[
{
"body": "<p><strong>Clear algorithm and naming</strong>. You've done a good job with the algorithm and\nusing clear naming. I had no trouble reading and understanding the code.</p>\n<p><strong>Declarative constants are good</strong>. Your idea to use declarative status\nconstants is sensible. In fact, I would encourage you to create such constants\nfor <code>LOOP</code> vs <code>NOLOOP</code> to further enhance code readability. On the same\ntopic, I increasingly give such variables declarative values as\nwell. Among other things, it can help when debugging.</p>\n<p><strong>Simple, natural-language names whenever possible</strong>. Within your habit of using\nclear names, I would encourage you to favor simpler names whenever they work\nfine without loss of meaning. For example, <code>course</code> rather than <code>course_vertex</code>\nand <code>statuses</code> rather than <code>vertex_status</code> (also: use plural for collections).\nThose shorter names are just as clear in context, and brevity in naming helps\nwith readability by lightening the visual weight of code.\nAs a separate naming\nissue, I don't know whether LeetCode requires you to use <code>numCourses</code>: if not,\nswitch to a consistent standard, using something like <code>n_courses</code>.</p>\n<p><strong>Convenience variables in the toolbox</strong>. Within clearly defined contexts, you\ncan often improve readability by using very short convenience variables.\nThis is illustrated below when checking for already-visited status.</p>\n<p><strong>Separate method, aided by OO</strong>. Regarding your sensible questions about\n<code>topological_sort()</code>, the easy step already suggested in a comment is to return\na <code>bool</code> rather than messing around with a <code>nonlocal found_loop</code>. I would take\nthings further and pull it out into a separate method. The annoyance with doing\nthat is the need to pass several arguments to the function: <code>course</code>,\n<code>statuses</code>, <code>adj_list</code>, and <code>stack</code>. However, <em>and I rarely say this around\nhere</em>, you should use more OO. You already have a class and this is actually a sensible use case for a\nfew attributes: <code>adj_list</code>, <code>statuses</code>, and <code>stack</code>.</p>\n<p><strong>More direct name for the method</strong>. After those changes, it also seemed more\nnatural and declarative to rename that function to <code>add_course()</code>: its job is\nto add each course to the stack, in the proper order. Simple naming is good.</p>\n<p><strong>Return a list</strong>. The <code>findOrder()</code> method should return a list rather than a\nreversed iterator: <code>list(reversed(stack))</code>.</p>\n<p><strong>Organize code in commented paragraphs</strong>. Finally, you can improve code\nreadability further by organizing the code into commented blocks or paragraphs.\nThe comments can often be very basic, functioning almost as guideposts or\nheadings (helps with visual scanning when projects get large). When needed,\nsuch comments can provide guidance about purpose, convey a sense of logical\nnarrative in the code, or provide some intuition to understand the algorithm.\nExamples of all of those are among the suggested edits below.</p>\n<pre><code>from typing import List\n\nUNVISITED = 'UNVISITED'\nVISITING = 'VISITING'\nVISITED = 'VISITED'\nLOOP = 'LOOP'\nNOLOOP = 'NOLOOP'\n\nclass Solution:\n\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n # Course visited/unvisited statuses.\n course_rng = range(numCourses)\n self.statuses = [UNVISITED for _ in course_rng]\n\n # Map PREREQ => COURSES.\n self.adj_list = {course: [] for course in course_rng}\n for course, prereq in prerequisites:\n self.adj_list[prereq].append(course)\n\n # Build course order as a stack.\n self.stack = []\n for course in course_rng:\n if self.add_course(course) is LOOP:\n return []\n return list(reversed(self.stack))\n\n def add_course(self, course):\n # Return immediately if already seen.\n s = self.statuses[course]\n if s is VISITING:\n return LOOP\n elif s is VISITED:\n return NOLOOP\n\n # Before adding the current course, we must add\n # those that depend on it.\n self.statuses[course] = VISITING\n for neighbor in self.adj_list[course]:\n self.add_course(neighbor)\n self.statuses[course] = VISITED\n\n # Success: add current course.\n self.stack.append(course)\n return NOLOOP\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T10:32:23.333",
"Id": "520555",
"Score": "1",
"body": "`add_course` currently never returns `LOOP`, to fix that `self.statuses[course] is VISITING` should be an assignment instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T15:32:27.710",
"Id": "520566",
"Score": "0",
"body": "@Jasmijn Thanks, I introduced that typo in a last-minuted edit. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T19:15:28.993",
"Id": "520798",
"Score": "0",
"body": "This is great, thank you for the suggestions!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T06:30:02.500",
"Id": "263657",
"ParentId": "263609",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263657",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T03:52:33.540",
"Id": "263609",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"graph",
"topological-sorting"
],
"Title": "Python leetcode: scheduling courses to meet prerequisite requirements"
}
|
263609
|
<p>I've tried, as practise, to write a Python 3 script which takes a list of paths to files/directories and compresses them with <code>tar</code>, before encrypting the resultant tarball with <code>gpg</code> (for backing up to an external location). The script allows the user to choose which compression and encryption algorithms to use, and where to save the resultant file to.</p>
<p>I'm fairly new to Python and come from a C-style background, so I'm hoping for feedback on proper use of loops, branches, object management, and the like. If I've made any glaring errors with use for <code>tar</code> or <code>gpg</code>, I would appreciate them being pointed out too.</p>
<p>This is how my script runs:</p>
<ol>
<li>The <code>read_arguments()</code> function:
<ol>
<li>Read and parse arguments and argument parameters.</li>
<li>If there's an error with arguments, state so and exit.</li>
<li>Depending on options, read from the standard input stream and/or format paths to be in absolute form.</li>
<li>Return an instance of <code>Configuration</code> with the configuration options.</li>
</ol>
</li>
<li>The <code>compress(config)</code> function, passed that <code>Configuration</code> object:
<ol>
<li>Check that the specified output directory exists and try to create it if it doesn't.</li>
<li>Make 64 attempts at finding a unique file path for the compressed output using a random filename (we're trying not to overwrite any existing files).</li>
<li>Call <code>tar</code> to compress the paths we were passed, using the specified compression algorithm.</li>
<li>Return a <code>pathlib.Path</code> instance pointing to the tarball.</li>
</ol>
</li>
<li>The <code>encrypt(config, tarball_path)</code> function, passed the <code>Configuration</code> object and the tarball path.
<ol>
<li>Call <code>gpg</code> to symmetrically compress the tarball with the specified encryption algorithm, writing output to the specified location. <code>gpg</code> then invokes <code>gpg-agent</code> to ask for a password and so on and so forth.</li>
</ol>
</li>
<li>The <code>cleanup(config, tarball_path)</code> function, passed the <code>Configuration</code> object and the tarball path.
<ul>
<li>Also called if any part of <code>compress()</code> or <code>encrypt()</code> fails.</li>
</ul>
<ol>
<li>Check to see if the user specified for the temporary tarball to <em>not</em> be deleted.</li>
<li>Delete the tarball file if it's alright for us to do so.</li>
</ol>
</li>
</ol>
<p>I also want to explain the <code>--force-absolute</code>, <code>--</code>, and <code>-@</code> functions because they're the ones that might be most confusing.</p>
<ul>
<li><code>--force-absolute</code> causes paths passed to the script to be resolved to their absolute forms before being passed to <code>tar</code>. Using this option is meant to help prevent naming collisions if a user passes files from multiple directories, and it's also something I like because then I can see the full path of where files came from if I need to use the backup later on.</li>
<li><code>--</code> tells the script to interpret all further arguments as paths, so if you have a file/directory path starting with a dash "-", it isn't read as an option, and you don't get a "hey this option doesn't exit" error.</li>
<li><code>-@</code> tells the script to read file paths from the standard input stream (separated by newline characters). It's useful for if you've got a directory/file with a space in its name, and you're calling this script from another script - then you can just pipe paths and avoid the hassle of dealing with shell stuffs.</li>
</ul>
<p>I made this script to use personally, it's not a work project that's going to be distributed to users or anything, but I try to write/describe programs as if they were going to be used by other people since it seems like a good idea for writing good code.</p>
<p>My environment is just Ubuntu 20.10 with Python 3.8.6, Gnu bash 5.0.17, Gnu tar 1.30, GnuPG 2.2.20 (libgcrypt 1.8.5), and Parallel BZIP2 1.1.13.</p>
<p>Here's the code of the script (in a file <code>extract.py</code>):</p>
<pre><code>#!/usr/bin/env python3
################################################################################################
##
## This script takes a list of file/directory paths and compresses them with tar, before
## encrypting that tarball with gpg. It includes options for:
## * The output directory (which temporary and output files are written to);
## * The name to give the final encrypted file;
## * Whether or not to delete the temporary tarball file;
## * If paths should be resolved to their absolute forms before being run through tar;
## * The compression algorithm for tar to use;
## * The encryptions algorithm for gpg to use.
##
################################################################################################
import os
import pathlib
import random
import subprocess
import sys
SCRIPT_NAME = pathlib.Path(sys.argv[0]).name
# Enumeration of return codes for various errors that may occur during this script.
class ReturnCode:
SUCCESS = 0
ARGUMENT_ERROR = 1
PATH_NOT_FOUND = 2
CANNOT_CREATE_OUTPUT_DIRECTORY = 4
CANNOT_LOCATE_PATH_FOR_TEMPORARY_FILES = 5
COMPRESSION_ERROR = 6
ENCRYPTION_ERROR = 7
CLEANUP_ERROR = 8
# Describes the configuration for this script as specified by command-line arguments and the
# standard input stream.
class Configuration:
output_directory = pathlib.Path.cwd()
output_name = "files"
delete_temporary_files = True
enforce_absolute_paths = False
compression_algorithm = "gzip"
encryption_algorithm = "AES256"
paths = list()
# Reads and parses command-line arguments to interpret how the user wants this script to run.
# May also read from the standard input stream, depending on command-line arguments.
#
# Returns an instance of `Configuration`.
def read_arguments():
# Prints help information for this script. Lines of help information should be at most 80
# characters in length.
def print_help():
# " -------------- This commented-out string is 80 characters long -------------- "
print("Python 3 script for packaging and encrypting a set of files using tar/gpg.")
print("")
print("Usage:")
print(" extract.py [option|file|directory]* [-- (file|directory)*]")
print("")
print("Options:")
print(" --help Print this help information and exit")
print(" --out-dir PATH Output directory path (default: './')")
print(" --out-name NAME Output file name (default: 'files')")
print(" --no-deletion Don't delete temporary files")
print(" --force-absolute Resolve relative paths before passing them to tar")
print(" --compress-with ALGO The program to use for compression (default: gzip)")
print(" --encrypt-with ALGO The algorithm to use for encryption (default: AES256)")
print(" -@ Read paths from stdin (seperated by newlines)")
print(" -- Specifies that all following arguments are paths")
# If the user didn't specify any arguments, print help information and exit.
if len(sys.argv) == 1:
print_help()
sys.exit(ReturnCode.ARGUMENT_ERROR)
config = Configuration()
read_from_stdin = False
index = 1
while index < len(sys.argv):
argument = sys.argv[index]
index += 1
# If we ran into an argument that needs a parameter, this function ensures that a parameter
# is specified and returns it. If a parameter is not specified, the script exits.
def retrieve_parameter(index):
if len(sys.argv) < index:
print(SCRIPT_NAME + ": the '" + argument + "' option requires an argument.")
sys.exit(ReturnCode.ARGUMENT_ERROR)
return sys.argv[index]
if argument == "-h" or argument == "--help":
print_help()
sys.exit(ReturnCode.SUCCESS)
if argument == "--out-dir":
config.output_directory = pathlib.Path(retrieve_parameter(index)).resolve()
index += 1
elif argument == "--out-name":
config.output_name = retrieve_parameter(index)
index += 1
elif argument == "--no-deletion":
config.delete_temporary_files = False
elif argument == "--force-absolute":
config.enforce_absolute_paths = True
elif argument == "--compress-with":
config.compression_algorithm = retrieve_parameter(index)
index += 1
elif argument == "--encrypt-with":
config.encryption_algorithm = retrieve_parameter(index)
index += 1
elif argument == "-@":
read_from_stdin = True
elif argument == "--":
for index in range(index, len(sys.argv)):
config.paths.append(pathlib.Path(sys.argv[index]))
break
elif argument.startswith("-"):
print(SCRIPT_NAME + ": the option '" + argument + "' does not exist.")
sys.exit(ReturnCode.ARGUMENT_ERROR)
else:
config.paths.append(pathlib.Path(argument))
# If the user specified to read paths from stdin, then we interpret each line of stdin as
# being a path.
if read_from_stdin:
for line in sys.stdin:
config.paths.append(pathlib.Path(line.strip("\n")))
existing_paths = list()
nonexistent_paths = list()
# Run through each path and check that it exists.
for path in config.paths:
if path.exists():
existing_paths.append(path.resolve() if config.enforce_absolute_paths else path)
else:
nonexistent_paths.append(path)
# If one or more paths doesn't exist (or isn't valid), print them and exit.
if nonexistent_paths:
if not existing_paths:
print(SCRIPT_NAME + ": none of the specified paths seem to exist.")
sys.exit(ReturnCode.PATH_NOT_FOUND)
print(SCRIPT_NAME + ": the following paths do not seem to exist:")
for path in nonexistent_paths:
print(SCRIPT_NAME + ": " + str(path))
sys.exit(ReturnCode.PATH_NOT_FOUND)
# Also exit if there aren't any valid or existing paths.
if not existing_paths:
print(SCRIPT_NAME + ": you need to specify one or more paths.")
sys.exit(ReturnCode.ARGUMENT_ERROR)
config.paths = existing_paths
return config
# Returns a string of length `length` randomly populated with characters from `characters`.
def random_string(length = 16, characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
# This seems to be the fastest method as per https://stackoverflow.com/a/19926932
return "".join([characters[random.randrange(len(characters))] for i in range(0, length)])
# Cleans up temporary files from running this script.
def cleanup(config, tarball_path):
if config.delete_temporary_files:
try:
tarball_path.unlink(True)
except:
print(SCRIPT_NAME + ": exception occured when trying to delete temporary files.")
print(SCRIPT_NAME + ": attempted to delete: " + str(tarball_path))
print(sys.exc_info()[0])
sys.exit(ReturnCode.CLEANUP_ERROR)
# Compresses the specified files/directories into a tarball, and returns the path of that
# tarball.
def compress(config):
# Check that the specified output directory exists and is a directory. If it isn't, then
# attempt to create that directory.
if not config.output_directory.is_dir():
try:
config.output_directory.mkdir(parents=True, exists_ok=True)
except:
print(SCRIPT_NAME + ": exception occured when trying to create the output directory.")
print(SCRIPT_NAME + ": attempted to create directory: " + str(config.output_directory))
print(sys.exc_info()[0])
sys.exit(ReturnCode.CANNOT_CREATE_OUTPUT_DIRECTORY)
# We need a path to store our compressed tarball in, so we'll make 64 attempts at finding a
# random file name not in use by another file.
destination = None
attempts = 0
while attempts < 64:
destination = config.output_directory / ("tarball_" + random_string())
if not destination.exists():
break
attempts += 1
# If all those attempts fail, we assume something went wrong and just exit.
if destination.exists():
print(SCRIPT_NAME + ": could not find a valid path for temporary files.")
sys.exit(ReturnCode.CANNOT_LOCATE_PATH_FOR_TEMPORARY_FILES)
# Run tar on the specified files, using the specified compression algorithm.
print(SCRIPT_NAME + ": compressing paths...")
completed_process = subprocess.run([
"tar",
"-c",
"--use-compress-program=" + config.compression_algorithm,
"-f", str(destination)] + config.paths)
# If tar returned a non-zero exit code, we print that code to the user and exit.
if completed_process.returncode != 0:
print(SCRIPT_NAME + ": error attempting to compress paths failed with return code '" + str(completed_process.returncode) + "'.")
cleanup(config, destination)
sys.exit(ReturnCode.COMPRESSION_ERROR)
return destination
# Encrypts the tarball file with gpg using the specified encryption algorithm
def encrypt(config, tarball_path):
print(SCRIPT_NAME + ": encrypting tarball...")
completed_process = subprocess.run([
"gpg",
"--s2k-mode", "3",
"--s2k-count", "65011712",
"--s2k-digest-algo", "SHA512",
"--s2k-cipher-algo", config.encryption_algorithm,
"--output", str(config.output_directory / config.output_name),
"--symmetric", str(tarball_path)])
# If gpg returned a non-zero exit code, we print that code to the user and exit.
if completed_process.returncode != 0:
print(SCRIPT_NAME + ": error attempting to encrypt tarball failed with return code '" + str(completed_process.returncode) + "'.")
cleanup(config, tarball_path)
sys.exit(ReturnCode.ENCRYPTION_ERROR)
def main():
config = read_arguments()
tarball_path = compress(config)
encrypt(config, tarball_path)
cleanup(config, tarball_path)
if __name__ == "__main__":
main()
</code></pre>
<p>And here, as supporting code, is the script I use to invoke <code>encrypt.py</code> (not so much looking for feedback on it, but it seemed like a good idea to include just for completeness):</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
cd "$(dirname "$0")";
prefix="Backup_";
datestr=$(date +%Y-%m-%d);
suffix="";
extension=".tar.bz2.gpg"
for id in {a..z};
do :
suffix=$id;
if [ ! -f "$prefix$datestr$suffix$extension" ];
then
break;
fi
if [ "$id" == "z" ];
then
printf "backup.sh: too many existing backups!\n";
exit 1;
fi
done
printf "backup.sh: creating archive...\n";
files=$(
ls |
grep -v "^Backup_[[:digit:]]\{4\}-[[:digit:]]\{2\}-[[:digit:]]\{2\}[[:lower:]]$extension$" |
grep -v "^tarball_[[:alnum:]]\{16\}$");
printf "$files" | python3 encrypt.py \
--out-name "$prefix$datestr$suffix$extension" \
--force-absolute \
--compress-with pbzip2 \
-@;
code=$?
if [ $code != 0 ];
then
printf "backup.sh: encrypt.py failed with exit code $code\n";
else
printf "backup.sh: done!\n";
fi
</code></pre>
<p>Much appreciated!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T05:11:58.150",
"Id": "263611",
"Score": "1",
"Tags": [
"beginner",
"python-3.x",
"encryption"
],
"Title": "Python script to compress and encrypt a list of files/directories (tar + gpg)"
}
|
263611
|
<p>I need to update a multidimensional array by same key paths of a multidimensional array.</p>
<p>I think my code can be better condensed :</p>
<pre class="lang-php prettyprint-override"><code>//source
$array = [
"hero" => [
"name" => "Peter",
"job" => "Spider Man"
],
"dog" => [
"age" => 5,
"toys" => [
"first" => "bone",
"second" => "ball"
]
]
];
//values to update
$toUpdate = [
"hero" => [
"name" => "Peter Parker",
"age" => 26
],
"dog" => [
"name" => "Rex",
"toys" => [
"second" => "frisbee"
]
]
];
$paths = nested_values($toUpdate);
foreach ($paths as $path => $value) {
$arr = &$array;
$parts = explode('/', $path);
foreach($parts as $key){
$arr = &$arr[$key];
}
$arr = $value;
}
function nested_values ($array, $path="") {
$output = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$output = array_merge($output, nested_values($value, (!empty($path)) ? $path.$key."/" : $key."/"));
}
else $output[$path.$key] = $value;
}
return $output;
}
var_dump($array);
/*
(array) [2 elements]
hero:
(array) [3 elements]
name: (string) "Peter Parker"
job: (string) "Spider Man"
age: (integer) 26
dog:
(array) [3 elements]
age: (integer) 5
toys:
(array) [2 elements]
first: (string) "bone"
second: (string) "frisbee"
name: (string) "Rex"
*/
</code></pre>
|
[] |
[
{
"body": "<p>...wait a sec, am I sitting a job interview?</p>\n<p>Yes, we have a native function for this.</p>\n<p>Because your array structure is completely associative, <code>array_replace_recursive()</code> is reliable, concise, and self-documenting.</p>\n<p>Code: (<a href=\"https://3v4l.org/nXa56\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>var_export(array_replace_recursive($array, $toUpdate));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T21:49:51.213",
"Id": "520519",
"Score": "0",
"body": "I need to perform my google search ^^ Thanks !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T13:36:59.263",
"Id": "263631",
"ParentId": "263617",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263631",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T07:41:53.393",
"Id": "263617",
"Score": "1",
"Tags": [
"php",
"array"
],
"Title": "PHP update multidimensional array values from same path multidmensional array"
}
|
263617
|
<p>I am given a CSV file of stations, with data like this:</p>
<pre><code>station_id,date,temperature_c
68,2000.375,10.500
68,2000.542,5.400
68,2000.958,23.000
68,2001.125,20.400
68,2001.292,13.300
68,2001.375,10.400
68,2001.958,21.800
68,2002.208,15.500
</code></pre>
<p>and so on for many different <code>station_id</code>s.</p>
<p>Then I want to create a Python program that (1) gives the minimum reading (the third column) and (2) the station with the maximum "travel distance" with its readings. Thus if a station has 3 readings of -5,0,8 then that would mean a travel distance of 13. This can take an optional date range. Here is what I did.</p>
<pre><code>#!/usr/bin/python
from collections import defaultdict
import csv
import random
import sys
# In order to track each station's statistics, we'll create a Station class
# to hold the data on a per-station basis.
class Station:
def __init__(self):
self.readings = []
self.minimum = 99999999.0
self.travel = 0
# travel holds the change in temperature reading-by-reading
def get_travel(self):
return self.travel
def set_travel(self, n):
self.travel += abs(n)
# getter & setter for station minimums
def get_minimum(self):
return self.minimum
def set_minimum(self, n):
self.minimum = n
# infrastructure for future code expansion
def get_readings(self):
return self.readings
def set_readings(self, date, temp):
self.readings.append({ "date" : date, "temp" : temp})
"""
Reporter class handles a list of Stations
"""
class Reporter:
def __init__(self):
# stations dict with entries for holding the specified stats.
self.stations = defaultdict(Station)
self.global_minimum = { "station" : "default", "date" : 1, "temp" : 9999999 }
self.longest_travel = { "station" : "default", "range" : 0 }
"""
Determines which station recorded the coldest temperature
args: CSV file
returns: dict with data
"""
def minimum_temperature(self, filename):
with open(filename, 'r') as datafile:
try:
csv_reader = csv.reader(datafile)
next(csv_reader)
# reading line-by-line since CSV could be a big file
for row in csv_reader:
station, date, temp = row
# save the station's readings
self.stations[station].set_readings(date, temp)
temp = float(temp)
if (temp < self.stations[station].get_minimum()):
self.stations[station].set_minimum(temp)
if(temp < self.global_minimum["temp"]):
self.global_minimum = { "station" : station, "temp" : temp, "date" : date }
# The specs state that in the event that a tie occurs simply return
# one pair at random.
if (temp == self.global_minimum["temp"]):
if (random.randint(1,100) % 2 == 0):
self.global_minimum = { "station" : station, "date" : date, "temp" : temp }
except csv.Error as e:
sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
return self.global_minimum
"""
Determines which station "traveled" the most
args: CSV file, begin date (optional), end date (optional)
returns: dict with data
"""
def max_travel(self,filename,begin=1.0,end=9999.9):
with open(filename, 'r') as datafile:
try:
csv_reader = csv.reader(datafile)
next(csv_reader)
# reading line-by-line since CSV could be a big file
for row in csv_reader:
station, date, temp = row
# save for future expansion
self.stations[station].set_readings(date, temp)
date = float(date)
if date > begin and date < end:
temp = float(temp)
self.stations[station].set_travel(temp)
travel = self.stations[station].get_travel()
if ( travel > self.longest_travel["range"]):
self.longest_travel = { "station" : station, "range" : travel }
except csv.Error as e:
sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
return self.longest_travel
if __name__ == "__main__":
csv_file = sys.argv[1]
# fetch lowest temperature
reporter = Reporter()
global_minimum = reporter.minimum_temperature(csv_file)
print("station {} had the global minimum on {}".format(global_minimum["station"], global_minimum["date"]))
# fetch maximum travel overall
longest_travel = reporter.max_travel(csv_file)
print("station {} had the greatest travel at {}".format(longest_travel["station"], longest_travel["range"]))
# now try a date range
reporter2 = Reporter()
begin = 2001.0
end = 2006.0
longest_travel = reporter2.max_travel(csv_file,begin,end)
print("for {} to {}, station {} had the greatest travel at {}".format(begin, end, longest_travel["station"], longest_travel["range"]))
</code></pre>
<p>I'm particularly interested in speeding it up and memory usage but also how to Pythonically deal with with getters/setters.</p>
|
[] |
[
{
"body": "<h1>Getters and Setters</h1>\n<p>If you are to use this pattern, the <code>@property</code> decorator will accomplish this in a more pythonic way:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Station:\n def __init__(self):\n self.readings = []\n self._minimum = 99999999.0\n self._travel = 0\n\n\n @property\n def minimum(self, value):\n return self._minimum\n\n\n @minimum.setter\n def minimum(self, value):\n self._minimum = value\n\n\n @property\n def travel(self, value):\n return self._travel\n\n\n @travel.setter\n def travel(self, value):\n self._travel = abs(value)\n\n\n def add_reading(self, date, temp):\n self.readings.append({ "date" : date, "temp" : temp})\n\n\n# access the elements this way\nstation = Station()\nprint(station.travel)\n0\n\nstation.travel += 1\nprint(station.travel)\n1\n</code></pre>\n<p>However, the setter pattern doesn't really make sense for your <code>readings</code>, because you aren't really setting, you're appending. So keep a function that appends a reading to the readings list, it's more explicit this way. I wouldn't expect:</p>\n<pre class=\"lang-py prettyprint-override\"><code>station.readings = ('date', 'reading')\n</code></pre>\n<p>to do anything other than set the attribute, but it actually has a surprising side-effect.</p>\n<h1>Spacing</h1>\n<p>Your indentation should be four spaces, not two.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T17:57:19.770",
"Id": "263637",
"ParentId": "263618",
"Score": "1"
}
},
{
"body": "<ul>\n<li>Probably a typo in your <code>except</code> clauses; I suspect it's supposed to say <code>csv_reader.line_num</code>.</li>\n<li>What is going on with the "travel"? What you've actually written is "sum of absolute values", but I assume what you actually want is <em>either</em> "max minus min" <em>or</em> "sum of day-to-day deltas".</li>\n<li>My opinion is that getters/setters/properties are inherently un-pythonic. More importantly, they're <em>opaque</em>. They look like attributes but they're functions that can have side-effects. Don't hide the possibility of side-effects from the audience; <em>do</em> just use an actual attribute wwh</li>\n<li>I like the <code>DictReader</code> provided by the <code>csv</code> module. It's not <em>everything</em> we might ask for, but it'll save us accidentally handling malformed data.</li>\n<li>You're doing a lot of work to handle the file in a stream, but you're also reading the file multiple times and you're keeping all the data in memory once it's read.\n<ul>\n<li>This could get buggy. For example, in your <code>main</code>, you re-use <code>reporter</code> for the second pass, which means it will contain every datapoint <em>in duplicate</em>.</li>\n<li>You should pick one: Either get everything you want in a single pass, or read all the data into an appropriate structure and run queries on that. Since you specify speed and memory usage as concerns, I'll assume you want the first choice (but I suspect that's the wrong decision).</li>\n</ul>\n</li>\n<li>You probably don't need a <code>Reporter</code> class at all. It's not helping you manage any state (that you want to keep) across functions, so just declare your functions in the top namespace.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T11:38:21.747",
"Id": "263661",
"ParentId": "263618",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T07:53:09.923",
"Id": "263618",
"Score": "1",
"Tags": [
"python",
"csv"
],
"Title": "Python script for parsing and using CSV data"
}
|
263618
|
<p>This is a problem of a past <a href="https://stepik.org/lesson/541850/step/2?unit=535311" rel="nofollow noreferrer">bioinformatic contest</a> (requires an account). My solution works but is too slow for some test cases.</p>
<h3>Input format</h3>
<p>The first line of the input contains one integer <span class="math-container">\$T\$</span>, <span class="math-container">\$(1 \leq T \leq 3)\$</span> the number of test cases. Each test case is specified by four lines.</p>
<p>The first line of each test case contains three integer numbers <span class="math-container">\$M\$</span>, <span class="math-container">\$K\$</span>, <span class="math-container">\$N\$</span>.</p>
<p>The second line contains <span class="math-container">\$M\$</span> numbers <span class="math-container">\$m_i\$</span> − masses of metabolites <span class="math-container">\$(0 < m_i\le 1000)\$</span>.</p>
<p>The third line contains <span class="math-container">\$K\$</span> numbers <span class="math-container">\$a_i\$</span> − masses of adducts <span class="math-container">\$(-1000 \le a_i \le 1000)\$</span>.</p>
<p>The fourth line contains <span class="math-container">\$N\$</span> numbers <span class="math-container">\$s_i\$</span> − masses of signals <span class="math-container">\$(0 < s_i\le 1000)\$</span>.</p>
<p>All the masses are indicated with exactly six decimal places.</p>
<h2>Output format</h2>
<p>For each signal <span class="math-container">\$s_i\$</span> of each test case, print numbers <span class="math-container">\$j\$</span> and <span class="math-container">\$k\$</span> such that <span class="math-container">\$s_i = m_j+a_k+\Delta\$</span>, <span class="math-container">\$m_j+a_k > 0\$</span> and the absolute value of <span class="math-container">\$\Delta\$</span> is smallest possible. If there are multiple numbers <span class="math-container">\$j\$</span> and <span class="math-container">\$k\$</span> with same absolute value of <span class="math-container">\$\Delta\$</span> for some signal, you can print any of them.</p>
<h3>Sample input</h3>
<pre><code>3
2 2 5
1.000002 0.000002
0.500000 -0.500000
0.500001 0.500002 0.500003 1.000000 0.000001
2 2 5
1.000002 0.000001
0.500000 -0.500000
0.500001 0.500002 0.500003 1.000000 0.000001
5 4 7
0.000001 0.000002 0.000003 0.000004 0.000005
0.000002 0.000010 0.000001 -0.000001
0.000001 0.000002 0.000100 0.000005 0.000020 0.000010 0.000003
</code></pre>
<h3>Sample output</h3>
<pre><code>1 2
1 2
1 2
1 2
1 2
2 1
1 2
1 2
1 2
2 1
2 4
1 3
5 2
3 1
5 2
1 2
1 1
</code></pre>
<h3>Test cases</h3>
<p><a href="https://stepik.org/media/attachments/lesson/541850/1.txt" rel="nofollow noreferrer">1.txt</a>: <span class="math-container">\$M,K,N≤10\$</span><br />
<a href="https://stepik.org/media/attachments/lesson/541850/3.zip" rel="nofollow noreferrer">3.zip</a>: <span class="math-container">\$M,K≤1000;N≤10^5\$</span><br />
<a href="https://stepik.org/media/attachments/lesson/541850/4.zip" rel="nofollow noreferrer">4.zip</a>: <span class="math-container">\$M≤10^6;K,N≤1000\$</span><br />
<a href="https://stepik.org/media/attachments/lesson/541850/5.zip" rel="nofollow noreferrer">5.zip</a>: <span class="math-container">\$M,K,N≤10^4\$</span><br />
<a href="https://stepik.org/media/attachments/lesson/541850/answers.zip" rel="nofollow noreferrer">answers.zip</a>: to test the solution</p>
<h3>Code</h3>
<pre class="lang-py prettyprint-override"><code>from bisect import bisect_left
from time import perf_counter as pc
# Find in arr the closest number to n
def take_closest(arr, n):
pos = bisect_left(arr, n)
if pos == 0:
return arr[0]
if pos == len(arr):
return arr[-1]
before = arr[pos - 1]
after = arr[pos]
if after - n < n - before:
return after
else:
return before
def solve(masses, adducts, signals):
totals = {}
for i, m in enumerate(masses):
for j, a in enumerate(adducts):
ma = m + a
if ma > 0:
totals[ma] = (i + 1, j + 1)
skeys = sorted(totals.keys())
for s in signals:
closest = take_closest(skeys, s)
yield totals[closest]
if __name__ == "__main__":
test_num = 3
of = open(f"out{test_num}.txt", "w")
with open(f"{test_num}.txt", "r") as f:
t0 = pc()
t = int(f.readline())
for _ in range(t):
M, K, N = map(int, f.readline().strip().split())
masses = list(map(float, f.readline().strip().split()))
adducts = list(map(float, f.readline().strip().split()))
signals = list(map(float, f.readline().strip().split()))
for j, k in solve(masses, adducts, signals):
of.write(f'{j} {k}\n')
t1 = pc()
print(f"Runtime: {round(t1-t0,3)} s")
of.close()
</code></pre>
<p><strong>Algorithm</strong>:</p>
<ol>
<li>Store all sums <span class="math-container">\$m_i + a_j\$</span> in a dictionary with indices <span class="math-container">\$i,j\$</span> as values.</li>
<li>Sort <code>signals</code></li>
<li>For each signal, find the closest number among the sorted keys of the dictionary using binary search.</li>
</ol>
<p><strong>Issues</strong>:</p>
<p>The solution works but is too slow for test case 4, while test case 5 takes around 10 minutes on my machine.</p>
<p>Any feedback is appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T09:50:28.307",
"Id": "520465",
"Score": "0",
"body": "You can avoid creating a dict+sorted list: \n1. Sort adducts. \n2. For each signal[i]-mass[j] look for (bisect) adduct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T10:32:30.300",
"Id": "520469",
"Score": "0",
"body": "@PavloSlavynskyy Thanks, I'll try your idea but at the moment I am not sure if that will be enough. `masses` would need to be scanned for each signal, and `M` is kind of large in test case 4. Feel free to post an answer, will help me to understand better your idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T10:45:17.717",
"Id": "520470",
"Score": "0",
"body": "Sorry, this is code_review, not write_my_code. But i've tested the idea - it's under 2 minutes for test case 5 on my i5-7500."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T11:07:42.060",
"Id": "520472",
"Score": "0",
"body": "@PavloSlavynskyy I wasn't asking for code, but for a more formal answer. Comments should be for clarifications as far as I know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T17:22:10.510",
"Id": "520506",
"Score": "0",
"body": "The only technological constraint I can see on the problem page is \"using programming\". Does it stipulate Python?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T01:21:35.977",
"Id": "520530",
"Score": "0",
"body": "@Reinderien this contest has no restrictions on programming languages. The answer is submitted as a text file, which could be written even manually for simple test cases."
}
] |
[
{
"body": "<p>The complexity of your algorithm is:</p>\n<p>Creating a dict of values: <span class=\"math-container\">\\$O(MNlog(MN))\\$</span> (Loops for M and for N, log for adding into dict).</p>\n<p>Sorting keys: <span class=\"math-container\">\\$O(MNlog(MN))\\$</span> (sorting a list of the size MN)</p>\n<p>Looking up: <span class=\"math-container\">\\$O(Klog(MN))\\$</span> (because we do K lookups among an MN-sized list).</p>\n<p>Total will be <span class=\"math-container\">\\$O((MN+K)log(MN))\\$</span>, for the case <span class=\"math-container\">\\$N=M=K\\$</span> it will be <span class=\"math-container\">\\$O(N^2log(N^2))\\$</span>, not great, not terrible.</p>\n<p><span class=\"math-container\">\\$\\Delta\\$</span> is represented as an expression for 3 variables; to search for minimum (with log complexity), we still need to fix two other variables, which gives us <span class=\"math-container\">\\$O(N^2log(N))\\$</span> - this is slightly better, but I think worth a try. The question is what variables should we loop over, and what to use for bisection search. The task is to find for every signal - so, we should have a loop over it. So the idea is something like this:</p>\n<pre><code>adducts_dict = {adducts[k]:k for k in range(len(adducts))}\nadducts = sorted(adducts)\nfor s in signals:\n for j, m in enumerate(masses):\n #bisect find minimal distance from s-m to adduct; save that adduct and j\n yield (closest_j, adducts_dict[closest_adduct])\n</code></pre>\n<p>The complexity here will be: <span class=\"math-container\">\\$O(Klog(K) + Klog(K)+N(Mlog(K)+log(K))) = O((MN+K)log(K)\\$</span>. Slightly better.</p>\n<p>One thing more: adducts and masses can be treated equally in the expression for <span class=\"math-container\">\\$\\Delta\\$</span> and swapped; this will give us <span class=\"math-container\">\\$O((KN+M)log(M))\\$</span>. It looks like it will be good to keep greatest of (M,N) added, not multiplied, so for the test case 4 you should sort and bisect search masses, not adducts (just swap the arrays and resulting pairs).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T12:40:45.380",
"Id": "263627",
"ParentId": "263620",
"Score": "2"
}
},
{
"body": "<p>A minor addition: the "sample" test case is ambiguous. Consider:</p>\n<p><span class=\"math-container\">$$s = 0.500,001$$</span>\n<span class=\"math-container\">$$s - 1.000,002 - (-0.5) = \n s - 0.000,002 - 0.5 = -0.000,001\n$$</span></p>\n<p>With synthesized tests you don't want to allow for nondeterministic behaviour. Better to choose inputs that unambiguously point toward one correct answer.</p>\n<h2>LP: Don't do this</h2>\n<p>It's possible (though not advisable) to reframe your implementation as a mixed-integer linear programming problem where:</p>\n<ul>\n<li>the structural variables are binary selection coefficients into the metabolite and adduct vectors</li>\n<li>there are three auxiliary variables: to minimize the objective, and one for each of metabolite and adduct to enforce exactly one choice</li>\n<li>since an abs needs to be applied, it requires two passes per value of <code>s</code></li>\n</ul>\n<p>This works(ish) but is very slow.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <assert.h>\n#include <limits.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <glpk.h>\n\n\n#define VERBOSE 1\n\nconst double epsilon = 1e-10;\n \n\nstatic void fatal(const char *msg) {\n fprintf(stderr, "%s\\n", msg);\n exit(1);\n}\n\n\nstatic void pfatal(const char *msg) {\n perror(msg);\n exit(1);\n}\n\n\nstatic void usage(const char *cmd) {\n fprintf(stderr, "Usage: %s problem-number [...]\\n", cmd);\n exit(1);\n}\n\n\nstatic void open_files(int i_problem, FILE **file_in, FILE **file_ans) {\n char filename_in[NAME_MAX], filename_ans[NAME_MAX];\n \n snprintf(filename_in, NAME_MAX, "%d.txt", i_problem);\n *file_in = fopen(filename_in, "r");\n if (!*file_in) \n pfatal("Failed to open input file");\n \n snprintf(filename_ans, NAME_MAX, "ans%d.txt", i_problem);\n *file_ans = fopen(filename_ans, "r");\n if (!*file_ans) \n pfatal("Failed to open output file");\n}\n\n\nstatic void read_line(FILE *file, char *line, int n) {\n if (!fgets(line, n, file))\n pfatal("Input I/O");\n \n if (line[strlen(line) - 1] != '\\n')\n fatal("Input line too long");\n}\n\n\nstatic void read_ints(FILE *file, int *array, int n) {\n const int field_chars = 12, buf_size = n*field_chars;\n char *line = malloc(buf_size);\n if (!line)\n pfatal("No memory for line");\n read_line(file, line, buf_size);\n \n const char *field = line;\n for (int i = 0; i < n; i++) {\n int consumed;\n if (sscanf(field, "%d%n", array + i, &consumed) != 1)\n pfatal("Bad input");\n field += consumed;\n }\n \n free(line);\n}\n\n\nstatic double *read_doubles(FILE *file, int n) {\n const int field_chars = 12, buf_size = n*field_chars;\n char *line = malloc(buf_size);\n if (!line)\n pfatal("No memory for line");\n read_line(file, line, buf_size);\n \n double *array = malloc(n * sizeof(double));\n if (!array)\n pfatal("No memory for input");\n \n const char *field = line;\n for (int i = 0; i < n-1; i++) {\n int consumed;\n if (sscanf(field, "%lf%n", array + i, &consumed) != 1)\n pfatal("Bad input");\n field += consumed;\n }\n \n free(line);\n return array;\n}\n\n\nstatic void read_case(\n FILE *file_in, \n int *M, int *K, int *N,\n double **m, double **a, double **s\n) {\n char line[256];\n read_line(file_in, line, sizeof(line));\n if (sscanf(line, "%d %d %d\\n", M, K, N) != 3)\n fatal("Incorrect test case header format");\n \n printf("M=%d K=%d N=%d ", *M, *K, *N);\n #if VERBOSE\n putchar('\\n');\n #endif\n fflush(stdout);\n \n if (*M < 1) fatal("Out-of-range M");\n if (*K < 1) fatal("Out-of-range K");\n if (*N < 1) fatal("Out-of-range N");\n \n *m = read_doubles(file_in, *M), // metabolites\n *a = read_doubles(file_in, *K), // adducts\n *s = read_doubles(file_in, *N); // signals\n}\n\n\n/*\nFor each given s, choose one m and one a to minimize |s - m - a|.\nShow the indices in m and a.\n\nIn GLPK terms,\n x[:M+K]: structural "col" variables, the actual selection coefficients\n x'[:3]: auxiliary "row" variables, to constrain the solution\n z: objective, should approach s\n c: objective coefficients, equal to m and a concatenated\n A: constraint coefficients, three constraint rows, one col for each m,a\n l, u: lower and upper bounds\n \n c\nz = [m m a a a][x]\n [x]\n [x]\n [x]\n [x]\n\n A\n[x'] [m m a a a][x]\n[x'] = [1 1 0 0 0][x]\n[x'] [0 0 1 1 1][x]\n [x]\n [x]\n \nMin|maximize z = cx subject to x' = Ax, l <= x <= u, l' <= x' <= u'\nSynthesizing "minimize abs(s - m - a)" translates to:\n - Maximize m+a subject to m+a <= s\n - Minimize m+a subject to m+a >= s\n - Take whichever solution is closer to s\n*/\n\n\nstatic glp_prob *make_prob(\n int i_problem, int i_test, \n int M, int K, const double *m, const double *a\n) {\n glp_term_out(GLP_OFF);\n glp_prob *lp = glp_create_prob();\n char name[64];\n snprintf(name, sizeof(name), "stepik-bioinfo-2021-%d.%d", i_problem, i_test);\n glp_set_prob_name(lp, name);\n glp_set_obj_name(lp, "m+a");\n \n // auxiliary "row" variables:\n // 0: tracking the objective function, to enforce minimum or maximum\n // 1: metabolite selection sum equal to 1\n // 2: adduct selection sum equal to 1\n glp_add_rows(lp, 3);\n glp_set_row_name(lp, 1, "objective_limit");\n glp_set_row_name(lp, 2, "fixed_sum_metabolite");\n glp_set_row_name(lp, 3, "fixed_sum_adduct");\n // set_row_bnds(lp, 1) deferred to the min/max step\n glp_set_row_bnds(lp, 2, GLP_FX, 1, 1);\n glp_set_row_bnds(lp, 3, GLP_FX, 1, 1);\n \n // structural "column" variables, M+K selection vector of metabolites and \n // adducts in [0, 1]\n glp_add_cols(lp, M + K);\n \n // The glpk array convention is dumb and 1-indexed, meaning every input\n // array needs a dummy prefix\n const int row_ind[4] = {INT_MIN, 1, 2, 3};\n \n char col_name[16];\n \n // Metabolites\n for (int i = 0; i < M; i++) {\n snprintf(col_name, sizeof(col_name), "m_%d", i+1);\n glp_set_col_name(lp, i+1, col_name);\n glp_set_col_kind(lp, i+1, GLP_BV);\n // implied: glp_set_col_bnds(lp, i+1, GLP_DB, 0, 1);\n glp_set_obj_coef(lp, i+1, m[i]);\n double constraints[4] = {NAN, m[i], 1, 0};\n glp_set_mat_col(lp, i+1, 3, row_ind, constraints);\n }\n \n // Adducts\n for (int i = 0; i < K; i++) {\n snprintf(col_name, sizeof(col_name), "a_%d", i+1);\n glp_set_col_name(lp, i+M+1, col_name);\n glp_set_col_kind(lp, i+M+1, GLP_BV);\n // implied: glp_set_col_bnds(lp, i+M+1, GLP_DB, 0, 1);\n glp_set_obj_coef(lp, i+M+1, a[i]);\n double constraints[4] = {NAN, a[i], 0, 1};\n glp_set_mat_col(lp, i+M+1, 3, row_ind, constraints);\n }\n \n return lp;\n}\n\n\nstatic int find_selected(glp_prob *lp, int n, int offset) {\n for (int i = 0; i < n; i++) {\n if (glp_mip_col_val(lp, i + offset + 1) > 0.5)\n return i;\n }\n fatal("Selected index not found");\n} \n\n\nstatic double optimize(\n glp_prob *lp, int direction, int i_s, double s,\n const double *m, const double *a,\n int M, int K, int *j_max, int *k_max\n) {\n const char *dir_str = direction == GLP_MIN ? "min" : "max";\n #if VERBOSE\n printf(" [%d] %s ", i_s, dir_str);\n #endif\n \n // Reset between optimization runs\n // glp_std_basis(lp);\n \n glp_set_obj_dir(lp, direction);\n int bound = direction == GLP_MIN ? GLP_LO : GLP_UP;\n glp_set_row_bnds(lp, 1, bound, s, s);\n \n int err = glp_simplex(lp, NULL);\n if (err) glp_error("GLPK simplex failure %d\\n", err);\n int stat = glp_get_status(lp);\n if (stat == GLP_OPT) {\n err = glp_intopt(lp, NULL);\n if (err) glp_error("GLPK MIP failure %d\\n", err);\n stat = glp_mip_status(lp);\n }\n \n if (stat != GLP_OPT) {\n #if VERBOSE\n printf("%lf: infeasible\\n", s);\n #endif\n return INFINITY;\n }\n \n double obj = glp_mip_obj_val(lp);\n #if VERBOSE\n if (direction == GLP_MIN) printf("%.2le <- %.2le ", s, obj);\n else printf("%.2le -> %.2le ", obj, s);\n #endif\n \n *j_max = find_selected(lp, M, 0);\n *k_max = find_selected(lp, K, M);\n \n double error = fabs(obj - s);\n #if VERBOSE\n printf(\n "j=%d k=%2d err=%.1le act_err=%+.1le\\n",\n *j_max+1, *k_max+1, error,\n s - m[*j_max] - a[*k_max]\n );\n #endif\n return error;\n}\n\n\nstatic void test_case(int i_problem, int i_test, FILE *file_in, FILE *file_ans) {\n printf("problem %d.%d ", i_problem, i_test);\n int M, K, N;\n double *m, *a, *s;\n read_case(file_in, &M, &K, &N, &m, &a, &s);\n \n glp_prob *lp = make_prob(i_problem, i_test, M, K, m, a);\n \n int matches = 0;\n \n int expected[2];\n \n for (int i_s = 0; i_s < N; i_s++) {\n int j = -1, k = -1;\n // Minimize m+a subject to m+a >= s\n double error = optimize(lp, GLP_MIN, i_s, s[i_s], m, a, M, K, &j, &k);\n \n if (error > epsilon) {\n int j1 = -1, k1 = -1;\n // Maximize m+a subject to m+a <= s\n double error1 = optimize(lp, GLP_MAX, i_s, s[i_s], m, a, M, K, &j1, &k1);\n \n if (error > error1) {\n error = error1;\n j = j1; k = k1;\n }\n }\n \n if (j < 0 || k < 0) fatal("No solution");\n \n read_ints(file_ans, expected, 2);\n #if VERBOSE\n printf(" Act %2d %2d exp %2d %2d\\n", j+1, k+1, expected[0], expected[1]);\n #endif\n if (j+1 == expected[0] && k+1 == expected[1])\n matches++;\n }\n \n glp_delete_prob(lp);\n free(m); free(a); free(s);\n \n printf(" matched %d/%d\\n", matches, N); \n}\n\nint main(int argc, const char **argv) {\n if (argc < 2) usage(*argv);\n \n printf("Using glpk %s\\n", glp_version());\n \n for (int a = 1; a < argc; a++) {\n FILE *file_in, *file_ans;\n int i_problem;\n if (sscanf(argv[a], "%d", &i_problem) != 1)\n usage(*argv);\n \n open_files(i_problem, &file_in, &file_ans);\n \n int T;\n if (fscanf(file_in, "%d\\n", &T) != 1) fatal("Bad test count");\n if (T < 1 || T > 3) fatal("Out-of-range test count");\n \n for (int i_test = 0; i_test < T; i_test++) {\n test_case(i_problem, i_test, file_in, file_ans);\n }\n }\n \n return 0;\n}\n</code></pre>\n<h2>Numpy vectorization</h2>\n<p>It's possible to use something vaguely close to your original implementation but using all numpy and no loops. This works-ish for problems 1.1, 2.2 and almost everything in 3.2 but</p>\n<ul>\n<li>there's a few stray mismatches in 3.2;</li>\n<li>I wasn't careful enough with memory so problem 4.1 dies from OOM - this could be fixed by switching to a KN lookup instead of an MK lookup; and</li>\n<li>Problems 2.1 and 3.1 are totally wrong for some reason;</li>\n</ul>\n<p>but it's still possible as a proof-of-concept to demonstrate how you would take your algorithm and vectorize it.</p>\n<pre><code>from sys import argv\n\nimport numpy as np\n\n\ndef solve_case(m: np.ndarray, a: np.ndarray, s: np.ndarray) -> np.ndarray:\n mrep = np.tile(m, len(a))\n jrep = np.tile(np.arange(len(m), dtype=np.int32), len(a))\n arep = np.repeat(a, len(m))\n krep = np.repeat(np.arange(len(a), dtype=np.int32), len(m))\n jk = np.vstack((jrep, krep))\n\n masum = mrep + arep\n order = masum.argsort()\n jk[:] = jk[:, order]\n masum[:] = masum[order]\n\n i = np.searchsorted(masum, s)\n lower = np.abs(s - masum[i - 1])\n upper = np.abs(s - masum[i])\n adj = lower < upper\n res = jk[:, i - adj]\n return res.T + 1\n\n\ndef solve(i_problem: int) -> None:\n with open(f'{i_problem}.txt') as file_in, \\\n open(f'ans{i_problem}.txt') as file_ans:\n T = int(next(file_in))\n\n for i_case in range(1, T + 1):\n M, K, N = (int(x) for x in next(file_in).split())\n print(f'problem {i_problem}.{i_case}: M={M} K={K} N={N}', end=' ')\n\n m, a, s = (\n np.genfromtxt(file_in, dtype=np.float64, max_rows=1)\n for _ in range(3)\n )\n assert m.shape == (M,)\n assert a.shape == (K,)\n assert s.shape == (N,)\n\n actual = solve_case(m, a, s)\n expected = np.genfromtxt(file_ans, dtype=np.int32, max_rows=N)\n matched = np.sum(actual == expected) / actual.size\n print(f'{matched:.2%} matched')\n\n\ndef main() -> None:\n for arg in argv[1:]:\n solve(int(arg))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T05:41:28.397",
"Id": "520709",
"Score": "0",
"body": "The test case in the question is actually the \"sample test\" provided by the contest. I agree that it is not the best test case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T01:45:02.190",
"Id": "263710",
"ParentId": "263620",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263627",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T08:04:58.837",
"Id": "263620",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"time-limit-exceeded"
],
"Title": "Finding pair of numbers that minimize a function"
}
|
263620
|
<h2>Background</h2>
<p>I am devising a simple file format to store some (possibly large) binary data together with some metadata that specifies how the data was generated:</p>
<pre><code><HEADER | 4 bytes> (specifies 'size' of METADATA)
<METADATA | 'size' bytes>
<DATA>
</code></pre>
<p>The use case is that if at some later point I just want to inspect the metadata (i.e. without touching the actual data), then I won't read the entire structure, but only the <code><METADATA></code> part (of known size).</p>
<p>I implemented the following class to facilitate working with such files. It behaves similarly to a singleton, loads metadata or data when first requested, then holds the reference to them during the entire lifespan of the class.</p>
<p>I am planning to use <a href="https://hypothesis.readthedocs.io/en/latest/" rel="nofollow noreferrer"><code>hypothesis</code></a> for testing (generating random data of various types).</p>
<h2>Code</h2>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pickle
from pathlib import Path
from typing import Any, Union
class MyFile:
HEADER_SIZE_BYTES = 4
def __init__(self, filename: Union[str, Path]):
self.filename = filename
self.__metadata = None
self.__data = None
with open(filename, 'rb') as fp:
self.metadata_size = int.from_bytes(fp.read(self.HEADER_SIZE_BYTES), "little")
def get_metadata(self) -> Any:
if self.__metadata is None:
with open(self.filename, "rb") as fp:
fp.seek(self.HEADER_SIZE_BYTES, 1)
self.__metadata = pickle.loads(fp.read(self.metadata_size))
return self.__metadata
def set_metadata(self, metadata: Any) -> None:
self.__metadata = metadata
def get_data(self) -> Any:
if self.__data is None:
with open(self.filename, "rb") as fp:
fp.seek(self.HEADER_SIZE_BYTES + self.metadata_size, 1)
self.__data = pickle.loads(fp.read())
return self.__data
def set_data(self, data: Any) -> None:
self.__data = data
def write_all(self) -> None:
if self.__metadata is None:
raise ValueError("No metadata to write!")
if self.__data is None:
raise ValueError("No data to write!")
metadata_bytes = pickle.dumps(self.__metadata)
data_bytes = pickle.dumps(self.__data)
header_bytes = len(metadata_bytes).to_bytes(self.HEADER_SIZE_BYTES, "little")
with open(self.filename, 'wb') as fp:
fp.write(header_bytes)
fp.write(metadata_bytes)
fp.write(data_bytes)
if __name__ == "__main__":
f = MyFile("out.epkl")
meta_w = {
"foo": "bar",
"baz": [1, 2, 3],
}
data_w = np.random.rand(3, 10, 10)
f.set_metadata(meta_w)
f.set_data(data_w)
f.write_all()
g = MyFile("out.epkl")
meta_r = g.get_metadata()
data_r = g.get_data()
assert meta_r == meta_w
assert np.allclose(data_r, data_w)
</code></pre>
<h2>Comments</h2>
<p>What are the crucial aspects that you, as a user of this library, would require from it?</p>
<p>I feel like things can be improved: there's some duplicated code, and possibly some edge-cases that I did not consider.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T14:12:06.763",
"Id": "520499",
"Score": "0",
"body": "I updated the code with the possibility to write to files. I am thinking that maybe I can specify the opening mode: `r`, `w`, `rw`, or even append, and have some sort of \"standard\" interface."
}
] |
[
{
"body": "<ul>\n<li>It's not necessary to represent this as a class; a read and write function will suffice</li>\n<li>Don't use double-underscores; that's reserved for name mangling</li>\n<li>The second argument of <code>Union[str, Path]</code> is more generically expressed as <code>os.PathLike</code></li>\n<li>Pickled objects are already length-aware. The much easier approach than what you've shown here is to omit any manual length information, and simply do two sequential serialization calls to pickle.</li>\n<li>Particularly since you're using pickle and not e.g. JSON, there is no excuse to have poorly-typed data. Replace your dictionary with <code>dataclass</code> or similar.</li>\n</ul>\n<p>The following suggested code represents the write operation as a naive method assuming both metadata and body are already in memory; and read as an iterator that yields them one at a time. Drop the logging if you don't need it; it's more to demonstrate successful operation than anything else.</p>\n<pre><code>import logging\nimport pickle\nfrom dataclasses import dataclass\nfrom os import PathLike\nfrom sys import stdout\nfrom typing import Iterable, Union, List\n\n\nimport numpy as np\n\nlogger = logging.getLogger('pickling_experments')\n\n\n@dataclass\nclass Metadata:\n foo: str\n baz: List[int]\n\n\ndef write_pickle(\n metadata: Metadata, \n body: np.ndarray,\n path: Union[str, PathLike] = 'out.epkl',\n) -> None:\n with open(path, 'wb') as f:\n pickle.dump(metadata, f)\n logger.debug(f'Position after metadata: {f.tell()}')\n pickle.dump(body, f)\n logger.debug(f'Position after {body.nbytes}-byte body: {f.tell()}')\n\n\ndef read_pickle(\n path: Union[str, PathLike] = 'out.epkl',\n get_metadata: bool = True,\n get_body: bool = True,\n) -> Iterable[\n Union[Metadata, np.ndarray]\n]:\n with open(path, 'rb') as f:\n metadata = pickle.load(f)\n logger.debug(f'Position after metadata: {f.tell()}')\n if get_metadata:\n yield metadata\n\n if not get_body:\n return\n body = pickle.load(f)\n logger.debug(f'Position after {body.nbytes}-byte body: {f.tell()}')\n\n yield body\n\n\ndef test():\n logger.addHandler(logging.StreamHandler(stdout))\n logger.setLevel(logging.DEBUG)\n\n print('Write:')\n write_pickle(\n Metadata(foo='bar', baz=[1, 2, 3]), \n np.random.random((512, 512)),\n )\n\n print('\\nCombined read:', flush=True)\n metadata, body = read_pickle()\n\n print('\\nSeparated read:', flush=True)\n results = read_pickle()\n metadata = next(results)\n print('Twiddle your thumbs for a while here; large memory not yet consumed', flush=True)\n body = next(results)\n\n print('\\nMetadata-only read:', flush=True)\n metadata, = read_pickle(get_body=False)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<p>Output:</p>\n<pre><code>Write:\nPosition after metadata: 68\nPosition after 2097152-byte body: 2097383\n\nCombined read:\nPosition after metadata: 68\nPosition after 2097152-byte body: 2097383\n\nSeparated read:\nPosition after metadata: 68\nTwiddle your thumbs for a while here; large memory not yet consumed\nPosition after 2097152-byte body: 2097383\n\nMetadata-only read:\nPosition after metadata: 68\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T17:17:53.473",
"Id": "520505",
"Score": "1",
"body": "Thank you, very clear and comprehensive! \"Pickled objects are already length-aware.\" - today I learned! This is extremely neat, since now different pickled objects can simply be concatenated; the file pointer is advanced \"for free\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T16:29:53.710",
"Id": "263634",
"ParentId": "263622",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263634",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T09:19:37.440",
"Id": "263622",
"Score": "1",
"Tags": [
"python",
"file"
],
"Title": "Python class for handling custom file type"
}
|
263622
|
<p>I'm using a site similar to SPOJ (in Portuguese, so I don't think linking it will help), where I need to find the number of different submasses in a given weighted string.</p>
<p>Through the use of an iterative FFT I was able to process strings of size 10⁵ in under 8 seconds, but it still doesn't pass all the test cases on the site due to the time limit and I am not capable of reducing the runtime; any tips would be greatly appreciated.</p>
<p>Link for <a href="https://drive.google.com/file/d/1BkVZV3I0e6jt9yPH4x4luBJGlzDzdW63/view?usp=sharing" rel="nofollow noreferrer">"entrada(input)" test file</a>.<br />
More details about the problem and the algorithm I used as base can be found in <a href="https://drive.google.com/file/d/1poHWQKNlYv0Z_k06vA7q1f-stbJpp04h/view?usp=sharing" rel="nofollow noreferrer">Finding submasses in weighted strings with Fast Fourier Transform</a>.</p>
<pre><code>using System;
using System.Numerics;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Cs
{
class URI
{
private static int ReverseBits(int val, int width) {
int result = 0;
for (int i = 0; i < width; i++, val >>= 1)
result = (result << 1) | (val & 1);
return result;
}
public static void TransformRadix2(Complex[] vec,int maxPeso, bool inverse) {
// Length variables
int n = vec.Length;
int levels = 0; // compute levels = floor(log2(n))
for (int temp = n; temp > 1; temp >>= 1)
levels++;
// Trigonometric table
Complex[] expTable = new Complex[n / 2];
double coef = 2 * Math.PI / n * (inverse ? 1 : -1);
for (int i = 0; i < n / 2; i++)
expTable[i] = Complex.FromPolarCoordinates(1, i * coef);
// Bit-reversed addressing permutation
for (int i = 0; i < n; i++) {
int j = ReverseBits(i, levels);
if (j > i) {
Complex temp = vec[i];
vec[i] = vec[j];
vec[j] = temp;
}
}
// Cooley-Tukey decimation-in-time radix-2 FFT
for (int size = 2; size <= n; size *= 2) {
int halfsize = size / 2;
int tablestep = n / size;
for (int i = 0; i < n; i += size) {
for (int j = i, k = 0; j < i + halfsize; j++, k += tablestep) {
Complex temp = vec[j + halfsize] * expTable[k];
vec[j + halfsize] = vec[j] - temp;
vec[j] += temp;
}
}
}
}
static void Main(string[] args){
Stopwatch sw = Stopwatch.StartNew();
int[] weightedAlphabet = new int[26];
for(int i=0;i<26;i++){
weightedAlphabet[i]=i+1;
}
char[] ipt = System.IO.File.ReadAllText(@"entrada.txt").ToCharArray();
int[] P = new int[ipt.Length];
int[] Q = new int[ipt.Length];
int maxPeso=0;
for(int i=0;i<ipt.Length;i++){
int pos =((int)ipt[i])-97;
int amount = weightedAlphabet[pos];
P[i]=amount+(i>0?P[i-1]:0);
}
maxPeso = P[P.Length-1];
for(int i=P.Length-1;i>0;i--){
Q[i]=maxPeso-P[i-1];
}
Q[0]=maxPeso;
Complex[] PPoly ={};
Complex[] QPoly ={};
Parallel.Invoke(()=>{PPoly = toSparsePoly(P,maxPeso);},
()=>{QPoly = toSparsePoly(Q,maxPeso);});
Parallel.Invoke(()=>TransformRadix2(PPoly,maxPeso,false),
()=>TransformRadix2(QPoly,maxPeso,false));
Complex[] CPoly = new Complex[PPoly.Length];
Complex[] CCPoly = new Complex[PPoly.Length];
for(int i=0;i<PPoly.Length;i++){
CPoly[i] = PPoly[i]*QPoly[i];
CCPoly[i] = PPoly[i]*QPoly[i];
}
TransformRadix2(CPoly,maxPeso,true);
int count=0;
for(int i=maxPeso-1;i<=2*maxPeso+1;i++){
if(Math.Round(CPoly[i].Real/CPoly.Length)>0){
count++;
}
}
Console.WriteLine("n of submasses: "+count);
Console.WriteLine("input length: "+ipt.Length);
Console.WriteLine("runtime: "+sw.Elapsed);
}
public static Complex[] toSparsePoly(int[] coeffArray,int maxVal){
int length=1;
while(length<=maxVal){
length*=2;
}
length*=2;
Complex[] polyArr = new Complex[length];
for(int i=0;i<length;i++){
polyArr[i]=new Complex();
}
foreach (int i in coeffArray)
{
polyArr[i-1]=new Complex(1,0);
}
return polyArr;
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T11:41:29.720",
"Id": "263624",
"Score": "0",
"Tags": [
"c#",
"performance",
"programming-challenge"
],
"Title": "Find the number of different submasses in a weighted string"
}
|
263624
|
<p>I have the following specific task, for which I have written code, in <strong>Rcpp</strong>, but it doesn't scale well and I would like to improve it. I'll describe first the steps of the procedure</p>
<p><strong>Step 1</strong>:</p>
<p>We have matrices of dimensions (K+1)x(K+1), which have non zero values on the positions displayed, and this can be generalized for larger K values</p>
<pre><code>K = 3
n = matrix(c(10,10,10,0,10,10,0,0,10,0,0,0,0,0,0,0),K+1,K+1,byrow=TRUE)
n
[,1] [,2] [,3] [,4]
[1,] 10 10 10 0
[2,] 10 10 0 0
[3,] 10 0 0 0
[4,] 0 0 0 0
K = 4
n = matrix(c(10,10,10,10,0,10,10,10,0,0,10,10,0,0,0,10,0,0,0,0,0,0,0,0,0),K+1,K+1,byrow=TRUE)
n
[,1] [,2] [,3] [,4] [,5]
[1,] 10 10 10 10 0
[2,] 10 10 10 0 0
[3,] 10 10 0 0 0
[4,] 10 0 0 0 0
[5,] 0 0 0 0 0
</code></pre>
<p><strong>Step 2</strong>:</p>
<p>Now we focus on the non-zero cells. Each cell corresponds to a vector of 0 and 1 values.</p>
<p>For example, for <code>K=3</code> the <code>n[1,1]</code> cell corresponds to the vector <code>c(1,1,1)</code>, where the <code>n[2,1]</code> to the vector <code>c(1,1,0)</code> and the cell <code>n[3,1]</code> to the vector <code>c(1,0,0)</code>.</p>
<p>Now if we move to the cells of the second column, the value 1 starts from the second position of the vectors, i.e. <code>n[1,2]</code> has as vector the <code>c(0,1,1)</code>, <code>n[2,2]</code> has as vector the <code>c(0,1,0)</code> and lastly in a similar manner <code>n[1,3]</code> has <code>c(0,0,1)</code>.</p>
<p>The same happens when <code>K=4</code>, the procedure remains the same the only thing that changes is the vector length, i.e. <code>n[1,1]</code> has as vector <code>c(1,1,1,1)</code>.</p>
<p>Hence, each cell corresponds to a particular 0-1 vector. What the value of each cell indicates, is the multiplicity of each corresponding vector. So, if <code>K=3</code> and <code>n[1,1]=10</code> then we have 10 times the vector <code>c(1,1,1)</code>.</p>
<p>So, I created the multiplicity matrix with the following code, I would stick into the <code>K=3</code> case for the illustration. First, I created the vector-matrix <code>Vector_Matrix</code> which holds all the possible vectors, as described previously <code>c(1,1,1),c(1,1,0),...,c(0,0,1)</code>. Then I create the <code>Multiplicity_Matrix</code>, which is created based on the <code>Vector_Matrix</code> by replicating each rows <code>n[i,j]</code> times.</p>
<pre><code>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
bool tell(int x, int y)
{
return x >= y;
}
// [[Rcpp::export]]
arma::mat Vector_Matrix(int K){
arma::mat P(K*(K+1)/2,K);
int Y = 0;
for (int step = K; step > 0; --step) {
for (int y = 0; y < step; ++y, ++Y) {
for (int x = 0; x < step; ++x) {
P(Y,x) = tell(x,y);
}
}
}
return P;
}
// [[Rcpp::export]]
int NonDiagSum(arma::mat n, int K){
int sum = 0;
for(int i=0; i<(K+1); ++i){
sum += n(i,K-i);
}
return accu(n) - sum;
}
// [[Rcpp::export]]
arma::mat Multiplicity_matrix(arma::mat n, int K){
arma::mat Res(NonDiagSum(n,K),K);
arma::mat P = Vector_Matrix(K);
int k = 0;
int ind_r = 0;
int next = 0;
for(int i=0; i<K; ++i){
for(int j=0; j<(K-k); ++j){
if( (n(i,j)!=0) ){
for(int t=0; t<K; ++t){
for(int iter=0; iter<n(i,j); ++iter){
Res(iter+next,t) = P(ind_r,t);
}
}
next = next + n(i,j);
}
ind_r = ind_r + 1;
}
k = k + 1;
}
return Res;
}
</code></pre>
<p>The results from those algorithms would be</p>
<pre><code>K = 3
Vector_Matrix(K)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 0 1 1
[3,] 0 0 1
[4,] 1 1 0
[5,] 0 1 0
[6,] 1 0 0
n = matrix(c(2,2,2,0,2,2,0,0,2,0,0,0,0,0,0,0),K+1,K+1,byrow=TRUE)
Multiplicity_Matrix(n,K)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 0 1 1
[4,] 0 1 1
[5,] 0 0 1
[6,] 0 0 1
[7,] 1 1 0
[8,] 1 1 0
[9,] 0 1 0
[10,] 0 1 0
[11,] 1 0 0
[12,] 1 0 0
</code></pre>
<p>where we see that each row of the <code>Vector_Matrix</code> has been replicated two times, because of the cells <code>n[i,j]=2</code>.</p>
<p><strong>Step 3</strong>:</p>
<p>Now as a third step, where the output of that step is our main goal, we have a Bernoulli trial on each non-zero cell of the <code>Multiplicity_Matrix</code> and we save the result matrix.</p>
<pre><code>// [[Rcpp::export]]
arma::mat Bern_Matrix(arma::mat n, int K, double p){
int N = NonDiagSum(n,K);
arma::mat P(N,K);
P = Multiplicity_Matrix(n, K);
for(int i=0; i<N; ++i){
for(int j=0; j<K; ++j){
P(i,j) = P(i,j)*R::rbinom(1,p);
}
}
return P;
}
</code></pre>
<p>So, if we run the <code>Bern_matrix</code> we have</p>
<pre><code>K = 3
n = matrix(c(2,2,2,0,2,2,0,0,2,0,0,0,0,0,0,0),K+1,K+1,byrow=TRUE)
Bern_Matrix(n, K, 0.5)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 0 0
[3,] 0 1 1
[4,] 0 1 0
[5,] 0 0 1
[6,] 0 0 1
[7,] 1 0 0
[8,] 0 1 0
[9,] 0 1 0
[10,] 0 1 0
[11,] 1 0 0
[12,] 1 0 0
</code></pre>
<p>Where the <code>Bern_Matrix</code> can be regarded as the <code>Multiplicity_Matrix</code> but with the non-zero values, i.e. 1, being changed to 0 with probability 0.5</p>
<p><strong>Conclusion</strong>:</p>
<p>What I want to achieve is to make those algorithms even faster if possible, and also to find a way that will make the algorithms scale well as the number of elements inside the cells of the matrix <code>n</code>increases.</p>
<p><strong>Side Note</strong>: I tried to find a way that will avoid the creation of all those matrices and will go directly from the matrix <code>n</code> to the <code>Bern_Matrix</code> without calculating the <code>Vector_Matrix</code> and <code>Multiplicity_Matrix</code>, the code for that is the following</p>
<pre><code>// [[Rcpp::export]]
arma::mat Direct_Matrix(arma::mat n, int K, double p){
int N = NonDiagSum(n,K);
arma::mat H(N,K);
H.zeros();
int next = 0;
for(int j=0; j<K; ++j){
for(int i=0; i<(K-j); ++i){
for(int iter=0; iter<n(i,j); ++iter){
H.submat(iter+next,j,iter+next,K-1-i) = as<arma::rowvec>(Rcpp::rbinom( K-j-i, 1, p ));
}
next += n(i,j);
}
}
return H;
}
</code></pre>
<p>Sorry for the long question, and if something it is needed to be added, I will happily add it and clarify it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T13:39:44.783",
"Id": "520493",
"Score": "0",
"body": "I am guessing that repeated calls of `Rcpp::rbinom` are the bottleneck. What is the current performance? and target?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T13:47:59.033",
"Id": "520495",
"Score": "0",
"body": "@minem For example, for the matrix ```n = matrix(c(2,2,2,0,2,2,0,0,2,0,0,0,0,0,0,0),K+1,K+1,byrow=TRUE)``` when I use the ```Direct_Matrix``` which avoids mainy computations it takes on average ```8.769453e-09``` second, whereas for ```n = matrix(c(650,800,900,0,500,750,0,0,800,0,0,0,0,0,0,0),K+1,K+1,byrow=TRUE)``` it takes on average ```4.474615e-07``` seconds. I would like to push it down as much as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T13:49:39.950",
"Id": "520496",
"Score": "0",
"body": "@minem Imagine that I will have to call the ```Direct_matrix``` in my MCMC algorithm on each iteration. That is ok when the values on the cells of ```n``` are small but when they increase it takes extremely much more time."
}
] |
[
{
"body": "<p>Your <code>Direct_Matrix()</code> function is already doing things quite well; it mainly avoids going multiple times over the same memory. However, there might be some more improvements possible. First of all:</p>\n<pre><code>arma::mat H(N,K);\nH.zeros();\n</code></pre>\n<p>This zeroes all elements, but we are actually going to overwrite about half of the elements anyway. It might be better to avoid zeroing the matrix, and do this only inside the loop for those elements we know should be zero.</p>\n<p>The triple nested <code>for</code>-loop is fine, it looks bad but it just does as many iterations as the number of rows in the result. But inside it we have:</p>\n<pre><code>H.submat(iter+next,j,iter+next,K-1-i) = as<arma::rowvec>(Rcpp::rbinom( K-j-i, 1, p ));\n</code></pre>\n<p>Especially if <code>Rcpp::binom()</code> cannot be inlined, this might be a bit inefficient, as it has to pass around a whole temporary vector. I would try to write it as:</p>\n<pre><code>for (int k = 0; k < i; ++k)\n H(j, k) = Rccp::rbinom(1, p);\nfor (int k = i; k < K; ++k)\n H(j, k) = 0;\n</code></pre>\n<p>Of course, now we have much more function calls inside the loop. I'd try to use <a href=\"https://en.cppreference.com/w/cpp/numeric/random/bernoulli_distribution\" rel=\"nofollow noreferrer\"><code>std::bernoulli_distribution()</code></a> next instead of <code>Rcpp::rbinom()</code>:</p>\n<pre><code>std::random_device rd;\nstd::mt19937 gen(rd());\nstd::bernoulli_distribution distrib(p);\n...\nfor (int k = 0; k < i; ++k)\n H(j, k) = distrib(gen);\nfor (int k = i; k < K; ++k)\n H(j, k) = 0;\n</code></pre>\n<p>If <code>p</code> is exactly 0.5 though, you could go for another approach: fill an unsigned integer with a random number, and then you use the individual bits to give you the value for each element in the matrix. Especially if <code>K <= 64</code>, this can be done very efficiently on 64-bits machines. I would then even merge the two loops:</p>\n<pre><code>std::random_device rd;\nstd::mt19937_64 gen(rd());\n...\nauto bits = gen(); // Generate 64 random bits\nbits &= (1UL << i) - 1; // Zero all but the first i bits\n\nfor (int k = 0; k < K; ++k) {\n H(j, k) = bits & 1;\n bits >>= 1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T11:45:32.057",
"Id": "520557",
"Score": "0",
"body": "This is a really helpful answer, I did manage to reduce the computational time with those suggestions!! So, for the ```H.zeros();``` because each row will have zeros on the first cells and last cells I think I would have to use 3 loops, one for the first zeros, for the ones in the middle and for the zeros in the end. What I did is instead of using ```arma::mat H(N,K) ``` and ```H.zeros();``` I used ```NumericMatrix H(N,K)``` which is much faster and initializes the matrix with zeros."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T11:47:03.583",
"Id": "520558",
"Score": "0",
"body": "Also, as you pointed out I changed the ```.submat``` which requires the use of a non optimal binomial version with a For Loop that goes exactly to the places where we want to conduct the trial"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T11:48:31.223",
"Id": "520559",
"Score": "0",
"body": "And lastly, the most significant time reduction was given by ```std::bernoulli_distribution distrib(p)``` and I was wondering why?? I mean a random draw from a Bernoulli distribution seems already easy and fast to implement what additionally they do that makes it even faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:31:58.930",
"Id": "520589",
"Score": "0",
"body": "I didn't delve into the internals of Rccp, but could it be that `Rccp::rbinom()` returns dynamically allocated memory? That means a lot of `new` and `delete` behind the scenes."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T20:39:45.950",
"Id": "263642",
"ParentId": "263626",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263642",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T12:37:05.927",
"Id": "263626",
"Score": "1",
"Tags": [
"c++",
"performance",
"r",
"rcpp"
],
"Title": "Accelerating creation of matrices and finding ways for optimal scaling"
}
|
263626
|
<p>I want to count the missing values for each case in different sets of variables in a bigger dataset. Lets say in the mtcars between the variable <code>disp</code> and the variable <code>qsec</code> for each column.</p>
<pre><code> # Dummy
set.seed(1337)
mtcars[round(runif(8,1,32)),round(runif(3,1,11))] <- rep(NA,3)
mtcars$na <- mtcars %>%
select(hp:wt) %>%
summarise(na = rowSums(is.na(.)))
mtcars <- cbind(mtcars,mtcars %>%
select(hp:wt) %>%
summarise(na = rowSums(is.na(.))))
</code></pre>
<p>The Problem with both approaches is, that in the new created <code>na</code> column, contains a dataframe instead of just a numeric column as the output of <code>str()</code> shows</p>
<pre><code>str(mtcars)
'data.frame': 32 obs. of 13 variables:
$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
$ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
$ disp: num 160 160 108 258 360 ...
$ hp : num 110 110 93 110 175 105 245 62 95 123 ...
$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
$ wt : num 2.62 2.88 2.32 3.21 3.44 ...
$ qsec: num 16.5 17 18.6 19.4 17 ...
$ vs : num 0 0 1 1 0 1 0 1 1 1 ...
$ am : num 1 1 1 0 0 0 0 0 0 0 ...
$ gear: num 4 4 4 3 3 3 3 4 4 4 ...
$ carb: num 4 4 1 1 2 1 4 2 2 4 ...
$ na :'data.frame': 32 obs. of 1 variable:
..$ na: Named num 0 0 0 0 0 0 0 0 0 0 ...
.. ..- attr(*, "names")= chr "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive" ...
$ na : Named num 0 0 0 0 0 0 0 0 0 0 ...
..- attr(*, "names")= chr "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" "Hornet 4 Drive" ...
</code></pre>
<p>What would be the better / best way to get a numeric na-column?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T07:12:20.467",
"Id": "520550",
"Score": "0",
"body": "\"contains a dataframe instead of just a numeric column\" would suggest this question is off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T07:12:31.527",
"Id": "520551",
"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)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T15:07:46.497",
"Id": "263633",
"Score": "0",
"Tags": [
"r"
],
"Title": "R Count rowwise missing values for specific columns - dplyr cleanest version"
}
|
263633
|
<p>Recently I needed to expand the exports in a file to all methods in order to allow for Jest tests to cover more of the code (without using <a href="https://github.com/jhnns/rewire" rel="nofollow noreferrer">Rewire</a>). Beforehand, only the functions used by other production files were exported, meaning unit tests only covered the exposed methods and not the non-exported ones. I'm wondering if there are any disadvantages to exporting all of the functions within a file - or if there is a better way that this code can be written such that I can unit test all of the methods within individually. I made a simple example of the code in question:</p>
<p>Calculator.js</p>
<pre class="lang-javascript prettyprint-override"><code>
const sum = (addend1, addend2) => addend1 + addend2;
const difference = (minuend, subtrahend) => subtrahend - minuend;
const product = (multiplicand, multiplier) => multiplicand * multiplier;
const quotient = (dividend, divisor) => dividend / divisor;
const findAbsDifference = (number1, number2) => difference(Math.abs(number1), Math.abs(number2));
export {
sum,
product,
quotient,
findAbsDifference
} // difference is not exported, because it's not used in any other file
</code></pre>
<p>Calculator.test.js</p>
<pre class="lang-javascript prettyprint-override"><code>import * as Calculator from "./Calculator.js";
describe('Calculator', () => {
test('sum(5, 5)', () => {
const addend1 = 5;
const addend2 = 5;
const expectedSum = 10;
expect(Calculator.sum(addend1, addend2)).toEqual(expectedSum);
});
test('findAbsDifference(-5, 2)', () => {
const minuend = -5;
const subtrahend = 2;
const expectedDiff = 3;
expect(Calculator.findAbsDifference(minuend, subtrahend)).toEqual(expectedDiff);
});
/**
*
* I'd like to test the difference(minuend, subtrahend) method here,
* although I am unable to do this unless it is exported.
* Is there any disadvantage to exporting this function when it's only used in the test
* and within findAbsDifference which is in the same file?
*
**/
test('product(11, 2)', () => {
const multiplicand = 11;
const multiplier = 2;
const expectedProduct = 22;
expect(Calculator.product(multiplicand, multiplier)).toEqual(expectedProduct);
});
test('quotient(20, 5)', () => {
const dividend = 20;
const divisor = 5;
const expectedQuotient = 4;
expect(Calculator.quotient(dividend, divisor)).toEqual(expectedQuotient);
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T19:39:09.263",
"Id": "520509",
"Score": "1",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>Well in your specific case, you are implementing the functionality of a calculator. The calculator has a public interface of what it can do. I do not think it makes sense to hide difference just because it is not used anywhere. You can still export it regardless of it being used or not.</p>\n<p>Also, you seem to be testing functions (implementation) instead of functionality or behavior. Have your tests assert that the calculator does something you want it to do, not that the function of a calculator does something you want it to do. It's a subtle difference, but it makes your tests much more readable when you are dealing with more complex behavior.</p>\n<p>This might be just my personal preference, but I think it makes tests also more readable: split the setup, execution and assertion into three different parts. This has many names, but is mostly known by given-when-then.</p>\n<p>Taking all this into account, if you want your calculator to also subtract, export the difference function and restructure the tests:</p>\n<pre><code>...\n test('sums two numbers', () => {\n // given\n const addend1 = 5;\n const addend2 = 5;\n\n // when\n const sum = Calculator.sum(addend1, addend2)\n\n // then\n expect(sum).toEqual(10);\n });\n\n test('finds the difference between two numbers', () => {\n // given\n const number1 = 5;\n const number2 = 5;\n\n // when\n const diff = Calculator.difference(number1, number2)\n\n // then\n expect(diff).toEqual(0);\n });\n...\n</code></pre>\n<p>It would be a totally different story if your difference function was a helper function specific to the calculator. Then the function would not be a part of the interface of the calculator and you should not test it directly, as it is a bad practice to test "private" functions, because you tie the tests to the implementation. This means that whenever you will refactor, the tests will also break. You can make the tests for a function while you develop it, but delete these tests afterwards, as they are not useful anymore. You should test the private functions indirectly, by testing the "publicly visible" interface, which is your main concern in the first place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T03:13:33.597",
"Id": "521272",
"Score": "0",
"body": "Thank you @Blaž Mrak, that perfectly answers my question and gives me a good direction to move forwards! I like the separation of given-when-then, makes tests concise in their intended outcomes. Appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T13:45:42.667",
"Id": "263667",
"ParentId": "263635",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "263667",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T17:07:54.533",
"Id": "263635",
"Score": "0",
"Tags": [
"javascript",
"unit-testing"
],
"Title": "Unit tests for individual methods of a calculator"
}
|
263635
|
<p>CodeSignal put out a challenge by Uber that involves writing a "fare estimator" that involves a function dependent on cost per minute, cost per mile, ride time and ride distance.</p>
<p>The formula is along the lines of:</p>
<pre><code>fare = (cost per minute) * (ride time) + (cost per mile) * (ride distance)
</code></pre>
<p>where <code>ride time</code> and <code>ride distance</code> are constant integers (or floats) and <code>cost per minute</code> and <code>cost per mile</code> are lists of integers and floats (as cost per minute and cost per mile depend on the car type).</p>
<p>This is my solution:</p>
<pre><code>def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):
y, f = [], lambda w, x, y, z: (w * x) + (y * z)
for a, b in zip(cost_per_minute, cost_per_mile):
y.append(f(a, ride_time, b, ride_distance))
return y
</code></pre>
<p>I'm just looking for any kind of feedback on the code. Is there a better way to implement it? Can you recommend better coding styles? Is my algorithm good or is it a steaming pile of wank? Leave any feedback you want!</p>
<p>You can check out the full challenge here (but you might need to sign up): <a href="https://app.codesignal.com/company-challenges/uber/HNQwGHfKAoYsz9KX6" rel="nofollow noreferrer">https://app.codesignal.com/company-challenges/uber/HNQwGHfKAoYsz9KX6</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T19:40:26.973",
"Id": "520510",
"Score": "1",
"body": "Can you show how you expect the function to be called? In particular, it helps to know what types the arguments will be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T23:13:35.347",
"Id": "520525",
"Score": "0",
"body": "It's just called by an external code judge (I didn't implement a main function)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T04:49:07.720",
"Id": "520535",
"Score": "0",
"body": "Ah, sorry, I see you have described the types of the arguments in the paragraph above the code."
}
] |
[
{
"body": "<p>Here are a few tips:</p>\n<ul>\n<li><p>Unless it makes the code easier to read, avoid multiple assignments in one line. making your code shorter does not necessarily make it better, faster nor more maintainable.</p>\n</li>\n<li><p>Give better names to your variables</p>\n</li>\n<li><p>Use <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a></p>\n</li>\n</ul>\n<p>So, your code could be changed to this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterable\n\ndef fareEstimator(ride_time: float, ride_distance: float, cost_per_minute_list: Iterable[float],\n cost_per_mile_list: Iterable[float]) -> Iterable[float]:\n result = []\n\n def calculateFare(ride_time: float, ride_distance: float, cost_per_minute: float,\n cost_per_mile: float) -> float:\n return ride_time*cost_per_minute + ride_distance*cost_per_mile\n\n for cost_per_minute, cost_per_mile in zip(cost_per_minute_list, cost_per_mile_list):\n result.append(calculateFare(ride_time, ride_distance, cost_per_minute, cost_per_mile))\n\n return result\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T18:50:13.297",
"Id": "263638",
"ParentId": "263636",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263638",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T17:21:41.857",
"Id": "263636",
"Score": "1",
"Tags": [
"python-3.x",
"programming-challenge",
"lambda",
"community-challenge"
],
"Title": "An implementation of Uber's \"Fare Estimator\" [CodeSignal]"
}
|
263636
|
<p>I have created Snake game in Python. it is a single-player game, where the snake has to eat the red dots in order to grow longer. I just wanted to review if there is any improvements for the code.</p>
<pre class="lang-py prettyprint-override"><code>import turtle
import random
import time
screen = turtle.Screen()
screen.title('Snake made in Python')
screen.setup(width = 800, height = 700)
screen.tracer(0)
turtle.bgcolor('turquoise')
turtle.speed(5)
turtle.pensize(4)
turtle.penup()
turtle.goto(-310,250)
turtle.pendown()
turtle.color('black')
turtle.forward(600)
turtle.right(90)
turtle.forward(500)
turtle.right(90)
turtle.forward(600)
turtle.right(90)
turtle.forward(500)
turtle.penup()
turtle.hideturtle()
score = 0
delay = 0.1
snake = turtle.Turtle()
snake.speed(0)
snake.shape('square')
snake.color("black")
snake.penup()
snake.goto(0,0)
snake.direction = 'stop'
fruit = turtle.Turtle()
fruit.speed(0)
fruit.shape('circle')
fruit.color('red')
fruit.penup()
fruit.goto(30,30)
old_fruit=[]
scoring = turtle.Turtle()
scoring.speed(0)
scoring.color("black")
scoring.penup()
scoring.hideturtle()
scoring.goto(0,300)
scoring.write("Score :",align="center",font=("Courier",24,"bold"))
def snake_go_up():
if snake.direction != "down":
snake.direction = "up"
def snake_go_down():
if snake.direction != "up":
snake.direction = "down"
def snake_go_left():
if snake.direction != "right":
snake.direction = "left"
def snake_go_right():
if snake.direction != "left":
snake.direction = "right"
def snake_move():
if snake.direction == "up":
y = snake.ycor()
snake.sety(y + 20)
if snake.direction == "down":
y = snake.ycor()
snake.sety(y - 20)
if snake.direction == "left":
x = snake.xcor()
snake.setx(x - 20)
if snake.direction == "right":
x = snake.xcor()
snake.setx(x + 20)
screen.listen()
screen.onkeypress(snake_go_up, "Up")
screen.onkeypress(snake_go_down, "Down")
screen.onkeypress(snake_go_left, "Left")
screen.onkeypress(snake_go_right, "Right")
while True:
screen.update()
if snake.distance(fruit)< 20:
x = random.randint(-290,270)
y = random.randint(-240,240)
fruit.goto(x,y)
scoring.clear()
score+=1
scoring.write("Score:{}".format(score),align="center",font=("Courier",24,"bold"))
delay-=0.001
new_fruit = turtle.Turtle()
new_fruit.speed(0)
new_fruit.shape('square')
new_fruit.color('red')
new_fruit.penup()
old_fruit.append(new_fruit)
for index in range(len(old_fruit)-1,0,-1):
a = old_fruit[index-1].xcor()
b = old_fruit[index-1].ycor()
old_fruit[index].goto(a,b)
if len(old_fruit)>0:
a= snake.xcor()
b = snake.ycor()
old_fruit[0].goto(a,b)
snake_move()
if snake.xcor()>280 or snake.xcor()< -300 or snake.ycor()>240 or snake.ycor()<-240:
time.sleep(1)
screen.clear()
screen.bgcolor('turquoise')
scoring.goto(0,0)
scoring.write(" GAME OVER \n Your Score is {}".format(score),align="center",font=("Courier",30,"bold"))
for food in old_fruit:
if food.distance(snake) < 20:
time.sleep(1)
screen.clear()
screen.bgcolor('turquoise')
scoring.goto(0,0)
scoring.write(" GAME OVER \n Your Score is {}".format(score),align="center",font=("Courier",30,"bold"))
time.sleep(delay)
turtle.Terminator()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T20:19:26.967",
"Id": "263639",
"Score": "3",
"Tags": [
"python",
"snake-game",
"turtle-graphics"
],
"Title": "Simple Snake Game in Python"
}
|
263639
|
<p>I have a Send method that is working but want to refactor a portion where it is using PostAsync().Result and ReadAsStringAsync().Result. I've never written async methods before and don't feel I understand the core concept or pattern yet. Here is the original method:</p>
<pre><code>public ServiceResult<string> Send(string tabDelimitedPOs)
{
var result = new ServiceResult<string>();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
httpClient.DefaultRequestHeaders.ExpectContinue = false;
var byteArray = Encoding.ASCII.GetBytes($"{User}:{Secret}");
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpResponseMessage response = null;
HttpContent httpContent = new StringContent(tabDelimitedPOs);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
response = httpClient.PostAsync(URL, httpContent).Result;
httpContent.Dispose();
result.StatusCode = response.StatusCode;
if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
{
result.IsFaulted = false;
result.ReturnedObject = response.Content.ReadAsStringAsync().Result;
}
else
{
result.IsFaulted = true;
result.FaultMessage = response.ReasonPhrase;
}
return result;
}
</code></pre>
<p>Would you critique the following refactor attempt? I've added two asynchronous methods.</p>
<pre><code>public ServiceResult<string> Send(string tabDelimitedPOs)
{
var result = new ServiceResult<string>();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
httpClient.DefaultRequestHeaders.ExpectContinue = false;
var byteArray = Encoding.ASCII.GetBytes($"{User}:{Secret}");
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpContent httpContent = new StringContent(tabDelimitedPOs);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
Task<HttpResponseMessage> taskResponse = PostData(URL, httpContent);
httpContent.Dispose();
result.StatusCode = taskResponse.Result.StatusCode;
if (taskResponse.Result.StatusCode == HttpStatusCode.OK || taskResponse.Result.StatusCode == HttpStatusCode.Created)
{
result.IsFaulted = false;
Task<string> taskString = ReadResponse(taskResponse.Result);
result.ReturnedObject = taskString.Result;
}
else
{
result.IsFaulted = true;
result.FaultMessage = taskResponse.Result.ReasonPhrase;
}
return result;
}
private async Task<HttpResponseMessage> PostData(string url, HttpContent content)
{
HttpResponseMessage response = await httpClient.PostAsync(url, content);
return response;
}
private async Task<string> ReadResponse(HttpResponseMessage response)
{
string responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
</code></pre>
<p>Here is the rest of the class. This project is .NET Framework 4.5.2. The application is designed to run in a Server 2008 environment which I do not manage.</p>
<pre><code>public class YoozAPI
{
public string URL { get; set; }
public string User { get; set; }
public string Secret { get; set; }
private static HttpClient httpClient = new HttpClient();
public YoozAPI() { }
public static YoozAPI Initialize()
{
string jsonFile = Path.Combine(Environment.CurrentDirectory, "YoozAPI.json");
StreamReader reader = new StreamReader(jsonFile);
string json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<YoozAPI>(json);
}
public bool PostOrders(PurchaseOrders orders)
{
string tabDelimitedPOs = orders.GetTabDelimitedString();
ServiceResult<string> result = Send(tabDelimitedPOs);
if (result.IsFaulted)
Log.RecordToDatabase("ExportReleasedPOs", string.Empty, string.Empty, string.Empty, string.Empty, result.FaultMessage);
return !result.IsFaulted;
}
// Code you've already seen above
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T21:01:32.833",
"Id": "520513",
"Score": "0",
"body": "What is .NET version? Also read [this article](https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects) and about [Asynchronous programming](https://docs.microsoft.com/en-us/dotnet/csharp/async)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T21:13:43.220",
"Id": "520515",
"Score": "0",
"body": "One more tip: `SecurityProtocol = SecurityProtocolType.Tls12` has no sense in .NET Framework 4.6 or newer, and has no effect (doesn't work for `HttpClient`) in .NET Core 3 or newer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T21:19:18.383",
"Id": "520516",
"Score": "0",
"body": "The version is .NET Framework 4.5.2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T07:10:05.693",
"Id": "520549",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Welcome to Code Review.</p>\n<p>There's a lot of points that I may describe here, then I'll do it short.</p>\n<h3>Architecture</h3>\n<p>The wrong point here is sequence of instatiation settings for API helper class and the class itself. Originally instance created first, and only then the proberties are filled. It makes difficult to properly setup <code>HttpClient</code>.</p>\n<p>I suggest to split settings and helper to reverse the instantiation order.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class YoozApiSettings\n{\n public string Url { get; set; }\n public string User { get; set; }\n public string Secret { get; set; }\n}\n</code></pre>\n<p><em>Naming guidline: don't use uppercased names for names of more than 2 characters long. For example <code>IO</code> is fine but <code>URL</code> isn't. Renaming <code>URL</code> to <code>Url</code>. The same for the class names.</em></p>\n<h3>Reading file</h3>\n<p>Here's a first occurance of a wrong <code>IDisposable</code> usage. You open the file <code>YoozAPI.json</code> but never close it. Let's fix.</p>\n<p><strong>Original</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>StreamReader reader = new StreamReader(jsonFile);\nstring json = reader.ReadToEnd();\n</code></pre>\n<p>You may add <code>reader.Close()</code> or <code>reader.Dispose()</code>.</p>\n<p><strong>Nearest fix</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>StreamReader reader = new StreamReader(jsonFile);\nstring json = reader.ReadToEnd();\nreader.Dispose()\n</code></pre>\n<p>But here's an issue. If <code>reader.ReadToEnd()</code> cause an exception, the file again will be never closed.</p>\n<p><strong>Good fix</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>StreamReader reader = new StreamReader(jsonFile);\ntry\n{\n string json = reader.ReadToEnd();\n}\nfinally\n{\n reader.Dispose()\n}\n</code></pre>\n<p>But C# has already implemented this pattern, you can use it with less code written.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using (StreamReader reader = new StreamReader(jsonFile))\n{\n string json = reader.ReadToEnd();\n}\n</code></pre>\n<p>Also .NET has a shortcut for this classic code pattern.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string json = File.ReadAllText(jsonFile);\n</code></pre>\n<p>Read more: <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects\" rel=\"nofollow noreferrer\">Using objects that implement IDisposable</a>, <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement\" rel=\"nofollow noreferrer\">using statement</a>.</p>\n<p>As a summary of above notes the <code>Initialize()</code> method will look like:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static YoozApi Initialize()\n{\n string jsonFile = Path.Combine(Environment.CurrentDirectory, "YoozAPI.json");\n string json = File.ReadAllText(jsonFile);\n return new YoozApi(JsonConvert.DeserializeObject<YoozApiSettings>(json));\n}\n</code></pre>\n<p>As you can see, I pass <code>YoozApiSettings</code> to <code>YoozApi</code> constructor.</p>\n<p>Here's why.</p>\n<h3>Initializing <code>HttpClient</code></h3>\n<p><code>DefaultRequestHeaders</code> must be implemented once, right after <code>HttpClient</code> instance creation and before the first request sent.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private readonly HttpClient httpClient;\n\nprivate YoozApi(YoozApiSettings settings) \n{\n httpClient = new HttpClient();\n httpClient.DefaultRequestHeaders.ExpectContinue = false; // I'm not sure if it needed\n ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Remove this for .NET version 4.6 or higher\n var byteArray = Encoding.ASCII.GetBytes($"{settings.User}:{settings.Secret}");\n httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));\n httpClient.BaseAddress = new Uri(settings.Url);\n}\n</code></pre>\n<ul>\n<li><code>ServicePointManager.SecurityProtocol</code> also can be set once.</li>\n<li>No reason to render credentials per request as <code>User</code> and <code>Secret</code> never changes.</li>\n<li><code>HttpClient.BaseAddress</code> is intended to set a root address to make easier futher requests. With base address <code>new Uri("https://myapi.com")</code> to call <code>https://myapi.com/method</code> you may write like <code>httpClient.GetAsync("method")</code> instead of whole URL.</li>\n<li><code>private</code> constructor means you can create the class only through <code>Initialize()</code> method.</li>\n</ul>\n<h3>Asynchronous programming</h3>\n<p>All IO apis has thier awaitable methods. It makes easy to write asynchronous code that allows not to block threads while waiting. <code>.Result</code> blocks the calling thread, <code>await</code> not. Read more: <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/async\" rel=\"nofollow noreferrer\">Asynchronous programming</a> (especially read about difference between IO-bound work and CPU-bound work there).</p>\n<p>Awaitable method is method that returns <code>Task</code> or <code>Task<T></code>, or any other type that implements awaitable pattern e.g. <code>ValueTask</code> of <code>ValueTask<T></code> (available in .NET Core 3.1 and newer .NET). Awaitable method may be marked as <code>async</code>, may be not. To detect is the method awaitable look at its returning type, not at <code>async</code>.</p>\n<p>To make the <code>await</code> able to work, the method must be implement State Machine pattern. C# compiler can implement the State Machine from a regular method automatically. Just add <code>async</code> keyword. Then <code>await</code> can't be used without <code>async</code>, <code>async</code> has no sense without <code>await</code> inside like State Machine for nothing.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private async Task<ServiceResult<string>> InternalSendAsync(string tabDelimitedPOs)\n{\n var result = new ServiceResult<string>();\n using (HttpContent httpContent = new StringContent(tabDelimitedPOs, Encoding.UTF8, "text/plain"))\n using (HttpResponseMessage response = await httpClient.PostAsync("/", httpContent))\n {\n result.StatusCode = response.StatusCode;\n result.FaultMessage = response.ReasonPhrase; // you always have a ReasonPhrase as StatusCode\n result.IsFaulted = !response.IsSuccessStatusCode;\n\n if (response.IsSuccessStatusCode)\n result.ReturnedObject = await response.Content.ReadAsStringAsync();\n\n return result;\n };\n}\n</code></pre>\n<p><em>Naming guideline: add <code>Async</code> suffix to the name of awaitable method (recommended by Microsoft, I find it useful too).</em></p>\n<p>In addition to above notes, <code>await</code> unwrap the returning result from <code>Task</code>. So it works like <code>.Result</code> but asynchronously.</p>\n<p>You can see that I hid the method with <code>private</code> modifier as if it used only internally then no reason to expose it.</p>\n<h3>Usage</h3>\n<p>The reasonable question can apper "How can I use async method from sync method". The general answer: "You can call but you can't await it". For top-level methods that launches asynchronous work <code>async</code> keyword can be used with <code>void</code> returning type`.</p>\n<p>Let's assume that you're implementing a Windows Forms app.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private readonly YoozApi api = YoozApi.Initialize();\n\nprivate async void button1_Click(object sender, EventArgs e)\n{\n try\n {\n if (await api.PostOrdersAsync(orders))\n {\n // Success\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n}\n</code></pre>\n<p>Always handle all possible exceptions in <code>async void</code> method otherwise you'll not see the fact of the occured exception. Visually nothing will happen.</p>\n<h3>The whole example</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public class YoozApi\n{\n private readonly HttpClient httpClient;\n\n private YoozApi(YoozApiSettings settings) \n {\n httpClient = new HttpClient();\n httpClient.DefaultRequestHeaders.ExpectContinue = false;\n ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;\n var byteArray = Encoding.ASCII.GetBytes($"{settings.User}:{settings.Secret}");\n httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));\n httpClient.BaseAddress = new Uri(settings.Url);\n }\n\n public static YoozApi Initialize()\n {\n string jsonFile = Path.Combine(Environment.CurrentDirectory, "YoozAPI.json");\n string json = File.ReadAllText(jsonFile);\n return new YoozApi(JsonConvert.DeserializeObject<YoozApiSettings>(json));\n }\n\n public async Task<bool> PostOrdersAsync(PurchaseOrders orders)\n {\n string tabDelimitedPOs = orders.GetTabDelimitedString();\n ServiceResult<string> result = await InternalSendAsync(tabDelimitedPOs);\n\n if (result.IsFaulted)\n Log.RecordToDatabase("ExportReleasedPOs", string.Empty, string.Empty, string.Empty, string.Empty, result.FaultMessage);\n\n return !result.IsFaulted;\n }\n\n private async Task<ServiceResult<string>> InternalSendAsync(string tabDelimitedPOs)\n {\n var result = new ServiceResult<string>();\n using (HttpContent httpContent = new StringContent(tabDelimitedPOs, Encoding.UTF8, "text/plain"))\n using (HttpResponseMessage response = await httpClient.PostAsync("/", httpContent))\n {\n result.StatusCode = response.StatusCode;\n result.FaultMessage = response.ReasonPhrase; // you always have a ReasonPhrase as StatusCode\n result.IsFaulted = !response.IsSuccessStatusCode;\n\n if (response.IsSuccessStatusCode)\n result.ReturnedObject = await response.Content.ReadAsStringAsync();\n\n return result;\n };\n }\n}\n</code></pre>\n<p><em>Note: Windows Server 2008 R2 doesn't support TLS 1.2 by default but it can be enabled manually through Windows Registry. Anyway I recommend to update the <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies#net-framework-472\" rel=\"nofollow noreferrer\">.NET Framework to 4.7.2 as it fully compartible with Server 2008 R2 SP1</a>. The update won't affect other 4.5.2 apps.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T20:37:05.547",
"Id": "520599",
"Score": "0",
"body": "Thank you very kindly for this thorough response. Can I follow up and ask how to write a unit test for PostOrdersAsync? I've modified an existing test method of mine and it appears as if it doesn't even run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T21:10:23.190",
"Id": "520601",
"Score": "0",
"body": "Currently reading this. Please let me know if you have a good reference to read as well. https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/november/async-programming-unit-testing-asynchronous-code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T21:32:18.597",
"Id": "520604",
"Score": "0",
"body": "@CodenameCain `a unit test` unfortunately I didn't write tests a lot. Btw, nice article containing a lot of useful info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T21:46:34.407",
"Id": "520606",
"Score": "1",
"body": "Instead of public void MyTestMethod (not the real name, don't skewer me) I had to change the signature to public async Task MyTestMethod."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T10:21:34.820",
"Id": "263659",
"ParentId": "263640",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263659",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T20:20:31.713",
"Id": "263640",
"Score": "3",
"Tags": [
"c#",
"comparative-review",
"async-await"
],
"Title": "Posts data to endpoint, trying not to use .Result on async methods"
}
|
263640
|
<p>I am the author of this code. It's from an actual project, and it returns the desired result. However, I am very concerned that I'm not defining my Model correctly.</p>
<p>The Model is instantiated in the Controller. The Controller calls the instance of that Model. The Model defines itself via <code>.map()</code>, then returns itself via <code>return this;</code>.</p>
<p>I believe I've created a situation that allows me to manipulate data returned from the Stored Procedure before it's returned to the Controller.</p>
<p>Do you agree? Am I doing this right? (I cannot use an ORM because I'm required to use Stored Procedures. I'm trying to use as much ES6 as possible, like Classes and Map).</p>
<p><strong>Employee Controller</strong></p>
<pre><code>const Employee = require('../models/Employee');
const employee = new Employee();
console.log(`I am the emoyeeController... This is employee just after instantiation ===>`)
console.log(employee)
function getEmployeeById(req, res) {
//req.params
//req.params.id
const { id } = req.params; // ES6 destructuring
employee.FindById(id).then(e =>{
console.log(`Hi. I'm the employee Controller... this is the employee after calling the model ===>`)
console.log(e)
res.json({e})
});
}
module.exports = {
getEmployeeById
};
</code></pre>
<p><strong>Employe Model</strong></p>
<pre><code>const db = require('../config/db');
class Employee {
constructor() {
this.EEID = null;
this.FullName = null;
this.SSN = null;
}
async FindById(id) {
try {
const result = await db.raw("exec cbo.StoredProcedureName '', '', '', :id", { id })
result.map(x => {
this.EEID = x.id
this.FullName = x.txtFullName
this.SSN = x.txtSSN
});
return this;
}
catch (e) {
console.error(e)
}
}
}
module.exports = Employee;
</code></pre>
|
[] |
[
{
"body": "<h2>Naming: variables, methods</h2>\n<p>Many popular style guides (e.g. <a href=\"https://eslint.org/docs/developer-guide/code-conventions#naming\" rel=\"nofollow noreferrer\">esLint</a>, <a href=\"https://google.github.io/styleguide/jsguide.html#naming-method-names\" rel=\"nofollow noreferrer\">Google JS</a>, <a href=\"https://github.com/airbnb/javascript#naming--camelCase\" rel=\"nofollow noreferrer\">AirBnB</a>, etc.) recommend <code>camelCase</code> for method names - use <code>findById</code> instead of <code>FindById</code>. The same goes for variables.</p>\n<p>Presuming <code>db.raw('EXEC cbo.StoredProcedureName')</code> always returns an array then <code>results</code> or <code>records</code> would be more appropriate than <code>result</code> since it would store an array that may contain multiple records.</p>\n<h2>Main question</h2>\n<blockquote>\n<h3>Do you agree? Am I doing this right?</h3>\n</blockquote>\n<p>Let us look at how the properties are assigned- using <code>.map()</code>:</p>\n<blockquote>\n<pre><code>result.map(x => {\n this.EEID = x.id\n this.FullName = x.txtFullName\n this.SSN = x.txtSSN\n});\n</code></pre>\n</blockquote>\n<p>Let's also look at the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">MDN documentation for <code>.map()</code></a></p>\n<blockquote>\n<h2>Array.prototype.map()</h2>\n<p>The <strong>map()</strong> method <strong>creates a new array</strong> populated with the results of calling a provided function on every element in the calling array.</p>\n<p>...</p>\n<h3><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#when_not_to_use_map\" rel=\"nofollow noreferrer\">When not to use map()</a></h3>\n<p>Since map builds a new array, using it when you aren't using the returned array is an anti-pattern; use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\"><code>forEach</code></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> instead.</p>\n<p>You shouldn't be using map if:</p>\n<ul>\n<li>you're not using the array it returns; and/or</li>\n<li>you're not returning a value from the callback.</li>\n</ul>\n<p><sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>As the documentation points out, you shouldn't be using <code>.map()</code> if you aren't using the return value. It could simply use <code>.forEach()</code> instead of <code>.map()</code> - in either case the values from the last set of values gets used to assign to properties of <code>this</code>.</p>\n<p>A better solution would be to ensure that <code>result</code> has a length greater than zero and use the first result - there should only be one element if the <code>id</code> field is unique. For example, if there are no records returned it could <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw\" rel=\"nofollow noreferrer\"><code>throw</code></a> an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error\" rel=\"nofollow noreferrer\"><code>Error</code></a> (or appropriate subclass), which could be caught by the controller to return a 404 status, though that may not be what is desired.</p>\n<pre><code>const result = await db.raw("exec cbo.StoredProcedureName '', '', '', :id", { id })\nif (!result.length) {\n //handle case where record not found \n throw new Error('record by id not found');\n}\nconst record = result[0];\nthis.EEID = record.id;\nthis.FullName = record.txtFullName;\nthis.SSN = record.txtSSN;\n</code></pre>\n<p>The record could also be <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructured</a> to only the fields needed:</p>\n<pre><code>const { txtFullName, txtSSN } = result[0];\n</code></pre>\n<p>And the assignment could also be achieved using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\"><code>Object.assign()</code></a>:</p>\n<pre><code>Object.assign(this, { EEID: id, FullName: txtFullName, SSN: txtSSN });\n</code></pre>\n<p>As radarbob’s answer states: “<em>Requiring an employee object to fetch its own data doesn't make design sense</em>”. Instead of having an instance method <code>FindById</code> perhaps it would be better to make that be a <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Static_method\" rel=\"nofollow noreferrer\"><strong>static method</strong></a> that will create a new instance after finding the record from the database. That way the constructor can accept the properties and they don’t have the be initialized to <code>NULL</code> before the real values are available.</p>\n<p>See a demonstration below by expanding the snippet</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/* Fake database object */ \nconst db = {\n raw: function(statement, { id }) {\n return new Promise(resolve => {\n resolve([{\n id,\n txtFullName: 'Luke Skywalker',\n SSN: 73\n }]);\n });\n }\n};\nclass Employee {\n constructor(id, FullName, SSN) {\n this.EEID = id;\n this.FullName = FullName;\n this.SSN = SSN;\n }\n static async findById(id) {\n try {\n const result = await db.raw(\"exec cbo.StoredProcedureName '', '', '', :id\", { id });\n const { txtFullName, txtSSN } = result[0];\n return new this(id, txtFullName, txtSSN);\n } catch (e) {\n console.error(e)\n }\n }\n}\nclass EmployeeController {\n getEmployeeById(req, res) {\n\n const { id } = req.params; // ES6 destructuring \n\n Employee.findById(id).then(e =>{\n console.log(`Hi. I'm the employee Controller... this is the employee after calling the model ===>`);\n console.log(e);\n //res.json({e})\n });\n }\n}\nconst ctrlr = new EmployeeController();\nctrlr.getEmployeeById({params: { id: 1337 }});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Follow-up question</h2>\n<blockquote>\n<p>Notice that I "remap" <code>txtSSN</code> to <code>SSN</code>, as specified in the <code>constructor</code>. Is that bad practice?</p>\n</blockquote>\n<p>I don’t believe it is bad practice. It is common to have database column names that are different than what is desired for the API fields.</p>\n<p>If you have control over the stored procedure and it has a <code>SELECT</code> query then the SQL query could be updated to have aliases on the columns in the <code>SELECT</code> clause - that might eliminate the need to map columns.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T01:21:51.623",
"Id": "520531",
"Score": "0",
"body": "OMG!! That `object.assign()` is the answer!!! That's what I wanted - your explanations are really helpful. Notice that I \"remap\" `txtSSN` to `SSN`, as specified in the `constructor`. Is that bad practice? Although I *could* immediately send back the DB response without \"remapping\" it, I wanted a way to manipulate data before returning it to the Controller. Example: obscure the SSN, or add a Job Title to the end of the Full Name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T04:56:09.123",
"Id": "520537",
"Score": "1",
"body": "Cool. I amended my answer to contain a response to the question in your comment, and also updated the main suggestion to promote using a static method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T20:03:53.020",
"Id": "520595",
"Score": "0",
"body": "If I `return new this`, will I end up with a bunch of extra objects taking up memory somewhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T20:06:56.510",
"Id": "520597",
"Score": "0",
"body": "Presuming that you accept the suggestion to use a static method, then it just shifts the instantiation - i.e. `new this` to inside that static method, so no it would not be extra objects, since the static call `Employee.findById` is on the class, not an individual instance - does that make sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T21:14:12.207",
"Id": "520602",
"Score": "0",
"body": "I need to apply your recommendations to fully understand. When I can properly describe it in English words, I will add a comment here."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T22:45:36.783",
"Id": "263646",
"ParentId": "263641",
"Score": "5"
}
},
{
"body": "<blockquote>\n<p>I cannot use an ORM because I'm required to use Stored Procedures</p>\n</blockquote>\n<p>Exchanging one for the other (and back again if you like) should not impact the Model design. So the right question is "... define a Model without regard to the database". A "business domain" object is not a database thing.</p>\n<blockquote>\n<p>I've created a situation that allows me to manipulate data returned from the Stored Procedure before it's returned to the Controller.</p>\n</blockquote>\n<p>Not sure exactly the intent of "manipulate data" but the <code>Employee</code> constructor is the best place to validate arguments and instantiate a valid <code>Employee</code>.</p>\n<p>Requiring an employee object to fetch its own data doesn't make design sense. That and strongly coupling the <code>Employee</code> model to the database - <code>Employee.FindById()</code> - are both antithetical to <code>Employee</code> single responsibility. This code, as is, makes it impractical to entertain the question of swapping out data-fetch-and-store mechanisms.</p>\n<blockquote>\n<p>The Model is instantiated in the Controller.</p>\n</blockquote>\n<p>Technically yes, but it is not a valid <code>Employee</code> object. The <code>Employee</code> constructor should be passed the values to guarantee we create valid object. This means the data calls should be made from the Controller.</p>\n<p>This is a constructor's true, special purpose. In other words constructor parameters tells you what is required for a valid object, will let you know if otherwise, and ideally, will not create an object with bad data.</p>\n<hr />\n<p><strong>The Data Layer</strong></p>\n<p>The Controller will have your desired methods, such as <code>FetchById()</code>. These methods will in turn call the appropriate data object's methods, like a corresponding <code>FetchById</code>.</p>\n<p>In other words you will "declare" a common set of methods that every data object will implement. <em><strong>Now we can swap out ORM and stored procedure data objects</strong></em></p>\n<p>Any data object that implements the required methods can be passed into the Controller.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T00:59:58.830",
"Id": "520529",
"Score": "0",
"body": "Technically, I could leave out the `constructor`. The response from KNEX is proper JSON, so, I *could* just send that back to the controller directly. My queries are all in Stored Procedures. I'm using KNEX, which is more of a \"query builder\" and less of an \"ORM\". So, I was trying to build my own Model since KNEX doesn't have one (like Sequelize)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T18:20:38.643",
"Id": "520584",
"Score": "1",
"body": "Keeping MVC components decoupled means you can expect to write data-transmogrifying code to conform to your Model (or Controller or View) design. Sam Onela's answer is an example of how technical considerations can change data structures. Write transforming code to fit your Model, for example. That is far easier and far less error prone than rewriting broad swaths of core code that's already working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T18:45:03.333",
"Id": "520586",
"Score": "1",
"body": "*I could leave out the constructor* You must still assign values to object properties. Using `constructor` well makes it obvious what a object instantiation requires. It's a huge START HERE sign. That does not change just because the incoming data is wrapped in a JSON object, a Set of individual values, an array of JSON objects, an array of a single JSON object .... Your post shows you realize going to ORM, or KNEX, whatever, is going to cause code changes everywhere. You need to isolate your Model from the whims of \"the outside world.\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T22:48:09.643",
"Id": "263648",
"ParentId": "263641",
"Score": "7"
}
},
{
"body": "<p>I've done a lot of sql + stored-proc over the years.</p>\n<p>Some things to watch out for:</p>\n<ul>\n<li>data formats : Dates / Times (Timezone?), integers (7,123.01 v. 6.321,7 v. 5.600e-3 etc), sizes of numbers (and length of number-strings), etc.</li>\n<li>text encoding : Ascii (José ??), UTF-8, "windows quotes", Win1251, KOI8, GB18030, EBCDIC, etc etc</li>\n<li>security : your DB driver should be using a read-only connection, as a user with minimal necessary privs. A Read/Write-permitted connection can be used for inserts/updates/deletes.</li>\n<li>Unique IDs : the DB should be returning new IDs for new records</li>\n<li>results scrolling : a typical query giving a list of records may begin sending data as soon as it's ready on the server; other time (depending on indexing and sorting) it will wait until the full result set is ready before sending. On your (client) side, it's important to think through the implications of choices; - * waiting for last record available; * reading the full dataset into memory before processing; * processing each record as it arrives. The db resultset will typically be a forward-only iterator.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T21:27:33.197",
"Id": "520603",
"Score": "0",
"body": "My hope is that I can control access to the backend through passport.js and authorization tokens, or something like that. Right now, the \"API account\" is only granted EXECUTE on the Stored Proc; this account has no other CRUD permissions. I'd eventually like to use an ORM one day, but I would need to grant SELECT, UPDATE, DELETE, etc etc etc, and the Boss Man is a little reluctant on that, unless I can guarantee security."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T19:23:11.367",
"Id": "520799",
"Score": "0",
"body": "the boss may be wise ;) .. Orms can be fun, or a complete nightmare .. Stored-procs provide very good isolation, and can make testing very easy. I personally prefer it that way, as (mostly-jokingly) i never met an Orm i didn't end up fighting with ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:24:47.880",
"Id": "263681",
"ParentId": "263641",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263646",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T20:30:14.267",
"Id": "263641",
"Score": "5",
"Tags": [
"javascript",
"node.js",
"mvc",
"ecmascript-8"
],
"Title": "Employee Model definition without an ORM"
}
|
263641
|
<p><a href="https://github.com/mountbuild/tone-script" rel="nofollow noreferrer">Here</a> is some working code for converting an input string to an output string:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const list = [
{ text: "i~&__", code: "\u14f0", name: 'Nasal German i with extra low tone' },
{ text: "i~&_", code: "\u14e2", name: 'Nasal German i with low tone' },
{ text: "i~&^^", code: "\u14ee", name: 'Nasal German i with extra high tone' },
{ text: "i~&^", code: "\u14ea", name: 'Nasal German i with high tone' },
{ text: "i~&", code: "\u14e6", name: 'Nasal German i' },
{ text: "(i~&__)", code: "\u14f1", name: 'Nasal German i with extra low tone and stress' },
{ text: "(i~&_)", code: "\u14e3", name: 'Nasal German i with low tone and stress' },
{ text: "(i~&^^)", code: "\u14ef", name: 'Nasal German i with extra high tone and stress' },
{ text: "(i~&^)", code: "\u14eb", name: 'Nasal German i with high tone and stress' },
{ text: "(i~&)", code: "\u14e7", name: 'Nasal German i with stress' },
{ text: "i~__", code: "\u14fa", name: 'German i with extra low tone' },
{ text: "i~_", code: "\u0434", name: 'German i with low tone' },
{ text: "i~^^", code: "\u14fe", name: 'German i with extra high tone' },
{ text: "i~^", code: "\u0438", name: 'German i with high tone' },
{ text: "i~", code: "\u0430", name: 'German i' },
{ text: "(i~__)", code: "\u14fb", name: 'German i with extra low tone and stress' },
{ text: "(i~_)", code: "\u0435", name: 'German i with low tone and stress' },
{ text: "(i~^^)", code: "\u14ff", name: 'German i with extra high tone and stress' },
{ text: "(i~^)", code: "\u0439", name: 'German i with high tone and stress' },
{ text: "(i~)", code: "\u0432", name: 'German i with stress' },
{ text: "i+&__", code: "\u1470", name: 'Nasal short i with extra low tone' },
{ text: "i+&_", code: "\u1462", name: 'Nasal short i with low tone' },
{ text: "i+&^^", code: "\u146e", name: 'Nasal short i with extra high tone' },
{ text: "i+&^", code: "\u146a", name: 'Nasal short i with high tone' },
{ text: "i+&", code: "\u1466", name: 'Nasal short i' },
{ text: "(i+&__)", code: "\u1471", name: 'Nasal short i with extra low tone and stress' },
{ text: "(i+&_)", code: "\u1463", name: 'Nasal short i with low tone and stress' },
{ text: "(i+&^^)", code: "\u146f", name: 'Nasal short i with extra high tone and stress' },
{ text: "(i+&^)", code: "\u146b", name: 'Nasal short i with high tone and stress' },
{ text: "(i+&)", code: "\u1467", name: 'Nasal short i with stress' },
{ text: "i+__", code: "\u147a", name: 'Short i with extra low tone' },
{ text: "i+_", code: "\u03d4", name: 'Short i with low tone' },
{ text: "i+^^", code: "\u147e", name: 'Short i with extra high tone' },
{ text: "i+^", code: "\u03d8", name: 'Short i with high tone' },
{ text: "i+", code: "\u03d0", name: 'Short i' },
{ text: "(i+__)", code: "\u147b", name: 'Short i with extra low tone and stress' },
{ text: "(i+_)", code: "\u03d5", name: 'Short i with low tone and stress' },
{ text: "(i+^^)", code: "\u147f", name: 'Short i with extra high tone and stress' },
{ text: "(i+^)", code: "\u03d9", name: 'Short i with high tone and stress' },
{ text: "(i+)", code: "\u03d2", name: 'Short i with stress' },
{ text: "i&__", code: "\u1530", name: 'Nasal i sound with extra low tone' },
{ text: "i&_", code: "\u1522", name: 'Nasal i sound with low tone' },
{ text: "i&^^", code: "\u152e", name: 'Nasal i sound with extra high tone' },
{ text: "i&^", code: "\u152a", name: 'Nasal i sound with high tone' },
{ text: "i&", code: "\u1526", name: 'Nasal i sound' },
{ text: "(i&__)", code: "\u1531", name: 'Nasal i sound with extra low tone and stress' },
{ text: "(i&_)", code: "\u1523", name: 'Nasal i sound with low tone and stress' },
{ text: "(i&^^)", code: "\u152f", name: 'Nasal i sound with extra high tone and stress' },
{ text: "(i&^)", code: "\u152b", name: 'Nasal i sound with high tone and stress' },
{ text: "(i&)", code: "\u1527", name: 'Nasal i sound with stress' },
{ text: "i__", code: "\u153a", name: 'I sound with extra low tone' },
{ text: "i_", code: "\u0474", name: 'I sound with low tone' },
{ text: "i^^", code: "\u153e", name: 'I sound with extra high tone' },
{ text: "i^", code: "\u0478", name: 'I sound with high tone' },
{ text: "i", code: "\u0470", name: 'I sound' },
{ text: "(i__)", code: "\u153b", name: 'I sound with extra low tone and stress' },
{ text: "(i_)", code: "\u0475", name: 'I sound with low tone and stress' },
{ text: "(i^^)", code: "\u153f", name: 'I sound with extra high tone and stress' },
{ text: "(i^)", code: "\u0479", name: 'I sound with high tone and stress' },
{ text: "(i)", code: "\u0472", name: 'I sound with stress' },
{ text: "e~&__", code: "\u1512", name: 'Nasal Danish oe with extra low tone' },
{ text: "e~&_", code: "\u1504", name: 'Nasal Danish oe with low tone' },
{ text: "e~&^^", code: "\u1500", name: 'Nasal Danish oe with extra high tone' },
{ text: "e~&^", code: "\u150c", name: 'Nasal Danish oe with high tone' },
{ text: "e~&", code: "\u1508", name: 'Nasal Danish oe' },
{ text: "(e~&__)", code: "\u1513", name: 'Nasal Danish oe with extra low tone and stress' },
{ text: "(e~&_)", code: "\u1505", name: 'Nasal Danish oe with low tone and stress' },
{ text: "(e~&^^)", code: "\u1501", name: 'Nasal Danish oe with extra high tone and stress' },
{ text: "(e~&^)", code: "\u150d", name: 'Nasal Danish oe with high tone and stress' },
{ text: "(e~&)", code: "\u1509", name: 'Nasal Danish oe with stress' },
{ text: "e~__", code: "\u1518", name: 'Danish oe with extra low tone' },
{ text: "e~_", code: "\u0456", name: 'Danish oe with low tone' },
{ text: "e~^^", code: "\u151c", name: 'Danish oe with extra high tone' },
{ text: "e~^", code: "\u045a", name: 'Danish oe with high tone' },
{ text: "e~", code: "\u0451", name: 'Danish oe' },
{ text: "(e~__)", code: "\u1519", name: 'Danish oe with extra low tone and stress' },
{ text: "(e~_)", code: "\u0457", name: 'Danish oe with low tone and stress' },
{ text: "(e~^^)", code: "\u151d", name: 'Danish oe with extra high tone and stress' },
{ text: "(e~^)", code: "\u045b", name: 'Danish oe with high tone and stress' },
{ text: "(e~)", code: "\u0453", name: 'Danish oe with stress' },
{ text: "e+&__", code: "\u1510", name: 'Nasal short e with extra low tone' },
{ text: "e+&_", code: "\u1502", name: 'Nasal short e with low tone' },
{ text: "e+&^^", code: "\u150e", name: 'Nasal short e with extra high tone' },
{ text: "e+&^", code: "\u150a", name: 'Nasal short e with high tone' },
{ text: "e+&", code: "\u1506", name: 'Nasal short e' },
{ text: "(e+&__)", code: "\u1511", name: 'Nasal short e with extra low tone and stress' },
{ text: "(e+&_)", code: "\u1503", name: 'Nasal short e with low tone and stress' },
{ text: "(e+&^^)", code: "\u150f", name: 'Nasal short e with extra high tone and stress' },
{ text: "(e+&^)", code: "\u150b", name: 'Nasal short e with high tone and stress' },
{ text: "(e+&)", code: "\u1507", name: 'Nasal short e with stress' },
{ text: "e+__", code: "\u151a", name: 'Short e with extra low tone' },
{ text: "e+_", code: "\u0454", name: 'Short e with low tone' },
{ text: "e+^^", code: "\u151e", name: 'Short e with extra high tone' },
{ text: "e+^", code: "\u0458", name: 'Short e with high tone' },
{ text: "e+", code: "\u0450", name: 'Short e' },
{ text: "(e+__)", code: "\u151b", name: 'Short e with extra low tone and stress' },
{ text: "(e+_)", code: "\u0455", name: 'Short e with low tone and stress' },
{ text: "(e+^^)", code: "\u151f", name: 'Short e with extra high tone and stress' },
{ text: "(e+^)", code: "\u0459", name: 'Short e with high tone and stress' },
{ text: "(e+)", code: "\u0452", name: 'Short e with stress' },
{ text: "e&__", code: "\u14d0", name: 'Nasal e sound with extra low tone' },
{ text: "e&_", code: "\u14c2", name: 'Nasal e sound with low tone' },
{ text: "e&^^", code: "\u14ce", name: 'Nasal e sound with extra high tone' },
{ text: "e&^", code: "\u14ca", name: 'Nasal e sound with high tone' },
{ text: "e&", code: "\u14c6", name: 'Nasal e sound' },
{ text: "(e&__)", code: "\u14d1", name: 'Nasal e sound with extra low tone and stress' },
{ text: "(e&_)", code: "\u14c3", name: 'Nasal e sound with low tone and stress' },
{ text: "(e&^^)", code: "\u14cf", name: 'Nasal e sound with extra high tone and stress' },
{ text: "(e&^)", code: "\u14cb", name: 'Nasal e sound with high tone and stress' },
{ text: "(e&)", code: "\u14c7", name: 'Nasal e sound with stress' },
{ text: "e__", code: "\u14da", name: 'E sound with extra low tone' },
{ text: "e_", code: "\u0414", name: 'E sound with low tone' },
{ text: "e^^", code: "\u14de", name: 'E sound with extra high tone' },
{ text: "e^", code: "\u0418", name: 'E sound with high tone' },
{ text: "e", code: "\u0410", name: 'E sound' },
{ text: "(e__)", code: "\u14db", name: 'E sound with extra low tone and stress' },
{ text: "(e_)", code: "\u0415", name: 'E sound with low tone and stress' },
{ text: "(e^^)", code: "\u14df", name: 'E sound with extra high tone and stress' },
{ text: "(e^)", code: "\u0419", name: 'E sound with high tone and stress' },
{ text: "(e)", code: "\u0412", name: 'E sound with stress' },
{ text: "a+~&__", code: "\u1492", name: 'Nasal Danish æ with extra low tone' },
{ text: "a+~&_", code: "\u148e", name: 'Nasal Danish æ with low tone' },
{ text: "a+~&^^", code: "\u148a", name: 'Nasal Danish æ with extra high tone' },
{ text: "a+~&^", code: "\u1486", name: 'Nasal Danish æ with high tone' },
{ text: "a+~&", code: "\u1482", name: 'Nasal Danish æ' },
{ text: "(a+~&__)", code: "\u1493", name: 'Nasal Danish æ with extra low tone and stress' },
{ text: "(a+~&_)", code: "\u148f", name: 'Nasal Danish æ with low tone and stress' },
{ text: "(a+~&^^)", code: "\u148b", name: 'Nasal Danish æ with extra high tone and stress' },
{ text: "(a+~&^)", code: "\u1487", name: 'Nasal Danish æ with high tone and stress' },
{ text: "(a+~&)", code: "\u1483", name: 'Nasal Danish æ with stress' },
{ text: "a+~__", code: "\u1498", name: 'Danish æ with extra low tone' },
{ text: "a+~_", code: "\u03b6", name: 'Danish æ with low tone' },
{ text: "a+~^^", code: "\u149c", name: 'Danish æ with extra high tone' },
{ text: "a+~^", code: "\u03ba", name: 'Danish æ with high tone' },
{ text: "a+~", code: "\u03b1", name: 'Danish æ' },
{ text: "(a+~__)", code: "\u1499", name: 'Danish æ with extra low tone and stress' },
{ text: "(a+~_)", code: "\u03b7", name: 'Danish æ with low tone and stress' },
{ text: "(a+~^^)", code: "\u149d", name: 'Danish æ with extra high tone and stress' },
{ text: "(a+~^)", code: "\u03bb", name: 'Danish æ with high tone and stress' },
{ text: "(a+~)", code: "\u03b3", name: 'Danish æ with stress' },
{ text: "a~&__", code: "\u1592", name: 'Nasal German e sound with extra low tone' },
{ text: "a~&_", code: "\u1584", name: 'Nasal German e sound with low tone' },
{ text: "a~&^^", code: "\u1580", name: 'Nasal German e sound with extra high tone' },
{ text: "a~&^", code: "\u158c", name: 'Nasal German e sound with high tone' },
{ text: "a~&", code: "\u1588", name: 'Nasal German e sound' },
{ text: "(a~&__)", code: "\u1593", name: 'Nasal German e sound with extra low tone and stress' },
{ text: "(a~&_)", code: "\u1585", name: 'Nasal German e sound with low tone and stress' },
{ text: "(a~&^^)", code: "\u1581", name: 'Nasal German e sound with extra high tone and stress' },
{ text: "(a~&^)", code: "\u158d", name: 'Nasal German e sound with high tone and stress' },
{ text: "(a~&)", code: "\u1589", name: 'Nasal German e sound with stress' },
{ text: "a~__", code: "\u1598", name: 'German e sound with extra low tone' },
{ text: "a~_", code: "\u0506", name: 'German e sound with low tone' },
{ text: "a~^^", code: "\u159c", name: 'German e sound with extra high tone' },
{ text: "a~^", code: "\u050a", name: 'German e sound with high tone' },
{ text: "a~", code: "\u0501", name: 'German e sound' },
{ text: "(a~__)", code: "\u1599", name: 'German e sound with extra low tone and stress' },
{ text: "(a~_)", code: "\u0507", name: 'German e sound with low tone and stress' },
{ text: "(a~^^)", code: "\u159d", name: 'German e sound with extra high tone and stress' },
{ text: "(a~^)", code: "\u050b", name: 'German e sound with high tone and stress' },
{ text: "(a~)", code: "\u0503", name: 'German e sound with stress' },
{ text: "a+&__", code: "\u1490", name: 'Nasal short a with extra low tone' },
{ text: "a+&_", code: "\u148c", name: 'Nasal short a with low tone' },
{ text: "a+&^^", code: "\u1488", name: 'Nasal short a with extra high tone' },
{ text: "a+&^", code: "\u1484", name: 'Nasal short a with high tone' },
{ text: "a+&", code: "\u1480", name: 'Nasal short a' },
{ text: "(a+&__)", code: "\u1491", name: 'Nasal short a with extra low tone and stress' },
{ text: "(a+&_)", code: "\u148d", name: 'Nasal short a with low tone and stress' },
{ text: "(a+&^^)", code: "\u1489", name: 'Nasal short a with extra high tone and stress' },
{ text: "(a+&^)", code: "\u1485", name: 'Nasal short a with high tone and stress' },
{ text: "(a+&)", code: "\u1481", name: 'Nasal short a with stress' },
{ text: "a+__", code: "\u149a", name: 'Short a with extra low tone' },
{ text: "a+_", code: "\u03b4", name: 'Short a with low tone' },
{ text: "a+^^", code: "\u149e", name: 'Short a with extra high tone' },
{ text: "a+^", code: "\u03b8", name: 'Short a with high tone' },
{ text: "a+", code: "\u03b0", name: 'Short a' },
{ text: "(a+__)", code: "\u149b", name: 'Short a with extra low tone and stress' },
{ text: "(a+_)", code: "\u03b5", name: 'Short a with low tone and stress' },
{ text: "(a+^^)", code: "\u149f", name: 'Short a with extra high tone and stress' },
{ text: "(a+^)", code: "\u03b9", name: 'Short a with high tone and stress' },
{ text: "(a+)", code: "\u03b2", name: 'Short a with stress' },
{ text: "a&__", code: "\u1590", name: 'Nasal a sound with extra low tone' },
{ text: "a&_", code: "\u1582", name: 'Nasal a sound with low tone' },
{ text: "a&^^", code: "\u158e", name: 'Nasal a sound with extra high tone' },
{ text: "a&^", code: "\u158a", name: 'Nasal a sound with high tone' },
{ text: "a&", code: "\u1586", name: 'Nasal a sound' },
{ text: "(a&__)", code: "\u1591", name: 'Nasal a sound with extra low tone and stress' },
{ text: "(a&_)", code: "\u1583", name: 'Nasal a sound with low tone and stress' },
{ text: "(a&^^)", code: "\u158f", name: 'Nasal a sound with extra high tone and stress' },
{ text: "(a&^)", code: "\u158b", name: 'Nasal a sound with high tone and stress' },
{ text: "(a&)", code: "\u1587", name: 'Nasal a sound with stress' },
{ text: "a__", code: "\u159a", name: 'A sound with extra low tone' },
{ text: "a_", code: "\u0504", name: 'A sound with low tone' },
{ text: "a^^", code: "\u159e", name: 'A sound with extra high tone' },
{ text: "a^", code: "\u0508", name: 'A sound with high tone' },
{ text: "a", code: "\u0500", name: 'A sound' },
{ text: "(a__)", code: "\u159b", name: 'A sound with extra low tone and stress' },
{ text: "(a_)", code: "\u0505", name: 'A sound with low tone and stress' },
{ text: "(a^^)", code: "\u159f", name: 'A sound with extra high tone and stress' },
{ text: "(a^)", code: "\u0509", name: 'A sound with high tone and stress' },
{ text: "(a)", code: "\u0502", name: 'A sound with stress' },
{ text: "o~&__", code: "\u1450", name: 'Nasal German o with extra low tone' },
{ text: "o~&_", code: "\u1442", name: 'Nasal German o with low tone' },
{ text: "o~&^^", code: "\u144e", name: 'Nasal German o with extra high tone' },
{ text: "o~&^", code: "\u144a", name: 'Nasal German o with high tone' },
{ text: "o~&", code: "\u1446", name: 'Nasal German o' },
{ text: "(o~&__)", code: "\u1451", name: 'Nasal German o with extra low tone and stress' },
{ text: "(o~&_)", code: "\u1443", name: 'Nasal German o with low tone and stress' },
{ text: "(o~&^^)", code: "\u144f", name: 'Nasal German o with extra high tone and stress' },
{ text: "(o~&^)", code: "\u144b", name: 'Nasal German o with high tone and stress' },
{ text: "(o~&)", code: "\u1447", name: 'Nasal German o with stress' },
{ text: "o~__", code: "\u145a", name: 'German o with extra low tone' },
{ text: "o~_", code: "\u0394", name: 'German o with low tone' },
{ text: "o~^^", code: "\u145e", name: 'German o with extra high tone' },
{ text: "o~^", code: "\u0398", name: 'German o with high tone' },
{ text: "o~", code: "\u0390", name: 'German o' },
{ text: "(o~__)", code: "\u145b", name: 'German o with extra low tone and stress' },
{ text: "(o~_)", code: "\u0395", name: 'German o with low tone and stress' },
{ text: "(o~^^)", code: "\u145f", name: 'German o with extra high tone and stress' },
{ text: "(o~^)", code: "\u0399", name: 'German o with high tone and stress' },
{ text: "(o~)", code: "\u0392", name: 'German o with stress' },
{ text: "o+&__", code: "\u1550", name: 'Nasal short o with extra low tone' },
{ text: "o+&_", code: "\u1542", name: 'Nasal short o with low tone' },
{ text: "o+&^^", code: "\u154e", name: 'Nasal short o with extra high tone' },
{ text: "o+&^", code: "\u154a", name: 'Nasal short o with high tone' },
{ text: "o+&", code: "\u1546", name: 'Nasal short o' },
{ text: "(o+&__)", code: "\u1551", name: 'Nasal short o with extra low tone and stress' },
{ text: "(o+&_)", code: "\u1543", name: 'Nasal short o with low tone and stress' },
{ text: "(o+&^^)", code: "\u154f", name: 'Nasal short o with extra high tone and stress' },
{ text: "(o+&^)", code: "\u154b", name: 'Nasal short o with high tone and stress' },
{ text: "(o+&)", code: "\u1547", name: 'Nasal short o stress' },
{ text: "o+__", code: "\u155a", name: 'Short o with extra low tone' },
{ text: "o+_", code: "\u04c4", name: 'Short o with low tone' },
{ text: "o+^^", code: "\u155e", name: 'Short o with extra high tone' },
{ text: "o+^", code: "\u04c8", name: 'Short o with high tone' },
{ text: "o+", code: "\u04c0", name: 'Short o' },
{ text: "(o+__)", code: "\u155b", name: 'Short o with extra low tone and stress' },
{ text: "(o+_)", code: "\u04c5", name: 'Short o with low tone and stress' },
{ text: "(o+^^)", code: "\u155f", name: 'Short o with extra high tone and stress' },
{ text: "(o+^)", code: "\u04c9", name: 'Short o with high tone and stress' },
{ text: "(o+)", code: "\u04c2", name: 'Short o stress' },
{ text: "o&__", code: "\u1570", name: 'Nasal o sound with extra low tone' },
{ text: "o&_", code: "\u1562", name: 'Nasal o sound with low tone' },
{ text: "o&^^", code: "\u156e", name: 'Nasal o sound with extra high tone' },
{ text: "o&^", code: "\u156a", name: 'Nasal o sound with high tone' },
{ text: "o&", code: "\u1566", name: 'Nasal o sound' },
{ text: "(o&__)", code: "\u1571", name: 'Nasal o sound with extra low tone and stress' },
{ text: "(o&_)", code: "\u1563", name: 'Nasal o sound with low tone and stress' },
{ text: "(o&^^)", code: "\u156f", name: 'Nasal o sound with extra high tone and stress' },
{ text: "(o&^)", code: "\u156b", name: 'Nasal o sound with high tone and stress' },
{ text: "(o&)", code: "\u1567", name: 'Nasal o sound with stress' },
{ text: "o__", code: "\u157a", name: 'O sound with extra low tone' },
{ text: "o_", code: "\u04e4", name: 'O sound with low tone' },
{ text: "o^^", code: "\u157e", name: 'O sound with extra high tone' },
{ text: "o^", code: "\u04e8", name: 'O sound with high tone' },
{ text: "o", code: "\u04e0", name: 'O sound' },
{ text: "(o__)", code: "\u157b", name: 'O sound with extra low tone and stress' },
{ text: "(o_)", code: "\u04e5", name: 'O sound with low tone and stress' },
{ text: "(o^^)", code: "\u157f", name: 'O sound with extra high tone and stress' },
{ text: "(o^)", code: "\u04e9", name: 'O sound with high tone and stress' },
{ text: "(o)", code: "\u04e2", name: 'O sound with stress' },
{ text: "u+&__", code: "\u15b0", name: 'Nasal short u with extra low tone' },
{ text: "u+&_", code: "\u15a2", name: 'Nasal short u with low tone' },
{ text: "u+&^^", code: "\u15ae", name: 'Nasal short u with extra high tone' },
{ text: "u+&^", code: "\u15aa", name: 'Nasal short u with high tone' },
{ text: "u+&", code: "\u15a6", name: 'Nasal short u' },
{ text: "(u+&__)", code: "\u15b1", name: 'Nasal short u with extra low tone and stress' },
{ text: "(u+&_)", code: "\u15a3", name: 'Nasal short u with low tone and stress' },
{ text: "(u+&^^)", code: "\u15af", name: 'Nasal short u with extra high tone and stress' },
{ text: "(u+&^)", code: "\u15ab", name: 'Nasal short u with high tone and stress' },
{ text: "(u+&)", code: "\u15a7", name: 'Nasal short u with stress' },
{ text: "u+__", code: "\u15ba", name: 'Short u with extra low tone' },
{ text: "u+_", code: "\u04a4", name: 'Short u with low tone' },
{ text: "u+^^", code: "\u15be", name: 'Short u with extra high tone' },
{ text: "u+^", code: "\u04a8", name: 'Short u with high tone' },
{ text: "u+", code: "\u04a0", name: 'Short u' },
{ text: "(u+__)", code: "\u15bb", name: 'Short u with extra low tone and stress' },
{ text: "(u+_)", code: "\u04a5", name: 'Short u with low tone and stress' },
{ text: "(u+^^)", code: "\u15bf", name: 'Short u with extra high tone and stress' },
{ text: "(u+^)", code: "\u04a9", name: 'Short u with high tone and stress' },
{ text: "(u+)", code: "\u04a2", name: 'Short u with stress' },
{ text: "u&__", code: "\u14b0", name: 'Nasal u sound with extra low tone' },
{ text: "u&_", code: "\u14a2", name: 'Nasal u sound with low tone' },
{ text: "u&^^", code: "\u14ae", name: 'Nasal u sound with extra high tone' },
{ text: "u&^", code: "\u14aa", name: 'Nasal u sound with high tone' },
{ text: "u&", code: "\u14a6", name: 'Nasal u sound' },
{ text: "(u&__)", code: "\u14b1", name: 'Nasal u sound with extra low tone and stress' },
{ text: "(u&_)", code: "\u14a3", name: 'Nasal u sound with low tone and stress' },
{ text: "(u&^^)", code: "\u14af", name: 'Nasal u sound with extra high tone and stress' },
{ text: "(u&^)", code: "\u14ab", name: 'Nasal u sound with high tone and stress' },
{ text: "(u&)", code: "\u14a7", name: 'Nasal u sound with stress' },
{ text: "u__", code: "\u14ba", name: 'U sound with extra low tone' },
{ text: "u_", code: "\u03f4", name: 'U sound with low tone' },
{ text: "u^^", code: "\u14be", name: 'U sound with extra high tone' },
{ text: "u^", code: "\u03f8", name: 'U sound with high tone' },
{ text: "u", code: "\u03f0", name: 'U sound' },
{ text: "(u__)", code: "\u14bb", name: 'U sound with extra low tone and stress' },
{ text: "(u_)", code: "\u03f5", name: 'U sound with low tone and stress' },
{ text: "(u^^)", code: "\u14bf", name: 'U sound with extra high tone and stress' },
{ text: "(u^)", code: "\u03f9", name: 'U sound with high tone and stress' },
{ text: "(u)", code: "\u03f2", name: 'U sound with stress' },
{ text: "m+", code: "\u0102", name: 'M sound with nasal quality' },
{ text: "m", code: "\u0100", name: 'M sound' },
{ text: "n+", code: "\u0142", name: 'Indian n sound' },
{ text: "n", code: "\u0140", name: 'N sound' },
{ text: "q", code: "\u0160", name: 'Ng sound' },
{ text: "g?", code: "\u0138", name: 'Implosive g sound' },
{ text: "g.", code: "\u135a", name: 'Stop g sound' },
{ text: "g@", code: "\u1357", name: 'Tense g sound' },
{ text: "g", code: "\u0130", name: 'G sound' },
{ text: "'", code: "\u01b0", name: 'Lack of sound, glottal stop' },
{ text: "\"", code: "\u01b2", name: 'Arabic voiced pharyngeal fricative' },
{ text: "d~", code: "\u00d1", name: 'Arabic d sound' },
{ text: "d!", code: "\u006c", name: 'Ejective d sound' },
{ text: "d?", code: "\u0068", name: 'Implosive d sound' },
{ text: "d*", code: "\u0064", name: 'Click d sound' },
{ text: "d+", code: "\u0062", name: 'Indian d sound' },
{ text: "d.", code: "\u123a", name: 'Stop d sound' },
{ text: "d@", code: "\u1237", name: 'Tense d sound' },
{ text: "d", code: "\u0060", name: 'D sound' },
{ text: "b?", code: "\u0048", name: 'Implosive b sound' },
{ text: "b!", code: "\u004c", name: 'Ejective b sound' },
{ text: "b.", code: "\u121a", name: 'Stop b sound' },
{ text: "b@", code: "\u1217", name: 'Tense b sound' },
{ text: "b", code: "\u0040", name: 'B sound' },
{ text: "p!", code: "\u0038", name: 'Ejective p sound' },
{ text: "p*", code: "\u0034", name: 'Click p sound' },
{ text: "p.", code: "\u120a", name: 'Stop p sound' },
{ text: "p@", code: "\u1207", name: 'Tense p sound' },
{ text: "p", code: "\u0030", name: 'P sound' },
{ text: "t+", code: "\u00d2", name: 'Indian t sound' },
{ text: "t!", code: "\u00dc", name: 'Ejective t sound' },
{ text: "t~", code: "\u00d1", name: 'Arabic t sound' },
{ text: "t*", code: "\u00d4", name: 'Click t sound' },
{ text: "t.", code: "\u129a", name: 'Stop t sound' },
{ text: "t@", code: "\u1297", name: 'Tense t sound' },
{ text: "t", code: "\u00d0", name: 'T sound' },
{ text: "k!", code: "\u0058", name: 'Ejective k sound' },
{ text: "k*", code: "\u0054", name: 'Click k sound' },
{ text: "k+", code: "\u0052", name: 'Arabic Q sound' },
{ text: "k+!", code: "\u0059", name: 'Arabic ejective Q sound' },
{ text: "k.", code: "\u122a", name: 'Stop k sound' },
{ text: "k@", code: "\u1227", name: 'Tense k sound' },
{ text: "k", code: "\u0050", name: 'K sound' },
{ text: "h+", code: "\u0122", name: 'Hebrew harsh h sound' },
{ text: "h~", code: "\u0121", name: 'Arabic h sound' },
{ text: "h", code: "\u0120", name: 'H sound' },
{ text: "j+", code: "\u0152", name: 'Indian j sound' },
{ text: "j", code: "\u0150", name: 'J sound' },
{ text: "s+", code: "\u0072", name: 'Navajo s sound' },
{ text: "s~", code: "\u0071", name: 'Arabic s sound' },
{ text: "s.", code: "\u124a", name: 'Stop s sound' },
{ text: "s@", code: "\u1247", name: 'Tense s sound' },
{ text: "s", code: "\u0070", name: 'S sound' },
{ text: "f+", code: "\u00c2", name: 'Labial f sound' },
{ text: "f", code: "\u00c0", name: 'f sound' },
{ text: "v+", code: "\u00f2", name: 'Labial v sound' },
{ text: "v~", code: "\u00f1", name: 'Other v sound' },
{ text: "v", code: "\u00f0", name: 'V sound' },
{ text: "z+", code: "\u0092", name: 'Zulu dl sound' },
{ text: "z", code: "\u0090", name: 'Z sound' },
{ text: "c+~", code: "\u00b2", name: 'Arabic voiced th sound' },
{ text: "c+", code: "\u00b0", name: 'Voiced th sound' },
{ text: "c", code: "\u0080", name: 'Unvoiced th sound' },
{ text: "l+", code: "\u0172", name: 'Indian l sound' },
{ text: "l*", code: "\u0174", name: 'Click l sound' },
{ text: "l~", code: "\u0171", name: 'Arabic l sound' },
{ text: "l", code: "\u0170", name: 'L sound' },
{ text: "r~", code: "\u01a2", name: 'French r sound' },
{ text: "r+", code: "\u00e2", name: 'Indian r sound' },
{ text: "r!", code: "\u00e0", name: 'Single rolling r sound' },
{ text: "r", code: "\u01a0", name: 'English r sound' },
{ text: "x+", code: "\u0192", name: 'Indian sh sound' },
{ text: "x.", code: "\u141a", name: 'Stop sh sound' },
{ text: "x@", code: "\u1417", name: 'Tense sh sound' },
{ text: "x", code: "\u0190", name: 'Sh sound' },
{ text: "w", code: "\u0110", name: 'W sound' },
{ text: "y", code: "\u0180", name: 'Y sound' },
{ text: "y+", code: "\u0182", name: 'Slight y sound' },
{ text: " ", code: "\u0020", name: 'Hanakana Space' },
{ text: ".", code: "\u0021", name: 'Hanakana Period' },
{ text: ",", code: "\u0024", name: 'Hanakana comma' },
{ text: "(", code: "\u0023", name: 'Hanakana opening parenthesis' },
{ text: ")", code: "\u002b", name: 'Hanakana closing parenthesis' },
{ text: "[", code: "\u0026", name: 'Hanakana opening bracket' },
{ text: "]", code: "\u0027", name: 'Hanakana closing bracket' },
{ text: "|", code: "\u0025", name: 'Hanakana pipe' },
{ text: "#", code: "\u0028", name: 'Hanakana at sign' },
{ text: "/", code: "\u0029", name: 'Hanakana forward slash' },
{ text: "\\", code: "\u002a", name: 'Hanakana backward slash' },
{ text: ":", code: "\u0022", name: 'Hanakana colon' }
]
const look = {}
list.forEach(({ text }) => {
look[text] = '^' + text.replace(/[\(\)\*\!\?\^\+\_\.\[\]\|\\\/]/g, _ => `\\${_}`)
})
const form = text => {
let remaining = text.replace(/([A-Z])/g, (_, $1) => `${$1.toLowerCase()}+`)
let output = []
a:
while (remaining.length) {
for (let node of list) {
const pattern = look[node.text]
const regex = new RegExp(pattern)
const match = remaining.match(regex)
if (match) {
const val = node.code
output.push(val)
remaining = remaining.substr(match[0].length)
continue a
}
}
throw new Error(`${remaining}:${text}`)
}
return output.join('')
}
console.log(form('asdf'))
console.log(form('helloworld'))</code></pre>
</div>
</div>
</p>
<p>Given I would like to specify the patterns in this <code>list</code> object, how can I perhaps compile them and/or optimize the main <code>form</code> function which converts input to output? Perhaps into a trie of some sort?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T06:34:02.693",
"Id": "520541",
"Score": "1",
"body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
}
] |
[
{
"body": "<h3>One way to simplify</h3>\n<p>As far as I can tell, each of your <code>RegExp</code>s just looks at the start of your string for certain exact content - at that point you probably don't want <code>match</code> but <code>startsWith</code>, and you probably don't want to compile <code>RegExp</code>s when you can just use the strings you're looking for directly</p>\n<p>It seems to me like you can get rid of <code>look</code> entirely and rewrite your <code>for</code> loop like:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>for (let node of list) {\n if (remaining.startsWith(node.text)) {\n output.push(node.code);\n remaining = remaining.substr(node.text.length);\n continue a;\n }\n}\n</code></pre>\n<p>which to me seems clearer, and also means you don't need to worry about messy escaping of regexp metacharacters. It also seems to improve performance quite a bit, though I haven't tested that very thoroughly.</p>\n<h3>How about a trie?</h3>\n<p>As you mentioned in a comment, a very natural approach could be to use a trie. There are probably better-written better-perform trie implementations out there already, but a decently-written decently-performing needn't be any more complicated than</p>\n<pre><code>const trie_insert = (trie, key, value) => {\n if ( ! key ) {\n trie.value = value;\n return;\n }\n if ( trie[key[0]] === undefined ) {\n trie[key[0]] = {};\n }\n trie_insert(trie[key[0]], key.substr(1), value);\n}\n\n\nconst trie_match = (trie, str) => {\n let current_trie = trie;\n \n let current_depth = 0;\n let last_value = undefined;\n let depth_of_last_match = undefined;\n \n while (current_trie && current_depth <= str.length) {\n if (current_trie.value !== undefined) {\n last_value = current_trie.value;\n depth_of_last_match = current_depth;\n }\n\n current_trie = current_trie[str[current_depth]];\n current_depth++;\n }\n \n if (last_value === undefined) {\n throw new Error(`No match for "${key}"`);\n }\n\n return {\n length: depth_of_last_match,\n value: last_value\n };\n}\n</code></pre>\n<p>Then <code>form</code> could be as simple as:</p>\n<pre><code>const form = text => {\n let remaining = text.replace(/([A-Z])/g, (_, $1) => `${$1.toLowerCase()}+`);\n let output = [];\n \n while (remaining) {\n let match = trie_match(lookup, remaining);\n output.push(match.value);\n remaining = remaining.substr(match.length);\n }\n\n return output.join("");\n}\n</code></pre>\n<p>This approach also has the added benefit of not caring about the order of <code>list</code> - it might affect how long it takes to construct the trie at first, but the correctness of the result shouldn't be affected - unlike the original approach or the <code>startsWith</code> approach, which could both misbehave if, say, the order of the <code>t+</code> and <code>t</code> checks was accidentally switched.</p>\n<p>In my limited testing this scales much better than the <code>startsWith</code> approach, as does the next one:</p>\n<h3>Another regexp alternative</h3>\n<p>As Toby Speight mentioned in a comment, it might be an option to use a <code>RegExp</code> - but it's possible to do it with just one rather than several. Depending on how well the runtime optimizes it, that could perform <em>very</em> well - or it might not. Still, it should be worth trying to see how it goes.</p>\n<p>A simple way to do this could simply be to escape all the patterns much like in your original post, but instead of converting each of the patterns into its own RegExp, joining them into one - perhaps a bit like</p>\n<pre><code>const patterns = [];\nconst lookup = {};\n\nlist.forEach((node) => {\n patterns.push(node.text.replace(/[\\(\\)\\*\\!\\?\\^\\+\\_\\.\\[\\]\\|\\\\\\/]/g, _ => `\\\\${_}`));\n lookup[node.text] = node.code;\n});\n\nconst full_pattern = new RegExp("^(" + patterns.join("|") + ")");\n\nconst form = text => {\n let remaining = text.replace(/([A-Z])/g, (_, $1) => `${$1.toLowerCase()}+`);\n let output = [];\n \n while (remaining) {\n const match = remaining.match(full_pattern);\n if (match) {\n output.push(lookup[match[0]]);\n remaining = remaining.substr(match[0].length);\n } else {\n throw new Error(`${remaining}:${text}`);\n }\n }\n\n return output.join("");\n}\n</code></pre>\n<p>This simple implementation <em>does</em> care about the order of <code>list</code> (<code>i~&|i~|i</code> and <code>i|i~|i~&</code> behave differently), making it slightly less robust than the trie, though it <em>is</em> arguably simpler which might make up for that. Performance-wise it seems <em>very slightly</em> slower than the trie, but there may be ways to improve the implementation of the regex approach and change that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T23:37:26.433",
"Id": "520526",
"Score": "0",
"body": "Can I get any more optimized, by creating a trie or something like that? That way you don't have to iterate through every item of the list for each chunk, potentially."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T00:00:26.163",
"Id": "520527",
"Score": "1",
"body": "@LancePollard Now that you mention it, a trie does seem like an appropriate tool for the job. Should definitely be worth trying, at least."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T06:39:33.637",
"Id": "520542",
"Score": "1",
"body": "Alternative: create a big regexp formed by regex-quoting all the patterns and joining them with `|`, and use that to determine the maximal match. Then lookup the match in a hash-table we formed from the patterns. This assumes that your regexp compiler optimises well, of course, in which case the innards would look much like the trie."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T07:08:15.017",
"Id": "520548",
"Score": "0",
"body": "@SaraJ can you show how to do that?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T23:23:52.697",
"Id": "263651",
"ParentId": "263643",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T20:45:52.493",
"Id": "263643",
"Score": "4",
"Tags": [
"javascript",
"performance",
"parsing"
],
"Title": "Convert ASCII representations of phonetics to Unicode characters"
}
|
263643
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/260576/231235">Android APP connect to FTP server in Java</a> and <a href="https://codereview.stackexchange.com/q/261514/231235">Android APP FTP uploading file implementation in Java</a>. I am attempting to perform the download operation to specified FTP server in Android APP. The public class <code>FTPconnection</code> has been implemented for performing the download details and due to <a href="https://developer.android.com/reference/android/os/AsyncTask" rel="nofollow noreferrer"><em>AsyncTask was deprecated in API level 30</em></a>, I am attempting to use <code>java.util.concurrent</code> for FTP downloading file implementation.</p>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p>Project name: FTPDownloadFile</p>
</li>
<li><p><code>FTPconnection</code> class implementation</p>
<pre><code>package com.example.ftpdownloadfile;
import android.util.Log;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.net.UnknownHostException;
public class FTPconnection {
private native String getHostname();
private native String getUsername();
private native String getPassword();
private static String FTPHostName = "";
private static final int FTPPort = 21;
private static String FTPUsername = "";
private static String FTPPassword = "";
public FTPconnection()
{
FTPHostName = getHostname();
FTPUsername = getUsername();
FTPPassword = getPassword();
}
// Reference: https://stackoverflow.com/a/24605713/6667035
public Boolean downloadAndSaveFile(String filename, File localFile)
throws IOException {
String LOG_TAG = "FTPconnection_download";
FTPClient ftp = null;
try {
ftp = new FTPClient();
ftp.connect(FTPHostName, FTPPort);
Log.d(LOG_TAG, "Connected. Reply: " + ftp.getReplyString());
ftp.login(FTPUsername, FTPPassword);
Log.d(LOG_TAG, "Logged in");
ftp.setFileType(FTP.BINARY_FILE_TYPE);
Log.d(LOG_TAG, "Downloading");
ftp.enterLocalPassiveMode();
OutputStream outputStream = null;
boolean success = false;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(
localFile));
success = ftp.retrieveFile(filename, outputStream);
} finally {
if (outputStream != null) {
outputStream.close();
}
}
return success;
} finally {
if (ftp != null) {
ftp.logout();
ftp.disconnect();
}
}
}
}
</code></pre>
</li>
<li><p><code>ftpdownloadfile.cpp</code></p>
<pre><code>#include <jni.h>
#include <string>
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_ftpdownloadfile_FTPconnection_getHostname(JNIEnv *env, jobject thiz) {
std::string output = "Hostname";
return env->NewStringUTF(output.c_str());
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_ftpdownloadfile_FTPconnection_getUsername(JNIEnv *env, jobject thiz) {
std::string output = "Username";
return env->NewStringUTF(output.c_str());
}
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_ftpdownloadfile_FTPconnection_getPassword(JNIEnv *env, jobject thiz) {
std::string output = "Password";
return env->NewStringUTF(output.c_str());
}
</code></pre>
</li>
<li><p><a href="https://developer.android.com/reference/java/util/concurrent/Executor" rel="nofollow noreferrer"><code>ExecutorService</code></a> for new thread</p>
<pre><code>ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
showToast(threadName, Toast.LENGTH_SHORT);
FTPconnection ftpConnect = new FTPconnection();
final String LOG_TAG = "executor";
try {
String filename = "test.txt";
Log.v(LOG_TAG,"Preparing to download " + filename);
var result = ftpConnect.downloadAndSaveFile(filename, Paths.get(getApplicationInfo().dataDir + "/" + filename).toFile());
if (result == false) {
Log.v(LOG_TAG,"Fail to download " + filename + "!");
} else {
Log.v(LOG_TAG,"Download " + filename + " successfully!");
}
} catch (Exception ex) {
ex.printStackTrace();
}
});
</code></pre>
</li>
<li><p>User permission setting</p>
<pre><code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</code></pre>
</li>
<li><p><code>AndroidManifest.xml</code></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ftpdownloadfile">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.FTPDownloadFile">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
</manifest>
</code></pre>
</li>
<li><p><code>build.gradle</code></p>
<pre><code>plugins {
id 'com.android.application'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.ftpdownloadfile"
minSdk 26
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
cppFlags ''
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
externalNativeBuild {
cmake {
path file('src/main/cpp/CMakeLists.txt')
version '3.18.1'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
// https://mvnrepository.com/artifact/commons-net/commons-net
implementation group: 'commons-net', name: 'commons-net', version: '20030805.205232'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
</code></pre>
</li>
</ul>
<p><strong>Full Testing Code</strong></p>
<p><code>MainActivity.java</code> implementation:</p>
<pre><code>package com.example.ftpdownloadfile;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTPClient;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
static {
System.loadLibrary("ftpdownloadfile");
}
private static final int READ_EXTERNAL_STORAGE_CODE = 1;
private static final int WRITE_EXTERNAL_STORAGE_CODE = 2;
private static final int ACCESS_NETWORK_STATE_CODE = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE_CODE);
checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE_CODE);
checkPermission(Manifest.permission.ACCESS_NETWORK_STATE, ACCESS_NETWORK_STATE_CODE);
downloadProcess("test.txt");
mySleep(1000);
try {
BufferedReader fileReader = new BufferedReader(new FileReader(this.getApplicationInfo().dataDir + "/test.txt"));
String row;
while ((row = fileReader.readLine()) != null) {
showToast(row, Toast.LENGTH_SHORT);
}
fileReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void downloadProcess(final String filename) {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
showToast(threadName, Toast.LENGTH_SHORT);
FTPconnection ftpConnect = new FTPconnection();
final String LOG_TAG = "executor";
try {
Log.v(LOG_TAG,"Preparing to download " + filename);
var result = ftpConnect.downloadAndSaveFile(filename, Paths.get(getApplicationInfo().dataDir + "/" + filename).toFile());
if (result == false) {
Log.v(LOG_TAG,"Fail to download " + filename + "!");
} else {
Log.v(LOG_TAG,"Download " + Paths.get(getApplicationInfo().dataDir + "/" + filename) + " successfully!");
}
} catch (Exception ex) {
ex.printStackTrace();
}
});
}
private void mySleep(final long millis)
{
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showToast(@StringRes int res, int duration) {
showToast(getResources().getString(res), duration);
return;
}
private void showToast(final String textInput, int duration)
{
Context context = getApplicationContext();
CharSequence text = textInput;
// Reference: https://stackoverflow.com/a/12897386/6667035
runOnUiThread(() -> Toast.makeText(context, text, duration).show());
}
// Function to check and request permission.
public void checkPermission(@NonNull String permission, final int requestCode)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) == PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(MainActivity.this, new String[] { permission }, requestCode);
}
else {
if (BuildConfig.DEBUG) {
showToast("Permission already granted", Toast.LENGTH_SHORT);
}
}
}
}
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/260576/231235">Android APP connect to FTP server in Java</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/261514/231235">Android APP FTP uploading file implementation in Java</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>I am attempting to perform the download operation to specified FTP server in Android APP in this post.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T22:32:19.493",
"Id": "263644",
"Score": "2",
"Tags": [
"android",
"file",
"error-handling",
"network-file-transfer",
"ftp"
],
"Title": "Android APP FTP downloading file implementation in Java"
}
|
263644
|
<p>I am given a file named <code>profile1.data</code> that looks like this:</p>
<pre><code> zone luminosity
1 1 1359.019
2 2 1359.030
3 3 1359.009
4 4 1358.988
5 5 1358.969
6 6 1358.951
</code></pre>
<p>There are <em>thousands</em> of profiles in my working directory (named <code>profileNUMBER.data</code>). Every one of them has a unique value called a <code>phase</code> that I have beforehand (meaning there is the same number of phase values as there are profiles) and every one of them has 300 rows (thus 300 zones).</p>
<p>What I am doing with this data is plotting luminosity vs phase <em>for each zone</em>. For example, to create a luminosity vs phase plot of the first zone, I grab the luminosity value from every profile in the directory at zone 1. This is my first plot. Then I do the same for the other 299 zones. At the moment, I am accomplishing this through for loops in R.</p>
<pre><code>for (zone_num in 1:300) {
luminosities <- c()
for (prof_num in prof.idx$prof_num) {
prof.path <- file.path(cwd,log.directory.after.FA, paste0('profile', prof_num, '.data'))
if (!file.exists(prof.path)) next
#print(prof.path)
DF.profile <- read.table(prof.path, header=1, skip=5)
luminosity <- DF.profile$luminosity[zone_num]
luminosities <- c(luminosities, luminosity)
}
png(file.path(plot.set.dir, paste("Zone",zone_num,"Light_Curve.png",sep="_")), width = 750, height = 600)
par(mar=c(5,5,4,1)+.1)
plot(x=phases, y=luminosities, main=paste(sets[set],"Zone",zone_num ,"Light Curve",sep=" "), pch=3, col="purple",
xlab=expression("Phase"), ylab=expression("Luminosity " (L/L['\u0298'])), cex.main=2.0, cex.lab=1.50, ceb.axis=1.80)
dev.off()
}
</code></pre>
<p>This is not the entire code and there are some variables that you do not see the definition of, but the point is for you to see how I structured the solution using for loops. I'm particularly interested in how to use R's unique vectorized functions to speed this up.</p>
<p><strong>Edit 1</strong>
Link to profile folders:</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T06:46:55.960",
"Id": "520545",
"Score": "0",
"body": "vectorized functions are mostly for math not creating hundreds of plots...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T13:54:56.060",
"Id": "520563",
"Score": "0",
"body": "@minem Ok, would there still be anyway this can be improved to expedite plot creation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T20:17:50.607",
"Id": "520598",
"Score": "1",
"body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>As you haven't provided data or explanation what's <code>prof.idx$prof_num</code> I am guessing that's vector of file names (part of filename).\nThis could work:</p>\n<pre><code>prof_num <- prof.idx$prof_num # vector of names? if so, should work\nprof.path <- file.path(cwd,log.directory.after.FA, paste0('profile', prof_num, '.data')) # vectorized function\npathList <- prof.path[file.exists(prof.path)] # take those who exists\n\n# read data list\ndataList <- lapply(pathList, function(x) {\n DF.profile <- read.table(x, header=1, skip=5)\n # DF.profile\n DF.profile$luminosity\n})\n\n# plots:\nfor (zone_num in 1:300) {\n luminosities <- sapply(dataList, function(v) v[zone_num])\n png(file.path(plot.set.dir, paste("Zone",zone_num,"Light_Curve.png",sep="_")), width = 750, height = 600)\n par(mar=c(5,5,4,1)+.1)\n plot(x=phases, y=luminosities, main=paste(sets[set],"Zone",zone_num ,"Light Curve",sep=" "), pch=3, col="purple",\n xlab=expression("Phase"), ylab=expression("Luminosity " (L/L['\\u0298'])), cex.main=2.0, cex.lab=1.50, ceb.axis=1.80)\n dev.off()\n}\n</code></pre>\n<p>As I don't have the data to test I am not 100% sure that this will fork...\nBut from your code it seems that the biggest problem is that you are repeatedly reading the same files into R. This should be done once separately.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:12:25.477",
"Id": "520576",
"Score": "0",
"body": "As soon as it completes zipping, I'll send all the data as well as my entire code. Yes, `prof.idx` is a data frame read from a file in the directory that lists the number of profiles, and `prof.idx$prof_num` is the vector of file names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:14:15.183",
"Id": "520577",
"Score": "0",
"body": "@Woj this doesn't work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:14:50.207",
"Id": "520578",
"Score": "0",
"body": "@Woj https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:43:24.473",
"Id": "520591",
"Score": "0",
"body": "See edit 1 in post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T21:09:11.287",
"Id": "520600",
"Score": "0",
"body": "@Woj your full code is too convoluted for me to dig into and I wont download any data, but I believe you will be able to incorporate this into your code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T13:31:52.023",
"Id": "521255",
"Score": "0",
"body": "Please consider waiting with an answer until the question has been fixed. Now we can't allow the edit in the question because the answer has come in already, but the proper action would've been to close the question and leave a comment instead of answering it. There are *plenty* of clear, on-topic questions on this site that could use your experience where you won't have to guess at the intentions."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T14:20:57.273",
"Id": "263669",
"ParentId": "263649",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T22:51:21.687",
"Id": "263649",
"Score": "1",
"Tags": [
"r"
],
"Title": "R code for reading tabular data files and plotting light curves of modeled stars"
}
|
263649
|
<p>I’m writing backend code for a website, and I’ve been surprised by the fact that a URL’s path component isn’t normalized at all, retaining trailing and duplicate slashes (<code>"/foo" != "/foo/" != "/foo//" != "//foo/"</code>, etc.), so I wrote a function to rectify this, but I’m unsure if it’s a good solution, or if it’s just hacky and problematic.</p>
<pre class="lang-js prettyprint-override"><code>function normalizePath(path: string): string {
return path.replaceAll(/\/+/g, "/").replace(/\/+$/, "").replace(/^\/*/, "/")
}
</code></pre>
<p>Sample I/O:</p>
<pre><code>>> normalizePath("a")
<- "/a"
>> normalizePath("/a")
<- "/a"
>> normalizePath("a/")
<- "/a"
>> normalizePath("a/b")
<- "/a/b"
>> normalizePath("//a//b//")
<- "/a/b"
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-30T23:53:22.990",
"Id": "263652",
"Score": "0",
"Tags": [
"regex",
"typescript",
"url"
],
"Title": "Normalizing URL pathnames in TypeScript"
}
|
263652
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.