Create new Config object, either ephemerally or from a file
357701
def write
      new = get
      new[@note] = @token
      File.open(@file, 'w', 0o0600) { |fh| fh.write new.to_yaml }
    end
1039791
def from_object(updates):
    ""
    import sys
    config = sys.modules[__name__]
    
    prefix = config.__name__.split('.')[0].upper()
    keys = [k for k in config.__dict__ if \
        k != from_object.__name__ and not k.startswith('_')]
    get_value = lambda c, k: hasattr(c, k) and getattr(c, k) or None
    for key in keys:
        prefix_key = '%s_%s' % (prefix, key)
        value = get_value(updates, prefix_key) or get_value(updates, key)
        if value: setattr(config, key, value)
690136
def config_maker(project_name, path):
    """"""

    with open(skeleton_path("config.py"), "r") as config_source:
        config_content = config_source.read()

    config_content = config_content.replace("__PROJECT_NAME__", project_name)

    with open(path, "w") as config_dest:
        config_dest.write(config_content)
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()
1331851
def createDefaultConfigFile() :
	""""""
	s = "[pyGeno_config]\nsettings_dir=%s\nremote_location=%s" % (pyGeno_SETTINGS_DIR, pyGeno_REMOTE_LOCATION)
	f = open('%s/config.ini' % pyGeno_SETTINGS_DIR, 'w')
	f.write(s)
	f.close()
618926
def _create_config(self, vm, path, content=None):
        

        log.info("Creating config file {}".format(path))
        config_dir = os.path.dirname(path)
        try:
            os.makedirs(config_dir, exist_ok=True)
        except OSError as e:
            raise DynamipsError("Could not create Dynamips configs directory: {}".format(e))

        if content is None or len(content) == 0:
            content = "!\n"
            if os.path.exists(path):
                return

        try:
            with open(path, "wb") as f:
                if content:
                    content = "!\n" + content.replace("\r", "")
                    content = content.replace('%h', vm.name)
                    f.write(content.encode("utf-8"))
        except OSError as e:
            raise DynamipsError("Could not create config file '{}': {}".format(path, e))

        return os.path.join("configs", os.path.basename(path))
31856
def custom_conf(self, conf):
        ''''''
        if conf:
            for (key, val) in conf.items():
                self.__conf[key] = val
        return self
942894
def create_app_from_yml(path):
    """"""

    try:
        with open(path, "rt", encoding="UTF-8") as f:
            try:
                # Substitute ALL occurrences of '%(here)s' with a path to a
                # directory with '.holocron.yml'. Please note, we also want
                # wrap the result into 'io.StringIO' in order to preserve
                # original filename in 'yaml.safe_load()' errors.
                interpolated = io.StringIO(f.read() % {
                    "here": os.path.abspath(os.path.dirname(path))})
                interpolated.name = f.name

                conf = yaml.safe_load(interpolated)
            except yaml.YAMLError as exc:
                raise RuntimeError(
                    "Cannot parse a configuration file. Context: " + str(exc))

    except FileNotFoundError:
        conf = {"metadata": None, "pipes": {}}

    return core.create_app(conf["metadata"], pipes=conf["pipes"])
1342353
def from_pyfile(self, filename):
        
        d = types.ModuleType('config')
        d.__file__ = filename
        with open(filename) as config_file:
            exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
        self.from_object(d)
        return True
260171
def options_from_file(args):
    
    logger.debug("updating options from config files")
    updated_from_file = []
    for config_file in CONFIG_FILES:
        logger.debug("updating from: %s", config_file)
        parser = ConfigParser()
        parser.read(config_file)
        try:
            items = parser.items('fades')
        except NoSectionError:
            continue

        for config_key, config_value in items:
            if config_value in ['true', 'false']:
                config_value = config_value == 'true'
            if config_key in MERGEABLE_CONFIGS:
                current_value = getattr(args, config_key, [])
                if current_value is None:
                    current_value = []
                current_value.append(config_value)
                setattr(args, config_key, current_value)
            if not getattr(args, config_key, False) or config_key in updated_from_file:
                # By default all 'store-true' arguments are False. So we only
                # override them if they are False. If they are True means that the
                # user is setting those on the CLI.
                setattr(args, config_key, config_value)
                updated_from_file.append(config_key)
                logger.debug("updating %s to %s from file settings", config_key, config_value)

    return args
1354436
def create_config(cls, params, prefix=None, name=None):
        
        if isinstance(cls.cfg, Config):
            cfg = cls.cfg.copy(name=name, prefix=prefix)
        else:
            cfg = cls.cfg.copy()
            if name:
                cfg[name] = name
            if prefix:
                cfg[prefix] = prefix
            cfg = Config(**cfg)
        cfg.update_settings()
        cfg.update(params, True)
        return cfg
1249334
def load_config(name, base='conf'):
    """"""
    fname = pjoin(base, name + '.json')
    if not os.path.exists(fname):
        return {}
    try:
        with open(fname) as f:
            cfg = json.load(f)
    except Exception as e:
        warn("Couldn't load %s: %s" % (fname, e))
        cfg = {}
    return cfg
1011760
def load_config(self, config_source, parameters_source):
        """"""
        with open(config_source) as config_source:
            config_raw = config_source.read()

            parameters = {}
            """Parameteres from file"""
            if os.path.isfile(parameters_source):
                params = self.load_parameters(parameters_source)
                if params is not None:
                    parameters.update(params)

            """Overwrite parameteres with the environment variables"""
            env_params = {}
            env_params.update(os.environ)
            for k, v in env_params.items():
                if is_string(v):
                    env_params[k] = "'" + v + "'"

            parameters.update(env_params)

            """Replace the parameters"""
            final_configuration = config_raw.format(**parameters)
            final_configuration = yaml.safe_load(final_configuration)
            return final_configuration if final_configuration is not None else {}
797801
def init_config(cls):
        
        try:
            # first load current conf and only overwrite needed params
            # we don't want to reset everything
            config_file = os.path.expanduser(cls.home_config)
            config = cls.load(config_file, 'global')
            cls._del('global', 'api.env')

            hidden_apikey = '%s...' % cls.get('api.key', '')[:6]
            apikey = click.prompt('Api key (xmlrpc)',
                                  default=hidden_apikey)
            if apikey == hidden_apikey:
                # if default value then use actual value not hidden one
                apikey = cls.get('api.key')
            env_choice = click.Choice(list(cls.apienvs.keys()))
            apienv = click.prompt('Environnment [production]/ote',
                                  default=cls.default_apienv,
                                  type=env_choice,
                                  show_default=False)
            sshkey = click.prompt('SSH keyfile',
                                  default='~/.ssh/id_rsa.pub')
            hidden_apikeyrest = '%s...' % cls.get('apirest.key', '')[:6]
            apikeyrest = click.prompt('Api key (REST)',
                                      default=hidden_apikeyrest)
            if apikeyrest == hidden_apikeyrest:
                # if default value then use actual value not hidden one
                apikeyrest = cls.get('apirest.key')

            config.update({
                'api': {'key': apikey,
                        'host': cls.apienvs[apienv]},
            })
            if apikeyrest:
                config.update({
                    'apirest': {'key': apikeyrest},
                })

            if sshkey is not None:
                sshkey_file = os.path.expanduser(sshkey)
                if os.path.exists(sshkey_file):
                    config['sshkey'] = [sshkey_file]

            directory = os.path.expanduser(os.path.dirname(config_file))
            if not os.path.exists(directory):
                mkpath(directory, 0o700)

            # save to disk
            cls.save(config_file, config)
            # load in memory
            cls.load(config_file, 'global')
        except (KeyboardInterrupt, click.exceptions.Abort):
            cls.echo('Aborted.')
            sys.exit(1)
69801
def from_config(cls):
        """"""
        config = Config()
        client = cls(
            email=config.get('email'),
            api_key=config.get('api_key'),
            server=config.get('api_server'),
            http_proxy=config.get('http_proxy'),
            https_proxy=config.get('https_proxy'),
        )
        return client
1084426
def new(filename: str, *, file_attrs: Optional[Dict[str, str]] = None) -> LoomConnection:
	
	if filename.startswith("~/"):
		filename = os.path.expanduser(filename)
	if file_attrs is None:
		file_attrs = {}

	# Create the file (empty).
	# Yes, this might cause an exception, which we prefer to send to the caller
	f = h5py.File(name=filename, mode='w')
	f.create_group('/layers')
	f.create_group('/row_attrs')
	f.create_group('/col_attrs')
	f.create_group('/row_graphs')
	f.create_group('/col_graphs')
	f.flush()
	f.close()

	ds = connect(filename, validate=False)
	for vals in file_attrs:
		ds.attrs[vals] = file_attrs[vals]
	# store creation date
	currentTime = time.localtime(time.time())
	ds.attrs['CreationDate'] = timestamp()
	ds.attrs["LOOM_SPEC_VERSION"] = loompy.loom_spec_version
	return ds
1218925
def new(self, filename=None):
        """"""
        path = (self.exec_path,)
        if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE):
            # get the absolute path to the python-executable
            p = find_executable("python")
            path = (p, 'python') + path
        else:
            # if run in frozen env (.exe):
            # first arg if execpath of the next session:
            path += (self.exec_path,)
        if filename:
            path += ('-o', filename)
        os.spawnl(os.P_NOWAIT, *path)