示例#1
0
    def __init__(self, mode: str, config_path: str = '..\set_locations.ini'):

        if mode not in available_modes:
            logger.error(
                f"""Eye movements Classifier mode should be one from: {available_modes}.
                         Given type {mode} is unrecognized.""")
            raise NotImplementedError

        self._mode = mode
        self._algorithm_name = None
        self._algorithm = None
        self._model_params = {}

        self._estimator = EyemovementsEstimator(
            [metric() for metric in all_metrics_list])

        # If config is not pre-initialized
        if len(config.sections()) == 0:
            # Read config and init config here
            if Path(config_path).exists():
                init_config(config_path)
            else:
                logger.error(
                    f"No pre-initialized config given and no configuration file found at {config_path}."
                )
                raise FileNotFoundError

        self.__init_algorithm()
示例#2
0
文件: api.py 项目: 7aske/blog
def api_post_comment(postid):
    if request.method == "POST":
        comment = commentutils.request_to_comment(request)
        if comment is not None:
            post = get_db().db.posts.find_one_or_404({"id": postid})
            post["comments"].append(comment)
            if "mailer" in config.sections():
                commentutils.mail_commenters(post, comment)
            get_db().db.posts.update_one(
                {"id": postid}, {"$set": {
                    "comments": post["comments"]
                }})
            return json.dumps(commentutils.comment_to_json(comment)), 201
        else:
            return "Not Found", 404
    elif request.method == "GET":
        post = get_db().db.posts.find_one_or_404({"id": postid})
        addr = request.headers.get("X-Forwarded-For",
                                   default=request.remote_addr)
        voter = get_db().db.voters.find_one({"voter", utils.get_hash(addr)})
        for comment in post["comments"]:
            comment["date_posted"] = comment["date_posted"].strftime(TIME_FMT)
        res = Response()
        res.set_data(
            json.dumps({
                "voter": voter,
                "comments": post["comments"]
            },
                       default=lambda o: str(o)))
        return res, 200
    else:
        return "Bad Request", 400
示例#3
0
def read_config_fill_queue():
    from glob import glob
    from os import chdir, getcwd
    from os.path import realpath

    global config

    # restore the current directory at the end of the function
    prev_dir = getcwd()
    chdir(config["config_path"])

    path_program_dict = {}
    for config_path in glob("*.conf"):
        config = configparser.ConfigParser()
        config.read(config_path)
        section = config.sections()[0]
        kwargs = dict(config[section])
        kwargs["name"] = section
        try:
            prog_path = realpath(config[section]["path"])
            del kwargs["path"]
        except KeyError:
            logging.error("%s is missing the path configuartion key",
                          config_path)
            continue
        if prog_path in path_program_dict:
            logging.warn("%s in %s has already been referenced by %s",
                         prog_path, config_path,
                         path_program_dict[prog_path].config_document)
        else:
            prog = Program(prog_path, **kwargs)
            path_program_dict[prog.path] = prog
            heappush(priority_queue, prog)

    chdir(prev_dir)
示例#4
0
def get_conf_dict():
    conf = {}
    for section in config.sections():
        conf[section] = {}
        for item in config.items(section):
            conf[section][item[0]] = item[1]
    return conf
示例#5
0
def setupExtruders(slicedModel):
    slicedModel.runtimeParameters.extruders = []

    extruderSections = []

    for section in config.sections():
        if section.startswith('Extruder'):
            slicedModel.runtimeParameters.extruders.append(Extruder(slicedModel.runtimeParameters, section))
示例#6
0
def setupExtruders(slicedModel):
    slicedModel.runtimeParameters.extruders = []

    extruderSections = []

    for section in config.sections():
        if section.startswith('Extruder'):
            slicedModel.runtimeParameters.extruders.append(
                Extruder(slicedModel.runtimeParameters, section))
示例#7
0
def get_afp(system: str):
    if request.method == 'GET':
        if system not in config.sections():
            abort(404)
        command = "ssh -n {user}@{server} 'python {afp_scpipt} {system}'".format(system=system, **config[system.lower()])
        stdin, stdout, stderr = ssh.exec_command(command)
        return jsonify([json.loads(line) for line in stdout.readlines()])
    else:
        abort(500)
示例#8
0
def health_check():
    checks = {}
    for section in config.sections():
        checks[section] = None
        len_section = len(section)
        for module, fn in available_checks.iteritems():
            if len(module) <= len_section and section[:len(module)] == module:
                checks[section] = fn(section)
    return json.dumps(checks)
        
示例#9
0
def qm_page(system):
    if system not in config.sections():
        abort(404)
    if request.method == 'GET':
        return TEMPLATE_ENVIRONMENT.get_template("qm.html").render({
            "date": datetime.datetime.now(), 
            "system": system,
            "logged_in_as": flask_login.current_user.id,
        })
    else:
        abort(405)
示例#10
0
def qm_list(system):
    if system not in config.sections():
        abort(404)
    if request.method == 'GET':
        folder = config.get(system, 'qm')
        ftp = ssh.open_sftp()
        files = ftp.listdir(folder)
        result = []
        for file in files:
            fullpath = os.path.join(folder, file)
            st = ftp.stat(fullpath)
            #datetime.datetime.fromtimestamp(st.st_mtime).strftime("MMM d, y")
            result.append({
                'create': datetime.datetime.fromtimestamp(st.st_mtime).strftime("%Y.%m.%d %H:%M:%S"),
                'filename': file,
                'fullpath': fullpath,
                'owner': st.st_uid,
                'size': st.st_size
                })
        return jsonify(result)
    elif request.method == 'POST':
        abort(500)
示例#11
0
                    print("Value changed ", section['name'], " ", section['value'], " ", app_idxr['fields'][schema['fields'].index(section)]['value'])
            except:
                if verbose:
                    print("No key Value!! in ", section['name'])
            if verbose:
                print(section)

        if verbose:
            print(json.dumps(schema, sort_keys=True, indent=4))
        if exist != 0 and changed is not False:
            print(app_idxr['name'], " already present, removing!")
            r = requests.delete(config[app]['url'] + app_indexers_url + "/" + str(app_idxr['id']) + "?apikey=" + config[app]['apikey'])
            if verbose:
                print(config[app]['url'] + app_indexers_url + "/" + str(app_idxr['id']) + "?apikey=" + config[app]['apikey'])
                print("[" + str(r.status_code) + "]")
                print(json.dumps(r.json(), indent=4, sort_keys=True))


        if changed is not False:
            print("Trying to add: " + idxr['@id'] + " to " + app)
            r = requests.post(config[app]['url'] + app_indexers_url + "?apikey=" + config[app]['apikey'], json=schema)

            print("Finished: " + idxr['@id'] + " [" + str(r.status_code) + "]")
            if r.status_code != 201:
                print(json.dumps(r.json(), indent=4, sort_keys=True))


for app in config.sections():
    if app != "default":
        add_indexers(app)
示例#12
0
    try:
        lib.init(log_cfg=pj.LogConfig(level=3, callback=log_cb))

        # List all sound devices and select one we want
        snd_devs = lib.enum_snd_dev()
        i = 0
        for snd_dev in snd_devs:
            print("%i: %s" % (i, snd_dev.name))
            if (snd_dev.name.startswith("plughw:CARD=CX300")):
                lib.set_snd_dev(i, i)
            i = i + 1

        lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(5080))
        lib.start()

        if "sip0" in config.sections():
            acc = lib.create_account(
                pj.AccountConfig(str(config['sip0']['server']),
                                 str(config['sip0']['user']),
                                 str(config['sip0']['password'])))
        else:
            pass
            # acc = lib.create_account_for_transport(transport, cb=MyAccountCallback())

        # Create UDP transport which listens to any available port
        transport = lib.create_transport(pj.TransportType.UDP,
                                         pj.TransportConfig(0))
        print "\nListening on", transport.info().host,
        print "port", transport.info().port, "\n"

        my_sip_uri = "sip:" + transport.info().host + ":" + str(