Beispiel #1
0
    def __init__(self):
        args = self.parse_arguments()
        """
        Load configuration
        """
        log.debug("Loading user configuration")
        self.config = configparser.ConfigParser()

        self.config.read(args['config'])

        # Check if config was loaded successfully, api section must be there
        # log.error("Missing config file")

        self.DEBUG = self.config["api"].getboolean("debug")
        self.HOST = self.config.get("api", "host")
        self.PORT = self.config.getint("api", "port")
        self.THREADED = self.config.getboolean("api", "threaded")
        self.SECRET_KEY = self.config["api"].get("secret_key", "")

        # If in debug mode we want all logging messages
        if self.DEBUG:
            logging.basicConfig(level=logging.DEBUG)

        self.version = self.config.get("api", "version")

        self.config.set(
            "api", "module_path",
            os.path.dirname(__file__) + self.config.get("api", "modules"))

        self.create_urls()
Beispiel #2
0
    def LoadConfig():
        cfg_fn = os.path.join(
            os.path.dirname(os.path.abspath(__file__)) + "/../sample.cfg")
        required_ops = [("Base", "AccessKeyId"), ("Base", "AccessKeySecret"),
                        ("Base", "Endpoint")]
        optional_ops = [("Optional", "SecurityToken")]

        parser = ConfigParser.ConfigParser()
        parser.read(cfg_fn)
        for sec, op in required_ops:
            if not parser.has_option(sec, op):
                sys.stderr.write("ERROR: need (%s, %s) in %s.\n" %
                                 (sec, op, cfg_fn))
                sys.stderr.write("Read README to get help inforamtion.\n")
                sys.exit(1)

        accessKeyId = parser.get("Base", "AccessKeyId")
        accessKeySecret = parser.get("Base", "AccessKeySecret")
        endpoint = parser.get("Base", "Endpoint")
        securityToken = ""
        if parser.has_option("Optional", "SecurityToken") and parser.get(
                "Optional", "SecurityToken") != "$SecurityToken":
            securityToken = parser.get("Optional", "SecurityToken")
            return accessKeyId, accessKeySecret, endpoint, securityToken

        return accessKeyId, accessKeySecret, endpoint, ""
 def __init__(self):
     self.conf = configparser.ConfigParser()
     self.conf._interpolation = configparser.ExtendedInterpolation()
     self.conf.read('conf.cfg')
     self.dc = {}
     self.dc_sub = {}
     self.load()
Beispiel #4
0
    def load(self, file_name):
        """Load patch config file (if exists).

        Args:
          file_name: path to config file to load or None

        Returns:
          True if loading was successful, False if config file is missing. Raises exception on parse failure
        """
        result = False

        if file_name is None:
            return result

        config_file_full = os.path.expanduser(file_name)

        if os.path.isfile(config_file_full):
            config = configparser.ConfigParser()
            # custom optionxform prevents keys from being lower-cased (default implementation) as CaSe matters for us
            config.optionxform = str

            # noinspection PyBroadException
            config.read(config_file_full)

            section = self.INI_SECTION_NAME
            if config.has_option(section, self.INI_KEY_CONFIG_NAME):
                self.name = Config.__strip_quotes_from_ini_string(
                    config.get(section, self.INI_KEY_CONFIG_NAME))

            if config.has_option(section, self.INI_KEY_FILE_OUT_FORMAT):
                self.file_out_format = Config.__strip_quotes_from_ini_string(
                    config.get(section, self.INI_KEY_FILE_OUT_FORMAT))

            if config.has_option(section, self.INI_KEY_SPEECH_SPEED):
                self.speech_speed = config.getint(section,
                                                  self.INI_KEY_SPEECH_SPEED)
            if config.has_option(section, self.INI_KEY_SPEECH_VOLUME_FACTOR):
                self.speech_volume_factor = config.get(
                    section,
                    self.INI_KEY_SPEECH_VOLUME_FACTOR).replace(',', '.')

            if config.has_option(section, self.INI_KEY_TITLE_FORMAT):
                self.title_format = Config.__strip_quotes_from_ini_string(
                    config.get(section, self.INI_KEY_TITLE_FORMAT))

            if config.has_option(section, self.INI_KEY_TICK_FORMAT):
                self.tick_format = Config.__strip_quotes_from_ini_string(
                    config.get(section, self.INI_KEY_TICK_FORMAT))
            if config.has_option(section, self.INI_KEY_TICK_OFFSET):
                self.tick_offset = config.getint(section,
                                                 self.INI_KEY_TICK_OFFSET)
            if config.has_option(section, self.INI_KEY_TICK_OFFSET):
                self.tick_interval = config.getint(section,
                                                   self.INI_KEY_TICK_INTERVAL)
            if config.has_option(section, self.INI_KEY_TICK_ADD):
                self.tick_add = config.getint(section, self.INI_KEY_TICK_ADD)

            result = True

        return result
Beispiel #5
0
def repertory():
    config = configparser.ConfigParser()
    if not (os.path.exists("config.ini")):
        creation_ini()

    config.read("config.ini")
    destinationRepertory = config["outputConfig"].get("outputRepertory")
    incomingRepertory = config["outputConfig"].get("inputRepertory")
    ##output
    if destinationRepertory:
        outputRepertory = destinationRepertory
        if outputRepertory[-1] != "\\":
            outputRepertory += "\\"
    else:  #output : Desktop/Out
        desktop = os.path.join(os.path.join(os.environ['USERPROFILE']),
                               'Desktop')  #desktop path
        outputRepertory = desktop + '\\Out\\'  #Out Folder
    ##input
    if incomingRepertory:
        filesRepertory = incomingRepertory
        if filesRepertory[-1] != "\\":
            filesRepertory += "\\"
    else:  #output : Desktop/Out
        desktop = os.path.join(os.path.join(os.environ['USERPROFILE']),
                               'Desktop')  #desktop path
        filesRepertory = desktop + '\\In\\'  #Out Folder

    if not (os.path.exists(outputRepertory)):
        os.mkdir(outputRepertory[:-1])

    if not (os.path.exists(filesRepertory)):
        os.mkdir(filesRepertory[:-1])

    return filesRepertory, outputRepertory
    def __init__(self):
        super(KeyringUtils, self).__init__()

        config_file = resilient.get_config_file()
        print(u"Configuration file: {}".format(config_file))

        # Read configuration options.
        if config_file:
            config_path = resilient.ensure_unicode(config_file)
            config_path = os.path.expanduser(config_path)
            if os.path.exists(config_path):
                try:
                    self.config = configparser.ConfigParser(interpolation=None)
                    with open(config_path, 'r', encoding='utf-8') as f:
                        first_byte = f.read(1)
                        if first_byte != u'\ufeff':
                            # Not a BOM, no need to skip first byte
                            f.seek(0)
                        self.config.read_file(f)
                except Exception as exc:
                    logger.warn(u"Couldn't read config file '%s': %s", config_path, exc)
                    self.config = None
            else:
                logger.warn(u"Couldn't read config file '%s'", config_file)
        else:
            logger.warn(u"Couldn't read config file")
Beispiel #7
0
    def __init__(self):
        args = self.parse_arguments()
        """
        Load configuration
        """
        log.debug("Loading user configuration")
        self.config = configparser.ConfigParser()

        res = self.config.read(
            [self.DEFAULT_CONFIG, 'config.ini', args['config']])

        # Check if config was loaded successfully, api section must be there
        if len(res) == 0:
            log.error("No configuration file was read! Using default values.")
            self.config.add_section("api")

        self.DEBUG = self.config["api"].getboolean("debug", False)
        self.HOST = self.config["api"].get("host", "localhost")
        self.PORT = self.config["api"].getint("port", 5555)
        self.THREADED = self.config["api"].getboolean("threaded", True)

        # If in debug mode we want all logging messages
        if self.DEBUG:
            logging.basicConfig(level=logging.DEBUG)

        self.version = self.config["api"].get("version", "1.0")

        # Create module path for module importing
        self.config.set(
            "api", "module_path",
            os.path.join(os.getcwd(),
                         self.config["api"].get("modules", "./modules")))

        self.create_urls()
    def save_data(self, reference_img, original_blur, error_blur, file_prefix,
                  phase):
        if phase == "single":
            name_folder = "Output/"
        else:
            name_folder = "Dataset/" + phase + "/"
        name_reference = name_folder + file_prefix + "_ref.png"
        name_IMU_original = name_folder + file_prefix + "_IMU_ori.txt"
        name_blur_original = name_folder + file_prefix + "_blur_ori.png"
        name_IMU_error = name_folder + file_prefix + "_IMU_err.txt"
        name_blur_error = name_folder + file_prefix + "_blur_err.png"
        name_param_error = name_folder + file_prefix + "_param.txt"
        name_param_config = name_folder + file_prefix + "_config.ini"
        # Output reference sharp image
        cv2.imwrite(name_reference, reference_img)

        # Original Perfect IMU data and corresponding blurry images.
        f_original = open(name_IMU_original, "w+")
        f_original.write(
            "Timestamp Gyro_x Gyro_y Gyro_z Acc_x Acc_y Acc_z \r\n")

        for i in range(self.pose + 1):
            # Timestamp  gyro_x gyro_y gyro_z acc_x acc_y acc_z
            f_original.write(
                "%.18e %.18e %.18e %.18e %.18e %.18e %.18e \r\n" %
                (self.time_stamp[i], self.gyro_x[i], self.gyro_y[i],
                 self.gyro_z[i], self.acc_x[i], self.acc_y[i], self.acc_z[i]))

        f_original.close()
        cv2.imwrite(name_blur_original, original_blur)

        # Error IMU data and corresponding blurry images.
        f_error = open(name_IMU_error, "w+")
        f_error.write("Timestamp Gyro_x Gyro_y Gyro_z Acc_x Acc_y Acc_z\r\n")

        for i in range(self.total_samples):
            # Timestamp  gyro_x gyro_y gyro_z acc_x acc_y acc_z
            f_error.write("%.18e %.18e %.18e %.18e %.18e %.18e %.18e \r\n" %
                          (self.delay_time_stamp[i], self.error_gyro[0][i],
                           self.error_gyro[1][i], self.error_gyro[2][i],
                           self.error_acc[0][i], self.error_acc[1][i],
                           self.error_acc[2][i]))

        f_error.close()
        cv2.imwrite(name_blur_error, error_blur)

        # Output Parameters of error data
        config = configparser.ConfigParser()
        f_error = open(name_param_error, "w+")
        config['param'] = {}

        for k, v in self.paramDict.items():
            # Timestamp  gyro_x gyro_y gyro_z acc_x acc_y acc_z
            f_error.write("%s: %f \r\n" % (k, v))
            config['param'][k] = str(v)

        f_error.close()

        with open(name_param_config, 'w') as configfile:
            config.write(configfile)
Beispiel #9
0
def generate_default():
    """ return string containing entire default app.config """
    base_config_fn = pkg_resources.resource_filename("resilient_circuits", "data/app.config.base")
    entry_points = pkg_resources.iter_entry_points('resilient.circuits.configsection')
    additional_sections = []
    for entry in entry_points:
        dist = entry.dist
        try:
            func = entry.load()
        except ImportError:
            LOG.exception(u"Failed to load configuration defaults for package '%s'", repr(dist))
            continue

        new_section = None
        try:
            config_data = func()
            if config_data:
                required_config = configparser.ConfigParser(interpolation=None)
                LOG.debug(u"Config Data String:\n%s", config_data)
                required_config.read_string(unicode(config_data))
                new_section = required_config.sections()[0]
        except:
            LOG.exception(u"Failed to get configuration defaults for package '%s'", repr(dist))
            continue
        if new_section:
            additional_sections.append(config_data)

    LOG.debug("Found %d sections to generate", len(additional_sections))
    with open(base_config_fn, 'r') as base_config_file:
        base_config = base_config_file.read()
        return "\n\n".join(([base_config, ] + additional_sections))
Beispiel #10
0
 def _connect():
     client = paramiko.SSHClient()
     if os.path.exists(NagiosPlugin.OPSMGR_CONF):
         try:
             parser = configparser.ConfigParser()
             parser.read(NagiosPlugin.OPSMGR_CONF, encoding='utf-8')
             server = parser.get(
                 NagiosPlugin.NAGIOS_SECTION,
                 NagiosPlugin.NAGIOS_SERVER).lstrip('"').rstrip('"')
             userid = parser.get(
                 NagiosPlugin.NAGIOS_SECTION,
                 NagiosPlugin.NAGIOS_USERID).lstrip('"').rstrip('"')
             sshkey = parser.get(
                 NagiosPlugin.NAGIOS_SECTION,
                 NagiosPlugin.NAGIOS_SSHKEY).lstrip('"').rstrip('"')
             prvkey = paramiko.RSAKey.from_private_key_file(sshkey)
             client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
             client.connect(server,
                            username=userid,
                            pkey=prvkey,
                            timeout=30,
                            allow_agent=False)
         except:
             raise exceptions.OpsException(
                 "connection to nagios server failed:\n"
                 "Server: " + server + "\n"
                 "Userid: " + userid + "\n"
                 "Sshkey: " + sshkey + "\n")
     return client
Beispiel #11
0
    def _create_parser(cls, seed_values=None):
        """Creates a config parser that supports %([key-name])s value substitution.

    A handful of seed values will be set to act as if specified in the loaded config file's DEFAULT
    section, and be available for use in substitutions.  The caller may override some of these
    seed values.

    :param seed_values: A dict with optional override seed values for buildroot, pants_workdir,
                        pants_supportdir and pants_distdir.
    """
        seed_values = seed_values or {}
        buildroot = seed_values.get('buildroot', get_buildroot())

        all_seed_values = {
            'buildroot': buildroot,
            'homedir': os.path.expanduser('~'),
            'user': getpass.getuser(),
            'pants_bootstrapdir': get_pants_cachedir(),
            'pants_configdir': get_pants_configdir(),
        }

        def update_dir_from_seed_values(key, default):
            all_seed_values[key] = seed_values.get(
                key, os.path.join(buildroot, default))

        update_dir_from_seed_values('pants_workdir', '.pants.d')
        update_dir_from_seed_values('pants_supportdir', 'build-support')
        update_dir_from_seed_values('pants_distdir', 'dist')

        return configparser.ConfigParser(all_seed_values)
Beispiel #12
0
 def __init__(self):
     self.config_parser = configparser.ConfigParser()
     self.effective_settings_file_name = os.getenv(
         'LYACORR_CONF_FILE', self.default_settings_file_name)
     if not os.path.exists(self.effective_settings_file_name):
         raise IOError(errno.ENOENT, os.strerror(errno.ENOENT),
                       self.effective_settings_file_name)
     self.config_parser.read(self.effective_settings_file_name)
Beispiel #13
0
def model_info():
    configinfo = configparser.ConfigParser()
    configinfo.read('../config/model.ini')
    info = configinfo['model_info']
    info_productName = info['product_name']
    info_modelNo = info['mdoel_no']
    updateRate = info['updateRate']
    return info_productName, info_modelNo, updateRate
Beispiel #14
0
 def load(self, path='../../config.ini'):
     """
     Load external configuration file and parse it
     """
     tmp_config = configparser.ConfigParser()
     tmp_config.read(path)
     self.modules[tmp_config.sections()[0]] = tmp_config[
         tmp_config.sections()[0]]
Beispiel #15
0
 def _flag_data_file(filename, data):
     res_file = resource_file(tmpdir, filename)
     cfg = configparser.ConfigParser()
     cfg.optionxform = str
     cfg['config'] = data
     with open(res_file, 'w') as f:
         cfg.write(f)
     return res_file
Beispiel #16
0
    def readConfigFile(self, licFile):

        self.config = configparser.ConfigParser(dict_type=iNI)

        if (os.path.exists(licFile)):
            self.config.read(licFile)

        return self.config
Beispiel #17
0
def read_database_connection():
    """ gets the database connection info and returns it
    """
    if os.path.exists(OPSMGR_CONF):
        parser = configparser.ConfigParser()
        parser.read(OPSMGR_CONF, encoding='utf-8')
        return parser.get('DATABASE', 'connection')
    else:
        pass
Beispiel #18
0
    def __init__(self, filename="data/digisun.ini"):
        """
        By default, the default file is digisun.ini but
        it can be different if specified.
        """
        self.config = configparser.ConfigParser()
        self.config_file = filename

        if not os.path.isfile(filename):
            self.write_empty_config()
Beispiel #19
0
def _write_conf_file(args):
    # Hack to support python2.7
    try:
        input = raw_input
    except NameError:
        pass

    if os.path.exists(CONF_FILE):
        print(
            CONF_FILE +
            " exist. To generate a new passphrase delete this file and run the command again."
        )
    else:
        passphrase = str(base64.b64encode(os.urandom(32)))

        print("At this time only a mysql database on localhost is supported. "
              "Any sqlalchemy supported database can be used by "
              "modifying the connection property in " + CONF_FILE + " "
              "and running opsmgr-admin db_sync.")

        if args.db_user:
            userid = args.db_user
        else:
            userid = input("Enter database userid:")

        if args.db_password:
            password = args.db_password
        else:
            password = getpass.getpass(
                prompt="Enter password for database userid (" + userid + "):")
        if args.db_name:
            database_name = args.db_name
        else:
            database_name = input("Enter database name [opsmgr]:")
            if database_name == '':
                database_name = "opsmgr"

        connection_string = "mysql+pymysql://" + userid + ":" + password + "@localhost/" + database_name
        cfgfile = open(CONF_FILE, 'w')
        config = configparser.ConfigParser()
        config.add_section('DATABASE')
        config.set('DATABASE', 'connection', connection_string)
        config.set('DEFAULT', 'passphrase', passphrase)
        config.write(cfgfile)
        cfgfile.close()

        os.chmod(CONF_FILE, 0o600)
        print(
            CONF_FILE +
            " has been created with the only the current user having read "
            "authority. To allow others to use the command line read access to this file "
            "is required. Be aware that exposes the password for the database user."
        )
        db_sync()
def generate_default(install_list):
    """ return string containing entire default app.config """
    base_config_fn = pkg_resources.resource_filename("resilient_circuits",
                                                     "data/app.config.base")
    entry_points = pkg_resources.iter_entry_points(
        'resilient.circuits.configsection')
    additional_sections = []
    remaining_list = install_list[:] if install_list else []
    for entry in entry_points:
        dist = entry.dist
        package_name = entry.dist.project_name

        # if a list is provided, use it to filter which packages to add to the app.config file
        if install_list is not None and package_name not in remaining_list:
            LOG.debug("{} bypassed".format(package_name))
            continue
        elif package_name in remaining_list:
            remaining_list.remove(package_name)

        try:
            func = entry.load()
        except ImportError:
            LOG.exception(
                u"Failed to load configuration defaults for package '%s'",
                repr(dist))
            continue

        new_section = None
        try:
            config_data = func()
            if config_data:
                required_config = configparser.ConfigParser(interpolation=None)
                LOG.debug(u"Config Data String:\n%s", config_data)
                required_config.read_string(unicode(config_data))
                new_section = required_config.sections()[0]
        except:
            LOG.exception(
                u"Failed to get configuration defaults for package '%s'",
                repr(dist))
            continue

        if new_section:
            additional_sections.append(config_data)

    LOG.debug("Found %d sections to generate", len(additional_sections))

    if install_list and len(remaining_list) > 0:
        LOG.warning("%s not found. Check package name(s)", remaining_list)

    with open(base_config_fn, 'r') as base_config_file:
        base_config = base_config_file.read()
        return "\n\n".join(([
            base_config,
        ] + additional_sections))
Beispiel #21
0
def _read_config(config_file):
    """
    Read a config file and return a dict containing config data

    :param str config_file: path to config
    :return dict(str, str): config data dict
    """
    cfg = configparser.ConfigParser()
    cfg.optionxform = str
    cfg.read(config_file)
    return dict(cfg.items('config'))
Beispiel #22
0
   def _read_config(self):
       """ 
       Reads the Bidtracker username/password and which auctions to read from the config file.
 
       Parameters: None  
       Returns: None  
       """        
       config = configparser.ConfigParser() 
       configFilePath = 'PennyAuctions.config'
       config.read(configFilePath)
       self._username = config['login-info']['username']
       self._password = config['login-info']['password']
       self._auction_pages = dict(config['auction-pages'])        
Beispiel #23
0
    def read_config(self):
        """ 
            Reads the configuration file to get the login information for the courthouse website

            Parameters: None

            Returns: None  
        """
        config = configparser.ConfigParser()
        configFilePath = 'login.config'
        config.read(configFilePath)
        self.username = config['login-info']['username']
        self.password = config['login-info']['password']
Beispiel #24
0
def bundle_feature_flag_config():
    default_cfg_path = os.path.join('user_sync', 'resources',
                                    'default_flags.cfg')
    default_cfg = configparser.ConfigParser()
    default_cfg.optionxform = str
    default_cfg.read(default_cfg_path)

    flag_data = {}

    for k, v in default_cfg.items('config'):
        env_val = os.environ.get(k)
        if env_val is not None:
            flag_data[k] = env_val
        else:
            flag_data[k] = v

    with open(os.path.join('user_sync', 'resources', 'flags.cfg'),
              'w') as flag_cfg_file:
        flag_cfg = configparser.ConfigParser()
        flag_cfg.optionxform = str
        flag_cfg['config'] = flag_data
        flag_cfg.write(flag_cfg_file)
Beispiel #25
0
 def load(self, storage_path, batch_id):
     # store the file
     config = configparser.ConfigParser()
     storage_sub_path = self.sub_path_for_batch(batch_id)
     filename = os.path.join(storage_path, storage_sub_path, str(batch_id))
     if not os.path.exists(filename):
         raise EBatch("Batch %s does not exists" % batch_id)
     with codecs.open(filename, 'rb', encoding='utf-8') as _file:
         config.readfp(_file)
     self.data.load_from_section('BATCH', config)
     for section_name in config.sections():
         if 'TRANSFORM' in section_name:
             trf = self.add_transformation()
             trf.load_from_section(section_name, config)
Beispiel #26
0
    def readModelTraining_params(_self, fileName):

        ConfigIni = ConfigParser.ConfigParser()
        ConfigIni.read(fileName)

        # Get training/validation image names
        # Paths
        # add

        _self.imagesFolder = ConfigIni.get('Training Images', 'imagesFolder')
        _self.GroundTruthFolder = ConfigIni.get('Training Images',
                                                'GroundTruthFolder')
        _self.ROIFolder = ConfigIni.get('Training Images', 'ROIFolder')

        # a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
        # _self.indexesForTraining = random.sample(a,10)
        # _self.indexesForValidation = random.sample(a,1)

        _self.indexesForTraining = random.sample(_self.index, 4)
        # _self.index = set(_self.index) - set(_self.indexesForTraining)
        _self.index = [
            x for x in _self.index if x not in _self.indexesForTraining
        ]
        f = open("D:\Zhuoran\ok.txt", 'a')
        f.write(str(_self.index) + '\n')
        f.close()
        print('####################print_train###################',
              _self.index)

        _self.indexesForValidation = random.sample(_self.index, 1)
        # _self.indexesForTraining       = json.loads(ConfigIni.get('Training Images','indexesForTraining'))
        # _self.indexesForValidation     = json.loads(ConfigIni.get('Training Images','indexesForValidation'))
        _self.imageTypesTrain = json.loads(
            ConfigIni.get('Training Images', 'imageTypes'))

        # training params
        _self.numberOfEpochs = json.loads(
            ConfigIni.get('Training Parameters', 'number of Epochs'))
        _self.numberOfSubEpochs = json.loads(
            ConfigIni.get('Training Parameters', 'number of SubEpochs'))
        _self.numberOfSamplesSupEpoch = json.loads(
            ConfigIni.get('Training Parameters',
                          'number of samples at each SubEpoch Train'))
        _self.firstEpochChangeLR = json.loads(
            ConfigIni.get('Training Parameters', 'First Epoch Change LR'))
        _self.frequencyChangeLR = json.loads(
            ConfigIni.get('Training Parameters', 'Frequency Change LR'))
        _self.applyPadding = json.loads(
            ConfigIni.get('Training Parameters', 'applyPadding'))
Beispiel #27
0
def initial_config():
    r"""Perform initial configuration steps, asking for user input."""
    usr_config = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation())
    usr_config.read(usr_config_file)
    usr_config['general']['default_project'] = input(
        'What is the name of the project that should be managed by default?: ')
    usr_config['github']['token'] = input(
        'What is your Github authentication token?: ')
    usr_config['smartsheet']['token'] = input(
        'What is your Smartsheet authenticaiton token?: ')
    with open(usr_config_file, 'w') as fd:
        usr_config.write(fd)
    # Update default_config by re-reading updated files
    global default_config
    default_config.read([def_config_file, usr_config_file])
Beispiel #28
0
    def readModelTesting_params(_self, fileName):
        ConfigIni = ConfigParser.ConfigParser()
        ConfigIni.read(fileName)

        _self.imagesFolder = ConfigIni.get('Segmentation Images',
                                           'imagesFolder')
        _self.GroundTruthFolder = ConfigIni.get('Segmentation Images',
                                                'GroundTruthFolder')
        _self.ROIFolder = ConfigIni.get('Segmentation Images', 'ROIFolder')

        _self.imageTypes = json.loads(
            ConfigIni.get('Segmentation Images', 'imageTypes'))
        _self.indexesToSegment = json.loads(
            ConfigIni.get('Segmentation Images', 'indexesToSegment'))
        _self.applyPadding = json.loads(
            ConfigIni.get('Segmentation Images', 'applyPadding'))
Beispiel #29
0
def login():
    userName = input("小伙纸,请输入您的学号:")
    userPwd = input("小伙纸,请输入您的密码:")
    login_url = 'https://zjyapp.icve.com.cn/newmobileapi/mobilelogin/newlogin'
    login_data = {
        'clientId': 'd3a22c66c8154964af6c8f3d0046f82b',
        'sourceType': '2',
        'userPwd': userPwd,
        'userName': userName,
        'appVersion': '3',
    }
    # 发送登陆请求
    html = requests.post(url=login_url, data=login_data).json()
    config = configparser.ConfigParser()  # 实例化一个配置写入
    config.add_section('information')  # 创建一个选择器
    config.set('information', 'userId', html['userId'])  # 保存学生ID
    config.write(open('config.info', 'w'))  # 写入文件
Beispiel #30
0
 def get_application_url():
     pluginApp = None
     if os.path.exists(ELKPlugin.OPSMGR_CONF):
         try:
             parser = configparser.ConfigParser()
             parser.read(ELKPlugin.OPSMGR_CONF, encoding='utf-8')
             web_protcol = parser.get(ELKPlugin.ELK_SECTION, "web_protocol")
             web_proxy = parser.get(ELKPlugin.ELK_SECTION, "web_proxy")
             web_port = parser.get(ELKPlugin.ELK_SECTION, "web_port")
             application = "ELK"
             capability = "logging"
             pluginApp = plugins.PluginApplication(application, capability, web_protcol,
                                                   web_proxy, web_port, None)
         except configparser.Error:
             # App missing from /etc/opsmgr/opsmgr.conf, may not be installed
             pass
     return pluginApp