def display_results( self, resp: Union[Response, List[Response]] = None, data: Union[List[dict], List[str], dict, None] = None, tablefmt: TableFormat = "rich", title: str = None, caption: str = None, pager: bool = False, outfile: Path = None, sort_by: str = None, reverse: bool = False, stash: bool = True, pad: int = None, exit_on_fail: bool = False, ok_status: Union[int, List[int], Dict[int, str]] = None, set_width_cols: dict = None, full_cols: Union[List[str], str] = [], fold_cols: Union[List[str], str] = [], cleaner: callable = None, **cleaner_kwargs, ) -> None: """Output Formatted API Response to display and optionally to file one of resp or data attribute is required Args: resp (Union[Response, List[Response], None], optional): API Response objects. data (Union[List[dict], List[str], None], optional): API Response output data. tablefmt (str, optional): Format of output. Defaults to "rich" (tabular). Valid Values: "json", "yaml", "csv", "rich", "simple", "tabulate", "raw", "action" Where "raw" is unformatted raw response and "action" is formatted for POST|PATCH etc. where the result is a simple success/error. title: (str, optional): Title of output table. Only applies to "rich" tablefmt. Defaults to None. caption: (str, optional): Caption displayed at bottome of table. Only applies to "rich" tablefmt. Defaults to None. pager (bool, optional): Page Output / or not. Defaults to True. outfile (Path, optional): path/file of output file. Defaults to None. sort_by (Union[str, List[str], None] optional): column or columns to sort output on. reverse (bool, optional): reverse the output. stash (bool, optional): stash (cache) the output of the command. The CLI can re-display with show last. Default: True ok_status (Union[int, List[int], Tuple[int, str], List[Tuple[int, str]]], optional): By default responses with status_code 2xx are considered OK and are rendered as green by Output class. provide int or list of int to override additional status_codes that should also be rendered as success/green. provide a dict with {int: str, ...} where string can be any color supported by Output class or "neutral" "success" "fail" where neutral is no formatting, and success / fail will use the default green / red respectively. set_width_cols (Dict[str: Dict[str, int]]): Passed to output function defines cols with min/max width example: {'details': {'min': 10, 'max': 30}, 'device': {'min': 5, 'max': 15}} full_cols (list): columns to ensure are displayed at full length (no wrap no truncate) cleaner (callable, optional): The Cleaner function to use. """ # TODO remove ok_status, and handle in CentralAPI method (set resp.ok = True) if pad: log.error("Deprecated pad parameter referenced in display_results", show=True) if resp is not None: resp = utils.listify(resp) # update caption with rate limit if resp[-1].rl: rl_str = f"[italic dark_olive_green2]{resp[-1].rl}[/]".lstrip() caption = f"{caption}\n {rl_str}" if caption else f" {rl_str}" for idx, r in enumerate(resp): # Multi request url line m_colors = { "GET": "bright_green", "DELETE": "red", "PATH": "dark_orange3", "PUT": "dark_orange3", "POST": "dark_orange3" } fg = "bright_green" if r else "red" conditions = [ len(resp) > 1, tablefmt in ["action", "raw"], r.ok and not r.output ] if any(conditions): _url = r.url if not hasattr(r.url, "raw_path_qs") else r.url.path m_color = m_colors.get(r.method, "reset") print(f"Request {idx + 1} [[{m_color}]{r.method}[reset]: " f"[cyan]{_url}[/cyan]]\n [fg]Response[reset]:") if self.raw_out: tablefmt = "raw" if not r.output: c = Console(record=True) c.begin_capture() c.print(f" Status Code: [{fg}]{r.status}[/]") c.print( f" :warning: Empty Response. This may be normal.") r.output = c.end_capture() if not r or tablefmt in ["action", "raw"]: if tablefmt == "raw": # dots = f"[{fg}]{'.' * 16}[/{fg}]" status_code = f"[{fg}]status code: {r.status}[/{fg}]" print(r.url) print(status_code) if not r.ok: print(r.error) # print(f"{dots}\n{status_code}\n{dots}") print( "[bold cyan]Unformatted response from Aruba Central API GW[/bold cyan]" ) print(r.raw) if outfile: self.write_file(outfile, r.raw) else: print(f"[{fg}]{r}") if idx + 1 == len(resp): console.print(f"\n{rl_str}") else: self._display_results(r.output, tablefmt=tablefmt, title=title, caption=caption, pager=pager, outfile=outfile, sort_by=sort_by, reverse=reverse, stash=stash, pad=pad, set_width_cols=set_width_cols, full_cols=full_cols, fold_cols=fold_cols, cleaner=cleaner, **cleaner_kwargs) # TODO make elegant caas send-cmds uses this logic if cleaner and cleaner.__name__ == "parse_caas_response": print(caption) if exit_on_fail and not all([r.ok for r in resp]): raise typer.Exit(1) elif data: self._display_results(data, tablefmt=tablefmt, title=title, caption=caption, pager=pager, outfile=outfile, sort_by=sort_by, reverse=reverse, stash=stash, pad=pad, set_width_cols=set_width_cols, full_cols=full_cols, fold_cols=fold_cols, cleaner=cleaner, **cleaner_kwargs)
from nornir_pyez.plugins.tasks import pyez_int_terse import os from nornir import InitNornir from nornir_utils.plugins.functions import print_result from rich import print from nornir.core.plugins.connections import ConnectionPluginRegister from nornir_pyez.plugins.connections import Pyez ConnectionPluginRegister.register("pyez", Pyez) script_dir = os.path.dirname(os.path.realpath(__file__)) nr = InitNornir(config_file=f"{script_dir}/config.yml") # xpath = 'interfaces/interface' # xml = '<interfaces></interfaces>' # database = 'committed' response = nr.run(task=pyez_int_terse) # response is an AggregatedResult, which behaves like a list # there is a response object for each device in inventory devices = [] for dev in response: print(response[dev].result)
def import_all_classes( paths: List[str], prefix: str, provider_ids: List[str] = None, print_imports: bool = False, print_skips: bool = False, ) -> Tuple[List[str], List[WarningMessage]]: """ Imports all classes in providers packages. This method loads and imports all the classes found in providers, so that we can find all the subclasses of operators/sensors etc. :param paths: list of paths to look the provider packages in :param prefix: prefix to add :param provider_ids - provider ids that should be loaded. :param print_imports - if imported class should also be printed in output :param print_skips - if skipped classes should also be printed in output :return: tupple of list of all imported classes and all warnings generated """ imported_classes = [] tracebacks = [] printed_packages: Set[str] = set() def mk_prefix(provider_id): return f'{prefix}{provider_id}' if provider_ids: provider_prefixes = [ mk_prefix(provider_id) for provider_id in provider_ids ] else: provider_prefixes = [prefix] def onerror(_): nonlocal tracebacks exception_string = traceback.format_exc() if any(provider_prefix in exception_string for provider_prefix in provider_prefixes): tracebacks.append(exception_string) all_warnings: List[WarningMessage] = [] for modinfo in pkgutil.walk_packages(path=paths, prefix=prefix, onerror=onerror): if not any( modinfo.name.startswith(provider_prefix) for provider_prefix in provider_prefixes): if print_skips: print(f"Skipping module: {modinfo.name}") continue if print_imports: package_to_print = ".".join(modinfo.name.split(".")[:-1]) if package_to_print not in printed_packages: printed_packages.add(package_to_print) print(f"Importing package: {package_to_print}") try: with warnings.catch_warnings(record=True) as w: warnings.filterwarnings("always", category=DeprecationWarning) _module = importlib.import_module(modinfo.name) for attribute_name in dir(_module): class_name = modinfo.name + "." + attribute_name attribute = getattr(_module, attribute_name) if isclass(attribute): imported_classes.append(class_name) if w: all_warnings.extend(w) except Exception: exception_str = traceback.format_exc() tracebacks.append(exception_str) if tracebacks: print( """ [red]ERROR: There were some import errors[/] """, file=sys.stderr, ) for trace in tracebacks: print("[red]----------------------------------------[/]", file=sys.stderr) print(trace, file=sys.stderr) print("[red]----------------------------------------[/]", file=sys.stderr) sys.exit(1) else: return imported_classes, all_warnings
def JS_SHOW(name): ID = SearchJSName(name) if ID == -1: print("找不到该角色!") return obj = AR.get("juese_info", UDD["juese_info"]) name = data.ID_C[ID] print("角色信息:", name, " 角色ID:", ID // 100) if name in obj: v = obj[name] if 'star' in v: print("星:", *['★'] * v['star']) if 'dengji' in v: print("等级:", v['dengji']) CELL = {} # (0,0) - (0,1) CELL[(0, 0)] = 'R' if 'rank' in v: CELL[(0, 1)] = str(v['rank']) else: CELL[(0, 1)] = "?" # (1,0) - (3,1) if 'zb' not in v: for i in range(6): CELL[(1 + i // 2, i % 2)] = "?" else: for i in range(6): CELL[(1 + i // 2, i % 2)] = '■' if v['zb'][i] else '□' CELL[(1, 2)] = "-->" # (0,3) - (3,4) if 'track_rank' in v and 'track_zb' in v: flag = True CELL[(0, 3)] = 'R' CELL[(0, 4)] = str(v['track_rank']) for i in range(6): CELL[(1 + i // 2, i % 2 + 3)] = '■' if v['track_zb'][i] else '□' else: flag = False if flag: max_c = 4 else: max_c = 1 max_r = 3 for r in range(max_r + 1): for c in range(max_c + 1): if (r, c) in CELL: print(CELL[(r, c)], end='\t') else: print(end='\t') print() if 'haogan' in v: print("好感:", v['haogan']) if 'special' in v: print("专武:", v["special"]) else: print("你并没有这个角色!")
def ZB_ST_LACK(args): from rich import print need_equip = {} juese = AR.get("juese_info", UDD["juese_info"]) for k, v in juese.items(): if k in data.C_ID and "track_rank" in v and "track_zb" in v \ and "rank" in v and "zb" in v: ne = data.calc_rankup_equip(data.C_ID[k], v["rank"], v["zb"], v["track_rank"], v["track_zb"]) data.dict_plus(need_equip, ne, False) if has_arg(args, "--item"): lack = need_equip else: if not has_arg(args, "--no-store"): store = {} zb = AR.get("zhuangbei_kucun", UDD["zhuangbei_kucun"]) for k, v in zb.items(): num, _, _ = v if k in data.EQU_ID: store[data.EQU_ID[k]] = num lack = data.calc_equips_decompose(need_equip, store) else: lack = data.calc_equips_decompose(need_equip) show = defaultdict(list) for equ in lack: show[data.EInfo[equ]['plevel']] += [equ] LABEL = { 1: '铁', 2: '铜', 3: '银', 4: '金', 5: '紫', 6: '红', } min_rare = int(get_arg(args, "--min-rare", "0")) max_rare = int(get_arg(args, "--max-rare", "6")) max_tu = get_arg(args, "--max-tu", None) if max_tu is not None: max_tu = int(max_tu) normal = data.make_normal_map_prob(max_tu) for k in sorted(show, reverse=True): if k < min_rare or k > max_rare: continue table = RTable(title="稀有度:" + LABEL[k], show_lines=True, box=rbox.HEAVY_EDGE) table.add_column("装备", justify="center") table.add_column("缺失", justify="center") if has_arg(args, "--normal"): table.add_column("刷取区域", justify="center") for equ in show[k]: row = [data.ID_EQU[equ], f"x{lack[equ]}"] if has_arg(args, "--normal"): if equ not in normal: row += [''] else: RR = ROrderGrid(8) lst = normal[equ] for prob, (A, B) in lst: RR.add(ROneTable(f"{A}-{B}", f"{prob}%")) RR.finish() row += [RR] table.add_row(*row) print(table)
def play(playlist: int, random_play: bool): """播放歌单 如果没有指定歌单id,默认播放名为 `我喜欢的音乐` 的歌单 默认循环播放列表,可以使用 --random 选项来随机播放 Args: playlist (int): 歌单id random (bool): 是否随机播放 """ if not playlist: user_playlist = api.get_user_playlist() for pl in user_playlist.playlist: if pl.name == '我喜欢的音乐': playlist = pl.id break if not playlist: rich.print('[red]没有找到播放列表') # start progress rendering in seprate thread immediately progress = Progress( '[yellow]{task.fields[status]}[/yellow] ' '[progress.description]{task.description}', '[blue]{task.fields[encode]}', '[cyan]{task.fields[quality]}', BarColumn(), TotalFileSizeColumn(), '[progress.percentage]{task.percentage:>3.0f}%', ) Thread(target=progress.start, name='progress rendering').start() # initialize task queue task_queue: Queue[CachingMusicFileTask] = Queue(2) # initialize playtask play_task_id = progress.add_task('play', start=False, total=0, status='P', encode='-', quality='-') # start download threads thread_1 = CachingMusicFile(task_queue) thread_1.start() thread_2 = CachingMusicFile(task_queue) thread_2.start() # initialize tasks tasks = [] tracks = api.get_playlist_detail(playlist).playlist.tracks tracks_id = list(map(lambda t: t.id, tracks)) musics = api.get_songs_url(tracks_id, 0).data for track, music in zip(tracks, musics): music_cache_path = os.path.join(config.cache_folder, f'{track.id}.{music.type}') tasks.append( CachingMusicFileTask( progress, progress.add_task(f'{track.name}', total=0, encode=music.type, quality=f'{music.br/1000}K', status='D'), music.url, music_cache_path)) # initialize download task queue def feed_taskq_queue(): for task in tasks: task_queue.put(task) Thread(target=feed_taskq_queue, name='task producer').start() # start play local_musics = list(zip(tracks, musics)) last_play_obj = None idx = 0 while True: if random_play: track, music = random.choice(local_musics) else: if idx >= len(local_musics): idx = 0 track, music = local_musics[idx] idx += 1 local_path = os.path.join(config.cache_folder, f'{track.id}.{music.type}') progress.update(play_task_id, description=track.name) if Path(local_path).is_file(): mf = mad.MadFile(Path(local_path).open('rb')) while True: buf = mf.read() if buf is None: break if last_play_obj is not None and last_play_obj.is_playing(): last_play_obj.wait_done() last_play_obj = sa.play_buffer(buf, 2, 2, mf.samplerate())
def ZB_KC_FIX(): # 修复装备库存 global AR kc = AR.get("zhuangbei_kucun", UDD["zhuangbei_kucun"]) bad_k = [] for k in kc: if k not in data.EQU_ID: bad_k += [k] if len(bad_k) == 0: print("装备库存无需修复。") return print("检测到有", len(bad_k), "个条目需要修复:") print("装备 库存 修复 ----------------------") print("接下来每行会输出一个名称不符的条目,并给出它的最近更新时间。") print("请输入它的正确名称,则该条目将会被替换为此名称。") print("若存在较新条目已经存在该名称,则此项会被舍弃。") print("若存在较旧条目已经存在该名称,此项将替换之。") print("输入 0 表示舍弃该项。") print("您可以在/ocrfix文件夹中找到出错的条目的截图以便于识别。") print("您可以手动把错误截图的文件名改为正确的名称,则下次再次识别出错时会自动修复。") total = len(bad_k) for ind, k in enumerate(bad_k): while True: v = kc[k] num, tim, bz = v print("[", ind + 1, "/", total, "] 上次更新:", get_time_str(tim), "数量", num, "备注", bz) new_k = input(f"{k} -> ") if new_k == "0": del kc[k] AR.set("zhuangbei_kucun", kc) break elif new_k not in data.EQU_ID: print("该名称不存在!") elif new_k in kc: if kc[new_k][1] > tim: print("存在较新记录,此项作废。") else: print("存在较旧记录,此项替换。") kc[new_k] = kc.pop(k) AR.set("zhuangbei_kucun", kc) break else: kc[new_k] = kc.pop(k) AR.set("zhuangbei_kucun", kc) break print("修复已完成!")
def do_setuppayload(self, line): """ setup-payload generate [options] Options: -vr Version -vi Vendor ID -pi Product ID -cf Custom Flow [Standard = 0, UserActionRequired = 1, Custom = 2] -dc Discovery Capabilities [SoftAP = 1 | BLE = 2 | OnNetwork = 4] -dv Discriminator Value -ps Passcode setup-payload parse-manual <manual-pairing-code> setup-payload parse-qr <qr-code-payload> """ warnings.warn( "This method is being deprecated. Please use the SetupPayload function in the chip.setup_payload package directly", DeprecationWarning) try: arglist = shlex.split(line) if arglist[0] not in ("generate", "parse-manual", "parse-qr"): self.do_help("setup-payload") return if arglist[0] == "generate": parser = argparse.ArgumentParser() parser.add_argument("-vr", type=int, default=0, dest='version') parser.add_argument("-pi", type=int, default=0, dest='productId') parser.add_argument("-vi", type=int, default=0, dest='vendorId') parser.add_argument('-cf', type=int, default=0, dest='customFlow') parser.add_argument("-dc", type=int, default=0, dest='capabilities') parser.add_argument("-dv", type=int, default=0, dest='discriminator') parser.add_argument("-ps", type=int, dest='passcode') args = parser.parse_args(arglist[1:]) SetupPayload().PrintOnboardingCodes( args.passcode, args.vendorId, args.productId, args.discriminator, args.customFlow, args.capabilities, args.version) if arglist[0] == "parse-manual": SetupPayload().ParseManualPairingCode(arglist[1]).Print() if arglist[0] == "parse-qr": SetupPayload().ParseQrCode(arglist[1]).Print() except exceptions.ChipStackException as ex: print(str(ex)) return
def ConnectFromSetupPayload(self, setupPayload, nodeid): # TODO(cecille): Get this from the C++ code? ble = 1 << 1 # Devices may be uncommissioned, or may already be on the network. Need to check both ways. # TODO(cecille): implement soft-ap connection. # Any device that is already commissioned into a fabric needs to use on-network # pairing, so look first on the network regardless of the QR code contents. print("Attempting to find device on Network") longDiscriminator = ctypes.c_uint16( int(setupPayload.attributes['Discriminator'])) self.devCtrl.DiscoverCommissionableNodesLongDiscriminator( longDiscriminator) print("Waiting for device responses...") strlen = 100 addrStrStorage = ctypes.create_string_buffer(strlen) # If this device is on the network and we're looking specifically for 1 device, # expect a quick response. if self.wait_for_one_discovered_device(): self.devCtrl.GetIPForDiscoveredDevice(0, addrStrStorage, strlen) addrStr = addrStrStorage.value.decode('utf-8') print("Connecting to device at " + addrStr) pincode = ctypes.c_uint32( int(setupPayload.attributes['SetUpPINCode'])) try: self.devCtrl.CommissionIP(addrStrStorage, pincode, nodeid) print("Connected") return 0 except Exception as ex: print(f"Unable to connect on network: {ex}") else: print("Unable to locate device on network") if int(setupPayload.attributes["RendezvousInformation"]) & ble: print("Attempting to connect via BLE") longDiscriminator = ctypes.c_uint16( int(setupPayload.attributes['Discriminator'])) pincode = ctypes.c_uint32( int(setupPayload.attributes['SetUpPINCode'])) try: self.devCtrl.ConnectBLE(longDiscriminator, pincode, nodeid) print("Connected") return 0 except Exception as ex: print(f"Unable to connect: {ex}") return -1
def __init__(self, rendezvousAddr=None, controllerNodeId=1, bluetoothAdapter=None): self.lastNetworkId = None pretty.install(indent_guides=True, expand_all=True) coloredlogs.install(level='DEBUG') chip.logging.RedirectToPythonLogging() logging.getLogger().setLevel(logging.DEBUG) warnings.showwarning = ShowColoredWarnings Cmd.__init__(self) Cmd.identchars = string.ascii_letters + string.digits + "-" if sys.stdin.isatty(): self.prompt = "chip-device-ctrl > " else: self.use_rawinput = 0 self.prompt = "" DeviceMgrCmd.command_names.sort() self.bleMgr = None self.chipStack = ChipStack.ChipStack( bluetoothAdapter=bluetoothAdapter, persistentStoragePath='/tmp/chip-device-ctrl-storage.json') self.fabricAdmin = FabricAdmin.FabricAdmin() self.devCtrl = self.fabricAdmin.NewController(controllerNodeId, True) self.commissionableNodeCtrl = ChipCommissionableNodeCtrl.ChipCommissionableNodeController( self.chipStack) # If we are on Linux and user selects non-default bluetooth adapter. if sys.platform.startswith("linux") and (bluetoothAdapter is not None): try: self.bleMgr = BleManager(self.devCtrl) self.bleMgr.ble_adapter_select( "hci{}".format(bluetoothAdapter)) except Exception as ex: traceback.print_exc() print( "Failed to initialize BLE, if you don't have BLE, run chip-device-ctrl with --no-ble" ) raise ex self.historyFileName = os.path.expanduser( "~/.chip-device-ctrl-history") try: import readline if "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") readline.set_completer_delims(" ") try: readline.read_history_file(self.historyFileName) except IOError: pass except ImportError: pass
def precmd(self, line): if not self.use_rawinput and line != "EOF" and line != "": print(">>> " + line) return line
def main(): optParser = OptionParser() optParser.add_option( "-r", "--rendezvous-addr", action="store", dest="rendezvousAddr", help="Device rendezvous address", metavar="<ip-address>", ) optParser.add_option( "-n", "--controller-nodeid", action="store", dest="controllerNodeId", default=1, type='int', help="Controller node ID", metavar="<nodeid>", ) if sys.platform.startswith("linux"): optParser.add_option( "-b", "--bluetooth-adapter", action="store", dest="bluetoothAdapter", default="hci0", type="str", help= "Controller bluetooth adapter ID, use --no-ble to disable bluetooth functions.", metavar="<bluetooth-adapter>", ) optParser.add_option( "--no-ble", action="store_true", dest="disableBluetooth", help= "Disable bluetooth, calling BLE related feature with this flag results in undefined behavior.", ) (options, remainingArgs) = optParser.parse_args(sys.argv[1:]) if len(remainingArgs) != 0: print("Unexpected argument: %s" % remainingArgs[0]) sys.exit(-1) adapterId = None if sys.platform.startswith("linux"): if options.disableBluetooth: adapterId = None elif not options.bluetoothAdapter.startswith("hci"): print( "Invalid bluetooth adapter: {}, adapter name looks like hci0, hci1 etc." ) sys.exit(-1) else: try: adapterId = int(options.bluetoothAdapter[3:]) except: print( "Invalid bluetooth adapter: {}, adapter name looks like hci0, hci1 etc." ) sys.exit(-1) try: devMgrCmd = DeviceMgrCmd(rendezvousAddr=options.rendezvousAddr, controllerNodeId=options.controllerNodeId, bluetoothAdapter=adapterId) except Exception as ex: print(ex) print("Failed to bringup CHIPDeviceController CLI") sys.exit(1) print("Chip Device Controller Shell") if options.rendezvousAddr: print("Rendezvous address set to %s" % options.rendezvousAddr) # Adapter ID will always be 0 if adapterId != 0: print("Bluetooth adapter set to hci{}".format(adapterId)) print() try: devMgrCmd.cmdloop() except KeyboardInterrupt: print("\nQuitting") sys.exit(0)
def do_EOF(self, line): print() return True
def do_getfabricid(self, line): """ get-fabricid Read the current Compressed Fabric Id of the controller device, return 0 if not available. """ try: args = shlex.split(line) if (len(args) > 0): print("Unexpected argument: " + args[1]) return compressed_fabricid = self.devCtrl.GetCompressedFabricId() raw_fabricid = self.devCtrl.GetFabricId() except exceptions.ChipStackException as ex: print("An exception occurred during reading FabricID:") print(str(ex)) return print("Get fabric ID complete") print("Raw Fabric ID: 0x{:016x}".format(raw_fabricid) + " (" + str(raw_fabricid) + ")") print("Compressed Fabric ID: 0x{:016x}".format(compressed_fabricid) + " (" + str(compressed_fabricid) + ")")
def main(): args = sys.argv if len(args) < 2: print( '[bold red]You need to pass an address after the command! Ex: python cluward.py ADDRESS' ) exit() addr = sys.argv[1] ABI = [{ "inputs": [], "stateMutability": "payable", "type": "constructor" }, { "anonymous": False, "inputs": [{ "indexed": True, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": True, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256" }], "name": "Approval", "type": "event" }, { "anonymous": False, "inputs": [{ "indexed": False, "internalType": "uint256", "name": "minTokensBeforeSwap", "type": "uint256" }], "name": "MinTokensBeforeSwapUpdated", "type": "event" }, { "anonymous": False, "inputs": [{ "indexed": True, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": True, "internalType": "address", "name": "newOwner", "type": "address" }], "name": "OwnershipTransferred", "type": "event" }, { "anonymous": False, "inputs": [{ "indexed": False, "internalType": "uint256", "name": "tokensSwapped", "type": "uint256" }, { "indexed": False, "internalType": "uint256", "name": "ethReceived", "type": "uint256" }, { "indexed": False, "internalType": "uint256", "name": "tokensIntoLiqudity", "type": "uint256" }], "name": "SwapAndLiquify", "type": "event" }, { "anonymous": False, "inputs": [{ "indexed": False, "internalType": "bool", "name": "enabled", "type": "bool" }], "name": "SwapAndLiquifyEnabledUpdated", "type": "event" }, { "anonymous": False, "inputs": [{ "indexed": True, "internalType": "address", "name": "from", "type": "address" }, { "indexed": True, "internalType": "address", "name": "to", "type": "address" }, { "indexed": False, "internalType": "uint256", "name": "value", "type": "uint256" }], "name": "Transfer", "type": "event" }, { "inputs": [], "name": "_liquidityFee", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "_maxTxAmount", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "_taxFee", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" }], "name": "allowance", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "approve", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "balanceOf", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "decimals", "outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "subtractedValue", "type": "uint256" }], "name": "decreaseAllowance", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "tAmount", "type": "uint256" }], "name": "deliver", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "excludeFromFee", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "excludeFromReward", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "geUnlockTime", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "includeInFee", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "includeInReward", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "addedValue", "type": "uint256" }], "name": "increaseAllowance", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "isExcludedFromFee", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "isExcludedFromReward", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "time", "type": "uint256" }], "name": "lock", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "name", "outputs": [{ "internalType": "string", "name": "", "type": "string" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "pause", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "tAmount", "type": "uint256" }, { "internalType": "bool", "name": "deductTransferFee", "type": "bool" }], "name": "reflectionFromToken", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "liquidityFee", "type": "uint256" }], "name": "setLiquidityFeePercent", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "maxTxPercent", "type": "uint256" }], "name": "setMaxTxPercent", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "setRestrictionAmount", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "bool", "name": "_enabled", "type": "bool" }], "name": "setSwapAndLiquifyEnabled", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "taxFee", "type": "uint256" }], "name": "setTaxFeePercent", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "time", "type": "uint256" }], "name": "setTradingStart", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "swapAndLiquifyEnabled", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [{ "internalType": "string", "name": "", "type": "string" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "rAmount", "type": "uint256" }], "name": "tokenFromReflection", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalFees", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "recipient", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "transfer", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "address", "name": "recipient", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" }], "name": "transferFrom", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "newOwner", "type": "address" }], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "uniswapV2Pair", "outputs": [{ "internalType": "address", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "uniswapV2Router", "outputs": [{ "internalType": "contract IUniswapV2Router02", "name": "", "type": "address" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "unlock", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "unpause", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "whitelistAccount", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "stateMutability": "payable", "type": "receive" }] w3 = Web3(Web3.HTTPProvider('https://bsc-dataseed.binance.org/')) from web3.middleware import geth_poa_middleware w3.middleware_onion.inject(geth_poa_middleware, layer=0) contract = w3.eth.contract(address=Web3.toChecksumAddress( '0x1162e2efce13f99ed259ffc24d99108aaa0ce935'), abi=ABI) totalCurrentRewards = 0 console.clear() counted_blocks = [] while True: currentBlock = w3.eth.blockNumber block = currentBlock lastBal = contract.functions.balanceOf(addr).call( block_identifier=block) bals = [] bals_raw = [] while True: try: balance = contract.functions.balanceOf(addr).call( block_identifier=block) if not block in counted_blocks: totalCurrentRewards += w3.fromWei( (Decimal(lastBal) - Decimal(balance)) * (Decimal(10)**9), 'ether') counted_blocks.append(block) bals.append("+" + str( w3.fromWei((Decimal(lastBal) - Decimal(balance)) * (Decimal(10)**9), 'ether'))) bals_raw.append( w3.fromWei((Decimal(lastBal) - Decimal(balance)) * (Decimal(10)**9), 'ether')) lastBal = balance block -= 1 if currentBlock - block == 60: break except ValueError: pass bals.reverse() console.clear() print( Panel( f'[bold blue]Current Balance:[/bold blue] {w3.fromWei(Decimal(contract.functions.balanceOf(addr).call())* (Decimal(10) ** 9), "ether"):,}\n[bold yellow]Average Reward per Block over last 1 minute:[/bold yellow] {sum(bals_raw[0:20]) / len(bals_raw[0:20]):,}\n[bold yellow]Average Reward per Block over last 3 minutes:[/bold yellow] {sum(bals_raw) / len(bals_raw):,}\n[bold green]Total Rewards over last 3 minutes: [/bold green]{sum(bals_raw):,}\n[bold cyan]Total Rewards Since Tracking Began:[/bold cyan] {totalCurrentRewards:,}', title= f'[bold purple]CLUCoin Reward Summary ({addr[0:3]}..{addr[-4:]}):[/bold purple]', title_align='center', highlight=True)) time.sleep(15)
def do_connect(self, line): """ connect -ip <ip address> <setup pin code> [<nodeid>] connect -ble <discriminator> <setup pin code> [<nodeid>] connect -qr <qr code> [<nodeid>] connect -code <manual pairing code> [<nodeid>] connect command is used for establishing a rendezvous session to the device. currently, only connect using setupPinCode is supported. -qr option will connect to the first device with a matching long discriminator. TODO: Add more methods to connect to device (like cert for auth, and IP for connection) """ warnings.warn( "This method is being deprecated. Please use the DeviceController.[ConnectBLE|CommissionIP] methods directly in the REPL", DeprecationWarning) try: args = shlex.split(line) if len(args) <= 1: print("Usage:") self.do_help("connect SetupPinCode") return nodeid = random.randint(1, 1000000) # Just a random number if len(args) == 4: nodeid = int(args[3]) print("Device is assigned with nodeid = {}".format(nodeid)) if args[0] == "-ip" and len(args) >= 3: self.devCtrl.CommissionIP(args[1].encode("utf-8"), int(args[2]), nodeid) elif args[0] == "-ble" and len(args) >= 3: self.devCtrl.ConnectBLE(int(args[1]), int(args[2]), nodeid) elif args[0] in ['-qr', '-code'] and len(args) >= 2: if len(args) == 3: nodeid = int(args[2]) print("Parsing QR code {}".format(args[1])) setupPayload = None if args[0] == '-qr': setupPayload = SetupPayload().ParseQrCode(args[1]) elif args[0] == '-code': setupPayload = SetupPayload().ParseManualPairingCode( args[1]) if not int( setupPayload.attributes.get("RendezvousInformation", 0)): print( "No rendezvous information provided, default to all.") setupPayload.attributes["RendezvousInformation"] = 0b111 setupPayload.Print() self.ConnectFromSetupPayload(setupPayload, nodeid) else: print("Usage:") self.do_help("connect SetupPinCode") return print( "Device temporary node id (**this does not match spec**): {}". format(nodeid)) except exceptions.ChipStackException as ex: print(str(ex)) return
highlighter = ReprHighlighter() for key, value in mapping.items(): table.add_row(Pretty(key, highlighter=highlighter), Pretty(value, highlighter=highlighter)) return table if __name__ == "__main__": # pragma: no cover from rich import print def test(foo, bar, tjustify=None, cjustify=None): list_of_things = [1, 2, 3, None, 4, True, False, "Hello World"] dict_of_things = { "version": "1.1", "method": "confirmFruitPurchase", "params": [["apple", "orange", "mangoes", "pomelo"], 1.123], "id": "194521489", } print( tabulate_mapping( locals(), title="locals()", title_justify=tjustify, caption="__main__.test", caption_justify=cjustify, )) print() test(20.3423, 3.1427, cjustify="right") print()
def wait_for_many_discovered_devices(self): # Discovery happens through mdns, which means we need to wait for responses to come back. # TODO(cecille): I suppose we could make this a command line arg. Or Add a callback when # x number of responses are received. For now, just 2 seconds. We can all wait that long. print("Waiting for device responses...") time.sleep(2)
RR.finish() row += [RR] elif js_flag: cur = map_js[out] cur_sort = sorted(cur, reverse=True, key=lambda x: cur[x]) sss = [] for p in cur_sort: sss += ["%s x%d" % (p, cur[p])] row += ["\n".join(sss)] table.add_row(*row) print(table) if __name__ == "__main__": GetLastAccount() print("--- PCR数据中心 ---") data = LoadPCRData() if data is None: print("数据库未加载") else: print( "数据库上次更新时间:", datetime.datetime.fromtimestamp( data.last_update_time).strftime("%Y-%m-%d %H:%M:%S")) print("help 帮助") print("exit 退出") precmd = "" while True: try: prompt = "[未绑定]>" if last_account == "" else f"[{last_account}]> "
def do_discover(self, line): """ discover -qr qrcode discover -all discover -l long_discriminator discover -s short_discriminator discover -v vendor_id discover -t device_type discover -c discover command is used to discover available devices. """ try: arglist = shlex.split(line) if len(arglist) < 1: print("Usage:") self.do_help("discover") return parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument( '-all', help='discover all commissionable nodes and commissioners', action='store_true') group.add_argument( '-qr', help='discover commissionable nodes matching provided QR code', type=str) group.add_argument( '-l', help= 'discover commissionable nodes with given long discriminator', type=int) group.add_argument( '-s', help= 'discover commissionable nodes with given short discriminator', type=int) group.add_argument( '-v', help='discover commissionable nodes with given vendor ID', type=int) group.add_argument( '-t', help='discover commissionable nodes with given device type', type=int) group.add_argument( '-c', help='discover commissionable nodes in commissioning mode', action='store_true') args = parser.parse_args(arglist) if args.all: self.commissionableNodeCtrl.DiscoverCommissioners() self.wait_for_many_discovered_devices() self.commissionableNodeCtrl.PrintDiscoveredCommissioners() self.devCtrl.DiscoverAllCommissioning() self.wait_for_many_discovered_devices() elif args.qr is not None: setupPayload = SetupPayload().ParseQrCode(args.qr) longDiscriminator = ctypes.c_uint16( int(setupPayload.attributes['Discriminator'])) self.devCtrl.DiscoverCommissionableNodesLongDiscriminator( longDiscriminator) self.wait_for_one_discovered_device() elif args.l is not None: self.devCtrl.DiscoverCommissionableNodesLongDiscriminator( ctypes.c_uint16(args.l)) self.wait_for_one_discovered_device() elif args.s is not None: self.devCtrl.DiscoverCommissionableNodesShortDiscriminator( ctypes.c_uint16(args.s)) self.wait_for_one_discovered_device() elif args.v is not None: self.devCtrl.DiscoverCommissionableNodesVendor( ctypes.c_uint16(args.v)) self.wait_for_many_discovered_devices() elif args.t is not None: self.devCtrl.DiscoverCommissionableNodesDeviceType( ctypes.c_uint16(args.t)) self.wait_for_many_discovered_devices() elif args.c is not None: self.devCtrl.DiscoverCommissionableNodesCommissioningEnabled() self.wait_for_many_discovered_devices() else: self.do_help("discover") return self.devCtrl.PrintDiscoveredDevices() except exceptions.ChipStackException as ex: print('exception') print(str(ex)) return except: self.do_help("discover") return
def JS_FIX(): # 修复角色信息 global AR kc = AR.get("juese_info", UDD["juese_info"]) bad_k = [] for k in kc: if k not in data.C_ID: bad_k += [k] if len(bad_k) == 0: print("角色名称无需修复。") return print("检测到有", len(bad_k), "个条目需要修复:") print("角色 修复 ---------------------------") print("接下来每行会输出一个名称不符的条目,并给出它的最近更新时间。") print("请输入它的正确名称,则该条目将会被替换为此名称。") print("若存在较新条目已经存在该名称,则此项会被舍弃。") print("若存在较旧条目已经存在该名称,此项将替换之。") print("输入 0 表示舍弃该项。") print("您可以在/ocrfix文件夹中找到出错的条目的截图以便于识别。") print("您可以手动把错误截图的文件名改为正确的名称,则下次再次识别出错时会自动修复。") total = len(bad_k) for ind, k in enumerate(bad_k): while True: v = kc[k] print("[", ind + 1, "/", total, "] 上次更新:", get_time_str(v['last_update'])) new_k = input(f"{k} -> ") if new_k == "0": del kc[k] AR.set("juese_info", kc) break elif new_k not in data.C_ID: print("该名称不存在!") elif new_k in kc: if kc[new_k]['last_update'] > v['last_update']: print("存在较新记录,此项作废。") else: print("存在较旧记录,此项替换。") kc[new_k] = kc.pop(k) AR.set("juese_info", kc) break else: kc[new_k] = kc.pop(k) AR.set("juese_info", kc) break print("修复已完成!")
def do_zcl(self, line): """ To send ZCL message to device: zcl <cluster> <command> <nodeid> <endpoint> <groupid> [key=value]... To get a list of clusters: zcl ? To get a list of commands in cluster: zcl ? <cluster> Send ZCL command to device nodeid """ try: args = shlex.split(line) all_commands = self.devCtrl.ZCLCommandList() if len(args) == 1 and args[0] == '?': print('\n'.join(all_commands.keys())) elif len(args) == 2 and args[0] == '?': if args[1] not in all_commands: raise exceptions.UnknownCluster(args[1]) for commands in all_commands.get(args[1]).items(): args = ", ".join([ "{}: {}".format(argName, argType) for argName, argType in commands[1].items() ]) print(commands[0]) if commands[1]: print(" ", args) else: print(" <no arguments>") elif len(args) > 4: if args[0] not in all_commands: raise exceptions.UnknownCluster(args[0]) command = all_commands.get(args[0]).get(args[1], None) # When command takes no arguments, (not command) is True if command is None: raise exceptions.UnknownCommand(args[0], args[1]) err, res = self.devCtrl.ZCLSend(args[0], args[1], int(args[2]), int(args[3]), int(args[4]), FormatZCLArguments( args[5:], command), blocking=True) if err != 0: print("Failed to receive command response: {}".format(res)) elif res != None: print("Received command status response:") print(res) else: print("Success, no status code is attached with response.") else: self.do_help("zcl") except exceptions.ChipStackException as ex: print("An exception occurred during process ZCL command:") print(str(ex)) except Exception as ex: print("An exception occurred during processing input:") traceback.print_exc() print(str(ex))
def JS_TRACKINFO(): from rich import print obj = AR.get("juese_info", UDD["juese_info"]) zb = AR.get("zhuangbei_kucun", UDD["zhuangbei_kucun"]) store = {} for k, v in zb.items(): num, _, _ = v if k in data.EQU_ID: store[data.EQU_ID[k]] = num table = RTable(title="练度追踪", caption="*当前可满:以目前的库存最高能满装Rank。\n" "*下一RANK:要在下一RANK上满装还需要的碎片。", caption_justify="left") table.add_column("角色", justify='center') table.add_column("进度", justify='center') table.add_column("当前可满", justify='center') table.add_column("下一RANK", justify='center') for k, v in obj.items(): if not ('track_rank' in v and 'track_zb' in v and 'zb' in v and 'rank' in v): continue if k not in data.C_ID: continue cid = data.C_ID[k] need_equip_before = data.calc_rankup_equip(cid, v['rank'], [False] * 6, v['track_rank'], v['track_zb']) before_store = data.calc_equips_decompose(need_equip_before) need_equip_after = data.calc_rankup_equip(cid, v['rank'], v['zb'], v['track_rank'], v['track_zb']) after_store = data.calc_equips_decompose(need_equip_after, store=store) before_sum = sum(before_store.values()) after_sum = sum(after_store.values()) if before_sum == 0: continue if v['track_rank'] == v['rank']: fg = True for t1, t2 in zip(v['track_zb'], v['zb']): if t1 and (not t2): fg = False break if fg: continue cur_rank = v['rank'] cur_after_sum = 0 while cur_rank <= v['track_rank']: cur_zb = [True ] * 6 if cur_rank < v['track_rank'] else v['track_zb'] cur_need = data.calc_rankup_equip(cid, v['rank'], v['zb'], cur_rank, cur_zb) cur_after = data.calc_equips_decompose(cur_need, store=store) cur_after_sum = sum(cur_after.values()) if cur_after_sum > 0: break cur_rank += 1 R = [] R += [k] OG = ROrderGrid(2) OG.add( RLRProgress(before_sum - after_sum, before_sum, RValue("R%2d" % v['rank']), RValue("R%2d" % v['track_rank']), width=20, percent=False)) OG.add(RComment(''.join(['O' if p else '_' for p in v['track_zb']]))) OG.finish() R += [OG] cur_rank -= 1 R += ["Rank " + str(cur_rank)] R += ["x" + str(cur_after_sum)] table.add_row(*R) print(table)
def do_zclread(self, line): """ To read ZCL attribute: zclread <cluster> <attribute> <nodeid> <endpoint> <groupid> """ try: args = shlex.split(line) all_attrs = self.devCtrl.ZCLAttributeList() if len(args) == 1 and args[0] == '?': print('\n'.join(all_attrs.keys())) elif len(args) == 2 and args[0] == '?': if args[1] not in all_attrs: raise exceptions.UnknownCluster(args[1]) print('\n'.join(all_attrs.get(args[1]).keys())) elif len(args) == 5: if args[0] not in all_attrs: raise exceptions.UnknownCluster(args[0]) res = self.devCtrl.ZCLReadAttribute(args[0], args[1], int(args[2]), int(args[3]), int(args[4])) if res != None: print(repr(res)) else: self.do_help("zclread") except exceptions.ChipStackException as ex: print("An exception occurred during reading ZCL attribute:") print(str(ex)) except Exception as ex: print("An exception occurred during processing input:") print(str(ex))
def ZB_ST_ADVICE(args, verbose=True): from rich import print max_tu = get_arg(args, "--max-tu", None) if max_tu is not None: max_tu = int(max_tu) min_rare = int(get_arg(args, "--min-rare", "0")) max_rare = int(get_arg(args, "--max-rare", "6")) num_w = float(get_arg(args, "--num-w", "0.1")) need_equip = {} js_need = {} zb_js = {} juese = AR.get("juese_info", UDD["juese_info"]) for k, v in juese.items(): if k in data.C_ID and "track_rank" in v and "track_zb" in v \ and "rank" in v and "zb" in v: ne = data.calc_rankup_equip(data.C_ID[k], v["rank"], v["zb"], v["track_rank"], v["track_zb"]) for n in list(ne.keys()): lv = data.EInfo[n]['plevel'] if lv < min_rare or lv > max_rare: ne.pop(n) ne2 = data.calc_equips_decompose(ne) for n in ne2: js_need.setdefault(k, {}) js_need[k].setdefault(n, 0) js_need[k][n] += ne2[n] zb_js.setdefault(n, {}) zb_js[n].setdefault(k, 0) zb_js[n][k] += ne2[n] data.dict_plus(need_equip, ne, False) store = {} if not has_arg(args, "--no-store"): zb = AR.get("zhuangbei_kucun", UDD["zhuangbei_kucun"]) for k, v in zb.items(): num, _, _ = v if k in data.EQU_ID: store[data.EQU_ID[k]] = num lack = data.calc_equips_decompose(need_equip, store) else: lack = data.calc_equips_decompose(need_equip) prob_map = data.make_normal_map_prob(max_tu) map_js = {} for k, v in zb_js.items(): if k not in prob_map: continue m = prob_map[k] for _, (A, B) in m: mid = f"{A}-{B}" map_js.setdefault(mid, {}) data.dict_plus(map_js[mid], v, False) out_map = None try: out_map, result_int = data.make_map_advice(lack, prob_map, num_w) except Exception as e: print(e) if num_w > 0: print("可能是混合整数搜索失败!你可能需要安装cvxopt依赖") out_map, result_int = data.make_map_advice(lack, prob_map, 0) mul = int(get_arg(args, "--n", "1")) if mul > 1: result_int = 0 keys = list(out_map.keys()) for i in keys: out_map[i] = int(round(out_map[i] / 2)) if out_map[i] == 0: out_map.pop(i) continue result_int += out_map[i] out_sorted = sorted(out_map, reverse=True, key=lambda x: out_map[x]) if not verbose: return out_sorted, out_map table = RTable(title="刷取建议", caption=RText("倍率:") + RValue("【", mul, "】") + RText(' 总次数:') + RValue(int(result_int)), box=rbox.HEAVY_EDGE, show_lines=True) js_flag = has_arg(args, "--js") zb_flag = has_arg(args, "--zb") store_flag = has_arg(args, "--no-store") table.add_column("图号", justify="center") table.add_column("次数", justify="center") if js_flag or zb_flag: table.add_column("详细信息", justify="center") for out in out_sorted: row = [] row += [out] row += [f"x{out_map[out]}"] if zb_flag: RR = ROrderGrid(4) A, B = out.split('-') A = int(A) B = int(B) rew = data.calc_normal_reward(A, B) for r in rew: if r["rid"] in lack: col = [] col += [data.ID_EQU[r['rid']]] col += [RValue(f"x{lack[r['rid']]}")] if not store_flag: col[-1] += f"\t库存:{store.get(r['rid'], 0)}" col += ["----------"] sss = [] if js_flag: sss += [] cur = zb_js[r['rid']] for nam in sorted(cur, reverse=True, key=lambda x: cur[x]): sss += ["%s x%d" % (nam, cur[nam])] col += ['\n'.join(sss)] ROT = ROneTable(*col) RR.add(ROT) RR.finish() row += [RR] elif js_flag: cur = map_js[out] cur_sort = sorted(cur, reverse=True, key=lambda x: cur[x]) sss = [] for p in cur_sort: sss += ["%s x%d" % (p, cur[p])] row += ["\n".join(sss)] table.add_row(*row) print(table)
def do_zclwrite(self, line): """ To write ZCL attribute: zclwrite <cluster> <attribute> <nodeid> <endpoint> <groupid> <value> """ try: args = shlex.split(line) all_attrs = self.devCtrl.ZCLAttributeList() if len(args) == 1 and args[0] == '?': print('\n'.join(all_attrs.keys())) elif len(args) == 2 and args[0] == '?': if args[1] not in all_attrs: raise exceptions.UnknownCluster(args[1]) cluster_attrs = all_attrs.get(args[1], {}) print('\n'.join([ "{}: {}".format(key, cluster_attrs[key]["type"]) for key in cluster_attrs.keys() if cluster_attrs[key].get("writable", False) ])) elif len(args) == 6: if args[0] not in all_attrs: raise exceptions.UnknownCluster(args[0]) attribute_type = all_attrs.get(args[0], {}).get(args[1], {}).get("type", None) res = self.devCtrl.ZCLWriteAttribute( args[0], args[1], int(args[2]), int(args[3]), int(args[4]), ParseValueWithType(args[5], attribute_type)) print(repr(res)) else: self.do_help("zclwrite") except exceptions.ChipStackException as ex: print("An exception occurred during writing ZCL attribute:") print(str(ex)) except Exception as ex: print("An exception occurred during processing input:") print(str(ex))
return imported_classes, all_warnings if __name__ == '__main__': parser = argparse.ArgumentParser( description='Perform import of all provider classes.') parser.add_argument('--path', action='append', help='paths to search providers in') parser.add_argument('--prefix', help='prefix to add in front of the class', default='airflow.providers.') args = parser.parse_args() print() print(f"Walking all packages in {args.path} with prefix {args.prefix}") print() classes, warns = import_all_classes(print_imports=True, print_skips=True, paths=args.path, prefix=args.prefix) if len(classes) == 0: print("[red]Something is seriously wrong - no classes imported[/]") sys.exit(1) if warns: print("[yellow]There were warnings generated during the import[/]") for w in warns: one_line_message = str(w.message).replace('\n', ' ') print(f"[yellow]{w.filename}:{w.lineno}: {one_line_message}[/]")
def do_zclsubscribe(self, line): """ To subscribe ZCL attribute reporting: zclsubscribe <cluster> <attribute> <nodeid> <endpoint> <minInterval> <maxInterval> To shut down a subscription: zclsubscribe -shutdown <subscriptionId> """ try: args = shlex.split(line) all_attrs = self.devCtrl.ZCLAttributeList() if len(args) == 1 and args[0] == '?': print('\n'.join(all_attrs.keys())) elif len(args) == 2 and args[0] == '?': if args[1] not in all_attrs: raise exceptions.UnknownCluster(args[1]) cluster_attrs = all_attrs.get(args[1], {}) print('\n'.join([ key for key in cluster_attrs.keys() if cluster_attrs[key].get("reportable", False) ])) elif len(args) == 6: if args[0] not in all_attrs: raise exceptions.UnknownCluster(args[0]) res = self.devCtrl.ZCLSubscribeAttribute( args[0], args[1], int(args[2]), int(args[3]), int(args[4]), int(args[5])) print(res.GetAllValues()) print(f"Subscription Established: {res}") elif len(args) == 2 and args[0] == '-shutdown': subscriptionId = int(args[1], base=0) self.devCtrl.ZCLShutdownSubscription(subscriptionId) else: self.do_help("zclsubscribe") except exceptions.ChipStackException as ex: print( "An exception occurred during configuring reporting of ZCL attribute:" ) print(str(ex)) except Exception as ex: print("An exception occurred during processing input:") print(str(ex))
from brainrender import Scene from brainrender.actors import make_neurons, Neuron from morphapi.api.mouselight import MouseLightAPI from rich import print from myterial import orange from pathlib import Path print(f"[{orange}]Running example: {Path(__file__).name}") # Create a brainrender scene scene = Scene(title="neurons") # Add a neuron from file scene.add(Neuron("examples/data/neuron1.swc")) # Download neurons data with morphapi mlapi = MouseLightAPI() neurons_metadata = mlapi.fetch_neurons_metadata(filterby="soma", filter_regions=["MOs"]) to_add = [neurons_metadata[47], neurons_metadata[51]] neurons = mlapi.download_neurons(to_add) neurons = scene.add(*make_neurons(*neurons, neurite_radius=12)) # Render! scene.render()
def _display_results( self, data: Union[List[dict], List[str], dict, None] = None, tablefmt: str = "rich", title: str = None, caption: str = None, pager: bool = False, outfile: Path = None, sort_by: str = None, reverse: bool = False, stash: bool = True, pad: int = None, set_width_cols: dict = None, full_cols: Union[List[str], str] = [], fold_cols: Union[List[str], str] = [], cleaner: callable = None, **cleaner_kwargs, ): if data: data = utils.listify(data) if cleaner and not self.raw_out: data = cleaner(data, **cleaner_kwargs) data = utils.listify(data) if sort_by and all(isinstance(d, dict) for d in data): if sort_by not in data[0] and sort_by.replace("_", " ") in data[0]: sort_by = sort_by.replace("_", " ") if not all([True if sort_by in d else False for d in data]): print( f":x: [dark_orange3]Error: [cyan]{sort_by}[reset] does not appear to be a valid field" ) print("Valid Fields:\n----------\n{}\n----------".format( "\n".join(data[0].keys()))) else: try: type_ = str for d in data: if d[sort_by] is not None: type_ = type(d[sort_by]) break data = sorted(data, key=lambda d: d[sort_by] if d[sort_by] != "-" else 0 or 0 if type_ == int else "") except TypeError as e: print( f":x: [dark_orange3]Warning:[reset] Unable to sort by [cyan]{sort_by}.\n {e.__class__.__name__}: {e} " ) if reverse: data = data[::-1] if self.raw_out and tablefmt in ["simple", "rich"]: tablefmt = "json" # TODO make sure "account" is not valid then remove from list below if config.account == "account": log.warning("DEV NOTE account is 'account'", show=True) kwargs = { "outdata": data, "tablefmt": tablefmt, "title": title, "caption": caption, "account": None if config.account in ["central_info", "default", "account"] else config.account, "config": config, "set_width_cols": set_width_cols, "full_cols": full_cols, "fold_cols": fold_cols, } outdata = utils.output(**kwargs) if stash: config.last_command_file.write_text( json.dumps( {k: v for k, v in kwargs.items() if k != "config"})) typer.echo_via_pager(outdata) if pager and tty and len( outdata) > tty.rows else typer.echo(outdata) if "Limit:" not in outdata and caption is not None and cleaner and cleaner.__name__ != "parse_caas_response": print(caption) if outfile and outdata: self.write_file(outfile, outdata.file) else: log.warning(f"No data passed to _display_output {title} {caption}")