def list(depth=None): tree = get_dependency_tree() # click.echo(json.dumps(tree, indent=4)) piper_file = project.piper_file base_keys = [_key for _key in piper_file["dependencies"]] dev_keys = [_key for _key in piper_file["dev_dependencies"]] click.echo("# " + crayons.green("base = green") + " | " + crayons.magenta("dev = magenta") + " | " + crayons.cyan("sub dependencies = cyan")) for node in tree: name = node["package"]["package_name"] if node["package"]["package_name"].lower() in IGNORED_PACKAGES: continue elif node["package"]["package_name"].lower() in base_keys: name = crayons.green(node["package"]["package_name"]) elif node["package"]["package_name"].lower() in dev_keys: name = crayons.magenta(node["package"]["package_name"]) else: name = crayons.cyan(node["package"]["package_name"]) click.echo("├─ {0}=={1}".format(name, node["package"]["installed_version"])) for dep in node["dependencies"]: version_string = dep["required_version"] or "" click.echo("│ └─ {0}{1}".format(dep["package_name"], version_string)) click.echo( crayons.green( emoji.emojize("\n:sparkles: Package list complete", use_aliases=True)))
async def clean(ctx: fortnitepy.ext.commands.Context) -> None: await ctx.send('Cleared CMD') clear() print( crayons.magenta( f'███████╗██╗ █████╗ ██████╗ ██████╗ █████╗ ████████╗') ) print( crayons.magenta( f'██╔════╝██║ ██╔══██╗██╔══██╗ ██╔══██╗██╔══██╗╚══██╔══╝') ) print( crayons.magenta( f'█████╗ ██║ ██║ ██║██████╔╝█████╗██████╦╝██║ ██║ ██║ ') ) print( crayons.magenta( f'██╔══╝ ██║ ██║ ██║██╔═══╝ ╚════╝██╔══██╗██║ ██║ ██║ ') ) print( crayons.magenta( f'██║ ███████╗╚█████╔╝██║ ██████╦╝╚█████╔╝ ██║ ') ) print( crayons.magenta( f'╚═╝ ╚══════╝ ╚════╝ ╚═╝ ╚═════╝ ╚════╝ ╚═╝ ') ) print( crayons.red( f'---------------------------------------------------------------------' )) print( crayons.magenta( f'[FLOP BOT] [{time()}] massive shout out to oli for inspiring me') ) print( crayons.magenta( f'[FLOP BOT] [{time()}] Discord server: https://discord.gg/7WrH6r3 ' )) print( crayons.magenta(f'[FLOP BOT] [{time()}] For support, questions, etc')) print( crayons.cyan( f'[FLOP BOT] [{time()}] This bot is in progress, if any issue occurs' )) print( crayons.cyan( f'[FLOP BOT] [{time()}] Please report to the discord ASAP')) print( crayons.red( f'---------------------------------------------------------------------' )) print( crayons.green( f'[FLOP BOT] [{time()}] Client ready as {client.user.display_name}' )) print( crayons.red( f'---------------------------------------------------------------------' ))
def add(git_remote): """Add a new repository to look for Dockerfiles""" git_remote = parse(git_remote) if git_remote.valid: repo_name = f'{git_remote.owner}_{git_remote.repo}' destination = settings.REPO_DIR.joinpath(repo_name) if destination.exists(): if click.confirm( crayons.cyan( 'That repo is already added, do you want me to add it again?' )): click.echo( crayons.red('Removing existing repo' + settings.LOADING)) shutil.rmtree(destination) else: raise click.Abort click.echo('{0} {1}{2}'.format( crayons.white('Adding repository', bold=True), crayons.green(repo_name), crayons.white(settings.LOADING, bold=True))) click.echo(f'repo dir - {str(destination)}') with Halo(): git.Repo.clone_from(git_remote.url2git, str(destination)) click.echo( crayons.cyan('Successfully added repository ', bold=True) + crayons.green(repo_name)) else: click.echo( crayons.red("I don't think that's a valid git remote url, sorry."))
def main(): logger.info("Starting") try: read_emojis() logger.info(f"Loaded [{len(emojis)}] emojis") print(crayons.cyan(list(emojis.keys()))) except EnvironmentError as enve: logger.warning(enve) try: tok = token() except ValueError as ve: logger.exception(ve) tok = input(crayons.cyan("Please enter your token: ")) config.token = tok try: bot.run(tok, bot=False) finally: logger.info("SAVING EMOJIS") save_emojis() logger.info("SAVING CONFIG") config.save()
def mainframe(): print("\nYour computer screen displays this message: \n") print(crayons.cyan("MAGMA LTD. - Interal System Bulletins\n")) print( crayons.red( "TOP SECRET - World Domination Plans have been relocated for security. One page has been sent to an agent in each of our affiliated countries.\n" )) time.sleep(3) print( "Hmmm, you think, wasn't there a reward posted for thwarting evil plans? How can I get those? \n Further down the screen you notice: \n" ) time.sleep(3) print(crayons.cyan("The travel droid is fully charged.\n")) time.sleep(3) print( "What would you like to do? \n Enter 1 - get out of here it could be dangerous \n Enter 2 - click on travel droid" ) while True: action = input(crayons.cyan("> ")).strip() if action == "1": print( "Good thinking those agents could be dangerous. Maybe go play a safer game like Mario. Goodbye" ) time.sleep(3) endGame() break elif action == "2": print("Excellent choice - your adventure begins!!") travelDroid() break elif action != "2" and action != "1": action = input(crayons.cyan("> ")).strip()
def output_config(kube_cluster: 'KubeCluster'): cluster_config_title = f'Cluster Config' print(crayons.cyan(cluster_config_title)) print(crayons.cyan('=' * len(cluster_config_title))) cluster_config = (f'Context: {kube_cluster.cluster_attributes.context}', f'User: {kube_cluster.cluster_attributes.user}') print(crayons.white('\n'.join(cluster_config))) print('')
def load_repository(self, addon: str): """Load repository configuration from remote repository and add-ons.""" click.echo("Locating repository add-on list...", nl=False) try: config = self.github_repository.get_contents(".addons.yml") except UnknownObjectException: print( "Seems like the repository does not contain an " ".addons.yml file, falling back to legacy file." ) try: config = self.github_repository.get_contents(".hassio-addons.yml") except UnknownObjectException: print( "Seems like the repository does not contain an " ".hassio-addons.yml file either." ) sys.exit(1) config = yaml.safe_load(config.decoded_content) click.echo(crayons.green("Loaded!")) if not config["channel"] in CHANNELS: click.echo( crayons.red( 'Channel "%s" is not a valid channel identifier' % config["channel"] ) ) sys.exit(1) self.channel = config["channel"] click.echo("Repository channel: %s" % crayons.magenta(self.channel)) if addon: click.echo(crayons.yellow('Only updating addon "%s" this run!' % addon)) click.echo("Start loading repository add-ons:") for target, addon_config in config["addons"].items(): click.echo(crayons.cyan("-" * 50, bold=True)) click.echo(crayons.cyan(f"Loading add-on {target}")) self.addons.append( Addon( self.git_repo, target, addon_config["image"], self.github.get_repo(addon_config["repository"]), addon_config["target"], self.channel, ( not addon or addon_config["repository"] == addon or target == addon ), ) ) click.echo(crayons.cyan("-" * 50, bold=True)) click.echo("Done loading all repository add-ons")
def print_dir_summary(self, path, colour_list=True): """Gets a sub-directory listing from the root of the specified path""" if not self.verify_dir_not_file(path): return False dirname = full_path(path) if os.path.isdir(dirname): fs = { "dir_count": 0, "file_count": 0, "max_size": 0, "total_size": 0, "mean_size": 0, "dir_size": {}, } longest_name = 0 files = Path(dirname).glob("*") for file in files: size = 0 f, e = split_filename(file) ext = e.replace(".", "").lower() if os.path.isdir(file): size = sum(f.stat().st_size for f in file.glob("**/*") if f.is_file()) subdir = str(file).replace(dirname, "").replace(os.sep, "") fs["dir_size"][subdir] = size fs["dir_count"] += 1 longest_name = max(len(subdir), longest_name) elif os.path.isfile(file): fs["file_count"] += 1 size = os.path.getsize(file) fs["total_size"] += size fs["max_size"] = max(size, fs["max_size"]) if fs["file_count"] > 0: fs["mean_size"] = fs["total_size"] / fs["file_count"] print("Directory: " + crayons.blue(dirname, bold=True)) print(" Files : " + crayons.cyan(fs["file_count"])) print(" Directories : " + crayons.cyan(fs["dir_count"])) print(" Total size : " + file_size_str(fs["total_size"], style="mono")) print(" Max size : " + file_size_str(fs["max_size"], style="mono")) print(" Average size : " + file_size_str(fs["mean_size"], style="mono")) listext = sorted(fs["dir_size"].items(), key=lambda x: x[1], reverse=True) longest_name = max(15, longest_name) fmt = "%%%ds : %%10s" % (longest_name) style = "colour" if colour_list else "mono" for el in listext: sd = " " * (longest_name - len(el[0])) + crayons.blue( el[0], bold=True) print(fmt % (sd, file_size_str(el[1], style=style))) elif self.verbose: self.colprint("Directory ", dirname, " does not exist", "red") return False
def showStatus(): print(crayons.cyan('--------------------------')) print(crayons.cyan('You are in ' + currentLocale)) # print players inventory print(crayons.cyan("Your inventory includes: " + str(inventory))) # print an item if there is one in the room if "item" in locales[currentLocale]: print(crayons.cyan("You see a " + locales[currentLocale]['item'])) print(crayons.cyan('--------------------------'))
def do_POST(self): content_length = int(self.headers['Content-Length']) body = self.rfile.read(content_length) self.send_response(200) self.end_headers() print(cyan('Webhook triggered', bold=True)) webhook = json.loads(body) print(green(' Retreive message', bold=True)) result = send_webex_get('https://webexapis.com/v1/messages/{0}'.format( webhook['data']['id'])) result = json.loads(result) if webhook['data']['personEmail'] != bot_email: in_message = result.get('text', '').lower() in_message = in_message.replace(bot_name.lower(), '') print(yellow("Message :", bold=True)) print(cyan(in_message, bold=True)) if in_message.startswith('help'): print(yellow("help received let s reply", bold=True)) msg = '''**How To Use:**\n- **help**, bring this help; \n- **:command-1**, trigger some python function \n- **:command-2**, trigger some python function 2\n ''' send_webex_post("https://webexapis.com/v1/messages", { "roomId": webhook['data']['roomId'], "markdown": msg }) elif in_message.startswith('ping'): print(yellow("let s reply PONG to this ping", bold=True)) send_webex_post("https://webexapis.com/v1/messages", { "roomId": webhook['data']['roomId'], "markdown": "*PONG !*" }) elif in_message.startswith(':command-1'): print(yellow("command-1", bold=True)) send_webex_post( "https://webexapis.com/v1/messages", { "roomId": webhook['data']['roomId'], "markdown": "*Do this* - ( line 65 in the script )" }) elif in_message.startswith(':command-2'): print(yellow("command-2", bold=True)) send_webex_post( "https://webexapis.com/v1/messages", { "roomId": webhook['data']['roomId'], "markdown": "*Do that- ( line 68 in the script )*" }) else: send_webex_post( "https://webexapis.com/v1/messages", { "roomId": webhook['data']['roomId'], "markdown": "*I don't understand this*" }) else: print( cyan( 'This is a message is a reply sent by BOT. Don t handle it', bold=True)) return "true"
async def clean(ctx: fortnitepy.ext.commands.Context) -> None: os.system('cls' if 'win' in sys.platform else 'clear') print(crayons.cyan(f'[PartyBot] [{time()}] PartyBot made by xMistt. ' 'Massive credit to Terbau for creating the library.')) print(crayons.cyan(f'[PartyBot] [{time()}] Discord server: https://discord.gg/fnpy - For support, questions, etc.')) await ctx.send('Command prompt/terminal cleared.') print(f'[PartyBot] [{time()}] Command prompt/terminal cleared.')
def rooms(): if session['logged_in'] == True and session['user'] == "admin": room = str(request.args['room']) print() print(cyan('Book Room', bold=True)) print(cyan('The Room Is : ' + room, bold=True)) print() return render_template('RoomBookingSDA.html', ROOM=room) else: return render_template('login.html')
def deliberate_observables(): api_key = get_jwt() # Let's get the third party API Key data = { } # Let's create a data directory to be sent back to Threat Response g.verdicts = [ ] # Let's create a list into which we will store valid verdicts data results for every observables g.judgements = [ ] # Let's create a list into which we will store valid judgements data results for every observables relay_input = get_json(ObservableSchema(many=True)) observables = group_observables(relay_input) if not observables: return jsonify_data({}) observables = build_input_api(observables) for observable in observables: o_value = observable['value'] o_type = observable['type'].lower() # print single observable for which to send a reputation query to the third party print(green(o_value, bold=True)) disposition = call_api(o_value, api_key) # query the third party for the observable print(cyan(disposition, bold=True)) # translate the third party returned value to Threat Response Expected value disposition_tuple = get_disposition(disposition) print(cyan(disposition_tuple, bold=True)) # disposition_tuple is not empty then continue if not disposition_tuple: continue # disposition_tuple then get the current date and calculate end date as an end of life date for judgment and verdicts # We need these information as mandatory information to return to Threat Response start_time = datetime.utcnow() end_time = start_time + timedelta(weeks=1) valid_time = { 'start_time': start_time.isoformat() + 'Z', 'end_time': end_time.isoformat() + 'Z', } # Let's append a new verdict item into the verdicts list with the minimum of information expected by the CTIM format g.verdicts.append( get_verdict(o_value, o_type, disposition_tuple, valid_time)) g.judgements.append( get_judgement(o_value, o_type, disposition_tuple, valid_time)) # The g.verdicts list content all verdicts for every requested observable. Let's add this list into the data dictionnary and do some formatting stuffs if g.verdicts: data['verdicts'] = format_docs(g.verdicts) if g.judgements: data['judgements'] = format_docs(g.judgements) # Let's get ready to send back a valid CTIM JSON result to the original Threat Response request . Let's put it into the result dictionnary result = {'data': data} print( green(f"JSON result to be sent to Threat Response : \n{result}", bold=True)) return jsonify(result)
def output_masters(kube_cluster: 'KubeCluster', action: KubeClusterAction = KubeClusterAction.create, vmid_placeholder=9999): masters_title = f'Cluster {kube_cluster.cluster_attributes.name} Master VMs' print(crayons.cyan(masters_title)) print(crayons.cyan('=' * len(masters_title))) print('') common_instance_clones(kube_cluster.masters, action=action, role='master', vmid_placeholder=vmid_placeholder)
def main(): #database="devices.db" database = str(repository_root) + "/bases/devices.db" devices = read_db(database) if devices: for device in devices: print(yellow("Collect VPN Indicators From :", bold=True)) print(cyan(device[1])) #print(white (" DO SOMETHING HERE")) selected_device = {'selected': device[7]} if selected_device['selected'] == 1: selected_device = { 'device_type': device[1], 'ip': device[3], 'username': device[4], 'password': device[5], 'secret': device[6] } if selected_device['device_type'] == 'cisco_asa': print(green("Device type is : cisco_asa", bold=True)) net_connect = ConnectHandler(**selected_device) net_connect.find_prompt() net_connect.enable() output = '**==>\n hostname = ' + net_connect.send_command( "show hostname") output = output + '**vpn-sessiondb \n' + net_connect.send_command( "show vpn-sessiondb") print(output) with open(output_file, 'w') as fichier: fichier.write(output) elif selected_device['device_type'] == 'cisco_ftd': print( red("Device type is : cisco_ftd - NOT AVAILABLE YET - STILL UNDER DEVELOPMENT !", bold=True)) #print(output) else: print(red("Device type is : UNKNOWN !", bold=True)) else: print(red(" => Not Selected")) print( cyan("OK Let's parse result of the show vpnsession-db", bold=True)) parse_show_result('show_result.txt') else: print('NO RESULTS') print( '====================================================================================================' ) print() print( green(" OK ALL DONE !!", bold=True))
def output_cluster(kube_cluster: 'KubeCluster'): title = f'Cluster: {kube_cluster.cluster_attributes.name}' print(crayons.cyan(title)) print(crayons.cyan('=' * len(title))) attributes = ( f'Kubernetes Version: {kube_cluster.cluster_attributes.version}', f'Docker Version: {kube_cluster.cluster_attributes.docker}', f'Proxmox Node Pool: {kube_cluster.cluster_attributes.pool}', f'OS Type: {kube_cluster.cluster_attributes.os_type}', ) print(crayons.white('\n'.join(attributes))) print('')
def cli(template, verbose=False, validate=False, version=False): click.echo(_greeter(), err=True) if version: sys.exit(0) print("{}: {}".format( crayons.white("Inspecting template", bold=True), crayons.blue(template.name))) template = template.read() try: t = json.loads(template) except Exception as e: pass try: json_template = to_json(template) t = json.loads(json_template) except Exception as e: click.echo( "Could not determine the input format or format not sane: {}".format(e), err=True) sys.exit(1) if 'Description' in t: print("{}: {}".format( crayons.white("Description", bold=True), crayons.white("{}".format(t['Description']), bold=False))) if 'Parameters' in t: _pprint_parameters(t['Parameters'], verbose=verbose) if 'Mappings' in t and verbose: _pprint_mappings(t['Mappings']) if 'Conditions' in t: _pprint_conditions(t['Conditions'], verbose=verbose) if 'Resources' in t: _pprint_resources(t['Resources'], verbose=verbose) if 'Outputs' in t: _pprint_outputs(t['Outputs'], verbose=verbose) if validate: if len(template) > 51200: click.echo( crayons.red("Can't validate the template AWS - template size exceeds 51200 bytes"), err=True) sys.exit(1) try: result = _boto_validate(template) if result[0] == True: print(crayons.cyan("Yay ! template is valid", bold=True)) else: print(crayons.cyan(":(, template is not valid: {}".format(result[1]), bold=True)) except Exception as e: click.echo(crayons.red("Problem with boto3 connection, {}".format(e)), err=True) sys.exit(1) sys.exit(0)
async def main() -> None: settings = partybot.BotSettings() await settings.load_settings_from_file('config.json') if settings.debug: enable_debug() async with aiohttp.ClientSession() as session: async with session.request( method="GET", url="https://partybot.net/api/discord") as r: invite = (await r.json())['invite'] if r.status == 200 else "8heARRB" print( crayons.cyan( f"[PartyBot] [{datetime.datetime.now().strftime('%H:%M:%S')}] PartyBot made by xMistt. " 'Massive credit to Terbau for creating the library.')) print( crayons.cyan( f"[PartyBot] [{datetime.datetime.now().strftime('%H:%M:%S')}] Discord server: " f"https://discord.gg/{invite} - For support, questions, etc.")) device_auths = partybot.DeviceAuths(filename='device_auths.json') try: await device_auths.load_device_auths() except partybot.errors.MissingDeviceAuth: print( f"[PartyBot] [{datetime.datetime.now().strftime('%H:%M:%S')}] Automatically opening Epic Games login, " f"please sign in.") gen = partybot.EpicGenerator() new_device_auths = await gen.generate_device_auths() device_auths.set_device_auth(**new_device_auths) await device_auths.save_device_auths() client = partybot.PartyBot(settings=settings, device_auths=device_auths) client.add_cog(partybot.CosmeticCommands(client)) client.add_cog(partybot.PartyCommands(client)) client.add_cog(partybot.ClientCommands(client)) try: await client.start() except fortnitepy.errors.AuthException as e: print(crayons.red(client.message % f"[ERROR] {e}")) await client.http.close()
def AMP1(): """Get a list of recent events from Cisco AMP.""" sha256 = request.args['detection_sha256'] print(cyan(f'SHA256 = {sha256}', bold=True)) token = request.headers.get('Authorization') print() print(cyan('AMP GET All Events for a specific Computer', bold=True)) print() if token == AMP_AUTHORIZATION and sha256 == '01468b1d3e089985a4ed255b6594d24863cfd94a647329c631e4f4e52759f8a9': print(green('AMP Authorization correct :' + token, bold=True)) print(green('SHA256 correct :' + sha256, bold=True)) return render_template('32.json') else: print(red('WRONG AMP Auth or SHA256 ! :' + token, bold=True)) return '{"ERROR": {"error cause":"invalid Authentication Basic Token :' + token + ' "}}'
def main(): """Runtime code. Always indent a function""" # print 'red string' in red print(crayons.red('red string')) # Red White and Blue text print('{} white {}'.format(crayons.red('red'), crayons.blue('blue'))) crayons.disable() # disables the crayons package print('{} white {}'.format(crayons.red('red'), crayons.blue('blue'))) crayons.DISABLE_COLOR = False # enable the crayons package # This line will print in color because color is enabled print('{} white {}'.format(crayons.red('red'), crayons.blue('blue'))) # print 'red string' in red print(crayons.red('red string', bold=True)) # print 'yellow string' in yellow print(crayons.yellow('yellow string', bold=True)) # print 'magenta string' in magenta print(crayons.magenta('magenta string', bold=True)) # print 'white string' in white print(crayons.white('white string', bold=True)) # print my name in two different colors print('{} {}'.format(crayons.cyan('Bob', bold=True), crayons.red('Brady', bold=True)))
def run_command(cmd, *args, is_verbose=False, **kwargs): """ Take an input command and run it, handling exceptions and error codes and returning its stdout and stderr. :param cmd: The list of command and arguments. :type cmd: list :returns: A 2-tuple of the output and error from the command :rtype: Tuple[str, str] :raises: exceptions.PipenvCmdError """ from pipenv._compat import decode_for_output from pipenv.cmdparse import Script catch_exceptions = kwargs.pop("catch_exceptions", True) if isinstance(cmd, ((str,), list, tuple)): cmd = Script.parse(cmd) if not isinstance(cmd, Script): raise TypeError("Command input must be a string, list or tuple") if "env" not in kwargs: kwargs["env"] = os.environ.copy() kwargs["env"]["PYTHONIOENCODING"] = "UTF-8" command = [cmd.command, *cmd.args] if is_verbose: click_echo(f"Running command: $ {cmd.cmdify()}") c = subprocess_run(command, *args, **kwargs) if is_verbose: click_echo( "Command output: {}".format(crayons.cyan(decode_for_output(c.stdout))), err=True, ) if c.returncode and catch_exceptions: raise PipenvCmdError(cmd.cmdify(), c.stdout, c.stderr, c.returncode) return c
def _str_value(v, prec=3, colour="white"): """Prints a single value as an optimal decimal valued string. If the crayons module is detected, then it will show the value in colour (unless the global force_no_colour is True).""" s = better_float_str(str(v), tolerance=prec, pre_strip=False).rstrip(".") if len(s): if s[0] != "-": s = " " + s else: s = " " + s if has_crayons and not force_no_colour: if colour.lower() == "red": return str(crayons.red(s)) elif colour.lower() == "green": return str(crayons.green(s)) elif colour.lower() == "blue": return str(crayons.blue(s)) elif colour.lower() == "yellow": return str(crayons.yellow(s)) elif colour.lower() == "magenta": return str(crayons.magenta(s)) elif colour.lower() == "white": return str(crayons.white(s)) else: return str(crayons.cyan(s)) else: return s
def main(): """run time code. Always indent under function""" # print 'red string' in red print(crayons.red('red string', bold=True)) # print 'yellow string' in yellow print(crayons.yellow('yellow string', bold=True)) # print 'magenta string' in magenta print(crayons.magenta('magenta string', bold=True)) # print 'white string' in white print(crayons.white('white string', bold=True)) # print 'black string' in black print(crayons.black('black string', bold=True)) # print 'green string' in green print(crayons.green('green string', bold=True)) # print 'cyan string' in cyan print(crayons.cyan('cyan string', bold=True)) # print 'blue string' in blue print(crayons.blue('blue string', bold=True)) # print 'Lina Do name' in Red print(crayons.red('Lina Do', bold=True))
def nuke(directory): """This is where all the nuking happens.""" click.echo("Nuking " + crayons.cyan(directory)) ### Nuke the directory # Just iterate over the contents and delete everything accordingly. file_list, ignore_patterns = get_file_list(directory) # Filter the file list based on the ignore patterns. nuke_list = ignore_paths(file_list, ignore_patterns) with click.progressbar(nuke_list, length=len(nuke_list)) as nuke_l: for x in nuke_l: try: delete(x) except (OSError, ) as ex: # file does not exist if ex.errno == errno.ENOENT: click.secho("Nuke target does not exist...", fg="red") else: click.secho( "File exception {0}: {1}!".format( ex.errno, ex.strerror), fg="red", )
def _column(t, q, s): cs = [] cs.append(str(crayons.normal("%15s" % (t)))) cs.append(" : ") cs.append(str(crayons.cyan("%-6d" % (q)))) cs.append("(%10s)" % (file_size_str(s, style=style))) return "".join(cs)
def soul___(self, soul_name): """soul *name*""" if self.does_soul_exist(soul_name): soul = self.spheres.souls[soul_name] rep = crayons.red( "**************************************************************\n" ) rep += crayons.magenta("%s:\n" % soul.name) rep += crayons.green(" vocabulary:\n") for i in range(len(soul.vocabulary)): v = soul.vocabulary[i] rep += crayons.blue(" %d.%s\n " % (i, v)) for e in soul.symbol_basis[v].full().T[0].tolist(): rep += '[{0.real:.2f}+{0.imag:.2f}i] '.format(e) rep += "\n" rep += crayons.yellow(" concordance_matrix:\n") rep += str(soul.concordance_matrix) + "\n" rep += crayons.cyan(" questions:\n") for i in range(len(soul.questions)): question, answer = soul.questions[i] rep += crayons.red(" %d.'%s'\n " % (i, ", ".join(question))) for e in answer.full().T[0].tolist(): rep += '[{0.real:.2f}+{0.imag:.2f}i] '.format(e) rep += crayons.blue( "**************************************************************" ) print(rep)
def generate_predictions_tree(history, distance=3, suppress_output=True, render=False): prediction_tree = {} for exchange, crypto_pairs in history.items(): print(crayons.cyan(' predicting {} hours into the future for {} exchange...'.format(distance, exchange))) prediction_tree[exchange] = {} figures = [] for exchange_pair, rates in crypto_pairs.items(): (from_, to) = exchange_pair df = pandas.DataFrame(rates) df.columns = ['y', 'ds'] with suppress_stdout_stderr(suppress_output): ml = Prophet() ml.fit(df) future = ml.make_future_dataframe(periods=distance, freq='1H', include_history=False) forecast = ml.predict(future) if render: label = '{} {}/{}'.format(exchange, from_, to) figure = ml.plot(forecast, xlabel='time', ylabel=label) figure.suptitle(label) figures.append(figure) forecast_set = forecast[['yhat']] tuple_list = [(x[0], 0) for x in forecast_set.values] tuple_list = [ ( df['y'][df.index[-1]], 0 ) ] + tuple_list # add t=now back in prediction_tree[exchange][exchange_pair] = tuple_list if render: for figure in figures: figure.show() print(crayons.white(' (enter to continue, "skip" to skip rest) '), end='') i = input() render = (i != 'skip') return prediction_tree
def cmd_assign_ordering(self, a, b): print(crayons.red(self.combo_question_string(a))) print("\t.VS.") print(crayons.blue(self.combo_question_string(b))) print(crayons.red("\t coexists ")) print(crayons.green("\t w covers ")) print(crayons.blue("\t q | e ")) print(crayons.yellow("\t defer... | / ")) print(crayons.magenta("\t | / ")) print(crayons.cyan("\t before a _______SUM_______ d after ")) print(crayons.magenta("\t / x ")) print(crayons.yellow("\t is / | p ")) print(crayons.blue("\t covered z | to quit... ")) print(crayons.green("\t by s ")) print(crayons.red("\t excludes ")) ordering = input( crayons.green('.') + crayons.magenta('.') + crayons.blue('.')) while ordering not in ["a", "d", "s", "w", "z", "e", "q", "p"]: if ordering == 'x': if self.questions[a][1].dims != self.questions[b][1].dims: print('wrong dimensions!' ) # add permutations aka word to word mapping! else: return x ordering = input( crayons.green('.') + crayons.magenta('.') + crayons.blue('.')) return ordering
def get_amp_events(query_params="", host=env.AMP.get("host"), client_id=env.AMP_CLIENT_ID, api_key=env.AMP_API_KEY, ): """Get a list of recent events from Cisco AMP.""" print("\n==> Getting events from AMP") url = f"https://{client_id}:{api_key}@{host}/v1/events" response = requests.get(url, params=query_params, verify=False) if debug:#PATRICK print(cyan(env.get_line(),bold=True)) print(cyan(response.json())) # Consider any status other than 2xx an error response.raise_for_status() events_list = response.json()["data"] return events_list
def v_pose(self, question, sentence_space, initial_state=None): print(crayons.red("\t +Z ")) print(crayons.green("\t w +Y ")) print(crayons.blue("\t q quit | e ")) print(crayons.yellow("\t | / ")) print(crayons.magenta("\t | / ")) print(crayons.cyan("\t -X a ________*________ d +X ")) print(crayons.magenta("\t / | ")) print(crayons.yellow("\t / | ")) print(crayons.blue("\t -Y | x save ")) print(crayons.green("\t z s ")) print(crayons.red("\t -Z ")) answer_spheres = [] answer_colors = [ vp.vector(*np.random.rand(3)) for i in range(len(question)) ] for i in range(len(question)): answer_vector = qt.Qobj(sentence_space[i]) answer_vector.dims = [[len(question)], [1]] answer_sphere = MajoranaSphere(len(question), answer_vector,\ color=answer_colors[i],\ star_color=answer_colors[i], tag=question[i]) answer_sphere.visualize() answer_spheres.append(answer_sphere) if initial_state == None: initial_state = qt.Qobj( sum([sentence_space[i] for i in range(len(question))])) decision_sphere = MajoranaSphere(len(question), initial_state) decision_sphere.visualize() save_v_decision = decision_sphere.decide() if save_v_decision: return decision_sphere.state else: return None
def update_status(config, status, computer, manager): """Update each application's status.""" log.info("Recording application status...") for application in config.applications: latest = status.get_latest(application) if manager.is_running(application): if computer != latest: if status.is_running(application, computer): # case 1: application just launched remotely manager.stop(application) status.stop(application, computer) print(crayons.green( f"{application} is now running on {latest}")) print(crayons.red( f"{application} is now stopped on {computer}")) else: # case 2: application just launched locally status.start(application, computer) print(crayons.green( f"{application} is now running on {computer}")) else: # case 3: application already running locally print(crayons.cyan( f"{application} is running on {computer}")) else: if status.is_running(application, computer): # case 4: application just closed locally status.stop(application, computer) print(crayons.red( f"{application} is now stopped on {computer}")) elif latest: # case 5: application already closed locally print(crayons.magenta( f"{application} is running on {latest}")) else: # case 6: application is not running print(crayons.white( f"{application} is not running"))