Save Config for HuaweiSSH
776347
def save_config(self, cmd="save", confirm=False, confirm_response=""):
        
        return super(HuaweiBase, self).save_config(
            cmd=cmd, confirm=confirm, confirm_response=confirm_response
        )
52352
def save(self):
        
        assert self.__class__ in conf.config._registry,\
            '%(class_name)s is not registered' % {
                'class_name': self.__class__.__name__
            }

        ConfigModel = apps.get_model('djconfig.Config')

        for field_name, value in self.cleaned_data.items():
            value = utils.serialize(
                value=value,
                field=self.fields.get(field_name, None))
            # TODO: use update_or_create
            count = (ConfigModel.objects
                .filter(key=field_name)
                .update(value=value))
            if not count:
                ConfigModel.objects.create(
                    key=field_name,
                    value=value)

        count = (ConfigModel.objects
            .filter(key='_updated_at')
            .update(value=str(timezone.now())))
        if not count:
            ConfigModel.objects.create(
                key='_updated_at',
                value=str(timezone.now()))

        conf.config._reload()
331350
def writeConfig(self):
        
        with self.writeSharedFileStream('config.pickle', isProtected=False) as fileHandle:
            pickle.dump(self.__config, fileHandle, pickle.HIGHEST_PROTOCOL)
1027512
def save_config(self, config_file_name):
        

        with open(config_file_name, 'w+') as f:
            f.write('P_RESET\n')
            for line in self.send_command_return_multilines('p_fullconfig', '?'):
                f.write(line.split(' ', 1)[1].lstrip())
284115
def save_config(template, params)
      config_file = File.join(config_dir, "#{template}.yml")
      config = File.read(config_file)

      params.map { |key, value| config = config.gsub(key, value) }

      File.open(config_file, 'w') { |file| file.write(config) }
    end
123695
def save_config(path, config):
    """"""
    import json
    config['version'] = 1
    with open(path, 'w') as f:
        json.dump(config, f)
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)
685284
def saveProfile(self, key, settings=None):
        
        #logger.debug("Writing view settings for: {}".format(key))
        if settings is None:
            settings = QtCore.QSettings()
        settings.setValue(key, self.horizontalHeader().saveState())
892866
def save_settings(self):
        
        def _save_displayed_setting(conf, submenu):
            for source, visible_sensors in \
                    self.view.graphs_menu.active_sensors.items():
                section = source + "," + submenu
                conf.add_section(section)

                sources = self.sources
                logging.debug("Saving settings for %s", source)
                logging.debug("Visible sensors %s", visible_sensors)
                # TODO: consider changing sensors_list to dict
                curr_sensor = [x for x in sources if
                               x.get_source_name() == source][0]
                sensor_list = curr_sensor.get_sensor_list()
                for sensor_id, sensor in enumerate(sensor_list):
                    try:
                        conf.set(section, sensor, str(
                            visible_sensors[sensor_id]))
                    except IndexError:
                        conf.set(section, sensor, str(True))

        if not user_config_dir_exists():
            make_user_config_dir()

        conf = configparser.ConfigParser()
        config_file = get_user_config_file()
        with open(config_file, 'w') as cfgfile:
            conf.add_section('GraphControll')
            # Save the configured refresh rete
            conf.set('GraphControll', 'refresh', str(
                self.refresh_rate))
            # Save the configured UTF8 setting
            conf.set('GraphControll', 'UTF8', str(
                self.smooth_graph_mode))
            # Save the configured t_thresh
            if self.temp_thresh:
                conf.set('GraphControll', 'TTHRESH', str(
                    self.temp_thresh))

            _save_displayed_setting(conf, "Graphs")
            _save_displayed_setting(conf, "Summaries")
            conf.write(cfgfile)
348820
def save_config(self):
        
        self.set_option('recent_projects', self.recent_projects)
        self.set_option('expanded_state',
                        self.explorer.treewidget.get_expanded_state())
        self.set_option('scrollbar_position',
                        self.explorer.treewidget.get_scrollbar_position())
        if self.current_active_project and self.dockwidget:
            self.set_option('visible_if_project_open',
                            self.dockwidget.isVisible())
1314081
def save_configs(self):
        

        if self.startup_config_content or self.private_config_content:
            startup_config_content, private_config_content = self.extract_configs()
            if startup_config_content:
                config_path = os.path.join(self.working_dir, "startup-config.cfg")
                try:
                    config = startup_config_content.decode("utf-8", errors="replace")
                    with open(config_path, "wb") as f:
                        log.info("saving startup-config to {}".format(config_path))
                        f.write(config.encode("utf-8"))
                except (binascii.Error, OSError) as e:
                    raise IOUError("Could not save the startup configuration {}: {}".format(config_path, e))

            if private_config_content and private_config_content != b'\nend\n':
                config_path = os.path.join(self.working_dir, "private-config.cfg")
                try:
                    config = private_config_content.decode("utf-8", errors="replace")
                    with open(config_path, "wb") as f:
                        log.info("saving private-config to {}".format(config_path))
                        f.write(config.encode("utf-8"))
                except (binascii.Error, OSError) as e:
                    raise IOUError("Could not save the private configuration {}: {}".format(config_path, e))
727628
def save_current_window_settings(self, prefix, section='main',
                                     none_state=False):
        """"""
        win_size = self.window_size
        prefs_size = self.prefs_dialog_size

        CONF.set(section, prefix+'size', (win_size.width(), win_size.height()))
        CONF.set(section, prefix+'prefs_dialog_size',
                 (prefs_size.width(), prefs_size.height()))
        CONF.set(section, prefix+'is_maximized', self.isMaximized())
        CONF.set(section, prefix+'is_fullscreen', self.isFullScreen())
        pos = self.window_position
        CONF.set(section, prefix+'position', (pos.x(), pos.y()))
        self.maximize_dockwidget(restore=True)# Restore non-maximized layout
        if none_state:
            CONF.set(section, prefix + 'state', None)
        else:
            qba = self.saveState()
            CONF.set(section, prefix + 'state', qbytearray_to_str(qba))
        CONF.set(section, prefix+'statusbar',
                    not self.statusBar().isHidden())
808595
def store_config(config, suffix = None):
    '''
    
    '''
    home = os.path.expanduser('~')
    if suffix is not None:
        config_path = os.path.join(home, '.transfer', suffix)
    else:
        config_path = os.path.join(home, '.transfer')

    os.makedirs(config_path, exist_ok = True)
    with open(os.path.join(config_path, 'config.yaml'), 'w') as fp:
        yaml.dump(config, fp)
640926
private static function _saveSystemConfig()
        {

            $sYmlDump = array(
                'parameters' => array(
                    'database_driver'   => self::checkEmpty(self::$_data['dbDriver']),
                    'database_host'     => self::checkEmpty(self::$_data['dbHost']),
                    'database_port'     => self::checkEmpty(self::$_data['dbPort']),
                    'database_name'     => self::checkEmpty(self::$_data['dbName']),
                    'database_user'     => self::checkEmpty(self::$_data['dbUser']),
                    'database_password' => self::checkEmpty(self::$_data['dbPassword']),
                    'mailer_transport'  => self::checkEmpty(self::$_data['mailerTransport']),
                    'mailer_host'       => self::checkEmpty(self::$_data['mailerHost']),
                    'mailer_user'       => self::checkEmpty(self::$_data['mailerUser']),
                    'mailer_password'   => self::checkEmpty(self::$_data['mailerPassword']),
                    'locale'            => 'de',
                    'secret'            => md5(uniqid(null, true)),
                ),
            );


            $oDumper = new Dumper();
            $sYaml   = $oDumper->dump($sYmlDump, 99, 0, true, false);
            $sAppPath = self::$_container->get('kernel')->getRootDir();
            $sPath   = $sAppPath. '/config/parameters.yml';
            $sYaml   = str_replace("'", '', $sYaml);
            file_put_contents($sPath, $sYaml);
        }
540444
def _saveGuiSettings(self):
        
        # Put the settings into a ConfigObj dict (don't use a config-spec)
        rcFile = self._rcDir+os.sep+APP_NAME.lower()+'.cfg'
        #
        if os.path.exists(rcFile): os.remove(rcFile)
        co = configobj.ConfigObj(rcFile) # can skip try-block, won't read file

        co['showHelpInBrowser']       = self._showHelpInBrowser
        co['saveAndCloseOnExec']      = self._saveAndCloseOnExec
        co['writeProtectOnSaveAsOpt'] = self._writeProtectOnSaveAs
        co['flagNonDefaultVals']      = self._flagNonDefaultVals
        co['frameColor']              = self._frmeColor
        co['taskBoxColor']            = self._taskColor
        co['buttonBoxColor']          = self._bboxColor
        co['entriesColor']            = self._entsColor
        co['flaggedColor']            = self._flagColor

        co.initial_comment = ['Automatically generated by '+\
            APP_NAME+'.  All edits will eventually be overwritten.']
        co.initial_comment.append('To use platform default colors, delete each color line below.')
        co.final_comment = [''] # ensure \n at EOF
        co.write()
609333
def config(self, settings):
        
        self.debug("()")
        # TODO synchronize access to vars
        try:
            self._device_id = settings['device_id']

            self._packet_timeout = settings.get(
                'packet_wait_timeout',
                self._packet_timeout
            )
            self._server_ip = settings.get('server_ip', self._server_ip)
            self._server_port = settings.get('server_port', self._server_port)
        except KeyError:
            raise SensorUpdateException("Key not in settings")

        if callable(self.on_config):
            try:
                self.on_config(settings)
            except:
                self.exception("Failed to update remote config")
                raise SensorUpdateException("Remote config failed")
87759
def saveSettings(self, settings):
        
        value = wrapVariant(os.path.pathsep.join(self.filenames()))
        settings.setValue('recent_files', value)