コード例 #1
0
def _parse_args():
    """ This will parse the incoming arguments for the count and the various number of pancake stacks """
    arg = raw_input()
    if _is_help(arg):
        return _print_usage()
    if not _is_integer(arg):
        print('ERROR: first parameter should be the count of pancake stacks')
        return _print_usage()

    count = int(arg)
    if count < 1 or count > 100:
        print('ERROR: the pancake stack count must be an integer from 1-100')
        return _print_usage()

    pancake_stacks = []
    for i in range(count):
        arg = raw_input()
        if not PancakeStack.is_valid_stack(arg):
            print(
                'ERROR: the pancake stack "%s" is invalid and should only contain \'+\' and \'-\' characters'
                % arg)
            return _print_usage()
        pancake_stacks.append(PancakeStack(arg))

    # We have already checked the size above and have error-ed out if an invalid pancake stack is encountered
    assert len(pancake_stacks) == count
    return pancake_stacks
コード例 #2
0
def connect():
	scan()
	if not os.path.isdir("temp"):
		os.system("mkdir temp")
	id_red = raw_input('Select id: ')
	red = redes[int(id_red)]
	essid = red.get("ssid")
	conf_file = "temp/last_connection.conf"
	cifrado = red.get("cifrado").lower()
	if cifrado == "none":
		os.system("echo 'network={\nssid=\""+essid+"\"\nkey_mgmt=NONE\npriority=100\n}' > conf_file")
		os.system("sudo wpa_supplicant -Dnl80211 -i"+interfaz+" -c"+conf_file+" ")
	elif cifrado == "wep":
		passphrase = raw_input("Passphrase:")
		while ( len(passphrase)!=5 and len(passphrase)!=13 and len(passphrase)!=16 and len(passphrase)!=29):
			print( "Incorrect length (5,13,16 or 29 characters)")
			passphrase = raw_input("Passphrase:")
		os.system("echo 'network={\nssid=\""+essid+"\"\nkey_mgmt=NONE\nwep_key0=\""+passphrase+"\"\nwep_tx_keyidx=0}' > conf_file")
		os.system("sudo wpa_supplicant -Dnl80211 -i"+interfaz+" -c"+conf_file+" ")
	elif cifrado.startswith("wpa"):
		passphrase = raw_input("Passphrase:")
		while len(passphrase)<8:
			print( "Incorrect length (8 or more characters)")
			passphrase = raw_input("Passphrase:")
		os.system("nmcli dev wifi connect "+essid+" password "+passphrase)
	else:
		print( "Unknown encryption type")
	sys.exit()
コード例 #3
0
ファイル: main.py プロジェクト: ricardojoserf/pylangame
def game():
    fails = []
    print("\nGame starts\n")
    if randomize:
        random.shuffle(lines)
    for l in lines:
        if dict_lang != transl_to:
            correct_answer = traductor.translate(
                l, dest=transl_to, src=dict_lang).text.encode("utf-8").decode(
                    "utf-8").encode("utf-8").lower()
        else:
            correct_answer = l
        if dict_lang != qust_lang:
            question = traductor.translate(
                l, dest=qust_lang, src=dict_lang).text.encode("utf-8").decode(
                    "utf-8").encode("utf-8").lower()
            answer = raw_input(question.decode("utf-8") + ": ").lower()
        else:
            question = l
            answer = raw_input(question.decode("utf-8") + ": ").lower()
        if answer == "stop":
            game_stopped()
        if answer != correct_answer:
            print("Failed! Answer: " + correct_answer.upper())
            fails.append(l)
            if restart_f:
                game()
    game_ended()
コード例 #4
0
def create_repo(site, git):
    create = raw_input("Want to create a Github repo for this project [Y/n]? ")
    if create and not create.lower() == "y":
        return puts("Not creating Github repo...")

    name = site.path.split('/')[-1]
    user = raw_input("What is your Github username? ")
    password = getpass.getpass("What is your Github password? ")
    headers = {
        'Content-type': 'application/json',
        'Accept': 'application/json'
    }
    data = {'name': name, 'has_issues': True, 'has_wiki': True}
    resp = requests.post('https://api.github.com/user/repos',
                         auth=(user, password),
                         headers=headers,
                         data=json.dumps(data))
    puts("Created {0!s}".format(
        colored.green("https://github.com/{0}/{1}".format(user, name))))
    clone_url = resp.json().get("clone_url")
    puts(
        git.remote.add("origin",
                       "[email protected]:{0}/{1}.git".format(user, name)))
    puts(git.push("origin", "master"))

    for title, description in ISSUES:
        puts("Creating {0!s}".format(colored.yellow(title)))
        data = {'title': title, 'body': description}
        resp = requests.post(
            'https://api.github.com/repos/{0}/{1}/issues'.format(user, name),
            auth=(user, password),
            headers=headers,
            data=json.dumps(data))
コード例 #5
0
def main(argv):
    parser = argparse.ArgumentParser(description="Delete Firefox Sync data")
    parser.add_argument("email",
                        help="Email of the account for which to delete data")
    parser.add_argument("--accounts-uri",
                        default=DEFAULT_FXA_URI,
                        help="URI of the Firefox Accounts API server")
    parser.add_argument("--tokenserver-uri",
                        default=DEFAULT_TOKENSERVER_URI,
                        help="URI of the Firefox Sync tokenserver")

    args = parser.parse_args(argv)

    # Sign in to the account.
    c = fxa.core.Client(args.accounts_uri)
    password = getpass.getpass("Password for {}: ".format(args.email))
    s = c.login(args.email, password, keys=True)
    try:
        # Verify the session if necessary.
        # TODO: this won't work if the user has enabled two-step auth.
        status = s.get_email_status()
        if not status["sessionVerified"]:
            if s.verificationMethod == "totp-2fa":
                code = raw_input("Enter TOTP code: ")
                s.totp_verify(code)
            else:
                code = raw_input(
                    "Enter verification link or code received via email: ")
                if "?" in code:
                    # They copy-pasted the full URL.
                    code_url = urlparse(code)
                    code = parse_qs(code_url.query)["code"][0]
                s.verify_email_code(code)

        # Prepare authentication details for tokenserver.
        (_, kB) = s.fetch_keys()
        xcs = hashlib.sha256(kB).hexdigest()[:32]
        auth = s.get_identity_assertion(args.tokenserver_uri)

        # Auth to tokenserver, find sync storage node.
        token_uri = urljoin(args.tokenserver_uri, "1.0/sync/1.5")
        r = requests.get(token_uri,
                         headers={
                             "Authorization": "BrowserID " + auth,
                             "X-Client-State": xcs,
                         })
        r.raise_for_status()

        node = r.json()
        api_endpoint = node["api_endpoint"]
        hawk_id = str(node["id"])
        hawk_key = str(node["key"])
        print("Deleting from", api_endpoint)
        req = requests.Request("DELETE", api_endpoint).prepare()
        hawkauthlib.sign_request(req, hawk_id, hawk_key)
        r = requests.session().send(req)
        r.raise_for_status()
        print(r)
    finally:
        s.destroy_session()
コード例 #6
0
def _create_spreadsheet(name, title, path, settings):
    """
    Create Google spreadsheet.
    """
    if not settings.client_secrets:
        return None

    create = raw_input("Would you like to create a Google spreadsheet? [Y/n] ")

    if create and not create.lower() == "y":
        return puts("Not creating spreadsheet.")

    email_message = (
        "What Google account(s) should have access to this "
        "this spreadsheet? (Use a full email address, such as "
        "[email protected]. Separate multiple addresses with commas.)")

    if settings.config.get("google_account"):
        emails = raw_input("\n{0}(Default: {1}) ".format(
            email_message, settings.config.get("google_account")))
        if not emails:
            emails = settings.config.get("google_account")
    else:
        emails = None
        while not emails:
            emails = raw_input(email_message)

    try:
        media_body = _MediaFileUpload(os.path.join(
            path, '_blueprint/_spreadsheet.xlsx'),
                                      mimetype='application/vnd.ms-excel')
    except IOError:
        show_error("_blueprint/_spreadsheet.xlsx doesn't exist!")
        return None

    service = get_drive_api()
    body = {
        'title': '{0} (Tarbell)'.format(title),
        'description': '{0} ({1})'.format(title, name),
        'mimeType': 'application/vnd.ms-excel',
    }
    try:
        newfile = service.files()\
            .insert(body=body, media_body=media_body, convert=True).execute()
        for email in emails.split(","):
            _add_user_to_file(newfile['id'], service, user_email=email.strip())
        puts("\n{0!s}! View the spreadsheet at {1!s}".format(
            colored.green("Success"),
            colored.yellow(
                "https://docs.google.com/spreadsheet/ccc?key={0}".format(
                    newfile['id']))))
        return newfile['id']
    except errors.HttpError as error:
        show_error('An error occurred creating spreadsheet: {0}'.format(error))
        return None
コード例 #7
0
ファイル: cli.py プロジェクト: eyeseast/tarbell
def _create_spreadsheet(name, title, path, settings):
    """
    Create Google spreadsheet.
    """
    if not settings.client_secrets:
        return None

    create = raw_input("Would you like to create a Google spreadsheet? [Y/n] ")

    if create and not create.lower() == "y":
        return puts("Not creating spreadsheet.")

    email_message = (
        "What Google account(s) should have access to this "
        "this spreadsheet? (Use a full email address, such as "
        "[email protected]. Separate multiple addresses with commas.)")

    if settings.config.get("google_account"):
        emails = raw_input("\n{0}(Default: {1}) ".format(email_message,
                                             settings.config.get("google_account")
                                            ))
        if not emails:
            emails = settings.config.get("google_account")
    else:
        emails = None
        while not emails:
            emails = raw_input(email_message)

    try:
        media_body = _MediaFileUpload(os.path.join(path, '_blueprint/_spreadsheet.xlsx'),
                                      mimetype='application/vnd.ms-excel')
    except IOError:
        show_error("_blueprint/_spreadsheet.xlsx doesn't exist!")
        return None

    service = get_drive_api()
    body = {
        'title': '{0} (Tarbell)'.format(title),
        'description': '{0} ({1})'.format(title, name),
        'mimeType': 'application/vnd.ms-excel',
    }
    try:
        newfile = service.files()\
            .insert(body=body, media_body=media_body, convert=True).execute()
        for email in emails.split(","):
            _add_user_to_file(newfile['id'], service, user_email=email.strip())
        puts("\n{0!s}! View the spreadsheet at {1!s}".format(
            colored.green("Success"),
            colored.yellow("https://docs.google.com/spreadsheet/ccc?key={0}"
                           .format(newfile['id']))
            ))
        return newfile['id']
    except errors.HttpError as error:
        show_error('An error occurred creating spreadsheet: {0}'.format(error))
        return None
コード例 #8
0
def deauth_client():
	scan()
	id_red = raw_input('Select id: ')
	red=redes[int(id_red)]
	ap_mac=red.get("mac")
	essid=red.get("ssid")
	channel=red.get("canal")
	client_mac = raw_input("Client MAC:")
	setMonitorMode()
	os.system("sudo iwconfig "+interfaz+" channel "+channel)
	os.system("sudo aireplay-ng -0 0 -a "+ap_mac+" -c "+client_mac+" -e \""+essid+"\" "+interfaz)
コード例 #9
0
ファイル: asklet_play.py プロジェクト: chrisspen/asklet
 def handle(self, *args, **options):
     if options['seed']:
         random.seed(int(options['seed']))
     
     verbose = options['verbose']
     
     ranker = options['ranker']
     if ranker:
         settings.ASKLET_RANKER = ranker
     
     domain = self.domain = models.Domain.objects.get(slug=options['domain'])
     
     user = self.user = ShellUser.load(clear=options['clear_session'])
     print('User ID:',user.id)
     session = self.session = domain.get_session(user.id)
     print('Session:',session.id)
     while 1:
         print('-'*80)
         qi = session.answers.all().count() + 1
         if session.answers.all().count() >= domain.max_questions:
             if not session.target:
                 self.admit_defeat()
                 return
         else:
             if qi == 1:
                 raw_input('Think of something and I will try to guess it. Press enter when ready.')
             q = session.get_next_question(verbose=verbose)
             if q is None:
                 self.admit_defeat()
                 return
             elif isinstance(q, models.Question):
                 print('Question %i:' % qi)
                 answer = user.ask(q.slug)
                 session.add_answer(
                     question=q,
                     answer=answer)
             elif isinstance(q, models.Target):
                 print('Question %i:' % qi)
                 correct = user.is_it(target=q.slug)
                 
                 models.Answer.objects.create(
                     session=session,
                     guess=q,
                     answer=c.YES if correct else c.NO)
                 
                 if correct:
                     print('Horray!')
                     session.target = q
                     session.winner = True
                     session.save()
                     return
                 else:
                     print('Aw shucks!')
コード例 #10
0
def _confirm(files, image_collection, labels):
	print("Are you sure you want to donate these %d images?\n" %(len(files)))

	if image_collection is not None:
		print("##############################################################")
		print("###################### Image Collection ######################")
		print("##############################################################\n\n")
		print(image_collection)

	print("##############################################################")
	print("########################### Labels ###########################")
	print("##############################################################\n\n")
	for elem in labels:
		print("Label: %s\tannotatable: %d" %(elem["label"], elem["annotatable"]))

	print("\n\n##############################################################")
	print("########################### Images ###########################")
	print("##############################################################\n\n")
	for file in files:
		print(path + os.path.sep + file)

	print("\n")
	line = raw_input("Are you sure? [yes/no]\n")
	if line == "yes":
		return True
	return False
コード例 #11
0
ファイル: cli.py プロジェクト: eyeseast/tarbell
def _get_path(name, settings, mkdir=True):
    """
    Generate a project path.
    """
    default_projects_path = settings.config.get("projects_path")
    path = None

    if default_projects_path:
        path = raw_input("\nWhere would you like to create this project? [{0}/{1}] ".format(default_projects_path, name))
        if not path:
            path = os.path.join(default_projects_path, name)
    else:
        while not path:
            path = raw_input("\nWhere would you like to create this project? (e.g. ~/tarbell/) ")

    return os.path.expanduser(path)
コード例 #12
0
def _install_requirements(path):
    """
    Install a blueprint's requirements.txt
    """
    locations = [
        os.path.join(path, "_blueprint"),
        os.path.join(path, "_base"), path
    ]
    success = True

    for location in locations:
        try:
            with open(os.path.join(location, "requirements.txt")):
                puts("\nRequirements file found at {0}".format(
                    os.path.join(location, "requirements.txt")))
                install_reqs = raw_input(
                    "Install requirements now with pip install -r requirements.txt? [Y/n] "
                )
                if not install_reqs or install_reqs.lower() == 'y':
                    pip = sh.pip.bake(_cwd=location)
                    puts("\nInstalling requirements...")
                    puts(pip("install", "-r", "requirements.txt"))
                else:
                    success = False
                    puts(
                        "Not installing requirements. This may break everything! Vaya con dios."
                    )
        except IOError:
            pass

    return success
コード例 #13
0
ファイル: auth.py プロジェクト: gsdu8g9/vk-requests
    def require_phone_number(self, html, session):
        logger.info(
            'Auth requires phone number. You do login from unusual place')

        # Raises VkPageWarningsError in case of warnings
        # NOTE: we check only 'security_check' case on warnings for now
        # in future it might be propagated to other cases as well
        check_html_warnings(html=html)

        # Determine form action url
        action_url = parse_form_action_url(html)

        # Get masked phone from html to make things more clear
        phone_prefix, phone_suffix = parse_masked_phone_number(html)

        if self._phone_number:
            code = self._phone_number[len(phone_prefix):-len(phone_suffix)]
        else:
            prompt = 'Enter missing digits of your phone number (%s****%s): '\
                        % (phone_prefix, phone_suffix)
            code = raw_input(prompt)

        params = parse_url_query_params(action_url, fragment=False)
        auth_data = {
            'code': code,
            'act': 'security_check',
            'hash': params['hash']
        }
        response = session.post(url=self.LOGIN_URL + action_url,
                                data=auth_data)
        logger.debug('require_phone_number resp: %s', response.text)
コード例 #14
0
ファイル: auth.py プロジェクト: gsdu8g9/vk-requests
    def get_captcha_key(captcha_image_url):
        """Read CAPTCHA key from user input
        """

        print('Open CAPTCHA image url: ', captcha_image_url)
        captcha_key = raw_input('Enter CAPTCHA key: ')
        return captcha_key
コード例 #15
0
ファイル: duplicate.py プロジェクト: wangvei/papers
def _ask_pick_loop(entries, extra=[], select=False):

    entry_choices = [str(i + 1) for i in range(len(entries))]
    if select:
        select_choices = ['-' + c for c in entry_choices]
    else:
        select_choices = []
    choices = entry_choices + select_choices + extra

    def _process_choice(i):
        i = i.strip()
        if i in entry_choices:
            return entries[int(i) - 1]
        elif i in select_choices:
            return [e for e in entries if e != entries[int(i) - 1]]
        elif select and len(i.lstrip('-').split()) > 1:
            if i.startswith('-'):
                deselect = [_process_choice(ii) for ii in i[1:].split()]
                return [e for e in entries if e not in deselect]
            else:
                return [_process_choice(ii) for ii in i.split()]
        elif i in choices:
            return i
        else:
            raise ValueError(i)

    while True:
        print('choices: ' + ', '.join(choices))
        i = raw_input('>>> ')
        try:
            return _process_choice(i)
        except:
            continue
コード例 #16
0
ファイル: situs_pdb2vol__batch.py プロジェクト: xut006/aitom
def display(path):
    import pickle
    with open(path) as f:
        m = pickle.load(f)

    import matplotlib.pyplot
    import aitom.image.vol.util as VU
    for pdb_id in m:
        for voxel_size in m[pdb_id]:
            for reolution in m[pdb_id][voxel_size]:
                print('pdb_id', pdb_id, 'voxel_size', voxel_size, 'reolution',
                      reolution)
                VU.dsp_cub(m[pdb_id][voxel_size][reolution]['map'])

            raw_input('press enter')
            matplotlib.pyplot.close('all')
コード例 #17
0
ファイル: command.py プロジェクト: bmarcote/jiveplot
 def __next__(self):
     try:
         l = raw_input(self.prompt + "> ")
         if self.controlc:
             #rl_done.value = 0
             self.controlc = None
             return None
         return l
     except (EOFError):
         quit = True
         print("\nKTHXBYE!")
     except KeyboardInterrupt:
         # user pressed ctrl-c whilst something was
         # in the buffer. Make the code skip the next line of input.
         if len(readline.get_line_buffer()) > 0:
             #self.controlc = readline.get_line_buffer()
             self.controlc = True
             #print "rlbuf: ",rl_line_buffer.value
             #rl_line_buffer.value = ""
             #print "rl_done = ",rl_done
             #rl_done.value = 1
             #print "rl_done = ",rl_done
             print(
                 "\nYour next line of input might be ignored.\nI have not understood readline's ^C handling good enough to make it work.\nFor the moment just type <enter> and ignore the displayed text."
             )
         return None
     if quit:
         raise StopIteration
コード例 #18
0
ファイル: _utils.py プロジェクト: mnieber/lindyscience
def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == "":
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")
コード例 #19
0
def move(f1, f2, copy=False, interactive=False, default="don't replace"):
    dirname = os.path.dirname(f2)
    if dirname and not os.path.exists(dirname):
        logger.info('create directory: ' + dirname)
        os.makedirs(dirname)
    if f1 == f2:
        logger.info('dest is identical to src: ' + f1)
        return
    if os.path.exists(f2):
        if interactive:
            ans = raw_input('dest file already exists: ' + f2 +
                            '. Replace? (y/n) ')
        else:
            if default is "don't replace":
                ans = 'n'
            else:
                ans = 'y'
        if ans != 'y':
            return

    if copy:
        cmd = u'cp {} {}'.format(f1, f2)
        logger.info(cmd)
        if not DRYRUN:
            shutil.copy(f1, f2)
    else:
        cmd = u'mv {} {}'.format(f1, f2)
        logger.info(cmd)
        if not DRYRUN:
            shutil.move(f1, f2)
コード例 #20
0
ファイル: auth.py プロジェクト: Strain88/vk-requests
    def require_phone_number(self, html, session):
        logger.info(
            'Auth requires phone number. You do login from unusual place')

        # Raises VkPageWarningsError in case of warnings
        # NOTE: we check only 'security_check' case on warnings for now
        # in future it might be propagated to other cases as well
        check_html_warnings(html=html)

        # Determine form action url
        action_url = parse_form_action_url(html)

        # Get masked phone from html to make things more clear
        phone_prefix, phone_suffix = parse_masked_phone_number(html)

        if self._phone_number:
            code = self._phone_number[len(phone_prefix):-len(phone_suffix)]
        else:
            prompt = 'Enter missing digits of your phone number (%s****%s): '\
                        % (phone_prefix, phone_suffix)
            code = raw_input(prompt)

        params = parse_url_query_params(action_url, fragment=False)
        auth_data = {
            'code': code,
            'act': 'security_check',
            'hash': params['hash']}
        response = session.post(
            url=self.LOGIN_URL + action_url, data=auth_data)
        logger.debug('require_phone_number resp: %s', response.text)
コード例 #21
0
ファイル: auth.py プロジェクト: Strain88/vk-requests
    def get_captcha_key(captcha_image_url):
        """Read CAPTCHA key from user input
        """

        print('Open CAPTCHA image url: ', captcha_image_url)
        captcha_key = raw_input('Enter CAPTCHA key: ')
        return captcha_key
コード例 #22
0
ファイル: duplicate.py プロジェクト: wangvei/papers
def conflict_resolution_on_insert(old, new, mode='i'):
    """conflict resolution with two entries
    """
    if mode == 'i':
        print(entry_diff(old, new))
        print(bcolors.OKBLUE + 'what to do? ')
        print('''
(u)pdate missing (discard conflicting fields in new entry)
(U)pdate other (overwrite conflicting fields in old entry)
(o)verwrite
(e)dit diff
(E)dit split (not a duplicate)
(s)kip
(a)ppend anyway
(r)aise'''.strip().replace('(u)', '(' + _colordiffline('u', '+') +
                           ')')  # green lines will be added 
              .replace('(o)', '(' + _colordiffline('o', '-') + ')') +
              bcolors.ENDC)
        # .replace('(s)','('+_colordiffline('s','-')+')'))
        choices = list('uUoeEsar')
        ans = None
        while ans not in choices:
            print('choices: ' + ', '.join(choices))
            ans = raw_input('>>> ')
        mode = ans

    # overwrite?
    if mode == 'o':
        resolved = [new]

    elif mode == 'a':
        resolved = [old, new]

    elif mode == 'u':
        logger.info('update missing fields')
        new.update(old)
        old.update(new)
        resolved = [old]

    elif mode == 'U':
        logger.info('update with other')
        old.update(new)
        resolved = [old]

    # skip
    elif mode == 's':
        resolved = [old]

    # edit
    elif mode == 'e':
        resolved = edit_entries([old, new], diff=True)

    elif mode == 'E':
        resolved = edit_entries([old, new])

    else:
        raise ValueError('conflicting entries')

    return resolved
コード例 #23
0
 def confirm(self):
     if not self.has_diff():
         return 'none'
     res = raw_input('({0}) Are you sure you want to make this '
                     'change (y/N)? '.format(self.name))
     if res.lower() in ['y', 'yes']:
         return 'accepted'
     return 'declined'
コード例 #24
0
ファイル: migrations.py プロジェクト: efremovd/conan
    def migrate_to_revisions_layout(self):
        # .conan/data/lib/1.0/user/channel/export/*
        # .conan/data/lib/1.0/user/channel/0/export/*

        # .conan/data/lib/1.0/user/channel/package/*
        # .conan/data/lib/1.0/user/channel/0/package/*

        # .conan/data/lib/1.0/user/channel/package/XXX/*
        # .conan/data/lib/1.0/user/channel/0/package/XXX/0/*
        from six.moves import input as raw_input
        print("**********************************************")
        print("*                                            *")
        print("*       STORAGE MIGRATION NEEDED!            *")
        print("*                                            *")
        print("**********************************************")
        a = raw_input("A migration of your storage is needed, please backup first the storage "
                      "directory before continue: \n\n'%s' \n\nContinue? Y/N " % self.store_path)
        print("**********************************************")

        if a.lower() != "y":
            print("Exiting...")
            exit(1)

        print("**********************************************")
        print("*                                            *")
        print("*       MIGRATION IN PROGRESS                *")
        print("*                                            *")
        print("**********************************************")
        subdirs = list_folder_subdirs(basedir=self.store_path, level=4)
        for subdir in subdirs:
            base_dir = os.path.join(self.store_path, subdir)
            for export_or_package in os.listdir(base_dir):
                the_dir = os.path.join(base_dir, export_or_package)
                dest_dir = os.path.join(base_dir, DEFAULT_REVISION_V1)
                mkdir(dest_dir)
                shutil.move(the_dir, dest_dir)
                print("Moving '%s': %s" % (subdir, export_or_package))

            packages_dir = os.path.join(self.store_path, subdir, DEFAULT_REVISION_V1, PACKAGES_FOLDER)

            if not os.path.exists(packages_dir):
                continue
            for pid in os.listdir(packages_dir):
                package_dir = os.path.join(packages_dir, pid)
                mkdir(os.path.join(package_dir, DEFAULT_REVISION_V1))
                print(" - Package '%s'" % pid)
                for item in os.listdir(package_dir):
                    if item == DEFAULT_REVISION_V1:
                        continue
                    origin_path = os.path.join(package_dir, item)
                    dest_path = os.path.join(package_dir, DEFAULT_REVISION_V1, item)
                    mkdir(dest_dir)
                    shutil.move(origin_path, dest_path)
        print("**********************************************")
        print("*                                            *")
        print("*       MIGRATION COMPLETED!                 *")
        print("*                                            *")
        print("**********************************************")
コード例 #25
0
    def init():
        url = raw_input('Your Webdav Address: ')
        path = raw_input('Your Webdav Path: ')
        username = raw_input('Your Webdav Username: '******'Your Webdav Password: '******'w') as f:
            json.dump(
                {
                    'platform': 'webdav',
                    'url': url,
                    'path': path,
                    'username': username,
                    'password': password,
                },
                f,
                indent=4)
コード例 #26
0
    def print_view_prompt(self):
        print(self)

        while True:
            s = raw_input('Press v, enter to open in browser, or enter to close...')
            if s == 'v':
                self.open_in_browser()
            else:
                break
コード例 #27
0
ファイル: cli.py プロジェクト: eyeseast/tarbell
def _get_project_name(args):
    """
    Get project name.
    """
    name = args.get(0)
    puts("")
    while not name:
        name = raw_input("What is the project's short directory name? (e.g. my_project) ")
    return name
 def plot_prediction():

    print('-'*30)
    print('Loading and preprocessing test data...')
    print('-'*30)

    imgs_test = np.load('../input_data/Green_Red_FarRed_Annotated_FISH_Dilation4Conn1Iter_Testing_128by128_normalize.npy')
    imgs_mask_test = np.load('../input_data/Green_Red_FarRed_Annotated_FISH_Dilation4Conn1Iter_Testing_128by128_normalize_Mask.npy')
    imgs_mask_test_predict = np.load('../input_data/Green_Red_FarRed_Annotated_FISH_Dilation4Conn1Iter_Testing_128by128_normalize_dropout_Mask_Pred_cshpaper.npy')

    imgs_test = imgs_test.astype('float32')
    imgs_mask_test = imgs_mask_test.astype('float32')
    imgs_mask_test /= 255.  # scale masks to [0, 1]
	
    print('Shape of input, target and prediction images ', imgs_test.shape, imgs_mask_test.shape, imgs_mask_test_predict.shape)    
    print('Input images min, max before normalization ', np.amin(imgs_test),np.amax(imgs_test))
    print('Target images min, max before normalization ', np.min(imgs_mask_test),np.max(imgs_mask_test))
    print('Prediction images min, max before normalization ', np.min(imgs_mask_test_predict),np.max(imgs_mask_test_predict))
    plt.ion()

    for i in range(0,imgs_test.shape[0]):    
      img = np.squeeze(imgs_test[i,:,:])
      img_amax = np.amax(img)
      img_amin = np.amin(img)
	  
      mask = np.squeeze(imgs_mask_test[i,:,:])
      mask_amax = np.amax(mask)
      mask_amin = np.amin(mask)

      mask_pre = np.squeeze(imgs_mask_test_predict[i,:,:])
      mask_pre_amax = np.amax(mask_pre)
      mask_pre_amin = np.amin(mask_pre)
	  
      fig = plt.figure(1)
      a = fig.add_subplot(1,3,1)
      imgplot = plt.imshow(img)
      imgplot.set_clim(img_amin,img_amax)
      a.set_title('Input : '+str(i))
      plt.colorbar(orientation ='horizontal')

      a = fig.add_subplot(1,3,2)
      imgplot = plt.imshow(mask)
      imgplot.set_clim(mask_amin, mask_amax)
      a.set_title('GroundTruth' + ' ' +str(i))
      plt.colorbar(orientation ='horizontal')

      a = fig.add_subplot(1,3,3)
      imgplot = plt.imshow(mask_pre)
      imgplot.set_clim(mask_pre_amin, mask_pre_amax)
      a.set_title('Prediction : '+str(i))
      plt.colorbar(orientation ='horizontal')

      plt.show()
      _ = raw_input("Press [enter] to continue.")      
      #plt.pause(2)
      plt.draw()
      plt.clf()
コード例 #29
0
    def init():
        access_key = raw_input('Qiniu Access Key: ')
        secert_key = raw_input('Qiniu Secret Key: ')
        bucket_name = raw_input('Qiniu Bucket Name: ')
        domain = raw_input('Qiniu Resource Domain: ')

        cfg = sshr_cfg_path()
        with open(cfg, 'w') as f:
            json.dump(
                {
                    'platform': 'qiniu',
                    'access_key': access_key,
                    'secert_key': secert_key,
                    'bucket_name': bucket_name,
                    'domain': domain
                },
                f,
                indent=4)
コード例 #30
0
 def get_2fa_code(self):
     if self.interactive:
         auth_check_code = raw_input('Auth check code: ')
         return auth_check_code.strip()
     else:
         raise VkAuthError(
             'Auth check code is needed (SMS, Google Authenticator or '
             'one-time password). '
             'Use interactive mode to enter the code manually')
コード例 #31
0
ファイル: main.py プロジェクト: ricardojoserf/pylangame
def chooseMode():
    mode = raw_input(
        "Choose mode: \n 1) All words \n 2) Failed words (first play mode 1) \nHint: Answer 'stop' to choose mode.\n\nElection (1/2):"
    )
    if mode == "1":
        game()
    elif mode == "2":
        failmode()
    else:
        print("Unknown mode")
コード例 #32
0
def help():
    valid = True
    try:
        f = open(helpPath, 'r')
        while (valid):
            Count = 0
            while (Count < 20):
                s = f.readline()
                if (len(s) != 0):
                    print(s[:len(s) - 1])
                    Count = Count + 1
                    if (Count == 20):
                        raw_input('press \"Enter\" for more...')
                else:
                    Count = 100
                    valid = False
        f.close()
    except IOError:
        print("No help file found.")
コード例 #33
0
 def user_input(self, prompt=None):
     """
     A wrapper function for getting user input while keeping track of the amount of time spent
     waiting for it.
     """
     start = arrow.utcnow()
     try:
         if self.default_format and prompt:
             return raw_input(
                 '%(format)s%(prompt)s%(end)s' % {
                     'format': self.default_format,
                     'prompt': prompt,
                     'end': TerminalFormats.ENDC
                 })
         else:
             return raw_input(prompt)
     finally:
         end = arrow.utcnow()
         self._waiting_on_user_delta += end - start
コード例 #34
0
def get_hidden_essid():
	scan()
	id_red = raw_input('Select id: ')
	red=redes[int(id_red)]
	if red is not None:
		ap_mac=red.get("mac")
		channel=red.get("canal")
		find_hidden_essid(interfaz,ap_mac,channel)
	else:
		print( "No funciona")
コード例 #35
0
 def init():
     access_token = raw_input('Dropbox Access Token: ')
     cfg = sshr_cfg_path()
     with open(cfg, 'w') as f:
         json.dump({
             'platform': 'dropbox',
             'access_token': access_token
         },
                   f,
                   indent=4)
コード例 #36
0
ファイル: cli.py プロジェクト: eyeseast/tarbell
def _get_project_title():
    """
    Get project title.
    """
    title = None
    puts("")
    while not title:
        title = raw_input("What is the project's full title? (e.g. My awesome project) ")

    return title
コード例 #37
0
def _get_project_name(args):
    """
    Get project name.
    """
    name = args.get(0)
    puts("")
    while not name:
        name = raw_input(
            "What is the project's short directory name? (e.g. my_project) ")
    return name
コード例 #38
0
ファイル: quickstart.py プロジェクト: spacetelescope/asv
    def run(cls, dest=".", top_level=None):
        log.info("Setting up new Airspeed Velocity benchmark suite.")

        if top_level is None:
            log.flush()
            color_print("")
            color_print("Which of the following template layouts to use:")
            color_print("(1) benchmark suite at the top level of the project repository")
            color_print("(2) benchmark suite in a separate repository")
            color_print("")
            while True:
                answer = raw_input("Layout to use? [1/2] ")
                if answer.lower()[:1] == "1":
                    top_level = True
                    break
                elif answer.lower()[:1] == "2":
                    top_level = False
                    break
            color_print("")

        template_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), '..', 'template')
        for entry in os.listdir(template_path):
            path = os.path.join(template_path, entry)
            dest_path = os.path.join(dest, entry)
            if os.path.exists(dest_path):
                log.info("Template content already exists.")
                log.info("Edit asv.conf.json to continue.")
                return 1

        for entry in os.listdir(template_path):
            path = os.path.join(template_path, entry)
            dest_path = os.path.join(dest, entry)
            if os.path.isdir(path):
                shutil.copytree(path, os.path.join(dest, entry))
            elif os.path.isfile(path):
                shutil.copyfile(path, os.path.join(dest, entry))

        if top_level:
            conf_file = os.path.join(dest, 'asv.conf.json')

            with open(conf_file, 'r') as f:
                conf = f.read()

            reps = [('"repo": "",', '"repo": ".",'),
                    ('// "env_dir": "env",', '"env_dir": ".asv/env",'),
                    ('// "results_dir": "results",', '"results_dir": ".asv/results",'),
                    ('// "html_dir": "html",', '"html_dir": ".asv/html",')]
            for src, dst in reps:
                conf = conf.replace(src, dst)

            with open(conf_file, 'w') as f:
                f.write(conf)

        log.info("Edit asv.conf.json to get started.")
コード例 #39
0
def create_repo(site, git):
    create = raw_input("Want to create a Github repo for this project [Y/n]? ")
    if create and not create.lower() == "y":
        return puts("Not creating Github repo...")

    name = site.path.split('/')[-1]
    user = raw_input("What is your Github username? ")
    password = getpass.getpass("What is your Github password? ")
    headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
    data = {'name': name, 'has_issues': True, 'has_wiki': True}
    resp = requests.post('https://api.github.com/user/repos', auth=(user, password), headers=headers, data=json.dumps(data))
    puts("Created {0!s}".format(colored.green("https://github.com/{0}/{1}".format(user, name))))
    clone_url = resp.json().get("clone_url")
    puts(git.remote.add("origin", "[email protected]:{0}/{1}.git".format(user,name)))
    puts(git.push("origin", "master"))

    for title, description in ISSUES:
        puts("Creating {0!s}".format(colored.yellow(title)))
        data = {'title': title, 'body': description}
        resp = requests.post('https://api.github.com/repos/{0}/{1}/issues'.format(user, name), auth=(user, password), headers=headers, data=json.dumps(data))
コード例 #40
0
ファイル: io.py プロジェクト: RitwikGupta/rabix
 def _metadata_prompt(self, input, metadata=None):
     cont = ''
     if metadata is None:
         metadata = {}
         cont = 'n'
         # cont = raw_input('Metadata for file %s not found. '
         #                  'Do you want to set it manually? [Y/n] '
         #                  % input)
         # print(cont.__class__)
         # cont = cont.lower().strip()
     if cont == 'y' or cont == '':
         key = raw_input("Key: ")
         if key == '':
             return metadata
         value = raw_input("Value: ")
         if value == '':
             return metadata
         metadata[key] = value
         return self._metadata_prompt(input, metadata)
     return metadata
コード例 #41
0
    def delete(self, **params):
        printable_name = class_to_api_name(
            self.class_name(), pluralize=False).replace('_', ' ')
        if not params.pop('force', False):
            res = raw_input('Are you sure you want to delete this %s? '
                            '[y/N] ' % printable_name)
            if res.strip().lower() != 'y':
                print('Not performing deletion.')
                return

        response = self.request('delete', self.instance_url(), params=params)
        return convert_to_solve_object(response, client=self._client)
コード例 #42
0
ファイル: utils.py プロジェクト: chrisspen/asklet
 def is_it(self, target):
     """
     Confirms or denies whether or not the given target is the one we chose.
     """
     while 1:
         print('%s?' % target)
         yn = raw_input('y/n: ').strip().lower()
         if yn.startswith('y'):
             return True
         elif yn.startswith('n'):
             return False
         print('Sorry, but that response is invalid.')
コード例 #43
0
ファイル: utils.py プロジェクト: chrisspen/asklet
 def ask(self, question_slug):
     """
     Returns the user's belief in the question's relation
     to our secret target.
     """
     while 1:
         print('%s? ' % question_slug)
         weight = raw_input('Enter integer weight between %s and %s: ' % (c.YES, c.NO))
         if is_int(weight):
             weight = int(weight)
             if c.YES >= weight >= c.NO:
                 return weight
         print('Sorry, but that weight is invalid.')
コード例 #44
0
ファイル: configure.py プロジェクト: eyeseast/tarbell
def _setup_tarbell_project_path(settings, path, prompt=True):
    """
    Prompt user to set up project path.
    """
    default_path = os.path.expanduser(os.path.join("~", "tarbell"))
    projects_path = raw_input("\nWhat is your Tarbell projects path? [Default: {0}, 'none' to skip] ".format(default_path))
    if projects_path == "":
        projects_path = default_path
    if projects_path.lower() == 'none':
        puts("\n- Not creating projects directory.")
        return {}

    if os.path.isdir(projects_path):
        puts("\nDirectory exists!")
    else:
        puts("\nDirectory does not exist.")
        make = raw_input("\nWould you like to create it? [Y/n] ")
        if make.lower() == "y" or not make:
            os.makedirs(projects_path)
    puts("\nProjects path is {0}".format(projects_path))
    puts("\n- Done setting up projects path.")
    return {"projects_path": projects_path}
コード例 #45
0
ファイル: cli.py プロジェクト: eyeseast/tarbell
def tarbell_generate(command, args, skip_args=False, extra_context=None, quiet=False):
    """
    Generate static files.
    """

    output_root = None
    with ensure_settings(command, args) as settings, ensure_project(command, args) as site:

        if not skip_args:
            output_root = list_get(args, 0, False)

            if output_root:
                is_folder = os.path.exists(output_root)
            else:
                puts("\nYou must specify an output directory (e.g. `{0}`)".format(
                    colored.cyan("tarbell generate _out")
                ))
                sys.exit()

        if quiet:
            site.quiet = True
        
        if not output_root:
            output_root = tempfile.mkdtemp(prefix="{0}-".format(site.project.__name__))
            is_folder = False

        if args.contains('--context'):
            site.project.CONTEXT_SOURCE_FILE = args.value_after('--context')

        if args.contains('--overwrite'):
            is_folder = False

        #check to see if the folder we're trying to create already exists
        if is_folder:
            output_file = raw_input(("\nA folder named {0} already exists! Do you want to delete it? (selecting 'N' will quit) [y/N] ").format(
                output_root
            ))
            if output_file and output_file.lower() == "y":
                puts(("\nDeleting {0}...\n").format(
                    colored.cyan(output_root)
                ))
                _delete_dir(output_root)
            else:
                puts("\nNot overwriting. See ya!")
                sys.exit()

        site.generate_static_site(output_root, extra_context)
        if not quiet:
            puts("\nCreated site in {0}".format(colored.cyan(output_root)))

        return output_root
コード例 #46
0
ファイル: utils.py プロジェクト: chrisspen/asklet
 def think_of_something(self):
     """
     Randomly choices a target for the system to guess.
     """
     print('Think of something.')
     while 1:
         target = raw_input('Enter it here: ')
         target = sterialize(target)
         if target:
             break
         print('Sorry, but that string is invalid.')
         print('Please enter a simple non-empty string with no punctuation.')
     print('You are thinking of %s.' % target)
     self.target = target
コード例 #47
0
ファイル: auth.py プロジェクト: solvebio/solvebio-python
def _ask_for_credentials():
    """
    Asks the user for their email and password.
    """
    _print_msg('Please enter your SolveBio credentials')
    domain = raw_input('Domain (e.g. <domain>.solvebio.com): ')
    # Check to see if this domain supports password authentication
    try:
        account = client.request('get', '/p/accounts/{}'.format(domain))
        auth = account['authentication']
    except:
        raise SolveError('Invalid domain: {}'.format(domain))

    # Account must support password-based login
    if auth.get('login') or auth.get('SAML', {}).get('simple_login'):
        email = raw_input('Email: ')
        password = getpass.getpass('Password (typing will be hidden): ')
        return (domain, email, password)
    else:
        _print_msg(
            'Your domain uses Single Sign-On (SSO). '
            'Please visit https://{}.solvebio.com/settings/security '
            'for instructions on how to log in.'.format(domain))
        sys.exit(1)
コード例 #48
0
ファイル: cli.py プロジェクト: eyeseast/tarbell
def _get_template(settings):
    """
    Prompt user to pick template from a list.
    """
    puts("\nPick a template\n")
    template = None
    while not template:
        _list_templates(settings)
        index = raw_input("\nWhich template would you like to use? [1] ")
        if not index:
            index = "1"
        try:
            index = int(index) - 1
            return settings.config["project_templates"][index]
        except:
            puts("\"{0}\" isn't a valid option!".format(colored.red("{0}".format(index))))
            pass
コード例 #49
0
ファイル: quickstart.py プロジェクト: andyfaff/asv
    def run(cls, dest=".", top_level=None):
        if top_level is None:
            while True:
                answer = raw_input("Is this the top level of your project repository? [y/n] ")
                if answer.lower()[:1] == "y":
                    top_level = True
                    break
                elif answer.lower()[:1] == "n":
                    top_level = False
                    break

        template_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), '..', 'template')
        for entry in os.listdir(template_path):
            path = os.path.join(template_path, entry)
            dest_path = os.path.join(dest, entry)
            if os.path.exists(dest_path):
                log.info("Template content already exists.")
                log.info("Edit asv.conf.json to continue.")
                return 1

        for entry in os.listdir(template_path):
            path = os.path.join(template_path, entry)
            dest_path = os.path.join(dest, entry)
            if os.path.isdir(path):
                shutil.copytree(path, os.path.join(dest, entry))
            elif os.path.isfile(path):
                shutil.copyfile(path, os.path.join(dest, entry))

        if top_level:
            conf_file = os.path.join(dest, 'asv.conf.json')

            with open(conf_file, 'r') as f:
                conf = f.read()

            reps = [('"repo": "",', '"repo": ".",'),
                    ('// "env_dir": "env",', '"env_dir": ".asv/env",'),
                    ('// "results_dir": "results",', '"results_dir": ".asv/results",'),
                    ('// "html_dir": "html",', '"html_dir": ".asv/html",')]
            for src, dst in reps:
                conf = conf.replace(src, dst)

            with open(conf_file, 'w') as f:
                f.write(conf)

        log.info("Edit asv.conf.json to get started.")
コード例 #50
0
ファイル: configure.py プロジェクト: eyeseast/tarbell
def tarbell_configure(command, args):
    """
    Tarbell configuration routine.
    """
    puts("Configuring Tarbell. Press ctrl-c to bail out!")

    # Check if there's settings configured
    settings = Settings()
    path = settings.path

    prompt = True
    if len(args):
        prompt = False

    config = _get_or_create_config(path)

    if prompt or "drive" in args:
        config.update(_setup_google_spreadsheets(config, path, prompt))
    if prompt or "s3" in args:
        config.update(_setup_s3(config, path, prompt))
    if prompt or "path" in args:
        config.update(_setup_tarbell_project_path(config, path, prompt))
    if prompt or "templates" in args:
        if "project_templates" in config:
            override_templates = raw_input("\nFound Base Template config. Would you like to override them? [Default: No, 'none' to skip]")
            if override_templates and override_templates != "No" and  override_templates != "no" and override_templates != "N" and override_templates != "n":
                config.update(_setup_default_templates(config, path, prompt))
            else:
                puts("\nPreserving Base Template config...")
        else:
            config.update(_setup_default_templates(config, path, prompt))

    settings.config = config

    with open(path, 'w') as f:
        puts("\nWriting {0}".format(colored.green(path)))
        settings.save()

    if all:
        puts("\n- Done configuring Tarbell. Type `{0}` for help.\n"
             .format(colored.green("tarbell")))

    return settings
コード例 #51
0
ファイル: asklet_play.py プロジェクト: chrisspen/asklet
 def admit_defeat(self):
     while 1:
         #target = sterialize(raw_input('I give up, what were you thinking? '))
         target_slug = raw_input('I give up, what were you thinking? ').strip()
         if target_slug:
             target, _ = models.Target.objects.get_or_create(domain=self.domain, slug=target_slug)
             self.session.target = target
             self.session.winner = False
             self.session.save()
             print("Ah, I see. I'll remember that next time.")
             things = self.user.describe(n=3)
             for question, weight in things:
                 question, _ = models.Question.objects.get_or_create(domain=self.domain, slug=sterialize(question))
                 weightObj, _ = models.TargetQuestionWeight.objects.get_or_create(target=target, question=question)
                 weightObj.weight += weight
                 weightObj.save()
             print("Thanks. Let's play again sometime.")
             return
         else:
             print('Sorry, but this is not a valid response.')
             continue
コード例 #52
0
ファイル: utils.py プロジェクト: chrisspen/asklet
 def describe(self, n=3, exclude=set()):
     """
     Returns 3 random attributes of our target.
     """
     things = []
     assert n > 0
     print('Please describe %i things about this.' % n)
     while len(things) < n:
         response = raw_input('<thing> <weight>').strip()
         if not response:
             break
         #response = sterialize(response)
         parts = response.split(' ')
         if parts:
             weight = parts[-1]
             if is_int(weight):
                 weight = int(weight)
                 slug = '_'.join(parts[:-1])
                 things.append((slug, weight))
         print('Sorry, but that is an invalid input.')
     return things
コード例 #53
0
ファイル: io.py プロジェクト: RitwikGupta/rabix
    def _prompt_files(self, input, prompt=None, secFiles=None):

        cont = 'n'
        # cont = ''
        # if prompt is None:
        #     prompt = []
        #     cont = raw_input('Do you want to include some additional '
        #                      'files for file %s %s? [y/N] '
        #                      % (input, str(secFiles))).lower().strip()
        if cont == 'y':
            ext = raw_input('Extension: ')
            if ext == '':
                return prompt
            elif ext in secFiles:
                log.error('Extension %s already included' % ext)
            else:
                prompt.append(ext)
                secFiles.append(ext)
            return self._prompt_files(input, prompt, secFiles=secFiles)
        else:
            return prompt
コード例 #54
0
ファイル: io.py プロジェクト: RitwikGupta/rabix
    def _get_secondary_files(self, secondaryFiles, input, autodetect=True,
                             prompt=True):

        def secondary_files_autodetect(path):
            log.info('Searching for additional files for file: %s', path)
            return [fn for fn in glob.glob(path + '.*')
                    if not (basename(fn).endswith('.meta') or
                            basename(fn).endswith('.rbx.json'))
                    ]

        secFiles = []
        if secondaryFiles:
            for n, sf in enumerate(secondaryFiles):
                path = sec_files_naming_conv(input.path, sf)
                log.info('Downloading: %s', path)
                secFiles.append(File(self._download(URL(path), metasearch=False)))
        if autodetect:
            if not secondaryFiles:
                secondaryFiles = []
            autodetected = secondary_files_autodetect(input.path)
            ad = []
            names = [basename(f) for f in secondaryFiles]
            for sf in autodetected:
                sf = sf.replace(input.path, '')
                if sf not in names:
                    ad.append(six.text_type(sf))
            if ad:
                cont = raw_input('Do you want to include autodetected '
                                 'additional files for file %s %s? [Y/n] '
                                 % (input, six.text_type(ad))).lower().strip()
                if cont == 'y' or cont == '':
                    log.info("Additional files %s included" % six.text_type(ad))
                    secFiles.extend(self._get_secondary_files(
                        ad, input, autodetect=False, prompt=False))
        if prompt:
            prompt = self._prompt_files(input, secFiles=secondaryFiles)
            secFiles.extend(self._get_secondary_files(
                prompt, input, autodetect=False, prompt=False))
        return secFiles
コード例 #55
0
ファイル: cli.py プロジェクト: eyeseast/tarbell
def _install_requirements(path):
    """
    Install a blueprint's requirements.txt
    """
    locations = [os.path.join(path, "_blueprint"), os.path.join(path, "_base"), path]
    success = True

    for location in locations:
        try:
            with open(os.path.join(location, "requirements.txt")):
                puts("\nRequirements file found at {0}".format(os.path.join(location, "requirements.txt")))
                install_reqs = raw_input("Install requirements now with pip install -r requirements.txt? [Y/n] ")
                if not install_reqs or install_reqs.lower() == 'y':
                    pip = sh.pip.bake(_cwd=location)
                    puts("\nInstalling requirements...")
                    puts(pip("install", "-r", "requirements.txt"))
                else:
                    success = False
                    puts("Not installing requirements. This may break everything! Vaya con dios.")
        except IOError:
            pass

    return success
コード例 #56
0
ファイル: auth.py プロジェクト: Strain88/vk-requests
 def get_app_id():
     user_login = raw_input('VK app id: ')
     return int(user_login.strip())
コード例 #57
0
ファイル: auth.py プロジェクト: Strain88/vk-requests
 def get_sms_code(self):
     """
     Read Auth code from shell
     """
     auth_check_code = raw_input('Auth check code: ')
     return auth_check_code.strip()
コード例 #58
0
ファイル: auth.py プロジェクト: Strain88/vk-requests
 def get_user_login():
     user_login = raw_input('VK user login: ')
     return user_login.strip()
コード例 #59
0
ファイル: userio.py プロジェクト: lasote/conan
 def get_username(self, remote_name):
     """Overridable for testing purpose"""
     return raw_input()
コード例 #60
0
ファイル: auth.py プロジェクト: Strain88/vk-requests
 def get_access_token(self):
     logger.debug('InteractiveMixin.get_access_token()')
     access_token = super(InteractiveAuthAPI, self).get_access_token()
     if not access_token:
         access_token = raw_input('VK API access token: ')
     return access_token