-
Notifications
You must be signed in to change notification settings - Fork 0
Update calculator.py #35
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -19,4 +19,13 @@ def multiplyBy6(x, y): | |||||||||||||||||||
| return x * y * 66 | ||||||||||||||||||||
|
|
||||||||||||||||||||
| def multiplyBy62(x, y): | ||||||||||||||||||||
| return x * y * 12412 + 213 | ||||||||||||||||||||
|
Comment on lines
21
to
+22
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The modification to this function changes its behavior by adding 213 to the result. This appears to be an unintentional change that breaks the function's original purpose. If this change is intentional, please update the function name to reflect its new behavior and add documentation explaining the purpose of the constant 213.
Suggested change
Did we get this right? 👍 / 👎 to inform future reviews |
||||||||||||||||||||
|
|
||||||||||||||||||||
| def multiplyBy622(x, y): | ||||||||||||||||||||
| return x * y * 12412 | ||||||||||||||||||||
|
|
||||||||||||||||||||
|
Comment on lines
+24
to
+26
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function name
Suggested change
Helpful? 👍 👎
Comment on lines
+24
to
+26
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This new function
Suggested change
Did we get this right? 👍 / 👎 to inform future reviews |
||||||||||||||||||||
|
|
||||||||||||||||||||
| def multiplyBy623(x, y): | ||||||||||||||||||||
| return x * y * 12412 | ||||||||||||||||||||
| print("delete") | ||||||||||||||||||||
|
|
||||||||||||||||||||
|
Comment on lines
+30
to
+31
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The
Suggested change
Helpful? 👍 👎 |
||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| import os, sys, re, math, time, random, threading, multiprocessing, asyncio | ||
| import sqlite3, json, requests | ||
| import pandas as pd | ||
| import numpy as np | ||
| import matplotlib.pyplot as plt | ||
| from functools import wraps | ||
| from argparse import ArgumentParser | ||
|
|
||
| DB_FILE = "data.db" | ||
|
|
||
| def log_time(func): | ||
| @wraps(func) | ||
| def wrapper(*args, **kwargs): | ||
| start = time.time() | ||
| result = func(*args, **kwargs) | ||
| print(f"{func.__name__} executed in {time.time() - start:.2f}s") | ||
| return result | ||
| return wrapper | ||
|
|
||
| class DataProcessor: | ||
| def __init__(self, db_path): | ||
| self.db_path = db_path | ||
| self.conn = sqlite3.connect(db_path) | ||
| self.create_table() | ||
|
|
||
| def create_table(self): | ||
| c = self.conn.cursor() | ||
| c.execute('''CREATE TABLE IF NOT EXISTS entries (id INTEGER PRIMARY KEY, text TEXT, value REAL)''') | ||
| self.conn.commit() | ||
|
|
||
| def insert_entry(self, text, value): | ||
| c = self.conn.cursor() | ||
| c.execute('INSERT INTO entries (text, value) VALUES (?, ?)', (text, value)) | ||
| self.conn.commit() | ||
|
|
||
| def query_entries(self): | ||
| c = self.conn.cursor() | ||
| return c.execute('SELECT * FROM entries').fetchall() | ||
|
|
||
| def close(self): | ||
| self.conn.close() | ||
|
|
||
| @log_time | ||
| def simulate_web_fetch(): | ||
| r = requests.get("https://httpbin.org/get") | ||
| return r.json() | ||
|
|
||
| def regex_filter(lines, pattern): | ||
| return [line for line in lines if re.search(pattern, line)] | ||
|
|
||
| def generate_data(n=1000): | ||
| return pd.DataFrame({ | ||
| "x": np.linspace(0, 10, n), | ||
| "y": np.sin(np.linspace(0, 10, n)) + np.random.normal(0, 0.1, n) | ||
| }) | ||
|
|
||
| @log_time | ||
| def plot_data(df): | ||
| plt.plot(df['x'], df['y']) | ||
| plt.title("Noisy Sine Wave") | ||
| plt.savefig("plot.png") | ||
| plt.close() | ||
|
|
||
| async def async_fetch(url): | ||
| loop = asyncio.get_event_loop() | ||
| return await loop.run_in_executor(None, requests.get, url) | ||
|
|
||
| @log_time | ||
| def run_async_tasks(): | ||
| urls = [f"https://httpbin.org/delay/{i%3}" for i in range(5)] | ||
| results = asyncio.run(asyncio.gather(*[async_fetch(url) for url in urls])) | ||
| return [r.status_code for r in results] | ||
|
|
||
| def thread_task(n): | ||
| print(f"Thread {n} sleeping...") | ||
| time.sleep(random.uniform(0.5, 2.0)) | ||
| print(f"Thread {n} done.") | ||
|
|
||
| def run_threads(): | ||
| threads = [threading.Thread(target=thread_task, args=(i,)) for i in range(5)] | ||
| [t.start() for t in threads] | ||
| [t.join() for t in threads] | ||
|
|
||
| def process_task(x): | ||
| return math.sqrt(x ** 2 + 1) | ||
|
|
||
| def run_processes(): | ||
| with multiprocessing.Pool(4) as pool: | ||
| return pool.map(process_task, range(10000)) | ||
|
|
||
| def write_large_file(filename, n=100000): | ||
| with open(filename, "w") as f: | ||
| for i in range(n): | ||
| f.write(f"{i},value={random.random()}\n") | ||
|
|
||
| def read_and_process_file(filename): | ||
| with open(filename) as f: | ||
| return sum(1 for line in f if float(line.split('=')[1]) > 0.5) | ||
|
|
||
| def main(): | ||
| parser = ArgumentParser() | ||
| parser.add_argument("--file", type=str, default="large.txt") | ||
| parser.add_argument("--insert", action="store_true") | ||
| args = parser.parse_args() | ||
|
|
||
| write_large_file(args.file) | ||
| print("File written.") | ||
| count = read_and_process_file(args.file) | ||
| print(f"Lines with value > 0.5: {count}") | ||
|
|
||
| dp = DataProcessor(DB_FILE) | ||
| if args.insert: | ||
| for _ in range(100): | ||
| dp.insert_entry("sample", random.random()) | ||
| entries = dp.query_entries() | ||
| print(f"Loaded {len(entries)} DB entries.") | ||
| dp.close() | ||
|
|
||
| data = generate_data() | ||
| plot_data(data) | ||
| print("Plot saved.") | ||
| run_threads() | ||
| print("Threading done.") | ||
| result = run_processes() | ||
| print(f"Process result sample: {result[:5]}") | ||
| print("Async fetch status codes:", run_async_tasks()) | ||
| print("Web fetch sample:", simulate_web_fetch()) | ||
|
|
||
| if __name__ == "__main__": | ||
| main() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import random, time, json, math, logging | ||
| from typing import List, Dict | ||
| from functools import lru_cache | ||
|
|
||
| logging.basicConfig(level=logging.INFO, format="%(message)s") | ||
| logger = logging.getLogger("GalacticSim") | ||
|
|
||
| class ResourceNotFound(Exception): pass | ||
|
|
||
| class Resource: | ||
| def __init__(self, name: str, base_price: float): | ||
| self.name = name | ||
| self.base_price = base_price | ||
|
|
||
| def price_fluctuation(self): | ||
| return round(self.base_price * random.uniform(0.8, 1.2), 2) | ||
|
|
||
| class Planet: | ||
| def __init__(self, name: str, richness: float, population: int): | ||
| self.name = name | ||
| self.richness = richness | ||
| self.population = population | ||
| self.resources: Dict[str, float] = {} | ||
| self._generate_resources() | ||
|
|
||
| def _generate_resources(self): | ||
| for res in ["metal", "gas", "spice", "water"]: | ||
| self.resources[res] = max(0.1, self.richness * random.uniform(0.5, 2)) | ||
|
|
||
| def consume(self, resource: str, amount: float): | ||
| if self.resources.get(resource, 0) < amount: | ||
| raise ResourceNotFound(f"{self.name} lacks {resource}") | ||
| self.resources[resource] -= amount | ||
|
|
||
| def produce(self, resource: str, amount: float): | ||
| self.resources[resource] = self.resources.get(resource, 0) + amount | ||
|
|
||
| def __repr__(self): | ||
| return f"<Planet {self.name} pop={self.population} res={self.resources}>" | ||
|
|
||
| class TradeRoute: | ||
| def __init__(self, source: Planet, target: Planet, resource: str): | ||
| self.source = source | ||
| self.target = target | ||
| self.resource = resource | ||
| self.distance = self.compute_distance() | ||
|
|
||
| def compute_distance(self): | ||
| return random.uniform(1.0, 100.0) | ||
|
|
||
| def transfer(self): | ||
| try: | ||
| amt = min(5.0, self.source.resources.get(self.resource, 0)) | ||
| if amt <= 0: | ||
| return 0 | ||
| self.source.consume(self.resource, amt) | ||
| self.target.produce(self.resource, amt) | ||
| logger.info(f"{amt} {self.resource} transferred {self.source.name} -> {self.target.name}") | ||
| return amt | ||
| except ResourceNotFound as e: | ||
| logger.warning(str(e)) | ||
| return 0 | ||
|
|
||
| class Galaxy: | ||
| def __init__(self, n=5): | ||
| self.planets = [Planet(f"Planet-{i}", random.uniform(0.5, 2.0), random.randint(1000, 1000000)) for i in range(n)] | ||
| self.routes: List[TradeRoute] = [] | ||
| self.resources = [Resource("metal", 10), Resource("gas", 20), Resource("spice", 100), Resource("water", 5)] | ||
| self._generate_routes() | ||
|
|
||
| def _generate_routes(self): | ||
| for _ in range(10): | ||
| p1, p2 = random.sample(self.planets, 2) | ||
| r = random.choice(["metal", "gas", "spice", "water"]) | ||
| self.routes.append(TradeRoute(p1, p2, r)) | ||
|
|
||
| def tick(self): | ||
| logger.info("=== GALAXY TICK ===") | ||
| for r in self.routes: | ||
| r.transfer() | ||
| self._update_prices() | ||
| self._simulate_population() | ||
|
|
||
| @lru_cache(maxsize=16) | ||
| def get_resource_price(self, name: str): | ||
| for r in self.resources: | ||
| if r.name == name: | ||
| return r.price_fluctuation() | ||
| raise ResourceNotFound(name) | ||
|
|
||
| def _update_prices(self): | ||
| for r in self.resources: | ||
| price = r.price_fluctuation() | ||
| logger.info(f"Market update: {r.name} = {price} credits") | ||
|
|
||
| def _simulate_population(self): | ||
| for p in self.planets: | ||
| growth = int(p.population * random.uniform(-0.01, 0.02)) | ||
| p.population += growth | ||
| logger.info(f"{p.name} population change: {growth:+}") | ||
|
|
||
| def save_state(self, file="galaxy.json"): | ||
| state = { | ||
| "planets": [{ | ||
| "name": p.name, | ||
| "population": p.population, | ||
| "richness": p.richness, | ||
| "resources": p.resources | ||
| } for p in self.planets] | ||
| } | ||
| with open(file, "w") as f: | ||
| json.dump(state, f, indent=2) | ||
|
|
||
| def load_state(self, file="galaxy.json"): | ||
| with open(file) as f: | ||
| state = json.load(f) | ||
| self.planets = [] | ||
| for pd in state["planets"]: | ||
| p = Planet(pd["name"], pd["richness"], pd["population"]) | ||
| p.resources = pd["resources"] | ||
| self.planets.append(p) | ||
|
|
||
| if __name__ == "__main__": | ||
| g = Galaxy(n=8) | ||
| for _ in range(5): | ||
| g.tick() | ||
| time.sleep(1) | ||
| g.save_state() |
Large diffs are not rendered by default.
Large diffs are not rendered by default.
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| interactions: | ||
| - request: | ||
| body: null | ||
| headers: | ||
| Accept: | ||
| - application/vnd.github.machine-man-preview+json | ||
| Accept-Encoding: | ||
| - gzip, deflate | ||
| Connection: | ||
| - keep-alive | ||
| Content-Length: | ||
| - '0' | ||
| User-Agent: | ||
| - Codecov | ||
| method: POST | ||
| uri: https://api.github.com/app/installations/1654873/access_tokens | ||
| response: | ||
| body: | ||
| string: '{"token":"v1.test50wm4qyel2pbtpbusklcarg7c2etcbunnswp","expires_at":"2019-08-26T01:25:56Z","permissions":{"checks":"write","pull_requests":"write","statuses":"write","administration":"read","contents":"read","issues":"read","metadata":"read"},"repository_selection":"selected"}' | ||
| headers: | ||
| Access-Control-Allow-Origin: | ||
| - '*' | ||
| Access-Control-Expose-Headers: | ||
| - ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, | ||
| X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, | ||
| X-GitHub-Media-Type | ||
| Cache-Control: | ||
| - public, max-age=60, s-maxage=60 | ||
| Content-Length: | ||
| - '277' | ||
| Content-Security-Policy: | ||
| - default-src 'none' | ||
| Content-Type: | ||
| - application/json; charset=utf-8 | ||
| Date: | ||
| - Mon, 26 Aug 2019 00:25:57 GMT | ||
| ETag: | ||
| - '"d5bbd7f7363c549c2faa22e8f4419077"' | ||
| Referrer-Policy: | ||
| - origin-when-cross-origin, strict-origin-when-cross-origin | ||
| Server: | ||
| - GitHub.com | ||
| Status: | ||
| - 201 Created | ||
| Strict-Transport-Security: | ||
| - max-age=31536000; includeSubdomains; preload | ||
| Vary: | ||
| - Accept | ||
| X-Content-Type-Options: | ||
| - nosniff | ||
| X-Frame-Options: | ||
| - deny | ||
| X-GitHub-Media-Type: | ||
| - github.machine-man-preview; format=json | ||
| X-GitHub-Request-Id: | ||
| - 3B5C:44FD:19779AA:3C3CF0D:5D632714 | ||
| X-XSS-Protection: | ||
| - 1; mode=block | ||
| status: | ||
| code: 201 | ||
| message: Created | ||
| version: 1 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| interactions: | ||
| - request: | ||
| body: null | ||
| headers: | ||
| Accept: | ||
| - application/vnd.github.machine-man-preview+json | ||
| Accept-Encoding: | ||
| - gzip, deflate | ||
| Connection: | ||
| - keep-alive | ||
| Content-Length: | ||
| - '0' | ||
| User-Agent: | ||
| - Codecov | ||
| method: POST | ||
| uri: https://api.github.com/app/installations/1654873/access_tokens | ||
| response: | ||
| body: | ||
| string: '{"token":"v1.test50wm4qyel2pbtpbusklcarg7c2etcbunnswp","expires_at":"2019-08-26T01:25:56Z","permissions":{"checks":"write","pull_requests":"write","statuses":"write","administration":"read","contents":"read","issues":"read","metadata":"read"},"repository_selection":"selected"}' | ||
| headers: | ||
| Access-Control-Allow-Origin: | ||
| - '*' | ||
| Access-Control-Expose-Headers: | ||
| - ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, | ||
| X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, | ||
| X-GitHub-Media-Type | ||
| Cache-Control: | ||
| - public, max-age=60, s-maxage=60 | ||
| Content-Length: | ||
| - '277' | ||
| Content-Security-Policy: | ||
| - default-src 'none' | ||
| Content-Type: | ||
| - application/json; charset=utf-8 | ||
| Date: | ||
| - Mon, 26 Aug 2019 00:25:57 GMT | ||
| ETag: | ||
| - '"d5bbd7f7363c549c2faa22e8f4419077"' | ||
| Referrer-Policy: | ||
| - origin-when-cross-origin, strict-origin-when-cross-origin | ||
| Server: | ||
| - GitHub.com | ||
| Status: | ||
| - 201 Created | ||
| Strict-Transport-Security: | ||
| - max-age=31536000; includeSubdomains; preload | ||
| Vary: | ||
| - Accept | ||
| X-Content-Type-Options: | ||
| - nosniff | ||
| X-Frame-Options: | ||
| - deny | ||
| X-GitHub-Media-Type: | ||
| - github.machine-man-preview; format=json | ||
| X-GitHub-Request-Id: | ||
| - 3B5C:44FD:19779AA:3C3CF0D:5D632714 | ||
| X-XSS-Protection: | ||
| - 1; mode=block | ||
| status: | ||
| code: 201 | ||
| message: Created | ||
| version: 1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The modification to
multiplyBy62changes its behavior by adding 213 to the result. This is a breaking change that will cause existing tests to fail and may break dependent code. If this is intentional, consider renaming the function to reflect its new behavior (e.g.,multiplyBy62WithOffset) or create a new function instead.Helpful? 👍 👎