Create a new config resource in the slicing service and upload the path contents to it
5413
def upload(self, path, engine, description=None):
        """"""

        if description is None:
            head, tail = ntpath.split(path)
            description = tail or ntpath.basename(head)

        url = "http://quickslice.{}/config/raw/".format(self.config.host)

        with open(path) as config_file:
            content = config_file.read()

        payload = {"engine": engine,
                   "description": description,
                   "content": content}

        post_resp = requests.post(url, json=payload, cookies={"session": self.session})
        if not post_resp.ok:
            raise errors.ResourceError("config upload to slicing service failed")

        self.description = description

        self.location = post_resp.headers["Location"]
1099866
def create(file_path):
    """"""
    if os.path.exists(file_path):
        raise IOError("There is already a configuration file at %s" %
                      file_path)
    with open(file_path, 'w') as f:
        config = configparser.ConfigParser()
        config.add_section('misc')
        config.set('misc', 'config-version', '1.0')
        default_nb_name = os.path.split(os.path.dirname(file_path))[1]
        config.set('misc', 'nb-name', default_nb_name)
        config.add_section('root')
        config.set('root', 'path', '.')
        config.add_section('models')
        config.set('models', 'module', 'models')
        config.add_section('tests')
        config.set('tests', 'module', 'tests')
        config.add_section('suites')
        config.set('suites', 'module', 'suites')
        config.write(f)
1025818
def _copy_config_template(name, title, template, path, key, settings):
        
        puts("\nCopying configuration file")
        context = settings.config
        context.update({
            "default_context": {
                "name": name,
                "title": title,
            },
            "name": name,
            "title": title,
            "template_repo_url": template.get('url'),
            "key": key,
        })

        # @TODO refactor this a bit
        if not key:
            spreadsheet_path = os.path.join(path, '_blueprint/', '_spreadsheet.xlsx')
            try:
                with open(spreadsheet_path, "rb") as f:
                    puts("Copying _blueprint/_spreadsheet.xlsx to tarbell_config.py's DEFAULT_CONTEXT")
                    data = process_xlsx(f.read())
                    if 'values' in data:
                        data = copy_global_values(data)
                    context["default_context"].update(data)
            except IOError:
                pass

        s3_buckets = settings.config.get("s3_buckets")
        if s3_buckets:
            puts("")
            for bucket, bucket_conf in s3_buckets.items():
                puts("Configuring {0!s} bucket at {1!s}\n".format(
                    colored.green(bucket),
                    colored.yellow("{0}/{1}".format(bucket_conf['uri'], name))
                ))

        puts("\n- Creating {0!s} project configuration file".format(
            colored.cyan("tarbell_config.py")
        ))
        template_dir = os.path.dirname(pkg_resources.resource_filename("tarbell", "templates/tarbell_config.py.template"))
        loader = jinja2.FileSystemLoader(template_dir)
        env = jinja2.Environment(loader=loader)
        env.filters["pprint_lines"] = pprint_lines  # For dumping context
        content = env.get_template('tarbell_config.py.template').render(context)
        codecs.open(os.path.join(path, "tarbell_config.py"), "w", encoding="utf-8").write(content)
        puts("\n- Done copying configuration file")
52142
function loadConfigFile(dist, paths, options, callback) {
        if (options.config) {
            fs.readFile(options.config, {encoding: 'utf8'}, function(err, contents) {
                if (err) {
                    callback(err);
                    return;
                }
                
                var config = ini.parse(contents);

                if (config && config.default) {
                    options.accessKeyId = config.default.access_key;
                    options.secretAccessKey = config.default.secret_key;
                }
                if (!options.secretAccessKey || !options.accessKeyId) {
                    callback("Config file missing access_key or secret_key");
                    return;
                }

                invalidate(dist, paths, options, callback);
            });
        } else {
            invalidate(dist, paths, options, callback);
        }
    }
185469
def from_file(cls, config_path=None, *args, **kwargs):
        

        config_reader = kaptan.Kaptan()

        config = {}

        if config_path:
            if not os.path.exists(config_path):
                raise exc.CihaiException(
                    '{0} does not exist.'.format(os.path.abspath(config_path))
                )
            if not any(
                config_path.endswith(ext) for ext in ('json', 'yml', 'yaml', 'ini')
            ):
                raise exc.CihaiException(
                    '{0} does not have a yaml,yml,json,ini extend.'.format(
                        os.path.abspath(config_path)
                    )
                )
            else:
                custom_config = config_reader.import_config(config_path).get()
                config = merge_dict(config, custom_config)

        return cls(config)
118871
def _setup_fun_config(self, fun_conf):
        '''
        
        '''
        conf = copy.deepcopy(self.config)
        conf['file_client'] = 'local'
        conf['fun'] = ''
        conf['arg'] = []
        conf['kwarg'] = {}
        conf['cache_jobs'] = False
        conf['print_metadata'] = False
        conf.update(fun_conf)
        conf['fun'] = conf['fun'].split(':')[-1]  # Discard typing prefix

        return conf
1026622
def create(path)
      raise ContainerError, "Container already exists." if exists?

      if path.is_a?(Hash)
        args = "-n #{name}"

        if !!path[:config_file]
          unless File.exists?(path[:config_file])
            raise ArgumentError, "File #{path[:config_file]} does not exist."
          end
          args += " -f #{path[:config_file]}"
        end

        if !!path[:template]
          template_dir =  path[:template_dir] || "/usr/lib/lxc/templates"
          template_path = File.join(template_dir,"lxc-#{path[:template]}")
          unless File.exists?(template_path)
            raise ArgumentError, "Template #{path[:template]} does not exist."
          end
          args += " -t #{path[:template]} "
        end

        args += " -B #{path[:backingstore]}" if !!path[:backingstore]
        args += " -- #{path[:template_options].join(" ")}".strip if !!path[:template_options]

        LXC.run("create", args)
        exists?
      else
        unless File.exists?(path)
          raise ArgumentError, "File #{path} does not exist."
        end

        LXC.run("create", "-n", name, "-f", path)
        exists?
      end
    end
532988
def configfile(f):
    

    @click.pass_context
    def new_func(ctx, *args, **kwargs):
        ctx.config = yaml.load(open(ctx.obj["configfile"]))
        return ctx.invoke(f, *args, **kwargs)

    return update_wrapper(new_func, f)
1360798
def create(self, resource):
        
        uri = self.URI + self.RESOURCES_PATH
        return self._client.create(resource=resource, uri=uri)
591265
def put(path, data, options = {})
      uri = build_uri(path, options)

      request = Net::HTTP::Put.new(uri.request_uri)
      set_authorisation_header(request)
      request.set_form_data(data)

      response = https_client(uri).request(request)
    end
637391
def create_config_files(directory):
    
    # Some constant strings
    vpn_gate_url = "http://www.vpngate.net/api/iphone/"

    if not os.path.exists(directory):
        os.makedirs(directory)

    # get csv into memory
    csv_str = ""
    logging.info("Downloading info from VPN Gate API...")
    r = requests.get(vpn_gate_url)
    for line in r.text.split('\n'):
        csv_str += line.encode('utf-8')
        csv_str += "\n"

    # convert csv string to string IO
    f = StringIO.StringIO(csv_str)

    # generate vpn dict
    vpn_dict = {}
    reader = csv.reader(f)
    reader.next()
    reader.next()
    for row in reader:
        if len(row) == 15:
            alpha2 = row[6]
            vpn_dict[alpha2] = vpn_dict.get(alpha2, [])
            vpn_dict[alpha2].append({
                "vpn_name": row[0],
                "ip": row[1],
                "country_name": row[5],
                "alpha2": alpha2,
                "openvpn_config": b64decode(row[-1])
            })
    f.close()

    server_country = {}

    # write config files
    for country in vpn_dict:
        for data in vpn_dict[country]:
            config_filename = "{}.ovpn".format(data['ip'])
            file_path = os.path.join(directory, config_filename)
            with open(file_path, 'w') as f:
                f.write(data['openvpn_config'])
                f.write("up /etc/openvpn/update-resolv-conf\n")
                f.write("down /etc/openvpn/update-resolv-conf\n")

            server_country[data['ip']] = country

    with open(os.path.join(directory, 'servers.txt'), 'w') as f:
        for ip in server_country:
            f.write('|'.join([ip, server_country[ip]]) + '\n')
577410
def go_to_and_do(aws_config, current_config, path, current_path, callback, callback_args = None):
    
    try:
        key = path.pop(0)
        if not current_config:
            current_config = aws_config
        if not current_path:
            current_path = []
        keys = key.split('.')
        if len(keys) > 1:
            while True:
                key = keys.pop(0)
                if not len(keys):
                    break
                current_path.append(key)
                current_config = current_config[key]
        if key in current_config:
            current_path.append(key)
            for (i, value) in enumerate(list(current_config[key])):
                if len(path) == 0:
                    if type(current_config[key] == dict) and type(value) != dict and type(value) != list:
                        callback(aws_config, current_config[key][value], path, current_path, value, callback_args)
                    else:
                        callback(aws_config, current_config, path, current_path, value, callback_args)
                else:
                    tmp = copy.deepcopy(current_path)
                    try:
                        tmp.append(value)
                        go_to_and_do(aws_config, current_config[key][value], copy.deepcopy(path), tmp, callback, callback_args)
                    except:
                        tmp.pop()
                        tmp.append(i)
                        go_to_and_do(aws_config, current_config[key][i], copy.deepcopy(path), tmp, callback, callback_args)

    except Exception as e:
        printException(e)
        if i:
            printInfo('Index: %s' % str(i))
        printInfo('Path: %s' % str(current_path))
        printInfo('Key = %s' % str(key))
        printInfo('Value = %s' % str(value))
        printInfo('Path = %s' % path)
644165
def create_config_file(filename):
    
    import textwrap
    from six.moves.urllib import parse

    if not os.path.exists(filename):
        old_default_config_file = os.path.join(os.path.dirname(filename),
                                               '.tksrc')
        if os.path.exists(old_default_config_file):
            upgrade = click.confirm("\n".join(textwrap.wrap(
                "It looks like you recently updated Taxi. Some "
                "configuration changes are required. You can either let "
                "me upgrade your configuration file or do it "
                "manually.")) + "\n\nProceed with automatic configuration "
                "file upgrade?", default=True
            )

            if upgrade:
                settings = Settings(old_default_config_file)
                settings.convert_to_4()
                with open(filename, 'w') as config_file:
                    settings.config.write(config_file)
                os.remove(old_default_config_file)
                return
            else:
                print("Ok then.")
                sys.exit(0)

        welcome_msg = "Welcome to Taxi!"
        click.secho(welcome_msg, fg='green', bold=True)
        click.secho('=' * len(welcome_msg) + '\n', fg='green', bold=True)

        click.echo(click.wrap_text(
            "It looks like this is the first time you run Taxi. You will need "
            "a configuration file ({}) in order to proceed. Please answer a "
            "few questions to create your configuration file.".format(
                filename
            )
        ) + '\n')

        config = pkg_resources.resource_string('taxi', 'etc/taxirc.sample').decode('utf-8')
        context = {}
        available_backends = plugins_registry.get_available_backends()

        context['backend'] = click.prompt(
            "Backend you want to use (choices are %s)" %
            ', '.join(available_backends),
            type=click.Choice(available_backends)
        )
        context['username'] = click.prompt("Username or token")
        context['password'] = parse.quote(
            click.prompt("Password (leave empty if you're using"
                         " a token)", hide_input=True, default=''),
            safe=''
        )
        # Password can be empty in case of token auth so the ':' separator
        # is not included in the template config, so we add it if the user
        # has set a password
        if context['password']:
            context['password'] = ':' + context['password']

        context['hostname'] = click.prompt(
            "Hostname of the backend (eg. timesheets.example.com)",
            type=Hostname()
        )

        editor = Editor().get_editor()
        context['editor'] = click.prompt(
            "Editor command to edit your timesheets", default=editor
        )

        templated_config = config.format(**context)

        directory = os.path.dirname(filename)
        if not os.path.exists(directory):
            os.makedirs(directory)

        with open(filename, 'w') as f:
            f.write(templated_config)
    else:
        settings = Settings(filename)
        conversions = settings.needed_conversions

        if conversions:
            for conversion in conversions:
                conversion()

            settings.write_config()
1017783
def create_config_files(directory):
    
    # get the config file template
    template_url = ("https://securenetconnection.com/vpnconfig/"
                    "openvpn-template.ovpn")
    resp = requests.get(template_url)
    resp.raise_for_status()
    template = resp.content

    # get the available servers and create a config file for each server
    server_url = ("https://securenetconnection.com/vpnconfig/"
                  "servers-cli.php")
    resp = requests.get(server_url)
    resp.raise_for_status()
    servers = resp.content.split("\n")

    if not os.path.exists(directory):
        os.makedirs(directory)
    with open(os.path.join(directory, "servers.txt"), 'w') as f:
        f.write(resp.content)

    for server_line in servers:
        if server_line.strip() == "":
            continue
        server_line = server_line.split("|")
        try:
            ip, desc, country, udp_sup, tcp_sup = server_line
        except ValueError:
            ip, desc, country, udp_sup, tcp_sup, no_rand = server_line
        with open(os.path.join(directory, ip + ".ovpn"), 'w') as file_o:
            file_o.write(template)
            # create tcp if available, else udp
            tcp_sup = tcp_sup.strip()
            if tcp_sup:
                port, proto = 443, "tcp"
            else:
                port, proto = 53, "udp"
            file_o.write("remote {0} {1}\n".format(ip, port))
            file_o.write("proto {0}\n".format(proto))
            # add automatic dns server update
            file_o.write("up /etc/openvpn/update-resolv-conf\n")
            file_o.write("down /etc/openvpn/update-resolv-conf\n")
1265415
def configure(xcodeproj_path, scheme, options: {})
      require 'slather'
      @project = Slather::Project.open(xcodeproj_path)
      @project.scheme = scheme
      @project.workspace = options[:workspace]
      @project.build_directory = options[:build_directory]
      @project.ignore_list = options[:ignore_list]
      @project.ci_service = options[:ci_service]
      @project.coverage_access_token = options[:coverage_access_token]
      @project.coverage_service = options[:coverage_service] || :terminal
      @project.source_directory = options[:source_directory]
      @project.output_directory = options[:output_directory]
      @project.input_format = options[:input_format]
      @project.binary_file = options[:binary_file]
      @project.decimals = options[:decimals]
      @project.configure
      @project.post if options[:post]
    end
1016854
def do_create(config, config_dir):
    
    if os.path.exists(config_dir):
        print "Configuration '{}' already exists.".format(config)
        exit(1)
    os.makedirs(config_dir)
    print "Configuration directory created."

    url = raw_input("RSS URL for processing []: ")
    torrent_dir = raw_input("Output directory for found .torrent files [{}]: "\
        .format(DEFAULT_TORRRENT_DIR)) or DEFAULT_TORRRENT_DIR
    update_interval = raw_input("Update interval (mins) [{}]: "\
        .format(DEFAULT_UPDATE_INTERVAL)) or DEFAULT_UPDATE_INTERVAL

    editor = os.environ["EDITOR"]

    config_filter = os.path.join(config_dir, 'filter')
    if confirm("Do you want to create filters list?", False):
        call([editor, config_filter])
        print "Filter configuration has been saved."

    config_blacklist = os.path.join(config_dir, 'blacklist')
    if confirm("Do you want to create blacklist?", False):
        call([editor, config_filter])
        print "Blacklist configuration has been saved."

    config_file = os.path.join(config_dir, 'config')
    config_data = json.dumps({
        "url": url,
        "torrent_dir": torrent_dir,
        "update_interval": update_interval
    }, sort_keys=True, indent=4, separators=(',', ': '))
    with open(config_file, 'w') as f:
        f.write(config_data)

    ct = CronTab(user=True)
    cmd = "{} {} -e {}".format(sys.executable,
                               os.path.abspath(__file__),
                               config)
    job = ct.new(command=cmd)
    job.minute.every(update_interval)
    job.enable()
    ct.write()
    print "Crontab updated."

    print "Config '{}' has been saved.".format(config)
904360
def create(cls, env=None, args=None):
    
    env = {k: v for k, v in (os.environ if env is None else env).items()
           if k.startswith('PANTS_')}
    args = tuple(sys.argv if args is None else args)

    flags = set()
    short_flags = set()

    def filecontent_for(path):
      return FileContent(ensure_text(path), read_file(path, binary_mode=True))

    def capture_the_flags(*args, **kwargs):
      for arg in args:
        flags.add(arg)
        if len(arg) == 2:
          short_flags.add(arg)
        elif kwargs.get('type') == bool:
          flags.add('--no-{}'.format(arg[2:]))

    GlobalOptionsRegistrar.register_bootstrap_options(capture_the_flags)

    def is_bootstrap_option(arg):
      components = arg.split('=', 1)
      if components[0] in flags:
        return True
      for flag in short_flags:
        if arg.startswith(flag):
          return True
      return False

    # Take just the bootstrap args, so we don't choke on other global-scope args on the cmd line.
    # Stop before '--' since args after that are pass-through and may have duplicate names to our
    # bootstrap options.
    bargs = tuple(filter(is_bootstrap_option, itertools.takewhile(lambda arg: arg != '--', args)))

    config_file_paths = cls.get_config_file_paths(env=env, args=args)
    config_files_products = [filecontent_for(p) for p in config_file_paths]
    pre_bootstrap_config = Config.load_file_contents(config_files_products)

    initial_bootstrap_options = cls.parse_bootstrap_options(env, bargs, pre_bootstrap_config)
    bootstrap_option_values = initial_bootstrap_options.for_global_scope()

    # Now re-read the config, post-bootstrapping. Note the order: First whatever we bootstrapped
    # from (typically pants.ini), then config override, then rcfiles.
    full_configpaths = pre_bootstrap_config.sources()
    if bootstrap_option_values.pantsrc:
      rcfiles = [os.path.expanduser(str(rcfile)) for rcfile in bootstrap_option_values.pantsrc_files]
      existing_rcfiles = list(filter(os.path.exists, rcfiles))
      full_configpaths.extend(existing_rcfiles)

    full_config_files_products = [filecontent_for(p) for p in full_configpaths]
    post_bootstrap_config = Config.load_file_contents(
      full_config_files_products,
      seed_values=bootstrap_option_values
    )

    env_tuples = tuple(sorted(iteritems(env), key=lambda x: x[0]))
    return cls(env_tuples=env_tuples, bootstrap_args=bargs, args=args, config=post_bootstrap_config)