text
stringlengths
1
2.12k
source
dict
rust fn main() { let days = [ ("first", "A", "a", " partridge in a pear tree"), ("second", "T", "t", "wo turtle doves"), ("third", "T", "t", "hree French hens"), ("fourth", "F", "f", "our calling birds"), ("fifth", "F", "f", "ive gold rings"), ("sixth", "S", "s", "ix geese a-laying"), ("seventh", "S", "s", "even swans a-swimming"), ("eighth", "E", "e", "ight maids a-milking"), ("ninth", "N", "n", "ine ladies dancing"), ("tenth", "T", "t", "en lords a-leaping"), ("eleventh", "E", "e", "leven pipers piping"), ("twelfth", "T", "t", "welve drummers drumming") ]; for verse_no in 0..days.len() { let (day, _, _, _) = days[verse_no]; println!("On the {day} day of Christmas my true love sent to me"); for gift_no in 0..(verse_no+1) { let (_, upper, lower, rest) = days[gift_no]; match gift_no.cmp(&verse_no) { Ordering::Less => println!("{upper}{rest},"), Ordering::Equal => println!("And {lower}{rest}."), Ordering::Greater => unreachable!(), } } if verse_no != days.len()-1 { println!(""); } } } Comments? Answer: The Program Has a Bug Its output begins: On the first day of Christmas my true love sent to me And a partridge in a pear tree. On the second day of Christmas my true love sent to me A partridge in a pear tree, And two turtle doves. On the third day of Christmas my true love sent to me A partridge in a pear tree, Two turtle doves, And three French hens. When it should be something close to: On the first day of Christmas, my true love sent to me A partridge in a pear tree. On the second day of Christmas, my true love sent to me Two turtledoves and A partridge in a pear tree. On the third day of Christmas, my true love sent to me Three French hens, Two turtledoves and A partridge in a pear tree.
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust There are several equally-valid variations. This isn’t quite the one you wanted, but I encourage you to fix it so the first verse says “A partridge in a pear tree,” and later ones end in “And a partridge in a pear tree.” (This shouldn’t use a conditional branch on each iteration of a loop; see below.) Another variation you might try that lets you use sentence capitalization is “Four calling birds, three French hens, two turtledoves and a partridge in a pear tree,” all on a single line. Do what looks interesting to you! Factor out Functions Small functions, each doing one thing that’s easy to understand, are much nicer to work with. It also lets us move our variables out of main or the global scope to where they’ll be used. It also lets this code be called from somewhere else in the program than main. For example, let’s say we’ve got a function that begins: fn verse(n : usize) -> String { /* Returns the n-th verse of “The Twelve Days of Christmas,” followed by * a newline. */ The main function then simplifies to pub fn main() { print!("{}", verse(1)); for i in 2..=DAYS_OF_CHRISTMAS { print!("\n{}", verse(i)); } } There are other ways we could do it, but buffering each verse (or the output for each item in a batch) in a String, printing that, and then dropping it is a good compromise between buffering nothing and buffering the entire output of the program before printing anything. You can still print! every individual piece of the song, as you were doing, and this will eliminate all use of dynamic memory. So that isn’t a bad approach, just a different trade-off. Use Constants where Appropriate. In this toy program, it might seem silly to define const DAYS_OF_CHRISTMAS : usize = 12;
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust But let’s say you’ve got a program that could also do “The Twelve Joys of Mary” or “Thirty Days Hath September,” with the data for twelve months. Or anything else where the constant 12 has some other meaning. It now becomes very difficult to go through the program and update all of the instances of 12 that are supposed to be the number of verses in this song, and not any other 12 that appears in the source. Or to catch a typo like 21. In this case, it’s not totally implausible that the type of this constant might change, either. In this case, I picked usize because I kept your great idea of storing the data for each verse in an array, and in that case, its index should have type usize. But this is a small number that would fit in an i8, so a smaller type might be more convenient to work with. It’s also good practice to write constant functions and data when you can, because those optimize better and are more robust against bugs that modify program state, and have simple static lifetimes. Combining this and the last piece of advice, we can write this little function to return first, second, third, etc. as a &str: const fn ordinal(n : usize) -> &'static str { /* Returns an uncapitalized English ordinal number between 0 and 12. */ const ORDINALS : [&str; DAYS_OF_CHRISTMAS+1] = [ "zeroth", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ]; assert!(n < ORDINALS.len(), "Ordinal out of range."); // Always check for buffer overruns! return ORDINALS[n]; }
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust This is pretty similar to what you did, but now the ordinal string constants are only in scope for the one part of the program that needs to see them. You could also write a more general-purpose ordinal function that could be used for other purposes and call that. (Although, if it were fully general, able to return values like "one billion two hundred thirty-four million five hundred sixty-seven thousand eight hundred ninetieth", it would no longer be const because you would then be generating the result string dynamically.) Print the Lines of Each Verse in the Right Order There’s a good example of how to do this right above where you were reading, in Section 3.5 of the Rust Book. for number in (1..4).rev() A for loop iterates on an iterator, and in this case, within each verse, you want to iterate in reverse. So, where you now have for gift_no in 0..(verse_no+1) { This should be something like for gift_no in (0..=verse_no).rev() {
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust This should be something like for gift_no in (0..=verse_no).rev() { But see below: Make the Control Flow Work for You Currently, you use std::cmp::Ordering; and then match every verse to see if it is the first. This is unnecessarily complex. You know that this condition will be false for every repetition but the last, which will always be the gift with index 0. So you could actually just do your for loop from verse_no to 1, and then print the final line after the loop. This eliminates the unnecessary extra match on each iteration. Similarly, you currently test if verse_no != days.len()-1 on each iteration, duplicating the check at the top of the loop, to determine whether to print a second newline after each verses. I solve this, above, by printing the first verse separately, and then printing verses 2 through 12 with an extra newline before them. Or you might also print verses 1 through eleven in a loop, followed by an extra newline, and then the final verse on its own. Putting it All Together This example is simplified compared to your version. That leaves you some space to tweak it in the ways you wanted, such as making the last line of each verse properly display either “A partridge in a pear tree.” or “And a partridge in a pear tree.” const DAYS_OF_CHRISTMAS : usize = 12; const fn ordinal(n : usize) -> &'static str { /* Returns an uncapitalized English ordinal number between 0 and 12. */ const ORDINALS : [&str; DAYS_OF_CHRISTMAS+1] = [ "zeroth", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ]; assert!(n < ORDINALS.len(), "Ordinal out of range."); // Always check for buffer overruns! return ORDINALS[n]; }
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust fn verse(n : usize) -> String { /* Returns the n-th verse of “The Twelve Days of Christmas,” followed by * a newline after. */ assert!( n > 0 && n <= DAYS_OF_CHRISTMAS, "There are only twelve days of Christmas." ); const GIFTS : [&str; DAYS_OF_CHRISTMAS] = [ "A partridge in a pear tree.", "Two turtledoves and", "Three French hens,", "Four calling birds,", "Five golden rings,", "Six geese a-laying,", "Seven swans a-swimming,", "Eight maids a-milking,", "Nine ladies dancing,", "Ten lords a-leaping", "Eleven pipers piping,", "Twelve drummers drumming," ]; let mut result = String::from("On the ") + ordinal(n) + " day of Christmas, my true love sent to me\n"; for i in (0..n).rev() { result += GIFTS[i]; result += "\n"; } return result; } pub fn main() { print!("{}", verse(1)); for i in 2..=DAYS_OF_CHRISTMAS { print!("\n{}", verse(i)); } } Possible Improvements There are other, more advanced variations you could try on verses, such as replacing the loop in verses with a collect_into or fold operation on the iterator. Another way to write verses in a functional style (eliminating all mutable variables and side-effects), for example, would be: fn verse(n : usize) -> String { /* Returns the n-th verse of “The Twelve Days of Christmas,” followed by * a newline after. */ assert!( n > 0 && n <= DAYS_OF_CHRISTMAS, "There are only twelve days of Christmas." );
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust const GIFTS : [&str; DAYS_OF_CHRISTMAS] = [ "A partridge in a pear tree.", "Two turtledoves and", "Three French hens,", "Four calling birds,", "Five golden rings,", "Six geese a-laying,", "Seven swans a-swimming,", "Eight maids a-milking,", "Nine ladies dancing,", "Ten lords a-leaping", "Eleven pipers piping,", "Twelve drummers drumming," ]; let prefix = String::from("On the ") + ordinal(n) + " day of Christmas, my true love sent to me\n"; return (0..n).rev() .fold( prefix, |s, i| s + GIFTS[i] + "\n" ); } There’s another useful optimization you could make. Because the entire song is composed of twenty-seven string constant building blocks, and the verses all put them together in different ways, you could have each verse collect references to the chunks in a Vec<&'static str>. This would still use a little bit of dynamic memory, but it would save you from making a deep copy of the entire contents of the song. const DAYS_OF_CHRISTMAS : usize = 12; const fn ordinal(n : usize) -> &'static str { /* Returns an uncapitalized English ordinal number between 0 and 12. */ const ORDINALS : [&str; DAYS_OF_CHRISTMAS+1] = [ "zeroth", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth" ]; assert!(n < ORDINALS.len(), "Ordinal out of range."); // Always check for buffer overruns! return ORDINALS[n]; } fn verse(n : usize) -> Vec<&'static str> { /* Returns the n-th verse of “The Twelve Days of Christmas,” in the form of * a collection of references to the building-blocks of the song. */ assert!( n > 0 && n <= DAYS_OF_CHRISTMAS, "There are only twelve days of Christmas." );
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust const GIFTS : [&str; DAYS_OF_CHRISTMAS] = [ "A partridge in a pear tree.\n", "Two turtledoves and\n", "Three French hens,\n", "Four calling birds,\n", "Five golden rings,\n", "Six geese a-laying,\n", "Seven swans a-swimming,\n", "Eight maids a-milking,\n", "Nine ladies dancing,\n", "Ten lords a-leaping\n", "Eleven pipers piping,\n", "Twelve drummers drumming,\n" ]; let mut result = Vec::from([ "On the ", ordinal(n), " day of Christmas, my true love gave to me\n" ]); for i in (0..n).rev() { result.push(GIFTS[i]); } return result; } pub fn main() { for chunk in verse(1) { print!( "{}", chunk ); } for i in 2..=DAYS_OF_CHRISTMAS { print!("\n"); for chunk in verse(i) { print!( "{}", chunk ); } } } ```
{ "domain": "codereview.stackexchange", "id": 44278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
python, web-scraping Title: Python web scraper for Amazon customer reviews Question: I'm new to web scraping and tried building a web scraper for Amazon customer reviews. The program works fine as is but I wanted to improve the design and get some feedback. The basic idea was to scrape customer review contents on Amazon product review pages using specific URL structures. 1. URL to search for product names: https://www.amazon.com/s?k={product_name} If I wanted to search for "Iphone 14", then the product query I provide would be "iphone+14" in the URL above. 2. To search for products over multiple pages, the URL would be: https://www.amazon.com/s?k={product_name}&page={n} 3. Each product has a unique identifier assigned (called ASIN), and each product search page lists ASINs embedded in "div" tag for product names. Customer reviews are on a separate page with ASIN in the URL. https://www.amazon.com/product-reviews/{ASIN} Not all the reviews are displayed in one product review page. To search for reviews over multiple pages, the URL used is as follows: https://www.amazon.com/product-reviews/{ASIN}?pageNumber={n} Concerns: I tried using map() function to loop over queries on multiple pages. And it led to nested lists which I had to flatten using reduce(operator.iconcat, ...). Would it be better to just use list comprehension? Or any other suggestions? For instance, in get_prod_name(): ... pages = range(start, end + 1) query = list(map(lambda x: query + f"&page={str(x)}", pages)) html_raw = list(map(lambda x: getpage(x, "item"), query)) html_tag = list(map(lambda x: x.find_all("span", class_ = "a-size-medium a-color-base a-text-normal"), html_raw)) html_tag = reduce(operator.iconcat, html_tag) # flatten the ResultSet products = list(map(lambda x: x.text, html_tag)) ... Some of the results from get_reviews() had text "the media could not be loaded." I don't quite understand why this is happening.
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, web-scraping I'm very much open to any criticism and thank you guys in advance for helping! Code: import requests import operator from bs4 import BeautifulSoup from functools import reduce # global variables BASE_URL = "https://www.amazon.com/" HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36", "Accept-Language": "en-US, en;q=0.9"} # user defined functions def getpage(query, url_type): """ A helper function to create a BeautifulSoup object. Input query string and specify the url type. The goal is to return html code of a page. query: str input. Accepts search query by "item name" or "asin" url_type: specify the url type for the search you're doing. options = "item", "asin" """ if url_type == "item": url = BASE_URL + "s?k=" + query elif url_type == "asin": url = BASE_URL + "product-reviews/" + query else: return "Error: url type unsupported. Choose from the following 'item', 'asin'" response = requests.get(url, headers = HEADERS) if response.status_code == 200: return BeautifulSoup(response.text, "html.parser") else: return "Error: status_code != 200" def get_prod_name(query, start = 1, end = None): """ query: string input. search items on amazon in browser url tab. e.g. if you wanted to search for "iphone 13", it would be "iphone+13" start: integer input. starting page number, default = 1 end: integer input. ending page number, default = None returns a list of product names from search """ if end == None: query = query + f"&page={str(start)}" html_raw = getpage(query, "item") products = html_raw.find_all("span", class_ = "a-size-medium a-color-base a-text-normal") return list(map(lambda x: x.text, products))
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, web-scraping else: pages = range(start, end + 1) query = list(map(lambda x: query + f"&page={str(x)}", pages)) html_raw = list(map(lambda x: getpage(x, "item"), query)) html_tag = list(map(lambda x: x.find_all("span", class_ = "a-size-medium a-color-base a-text-normal"), html_raw)) html_tag = reduce(operator.iconcat, html_tag) # flatten the ResultSet products = list(map(lambda x: x.text, html_tag)) return products def get_asin(query, start = 1, end = None): """ ***NEED QUERY FORMAT ITEMS TO RETRIEVE ASIN*** query: string input. search items on amazon in browser url tab. e.g. if you wanted to search for "iphone 13", it would be "iphone+13" start: integer input. starting page number, default = 1 end: integer input. ending page number, default = None returns a list of asin associated with the items from search """ if end == None: query = query + f"&page={str(start)}" html_raw = getpage(query, "item") html_tag = html_raw.find_all("div", class_ = "s-result-item s-asin sg-col-0-of-12 sg-col-16-of-20 sg-col s-widget-spacing-small sg-col-12-of-16") return list(map(lambda x: x.attrs["data-asin"], html_tag)) else: pages = range(start, end + 1) query = list(map(lambda x: query + f"&page={str(x)}", pages)) html_raw = list(map(lambda x: getpage(x, "item"), query)) html_tag = list(map(lambda x: x.find_all("div", class_ = "s-result-item s-asin sg-col-0-of-12 sg-col-16-of-20 sg-col s-widget-spacing-small sg-col-12-of-16"), html_raw ) ) html_tag = reduce(operator.iconcat, html_tag) # flatten the ResultSet asin_list = list(map(lambda x: x.attrs["data-asin"], html_tag)) return asin_list
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, web-scraping return asin_list def get_reviews(asin: list, start = 1, end = None): """ asin: list input. a list of ASIN start: integer input. starting page number, default = 1 end: integer input. ending page number, default = None returns individual review contents of a product-review page. """ if end == None: query = list(map(lambda x: x + f"?pageNumber={str(start)}", asin)) html_raw = list(map(lambda x: getpage(x, "asin"), query)) html_tag = list(map(lambda x: x.find_all("span", attrs = {"data-hook": "review-body"}), html_raw)) html_tag = reduce(operator.iconcat, html_tag) # flatten the ResultSet reviews = list(map(lambda x: x.text, html_tag)) reviews = [r.strip("\n") for r in reviews] return reviews else: pages = range(start, end + 1) queries = [] for p in pages: for id in asin: query = id + f"?pageNumber={str(p)}" queries.append(query) html_raw = list(map(lambda x: getpage(x, "asin"), queries)) html_tag = list(map(lambda x: x.find_all("span", attrs = {"data-hook": "review-body"}), html_raw)) html_tag = reduce(operator.iconcat, html_tag) # flattent the ResultSet reviews = list(map(lambda x: x.text, html_tag)) reviews = [r.strip("\n") for r in reviews] return reviews ### test # search_query = "iphone+14" # print(get_prod_name(search_query, 1, 3)) # IDs = get_asin(search_query, 1, 3) # print(get_reviews(IDs, 1, 3))
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, web-scraping # IDs = get_asin(search_query, 1, 3) # print(get_reviews(IDs, 1, 3)) Answer: Your code is pretty clean, you implement docstrings and it seems easy enough to read. You do have 1 extra indentation level, which I will assume that it is a copy-paste-format error. However... Bugs I found 2 bugs that are easy to catch. getpage returns strings Here's the code in question: # user defined functions def getpage(query, url_type): """ A helper function to create a BeautifulSoup object. Input query string and specify the url type. The goal is to return html code of a page. query: str input. Accepts search query by "item name" or "asin" url_type: specify the url type for the search you're doing. options = "item", "asin" """ if url_type == "item": url = BASE_URL + "s?k=" + query elif url_type == "asin": url = BASE_URL + "product-reviews/" + query else: return "Error: url type unsupported. Choose from the following 'item', 'asin'" response = requests.get(url, headers = HEADERS) if response.status_code == 200: return BeautifulSoup(response.text, "html.parser") else: return "Error: status_code != 200" The first sentence of the docstring reads: A helper function to create a BeautifulSoup object. This is obviously a lie! The 6th and last lines return a string. Return a BeautifulSoup or consider throwing a "proper" exception. But why is this bad? This is bad because you're using the return value directly. Here's an example taken from get_prod_name: # [...] html_raw = getpage(query, "item") products = html_raw.find_all("span", class_ = "a-size-medium a-color-base a-text-normal") # [...] This will throw an exception because you're accessing the method find_all on a string value. This method doesn't exist.
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, web-scraping Input handling More like, the lack of input handling... You expect that the string is already URL-formatted. Yeah, you do talk about this in the docstring, but, this is error prone and the reason why I classify it as a bug. Just imagine trying to find HB #2 pencils with your code, and having to manually encode the space and the pound symbol. You're putting the "user" in an error-prone situation because of pure lazyness. All you have to do is to take the input and use requests.utils.quote on it. I found this on here: https://stackoverflow.com/questions/46783078/uri-encoding-in-python-requests-package#comment126847571_46783596 You just need to go to the functions get_prod_name and get_asin and add this as the first line: query = requests.utils.quote(query, safe='') But why add safe=''? As explained in the linked comment, this function assumes that / is a safe character (as it is just the function urllib.parse.quote). Here's an example: Leaving the bugs behind, now it's time to talk about ... Weird things Strange string usage Inside the function get_prod_name, you have the following: query = query + f"&page={str(start)}" Inside a formatted string, you don't need to use the str function, as it is implicitly converted to string. And then, you're concatenating it, which is kinda weird too. You can just do this: query = f"{query}&page={start}" In this case, maybe you should just use the += operator: query += f"&page={start}" Both will have the same exact effect. Repeated code You have quite a lot of repeated code, for apparently no reason at all... Lets analyze the code inside the get_reviews function: # asin: list, start = 1, end = None # [...]
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, web-scraping if end == None: query = list(map(lambda x: x + f"?pageNumber={str(start)}", asin)) html_raw = list(map(lambda x: getpage(x, "asin"), query)) html_tag = list(map(lambda x: x.find_all("span", attrs = {"data-hook": "review-body"}), html_raw)) html_tag = reduce(operator.iconcat, html_tag) # flatten the ResultSet reviews = list(map(lambda x: x.text, html_tag)) reviews = [r.strip("\n") for r in reviews] return reviews else: pages = range(start, end + 1) queries = [] for p in pages: for id in asin: query = id + f"?pageNumber={str(p)}" queries.append(query) html_raw = list(map(lambda x: getpage(x, "asin"), queries)) html_tag = list(map(lambda x: x.find_all("span", attrs = {"data-hook": "review-body"}), html_raw)) html_tag = reduce(operator.iconcat, html_tag) # flattent the ResultSet reviews = list(map(lambda x: x.text, html_tag)) reviews = [r.strip("\n") for r in reviews] return reviews So, what's the difference between the code in the ifs? I compared both, and this is the result: The way the queries are built changes The way you call getpage The spelling of "flatten" (vs. "flattent") All the other lines are REPEATED, exactly byte by byte. You can just write this: if end == None: html_raw = list(map(lambda x: getpage(f"{x}?pageNumber={start}", "asin"), asin)) else: pages = range(start, end + 1) queries = [] for p in pages: for id in asin: queries.append(f"{id}?pageNumber={p}") html_raw = list(map(lambda x: getpage(x, "asin"), queries)) html_tag = list(map(lambda x: x.find_all("span", attrs = {"data-hook": "review-body"}), html_raw)) html_tag = reduce(operator.iconcat, html_tag) # flatten the ResultSet reviews = list(map(lambda x: x.text, html_tag)) reviews = [r.strip("\n") for r in reviews] return reviews
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, web-scraping return reviews I also removed some (kinda) useless maps, but if you want to add them back, feel free to do so. However, it can be reduced a little more, if you're okay with changing variables as well: if end == None: queries = list(map(lambda x: f"{x}?pageNumber={start}", asin)) else: queries = [] for page in range(start, end + 1): for id in asin: queries.append(f"{id}?pageNumber={page}") html_raw = list(map(lambda x: getpage(x, "asin"), queries)) html_tag = list(map(lambda x: x.find_all("span", attrs = {"data-hook": "review-body"}), html_raw)) html_tag = reduce(operator.iconcat, html_tag) # flatten the ResultSet reviews = list(map(lambda x: x.text, html_tag)) reviews = [r.strip("\n") for r in reviews] return reviews I've removed the variables query and pages, and reduced a repeated line. I'm sure there's better ways to re-write this, but this is just to get your feet wet and a few ideas on what to do. The strange pick of maps everywhere On the above code, you do use the pattern list(map(lambda x: x)) a lot. Try using list comprehensions, like this: # old: html_raw = list(map(lambda x: getpage(x, "asin"), queries)) html_raw = [getpage(x, "asin") for x in queries] Or, a better example: # old: reviews = list(map(lambda x: x.text, html_tag)) # reviews = [r.strip("\n") for r in reviews] reviews = [x.text.strip("\n") for x in html_tag] This should work with BeautifulSoup, as the documentation contains the following example, in the first page: One common task is extracting all the URLs found within a page’s tags: for link in soup.find_all('a'): print(link.get('href')) # http://example.com/elsie # http://example.com/lacie # http://example.com/tillie The name choices There are some names that are extremely puzzling:
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, web-scraping The name choices There are some names that are extremely puzzling: getpage - gives you a BeautifulSoup object or a string html_raw - it's either a BeautifulSoup object or a string (no HTML here) html_tag - has a list of HTML elements, not tags products - it's either a list of HTML elements or a list of product names Please, try to come up with better names. There's a lot more to say about the code, but, I don't feel comfortable talking about those points. I do have a limited python knowledge, and I just hope I've helped enough for others to pick and carry on from here (or even see any mistakes I've made and point them out to me as well). Any questions, just throw them in the comments.
{ "domain": "codereview.stackexchange", "id": 44279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, web-scraping", "url": null }
python, python-3.x, game Title: Slot Machine Project Question: I am familiar with Python but recently I have been trying to solidify my skills as a Python developer. I decided to do a project that would help me build some skills using the fundamentals of the language (limited modules, mostly just vanilla Python). I did this Slot Machine program, inspired by Tech with Tim, and I was wondering if I could get some feedback on my code about best practices in Python and improvements I can make to make my code more production-level. CODE: # Author: Kade Carlson # Date: 12/30/2022 # Slot Machine program that is going to be used to test my skills. Slot machine of 3 lines, players can bet on a chosen number of # lines from 1 to 3. If a row has all the same symbols then it's a win and their bet is multiplied by that symbol's value. # Imports import os import random # Constants MAX_BET = 1000 MIN_BET = 10 SYMBOLS = ["@", "#", "%", "&"] SYMBOL_VALUES = {"@": 2, "#": 3, "%": 5, "&": 7} def set_balance(): """Ask the user for the amount of money that they would like to deposit into their account.""" balance = int(input("How much would you like to deposit?: $")) if balance <= 0: os.system("cls") print("Please input an amount greater than $0...") balance = set_balance() return balance def set_bet(balance): """Ask the user for the amount of money that they would like to bet and on how many lines.""" bet = int(input("How much would you like to bet?: $")) if not MIN_BET <= bet <= MAX_BET: os.system("cls") print(f"Please bet an amount between ${MIN_BET} and ${MAX_BET}") bet = set_bet(balance) if bet > balance: os.system("cls") print(f"Not enough money. Your balance is ${balance}.") bet = set_bet(balance) return bet
{ "domain": "codereview.stackexchange", "id": 44280, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game", "url": null }
python, python-3.x, game return bet def set_lines(balance, bet): """Ask the user for how many lines they want to bet on.""" lines = int(input("How many lines do you want to bet on (1-3)?: ")) if not 1 <= lines <= 3: os.system("cls") print("You must bet on either 1, 2, or 3 lines") lines = set_lines(balance, bet) if bet * lines > balance: os.system("cls") print(f"Not enough money. Your balance is ${balance}. Your bet is ${bet}.") lines = set_lines(balance, bet) return lines # Print the slot machine def print_machine(): """Prints the slot machine with the symbols in a 3x3 format.""" row = [] copy_row = [] for i in range(9): row.append(random.choice(SYMBOLS)) if (i + 1) % 3 == 0: print("", end="|") for symbol in row: print(symbol, end="|") print() print("-------") copy_row.append(row) row = [] return copy_row def get_symbol_value(symbol): """Returns the symbol value that the bet is multiplied by.""" for key, value in SYMBOL_VALUES.items(): if key == symbol: return value # Check for wins, add winnings to deposit balance def check_winnings(rows, bet, balance): for row in rows: for symbol in row: if symbol != row[0]: balance -= bet break else: balance += bet * get_symbol_value(symbol) return balance def game(balance): """This function contains the game logic""" bet = set_bet(balance) lines = set_lines(balance, bet) print(f"Your balance is ${balance}") print(f"You bet ${bet}") print(f"You bet on {lines} lines for a total bet of ${bet * lines}") rows = print_machine() new_balance = check_winnings(rows[0:lines], bet, balance) print(f"Your new balance is: ${new_balance}") return new_balance
{ "domain": "codereview.stackexchange", "id": 44280, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game", "url": null }
python, python-3.x, game return new_balance def main(): balance = set_balance() new_balance = game(balance) query = input( "Press q to quit, d to deposit more, or any other key to make another bet: " ) while query != "q": if new_balance < MIN_BET: query = input( f"Balance below minimum bet (${MIN_BET}). Press q to quit or d to deposit more: " ) if query != "q" or query != "d": print("Can't bet more. Bye") break if query == "d": new_balance += set_balance() print(f"Your new balance is ${new_balance}") game(new_balance) else: game(new_balance) query = input( "Press q to quit, d to deposit more, or any other key to make another bet: " ) if __name__ == "__main__": main() Answer: Some of the initial comment lines look like they should be a module """docstring""". The os.system() call is expensive and non-portable. You might assign cls = "\x1b[2J" and print it. Or import ansi and use erase. Break out a def cls(): helper, since you use it several times. balance = set_balance() That chews up stack space each time you call yourself. Prefer a while loop instead. The get_symbol_value function is insane. It should just be return SYMBOL_VALUES.get(symbol), if you bother to define it at all. Also, if not found, the current code falls off the end and returns None. Not clear if that was intended, since neither the docstring nor optional type hinting addresses that topic. If a value is always supposed to be found, then use return SYMBOL_VALUES[symbol]. That way you'll get a nice helpful diagnostic error if it turns out that symbol is not present. # Check for wins, add winnings to deposit balance
{ "domain": "codereview.stackexchange", "id": 44280, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game", "url": null }
python, python-3.x, game # Check for wins, add winnings to deposit balance You were doing great on docstrings, you were killing it. And now, bury it in a comment? No, no, promote this to a docstring, please. And nuke the # Print the slot machine comment, as it isn't telling us anything new. def print_machine(): ... return copy_row Hmmm, the identifier suggests that we evaluate for side effects, for printing, yet we're also computing some cool return value?!? Better document what that value is, please! This seems to be mis-named: def set_balance(): That is, we're maintaining a balance. But this function comes up with a value that will be added to the balance. It's not like it sets it. We commonly encounter getters and setters, named get_foo() and set_foo(). This function is not one of those. Overall, it looks pretty good, no big maintenance surprises. Consider breaking out the balance, and the slot machine, into separate classes.
{ "domain": "codereview.stackexchange", "id": 44280, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game", "url": null }
c++, matrix Title: Calculate determinant of a matrix using cofactor expansion Question: I'm using the following two functions to calculate the determinant of A. Would this code be considered to have an asymptotic time complexity of O(n³)? The recursion is throwing me off, but I think that it would, since it would end up looking something like: n³ + n³ + ... based on however many cofactors of the original are needed. void MatrixOps::cofactor(const std::vector<Entries>& A, std::vector<Entries>& C, int32_t n, int32_t k){ for (int i = 1 ; i < n ; i++){ // never take row 1 for (int j = 0 ; j < n ; j++){ // decide which col not to take if (j == k) continue; else C.push_back(A[i*n + j]); // very efficient } } } Entries MatrixOps::determinant(const std::vector<Entries> & A, const int32_t n){ if (1 == n) return A[0]; if (2 == n) return (A[0]*A[3] - A[1] * A[2]); Entries determinant = 0.0; int32_t sign = 1; vector<Entries> C; C.reserve((n-1)*(n-1)); for (int k = 0 ; k < n ; k++){ cofactor(A, C, n, k); determinant += sign * A[k] * MatrixOps::determinant(C, n-1); sign = -sign; C.clear(); } return determinant; } Answer: It's much worse than cubic time. At every "level" of the recursion, there are n recursive calls to a determinant of a matrix that is smaller by 1: T(n) = n * T(n - 1)
{ "domain": "codereview.stackexchange", "id": 44281, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, matrix", "url": null }
c++, matrix I left a bunch of things out there (which if anything means I'm underestimating the cost) to end up with a nicer formula: n * (n - 1) * (n - 2) ... which you probably recognize as n!. Cofactor expansion, or Laplace expansion, which is what this algorithm is, is rarely used computationally for that reason. There are other algorithms that compute the determinant that do run in cubic time, for example the Bareiss algorithm (suitable for integers, but be careful with overflow) or LU decomposition followed by taking the product of the entries on the diagonal (not very integer-friendly).
{ "domain": "codereview.stackexchange", "id": 44281, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, matrix", "url": null }
c, memory-management Title: C Arena (pool allocator) Question: I wrote a pool allocator (Arena) for a compiler I'm writing. My use case for this allocator is for storing the parse tree because it allows me to free all the memory at once, so I don't need to keep a reference to each node (which makes the code and logic a big mess). The implementation uses a singly linked list of blocks. For each block more memory than needed is allocated, and then the "tail" memory is used for allocating. To align the allocated memory I used union align (a union with types that have the strictest alignment requirements according to the book), a trick I learned from the book C Interfaces and Implementations. The union header is for calculating the aligned size of the Arena struct. The error if malloc() fails was reported using my compiler's error reporting code, so I replaced it with an fprintf(stderr, ...) call to report the error, and an exit(1) call to stop the execution of the program. I'm aware that using an existing library would most likely be better, but as I'm writing the compiler for learning purposes, I want to implement all the data structures I use as an exercise. Interface: #ifndef ARENA_H #define ARENA_H #include <stddef.h> // size_t // The default block size is 10K #define ARENA_DEFAULT_BLOCK_SIZE 10 * 1024 typedef struct block Block; typedef struct arena { Block *blocks; } Arena; void arenaInit(Arena *a); void arenaFree(Arena *a); void *arenaAlloc(Arena *a, size_t size); void *arenaCalloc(Arena *a, size_t nmemb, size_t size); #endif // ARENA_H Implementation: #include <stdlib.h> // malloc(), free() #include <string.h> // memset() #include "Arena.h" typedef struct block { struct block *prev; size_t size, used; char data[]; } Block; union align { int i; long l; long *lp; void *p; void (*fp)(void); float f; double d; long double ld; }; union header { Arena arena; union align a; };
{ "domain": "codereview.stackexchange", "id": 44282, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, memory-management", "url": null }
c, memory-management union header { Arena arena; union align a; }; static inline Block *new_block(size_t size, Block *prev) { Block *b = malloc(sizeof(union header) + size); // In my compiler, the following check uses the internal error // reporting system. I replaced it with fprintf() and exit() calls. if(b == NULL) { fprintf(stderr, "Error: Arena: new_block(): failed to allocate %zu bytes.\n", size); exit(1); } b->size = size; b->used = 0; b->prev = prev; return b; } static inline void free_blocks(Block *b) { while(b) { Block *prev = b->prev; free(b); b = prev; } } void arenaInit(Arena *a) { a->blocks = new_block(ARENA_DEFAULT_BLOCK_SIZE, NULL); } void arenaFree(Arena *a) { free_blocks(a->blocks); a->blocks = NULL; } void *arenaAlloc(Arena *a, size_t size) { size = (size + sizeof(union align) - 1) / sizeof(union align) * sizeof(union align); if(a->blocks->used + size > a->blocks->size) { // All blocks have at least 10K of memory space. a->blocks = new_block(size + ARENA_DEFAULT_BLOCK_SIZE, a->blocks); } a->blocks->used += size; return (void *)(a->blocks->data + a->blocks->used - size); } void *arenaCalloc(Arena *a, size_t nmemb, size_t size) { void *p = arenaAlloc(a, nmemb * size); memset(p, 0, nmemb * size); return p; } Answer: #include <stddef.h> // size_t This is my personal pet peeve, but comments after preprocessor instructions are non standard. All preprocessor in existence can handle it; but since I once needed to write one, I cringe little inside when I see this. // The default block size is 10K #define ARENA_DEFAULT_BLOCK_SIZE 10 * 1024 Is there a good reason why the default block size must be in the header? typedef struct arena { Block *blocks; } Arena; void arenaInit(Arena *a);
{ "domain": "codereview.stackexchange", "id": 44282, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, memory-management", "url": null }
c, memory-management typedef struct arena { Block *blocks; } Arena; void arenaInit(Arena *a); Have you considered changing the API to hide the implementation to Arena? As in Arena* arenaInit(). This has the benefit that you could change the implementation while remaining ABI compatible. The obvious downside is that you would not he able to put it on the stack; but IMHO this should not be that big of a deal. #include <stdlib.h> // malloc(), free() #include <string.h> // memset() #include "Arena.h" Unless you are forced to do so (e.g. precompiled headers), you should include the matching header first. This makes the compiler check for you to be sure the header compiles on it's own. typedef struct block { struct block *prev; size_t size, used; char data[]; } Block; size and used should be put on their own line and have their own type. Technically not wrong, but I find defining an array to have a pointer feels wrong. I would prefer using char* data. union header { Arena arena; union align a; }; static inline Block *new_block(size_t size, Block *prev) { Block *b = malloc(sizeof(union header) + size); // ... b->size = size; b->used = 0; b->prev = prev; return b; } I understand that you allocate the header with alignment hack, plus the size of the requested data; what I don't understand is why use the Arena and not Block. I think this makes size off by 2*size_t. Here I think it would be beneficial if the block size is a power of two. Most OS allocators will provide a power of two block anyway. (Or multiple of power of two for large blocks.) This means there is a chance that it would create less waste. This is a mater of taste, but using arguments as variables may not be the best idea. (Applies to all other instances.) void *arenaAlloc(Arena *a, size_t size) { size = (size + sizeof(union align) - 1) / sizeof(union align) * sizeof(union align);
{ "domain": "codereview.stackexchange", "id": 44282, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, memory-management", "url": null }
c, memory-management I think you can improve readability by providing an function that does the alignment. You probably should also get the sizeof one and use that. Not for performance reasons but readability. Consider the following: static inline size_t align_size(size_t size) { static const size_t a = sizeof(union align); return (size + a - 1) / a * a; } void *arenaAlloc(Arena *a, size_t size) { size = align_size(size); // ... } if(a->blocks->used + size > a->blocks->size) { // All blocks have at least 10K of memory space. a->blocks = new_block(size + ARENA_DEFAULT_BLOCK_SIZE, a->blocks); } I think the size + ARENA_DEFAULT_BLOCK_SIZE is wrong here. You are adding 10k to a random size resulting in lots of differently sized blocks. I would rather use max(size, ARENA_DEFAULT_BLOCK_SIZE) or just pass size to new_block and then let that round up the size to ARENA_MIN_BLOCK_SIZE (of 10k). a->blocks->used += size; return (void *)(a->blocks->data + a->blocks->used - size); } This is minor, but I would rather take the resulting pointer and return that instead of first adding size and then subtracting it again. Here mere mortals like me can immediately understand what is happening: void* result = (void *)(a->blocks->data + a->blocks->used); a->blocks->used += size; return result;
{ "domain": "codereview.stackexchange", "id": 44282, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, memory-management", "url": null }
c++, memory-management, c++17 Title: Multiple containers share a single memory resource Question: In my project, I'm trying to use the std::pmr allocator and monotonic_buffer_resource. I'm using vector in various classes, and I need to use the same resource in all of them. I created a separate free function that returns the resource pointer and used it while declaring the vectors. Here is the code #include <memory_resource> #include <vector> #include <array> std::pmr::monotonic_buffer_resource *getMemoryResource() { static std::array<std::byte, 100000> buffer; static std::pmr::monotonic_buffer_resource resource{buffer.data(), buffer.size()}; return &resource; } struct JsonData { std::pmr::vector<int> data{getMemoryResource()}; }; struct XMLData { std::pmr::vector<char> data{getMemoryResource()}; }; Is there anything I can do to improve the code, especially getMemoryResource function? Answer: Since there is so little code to review I only have one observation to make: Magic Numbers There is a Magic Numbers in the getMemoryResource() function (100000), it might be better to create a symbolic constant for it to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier. Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
{ "domain": "codereview.stackexchange", "id": 44283, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, memory-management, c++17", "url": null }
performance, rust, lexical-analysis Title: lexer for programming languages in rust Question: I'm relatively new to rust, so you don't need to go easy on the criticism. right now, this lexes 1MB of text (well, trims a 1MB-long word) in 30ms. is there any way I can make this faster? cursor.rs: use std::str::Chars; #[derive(Debug)] pub struct Cursor<'a> { peek: Option<char>, pub chars: Chars<'a>, pub pos: usize, pub row: usize, pub col: usize } impl<'a> Cursor<'a> { pub fn new(text: &'a str) -> Self { let mut chars = text.chars(); Self { peek: chars.next(), chars, pos: 0, row: 1, col: 0, } } pub fn next(&mut self) -> Option<char> { let peek = self.peek?; if peek == '\n' { self.col = 1; self.row += 1; } else { self.col += 1; } self.pos += peek.len_utf8(); self.peek = self.chars.next(); Some(peek) } pub fn peek_is<F: FnOnce(char) -> bool>(&mut self, fun: F) -> bool { self.peek.map_or(false, fun) } #[inline] pub fn peeking(&mut self, ch: char) -> bool { self.peek == Some(ch) } pub fn next_if<F: FnOnce(char) -> bool>(&mut self, fun: F) -> Option<char> { if self.peek_is(fun) { self.next() } else { None } } } lexer.rs: use crate::cursor::Cursor; pub enum TokenKind<'a> { Ident(&'a str), Num(&'a str), Str(String) } pub struct Lexer<'a> { text: &'a str, pub cursor: Cursor<'a> } impl<'a> Lexer<'a> { pub fn new<T: Into<&'a str>>(text: T) -> Self { let text = text.into(); Self { text, cursor: Cursor::new(text) } }
{ "domain": "codereview.stackexchange", "id": 44284, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, rust, lexical-analysis", "url": null }
performance, rust, lexical-analysis #[inline] pub fn token<F: FnOnce(char) -> bool + Copy>(&mut self, fun: F) -> &'a str { let pos = self.cursor.pos; while self.cursor.peek_is(fun) { self.cursor.next(); } &self.text[pos..self.cursor.pos] } pub fn trim_ident(&mut self) -> &'a str { self.token(|x| x.is_alphanumeric() || x == '_') } pub fn trim_integer(&mut self) -> &'a str { self.token(char::is_numeric) } } // impl<'a> Iterator for Lexer<'a> { // type Item = TokenKind<'a>; // // fn next(&mut self) -> Option<TokenKind<'a>> { // todo!() // } // } lib.rs: #![allow(unused)] pub mod cursor; pub mod lexer; pub use lexer::*; #[cfg(test)] mod tests { use super::*; } main.rs: use scanner_rs::*; macro_rules! time { ($name:literal, $($test:tt)*) => { { let start = std::time::Instant::now(); $($test)* println!("{}: {:?}", $name, start.elapsed()); } } } fn main() { let code = "H".repeat(104_857_6); let mut test_time = Lexer::new(&*code); time! { "init", Lexer::new(&*code); }; time! { "next", lexer.cursor.next(); }; time! { "ident", println!("{}", lexer.trim_ident()); // HHHHHHHHHHHH... }; let mut hello_world = Lexer::new("Hello"); println!("{}", lexer.trim_ident()); // Hello }
{ "domain": "codereview.stackexchange", "id": 44284, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, rust, lexical-analysis", "url": null }
performance, rust, lexical-analysis Answer: Let's focus on performance, with general principles first. Memory Allocations You did well using an iterator over str, rather than allocating a Vec<char>. This avoids memory allocations, and that's generally a good thing. On the other hand, your plan to use a String is TokenKind is not great. It would be better to just use a slice. If you plan to have potentially escaped characters, you can just add a variant for string-without-escaped-characters and string-with-escaped-characters. The goal is to defer the memory allocation as long as possible, and if possible to eschew it at the end too. char is problematic. From a pure performance point of view, char is fairly problematic. It may be necessary, mind, but it still is problematic. The problem is that you turn a byte into a char, then query the char, and go back to the byte. From a performance point of view, you'd be better off operating on bytes altogether... although if you want to support Unicode it'll definitely makes things a tad harder. Byte-wise segmentation is slow by design Your algorithm is, at its core, operating one byte at a time. That is far from ideal. The throughput of a lexer is typically expressed as the number of cycles it takes per byte, and the lower the better. You can try to fine-tune the operations performed on each byte to minimize this measure... but that's ignoring two important aspects of the CPU: ILP: Instruction Level Parallelism, which consists in performing multiple instructions "in parallel". SIMD: Same Instruction Multiple Data, which consists in performing a single instructions on multiple elements at once.
{ "domain": "codereview.stackexchange", "id": 44284, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, rust, lexical-analysis", "url": null }
performance, rust, lexical-analysis At the moment, a compiler may be able to turn your byte-by-byte algorithm into a vectorized version, or to unlock some ILP, but there are limits to the magic that a compiler is able to perform, and the char intermediary step is making your compiler's life difficult in the first place. Back to the drawing board What are you trying to do here? Lex a piece of code. Code typically looks like: 3 * 4 object.method(item, expr + ession) If you look closely, you'll realize that you have roughly 3 or 4 categories of characters: Identifiers & numbers. "Operators" & braces -- aka separators. Whitespace. This is because you can view tokenization as a two-steps processes: Segmentation and Classification. It's common for text-book lexers to mix the two together: peek at the first non-whitespace character, then parse a number/identifier/... based on it. It's simple, but not necessarily efficient. If you split the process, you can first segment and then classify. And that's much more mechanically sympathetic. So, taking object.method(item, expr + ession): Segmentation is about splitting into object, ., method, (, item, ,, expr, +, ession, and ). Classification is about assigning the kind: object is an identifier, . is (here) a method/field separator, ... There's two difficulties here: Floating point numbers, and their pesky . and - in the middle of those numbers. The tokens can be reassembled in the parsing stage, or in an intermediate stage. Strings and comments, which require a "mode switch" regardless.
{ "domain": "codereview.stackexchange", "id": 44284, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, rust, lexical-analysis", "url": null }
performance, rust, lexical-analysis Fortunately, they are quite rarer than regular tokens. Implementation-wise, the idea is to use an iterator on chunks of bytes and "mark" each as "identifier-like", whitespace, and other (operator, brace, quote, ...). Chunks of 64 bytes are great because u64 is native on most architectures, even if 16-bytes or 32-bytes SIMD operations need to be used. On the u64, you'll be looking at operations identifying the next set/unset bit, which in Rust are leading_zeros, leading_ones or trailing_zeros, trailing_ones depending on the way you compose the mask.
{ "domain": "codereview.stackexchange", "id": 44284, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, rust, lexical-analysis", "url": null }
python, pandas, pdf, dataframe Title: Unstructured to Structured TOC Question: The following code tries to convert an unstructured TOC with bounding box layout data given by the output of pdftotext -bbox-layout -f 11 -l 13 new_book.pdf toc.html in a html file into structured data on a DataFrame. I intend to use this data to build the internal TOC of a pdf document from scratch. I would like to hear suggestions about how to make better use of pandas.DataFrame functionalities to make the code more efficient. Updated: Since there is not yet an answer, and @J_H does have a valid point there (see his comment below), I have updated my code with functions so that it is more readable and hopefully somebody would be keen (and kind) enough to review it for me. from lxml import etree import pandas as pd import numpy as np import numeral # This is a rewriting of parse_toc.py to improve on readability. def build_dataframe(file_path): """Build dataframe from pdftotext output.""" with open(file_path) as f: text = f.read() tree = etree.HTML(text) toc_data = [] for i, page in enumerate(tree.findall('.//page')): # .// recursively search beyond the immediate children. for f, flow in enumerate(page.findall('.//flow')): for j, block in enumerate(flow.findall('.//block')): for k, line in enumerate(block.findall('.//line')): for word in line.findall('word'): toc_data.append((word.text, i, f, j, k, round(float(word.get('xmin'))), # round-off to smoothen values. round(float(word.get('ymin'))), round(float(word.get('xmax'))), round(float(word.get('ymax'))))) df = pd.DataFrame(toc_data, columns=["word", "page", "flow", "block", "line", "xMin", "yMin", "xMax", "yMax"]) df = df.sort_values(by=["page", "yMax", "xMax"]) return df
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe return df def consolidate_bboxes(df): df = df.assign(new_yMax=np.where(df['yMax'].diff(-1) == -1, df.yMax + 1, df.yMax)) df = df.assign(new_yMax=df.groupby(['page', 'yMax'])['new_yMax'].transform('max')) df.sort_values(by=['page', 'new_yMax', 'xMax'], inplace=True) df.reset_index(drop=True, inplace=True) return df def max_and_min(df): """Helper script to explore extremities to filter off.""" min_values = df.groupby('page')['new_yMax'].min().to_list() max_values = df.groupby('page')['new_yMax'].max().to_list() min_max = min_values + max_values suggested = [] for i, v in enumerate(min_max): candidate = df.loc[df['new_yMax'] == v] print(candidate) print() if len(candidate) < 3: suggested.append(v) return suggested def apply_filter(df, filter_list): return df.loc[~(df['new_yMax'].isin(filter_list))] def is_roman_numeral(num: str) -> bool: try: numeral.roman2int(num) except ValueError: return False return True def build_toc(df): """Iterate through word list to build dataframe with the right TOC labels.""" # Iterate through word list words = list(df['word']) labels = [] pg_no = [] caption = None label = None for i, word in enumerate(words): word = word.replace(",", "").replace(".", "") if word.isnumeric() and int(word) <= 332 or is_roman_numeral(word): # 332 is the maximum number of pages in the book. pg_no.append(word) if caption: if caption not in ["CONTENTS"]: labels.append(caption) caption = None else: caption = None if label: label = label.replace("- ", "") labels.append(label) if label[-1] == "-": pass else: label = None
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe else: if word.isupper() and len(word) > 1: if caption: caption += " " + word else: caption = word else: if label: label += " " + word else: label = word pg_no += [np.nan] * 3 # Output Dataframe df_out = pd.DataFrame({"labels": labels, "page": pg_no}) return df_out def build_bookmark_arrays(df, label): """Build arrays that locate a certain label within the dataframe.""" lb = np.where(df['labels'] == label)[0] # label cp = lb + 1 # caption location = np.concatenate((lb, cp)) arr = np.sort(location) return arr def shift_cells_down(df_out, caption): """Shift page-label cells down at cardinal captions where no page number is associated.""" arr_shift = np.where(df_out['labels'] == caption)[0] + 1 for i in arr_shift: df_out.loc[i:, 'page'] = df_out.loc[i:, 'page'].shift(1) return df_out def set_bookmark_levels(df_out): """Set bookmark levels with a dictionary.""" d = BOOKMARK_LEVELS for key in d.keys(): if d[key][0] == "default": df_out['BookmarkLevel'] = key else: df_out.loc[d[key], 'BookmarkLevel'] = key return df_out def set_labels(df_out, loc_arr): """Set bookmark labels by string concatenation from different cardinal cells.""" caption = df_out.loc[loc_arr, ['labels', 'page']] caption = caption.stack().groupby(level=0).apply(' '.join) this_index = None for i, row in enumerate(caption): last_index = this_index this_index = caption.index[i] if this_index and last_index: if this_index - last_index == 1: caption[this_index] = ": ".join((caption[last_index], caption[this_index])) caption[last_index] = np.nan return caption
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe return caption def update_dataframe(df_out): """Update labels and rename columns.""" df_out['labels'].update(parts_lbl) df_out['labels'].update(chapters_lbl) df_out.drop(df_out[df_out.labels == "Part"].index, inplace=True) df_out.drop(df_out[df_out.labels == "Chapter"].index, inplace=True) df_out['BookmarkPageNumber'] = None df_out.rename(columns={ "labels": "BookmarkTitle", "page": "ActualPageNumber", }, inplace=True) return df_out def offset_page_numbers(df_out, offset): """Offset page numbers where actual labels or numbers differ from index.""" for i, n in enumerate(df_out['ActualPageNumber']): if not n: # Skip None values continue loc = df_out.index[i] if is_roman_numeral(n): df_out.loc[loc, 'BookmarkPageNumber'] = numeral.roman2int(n) else: df_out.loc[loc, 'BookmarkPageNumber'] = int(n) + offset return df_out if __name__ == '__main__': toc_df_raw = build_dataframe('toc.html') toc_df_raw = consolidate_bboxes(toc_df_raw) suggested_filter = max_and_min(toc_df_raw) toc_df_raw = apply_filter(toc_df_raw, suggested_filter) # [44, 45, 127, 551] toc_df = build_toc(toc_df_raw) toc_df = shift_cells_down(toc_df, "Part") # Build Bookmark Arrays chapters = build_bookmark_arrays(toc_df, "Chapter") parts = build_bookmark_arrays(toc_df, "Part") BOOKMARK_LEVELS = { 1: parts, 2: chapters, 3: ["default"], } toc_df = set_bookmark_levels(toc_df) parts_lbl = set_labels(toc_df, parts) chapters_lbl = set_labels(toc_df, chapters) chapters_lbl = chapters_lbl.str.replace(" \d+$", "", regex=True) toc_df = update_dataframe(toc_df) toc_df = offset_page_numbers(toc_df, 24) print(toc_df)
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe toc.html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Evolution, development, and children&apos;s learning</title> <meta name="Keywords" content="http://archive.org/details/evolutiondevelop00fish"/> <meta name="Author" content="Fishbein, Harold D"/> <meta name="Creator" content="Digitized by the Internet Archive"/> <meta name="Producer" content="Recoded by LuraDocument PDF v2.53"/> <meta name="CreationDate" content=""/> </head> <body> <doc> <page width="389.000000" height="612.000000"> <flow> <block xMin="16.975480" yMin="110.518904" xMax="115.665742" yMax="126.679434"> <line xMin="16.975480" yMin="110.518904" xMax="115.665742" yMax="126.679434"> <word xMin="16.975480" yMin="110.518904" xMax="115.665742" yMax="126.679434">CONTENTS</word> </line> </block> </flow> <flow> <block xMin="17.263200" yMin="293.420111" xMax="56.250411" yMax="299.804267"> <line xMin="17.263200" yMin="293.420111" xMax="56.250411" yMax="299.804267"> <word xMin="17.263200" yMin="293.420111" xMax="56.250411" yMax="299.804267">Foreword</word> </line> </block> </flow> <flow> <block xMin="74.231760" yMin="295.046148" xMax="81.425335" yMax="299.757939"> <line xMin="74.231760" yMin="295.046148" xMax="81.425335" yMax="299.757939"> <word xMin="74.231760" yMin="295.046148" xMax="81.425335" yMax="299.757939">xi</word> </line> </block> </flow> <flow> <block xMin="17.119340" yMin="315.807962" xMax="149.332434" yMax="322.439750"> <line xMin="17.119340" yMin="315.807962" xMax="149.332434" yMax="322.439750"> <word xMin="17.119340" yMin="316.640467" xMax="46.036926" yMax="322.052187">Preface</word> <word xMin="49.775560" yMin="315.987128" xMax="64.450143" yMax="322.395030">and</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="49.775560" yMin="315.987128" xMax="64.450143" yMax="322.395030">and</word> <word xMin="68.333500" yMin="315.807962" xMax="149.332434" yMax="322.439750">Acknowledgements</word> </line> </block> <block xMin="16.831620" yMin="338.716199" xMax="94.082714" yMax="344.046505"> <line xMin="16.831620" yMin="338.716199" xMax="94.082714" yMax="344.046505"> <word xMin="16.831620" yMin="338.760569" xMax="61.857498" yMax="343.675894">Illustration</word> <word xMin="65.600160" yMin="338.716199" xMax="94.082714" yMax="344.046505">Credits</word> </line> </block> </flow> <flow> <block xMin="168.316200" yMin="316.433218" xMax="177.522665" yMax="322.463452"> <line xMin="168.316200" yMin="316.433218" xMax="177.522665" yMax="322.463452"> <word xMin="168.316200" yMin="316.433218" xMax="177.522665" yMax="322.463452">xv</word> </line> </block> </flow> <flow> <block xMin="112.930100" yMin="338.841088" xMax="128.180411" yMax="343.835565"> <line xMin="112.930100" yMin="338.841088" xMax="128.180411" yMax="343.835565"> <word xMin="112.930100" yMin="338.841088" xMax="128.180411" yMax="343.835565">xvii</word> </line> </block> </flow> <flow> <block xMin="16.687760" yMin="358.565974" xMax="49.775272" yMax="366.057124"> <line xMin="16.687760" yMin="358.565974" xMax="49.775272" yMax="366.057124"> <word xMin="16.687760" yMin="358.565974" xMax="39.561500" yMax="366.057124">Part</word> <word xMin="44.740460" yMin="359.426498" xMax="49.775272" yMax="366.022103">1</word> </line> </block> </flow> <flow> <block xMin="63.010680" yMin="355.260450" xMax="216.080022" yMax="366.882191"> <line xMin="63.010680" yMin="355.260450" xMax="216.080022" yMax="366.882191">
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <line xMin="63.010680" yMin="355.260450" xMax="216.080022" yMax="366.882191"> <word xMin="63.010680" yMin="355.889341" xMax="129.183978" yMax="366.725218">OVERVIEW</word> <word xMin="133.645940" yMin="355.260450" xMax="160.260615" yMax="366.882191">AND</word> <word xMin="165.295140" yMin="355.687553" xMax="216.080022" yMax="366.775585">THEORY</word> </line> </block> </flow> <flow> <block xMin="17.550920" yMin="381.853339" xMax="56.536692" yMax="387.749015"> <line xMin="17.550920" yMin="381.853339" xMax="56.536692" yMax="387.749015"> <word xMin="17.550920" yMin="381.853339" xMax="49.054534" yMax="387.749015">Chapter</word> <word xMin="53.228200" yMin="383.246837" xMax="56.536692" yMax="387.580962">1</word> </line> </block> </flow> <flow> <block xMin="73.368600" yMin="379.620065" xMax="204.569208" yMax="388.665982"> <line xMin="73.368600" yMin="379.620065" xMax="204.569208" yMax="388.665982"> <word xMin="73.368600" yMin="380.381084" xMax="121.705560" yMax="388.296261">OVERVIEW</word> <word xMin="125.302060" yMin="379.921390" xMax="145.155603" yMax="388.590770">AND</word> <word xMin="148.895100" yMin="379.620065" xMax="197.232060" yMax="388.665982">SUMMARY</word> <word xMin="201.404000" yMin="383.397047" xMax="204.569208" yMax="387.543469">1</word> </line> </block> <block xMin="73.368600" yMin="396.203985" xMax="340.803765" yMax="402.973982"> <line xMin="73.368600" yMin="396.203985" xMax="340.803765" yMax="402.973982"> <word xMin="73.368600" yMin="396.984912" xMax="115.378597" yMax="402.488222">Evolution,</word> <word xMin="119.979240" yMin="396.688096" xMax="156.950109" yMax="402.742076">Learning</word> <word xMin="161.267060" yMin="396.203985" xMax="176.516508" yMax="402.862911">and</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="161.267060" yMin="396.203985" xMax="176.516508" yMax="402.862911">and</word> <word xMin="180.832020" yMin="396.601227" xMax="227.874240" yMax="402.763758">Adaptation</word> <word xMin="232.190040" yMin="398.358487" xMax="238.520455" yMax="402.504909">1,</word> <word xMin="242.691820" yMin="396.676348" xMax="296.635867" yMax="402.565240">Evolutionary</word> <word xMin="300.523540" yMin="396.236577" xMax="330.012538" yMax="402.675008">Theory</word> <word xMin="334.186780" yMin="398.639857" xMax="340.803765" yMax="402.973982">3,</word> </line> </block> <block xMin="72.937020" yMin="407.087577" xMax="340.949351" yMax="436.352955"> <line xMin="73.368600" yMin="407.087577" xMax="340.949351" yMax="414.071343"> <word xMin="73.368600" yMin="408.205992" xMax="115.378597" yMax="413.709302">Evolution,</word> <word xMin="119.259940" yMin="407.399744" xMax="173.930768" yMax="413.910543">Development</word> <word xMin="177.667100" yMin="407.475738" xMax="192.771537" yMax="414.071343">and</word> <word xMin="196.656620" yMin="407.859423" xMax="241.972520" yMax="413.795806">Behavioral</word> <word xMin="245.712880" yMin="407.678447" xMax="292.755100" yMax="413.840978">Adaptation</word> <word xMin="296.495460" yMin="409.579567" xMax="302.825875" yMax="413.725989">6,</word> <word xMin="306.853380" yMin="407.087577" xMax="322.245249" yMax="413.808693">The</word> <word xMin="325.699040" yMin="408.613188" xMax="340.949351" yMax="413.607665">Pri-</word> </line> <line xMin="73.224740" yMin="418.257984" xMax="340.665084" yMax="425.042421"> <word xMin="73.224740" yMin="418.484203" xMax="93.077420" yMax="424.985956">mate</word> <word xMin="96.673920" yMin="418.855220" xMax="150.338304" yMax="424.713582">Evolutionary</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="154.074060" yMin="419.102236" xMax="175.942219" yMax="424.831694">Lines</word> <word xMin="179.825000" yMin="420.054138" xMax="191.045217" yMax="424.953632">10,</word> <word xMin="194.786440" yMin="418.257984" xMax="210.323320" yMax="425.042421">The</word> <word xMin="213.632100" yMin="418.820819" xMax="283.263217" yMax="424.901936">Hunter-Gatherer</word> <word xMin="287.000700" yMin="418.855220" xMax="340.665084" yMax="424.713582">Evolutionary</word> </line> <line xMin="72.937020" yMin="428.400463" xMax="260.385737" yMax="436.352955"> <word xMin="72.937020" yMin="429.726143" xMax="91.063380" yMax="435.662526">Line</word> <word xMin="94.947600" yMin="430.987498" xMax="106.167817" yMax="435.886992">14,</word> <word xMin="110.052900" yMin="429.859145" xMax="141.846535" yMax="435.809096">Aspects</word> <word xMin="145.586320" yMin="430.247338" xMax="153.929625" yMax="435.712202">of</word> <word xMin="156.519680" yMin="428.400463" xMax="186.872701" yMax="436.352955">Human</word> <word xMin="190.614500" yMin="429.582236" xMax="244.990991" yMax="436.057981">Development</word> <word xMin="249.165520" yMin="430.843638" xMax="260.385737" yMax="435.743132">17.</word> </line> </block> </flow> <flow> <block xMin="17.407060" yMin="451.481579" xMax="56.537268" yMax="457.428499"> <line xMin="17.407060" yMin="451.481579" xMax="56.537268" yMax="457.428499"> <word xMin="17.407060" yMin="451.481579" xMax="48.910674" yMax="457.377255">Chapter</word> <word xMin="52.940480" yMin="452.716708" xMax="56.537268" yMax="457.428499">2</word> </line> </block> </flow> <flow> <block xMin="72.937020" yMin="449.977638" xMax="195.649600" yMax="458.199573"> <line xMin="72.937020" yMin="449.977638" xMax="195.649600" yMax="458.199573">
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <line xMin="72.937020" yMin="449.977638" xMax="195.649600" yMax="458.199573"> <word xMin="72.937020" yMin="449.977638" xMax="110.194458" yMax="458.112178">THEORY</word> <word xMin="113.937120" yMin="450.448159" xMax="125.733065" yMax="458.174503">OF</word> <word xMin="129.330140" yMin="450.347717" xMax="183.274187" yMax="458.199573">EVOLUTION</word> <word xMin="187.449580" yMin="452.333023" xMax="195.649600" yMax="457.704036">21</word> </line> </block> <block xMin="73.080880" yMin="465.983340" xMax="340.661343" yMax="472.747476"> <line xMin="73.080880" yMin="465.983340" xMax="340.661343" yMax="472.747476"> <word xMin="73.080880" yMin="466.758806" xMax="103.436491" yMax="472.439642">History</word> <word xMin="108.326580" yMin="467.621124" xMax="119.691808" yMax="472.583940">21,</word> <word xMin="124.582760" yMin="466.954244" xMax="167.455917" yMax="472.570628">Precursors</word> <word xMin="172.632000" yMin="467.451928" xMax="180.257155" yMax="472.446405">of</word> <word xMin="184.572380" yMin="466.245723" xMax="214.351400" yMax="472.747476">Darwin</word> <word xMin="219.098780" yMin="466.320828" xMax="233.773363" yMax="472.728730">and</word> <word xMin="239.095320" yMin="466.579624" xMax="271.607968" yMax="472.664134">Spencer</word> <word xMin="276.642780" yMin="467.527938" xMax="287.862997" yMax="472.427432">21,</word> <word xMin="293.042820" yMin="465.983340" xMax="322.676829" yMax="472.453432">Darwin</word> <word xMin="325.986760" yMin="466.033108" xMax="340.661343" yMax="472.441010">and</word> </line> </block> </flow> <flow> <block xMin="73.224740" yMin="477.304862" xMax="340.806642" yMax="516.833445"> <line xMin="73.368600" yMin="477.304862" xMax="340.516908" yMax="483.649442">
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <line xMin="73.368600" yMin="477.304862" xMax="340.516908" yMax="483.649442"> <word xMin="73.368600" yMin="477.412558" xMax="105.591226" yMax="483.442792">Wallace</word> <word xMin="112.642380" yMin="478.605158" xMax="123.862597" yMax="483.504652">25,</word> <word xMin="130.912600" yMin="477.757301" xMax="183.851929" yMax="483.536511">Evolutionary</word> <word xMin="190.470640" yMin="477.354630" xMax="219.244942" yMax="483.637019">Theory</word> <word xMin="226.004060" yMin="477.304862" xMax="240.533632" yMax="483.649442">and</word> <word xMin="247.295340" yMin="477.838741" xMax="281.966751" yMax="483.516184">Genetics</word> <word xMin="288.870880" yMin="478.461298" xMax="296.351025" yMax="483.360792">to</word> <word xMin="303.544600" yMin="477.374553" xMax="322.102540" yMax="483.452279">1935</word> <word xMin="329.151680" yMin="478.410624" xMax="340.516908" yMax="483.373440">26,</word> </line> <line xMin="73.368600" yMin="487.346947" xMax="340.806642" yMax="494.606943"> <word xMin="73.368600" yMin="487.346947" xMax="105.882111" yMax="494.445730">Modern</word> <word xMin="110.772200" yMin="488.664436" xMax="149.466800" yMax="494.296650">Synthetic</word> <word xMin="154.217920" yMin="488.019257" xMax="183.706918" yMax="494.457688">Theory</word> <word xMin="188.744320" yMin="489.017323" xMax="196.944340" yMax="494.388336">of</word> <word xMin="200.828560" yMin="488.673469" xMax="240.680657" yMax="494.474163">Evolution</word> <word xMin="245.425160" yMin="489.581936" xMax="256.932809" yMax="494.606943">27,</word> <word xMin="262.256780" yMin="489.168438" xMax="309.727127" yMax="494.350617">Definitions,</word> <word xMin="314.621820" yMin="488.596570" xMax="340.806642" yMax="494.313589">Evolu-</word> </line>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe </line> <line xMin="73.224740" yMin="499.071140" xMax="340.657891" yMax="505.672670"> <word xMin="73.224740" yMin="499.752530" xMax="102.287337" yMax="505.191388">tionary</word> <word xMin="107.031840" yMin="500.260136" xMax="146.452357" yMax="505.424224">Strategies</word> <word xMin="151.340720" yMin="499.264768" xMax="166.015303" yMax="505.672670">and</word> <word xMin="170.617960" yMin="499.868323" xMax="213.775960" yMax="505.522021">Inventions</word> <word xMin="218.811060" yMin="500.759598" xMax="230.031277" yMax="505.659092">28,</word> <word xMin="234.923380" yMin="500.062856" xMax="286.132936" yMax="505.653233">Canalization</word> <word xMin="290.597200" yMin="499.071140" xMax="305.414205" yMax="505.541232">and</word> <word xMin="310.018300" yMin="499.660217" xMax="340.657891" yMax="505.394197">Genetic</word> </line> <line xMin="73.512460" yMin="510.141105" xMax="340.804628" yMax="516.833445"> <word xMin="73.512460" yMin="510.619818" xMax="125.737093" yMax="516.321007">Assimilation</word> <word xMin="132.351200" yMin="511.742726" xMax="143.428995" yMax="516.580030">32,</word> <word xMin="151.340720" yMin="510.141105" xMax="166.590168" yMax="516.800031">The</word> <word xMin="174.214460" yMin="510.945543" xMax="191.477660" yMax="516.599241">Five</word> <word xMin="199.246100" yMin="510.727451" xMax="222.551420" yMax="516.833445">Major</word> <word xMin="230.176000" yMin="511.283047" xMax="259.093586" yMax="516.694767">Factors</word> <word xMin="266.860300" yMin="511.329228" xMax="274.485455" yMax="516.323705">in</word> <word xMin="282.109460" yMin="510.557381" xMax="321.813957" yMax="516.336591">Evolution</word> <word xMin="329.439400" yMin="511.354564" xMax="340.804628" yMax="516.317380">40,</word> </line> </block> </flow> <flow>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe </line> </block> </flow> <flow> <block xMin="73.512460" yMin="519.982323" xMax="128.609689" yMax="527.466689"> <line xMin="73.512460" yMin="519.982323" xMax="128.609689" yMax="527.466689"> <word xMin="73.512460" yMin="519.982323" xMax="113.505252" yMax="527.466689">Summary</word> <word xMin="117.102040" yMin="522.094296" xMax="128.609689" yMax="527.119303">43.</word> </line> </block> <block xMin="330.014840" yMin="544.868388" xMax="339.797895" yMax="551.276290"> <line xMin="330.014840" yMin="544.868388" xMax="339.797895" yMax="551.276290"> <word xMin="330.014840" yMin="544.868388" xMax="339.797895" yMax="551.276290">vu</word> </line> </block> </flow> </page> <page width="389.000000" height="612.000000"> <flow> <block xMin="47.617660" yMin="40.654677" xMax="59.988469" yMax="44.706117"> <line xMin="47.617660" yMin="40.654677" xMax="59.988469" yMax="44.706117"> <word xMin="47.617660" yMin="40.654677" xMax="59.988469" yMax="44.706117">viii</word> </line> </block> </flow> <flow> <block xMin="68.333500" yMin="38.651306" xMax="106.167529" yMax="44.846628"> <line xMin="68.333500" yMin="38.651306" xMax="106.167529" yMax="44.846628"> <word xMin="68.333500" yMin="38.651306" xMax="106.167529" yMax="44.846628">CONTENTS</word> </line> </block> </flow> <flow> <block xMin="45.891340" yMin="66.123168" xMax="84.733540" yMax="71.965700"> <line xMin="45.891340" yMin="66.123168" xMax="84.733540" yMax="71.965700"> <word xMin="45.891340" yMin="66.123168" xMax="77.110974" yMax="71.965700">Chapter</word> <word xMin="81.280900" yMin="67.035302" xMax="84.733540" yMax="71.558261">3</word> </line> </block> </flow> <flow> <block xMin="101.277440" yMin="62.968901" xMax="326.273905" yMax="71.879473">
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <flow> <block xMin="101.277440" yMin="62.968901" xMax="326.273905" yMax="71.879473"> <line xMin="101.277440" yMin="62.968901" xMax="326.273905" yMax="71.879473"> <word xMin="101.277440" yMin="63.587759" xMax="164.572963" yMax="71.879473">EMBRYOLOGY</word> <word xMin="168.316200" yMin="63.242111" xMax="187.882311" yMax="71.785980">AND</word> <word xMin="191.909240" yMin="63.318153" xMax="272.184846" yMax="71.407464">DEVELOPMENTAL</word> <word xMin="275.779620" yMin="62.968901" xMax="313.182069" yMax="71.135102">THEORY</word> <word xMin="316.635860" yMin="64.451998" xMax="326.273905" yMax="70.764917">46</word> </line> </block> <block xMin="101.277440" yMin="78.797152" xMax="367.274868" yMax="108.549492"> <line xMin="101.421300" yMin="78.797152" xMax="367.274868" yMax="86.599255"> <word xMin="101.421300" yMin="80.674745" xMax="132.495923" yMax="86.490139">Aspects</word> <word xMin="136.667000" yMin="80.961608" xMax="144.723735" yMax="86.238770">of</word> <word xMin="147.888080" yMin="78.797152" xMax="177.667100" yMax="86.599255">Human</word> <word xMin="182.126760" yMin="79.693903" xMax="231.758460" yMax="86.195656">Embryology</word> <word xMin="235.642680" yMin="80.825003" xMax="247.295340" yMax="85.913331">47,</word> <word xMin="251.611140" yMin="79.836922" xMax="309.006964" yMax="85.620655">Psychological</word> <word xMin="313.183220" yMin="79.310282" xMax="367.274868" yMax="85.752106">Development</word> </line> <line xMin="101.421300" yMin="90.675222" xMax="367.273429" yMax="97.647062"> <word xMin="101.421300" yMin="92.873079" xMax="112.354085" yMax="97.647062">55,</word> <word xMin="116.670460" yMin="92.398049" xMax="170.191559" yMax="97.406095">Interactionist</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="174.358320" yMin="91.352040" xMax="219.820957" yMax="97.307646">Hypothesis</word> <word xMin="224.133880" yMin="92.297639" xMax="235.066665" yMax="97.071622">58,</word> <word xMin="239.383040" yMin="90.675222" xMax="293.474688" yMax="97.117046">Development</word> <word xMin="297.790200" yMin="90.890599" xMax="320.663940" yMax="96.883519">Leads</word> <word xMin="324.404300" yMin="91.840723" xMax="331.741160" yMax="96.646366">to</word> <word xMin="335.481520" yMin="91.520395" xMax="367.273429" yMax="96.726320">Increas-</word> </line> <line xMin="101.277440" yMin="101.478295" xMax="366.988586" yMax="108.549492"> <word xMin="101.277440" yMin="103.210139" xMax="113.504965" yMax="108.549492">ing</word> <word xMin="118.396780" yMin="103.227348" xMax="177.229766" yMax="108.365429">Differentiation</word> <word xMin="181.695180" yMin="102.067308" xMax="196.369763" yMax="108.475210">and</word> <word xMin="200.828560" yMin="102.443770" xMax="243.408243" yMax="108.021708">Hierarchic</word> <word xMin="247.870780" yMin="102.643748" xMax="292.610089" yMax="107.971793">Integration</word> <word xMin="297.070900" yMin="103.079884" xMax="308.436128" yMax="108.042700">61,</word> <word xMin="313.039360" yMin="101.478295" xMax="366.988586" yMax="107.903158">Development</word> </line> </block> <block xMin="101.277440" yMin="111.685926" xMax="212.194075" yMax="119.226526"> <line xMin="101.277440" yMin="111.685926" xMax="212.194075" yMax="119.226526"> <word xMin="101.277440" yMin="114.207778" xMax="108.757585" yMax="119.107272">in</word> <word xMin="112.642380" yMin="113.730001" xMax="137.817305" yMax="119.226526">Stages</word> <word xMin="141.702100" yMin="113.963476" xMax="153.209749" yMax="118.988483">63,</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="141.702100" yMin="113.963476" xMax="153.209749" yMax="118.988483">63,</word> <word xMin="157.095120" yMin="111.685926" xMax="197.232923" yMax="119.197429">Summary</word> <word xMin="201.116280" yMin="113.682106" xMax="212.194075" yMax="118.519410">66.</word> </line> </block> </flow> <flow> <block xMin="46.179060" yMin="139.943129" xMax="78.547560" yMax="147.199085"> <line xMin="46.179060" yMin="139.943129" xMax="78.547560" yMax="147.199085"> <word xMin="46.179060" yMin="139.943129" xMax="68.334651" yMax="147.199085">Part</word> <word xMin="73.368600" yMin="140.176604" xMax="78.547560" yMax="146.961041">2</word> </line> </block> <block xMin="45.891340" yMin="162.754559" xMax="85.020972" yMax="168.650235"> <line xMin="45.891340" yMin="162.754559" xMax="85.020972" yMax="168.650235"> <word xMin="45.891340" yMin="162.754559" xMax="77.394954" yMax="168.650235">Chapter</word> <word xMin="81.280900" yMin="163.407898" xMax="85.020972" yMax="168.307392">4</word> </line> </block> </flow> <flow> <block xMin="91.638820" yMin="136.824930" xMax="167.023762" yMax="147.797627"> <line xMin="91.638820" yMin="136.824930" xMax="167.023762" yMax="147.797627"> <word xMin="91.638820" yMin="136.824930" xMax="167.023762" yMax="147.797627">PHYLOGENY</word> </line> </block> <block xMin="101.421300" yMin="160.757537" xMax="297.358045" yMax="168.872043"> <line xMin="101.421300" yMin="160.757537" xMax="297.358045" yMax="168.872043"> <word xMin="101.421300" yMin="161.145699" xMax="119.115217" yMax="168.872043">THE</word> <word xMin="122.856440" yMin="160.812719" xMax="244.423894" yMax="168.775388">PALEOANTHROPOLOGICAL</word> <word xMin="248.590080" yMin="160.757537" xMax="284.552778" yMax="168.609393">RECORD</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="288.583160" yMin="162.441518" xMax="297.358045" yMax="168.189067">69</word> </line> </block> <block xMin="101.421300" yMin="176.911577" xMax="367.561149" yMax="216.441369"> <line xMin="101.565160" yMin="176.911577" xMax="367.419015" yMax="183.632693"> <word xMin="101.565160" yMin="177.162228" xMax="140.697382" yMax="183.570130">Overview</word> <word xMin="144.291580" yMin="178.606384" xMax="155.656808" yMax="183.569200">69,</word> <word xMin="158.965300" yMin="176.911577" xMax="174.357169" yMax="183.632693">The</word> <word xMin="177.954820" yMin="178.192886" xMax="201.405151" yMax="183.312875">Fossil</word> <word xMin="205.144360" yMin="177.118810" xMax="233.918662" yMax="183.401199">Record</word> <word xMin="237.512860" yMin="176.917927" xMax="252.474875" yMax="183.451340">and</word> <word xMin="256.070800" yMin="177.830061" xMax="279.950985" yMax="183.043901">Fossil</word> <word xMin="283.404200" yMin="177.326948" xMax="310.163886" yMax="183.169480">Dating</word> <word xMin="314.334100" yMin="178.369338" xMax="325.554317" yMax="183.268832">71,</word> <word xMin="329.151680" yMin="177.688884" xMax="367.419015" yMax="183.258907">Placental</word> </line> <line xMin="101.421300" yMin="188.042216" xMax="367.273429" yMax="194.633772"> <word xMin="101.421300" yMin="188.582398" xMax="151.629591" yMax="194.561749">Adaptations</word> <word xMin="155.081080" yMin="189.734278" xMax="166.301297" yMax="194.633772">72,</word> <word xMin="169.898660" yMin="188.541678" xMax="202.121286" yMax="194.571912">Primate</word> <word xMin="205.432080" yMin="188.614989" xMax="244.996745" yMax="194.373846">Evolution</word> <word xMin="248.590080" yMin="188.045820" xMax="263.407085" yMax="194.515912">and</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="248.590080" yMin="188.045820" xMax="263.407085" yMax="194.515912">and</word> <word xMin="266.860300" yMin="188.706398" xMax="279.375257" yMax="194.171262">the</word> <word xMin="282.684900" yMin="188.042216" xMax="330.737017" yMax="194.337044">Anthropoid</word> <word xMin="334.186780" yMin="188.412280" xMax="367.273429" yMax="194.604210">Adapta-</word> </line> <line xMin="101.565160" yMin="198.130466" xMax="367.561149" yMax="205.279412"> <word xMin="101.565160" yMin="199.941083" xMax="120.986260" yMax="205.029411">tions</word> <word xMin="124.295040" yMin="200.379918" xMax="135.515257" yMax="205.279412">73,</word> <word xMin="138.968760" yMin="199.582750" xMax="172.777011" yMax="205.118852">Climate,</word> <word xMin="176.372360" yMin="198.504150" xMax="212.196089" yMax="205.208305">Hominid</word> <word xMin="215.646140" yMin="199.336655" xMax="257.509400" yMax="204.820742">Evolution,</word> <word xMin="261.105900" yMin="198.547600" xMax="275.922905" yMax="205.017692">and</word> <word xMin="279.376120" yMin="199.208178" xMax="291.891077" yMax="204.673042">the</word> <word xMin="294.913000" yMin="198.130466" xMax="331.310731" yMax="204.942042">Hominid</word> <word xMin="334.474500" yMin="198.770200" xMax="367.561149" yMax="204.962130">Adapta-</word> </line> <line xMin="101.421300" yMin="208.957003" xMax="221.544688" yMax="216.441369"> <word xMin="101.421300" yMin="210.844582" xMax="120.984821" yMax="215.970224">tions</word> <word xMin="124.870480" yMin="211.262604" xMax="136.235708" yMax="216.225420">79,</word> <word xMin="140.119640" yMin="208.957003" xMax="180.112432" yMax="216.441369">Summary</word> <word xMin="183.996940" yMin="210.067306" xMax="206.581521" yMax="215.984466">Table</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="183.996940" yMin="210.067306" xMax="206.581521" yMax="215.984466">Table</word> <word xMin="210.179460" yMin="210.831024" xMax="221.544688" yMax="215.793840">85.</word> </line> </block> </flow> <flow> <block xMin="46.035200" yMin="232.260656" xMax="85.021260" yMax="238.129194"> <line xMin="46.035200" yMin="232.260656" xMax="85.021260" yMax="238.129194"> <word xMin="46.035200" yMin="232.260656" xMax="77.393803" yMax="238.129194">Chapter</word> <word xMin="81.568620" yMin="233.337462" xMax="85.021260" yMax="237.860421">5</word> </line> </block> </flow> <flow> <block xMin="101.852880" yMin="230.119711" xMax="343.106100" yMax="238.663580"> <line xMin="101.852880" yMin="230.119711" xMax="343.106100" yMax="238.663580"> <word xMin="101.852880" yMin="231.165752" xMax="129.474000" yMax="238.402485">BRAIN</word> <word xMin="133.502080" yMin="230.754937" xMax="180.830869" yMax="238.505026">FUNCTION</word> <word xMin="184.572380" yMin="230.119711" xMax="204.138491" yMax="238.663580">AND</word> <word xMin="207.877700" yMin="230.723266" xMax="261.394483" yMax="238.512931">EVOLUTION</word> <word xMin="265.277840" yMin="231.000159" xMax="276.642205" yMax="238.443818">OF</word> <word xMin="280.670860" yMin="230.630079" xMax="298.364777" yMax="238.356423">THE</word> <word xMin="302.249860" yMin="231.075264" xMax="330.302560" yMax="238.425071">BRAIN</word> <word xMin="334.042920" yMin="232.350223" xMax="343.106100" yMax="238.286606">86</word> </line> </block> <block xMin="101.996740" yMin="246.628511" xMax="141.267067" yMax="253.059027"> <line xMin="101.996740" yMin="246.628511" xMax="141.267067" yMax="253.059027"> <word xMin="101.996740" yMin="246.628511" xMax="141.267067" yMax="253.059027">Overview</word> </line> </block>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe </line> </block> </flow> <flow> <block xMin="147.168780" yMin="248.090764" xMax="158.534008" yMax="253.053580"> <line xMin="147.168780" yMin="248.090764" xMax="158.534008" yMax="253.053580"> <word xMin="147.168780" yMin="248.090764" xMax="158.534008" yMax="253.053580">86,</word> </line> </block> </flow> <flow> <block xMin="164.719700" yMin="246.345284" xMax="367.993880" yMax="253.129721"> <line xMin="164.719700" yMin="246.345284" xMax="367.993880" yMax="253.129721"> <word xMin="164.719700" yMin="246.517211" xMax="199.824417" yMax="253.086808">Methods</word> <word xMin="205.575940" yMin="247.627498" xMax="213.487665" yMax="252.809677">of</word> <word xMin="218.523340" yMin="246.948838" xMax="255.349198" yMax="252.979072">Studying</word> <word xMin="261.393620" yMin="247.039326" xMax="283.978201" yMax="252.956486">Brain</word> <word xMin="289.734040" yMin="247.132529" xMax="329.586137" yMax="252.933223">Evolution</word> <word xMin="335.193800" yMin="248.090764" xMax="346.559028" yMax="253.053580">88,</word> <word xMin="352.457000" yMin="246.345284" xMax="367.993880" yMax="253.129721">The</word> </line> </block> </flow> <flow> <block xMin="101.852880" yMin="257.479527" xMax="368.281600" yMax="264.012940"> <line xMin="101.852880" yMin="257.479527" xMax="368.281600" yMax="264.012940"> <word xMin="101.852880" yMin="258.492103" xMax="125.158200" yMax="263.580431">Fossil</word> <word xMin="128.754700" yMin="257.561887" xMax="157.383991" yMax="263.812615">Record</word> <word xMin="160.979340" yMin="258.930938" xMax="172.199557" yMax="263.830432">90,</word> <word xMin="175.653060" yMin="258.217004" xMax="214.207828" yMax="263.828864">Increased</word> <word xMin="217.516320" yMin="258.213384" xMax="238.952899" yMax="263.829768">Brain</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="217.516320" yMin="258.213384" xMax="238.952899" yMax="263.829768">Brain</word> <word xMin="242.260240" yMin="258.334638" xMax="258.946849" yMax="263.799502">Size</word> <word xMin="262.256780" yMin="258.880264" xMax="273.622008" yMax="263.843080">90,</word> <word xMin="277.362080" yMin="258.039663" xMax="298.941080" yMax="263.693361">Brain</word> <word xMin="302.106000" yMin="258.296633" xMax="318.937620" yMax="263.808988">Size</word> <word xMin="321.814820" yMin="257.479527" xMax="336.776835" yMax="264.012940">and</word> <word xMin="339.797320" yMin="258.145518" xMax="357.205531" yMax="263.846707">Rate</word> <word xMin="360.513160" yMin="258.635963" xMax="368.281600" yMax="263.724291">of</word> </line> </block> </flow> <flow> <block xMin="101.996740" yMin="268.269027" xMax="367.707311" yMax="274.944719"> <line xMin="101.996740" yMin="268.269027" xMax="367.707311" yMax="274.944719"> <word xMin="101.996740" yMin="268.981151" xMax="146.449480" yMax="274.804460">Maturation</word> <word xMin="150.765280" yMin="269.813624" xMax="162.130508" yMax="274.776440">93,</word> <word xMin="166.446020" yMin="268.825512" xMax="235.352083" yMax="274.843308">Hunter-Gatherer</word> <word xMin="239.526900" yMin="268.658125" xMax="290.304876" yMax="274.705320">Adaptations</word> <word xMin="294.481420" yMin="268.269027" xMax="309.443435" yMax="274.802440">and</word> <word xMin="314.046380" yMin="268.445478" xMax="323.684425" yMax="274.758397">an</word> <word xMin="327.856940" yMin="268.419221" xMax="367.707311" yMax="274.944719">Overview</word> </line> </block> <block xMin="101.421300" yMin="279.145364" xMax="367.565177" yMax="285.979477"> <line xMin="101.421300" yMin="279.145364" xMax="367.565177" yMax="285.979477">
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <line xMin="101.421300" yMin="279.145364" xMax="367.565177" yMax="285.979477"> <word xMin="101.421300" yMin="280.201358" xMax="109.764605" yMax="285.666222">of</word> <word xMin="112.498520" yMin="279.446688" xMax="136.956159" yMax="285.854590">Man&apos;s</word> <word xMin="140.263500" yMin="279.627664" xMax="163.857979" yMax="285.809418">Three</word> <word xMin="167.596900" yMin="279.924465" xMax="194.211575" yMax="285.735336">Brains</word> <word xMin="197.951360" yMin="280.941518" xMax="209.171577" yMax="285.841012">95,</word> <word xMin="212.768940" yMin="279.196037" xMax="228.160809" yMax="285.917153">The</word> <word xMin="231.614600" yMin="279.792337" xMax="259.808858" yMax="285.948083">Limbic</word> <word xMin="263.695380" yMin="279.666558" xMax="292.609514" yMax="285.979477">System</word> <word xMin="296.639320" yMin="280.639288" xMax="312.752791" yMax="285.916450">102,</word> <word xMin="316.348140" yMin="279.145364" xMax="331.885020" yMax="285.929801">The</word> <word xMin="335.481520" yMin="279.913590" xMax="367.565177" yMax="285.917818">Neocor-</word> </line> </block> <block xMin="101.996740" yMin="289.985537" xMax="280.527575" yMax="307.941749"> <line xMin="119.979240" yMin="289.985537" xMax="280.527575" yMax="296.706653"> <word xMin="119.979240" yMin="291.466793" xMax="135.947700" yMax="296.696463">104,</word> <word xMin="142.709120" yMin="289.985537" xMax="173.492858" yMax="296.706653">Growth</word> <word xMin="180.112720" yMin="290.186420" xMax="194.929725" yMax="296.656512">and</word> <word xMin="201.835580" yMin="290.507652" xMax="248.161377" yMax="296.576332">Maturation</word> <word xMin="254.632200" yMin="291.134718" xMax="262.975505" yMax="296.599582">of</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="254.632200" yMin="291.134718" xMax="262.975505" yMax="296.599582">of</word> <word xMin="268.155040" yMin="291.184486" xMax="280.527575" yMax="296.587160">the</word> </line> <line xMin="101.996740" yMin="300.430246" xMax="227.297649" yMax="307.941749"> <word xMin="101.996740" yMin="301.665407" xMax="142.998566" yMax="307.633450">Neocortex</word> <word xMin="147.312640" yMin="302.506008" xMax="163.426111" yMax="307.783170">109,</word> <word xMin="167.309180" yMin="300.430246" xMax="207.446983" yMax="307.941749">Summary</word> <word xMin="211.474200" yMin="302.294298" xMax="227.297649" yMax="307.476477">111.</word> </line> </block> </flow> <flow> <block xMin="101.565160" yMin="291.292183" xMax="113.217820" yMax="296.380511"> <line xMin="101.565160" yMin="291.292183" xMax="113.217820" yMax="296.380511"> <word xMin="101.565160" yMin="291.292183" xMax="113.217820" yMax="296.380511">tex</word> </line> </block> </flow> <flow> <block xMin="46.466780" yMin="323.344848" xMax="85.452840" yMax="329.187380"> <line xMin="46.466780" yMin="323.344848" xMax="85.452840" yMax="329.187380"> <word xMin="46.466780" yMin="323.344848" xMax="77.686414" yMax="329.187380">Chapter</word> <word xMin="81.568620" yMin="323.948403" xMax="85.452840" yMax="329.036731">6</word> </line> </block> </flow> <flow> <block xMin="286.856840" yMin="289.029984" xMax="367.849157" yMax="296.945161"> <line xMin="286.856840" yMin="289.029984" xMax="367.849157" yMax="296.945161"> <word xMin="286.856840" yMin="289.029984" xMax="317.067440" yMax="296.945161">Human</word> <word xMin="323.685000" yMin="290.772766" xMax="346.269581" yMax="296.689926">Brain</word> <word xMin="352.744720" yMin="290.085978" xMax="367.849157" yMax="296.681583">and</word> </line>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe </line> </block> </flow> <flow> <block xMin="101.709020" yMin="321.870784" xMax="285.563251" yMax="329.735078"> <line xMin="101.709020" yMin="321.870784" xMax="285.563251" yMax="329.735078"> <word xMin="101.709020" yMin="321.935935" xMax="161.120323" yMax="329.718816">CATARRHINE</word> <word xMin="165.007420" yMin="322.433619" xMax="197.805774" yMax="329.594593">SOCIAL</word> <word xMin="201.835580" yMin="321.870784" xMax="267.871636" yMax="329.735078">ADAPTATIONS</word> <word xMin="272.470840" yMin="323.589150" xMax="285.563251" yMax="329.306169">113</word> </line> </block> <block xMin="100.989720" yMin="336.984338" xMax="368.281025" yMax="376.437139"> <line xMin="101.133580" yMin="336.984338" xMax="366.985709" yMax="343.695570"> <word xMin="101.133580" yMin="337.241308" xMax="140.548918" yMax="343.695570">Overview</word> <word xMin="147.024920" yMin="338.327148" xMax="163.138391" yMax="343.604310">113,</word> <word xMin="169.754800" yMin="337.819526" xMax="222.259096" yMax="343.551245">Canalization</word> <word xMin="228.593540" yMin="338.183288" xMax="236.650275" yMax="343.460450">of</word> <word xMin="242.116380" yMin="337.523631" xMax="279.377271" yMax="343.625102">Behavior</word> <word xMin="285.418240" yMin="336.984338" xMax="300.522677" yMax="343.579943">and</word> <word xMin="306.853380" yMin="337.398773" xMax="343.969260" yMax="343.476499">Learning</word> <word xMin="350.730680" yMin="338.002328" xMax="366.985709" yMax="343.325850">114,</word> </line> <line xMin="100.989720" yMin="347.963816" xMax="368.281025" yMax="354.861327"> <word xMin="100.989720" yMin="347.963816" xMax="127.316100" yMax="354.861327">Which</word> <word xMin="132.495060" yMin="348.751966" xMax="168.602769" yMax="354.664603">Primates</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="173.782880" yMin="349.637843" xMax="181.119740" yMax="354.443486">to</word> <word xMin="186.442560" yMin="348.111311" xMax="227.439207" yMax="354.824512">Compare?</word> <word xMin="232.909340" yMin="349.511128" xMax="249.164369" yMax="354.834650">117,</word> <word xMin="254.488340" yMin="348.427130" xMax="287.291009" yMax="354.565915">General</word> <word xMin="292.611240" yMin="348.852439" xMax="354.758760" yMax="354.279989">Characteristics</word> <word xMin="359.937720" yMin="348.678718" xMax="368.281025" yMax="354.143582">of</word> </line> <line xMin="100.989720" yMin="358.994918" xMax="367.416138" yMax="365.605403"> <word xMin="100.989720" yMin="359.967648" xMax="134.942982" yMax="365.527495">Selected</word> <word xMin="138.681040" yMin="359.810199" xMax="187.018863" yMax="365.566794">Catarrhines</word> <word xMin="191.189940" yMin="360.375733" xMax="207.158400" yMax="365.605403">119,</word> <word xMin="211.186480" yMin="360.204726" xMax="267.438617" yMax="365.468319">Socialization,</word> <word xMin="271.319960" yMin="359.356870" xMax="318.215443" yMax="365.500178">Maturation</word> <word xMin="321.958680" yMin="358.994918" xMax="337.063117" yMax="365.590523">and</word> <word xMin="340.516620" yMin="359.429276" xMax="367.416138" yMax="365.302338">Learn-</word> </line> <line xMin="101.133580" yMin="369.589885" xMax="367.417865" yMax="376.437139"> <word xMin="101.133580" yMin="370.645879" xMax="113.361105" yMax="375.985232">ing</word> <word xMin="117.677480" yMin="370.983368" xMax="133.790951" yMax="376.260530">123,</word> <word xMin="137.674020" yMin="370.559900" xMax="167.739609" yMax="376.186460">Infancy</word> <word xMin="171.912700" yMin="371.021373" xMax="187.881160" yMax="376.251043">124,</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="171.912700" yMin="371.021373" xMax="187.881160" yMax="376.251043">124,</word> <word xMin="192.053100" yMin="369.834187" xMax="207.015115" yMax="376.367600">The</word> <word xMin="210.611040" yMin="370.996020" xMax="243.839247" yMax="376.437139">Juvenile</word> <word xMin="247.583060" yMin="370.652182" xMax="269.304481" yMax="376.343194">Stage</word> <word xMin="273.477860" yMin="370.877513" xMax="289.446320" yMax="376.107183">127,</word> <word xMin="293.474400" yMin="369.589885" xMax="308.723848" yMax="376.248811">The</word> <word xMin="312.463920" yMin="370.130098" xMax="349.006662" yMax="376.113972">Subadult</word> <word xMin="352.600860" yMin="369.741000" xMax="367.417865" yMax="376.211092">and</word> </line> </block> <block xMin="101.133580" yMin="380.150403" xMax="308.146969" yMax="387.634769"> <line xMin="101.133580" yMin="380.150403" xMax="308.146969" yMax="387.634769"> <word xMin="101.133580" yMin="381.343939" xMax="124.007320" yMax="387.336859">Adult</word> <word xMin="128.035400" yMin="381.834368" xMax="153.500346" yMax="387.394215">Stages</word> <word xMin="157.814420" yMin="382.173698" xMax="173.496311" yMax="387.309517">129,</word> <word xMin="177.810960" yMin="381.184696" xMax="223.705177" yMax="387.196839">Aggression</word> <word xMin="227.730380" yMin="382.204448" xMax="243.843851" yMax="387.481610">131,</word> <word xMin="248.014640" yMin="380.150403" xMax="288.007432" yMax="387.634769">Summary</word> <word xMin="292.323520" yMin="381.848878" xMax="308.146969" yMax="387.031057">134.</word> </line> </block> </flow> <flow> <block xMin="45.891340" yMin="402.467848" xMax="84.589392" yMax="408.310380"> <line xMin="45.891340" yMin="402.467848" xMax="84.589392" yMax="408.310380">
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <line xMin="45.891340" yMin="402.467848" xMax="84.589392" yMax="408.310380"> <word xMin="45.891340" yMin="402.467848" xMax="77.110974" yMax="408.310380">Chapter</word> <word xMin="81.280900" yMin="403.818817" xMax="84.589392" yMax="408.152942">7</word> </line> </block> </flow> <flow> <block xMin="101.277440" yMin="401.177458" xMax="315.484692" yMax="409.152573"> <line xMin="101.277440" yMin="401.177458" xMax="315.484692" yMax="409.152573"> <word xMin="101.277440" yMin="401.177458" xMax="190.756921" yMax="408.992000">HUNTER-GATHERER</word> <word xMin="194.354860" yMin="401.819002" xMax="227.298225" yMax="409.011637">SOCIAL</word> <word xMin="231.183020" yMin="401.254357" xMax="297.503919" yMax="409.152573">ADAPTATIONS</word> <word xMin="302.249860" yMin="402.950101" xMax="315.484692" yMax="408.729311">135</word> </line> </block> <block xMin="101.133580" yMin="417.102611" xMax="367.276594" yMax="423.991120"> <line xMin="101.133580" yMin="417.102611" xMax="367.276594" yMax="423.991120"> <word xMin="101.133580" yMin="417.102611" xMax="140.403907" yMax="423.533127">Overview</word> <word xMin="145.442460" yMin="418.457168" xMax="161.555931" yMax="423.734330">135,</word> <word xMin="167.165320" yMin="417.580340" xMax="220.677787" yMax="423.953188">Assumptions</word> <word xMin="226.147920" yMin="418.148588" xMax="248.447659" yMax="423.991120">about</word> <word xMin="253.912900" yMin="418.080738" xMax="306.562207" yMax="423.828287">Canalization</word> <word xMin="312.176200" yMin="418.639033" xMax="328.144660" yMax="423.868703">138,</word> <word xMin="333.035900" yMin="417.408428" xMax="367.276594" yMax="423.816330">Contem-</word> </line> </block> <block xMin="101.277440" yMin="428.287543" xMax="367.131871" yMax="456.668783">
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe </block> <block xMin="101.277440" yMin="428.287543" xMax="367.131871" yMax="456.668783"> <line xMin="101.421300" yMin="428.287543" xMax="367.131871" yMax="434.667690"> <word xMin="101.421300" yMin="428.287543" xMax="128.610840" yMax="434.223926">porary</word> <word xMin="132.063480" yMin="428.403352" xMax="204.997047" yMax="434.374788">Hunter-Gatherers</word> <word xMin="208.740860" yMin="429.390528" xMax="224.854331" yMax="434.667690">139,</word> <word xMin="228.449680" yMin="428.549927" xMax="269.451506" yMax="434.517970">Canalized</word> <word xMin="273.190140" yMin="428.443151" xMax="310.451031" yMax="434.544622">Behavior</word> <word xMin="313.183220" yMin="428.858490" xMax="347.274587" yMax="434.440952">Patterns</word> <word xMin="351.018400" yMin="429.246668" xMax="367.131871" yMax="434.523830">141,</word> </line> <line xMin="101.277440" yMin="439.260686" xMax="366.985709" yMax="445.826910"> <word xMin="101.277440" yMin="439.508639" xMax="149.615263" yMax="445.265234">Cooperative</word> <word xMin="153.786340" yMin="439.260686" xMax="187.163011" yMax="445.506892">Hunting</word> <word xMin="192.053100" yMin="440.361893" xMax="208.021560" yMax="445.591563">141,</word> <word xMin="212.337360" yMin="439.690488" xMax="230.318709" yMax="445.579380">Tool</word> <word xMin="234.779520" yMin="439.495034" xMax="286.279098" yMax="445.628166">Manufacture</word> <word xMin="290.597200" yMin="439.325822" xMax="305.126772" yMax="445.670402">and</word> <word xMin="309.299000" yMin="439.652483" xMax="327.425360" yMax="445.588866">Tool</word> <word xMin="331.741160" yMin="439.419008" xMax="346.415743" yMax="445.826910">Use</word> <word xMin="351.162260" yMin="440.256038" xMax="366.985709" yMax="445.438217">144,</word> </line>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe </line> <line xMin="101.421300" yMin="449.701823" xMax="366.984558" yMax="456.668783"> <word xMin="101.421300" yMin="449.701823" xMax="121.273980" yMax="456.203576">Food</word> <word xMin="126.740660" yMin="450.394945" xMax="157.815283" yMax="456.210339">Sharing</word> <word xMin="164.000400" yMin="451.226498" xMax="179.682291" yMax="456.362317">144,</word> <word xMin="185.291680" yMin="450.233845" xMax="243.699991" yMax="456.610086">Husband-Wife</word> <word xMin="249.165520" yMin="451.246389" xMax="301.668953" yMax="456.537120">Reciprocities</word> <word xMin="307.572680" yMin="451.439113" xMax="323.541140" yMax="456.668783">146,</word> <word xMin="329.295540" yMin="450.397628" xMax="366.984558" yMax="456.569205">Symbolic</word> </line> </block> </flow> <flow> <block xMin="101.133580" yMin="460.570937" xMax="166.451487" yMax="467.152972"> <line xMin="101.133580" yMin="460.570937" xMax="166.451487" yMax="467.152972"> <word xMin="101.133580" yMin="460.570937" xMax="166.451487" yMax="467.152972">Communication</word> </line> </block> </flow> <flow> <block xMin="173.782880" yMin="462.084753" xMax="189.751340" yMax="467.314423"> <line xMin="173.782880" yMin="462.084753" xMax="189.751340" yMax="467.314423"> <word xMin="173.782880" yMin="462.084753" xMax="189.751340" yMax="467.314423">147,</word> </line> </block> </flow> <flow> <block xMin="196.656620" yMin="461.141868" xMax="343.251399" yMax="467.549770"> <line xMin="196.656620" yMin="461.141868" xMax="343.251399" yMax="467.549770"> <word xMin="196.656620" yMin="461.481198" xMax="214.927991" yMax="467.465072">Rule</word> <word xMin="221.544400" yMin="461.544540" xMax="248.588929" yMax="467.449262">Giving</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="255.351500" yMin="461.141868" xMax="270.026083" yMax="467.549770">and</word> <word xMin="276.930500" yMin="461.481198" xMax="295.201871" yMax="467.465072">Rule</word> <word xMin="301.962140" yMin="461.460386" xMax="343.251399" yMax="467.470267">Following</word> </line> </block> </flow> <flow> <block xMin="350.874540" yMin="462.122758" xMax="366.697989" yMax="467.304937"> <line xMin="350.874540" yMin="462.122758" xMax="366.697989" yMax="467.304937"> <word xMin="350.874540" yMin="462.122758" xMax="366.697989" yMax="467.304937">149,</word> </line> </block> </flow> <flow> <block xMin="101.421300" yMin="470.702590" xMax="161.123200" yMax="478.106673"> <line xMin="101.421300" yMin="470.702590" xMax="161.123200" yMax="478.106673"> <word xMin="101.421300" yMin="470.702590" xMax="140.985102" yMax="478.106673">Summary</word> <word xMin="145.154740" yMin="472.586533" xMax="161.123200" yMax="477.816203">151.</word> </line> </block> <block xMin="45.747480" yMin="494.089349" xMax="78.259552" yMax="501.538223"> <line xMin="45.747480" yMin="494.089349" xMax="78.259552" yMax="501.538223"> <word xMin="45.747480" yMin="494.089349" xMax="68.044629" yMax="501.391665">Part</word> <word xMin="73.224740" yMin="494.942618" xMax="78.259552" yMax="501.538223">3</word> </line> </block> <block xMin="46.322920" yMin="516.858265" xMax="85.021260" yMax="522.960011"> <line xMin="46.322920" yMin="516.858265" xMax="85.021260" yMax="522.960011"> <word xMin="46.322920" yMin="516.858265" xMax="77.397543" yMax="522.673659">Chapter</word> <word xMin="81.137040" yMin="517.871683" xMax="85.021260" yMax="522.960011">8</word> </line> </block> </flow> <flow> <block xMin="91.351100" yMin="491.047128" xMax="160.258889" yMax="502.330779">
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <flow> <block xMin="91.351100" yMin="491.047128" xMax="160.258889" yMax="502.330779"> <line xMin="91.351100" yMin="491.047128" xMax="160.258889" yMax="502.330779"> <word xMin="91.351100" yMin="491.047128" xMax="160.258889" yMax="502.330779">ONTOGENY</word> </line> </block> <block xMin="101.709020" yMin="515.005930" xMax="257.940692" yMax="523.695850"> <line xMin="101.709020" yMin="515.005930" xMax="257.940692" yMax="523.695850"> <word xMin="101.709020" yMin="515.005930" xMax="134.798259" yMax="523.675310">MOTOR</word> <word xMin="138.537180" yMin="516.833770" xMax="168.606222" yMax="523.398844">SKILLS</word> <word xMin="172.775860" yMin="515.643854" xMax="240.388046" yMax="523.695850">DEVELOPMENT</word> <word xMin="244.705860" yMin="517.750381" xMax="257.940692" yMax="523.529591">153</word> </line> </block> <block xMin="101.133580" yMin="530.879504" xMax="367.129569" yMax="549.416273"> <line xMin="101.565160" yMin="530.879504" xMax="367.128994" yMax="538.553356"> <word xMin="101.565160" yMin="530.879504" xMax="112.786240" yMax="538.229311">An</word> <word xMin="117.677480" yMin="531.577166" xMax="157.237829" yMax="538.055173">Overview</word> <word xMin="162.130220" yMin="532.682008" xMax="170.186955" yMax="537.959170">of</word> <word xMin="173.782880" yMin="532.675658" xMax="198.812794" yMax="538.140522">Social</word> <word xMin="203.849620" yMin="531.899256" xMax="254.344480" yMax="538.514082">Competency</word> <word xMin="259.379580" yMin="533.182343" xMax="275.779620" yMax="538.553356">153,</word> <word xMin="280.670860" yMin="531.770778" xMax="305.844921" yMax="538.366383">Motor</word> <word xMin="310.306020" yMin="533.091918" xMax="335.767514" yMax="537.856855">Skills:</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="340.804340" yMin="532.161718" xMax="367.128994" yMax="537.909267">Evolu-</word> </line> <line xMin="101.133580" yMin="542.498778" xMax="367.129569" yMax="549.416273"> <word xMin="101.133580" yMin="543.299581" xMax="130.480157" yMax="548.791583">tionary</word> <word xMin="133.358220" yMin="543.217221" xMax="195.072434" yMax="548.991908">Considerations</word> <word xMin="198.095220" yMin="544.084953" xMax="214.063680" yMax="549.314623">157,</word> <word xMin="216.797020" yMin="542.957489" xMax="271.031089" yMax="549.416273">Development</word> <word xMin="273.621720" yMin="543.676868" xMax="282.110035" yMax="549.236715">of</word> <word xMin="283.548060" yMin="543.250686" xMax="319.655769" yMax="549.163323">Reaction</word> <word xMin="321.958680" yMin="542.981952" xMax="345.121579" yMax="549.050632">Time,</word> <word xMin="347.853480" yMin="542.498778" xMax="367.129569" yMax="548.811697">Tim-</word> </line> </block> <block xMin="101.852880" yMin="553.029451" xMax="367.272854" yMax="560.205773"> <line xMin="101.852880" yMin="553.029451" xMax="367.272854" yMax="560.205773"> <word xMin="101.852880" yMin="554.494483" xMax="116.526600" yMax="559.300126">ing,</word> <word xMin="120.410820" yMin="553.255687" xMax="135.372835" yMax="559.789100">and</word> <word xMin="139.400340" yMin="553.029451" xMax="182.123307" yMax="560.025337">Movement</word> <word xMin="185.723260" yMin="553.304519" xMax="206.584111" yMax="560.136447">Time</word> <word xMin="210.611040" yMin="554.874453" xMax="226.579500" yMax="560.104123">161,</word> <word xMin="230.607580" yMin="553.746989" xMax="284.841649" yMax="560.205773">Development</word> <word xMin="288.439300" yMin="554.398518" xMax="296.782605" yMax="559.863382">of</word>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe <word xMin="288.439300" yMin="554.398518" xMax="296.782605" yMax="559.863382">of</word> <word xMin="299.660380" yMin="554.197650" xMax="333.468631" yMax="559.733752">Visually</word> <word xMin="337.063980" yMin="553.205918" xMax="367.272854" yMax="559.801523">Guided</word> </line> </block> </flow> <flow> <block xMin="101.996740" yMin="563.556584" xMax="366.986860" yMax="570.700778"> <line xMin="101.996740" yMin="563.556584" xMax="366.986860" yMax="570.700778"> <word xMin="101.996740" yMin="563.884166" xMax="139.830769" yMax="570.079488">Reaching</word> <word xMin="144.867020" yMin="563.857908" xMax="159.541603" yMax="570.265810">and</word> <word xMin="164.144260" yMin="564.152883" xMax="202.123300" yMax="570.371951">Grasping</word> <word xMin="207.302260" yMin="565.376233" xMax="223.270720" yMax="570.605903">167,</word> <word xMin="228.161960" yMin="564.275915" xMax="282.111186" yMax="570.700778">Development</word> <word xMin="286.712980" yMin="564.975403" xMax="294.913000" yMax="570.346416">of</word> <word xMin="298.365640" yMin="564.856879" xMax="310.593165" yMax="570.196232">the</word> <word xMin="315.197260" yMin="563.556584" xMax="366.986860" yMax="570.341021">Complemen-</word> </line> </block> </flow> </page> </doc> </body> </html>
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe Desired Outcome: | BookmarkTitle | BookmarkLevel | PageNumber | |--------------------------------------------------+---------------+------------------| | Forward | 1 | xi | | Preface and Acknowledgements | 1 | xv | | Illustration Credits | 1 | xvii | | Part 1 Overview and Theory | 1 | 1 | | Chapter 1 OVERVIEW AND SUMMARY | 2 | 1 | | Evolution, Learning and Adaptation | 3 | 1 | | Evolutionary Theory | 3 | 3 | | Evolution, Development and Behavioral Adaptation | 3 | 6 | | ... | ... | ... | | Chapter 2 THEORY OF EVOLUTION | 2 | 21 | | History | 3 | 21 | | Precursors of Darwin and Spencer | 3 | 21 | ``` Answer: updated my code with functions Thank you, that's a lovely refactoring. Now I am brave enough to wade into it. Such structuring helps the Gentle Reader in a few ways: The name documents the one thing this chunk of code tries to do. Local variables go out of scope upon exit, so the Reader doesn't have to hold dozens of facts in his head. In build_dataframe I'm reading df = df.sort_values(by=["page", "yMax", "xMax"]) I wonder if it might be helpful to promote those three to Index? Certainly in an RDBMS table I would define that as the compound PK. I will stay tuned and see how it shakes out.
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe I'm reading consolidate_bboxes, and I have a thing about inplace. In the design of pandas API, it (A.) isn't necessary and (B.) tends to create problems. Nevermind some poor caller that got his supposedly readonly dataframe mutated. Worse, it can lead to chained assignment bugs. Pandas might possibly phase it out in future. So as a knee-jerk response, without even thinking about it, I offer this Tiny Nit. Rephrase as: df = df.sort_values( ... ) df = df.reset_index( ... ) As a bigger item, I confess I cannot explain exactly what this does: df = df.assign(new_yMax=np.where(df['yMax'].diff(-1) == -1, df.yMax + 1, df.yMax)) It seems to be consolidating roundoff issues, so two lines that are almost the same come out the same. But I don't see how that relates to the high level business goal of producing a nicely formatted ToC, and it's not clear that a window of 1 suffices. Perhaps a "small" window should be an input parameter that defaults to 1? Perhaps we'd like another technique for "smoosh them together" or "go with the majority value", such as .median(), so [11, 12, 13, 14] doesn't become new sequential numbers? The identifier new_Ymax is nice enough, but it doesn't help me understand the higher level goal. And then the .groupby() I'm not quite getting, either. We're looking at all words (xMax) on a line, and finding the extent of the line? So, pardon my density, but I'm looking for a little help, which could take any of these forms: A unit test that demonstrates in / out values for this function. Variable name(s) that spell out the intent more clearly. This is already pretty small, but maybe an even tinier helper function that has an informative name. # comments """docstring""" on this or on a tiny helper.
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe tl;dr: If you ask me what this does, I couldn't properly explain it. I feel like I should, but I'm not yet seeing it. Perhaps it will become clearer as I read more code. What I'm going for ATM is Local Analysis -- I should be able to say "this is correct", or that it isn't, and so far I cannot say that conclusively. If you assigned me a maintenance task, I would have some trouble maintaining this particular function. BTW, the function's name is terrific, and offered me a valuable clue. I am just unclear on the details of consolidating those bounding boxes. In part that's because the row count didn't change, so I suppose we're trying to winnow many distinct values down to fewer values. def max_and_min(df): """Helper script to explore extremities to filter off.""" tiny nit: recommend you call it "helper function" or just "helper". I think of a script as a module, a file, which runs top to bottom, such as the part protected by "if name is main". And "explore" tends to describe a person's behavior, so maybe prefer "identify" here. Oh, maybe this is about interactively examining and exploring, as I see there's still a debug print here, nevermind. If the code is stable enough that it's ready for production, maybe remove the debug? That parameter 3 is a magic number. Please give it a name. It tends to be convenient to make it a defaulted kwarg in the function signature. That way callers, such as unit tests, are free to override the default if they wish. I'm not very fond of the identifier min_max. It is clearly accurate, but it's not as helpful as suggested and candidate. However, I confess that I'm still not sure if we're returning per-page vertical extents, or something more fine grained. I do like apply_filter, short and sweet. def is_roman_numeral(num: str) -> bool: Brilliant! Self explanatory, it leaves no questions. The conventional is_ prefix goes with the boolean return. In build_toc, consider eliding this redundant comment: # Iterate through word list
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe In build_toc, consider eliding this redundant comment: # Iterate through word list We see the for word in words, we've got it. The code gives the specifics. Reserve # comments for the general, for the poetic remarks, for higher level items not apparent in the code. Again, <= 332 is a magic number that probably should become a kwarg defaulted parameter. But thank you for the comment explaining its meaning. def build_toc(df, max_pages=332): I imagine we're range limiting it so things like calendar year can't be confused with page numbers. tiniest of nits: caption = None else: caption = None Rather than an else clause, we might just unconditionally assign that after the if. Similarly, you might use not equal, if label[-1] != "-":, to collapse a clause. The if ... label += " " + word idiom commonly comes up, in many languages. The conditional can be slightly distracting. One approach is to init to " " and finally use .lstrip(). Another is to init to [] and finally use " ".join( ... ). No biggie. pg_no += [np.nan] * 3 Again, consider promoting magic number to a kwarg defaulted parameter. Or make this dependent on len(labels). cp = lb + 1 # caption
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe cp = lb + 1 # caption On the one hand, you did a service to the Reader, thank you. OTOH, listen to what the code is telling you. The cp identifier was too obscure, so it needed a comment. Well, that suggests renaming it to caption, right? In any event, kudos, it is much clearer than np.concatenate((lb, lb + 1)). (And BTW lb was perfectly clear from context, it is fine as a local variable, since they have lower documentation burden.) Naming the arr temp var is maybe useful. But consider returning the sort results directly, and telling the Reader the return type via an optional type annotation in the signature. Or maybe the function name told us that already. If I could quibble about the verb for a moment, I would prefer get_bookmarks() (with annotation) or perhaps the more verbose get_bookmark_arrays(). The "build" suggests to me that we're evaluating for side effects and the build product is stored someplace to be accessed later. Kind of like a "print_foo()" prefix, which suggests a single side effect on sys.stdout. But that's just me, reasonable people will differ, YMMV. I'm just revealing my thought process as I read it. def shift_cells_down(df_out, caption): """Shift page-label cells down at cardinal captions where no page number is associated.""" Oooohh! A vocabulary word. I'm sure it has a precise meaning for editors and type setters. I confess I don't know what a cardinal caption is, and google results were entertaining but uninformative. But that's cool, I don't need to understand everything, and I appreciate that you're trying to help me out, "A" for effort. Perhaps it denotes "large font", or "first on page". This is the sort of thing that a unit test can conveniently illustrate.
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe I am reading set_bookmark_levels. The way you're using .loc(), it appears you're extending the dataframe by a row on each iteration. Now, you only iterate a handful of times so it doesn't really matter. But it's not a terrific habit to be in. Pandas, and the underlying numpy, kind of wants to know how many rows to allocate at init time. And then we refrain from adding rows. So a common pattern is to build up a list of dicts (or a dict of lists) which we hand in to pd.DataFrame(). Why? Because numpy allocations, unlike list allocations, are expensive. They may involve copying many data values from small buffer to slightly larger buffer. And this can lead to quadratic performance, something you really don't want. tl;dr: Consider creating that Series with a list comprehension. def set_labels(df_out, loc_arr): Sorry, I don't like the identifier df_out, I don't think it's accurate. Seems pretty clear it is an input which is never altered. Calling it df or maybe df_in would be fine. Or invent a new name, some business term that more precisely describes its contents. if this_index and last_index: if this_index - last_index == 1: tiny nit: The guard, as written, is perfectly lovely. Consider changing 2nd if to and, for same effect. In update_dataframe, usual nit about maybe not using inplace. df_out['BookmarkPageNumber'] = None Consider moving that initialization down to next function, so we see init + assignments all together. In offset_page_numbers, the "skip None" clause is perfectly clear as written. Maybe accomplish that with .dropna()? Whatever. The is_roman_numeral / roman / int calculation is perfectly clear. Consider combining it into a temp var or helper function. No biggie.
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, pandas, pdf, dataframe At toplevel, the # [44, 45, 127, 551] comment is (I'm sure!) helpful to you, but also cryptic, possibly describing troublesome page numbers. Consider writing it as a longer comment on a separate line. Consider immortalizing those page numbers in their very own unit test, which demonstrates the trouble. Consider the trivial refactor of putting all this within def main(): ... return toc_df. Why? So the temp vars go out-of-scope upon function exit. That way we're not polluting the global namespace. Overall? I have to say, I am pretty impressed with two aspects of this code. well organized pipeline of distinct processing steps well chosen identifiers I suspect it was well organized even before functions were imposed on it. And the identifiers are helpful to the Reader, short where local scope makes it appropriate, longer when they're global and so must be self-explanatory. Could others usefully maintain this code? Yes, I think so.
{ "domain": "codereview.stackexchange", "id": 44285, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, pandas, pdf, dataframe", "url": null }
python, console Title: Simple and secure Python console menu without conditionals or match case statements Question: I'm writing a basic tutorial for a simple console menu for Python. I think it is secure, since the input() is controlled by a dispatch. Any suggestions would be appreciated. """ Nice Menu for Python """ import time # used only for testing purposes def m_help(): """ - - - - - - - - - Micro Menu Help - help line 1 - Help line 1 - - - - - - - - -""" print(m_help.__doc__) m_message('...') def m_message(message): """Message.""" print(f'|===> {message} <===|') time.sleep(0.70) # slow down to see the message def m_not_found(): """not found.""" m_message('Choice NOT found, please try again.') def m_view(): """View.""" m_message('`m_view` function was called.') def m_delete(): """Delete.""" m_message('`m_delete` function was called.') def m_quit(): """Quit program.""" m_message('`m_quit` function was called.') quit() def menu_text(): """ Welcome to Micro Menu 1] View (v) 2] Delete 3] Help 4] Quit (q) """ print(menu_text.__doc__) def menu(index): """ Will return a function based on the index.""" dispatcher = { '1': m_view, '2': m_delete, '3': m_help, '4': m_quit, 'v': m_view, # alternative key to '1' 'q': m_quit # alternative key to '3' # ... } return dispatcher.get(index, m_not_found) def main(): """Main function.""" while True: menu_text() choice = input('>> Make your choice: ') menu(choice)() if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 44286, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, console", "url": null }
python, console if __name__ == '__main__': main() Answer: The print(__doc__) pattern is an interesting one but not one that I recommend. Docstrings are meant to document the function itself, and your m_help docstring is not that: instead, presumably, it documents the program. Those are not the same thing. m_function is a little odd as a naming convention. Either spell it out - menu_function - or drop the prefix entirely and make an enclosing module called menu. Since you're just doing simple appends, print(f'|===> {message} <===|') can be expressed as print('|===>', message, '<===|') Do not sleep. "Slowing down to see the message" should not be a concern for this application since you have so little content. If your content grows, sleeping is still not the solution; you would instead want to paginate. Your code is not DRY (don't-repeat-yourself) enough. You write the "index" characters in multiple places. There are many ways to centralise this; I show one below. Try your best to avoid quit(). One simple way is to return a flag from your dispatched functions indicating whether the menu loop needs to break. """View.""", as a comment, is less helpful than having no comment at all. Similar for most of your other comments. Suggested """ Nice Menu for Python """ from typing import Any, Callable, NamedTuple, Iterable, Iterator def menu_help() -> None: print(""" - - - - - - - - - Micro Menu Help - help line 1 - help line 2 - - - - - - - - -""") menu_message('...') def menu_message(message: str) -> None: print('|===>', message, '<===|') def menu_not_found() -> None: menu_message('Choice not found; please try again.') def menu_view() -> None: pass def menu_delete() -> None: pass def menu_quit() -> bool: return True class MenuItem(NamedTuple): index: tuple[str, ...] name: str callback: Callable[[], Any]
{ "domain": "codereview.stackexchange", "id": 44286, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, console", "url": null }
python, console class MenuItem(NamedTuple): index: tuple[str, ...] name: str callback: Callable[[], Any] def __str__(self) -> str: desc = f'{self.index[0]}] {self.name}' if len(self.index) > 1: others = ', '.join(self.index[1:]) desc += f' ({others})' return desc def menu_fragments(items: Iterable[MenuItem]) -> Iterator[str]: yield 'Welcome to Micro Menu' for item in items: yield str(item) def menu_text(items: Iterable[MenuItem]) -> None: print('\n'.join(menu_fragments(items))) def menu(dispatcher: dict[str, MenuItem], index: str) -> Callable[[], Any]: """ Will return a function based on the index.""" item = dispatcher.get(index) if item is None: return menu_not_found # Delete this once you're done debugging the program menu_message(f'`{item.name}` function was called.') return item.callback def main() -> None: items = ( MenuItem(('1', 'v'), 'View', menu_view), MenuItem(('2',), 'Delete', menu_delete), MenuItem(('3',), 'Help', menu_help), MenuItem(('4', 'q'), 'Quit', menu_quit), ) dispatcher = { index: item for item in items for index in item.index } while True: menu_text(items) choice = input('>> Make your choice: ').strip().lower() if menu(dispatcher, choice)(): break print() if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 44286, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, console", "url": null }
object-oriented, ruby, chess Title: Ruby chess engine gem Question: This is my first Ruby gem that claims to provide all the rules of the chess game. My goal was to keep this library as simple as possible via OOP principles, and I'd be glad to hear any feedback from you. In particular, I'm interested in code organization and OOP issues The source code and useful README can be found at GitHub: https://github.com/anikeef/chess_engine The library consists of 5 main parts: Game class that implements the chess rules Board class that provides data structure for the chess board Piece class and its inheritors, which I've tried to make as lightweight as possible MoveValidator module that provides validations methods to Game class Move class that I've found useful to make move canceling easier. I'm particularly interested about what you think about this decision Also it contains the CLI class for command line interface, available with chess_engine executable. NOTE: The "bishop" piece here is referred as the "elephant" because of the russian tradition, but for the rest of the app there should be no difference in naming Game require_relative "board" require_relative "move_validator" require_relative "move" module ChessEngine class InvalidMove < StandardError; end ## # This class provides all the rules for the chess game. It recognizes check, # checkmate and stalemate. Move validations logic can be found in the # MoveValidator module, which is included in this class class Game attr_accessor :name attr_reader :current_color include MoveValidator def initialize @board = Board.new @board.set_default @current_color = :white @last_piece = nil @name = nil @promotion_coords = false end
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
object-oriented, ruby, chess ## # Accepts the move string in algebraic notation, e.g. "e2e4", # and applies it to the board. # Raises InvalidMove if: # * Game is already over # * Pawn promotion should be executed first # * Empty square is chosen # * Player tries to move piece of the opponent # * Move is invalid (checks via the MoveValidator module) # * Move is fatal (king is attacked after the move) # # After successfull move, the method changes the current player or # goes into "A pawn needs promotion" state, which can be checked by # #needs_promotion? method def move(string) from, to = Game.string_to_coords(string) piece = @board.at(from) raise InvalidMove, "Game is over" if over? raise InvalidMove, "#{@current_color} player should execute pawn promotion first" if needs_promotion? raise InvalidMove, "Empty square is chosen" if piece.nil? raise InvalidMove, "This is not your piece" unless piece.color == @current_color raise InvalidMove, "Invalid move" unless valid_moves(from).include?(to) move = Move.new(@board, from, to) move.commit if king_attacked? move.rollback raise InvalidMove, "Fatal move" end @last_piece = piece piece.moves_count += 1 @promotion_coords = to and return if piece.pawn? && [7, 0].include?(to[1]) next_player end ## # Returns a piece (or nil if the square is empty) at given coordinates # === Example # g = Game.new # g["e2"] #=> <Pawn ...> # g["e4"] #=> nil def [](str) letters = ("a".."h").to_a return nil unless /[a-h][1-8]/.match?(str) @board.at([letters.find_index(str[0]), str[1].to_i - 1]) end ## # Returns the board in the nice-looking string def draw @board.to_s end
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
object-oriented, ruby, chess ## # Returns the board in the nice-looking string def draw @board.to_s end ## # Accepts a string with name of the piece. # Promotes a pawn and changes the current player. # Raises InvalidMove if promotion is not needed or invalid +class_name+ # has been passed # === Example # game.promotion("queen") def promotion(class_name) unless needs_promotion? && ["rook", "knight", "elephant", "queen"].include?(class_name.downcase) raise InvalidMove, "Invalid promotion" end @board.set_at(@promotion_coords, Module.const_get("ChessEngine::#{class_name.capitalize}").new(@current_color)) @promotion_coords = nil next_player end ## # Accepts a +length+ sybmol :short or :long. Ensures that castling is # possible and commits appropriate moves. Otherwise, raises InvalidMove def castling(length) row = @current_color == :white ? 0 : 7 king = @board.at([4, row]) if length == :short rook = @board.at([7, row]) line = [5, 6] moves = [Move.new(@board, [4, row], [6, row]), Move.new(@board, [7, row], [5, row])] else rook = @board.at([0, row]) line = [1, 2, 3] moves = [Move.new(@board, [4, row], [2, row]), Move.new(@board, [0, row], [3, row])] end raise InvalidMove, "Invalid castling" unless king && rook && king.moves_count == 0 && rook.moves_count == 0 && line.all? { |x| @board.at([x, row]).nil? } moves.each { |move| move.commit } if king_attacked? moves.each { |move| move.rollback } raise InvalidMove, "Fatal move" end @last_piece = nil next_player end ## # Returns true if game is over def over? @board.pieces_coords(@current_color).all? do |coords| safe_moves(coords).empty? end end ## # Checks if pawn promotion is needed
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
object-oriented, ruby, chess ## # Checks if pawn promotion is needed def needs_promotion? !!@promotion_coords end ## # Returns true if current king is attacked def check? king_attacked? end private def king_attacked? king_coords = @board.king_coords(@current_color) [[1, 1], [-1, 1], [-1, -1], [1, -1]].each do |move| next_coords = relative_coords(king_coords, move) piece = @board.at(next_coords) return true if piece && piece.color != @current_color && (piece.pawn? || piece.king?) edge_coords = repeated_move(king_coords, move).last piece = edge_coords.nil? ? nil : @board.at(edge_coords) return true if piece && piece.beats_diagonally? end [[1, 0], [-1, 0], [0, 1], [0, -1]].each do |move| next_coords = relative_coords(king_coords, move) piece = @board.at(next_coords) return true if piece && piece.king? edge_coords = repeated_move(king_coords, move).last piece = edge_coords.nil? ? nil : @board.at(edge_coords) return true if !piece.nil? && piece.beats_straight? end [[1, 2], [2, 1], [1, -2], [-2, 1], [-1, 2], [2, -1], [-1, -2], [-2, -1]].each do |move| coords = relative_coords(king_coords, move) piece = possible_move?(coords) ? @board.at(coords) : nil return true if !piece.nil? && piece.knight? end false end ## # Converts a string in algebraic notation to array of coordinates # === Example # Game.string_to_coords("a2a4") #=> [[0, 1], [0, 3]] def Game.string_to_coords(string) string = string.gsub(/\s+/, "").downcase raise InvalidMove, "Input must look like \"e2 e4\" or \"a6b5\"" unless /^[a-h][1-8][a-h][1-8]$/.match?(string) letters = ("a".."h").to_a [[letters.find_index(string[0]), string[1].to_i - 1], [letters.find_index(string[2]), string[3].to_i - 1]] end
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
object-oriented, ruby, chess def opposite_color @current_color == :white ? :black : :white end def next_player @current_color = opposite_color end end end MoveValidator module ChessEngine ## # This module contains all the methods needed to check if # some move is valid or not. It is included in the Game class and so uses # some of its attributes: board, current_color and last_piece (for en passant only) module MoveValidator ## Excludes from valid_moves all fatal moves def safe_moves(from) valid_moves(from).reject { |move| fatal_move?(from, move) } end ## # Returns an array of valid moves for a piece at the given position. # Note: this method doesn't exclude moves that lead current king to be attacked # (See +#safe_moves+ method) def valid_moves(from) piece = @board.at(from) if piece.king? || piece.knight? piece.moves.map do |move| to = relative_coords(from, move) to if possible_move?(to) end.compact elsif piece.pawn? pawn_valid_moves(from) else valid_moves_recursive(from) end end ## # Returns an array of coordinates that can be reached by recursively # applying the given +move+, starting from the +from+ coordinates private def repeated_move(from, move, valid_moves = []) coords = relative_coords(from, move) return valid_moves unless possible_move?(coords) return valid_moves << coords unless @board.at(coords).nil? repeated_move(coords, move, valid_moves << coords) end ## # Returns coordinates that will be reached after applying the +move+, # starting from the +from+ coordinates def relative_coords(from, move) [from[0] + move[0], from[1] + move[1]] end ## # Returns true if: # * The 8x8 board exists at given coordinates # * Board at given coordinates is empty or it contains a piece with the same # color as the current_color
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
object-oriented, ruby, chess def possible_move?(coords) if @board.exists_at?(coords) piece = @board.at(coords) return (piece.nil? || piece.color != @current_color) end return false end ## # Returns true if the current king is attacked after the given move def fatal_move?(from, to) is_fatal = false move = Move.new(@board, from, to) move.commit is_fatal = true if king_attacked? move.rollback is_fatal end def pawn_valid_moves(from) pawn = @board.at(from) direction = pawn.direction moves = [] next_coords = relative_coords(from, [0, direction]) jump_coords = relative_coords(from, [0, direction * 2]) take_coords = [relative_coords(from, [1, direction]), relative_coords(from, [-1, direction])] if @board.exists_at?(next_coords) && @board.at(next_coords).nil? moves << next_coords moves << jump_coords unless pawn.moves_count > 0 || @board.at(jump_coords) end take_coords.each do |coords| moves << coords if @board.at(coords) && @board.at(coords).color != pawn.color end en_passant_coords(from) ? moves << en_passant_coords(from) : moves end ## # Returns additional valid coordinates for the pawn if available def en_passant_coords(from) pawn = @board.at(from) [1, -1].each do |x| next_coords = [from[0] + x, from[1]] next_piece = @board.at(next_coords) if next_piece.class == Pawn && next_piece == @last_piece && next_piece.moves_count == 1 && from[1].between?(3, 4) return [from[0] + x, from[1] + pawn.direction] end end nil end ## # This method is used by #valid_moves for pieces like Queen, Rook and Elephant, # that should move recursively
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
object-oriented, ruby, chess def valid_moves_recursive(from) piece = @board.at(from) piece.moves.inject([]) do |valid_moves, move| valid_moves.push(*repeated_move(from, move)) end end end end Move module ChessEngine ## # This class is made to make move canceling easier if something goes wrong. class Move def initialize(board, from, to) @board = board @from = from @to = to @original_squares = [] @original_squares << {coords: from, piece: board.at(from)} @original_squares << {coords: to, piece: board.at(to)} if en_passant? @en_passant_coords = [to[0], from[1]] @original_squares << {coords: @en_passant_coords, piece: board.at(@en_passant_coords)} end end ## # Applies the move to the board def commit if en_passant? @board.set_at(@en_passant_coords, nil) end @board.move_piece(@from, @to) end ## # Moves pieces back and returns the board to the previous state def rollback @original_squares.each do |square| @board.set_at(square[:coords], square[:piece]) end end private def en_passant? @board.at(@from).pawn? && @from[0] != @to[0] && @board.at(@to).nil? end end end ``` Answer: I like move(). At least until encountering this expression at the end: ... && [7, 0].include?(to[1]) At a minimum, please define a .rank (or .row) accessor, so we can banish that magic number of 1. Consider adding a tiny predicate that lets us write ... if piece.pawn? && piece.needs_promotion?. I confess I don't understand the whole "promotion state" design decision. Why not just make it an optional part of a move? So we might see any of: a6 a7 a7 a8 N a7 a8 Q Given that there's a state, I am slightly surprised we don't have "next player" taking on values of white white promoting a pawn black black promoting a pawn but whatever. Six versus half dozen. I will keep reading to see how this pans out.
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
object-oriented, ruby, chess but whatever. Six versus half dozen. I will keep reading to see how this pans out. The def [](str) parsing is nice enough, I guess. It feels like turning e.g. "e4" into (4, 3) should be the Single Responsibility of some helper. I am not especially pleased that there's two ways to return nil: valid deref or invalid coord. If caller passes in "e9", I feel a fatal error should be raised. DbC describes that as caller violating a precondition. In promotion, kudos on assigning @promotion_coords = nil to prevent potential hard-to-diagnose bugs. Getting the "capitalize" reference seemed like a surprisingly verbose operation, but ok, perhaps that's the best we can do. The castling method is lovely. It's very clear. XXX But it doesn't appear to implement standard chess rules. A player may not castle out of, through, or into check. I don't write ruby code daily, so I found the !! double bang in needs_promotion? correct but a bit jargony, and hard-to-google. Is there maybe a bool( ... ) call that would more clearly say the same thing? In king_attacked?, the vectors of orthogonal and diagonal moves make perfect sense. But I wonder if we should rely on some common definition that other pieces can use, as well? XXX I don't understand this expression at all: ... && (piece.pawn? || piece.king?). Suppose White moved "c2 c4", then carnage cleared out the board, then Black's king wandered over to say hello to the other king. If Black's king manages to make a move like "d2 d3", or a move to b3, that is rare but perfectly legit. The bug seems to stem from the fact that piece.beats_diagonally? goes "in both directions", forward and back, while pawn attacks are strictly forward. But the logic I'm reading doesn't match chess rules. This line is correct: return true if piece && piece.king?
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
object-oriented, ruby, chess In the interest of parallel construction, I wouldn't mind seeing a piece.color guard thrown in there. Yes, yes, I know there's two kings so the guard will always evaluate true. Engineers look for such parallelism when maintaining chunks of code that have similar function. In the final .beats_straight and !piece.nil? && piece.knight? expressions, consider sticking with the simpler idiom of piece && ... for the 1st conjunct. I like Game.string_to_coords. I feel that def [](str) which we saw above should be calling it, so validation happens in just one place. Here's a trivial refactor. In fatal_move?, a pair of assignments could be reduced to just is_fatal = king_attacked? In en_passant_coords I found the .between?(3, 4) expression slightly surprising. It seems to conflate both en passant and normal captures. I would have expected "normal" to be handled elsewhere. XXX More seriously, I am concerned that we tested this for White's side of the board, but not Black's. This code mostly implements standard chess rules. In board.rb I would have preferred the spelling valid? over exists_at?. Each time I read "exists" it made think about a piece existing at that location, rather than about whether the location even exists. I wonder if an iteration helper could have buried the issue -- give me some proposed locations (or deltas) and I will iterate over just the ones that are valid. Recursing on "long range" moves, rather than iterating, seemed slightly tricky. In some places the [0] / [1] dereference felt completely natural. In others, I would have been happier to see chess .rank / .file terminology. Overall, looks good.
{ "domain": "codereview.stackexchange", "id": 44287, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, ruby, chess", "url": null }
rust, binary-tree Title: 'Learning' Animal Guesser Program Question: I've written a program that uses a binary tree to essentially 'learn' about animals given the name and questions about them. Learn is probably a little strong of a word, all it does is store the questions using bincode (pre-release 2.0.0-rc.2) and ask them later to figure out what the user is talking about. #![warn(clippy::pedantic, clippy::nursery, rust_2018_idioms)] use std::{fs::File, io::Seek, path::PathBuf}; use bincode::{Decode, Encode}; #[derive(Encode, Decode, Debug)] enum Btree { Branch { question: String, // No left: Box<Btree>, // Yes right: Box<Btree>, }, Leaf { animal: String, }, } impl Btree { fn get_current(&self, current: &[bool]) -> &Self { let mut tree = self; for &i in current { // Should always be a branch if let Self::Branch { question: _, left, right, } = tree { if i { tree = right; } else { tree = left; } } else { unreachable!() } } tree } fn get_current_mut(&mut self, current: &[bool]) -> &mut Self { let mut tree = self; for &i in current { // Should always be a branch if let Self::Branch { question: _, left, right, } = tree { if i { tree = right; } else { tree = left; } } else { unreachable!() } } tree } }
{ "domain": "codereview.stackexchange", "id": 44288, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree fn create_db(db_path: PathBuf) { println!("Database not found, creating now"); let mut db_file = std::fs::File::create(db_path).expect("Couldn't create database file"); let animal1: String = promptly::prompt("Please enter the name of an animal").expect("Couldn't read answer"); let animal2: String = promptly::prompt("Please enter the name of another animal").expect("Couldn't read answer"); let question: String = promptly::prompt(format!( "Please write a yes/no question to differentiate between a(n) {animal1} and a(n) {animal2}" )) .expect("Couldn't read question"); let animal_yesno: bool = promptly::prompt(format!( "Does 'yes' in your question correspond to a {animal1}?" )) .expect("Couldn't read answer"); let btree = if animal_yesno { Btree::Branch { question, left: Box::new(Btree::Leaf { animal: animal2 }), right: Box::new(Btree::Leaf { animal: animal1 }), } } else { Btree::Branch { question, left: Box::new(Btree::Leaf { animal: animal1 }), right: Box::new(Btree::Leaf { animal: animal2 }), } }; bincode::encode_into_std_write(btree, &mut db_file, bincode::config::standard()) .expect("Couldn't save database"); } fn read_db() -> Option<(Btree, File)> { let db_path: PathBuf = promptly::prompt("Enter the database path").expect("Couldn't read database path"); let mut db_file = if let Ok(db_file) = std::fs::OpenOptions::new() .read(true) .write(true) .open(&db_path) { db_file } else { create_db(db_path); return None; }; Some(( bincode::decode_from_std_read(&mut db_file, bincode::config::standard()) .expect("Couldn't parse database"), db_file, )) }
{ "domain": "codereview.stackexchange", "id": 44288, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree fn main() { let (mut db, mut db_file) = match read_db() { Some(dbs) => dbs, None => return, }; let mut current_db = Vec::new(); loop { match db.get_current(&current_db) { Btree::Branch { question, left: _, right: _, } => { let ans: bool = promptly::prompt(question).expect("Couldn't read answer"); if ans { current_db.push(true); } else { current_db.push(false); } } Btree::Leaf { animal } => { let ans: bool = promptly::prompt(format!("Is your animal a(n) {animal}?")) .expect("Couldn't read answer"); if ans { println!("Yay!"); break; } let new_animal: String = promptly::prompt("Please enter the name of your animal") .expect("Couldn't read answer"); let new_question: String = promptly::prompt(format!("Please write a yes/no question to differentiate between a(n) {new_animal} and a(n) {animal}")).expect("Couldn't read question"); let new_animal_yesno: bool = promptly::prompt(format!( "Does 'yes' in your question correspond to a(n) {new_animal}?" )) .expect("Couldn't read answer"); let animal = animal.clone(); let parent = db.get_current_mut(&current_db[0..current_db.len() - 1]); let parent = if let Btree::Branch { question: _, left, right, } = parent { if *current_db.last().unwrap() { right } else { left } } else { unreachable!();
{ "domain": "codereview.stackexchange", "id": 44288, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree } } else { unreachable!(); }; *parent = if new_animal_yesno { Box::new(Btree::Branch { question: new_question, left: Box::new(Btree::Leaf { animal }), right: Box::new(Btree::Leaf { animal: new_animal }), }) } else { Box::new(Btree::Branch { question: new_question, left: Box::new(Btree::Leaf { animal: new_animal }), right: Box::new(Btree::Leaf { animal }), }) }; db_file.rewind().expect("Couldn't truncate database"); bincode::encode_into_std_write(db, &mut db_file, bincode::config::standard()) .expect("Couldn't save database"); println!("Database changes saved"); break; } } } }
{ "domain": "codereview.stackexchange", "id": 44288, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree I'm hoping to be able to find a better way to navigate down the tree instead of using a Vec<bool>. If possible, I'm also hoping for a better way to get around the can't have an immutable and mutable reference at the same time error that I tried to fix with let animal = animal.clone(). Of course, any other improvements are also welcome. Answer: When it comes to tree data structures in Rust, you have three options: Firstly, you can write your algorithm recursively. So you could write a function something like: fn play_game(node: &mut Btree) { // either: play_game(node.left); // or: play_game(node.right); // or: *node = Btree { // replace the node } } Secondly, you can use indexes to keep track your location in the tree. This is essentially what you've done with current_db which keep track of the location of the current node. You can go a little further and always use indexes, even with the data structure itself. enum Node { Branch { question: String, left: usize, right: usize, }, Leaf { animal: String, }, }
{ "domain": "codereview.stackexchange", "id": 44288, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree In this case left and right would be indexes into a Vec<Node> on a basic tree object. Then just keep track of simpler usize indexes to know which node you are working with. Thirdly, you can use RefCell. Instead of Box<Btree> use Box<RefCell<Btree>>. RefCell has interior mutability, you can modify the interior of the RefCell even if you don't have a mutable reference to the RefCell itself. This means that you can navigate and manipulate the parts of the tree more easily at the cost of extra runtime checking. Personally, I favor the first option when my algorithm is naturally suited to running recursively on trees. I favor the second option when I need to freely manipulate a tree. I pretty much never take the third option. As for the animal.clone() issue: If you rewrite your game playing algorithm in a recursive fashion, it should be possible to avoid it. Basically, you need to write the algorithm in such a way that Rust realize that you are replacing the same Btree that you taking the animal String from, so its okay to move it. But in the event that proves tricky, there is an alternative: let animal = std::mem::replace(animal, String::new()); This will replace the original animal name with a temporary empty string (which will not allocate and thus be cheaper than cloning the string) and gives you the original animal String for whatever use you might put it to.
{ "domain": "codereview.stackexchange", "id": 44288, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree Title: Binary space partition implemented in Rust which operates on a 2D vector Question: So I have this binary spaced partition leaf: #[derive(Clone)] pub struct Leaf { container: Rect, left: Option<Box<Leaf>>, right: Option<Box<Leaf>>, room: Option<Rect>, split_vertical: Option<bool>, } impl Leaf { fn new(container: Rect) -> Leaf { Leaf { container, left: None, right: None, room: None, split_vertical: None, } } fn split( &mut self, grid: Vec<Vec<i32>>, mut random_generator: StdRng, min_container_size: i32, debug_game: bool, ) -> bool { if self.left.is_some() && self.right.is_some() { return false; } let mut split_vertical: bool = random_generator.gen::<bool>(); if (self.container.width > self.container.height) && ((self.container.width.unwrap() / self.container.height.unwrap()) as f64 >= 1.25) { split_vertical = true; } else if (self.container.height > self.container.width) && ((self.container.height.unwrap() / self.container.width.unwrap()) as f64 >= 1.25) { split_vertical = false; } let max_size: i32 = if split_vertical { self.container.width.unwrap() - min_container_size } else { self.container.height.unwrap() - min_container_size }; if max_size <= min_container_size { return false; } let mut pos: i32 = random_generator.gen_range(min_container_size..max_size); if split_vertical { pos += self.container.top_left.x; if debug_game { println!("split vertical debug"); }
{ "domain": "codereview.stackexchange", "id": 44289, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree self.left = Option::from(Box::new(Leaf { container: Rect { top_left: Point { x: self.container.top_left.x, y: self.container.top_left.y, }, bottom_right: Point { x: pos - 1, y: self.container.bottom_right.y, }, center: None, width: None, height: None, }, left: None, right: None, room: None, split_vertical: None, })); self.right = Option::from(Box::new(Leaf { container: Rect { top_left: Point { x: pos + 1, y: self.container.top_left.y, }, bottom_right: Point { x: self.container.bottom_right.x, y: self.container.bottom_right.y, }, center: None, width: None, height: None, }, left: None, right: None, room: None, split_vertical: None, })) } else { pos += self.container.top_left.y; if debug_game { println!("split horizontal debug"); }
{ "domain": "codereview.stackexchange", "id": 44289, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree self.left = Option::from(Box::new(Leaf { container: Rect { top_left: Point { x: self.container.top_left.x, y: self.container.top_left.y, }, bottom_right: Point { x: self.container.bottom_right.x, y: pos - 1, }, center: None, width: None, height: None, }, left: None, right: None, room: None, split_vertical: None, })); self.right = Option::from(Box::new(Leaf { container: Rect { top_left: Point { x: self.container.top_left.x, y: pos - 1, }, bottom_right: Point { x: self.container.bottom_right.x, y: self.container.bottom_right.y, }, center: None, width: None, height: None, }, left: None, right: None, room: None, split_vertical: None, })) } self.split_vertical = Option::from(split_vertical); return true; } fn create_room( &mut self, grid: Vec<Vec<i32>>, mut random_generator: StdRng, min_room_size: i32, room_ratio: f32, ) -> bool { if self.left.is_some() && self.right.is_some() { return false; } let width: i32 = random_generator.gen_range(min_room_size..self.container.width.unwrap()); let height: i32 = random_generator.gen_range(min_room_size..self.container.height.unwrap());
{ "domain": "codereview.stackexchange", "id": 44289, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree let x_pos: i32 = random_generator .gen_range(self.container.top_left.x..self.container.bottom_right.x - width); let y_pos: i32 = random_generator .gen_range(self.container.top_left.y..self.container.bottom_right.y - height); let rect: Rect = Rect { top_left: Point { x: x_pos, y: y_pos }, bottom_right: Point { x: x_pos + width - 1, y: y_pos + height - 1, }, center: None, width: None, height: None, }; if ((min(rect.width.unwrap(), rect.height.unwrap()) as f32) / (max(rect.width.unwrap(), rect.height.unwrap()) as f32)) < room_ratio { return false; } rect.place_rect(grid); self.room = Option::from(rect); return true; } } And the Point and Rect structs: #[derive(PartialEq, Eq, Hash, Clone, Copy)] pub struct Point { pub x: i32, pub y: i32, } impl Point { fn new(x: i32, y: i32) -> Point { Point { x, y } } pub fn sum(&self, other: &Point) -> (i32, i32) { (self.x + other.x, self.y + other.y) } pub fn abs_diff(&self, other: &Point) -> (i32, i32) { ((self.x - other.x).abs(), (self.y - other.y).abs()) } } #[derive(Clone)] pub struct Rect { pub top_left: Point, pub bottom_right: Point, pub center: Option<Point>, pub width: Option<i32>, pub height: Option<i32>, }
{ "domain": "codereview.stackexchange", "id": 44289, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree impl Rect { fn new(top_left: Point, bottom_right: Point) -> Rect { let sum: (i32, i32) = top_left.sum(&bottom_right); let diff: (i32, i32) = bottom_right.abs_diff(&top_left); Rect { top_left, bottom_right, center: Option::from(Point { x: ((sum.0 as f32) / 2.0).round() as i32, y: ((sum.1 as f32) / 2.0).round() as i32, }), width: Option::from(diff.0), height: Option::from(diff.1), } } pub fn get_distance_to(&self, other: &Rect) -> i32 { return max( (self.center.unwrap().x - other.center.unwrap().x).abs(), (self.center.unwrap().y - other.center.unwrap().y).abs(), ); } pub fn place_rect(&self, grid: Vec<Vec<i32>>) {} } However, I'm fairly new to Rust and am not sure how to optimise this further than I already have. I know there's some repetition (especially with creating the child leafs) and wanted to know if there was a way to simplify it, speed it up, and make it more idiomatic? Answer: #[derive(Clone)] pub struct Leaf { container: Rect, left: Option<Box<Leaf>>, right: Option<Box<Leaf>>, room: Option<Rect>, split_vertical: Option<bool>, } The left, right, and split_vertical options are all linked. They are all set together. So I'd do something like: #[derive(Clone)] pub struct Division { left: Leaf, right: Leaf, split_vertical: bool } #[derive(Clone)] pub struct Leaf { container: Rect, division: Option<Box<Division>>, room: Option<Rect>, }
{ "domain": "codereview.stackexchange", "id": 44289, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
rust, binary-tree This will allow you to simplify the code quite a bit as you don't have to create multiple options/boxes/unwrap separate fields. self.left = Option::from(Box::new(Leaf { container: Rect { top_left: Point { x: self.container.top_left.x, y: self.container.top_left.y, }, bottom_right: Point { x: self.container.bottom_right.x, y: pos - 1, }, center: None, width: None, height: None, }, left: None, right: None, room: None, split_vertical: None, })); You already have Leaf::new and Rect::new which could be used to avoid most of the boilerplate that you have here. self.left = Option::from(Box::new(Leaf::new(Rect::new(Point { x: self.container.top_left.x, y: self.container.top_left.y, }, Point { x: self.container.bottom_right.x, y: pos - 1, }))));
{ "domain": "codereview.stackexchange", "id": 44289, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, binary-tree", "url": null }
c#, async-await, task-parallel-library Title: Implement DRY principle with IAsyncDisposable Question: This is a tiny class that creates backup copies of a file so these can be diff'ed to spot the changes compared to last run; used when generating code and so far has proved to be very helpful. Basically, I reuse the async disposable logic because it doesn't really make sense to write it twice; the documentation simply doesn't bother about that so it's more or less an improvisation. Example: await using (var history = await FileHistory.CreateAsync("test.cs")) { if (history != null) { var path = history.Info.FullName; var text = DateTime.Now.ToString(CultureInfo.InvariantCulture); await File.WriteAllTextAsync(path, text); } } The first time it is run: user writes test.cs nothing else happens as there's no history yet The second time it is run: user writes test.cs writes previous version of test.cs to test-backup.cs The third time it is run: user writes test.cs writes previous version of test-backup.cs to test-backup-2022-12-31T22-29-28-8881210Z.cs writes previous version of test.cs to test-backup.cs And so on, it creates backup copies of the file which can then be compared for changes. Code: using JetBrains.Annotations; namespace abcd; public sealed class FileHistory : IDisposable, IAsyncDisposable { private FileHistory(FileInfo info, byte[] data) { Info = info; Data = data; } [PublicAPI] public FileInfo Info { get; } private byte[] Data { get; } private bool IsDisposed { get; set; } public async ValueTask DisposeAsync() { await DisposeAsyncCore(false).ConfigureAwait(false); GC.SuppressFinalize(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~FileHistory() { Dispose(false); } private async ValueTask DisposeAsyncCore(bool disposing) { if (IsDisposed) return;
{ "domain": "codereview.stackexchange", "id": 44290, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, async-await, task-parallel-library", "url": null }
c#, async-await, task-parallel-library if (disposing) { // NOP } if (Data.Length is not 0) { Info.Refresh(); if (Info.Exists) { var name = Info.FullName; var data = await File.ReadAllBytesAsync(name); if (data.AsSpan().SequenceEqual(Data) is false) { var type = Path.GetExtension(name); name = name[..^type.Length]; var path = $"{name}-backup{type}"; if (File.Exists(path)) { var time = File.GetLastWriteTimeUtc(path); var dest = $"{name}-backup-{time.ToString("O").Replace(':', '-').Replace('.', '-')}{type}"; File.Move(path, dest); } await File.WriteAllBytesAsync(path, Data); } } } IsDisposed = true; } private void Dispose(bool disposing) { DisposeAsyncCore(disposing).AsTask().Wait(); } public static async Task<FileHistory?> CreateAsync(string path, CancellationToken cancellationToken = default) { var info = new FileInfo(path); byte[] data; if (info.Exists) { await using var stream = info.OpenRead(); data = new byte[stream.Length]; // ReSharper disable once UnusedVariable var read = await stream.ReadAsync(data, cancellationToken); } else { data = Array.Empty<byte>(); } return cancellationToken.IsCancellationRequested ? null : new FileHistory(info, data); } } Answer: I read your code three times and quite frankly it does not make too much sense for me. (Maybe I'm just tired, but still it doesn't ...) You have implemented the disposable pattern where your are not freeing up any resources
{ "domain": "codereview.stackexchange", "id": 44290, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, async-await, task-parallel-library", "url": null }
c#, async-await, task-parallel-library You have implemented the disposable pattern where your are not freeing up any resources The FileHistory does not even own any resources at all It seems like the whole implementation is aiming for small file which can nicely fit into a pre-allocated byte array but it would miserably fail with large files you are reading the entire file again and compare its content byte-wise why checking the last modification date is not enough? ToString("O").Replace(':', '-').Replace('.', '-') This date formatting logic is ... well sub-optimal Sometimes you try to follow good async practices like: .ConfigureAwait(false) Where other times you don't: .AsTask().Wait() Apologize if my post felt as offensive that was not my intent. UPDATE #1 As for the date formatting, I don't know, maybe you can suggest better. Your chosen date time format (2022-12-31T22-29-28-8881210Z) is not supported out of the box by any formatter. Mostly because the hyphens are usually used only on the date part, but not on the time component. So, using o or s formatter changes only the date part: o: 2023-01-03T08:23:27.1870000Z s: 2023-01-03T08:23:27 There is a class called DateTimeFormatInfo which has a DateSeparator and a TimeSeparator. You can set both to hyphens. CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); DateTimeFormatInfo dtfi = culture.DateTimeFormat; dtfi.DateSeparator = "-"; dtfi.TimeSeparator = "-"; The problem with this approach is that the o or s formatter does not take advantage of the TimeSeparator :( G: 1-3-2023 8-28-52 AM O: 2023-01-03T08:28:52.8980000Z s: 2023-01-03T08:28:52 T: 8-28-52 AM u: 2023-01-03 08:28:52Z U: Tuesday, January 3, 2023 8-28-52 AM You can set the FullDateTimePattern on the DateTimeFormatInfo to specify how the U formatter should work dtfi.FullDateTimePattern = "yyyy-MM-ddThh-mm-ss-ffffffZ"; //2023-01-03T08-34-30-538000Z
{ "domain": "codereview.stackexchange", "id": 44290, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, async-await, task-parallel-library", "url": null }