Dump config 'cnf' to a file 'filepath'.

        :param cnf: Configuration data to dump
        :param filepath: Config file path
        :param kwargs: optional keyword parameters to be sanitized :: dict
346474
def dump_to_path(self, cnf, filepath, **kwargs):
        
        with self.wopen(filepath) as out:
            out.write(self.dump_to_string(cnf, **kwargs))
942244
def savef(self, format, *args):
        
        return lib.zconfig_savef(self._as_parameter_, format, *args)
49162
def common_cli_config_options(f):
    """"""

    @click.option(
        "-C",
        "--config-file",
        envvar="CLOUDSMITH_CONFIG_FILE",
        type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True),
        help="The path to your config.ini file.",
    )
    @click.option(
        "--credentials-file",
        envvar="CLOUDSMITH_CREDENTIALS_FILE",
        type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True),
        help="The path to your credentials.ini file.",
    )
    @click.option(
        "-P",
        "--profile",
        default=None,
        envvar="CLOUDSMITH_PROFILE",
        help="The name of the profile to use for configuration.",
    )
    @click.pass_context
    @functools.wraps(f)
    def wrapper(ctx, *args, **kwargs):
        # pylint: disable=missing-docstring
        opts = config.get_or_create_options(ctx)
        profile = kwargs.pop("profile")
        config_file = kwargs.pop("config_file")
        creds_file = kwargs.pop("credentials_file")
        opts.load_config_file(path=config_file, profile=profile)
        opts.load_creds_file(path=creds_file, profile=profile)
        kwargs["opts"] = opts
        return ctx.invoke(f, *args, **kwargs)

    return wrapper
651172
def _parse_config(config_file_path):
    
    config_file = open(config_file_path, 'r')
    config = yaml.load(config_file)
    config_file.close()
    return config
463783
def fromConfigFile(filename = DEFAULT_CONFIG_FILE):
    
    parser = SafeConfigParser()
    section = 'fenixedu'
    parser.read(filename)

    client_id = parser.get(section, 'client_id')
    redirect_uri = parser.get(section, 'redirect_uri')
    client_secret = parser.get(section, 'client_secret')

    base_url = parser.get(section, 'base_url')
    api_endpoint = parser.get(section, 'api_endpoint')
    api_version = parser.get(section, 'api_version')

    return FenixEduConfiguration(client_id = client_id,
                                  redirect_uri = redirect_uri,
                                  client_secret = client_secret,
                                  base_url = base_url,
                                  api_endpoint = api_endpoint,
                                  api_version = api_version)
105227
def dump(data, hdfs_path, **kwargs):
    
    kwargs["mode"] = "w" if isinstance(data, bintype) else "wt"
    with open(hdfs_path, **kwargs) as fo:
        i = 0
        bufsize = common.BUFSIZE
        while i < len(data):
            fo.write(data[i: i + bufsize])
            i += bufsize
    fo.fs.close()
972196
def save(self, filepath = None, password = None, keyfile = None):
        
        
        if (password is None and keyfile is not None and keyfile != "" and
            type(keyfile) is str):
            self.keyfile = keyfile
        elif (keyfile is None and password is not None and password != "" and
              type(password is str)):
            self.password = password
        elif (keyfile is not None and password is not None and
              keyfile != "" and password != "" and type(keyfile) is str and
              type(password) is str):
            self.keyfile = keyfile
            self.password = password

        if self.read_only:
            raise KPError("The database has been opened read-only.")
        elif ((self.password is None and self.keyfile is None) or 
              (filepath is None and self.filepath is None) or 
              (keyfile == "" and password == "")):
            raise KPError("Need a password/keyfile and a filepath to save the "
                          "file.")
        elif ((type(self.filepath) is not str and self.filepath is not None) or
              (type(self.password) is not str and self.password is not None) or
              (type(self.keyfile) is not str and self.keyfile is not None)):
            raise KPError("filepath, password and keyfile  must be strings.")
        elif self._num_groups == 0:
            raise KPError("Need at least one group!")
        
        content = bytearray()

        # First, read out all groups
        for i in self.groups:
            # Get the packed bytes
            # j stands for a possible field type
            for j in range(1, 10):
                ret_save = self._save_group_field(j, i)
                # The field type and the size is always in front of the data
                if ret_save is not False:
                    content += struct.pack('<H', j)
                    content += struct.pack('<I', ret_save[0])
                    content += ret_save[1]
            # End of field
            content += struct.pack('<H', 0xFFFF)
            content += struct.pack('<I', 0) 

        # Same with entries
        for i in self.entries:
            for j in range(1, 15):
                ret_save = self._save_entry_field(j, i)
                if ret_save is not False:
                    content += struct.pack('<H', j)
                    content += struct.pack('<I', ret_save[0])
                    content += ret_save[1]
            content += struct.pack('<H', 0xFFFF)
            content += struct.pack('<I', 0)

        # Generate new seed and new vector; calculate the new hash
        Random.atfork()
        self._final_randomseed = Random.get_random_bytes(16)
        self._enc_iv = Random.get_random_bytes(16)
        sha_obj = SHA256.new()
        sha_obj.update(bytes(content))
        self._contents_hash = sha_obj.digest()
        del sha_obj

        # Pack the header
        header = bytearray()
        header += struct.pack('<I', 0x9AA2D903)
        header += struct.pack('<I', 0xB54BFB65)
        header += struct.pack('<I', self._enc_flag)
        header += struct.pack('<I', self._version)
        header += struct.pack('<16s', self._final_randomseed)
        header += struct.pack('<16s', self._enc_iv)
        header += struct.pack('<I', self._num_groups)
        header += struct.pack('<I', self._num_entries)
        header += struct.pack('<32s', self._contents_hash)
        header += struct.pack('<32s', self._transf_randomseed)
        if self._key_transf_rounds < 150000:
            self._key_transf_rounds = 150000
        header += struct.pack('<I', self._key_transf_rounds)

        # Finally encrypt everything...
        if self.password is None:
            masterkey = self._get_filekey()
        elif self.password is not None and self.keyfile is not None:
            passwordkey = self._get_passwordkey()
            filekey = self._get_filekey()
            sha = SHA256.new()
            sha.update(passwordkey+filekey)
            masterkey = sha.digest()
        else:
            masterkey = self._get_passwordkey()
        final_key = self._transform_key(masterkey)
        encrypted_content = self._cbc_encrypt(content, final_key)
        del content
        del masterkey
        del final_key
        
        # ...and write it out
        if filepath is not None:
            try:
                handler = open(filepath, "wb")
            except IOError:
                raise KPError("Can't open {0}".format(filepath))
            if self.filepath is None:
                self.filepath = filepath
        elif filepath is None and self.filepath is not None:
            try:
                handler = open(self.filepath, "wb")
            except IOError:
                raise KPError("Can't open {0}".format(self.filepath))
        else:
            raise KPError("Need a filepath.")

        try:
            handler.write(header+encrypted_content)
        except IOError:
            raise KPError("Can't write to file.")
        finally:
            handler.close()
        
        if not path.isfile(self.filepath+".lock"):
            try:
                lock = open(self.filepath+".lock", "w")
                lock.write('')
            except IOError:
                raise KPError("Can't create lock-file {0}".format(self.filepath
                                                                  +".lock"))
            else:
                lock.close()
        return True
732239
def dump_to_stream(self, cnf, stream, **kwargs):
        
        for key, val in anyconfig.compat.iteritems(cnf):
            stream.write("%s='%s'%s" % (key, val, os.linesep))
1022109
def save_config(**kwargs):
    
    if kwargs == {}:
        kwargs = config._config
    current_config = _load_config()
    current_config.update(**kwargs)
    # write to disk
    fname = _get_config_fname()
    if fname is None:
        raise RuntimeError('config filename could not be determined')
    if not op.isdir(op.dirname(fname)):
        os.mkdir(op.dirname(fname))
    with open(fname, 'w') as fid:
        json.dump(current_config, fid, sort_keys=True, indent=0)
663946
def write_config(path, config):
    
    config_as_string = to_nice_yaml(config)

    config_as_string = "---\n" + config_as_string

    string_to_file(path, config_as_string)
430064
def write_config_file(self, params, path):
        
        cfgp = ConfigParser()
        cfgp.add_section(params['name'])
        for p in params:
            if p == 'name':
                continue
            cfgp.set(params['name'], p, params[p])
        f = open(os.path.join(path, 'experiment.cfg'), 'w')
        cfgp.write(f)
        f.close()
462556
def save_config(self, filepath):
        
        def get_hidden_parameter(item):

            num_sub_elements = item.childCount()

            if num_sub_elements == 0:
                dictator = {item.name : item.visible}
            else:
                dictator = {item.name:{}}
                for child_id in range(num_sub_elements):
                    dictator[item.name].update(get_hidden_parameter(item.child(child_id)))
            return dictator

        try:
            filepath = str(filepath)
            if not os.path.exists(os.path.dirname(filepath)):
                os.makedirs(os.path.dirname(filepath))

            # build a dictionary for the configuration of the hidden parameters
            dictator = {}
            for index in range(self.tree_scripts.topLevelItemCount()):
                script_item = self.tree_scripts.topLevelItem(index)
                dictator.update(get_hidden_parameter(script_item))

            dictator = {"gui_settings": self.gui_settings, "gui_settings_hidden": self.gui_settings_hidden, "scripts_hidden_parameters":dictator}

            # update the internal dictionaries from the trees in the gui
            for index in range(self.tree_scripts.topLevelItemCount()):
                script_item = self.tree_scripts.topLevelItem(index)
                self.update_script_from_item(script_item)

            dictator.update({'instruments': {}, 'scripts': {}, 'probes': {}})

            for instrument in self.instruments.values():
                dictator['instruments'].update(instrument.to_dict())
            for script in self.scripts.values():
                dictator['scripts'].update(script.to_dict())

            for instrument, probe_dict in self.probes.items():
                dictator['probes'].update({instrument: ','.join(list(probe_dict.keys()))})

            with open(filepath, 'w') as outfile:
                json.dump(dictator, outfile, indent=4)

            save_config_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'save_config.json'))
            if os.path.isfile(save_config_path) and os.access(save_config_path, os.R_OK):
                with open(save_config_path, 'w') as outfile:
                    json.dump({'last_save_path': filepath}, outfile, indent=4)
            else:
                with io.open(save_config_path, 'w') as save_config_file:
                    save_config_file.write(json.dumps({'last_save_path': filepath}))

            self.log('Saved GUI configuration (location: {0}'.format(filepath))
        except Exception:
            msg = QtWidgets.QMessageBox()
            msg.setText("Saving failed. Please use 'save as' to define a valid path for the gui.")
            msg.exec_()
186394
def write_example_config(example_file_path: str):
    
    document = tomlkit.document()
    for header_line in _get_header():
        document.add(tomlkit.comment(header_line))
    config_keys = _aggregate_config_values(ConfigValue.config_values)
    _add_config_values_to_toml_object(document, config_keys)
    _doc_as_str = document.as_string().replace(f'"{_NOT_SET}"', '')
    with open(example_file_path, 'w') as stream:
        stream.write(_doc_as_str)
1091901
def file(value, **kwarg):
    
    #a bit weird, but I don't want to hard code default values
    try:
        f = open(value, **kwarg)
    except IOError as e:
        raise ValueError("unable to open %s : %s" % (path.abspath(value), e))
    return f
516327
def save(self, filepath):
        # type: (str) -> None
        
        sections = [
            "Connection",
            "Proxies",
            "RedirectPolicy"]
        for section in sections:
            self._config.add_section(section)

        self._config.set("Connection", "timeout", self.connection.timeout)
        self._config.set("Connection", "verify", self.connection.verify)
        self._config.set("Connection", "cert", self.connection.cert)

        self._config.set("Proxies", "proxies", self.proxies.proxies)
        self._config.set("Proxies", "env_settings",
                         self.proxies.use_env_settings)

        self._config.set("RedirectPolicy", "allow", self.redirect_policy.allow)
        self._config.set("RedirectPolicy", "max_redirects",
                         self.redirect_policy.max_redirects)

        try:
            with open(filepath, 'w') as configfile:
                self._config.write(configfile)
        except (KeyError, EnvironmentError):
            error = "Supplied config filepath invalid."
            raise_with_traceback(ValueError, error)
        finally:
            self._clear_config()
536684
def _write_csv(filepath, data, kwargs):
    """"""
    kwargs_open = {'newline': ''}
    mode = 'w'
    if sys.version_info < (3, 0):
        kwargs_open.pop('newline', None)
        mode = 'wb'
    with open(filepath, mode, **kwargs_open) as fp:
        if 'delimiter' not in kwargs:
            kwargs['delimiter'] = ','
        if 'quotechar' not in kwargs:
            kwargs['quotechar'] = '"'
        with open(filepath, 'w') as fp:
            writer = csv.writer(fp, **kwargs)
            writer.writerows(data)
    return data
1249069
def make(self, **kwargs):
        ''' 
        '''
        configpath = os.path.dirname(os.path.abspath(__file__)) + "/config.py"
        print ("Writing to " + configpath)
        with open(configpath, 'w+') as fh:
            try:
                fh.write("#!/usr/bin/python3\n\n")
            except Exception as e:
                print(e)
            else:
                for key, value in kwargs.items():
                    fh.write(key + ' = ' + value + "\n")