コード例 #1
0
ファイル: collect.py プロジェクト: mrdro1/channel_utils
 def get_user_video(self, user_id):
     _first = True
     count_of_loaded_photo = 0
     next_max_id = None
     while next_max_id or _first:
         try:
             _first = False
             results = self.API.user_feed(user_id=user_id,
                                          max_id=next_max_id)
             for item in results.get('items', []):
                 try:
                     id = item["id"]
                     date = item["caption"]["created_at"]
                     photo_url = item['video_versions'][0]['url']
                     print('I find video))')
                 except:
                     continue
                 if self._save_photo(photo_url, id, date, extension='mp4'):
                     print('I load video))')
                     db_utils.insert_photo({
                         "source_id": id,
                         "source": self.Source,
                         "date": date
                     })
                     count_of_loaded_photo += 1
                     if count_of_loaded_photo % db_utils.COMMIT_COUNT == 0:
                         db_utils.commit()
             next_max_id = results.get('next_max_id')
         except:
             utils.print_message(traceback.format_exc())
     db_utils.commit()
     return count_of_loaded_photo
コード例 #2
0
ファイル: search.py プロジェクト: zyhuang/ragno
def get_filter_options_url(driver, filt_name):
    # filt_name = 'SKILL LEVELS', 'ROLES', 'SUBJECTS TO LEARN'
    # 'TOOLS', 'CERTIFICATIONS', 'AUTHORS'
    # reload the search url
    utils.print_message('get options of filter {} ...'.format(filt_name))
    utils.open_url(driver, search_url, reopen=True)

    opt_url_dict = dict()
    for filt in driver.find_elements_by_xpath(
            '//li[starts-with(@class, "facet__section ")]'):
        if filt_name != filt.find_element_by_xpath('./div/h3').text:
            continue

        # expand option list
        if (filt.get_attribute('class') ==
                'facet__section l-search__facets-list--item'):
            filt.find_element_by_xpath('./div/div').click()

        # get all options
        for opt in filt.find_elements_by_xpath('.//a[@role="checkbox"]'):
            opt_name = opt.get_attribute('aria-label')
            opt_url = opt.get_attribute('href')
            opt_url_dict[opt_name] = opt_url

    utils.print_message('found urls of {} options'.format(len(opt_url_dict)))

    return opt_url_dict
コード例 #3
0
    def drop(self, player, location):
        config = self.get_config()
        location.add_inventory_item(self.name, config)
        player.remove_inventory_item(self.name)

        utils.print_message("You drop the '{}'".format(colour.green(
            self.name)))
コード例 #4
0
    def go(self, game, location_name):
        location = game.get_location()
        locations = utils.build_index(location.find_item_by_attribute("room"))
        location_names = sorted(locations)
        if (location_name):
            if (len(location_name) == 1 and location_name in location_names):
                # using the alias - so look up name
                loc = locations[location_name]
                location_name = loc["name"]
            self._go(game, location_name, location)
        else:
            # try auto routing - if room has single exit

            # commented out - always go to first location in list of routes - as per UI
            # if(len(location_names) > 2): # locations are indexed, so will have alias in it too.
            #     utils.print_message("I dont understand where to go - Try: go <place>")
            #     return

            if (len(location_names) < 1):
                # the solution must be in this room
                utils.print_message(
                    "There doesn't appear to be anywhere I can go to at the moment."
                )
                return

            location_name = location_names[0]
            if (len(location_name) == 1 and location_name in location_names):
                # using the alias - so look up name
                loc = locations[location_name]
                location_name = loc["name"]

            self._go(game, location_name, location)
コード例 #5
0
 def describe(self):
     if ("description" in self._config):
         desc = self._config["description"]
         for line in desc:
             utils.print_message(colour.blue(line))
     else:
         utils.print_message("You see nothing special.")
コード例 #6
0
def send_comment_to_wall_post(msg, ids, count=20, use_random_photo=False):
    for id in ids:
        try:
            t = random.randint(10, 11)
            time.sleep(t)
            posts_info = API.wall.get(owner_id=id, count=count)[1:]
        except:
            utils.print_message(traceback.format_exc())
            #utils.print_message('нет доступа к постам {}'.format(id))
            continue
        for i, post in enumerate(posts_info):
            try:
                t = random.randint(5, 6)
                time.sleep(t)
                att = upload_photo_to_wall(id)[0]["id"] if use_random_photo else None
                API.wall.createComment(owner_id=id, post_id=post['id'], message=msg, attachments=att)
                utils.print_message('послал коммент на стену. id сообщества: {}'.format(id))
                global SUCCESS_POST
                SUCCESS_POST += 1
            except vk.exceptions.VkAPIError as e:
                if e.code == 14:
                    input("Введите капчу. Нажмите Enter для продолжения.")
                elif e.code == 213:
                    utils.print_message('для группы {} комменты на стене заблокированы'.format(id))
                    break
                else:
                    utils.print_message(traceback.format_exc())
            except:
                utils.print_message(traceback.format_exc())
                #
            if i == count:
                break
    return 0
コード例 #7
0
ファイル: script.py プロジェクト: adelrio89/codecademy
def coffee_bot():
    print('Welcome to the cafe!')
    order_drink = "y"
    drinks = []
    yes_options = ["y", "yes", "sure"]
    no_options = ["n", "no", "nah"]
    exit_words = ["stop", "bye"]
    while order_drink in yes_options:
        size = get_size()
        drink_type = get_drink_type()
        drink = '{} {}'.format(size, drink_type)
        print('Alright, that\'s a {}!'.format(drink))
        drinks.append(drink)
        while True:
            res = input("Would you like to order another drink? (y/n)")
            if res in no_options:
                name = input('Can I get your name please? \n> ')
                print('Thanks, {}! Your order will be ready shortly.'.format(
                    name))
                print("Okay, so I have:")
                for i in drinks:
                    print(i)
                return
            if res in yes_options:
                break
            print_message()
コード例 #8
0
ファイル: course.py プロジェクト: zyhuang/ragno
    def rename_exercise_files(self, down_dir):

        # get downloaded temporary file
        tmp_fname = ''
        wait_time = 3  # check download dir every wait_time seconds
        wait_time_max = 10 * 60  # give up after wait_time_max seconds
        nretry = 0
        nretry_max = wait_time_max / wait_time
        while True:
            tmp_flist = [
                self.cache_dir + '/' + x for x in os.listdir(self.cache_dir)
                if x.endswith('.zip')
            ]

            if len(tmp_flist) != 0:
                tmp_flist.sort(key=lambda x: os.path.getmtime(x), reverse=True)
                tmp_fname = tmp_flist[0]
                break

            utils.wait(3)
            nretry += 1

            if nretry == nretry_max:
                utils.print_message('*ERROR*: download time out. retry later!')
                utils.clean_dir(self.cache_dir)
                sys.exit(1)

        os.makedirs(down_dir, exist_ok=True)
        new_fname = '{}/{}'.format(down_dir, tmp_fname.split('/')[-1])
        os.rename(tmp_fname, new_fname)
        utils.print_message(
            'save downloaded exercise files as {}'.format(new_fname))
        return new_fname
コード例 #9
0
ファイル: coffeebot_v3.py プロジェクト: dtsyi100/coffeebot
def order_mocha():
  while True:
    res = input('Would you like to try our limited-edition peppermint mocha? \n[a] Sure! \n[b] Maybe next time! \n>')
    if res == 'a':
      return 'peppermint mocha'
    elif res == 'b':
      return 'mocha'
    print_message()
コード例 #10
0
def read_ranked_columns(fn):

    frame = inspect.currentframe().f_code.co_name
    utils.print_message(frame,"Reading vote matrix data.")

    df = utils.load_file(fn)

    return df
コード例 #11
0
def order_mocha():
  while True:
    res = input("Would you like to try out our limited-edition peppermint mocha? \n[a] Sure!\n[b] Maybe next time!\n> ")
    if res == 'a':
      return "peppermint mocha"
    elif res == "b":
      return "mocha"
    print_message()
コード例 #12
0
ファイル: course.py プロジェクト: zyhuang/ragno
    def get_description(self):

        if not self.switch_tab('Description'):
            utils.print_message('This course has no description.')
            return

        utils.print_message('extracting description ...')
        self.description = self.driver.find_element_by_xpath(
            '//div[@class="l-course-page__content"]/p').text
コード例 #13
0
def create_tlg_client():
    api_id, api_hash, phone = utils.read_tlg_token()

    client = TelegramClient('@Sess81', api_id, api_hash)
    client.connect()
    client.sign_in(phone=phone)
    me = client.sign_in(code=input('введи код из сообщения от телеги: '))
    utils.print_message(client.is_user_authorized())
    return client
コード例 #14
0
 def _invoke(self, action):
     if (self._registry.has_command(action.action)):
         cmd = self._registry.get_command(action.action)
         if (cmd.pass_args):
             cmd.command(self._game, action.args)
         else:
             cmd.command(self._game)
     else:
         utils.print_message("I dont know how to '{}'".format(
             colour.red(action.action)))
コード例 #15
0
def read_forms_data(fn):

    frame = inspect.currentframe().f_code.co_name
    utils.print_message(frame,"Reading MS Forms data.")

    df = utils.load_file(fn)

    df.columns = [np.arange(0,df.shape[1])]

    return df
コード例 #16
0
def upload_photo_to_message(peer_id):
    try:
        upload_info = API.photos.getMessagesUploadServer(peer_id=peer_id)
        photo = get_rand_photo()
        if photo is None: return None
        resp = json.loads(requests.post(upload_info["upload_url"], files={"file1":photo}).content)
        return API.photos.saveMessagesPhoto(server=resp["server"], photo=resp["photo"], hash=resp["hash"])
    except:
        utils.print_message("Не удалось загрузить фотографию в диалог {}.".format(peer_id))
        utils.print_message(traceback.format_exc())
    return None
コード例 #17
0
def upload_photo_to_album(album_id):
    try:
        upload_info = API.photos.getUploadServer(album_id=album_id)
        photo = get_rand_photo()
        if photo is None: return None
        resp = json.loads(requests.post(upload_info["upload_url"], files={"file1":photo}).content)
        return API.photos.save(album_id=album_id, server=resp["server"], photos_list=resp["photos_list"], hash=resp["hash"])
    except:
        utils.print_message("Не удалось загрузить фотографию в альбом {}.".format(album_id))
        utils.print_message(traceback.format_exc())
    return None
コード例 #18
0
ファイル: core.py プロジェクト: webisaac/isip
def new_variable_adder(name, pkt, variable_list):
    global i
    t = ISipInterface(name="{0}.{1}".format(name, i))
    t.ip = pkt[IP]
    t.udp = pkt[UDP]
    t.message = ISipRequestMessage(str(pkt[Raw]))
    del t.ip[UDP]
    del t.udp[Raw]
    variable_list.add(t)
    utils.print_message("New variable: '{0}'".format(t.name))
    i += 1
コード例 #19
0
def order_brewed_coffee():
  while True:
    res = input('What is your chose?\n [a] Classic Style\n [b]Cold Version\n')
    if res == 'a':
      return 'Classic Brewed Coffee'
    elif res == 'b':
      return 'Cold Brewed'
    elif res == 'stop':
      raise SystemExit
    else:
      print_message()
      return get_drink_type() 
コード例 #20
0
def order_mocha():
  while True:
    res = input('Would you like to try our limited-edition peppermint mocha?\n [a] Sure\n [b] Maybe next time!\n')
    if res == 'a':
      return 'peppermint mocha'
    elif res == 'b':
      return 'mocha'
    elif res == 'stop':
      raise SystemExit
    else:
      print_message()
      return get_drink_type()
コード例 #21
0
ファイル: coffeebot_v3.py プロジェクト: dtsyi100/coffeebot
def get_drink_type():
  res = input('What type of drink would you like? \n[a] Brewed Coffee \n[b] Mocha \n[c] Latte \n> ')

  if res == 'a':
    return 'brewed coffee'
  elif res == 'b':
    return order_mocha()
  elif res == 'c':
    return order_latte()
  else:
    print_message()
    return get_drink_type()
コード例 #22
0
def upload_photo_to_wall(group_id):
    try:
        group_id = abs(int(group_id))
        upload_info = API.photos.getWallUploadServer(group_id=group_id)
        photo = get_rand_photo()
        if photo is None: return None
        resp = json.loads(requests.post(upload_info["upload_url"], files={"file1":photo}).content)
        return API.photos.saveWallPhoto(group_id=group_id, server=resp["server"], photo=resp["photo"], hash=resp["hash"])
    except:
        utils.print_message("Не удалось загрузить фотографию на стену {}.".format(group_id))
        utils.print_message(traceback.format_exc())
    return None
コード例 #23
0
 def move(self, game, item_name):
     location = game.get_location()
     if (item_name):
         context = self._get_context(item_name, [location, game.player])
         if (context):
             item = context.get_inventory_item(item_name)
             item.move(context)
         else:
             utils.print_message(
                 "I cant see a '{}' - Try open <item>".format(
                     colour.red(item_name)))
     else:
         utils.print_message("I dont know what to move - Try open <item>")
コード例 #24
0
def order_mocha():
    while True:
        res = input(
            """Would you like to try our limited-edition peppermint mocha?
[a] Sure!
[b] Maybe next time! \n""")
        if res == 'a':
            return 'peppermint mocha'
        elif res == 'b':
            return 'mocha'
        else:
            print_message()
            return order_mocha()
コード例 #25
0
ファイル: scenes.py プロジェクト: lysukhin/Adventure
    def enter(self):
        message = [
            'You are the pilot of a spaceship. The big one.',
            'Your ship is about to waste it\'s last gallon of fuel.',
            'You see two planets ahead: one is blue, other is green.',
            'Which one will you choose to land on?'
        ]
        print_message(message)

        action = input('Your action >: ')
        if action == 'blue':
            message = [
                'You choose to land on a blue planet.',
                'The surface seems to be inhabitable at first glance.',
                'However, after leaving the ship you get caught in the ',
                'trap by blue-skinned aliens.', 'You are raped to death.'
            ]
            print_message(message)
            return 'end'
        elif action == 'green':
            message = [
                'You choose to land on a green planet.',
                'The surface seems to be inhabitable at first glance.',
                'However, after leaving the ship you get caught in the ',
                'trap by green-skinned aliens.', 'You are raped to death.'
            ]
            print_message(message)
            return 'end'
        else:
            message = ['Your action is unacceptable! Try again.']
            print_message(message)
            return 'cockpit'
コード例 #26
0
ファイル: course.py プロジェクト: zyhuang/ragno
    def get_exercise_files(self, down_dir):

        if not self.switch_tab('Exercise files'):
            utils.print_message('This course has no exercise files.')
            return

        button_list = self.driver.find_elements_by_xpath(
            '//button[@class="button"]')

        if len(button_list) == 0:
            utils.print_message('This course has no exercise files.')
            return

        for button in button_list:
            if button.text != 'Download exercise files':
                continue
            utils.print_message('downloading exercise files ...')
            button.click()
            # in case it turns an XML with access denied error code
            # e.g. https://app.pluralsight.com/library/courses/shattering-statue-bullet-physics-maya-2062/table-of-contents
            if len(
                    self.driver.find_elements_by_id(
                        'webkit-xml-viewer-source-xml')):
                utils.print_message('The exercise files access is denied.')
                self.driver.back()
                skip_ads(self.driver)
                return
            self.exercise_files = self.rename_exercise_files(down_dir)
コード例 #27
0
def is_login(driver, verbose=False):
    try:
        name = driver.find_element_by_xpath(
            '//*[starts-with(@class, "firstName---")]').text
    except:
        name = None
    if name:
        if verbose:
            utils.print_message('Hello {}!'.format(name))
        return True
    else:
        if verbose:
            utils.print_message('You are not login.')
        return False
コード例 #28
0
ファイル: script.py プロジェクト: Kummma/Coffee_ChatBot1
def get_drink_type():
    res = input(
        "Какой напиток вы хотите заказать? \n[a] Американо \n[b] Мокко \n[c] Латте \n> "
    )

    if res == "a":
        return order_americano()
    elif res == "b":
        return order_mocha()
    elif res == "c":
        return order_latte()
    else:
        print_message()
        return get_drink_type()
コード例 #29
0
ファイル: main.py プロジェクト: exploit-inters/INSTACAT
def parser_init():
    # Command line parser
    _parser = argparse.ArgumentParser()
    requiredNamed = _parser.add_argument_group('Required arguments')
    requiredNamed.add_argument("-c",
                               "--control",
                               action="store",
                               dest="CONTROL_FILE_NAME",
                               help="Control file",
                               type=str,
                               required=True)
    try:
        with open(_parser.parse_args().CONTROL_FILE_NAME, "r") as data_file:
            PARAMS.update(json.load(data_file))
        for key in PARAMS.keys():
            if not key in CONTROL_KEYS:
                raise Exception("Unknown parameter: {0}".format(key))
        # check all params, if null then set default
        for key in CONTROL_DEFAULT_VALUES.keys():
            PARAMS.setdefault(key, CONTROL_DEFAULT_VALUES[key])
    except Exception as error:
        utils.print_message("Invalid file control. Check the syntax.")
        utils.print_message(error.args[0])
        exit()
    utils.print_message("Parameters:")
    for key in PARAMS.keys():
        param_str = "  {0} = '{1}'".format(key, PARAMS[key])
        utils.print_message(param_str)
    _SUCCESSFUL_START_FLAG = True
コード例 #30
0
 def unlock(self, game, action, method="key"):
     # location = game.get_location()
     if (action):
         items = action.split(" with ")
         if (not (type(items) == list and len(items) == 2)):
             items = action.split(" w ")  # alias
         if (type(items) == list and len(items) == 2):
             location = game.get_location()
             context = self._get_context(items[0], [location, game.player])
             if (not context):
                 utils.print_message("I cannot see a '{}'".format(
                     colour.red(items[0])))
                 return
             ##TODO we could index target and use alias
             target = context.get_inventory_item(items[0])
             if (not game.player.has_inventory_item(items[1])):
                 utils.print_message("You dont have a {}".format(
                     colour.red(items[1])))
                 return
             ##TODO we could index tools and use alias
             tool = game.player.get_inventory_item(items[1])
             target.unlock(location, tool, method)
         else:
             method_display = method
             if (method == "key"):
                 method_display = "unlock"
             utils.print_message(
                 "I dont understand: '{}' - Try {} <item> with <item>.".
                 format(
                     colour.red(action),
                     colour.red(method_display),
                 ))
     else:
         utils.print_message(
             "I dont understand - Try: unlock <item> with <item>")
コード例 #31
0
    import configparser
    import subprocess
    import shutil
    import argparse
    import time
    import re
    from stat import S_ISREG, ST_MTIME, ST_MODE

    import target
    import gui

except ImportError as e:
    # could not import one of the remaining
    # modules
    utils.print_message(utils.logtype.ERROR,
                        "Dependencies missing:",
                        e)
    # call exit explicitly in case the break
    # on error options is not set
    sys.exit(1)


registered_toolchains = dict()

master_repo_name = "sources"
bscripts_path = os.path.abspath(os.path.dirname(sys.argv[0]))
root_path= os.path.abspath(bscripts_path + "/..")
master_repo_path = root_path + "/" + master_repo_name
state = "INIT"
done = False
build_log_file = None