def __init__(self, location, amount, consumption, distance, age): super().__init__() self.location = location self.amount = amount self.consumption = consumption self.distance = distance * 1000 self.age = age self.route_cache = RouteCache('data') self.router = Router() self.pane = LiveRender("") console.print(self.pane.position_cursor()) console.print(self.pane)
def run_complex() -> None: cache = Cache() console = Console() filter_year = int(os.environ.get("YEAR", 0)) by_year: Dict[int, List[Target]] = {} for target in discover(): if target.year not in by_year: by_year[target.year] = [] by_year[target.year].append(target) for year, targets in by_year.items(): if filter_year and filter_year != year: continue table = Table( show_header=True, box=box.HORIZONTALS, header_style="bold", show_edge=False, show_lines=False, title=f":christmas_tree: [b]Year {year} :christmas_tree:", title_style="white", ) table.add_column("") table.add_column("Part 1") table.add_column("Part 2") # Set up rows for each day for day in range(1, 26): table.add_row(f"Day {day}", "", "") # Set up live render live_render = LiveRender(table) # Print initial table console.print(live_render) for target in targets: path = target.get_path() path_hash = f"{cache.hash_folder(path)}" lst: List[Literal[1, 2]] = [1, 2] # For mypy... for part in lst: part_hash = f"{path_hash}-part_{part}" if not (solution := cache.get_cached(part_hash)): table.columns[part]._cells[target.day - 1] = "..." console.print(live_render.position_cursor(), live_render) solution = target.get_solution(part) cache.update_cache(part_hash, solution) table.columns[part]._cells[target.day - 1] = str(solution) console.print(live_render.position_cursor(), live_render)
def live_render(): return LiveRender(renderable="my string")
return False params = {"msgtype": "text", "text": {"content": msg}} ret = requests.post(web_hook_url, json=params) return ret.ok and ret.json()['errmsg'] == 'ok' if __name__ == "__main__": if len(sys.argv) >= 1: nofitication_web_hook_urls = sys.argv[1:] else: nofitication_web_hook_urls = [] console = Console() lr = LiveRender(None) stat_table = Table(title='历史北向资金净流入统计', show_header=True, header_style="bold blue") stat_table.add_column("Name") stat_table.add_column("Mean") stat_table.add_column("Std") console.print(f"历史北向资金流向url:{his_flow_url}") console.print(f"实时北向资金流向url:{realtime_flow_url}") his_money_flow = get_history_money_flow(his_flow_url) statistics = calc_his_statistics(his_money_flow) for name, stats in statistics.items(): stat_table.add_row(name, *map(str, stats)) notify_state = {
class PriceCalculator(object): def __init__(self, location, amount, consumption, distance, age): super().__init__() self.location = location self.amount = amount self.consumption = consumption self.distance = distance * 1000 self.age = age self.route_cache = RouteCache('data') self.router = Router() self.pane = LiveRender("") console.print(self.pane.position_cursor()) console.print(self.pane) def update_count(self, count): self.pane.set_renderable( Panel(f'Api requests made: {count}', box=SIMPLE)) console.print(self.pane.position_cursor()) console.print(self.pane) def calc(self, row): lat = row["lat"] lon = row["lon"] name = row["Name"] price = row["95E10 Price"] route_query = f"{lat},{lon}" if lat and lon else f'{name} Helsinki' distance, duration, route_path = self.router.get_route( self.location, route_query, self.route_cache) self.update_count(self.router.count) total_price = ((self.consumption / 100) * distance * 2 * price) + self.amount \ * price if price and distance else None gas_price = self.amount * price if price else None return pd.Series({ "Distance": f'{round(distance * 2)}', "Duration": f'{round(duration * 2)}', "Total price": total_price, f"{self.amount}l price": gas_price }) def cal_via(self, row, shortest_distance, shortest_duration): lat = row["lat"] lon = row["lon"] price = row["95E10 Price"] origin, destination = self.location station = f"{lat},{lon}" distance_from_origin, duration_from_origin, _ = \ self.router.get_route(origin, station, self.route_cache) distance_from_station, duration_from_station, _ = \ self.router.get_route(station, destination, self.route_cache) self.update_count(self.router.count) full_distance = distance_from_origin + distance_from_station full_duration = round(duration_from_origin + duration_from_station) distance_delta = full_distance - shortest_distance total_price = ((self.consumption / 100) * distance_delta * 2 * price) \ + self.amount * price if price and distance_delta is not None else None gas_price = self.amount * price if price else None return pd.Series({ "Distance": f'+{round((distance_delta)*1000)}m', "Duration": f'+{round(full_duration-shortest_duration)}min', "Total price": total_price, "40l price": gas_price }) def filter_stations(self, stations, filter_by_distance=False): notnull_stations = stations.merge(stations.apply(lambda row: pd.Series( {"point": _project(Point(row["lat"], row["lon"]))}), axis=1), left_index=True, right_index=True) now = datetime.now() notnull_stations = notnull_stations[notnull_stations.apply( lambda row: (now - row["Timestamp"]).days <= self.age, axis=1)] if filter_by_distance: lat, lon = self.router.get_point(self.location, self.route_cache) from_point = _project(Point(lat, lon)) notnull_stations = notnull_stations[notnull_stations.apply( lambda row: row["point"].distance(from_point) <= self.distance, axis=1)] return notnull_stations def calc_via_route(self, stations): start, end = self.location distance, duration, route_path = \ self.router.get_route(start, end, self.route_cache) self.update_count(self.router.count) line = _project(LineString(route_path)) notnull_stations = stations.merge(stations.apply(lambda row: pd.Series( {"point": _project(Point(row["lat"], row["lon"]))}), axis=1), left_index=True, right_index=True) stations_on_path = notnull_stations[notnull_stations.apply( lambda x: line.distance(x["point"]) <= self.distance, axis=1)] return {"distance": round(distance), "duration": round(duration)}, \ stations_on_path.merge(stations_on_path.apply(lambda x: self.cal_via( x, distance, duration), axis=1), left_index=True, right_index=True) def calc_from_point(self, stations): filtered_stations = self.filter_stations(stations, filter_by_distance=True) if filtered_stations.empty: return None, pd.DataFrame() return None, filtered_stations.merge(filtered_stations.apply(self.calc, axis=1), left_index=True, right_index=True) def calculate_prices(self, stations): route_data, updated_stations = self.calc_from_point(stations) \ if not isinstance(self.location, tuple) else self.calc_via_route(stations) self.route_cache.write_cache() if updated_stations.empty: return route_data, pd.DataFrame() return route_data, updated_stations \ .round({"Total price": 2, f"{self.amount}l price": 2, "95E10 Price": 3}) \ .sort_values("Total price")