Persist device config to a file

 If the file does not exist, it will be created.

 === Parameters
 device(String):: target device name
 data(String):: target device config
544794
def write_adaptor_config(device, data)
      config_file = config_file(device)
      raise "FATAL: invalid device name of '#{device}' specified for static IP allocation" unless device.match(/eth[0-9+]/)
      logger.info "Writing persistent network configuration to #{config_file}"
      File.open(config_file, "w") { |f| f.write(data) }
    end
997821
def store_config config
      required = Set.new([:name, :parameters, :output])
      missing = required - config.keys
      raise TargetLoadError.new("Required keys are missing from target definition: #{missing.to_a.join(",")}") unless missing.empty?
      config.each_pair do |param, data|
        case param
        when :name
          raise TargetLoadError.new('Target name must be a string') unless data.is_a? String
          @name = data
        when :shortname
          raise TargetLoadError.new('Target shortname must be a string') unless data.is_a? String
          @shortname = data
        when :parameters
          self.generate_parameters data
        when :output
          raise TargetLoadError.new('Target output must be a hash') unless data.is_a?(Hash)
          @output = data
        end
      end
    end
1369174
def _try_persist_settings(serializable_data: dict):
    
    with open(CONFIG_FILE, "w") as json_file:
            json.dump(serializable_data, json_file, indent=4)
513830
private void save(OneOrOther<File, Path> configFile) throws IOException {
		if (configFile.isOne()) {
			File config = configFile.getOne();
			this.saveToWriter(getFileWriter(config));
		} else {
			Path config = configFile.getOther();
			this.saveToWriter(getPathWriter(config));
		}
	}
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)
682268
def save(self, filename=None):
        """"""
        if self.__fname is None and filename is None:
            raise ValueError('Config loaded from string, no filename specified')
        conf = self.__config
        cpa = dict_to_cp(conf)
        with open(self.__fname if filename is None else filename, 'w') as f:
            cpa.write(f)
162689
def write(self, data):
        
        try:
            self._device.write_data(data)

            self.on_write(data=data)

        except FtdiError as err:
            raise CommError('Error writing to device: {0}'.format(str(err)), err)
144031
def save(self, filename=None, verbose=False):
        ''' 
        '''
        if filename is None:
            if (not self.has_section(self.application_name) or
                    not self.has_option(self.application_name, 'config_file')):
                if not self.has_section(self.application_name):
                    self.add_section(self.application_name)
                if not self.application_name in self.config_description:
                    self.config_description[self.application_name] = {}

                appdir = AppDirs(self.application_name,
                        self.application_author,
                        version=self.application_version)
                value = os.path.join(appdir.user_data_dir, '{0}.conf'.format(
                    self.application_name.lower()))
                if not self.has_option(self.application_name, 'config_file'):
                    self.set(self.application_name, 'config_file', value)
                if not ('config_file' in
                        self.config_description[self.application_name]):
                    self.config_description[self.application_name]\
                            ['config_file'] = ('The config file to '
                                'overwrite on change of the config values. '
                                '[$HOME/.{0}/{0}.conf]'.format(
                                    self.application_name), str, value)

            filename = self.get(self.application_name, 'config_file')

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

        hidden = None
        if self.has_section('hidden'):
            hidden = self.items('hidden')
            self.remove_section('hidden')

        cfp = open(filename, 'w')
        self._write_config(cfp, verbose)
        cfp.close()

        if hidden is not None:
            for key, value in hidden:
                self.set('hidden', key, value)
1317128
def save_config(name, data, base='conf'):
    """"""
    if not os.path.exists(base):
        os.mkdir(base)
    fname = pjoin(base, name+'.json')
    with open(fname, 'w') as f:
        json.dump(data, f, indent=2)
342557
def save(keystorerc=None, keystore=None, files=[], verbose=False):
  ''''''

  config = None
  if keystorerc:
    config = config_reader.read(keystorerc)
    if not config:
      print('No configuration found.', file=sys.stderr)
      sys.exit(-1)
  elif keystore and len(files) > 0:
    config = {
      'keystore': keystore,
      'files': files
    }

  if 'verbose' in config and config['verbose']:
    verbose = True

  keystore_path = None
  if 'keystore' not in config:
    print('.keystorerc needs to specify a keystore file path.', file=sys.stderr)
    sys.exit(-1)

  keystore_path = os.path.expanduser(config['keystore'])
  if os.path.isdir(keystore_path):
    print('keystore cannot be a folder: {}'.format(config['keystore']), file=sys.stderr)
    sys.exit(-1)
  elif not os.path.isfile(keystore_path):
    # If keystore file does not exist already, attempt to create one
    try:
      pathlib.Path(keystore_path).touch()
    except OSError as err:
      print('keystore cannot be accessed: {}\n{}'.format(config['keystore'], err), file=sys.stderr)
      sys.exit(-1)

  # iterate through keys and add them here

  keystore = {}
  try:
    for p in config['files']:

      expanded_path = os.path.expanduser(p)
      path = pathlib.Path(expanded_path)
      if verbose: print('Inspecting {}:'.format(expanded_path))

      if not path.exists():
        print('Error: File or folder does not exist: {}'.format(p), file=sys.stderr)
        sys.exit(-1)
      if path.is_dir():
        for dirpath, dirnames, filenames in os.walk(expanded_path):
          for name in filenames:
            fullpath = os.path.join(dirpath, name)
            if verbose: print('Adding {} ...'.format(fullpath))
            with open(fullpath, 'rb') as keyfile:
              b64_bytes = base64.encodebytes(keyfile.read()).decode('utf-8')
              keystore[fullpath] = b64_bytes
      elif path.is_file():
        fullpath = expanded_path
        if verbose: print('Adding {} ...'.format(fullpath))
        with open(fullpath, 'rb') as keyfile:
          b64_bytes = base64.encodebytes(keyfile.read()).decode('utf-8')
          keystore[fullpath] = b64_bytes

    if verbose: print('Added {} key(s) to keystore.\n'.format(len(keystore)))

    # prompt user for a one-time passphase for encryption

    do_passphrases_match = False
    passphrase = None
    print('This passphrase is used to decrypt your keystore. Please remember it.')
    while not do_passphrases_match:
      passphrase = getpass.getpass('Please enter a passphrase: ')
      passphrase_verify = getpass.getpass('Please verify your passphrase: ')
      do_passphrases_match = passphrase != '' and passphrase == passphrase_verify
      if passphrase == '':
        print('Passphrase cannot be empty.')
      elif not do_passphrases_match:
        print('Passphrases do not match. Please try again.')
    if verbose: print('Passphrase accepted. Encrypting ...')

    # serialise, compress, encrypt

    serial_keystore = json.dumps(keystore)
    compressed_keystore = gzip.compress(serial_keystore.encode('utf-8'))
    try:
      encrypted_keystore = simplecrypt.encrypt(passphrase, compressed_keystore)
    except simplecrypt.EncryptionException as err:
      print('You managed to bump into a very, very rare issue with AES.\nPlease contact the author. {}'.format(err), file=sys.stder)
      sys.exit(-1)

    # save encrypted keystore to file
    keystore_path = os.path.expanduser(keystore_path)
    if verbose: print('Writing to keystore file {}'.format(keystore_path))

    with open(keystore_path, 'wb') as keystore_file:
      keystore_file.write(encrypted_keystore)

    if verbose: print('Keystore successfully created: ')
    # if verbose: print(encrypted_keystore)

  except KeyError as err:
    print('.keystorerc config is missing `files` attribute: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
  except TypeError as err:
    print('Error: {}'.format(err), file=sys.stderr)
    traceback.print_exc()
    sys.exit(-1)
  except OSError as err:
    print('The file system gave an error: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
  except Exception as err:
    print('Serious error. Please report this bug to the author: {}'.format(err), file=sys.stderr)
    sys.exit(-1)
499703
function (sLayer, sNameSpace, sFileName, sFileType, sData, sTransportId, sPackageName) {
			return LRepConnector.saveFile(sLayer, sNameSpace, sFileName, sFileType, sData, sTransportId, sPackageName).then(this._navToDisplayMode.bind(this));
		}
541365
def saveas name=nil, config={}
      unless name
        name = rb_gets "File to save as: "
        return if name.nil? || name == ""
      end
      overwrite_if_exists = config[:overwrite_if_exists] || false
      unless overwrite_if_exists
        exists = File.exists? name
        if exists # need to prompt
          return unless rb_confirm("Overwrite existing file? ")
        end
      end
      # if it has been set do not prompt. or ask only if value is :ask
      # But this should only be if there is someformatting provided, that is there 
      # is a @document
      l = @list
      # the check for document is to see if it is some old widget like textarea that is calling this.
      if @document
        if config.key? :save_with_formatting
          save_with_formatting = config[:save_with_formatting] 
        else
          save_with_formatting = rb_confirm("Save with formatting?")
        end
        if save_with_formatting
          l = @list
        else
          l = @document.native_text().map do |w| w.to_s ; end
        end
      end
      #l = getvalue
      File.open(name, "w"){ |f|
        l.each { |line| f.puts line }
        #l.each { |line| f.write line.gsub(/\r/,"\n") }
      }
      rb_puts "#{name} written."
    end
974864
def create(self, **kwargs):
        ''''''

        self._set_attributes(**kwargs)
        self._check_type()
        pollster(self._check_all_devices_in_sync)()
        dg = self.devices[0].tm.cm.device_groups.device_group
        dg.create(name=self.name, partition=self.partition, type=self.type)
        for device in self.devices:
            self._add_device_to_device_group(device)
            device.tm.sys.config.exec_cmd('save')
        self.ensure_all_devices_in_sync()
188258
def make_config_file(guided=False):
    
    config_path = _make_config_location(guided=guided)

    config_data = make_config_data(guided=guided)

    write_config_file(config_path, config_data)
150243
def save_plist(filename, options = {})
      options = { :indent => DEFAULT_INDENT }.merge(options)
      Plist::Emit.save_plist(self, filename, options)
    end
1008859
def save_to_file(self, text, filename, name):
        '''
        
        '''
        self._push(self._driver.save_to_file, (text, filename), name)
132347
def save_data_as(self, data, file_name, destination_folder=None):
        
        if not destination_folder:
            destination_folder = constants.Files.DOWNLOADS_FOLDER
        page_utils._save_data_as(data, destination_folder, file_name)