Ejemplo n.º 1
0
Archivo: main.py Proyecto: devolt5/ntg
def leitzeile_json(passage_or_id):
    """Endpoint.  Serve the leitzeile for the verse containing passage_or_id. """

    auth()

    with current_app.config.dba.engine.begin() as conn:
        passage = Passage(conn, passage_or_id)
        verse_start = (passage.start // 1000) * 1000
        verse_end = verse_start + 999

        res = execute(
            conn, """
        SELECT l.begadr, l.endadr, l.lemma, ARRAY_AGG (p.pass_id)
        FROM nestle l
          LEFT JOIN passages p ON (p.passage @> l.passage)
        WHERE int4range (:start, :end + 1) @> l.passage
        GROUP BY l.begadr, l.endadr, l.lemma

        UNION -- get the insertions

        SELECT p.begadr, p.endadr, '', ARRAY_AGG (p.pass_id)
        FROM passages_view p
        WHERE int4range (:start, :end + 1) @> p.passage AND (begadr % 2) = 1
        GROUP BY p.begadr, p.endadr

        ORDER BY begadr, endadr DESC
        """, dict(parameters, start=verse_start, end=verse_end))

        Leitzeile = collections.namedtuple('Leitzeile',
                                           'begadr, endadr, lemma, pass_ids')
        leitzeile = [Leitzeile._make(r)._asdict() for r in res]

        return make_json_response(leitzeile)
Ejemplo n.º 2
0
def stemma_png(passage_or_id):
    """ Return a local stemma diagram in .png format. """

    auth()

    dot = stemma(passage_or_id)
    png = tools.graphviz_layout(dot, format='png')
    return make_png_response(png)
Ejemplo n.º 3
0
def stemma_dot(passage_or_id):
    """ Return a local stemma diagram in .dot format. """

    auth()

    dot = stemma(passage_or_id)
    dot = tools.graphviz_layout(dot)
    return make_dot_response(dot)
Ejemplo n.º 4
0
def textflow_png(passage_or_id):
    """ Return a textflow diagram in .png format. """

    auth()

    dot = textflow(passage_or_id)
    png = tools.graphviz_layout(dot, format='png')
    return make_png_response(png)
Ejemplo n.º 5
0
def textflow_dot(passage_or_id):
    """ Return a textflow diagram in .dot format. """

    auth()

    dot = textflow(passage_or_id)
    dot = tools.graphviz_layout(dot)
    return make_dot_response(dot)
Ejemplo n.º 6
0
Archivo: main.py Proyecto: devolt5/ntg
def cliques_json(passage_or_id):
    """ Endpoint.  Serve all cliques found in a passage.

    :param string passage_or_id: The passage id.

    """

    auth()

    with current_app.config.dba.engine.begin() as conn:
        passage = Passage(conn, passage_or_id)
        return make_json_response(passage.cliques())
Ejemplo n.º 7
0
Archivo: main.py Proyecto: devolt5/ntg
def manuscript_json(hs_hsnr_id):
    """Endpoint.  Serve information about a manuscript.

    :param string hs_hsnr_id: The hs, hsnr or id of the manuscript.

    """

    auth()

    hs_hsnr_id = request.args.get('ms_id') or hs_hsnr_id

    with current_app.config.dba.engine.begin() as conn:
        ms = Manuscript(conn, hs_hsnr_id)
        return make_json_response(ms.to_json())
Ejemplo n.º 8
0
def setup():
    if (not login.auth(user(), request.values['password'])):
        return "password invalid"
    submit = request.values['submit']
    if submit == "Set time zone":
        timezone = request.values['timezone']
        return subprocess.check_output(["sudo" "/usr/share/bitquant/timezone.sh", timezone]).decode("utf-8")
    elif submit == "Refresh CGI scripts":
        return refresh_scripts()
    elif submit == "Lock wiki":
#        password = request.values['password']
#        salt = os.urandom(6).encode('base_64').strip()
#        hashval = crypt.crypt(password, "$1$" + salt + "$")
        hashval = ""
        retval = subprocess.check_output(["sudo", "/usr/share/bitquant/conf.sh", "/wiki-lock"]);
        retval += subprocess.check_output(["./wiki.sh", "/rmuser",
                                           user()])
        retval += subprocess.check_output(["./wiki.sh", "/adduser",
                                           user() + ":" + hashval + ":Dokuwiki Admin:[email protected]:admin,users,upload"])
        return retval
    elif submit == "Unlock wiki":
        return subprocess.check_output(["sudo", "/usr/share/bitquant/conf.sh", "/wiki-unlock"])
    elif submit == "Lock httpd":
        return subprocess.check_output(["sudo", "/usr/share/bitquant/conf.sh", "/httpd-lock"])
    elif submit == "Unlock httpd":
        return subprocess.check_output(["sudo", "/usr/share/bitquant/conf.sh", "/httpd-unlock"])
    else:
        return "unknown command"
Ejemplo n.º 9
0
def setup():
    if (not login.auth(user(), request.values['password'])):
        return "password invalid"
    submit = request.values['submit']
    if submit == "Set time zone":
        timezone = request.values['timezone']
        return subprocess.check_output(["sudo" "/usr/share/bitquant/timezone.sh", timezone])
    elif submit == "Refresh CGI scripts":
        return refresh_scripts()
    elif submit == "Lock wiki":
#        password = request.values['password']
#        salt = os.urandom(6).encode('base_64').strip()
#        hashval = crypt.crypt(password, "$1$" + salt + "$")
        hashval = ""
        retval = subprocess.check_output(["sudo", "/usr/share/bitquant/conf.sh", "/wiki-lock"]);
        retval += subprocess.check_output(["./wiki.sh", "/rmuser",
                                           user()])
        retval += subprocess.check_output(["./wiki.sh", "/adduser",
                                           user() + ":" + hashval + ":Dokuwiki Admin:[email protected]:admin,users,upload"])
        return retval
    elif submit == "Unlock wiki":
        return subprocess.check_output(["sudo", "/usr/share/bitquant/conf.sh", "/wiki-unlock"])
    elif submit == "Lock httpd":
        return subprocess.check_output(["sudo", "/usr/share/bitquant/conf.sh", "/httpd-lock"])
    elif submit == "Unlock httpd":
        return subprocess.check_output(["sudo", "/usr/share/bitquant/conf.sh", "/httpd-unlock"])
    else:
        return "unknown command"
Ejemplo n.º 10
0
def version(tag=None):
    os.chdir(bitquant_root())
    retval = {}
    if tag == "user" or tag == None:
        retval['user'] = user()
    if tag == "version" or tag == None:
        retval['version'] = \
                          subprocess.check_output(["git", "rev-parse",
                                                   "--short", "HEAD"]).strip();
    if tag == "bootstrap_finished" or \
           tag == "bootstrap_status" or tag == None:
        retval['bootstrap_finished'] = \
                               os.path.exists(os.path.join(bitquant_root(),
                                                           "web", "log",
                                                           "bootstrap.done"));
    if tag == "default_password" or tag == None:
        retval["default_password"] = login.auth(user(), default_password)
    if tag == "bootstrap_running" or \
           tag == "bootstrap_status" or tag == None:
        retval['bootstrap_running'] = is_locked("bootstrap")
    if tag == "timezone" or tag == None:
        for line in subprocess.check_output(['timedatectl',
                                              'status']).splitlines():
            if "zone:" in line:
                retval['timezone'] = line.strip().split(":")[1].split()[0]
        if retval['timezone'] == "n/a":
            retval['timezone'] = subprocess.check_output(["grep",
                   "ZONE=",
                   "/etc/sysconfig/clock"]).strip().replace("ZONE=","")
    return Response(json.dumps(retval), mimetype='application/json')
Ejemplo n.º 11
0
def version(tag=None):
    os.chdir(bitquant_root())
    retval = {}
    if tag == "user" or tag == None:
        retval['user'] = user()
    if tag == "version" or tag == None:
        retval['version'] = \
                          subprocess.check_output(["git", "rev-parse",
                                                   "--short", "HEAD"]).strip();
    if tag == "bootstrap_finished" or \
           tag == "bootstrap_status" or tag == None:
        retval['bootstrap_finished'] = \
                               os.path.exists(os.path.join(bitquant_root(),
                                                           "web", "log",
                                                           "bootstrap.done"));
    if tag == "default_password" or tag == None:
        retval["default_password"] = login.auth(user(), default_password)
    if tag == "bootstrap_running" or \
           tag == "bootstrap_status" or tag == None:
        retval['bootstrap_running'] = is_locked("bootstrap")
    if tag == "timezone" or tag == None:
        for line in subprocess.check_output(['timedatectl',
                                              'status']).splitlines():
            if "zone:" in line:
                retval['timezone'] = line.strip().split(":")[1].split()[0]
        if retval['timezone'] == "n/a":
            retval['timezone'] = subprocess.check_output(["grep",
                   "ZONE=",
                   "/etc/sysconfig/clock"]).strip().replace("ZONE=","")
    return Response(json.dumps(retval), mimetype='application/json')
Ejemplo n.º 12
0
Archivo: main.py Proyecto: devolt5/ntg
def attesting_csv(passage_or_id, labez):
    """ Serve all relatives of all mss. attesting labez at passage. """

    auth()

    with current_app.config.dba.engine.begin() as conn:
        passage = Passage(conn, passage_or_id)

        res = execute(
            conn, """
        SELECT ms_id, hs, hsnr
        FROM apparatus_view
        WHERE pass_id = :pass_id AND labez = :labez
        ORDER BY hsnr
        """, dict(parameters, pass_id=passage.pass_id, labez=labez))

        Attesting = collections.namedtuple('Attesting', 'ms_id hs hsnr')

        return csvify(Attesting._fields, list(map(Attesting._make, res)))
Ejemplo n.º 13
0
def clear_data_dump():
    if (not login.auth(user(), request.values['password'])):
        return "Error: password invalid"
    filename = request.values['filename']
    if "/" in filename:
        return "Error: bad filename"
    try:
        os.remove(os.path.join(bitquant_root(), "web", "data", filename))
    except:
        return "Error: exception thrown in file"
    return Response(filename + " deleted", mimetype="text/plain")
Ejemplo n.º 14
0
def passwd():
    myuser = user()
    oldpass = request.form['oldpass']
    newpass1 = request.form['newpass1']
    newpass2 = request.form['newpass2']
    if not login.auth(myuser, oldpass):
        return "old password not correct"
    if newpass1 != newpass2:
        return "passwords do not match"
    else:
        return login.chpasswd(myuser, request.form['newpass1']) + "<br>\n"
Ejemplo n.º 15
0
Archivo: main.py Proyecto: devolt5/ntg
def apparatus_json(passage_or_id):
    """ The contents of the apparatus table. """

    auth()

    with current_app.config.dba.engine.begin() as conn:
        passage = Passage(conn, passage_or_id)

        # list of labez => lesart
        res = execute(
            conn, """
        SELECT labez, reading (labez, lesart)
        FROM readings
        WHERE pass_id = :pass_id
        ORDER BY labez
        """, dict(parameters, pass_id=passage.pass_id))

        Readings = collections.namedtuple('Readings', 'labez lesart')
        readings = [Readings._make(r)._asdict() for r in res]

        # list of labez_clique => manuscripts
        res = execute(
            conn, """
        SELECT labez, clique, labez_clique, labezsuf, reading (labez, lesart), ms_id, hs, hsnr, certainty
        FROM apparatus_view_agg
        WHERE pass_id = :pass_id
        ORDER BY hsnr, labez, clique
        """, dict(parameters, pass_id=passage.pass_id))

        Manuscripts = collections.namedtuple(
            'Manuscripts',
            'labez clique labez_clique labezsuf lesart ms_id hs hsnr certainty'
        )
        manuscripts = [Manuscripts._make(r)._asdict() for r in res]

        return make_json_response({
            'readings': readings,
            'manuscripts': manuscripts,
        })

    return 'Error'
Ejemplo n.º 16
0
def passwd():
    myuser = user()
    if (not login.auth(myuser, default_password)):
        return "Password not default"
    newpass1 = request.form['newpass1']
    newpass2 = request.form['newpass2']
    timezone = request.form['timezone']
    if newpass1 != newpass2:
        return "passwords do not match"
    return subprocess.check_output(["./timezone.sh", timezone]) + \
           login.chpasswd(myuser, request.form['newpass1']) + "<br>\n" + \
           login.chpasswd("root", request.form['newpass1']) + "\n"
Ejemplo n.º 17
0
def upload_dump():
    if (not login.auth(user(), request.values['password'])):
        return "Error: password invalid"
    file = request.files['upload']
    if not file:
        return "Error: no file"
    filename = secure_filename(file.filename)
    save_file = os.path.join(bitquant_root(), "web", "data", filename)
    if os.path.exists(save_file):
        return "Error: file exists"
    file.save(os.path.join(bitquant_root(), "web", "data", filename))
    return "File uploaded"
Ejemplo n.º 18
0
def passwd():
    myuser = user()
    if (not login.auth(myuser, default_password)):
        return "Password not default"
    newpass1 = request.form['newpass1']
    newpass2 = request.form['newpass2']
    timezone = request.form['timezone']
    if newpass1 != newpass2:
        return "passwords do not match"
    return subprocess.check_output(["./timezone.sh", timezone]) + \
           login.chpasswd(myuser, request.form['newpass1']) + "<br>\n" + \
           login.chpasswd("root", request.form['newpass1']) + "\n"
Ejemplo n.º 19
0
def clear_data_dump():
    if (not login.auth(user(), request.values['password'])):
        return "Error: password invalid"
    filename = request.values['filename']
    if "/" in filename:
        return "Error: bad filename"
    try:
        os.remove(os.path.join(bitquant_root(),
                               "web", "data", filename))
    except:
        return "Error: exception thrown in file"
    return Response(filename + " deleted", mimetype="text/plain")
Ejemplo n.º 20
0
Archivo: main.py Proyecto: devolt5/ntg
def passage_json(passage_or_id=None):
    """Endpoint.  Serve information about a passage.

    Return information about a passage or navigate to it.

    :param string passage_or_id: The passage id.
    :param string siglum:        The siglum of the book to navigate to.
    :param string chapter:       The chapter to navigate to.
    :param string verse:         The verse to navigate to.
    :param string word:          The word (range) to navigate to.
    :param string button:        The button pressed.

    """

    auth()

    passage_or_id = request.args.get('pass_id') or passage_or_id or '0'

    siglum = request.args.get('siglum')
    chapter = request.args.get('chapter')
    verse = request.args.get('verse')
    word = request.args.get('word')
    button = request.args.get('button')

    with current_app.config.dba.engine.begin() as conn:
        if siglum and chapter and verse and word and button == 'Go':
            parsed_passage = Passage.parse("%s %s:%s/%s" %
                                           (siglum, chapter, verse, word))
            passage = Passage(conn, parsed_passage)
            return make_json_response(passage.to_json())

        if button in ('-1', '1'):
            passage = Passage(conn, passage_or_id)
            passage = Passage(conn, int(passage.pass_id) + int(button))
            return make_json_response(passage.to_json())

        passage = Passage(conn, passage_or_id)
        return cache(make_json_response(passage.to_json()))
Ejemplo n.º 21
0
def generate_log_dump():
    if (not login.auth(user(), request.values['password'])):
        return "Error: password invalid"
    def dump_data():
        yield "Generate user data"
        proc = subprocess.Popen([os.path.join(bitquant_root(),
                                              "web", "scripts",
                                              "dump-log.sh")],
                                stdout=subprocess.PIPE)
        for line in iter(proc.stdout.readline, ''):
            print line.rstrip()
        yield "Return files"
        return
    return Response(dump_data(), mimetype="text/plain")
Ejemplo n.º 22
0
def upload_dump():
    if (not login.auth(user(), request.values['password'])):
        return "Error: password invalid"
    file = request.files['upload']
    if not file:
        return "Error: no file"
    filename = secure_filename(file.filename)
    save_file = os.path.join(bitquant_root(),
                             "web", "data", filename)
    if os.path.exists(save_file):
        return "Error: file exists"
    file.save(os.path.join(bitquant_root(),
                           "web", "data", filename))
    return "File uploaded"
Ejemplo n.º 23
0
def generate_log_dump():
    if (not login.auth(user(), request.values['password'])):
        return "Error: password invalid"
    def dump_data():
        yield "Generate user data"
        proc = subprocess.Popen([os.path.join(bitquant_root(),
                                              "web", "scripts",
                                              "dump-log.sh")],
                                stdout=subprocess.PIPE)
        for line in iter(proc.stdout.readline, ''):
            print line.rstrip()
        yield "Return files"
        return
    return Response(dump_data(), mimetype="text/plain")
Ejemplo n.º 24
0
Archivo: main.py Proyecto: devolt5/ntg
def attestation_json(passage_or_id):
    """Answer with a list of the attestations of all manuscripts at one specified
    passage."""

    auth()

    with current_app.config.dba.engine.begin() as conn:
        passage = Passage(conn, passage_or_id)

        res = execute(
            conn, """
        SELECT ms_id, labez
        FROM apparatus
        WHERE pass_id = :pass_id
        ORDER BY ms_id
        """, dict(parameters, pass_id=passage.pass_id))

        attestations = {}
        for row in res:
            ms_id, labez = row
            attestations[str(ms_id)] = labez

        return make_json_response({'attestations': attestations})
Ejemplo n.º 25
0
def setup():
    if (not login.auth(user(), request.values['password'])):
        return "password invalid"
    submit = request.values['submit']
    if submit == "Startup servers":
        try:
            return subprocess.check_output(["./servers.sh", "/on"])
        except:
            return traceback.extract_stack()
    elif submit == "Shutdown servers":
        try:
            return subprocess.check_output(["./servers.sh", "/off"])
        except:
            return traceback.extract_stack()
    elif submit == "Set time zone":
        timezone = request.values['timezone']
        return subprocess.check_output(
            ["sudo"
             "/usr/share/bitquant/timezone.sh", timezone])
    elif submit == "Refresh CGI scripts":
        return refresh_scripts()
    elif submit == "Remove local install":
        return subprocess.check_output(["./clean-to-factory.sh"])
    elif submit == "Lock wiki":
        #        password = request.values['password']
        #        salt = os.urandom(6).encode('base_64').strip()
        #        hashval = crypt.crypt(password, "$1$" + salt + "$")
        hashval = ""
        retval = subprocess.check_output(
            ["sudo", "/usr/share/bitquant/conf.sh", "/wiki-lock"])
        retval += subprocess.check_output(["./wiki.sh", "/rmuser", user()])
        retval += subprocess.check_output([
            "./wiki.sh", "/adduser",
            user() + ":" + hashval +
            ":Dokuwiki Admin:[email protected]:admin,users,upload"
        ])
        return retval
    elif submit == "Unlock wiki":
        return subprocess.check_output(
            ["sudo", "/usr/share/bitquant/conf.sh", "/wiki-unlock"])
    elif submit == "Lock httpd":
        return subprocess.check_output(
            ["sudo", "/usr/share/bitquant/conf.sh", "/httpd-lock"])
    elif submit == "Unlock httpd":
        return subprocess.check_output(
            ["sudo", "/usr/share/bitquant/conf.sh", "/httpd-unlock"])
    else:
        return "unknown command"
Ejemplo n.º 26
0
def main_db():
    """ run the solver using DB data """
    solver = SolutionGenerator(DIRECTIONS)
    board_generator = BoardGenerator()
    token = auth("lee", "halcyon88")  # make some include w/ this info
    r = requests.post(
        "https://tactics.prototypeholdings.com/x/puzzle.php?action=solver_get",
        data={"token": token})
    if r.text and r.status_code == 200:
        data = json.loads(r.text)
        # array containing arrays of puzzles
        # puzzle array == [
        #   puzzle_key, board_1_key, board_2_key, board_3_key, board_4_key,
        #   goal_index, player_1_index, player_2_index, player_3_index, player_4_index]
        for puzzle in data:
            key = puzzle[0]
            board = board_generator.generate(
                puzzle[1], puzzle[2], puzzle[3],
                puzzle[4])  # returns the board as a list
            goal = puzzle[5]
            pieces = [
                (puzzle[9], None),  # (piece index, last direction moved)
                (puzzle[8], None),
                (puzzle[7], None),
                (puzzle[6], None)
            ]
            # Goal piece needs to be last in the above array
            # But the goal piece is the first piece in the array (player_1_index)
            solver_result = solver.generate(board, pieces, goal, True)
            solver.display_solution(solver_result['path'])
            solution = len(
                solver_result['path']) if solver_result['solved'] else -len(
                    solver_result['path'])
            # the solution is all but the last move, but includes starting positions
            # len = optimal moves
            r = requests.post(
                "https://tactics.prototypeholdings.com/x/puzzle.php?action=add_solution",
                data={
                    "token": token,
                    "key": key,
                    "solution": solution
                })
    else:
        raise ValueError("Malformed response", r.text, r.status_code, r.reason)
Ejemplo n.º 27
0
def setup():
    if (not login.auth(user(), request.values['password'])):
        return "password invalid"
    submit = request.values['submit']
    if submit == "Startup servers":
        try:
            return subprocess.check_output(["./servers.sh", "/on"])
        except:
            return traceback.extract_stack()
    elif submit == "Shutdown servers":
        try:
            return subprocess.check_output(["./servers.sh", "/off"])
        except:
            return traceback.extract_stack()
    elif submit == "Set time zone":
        timezone = request.values['timezone']
        return subprocess.check_output(["./timezone.sh", timezone])
    elif submit == "Startup ssh":
        return subprocess.check_output(["./sshd.sh", "/on"])
    elif submit == "Shutdown ssh":
        return subprocess.check_output(["./sshd.sh", "/off"])
    elif submit == "Refresh CGI scripts":
        return refresh_scripts()
    elif submit == "Remove local install":
        return subprocess.check_output(["./clean-to-factory.sh"])
    elif submit == "Lock wiki":
#        password = request.values['password']
#        salt = os.urandom(6).encode('base_64').strip()
#        hashval = crypt.crypt(password, "$1$" + salt + "$")
        hashval = ""
        retval = subprocess.check_output(["./conf.sh", "/wiki-lock"]);
        retval += subprocess.check_output(["./wiki.sh", "/rmuser",
                                           user()])
        retval += subprocess.check_output(["./wiki.sh", "/adduser",
                                           user() + ":" + hashval + ":Dokuwiki Admin:[email protected]:admin,users,upload"])
        return retval
    elif submit == "Unlock wiki":
        return subprocess.check_output(["./conf.sh", "/wiki-unlock"])
    elif submit == "Lock httpd":
        return subprocess.check_output(["./conf.sh", "/httpd-lock"])
    elif submit == "Unlock httpd":
        return subprocess.check_output(["./conf.sh", "/httpd-unlock"])
    else:
        return "unknown command"
Ejemplo n.º 28
0
def version(tag=None):
    os.chdir(bitquant_root())
    retval = {}
    if tag == "user" or tag == None:
        retval['user'] = user()
    if tag == "version" or tag == None:
        retval['version'] = \
                          subprocess.check_output(["git", "rev-parse",
                               "--short", "HEAD"]).strip().decode('utf-8')
    if tag == "bootstrap_finished" or \
           tag == "bootstrap_status" or tag == None:
        retval['bootstrap_finished'] = True;
    if tag == "default_password" or tag == None:
        retval["default_password"] = login.auth(user(), default_password)
    if tag == "timezone" or tag == None:
        retval['timezone'] = subprocess.check_output(["grep",
                       "ZONE=",
                       "/etc/sysconfig/clock"]).decode('utf-8').strip().replace("ZONE=","")
    return Response(json.dumps(retval), mimetype='application/json')
Ejemplo n.º 29
0
def install_data_dump():
    if (not login.auth(user(), request.values['password'])):
        return "Error: password invalid"
    filename = request.values['filename']
    if "/" in filename:
        return "Error: bad filename"
    def dump_data():
        yield "Generate user data"
        proc = subprocess.Popen([os.path.join(bitquant_root(),
                                              "web", "scripts",
                                              "install-data.sh"),
                                 os.path.join(bitquant_root(),
                                              "web", "scripts",
                                              filename)
                                 ],
                                stdout=subprocess.PIPE)
        for line in iter(proc.stdout.readline, ''):
            print line.rstrip()
        yield "Return files"
        return
    return Response(dump_data(), mimetype="text/plain")
Ejemplo n.º 30
0
def install_data_dump():
    if (not login.auth(user(), request.values['password'])):
        return "Error: password invalid"
    filename = request.values['filename']
    if "/" in filename:
        return "Error: bad filename"
    def dump_data():
        yield "Generate user data"
        proc = subprocess.Popen([os.path.join(bitquant_root(),
                                              "web", "scripts",
                                              "install-data.sh"),
                                 os.path.join(bitquant_root(),
                                              "web", "scripts",
                                              filename)
                                 ],
                                stdout=subprocess.PIPE)
        for line in iter(proc.stdout.readline, ''):
            print line.rstrip()
        yield "Return files"
        return
    return Response(dump_data(), mimetype="text/plain")
Ejemplo n.º 31
0
def version(tag=None):
    os.chdir(bitquant_root())
    retval = {}
    if tag == "user" or tag == None:
        retval['user'] = user()
    if tag == "version" or tag == None:
        retval['version'] = \
                          subprocess.check_output(["git", "rev-parse",
                                                   "--short", "HEAD"]).strip();
    if tag == "bootstrap_finished" or \
           tag == "bootstrap_status" or tag == None:
        retval['bootstrap_finished'] = True;
    if tag == "default_password" or tag == None:
        retval["default_password"] = login.auth(user(), default_password)
    if tag == "bootstrap_running" or \
           tag == "bootstrap_status" or tag == None:
        retval['bootstrap_running'] = is_locked("bootstrap")
    if tag == "timezone" or tag == None:
        retval['timezone'] = subprocess.check_output(["grep",
                       "ZONE=",
                       "/etc/sysconfig/clock"]).decode('utf-8').strip().replace("ZONE=","")
    return Response(json.dumps(retval), mimetype='application/json')
Ejemplo n.º 32
0
#!/usr/bin/env python
# -*- coding: utf-8 -*- 
import login
import getpass
import urllib2
import requests
from urllib import urlencode
import signal
import sys

email = "*****@*****.**"#raw_input("Email: ")
password = "******"#getpass.getpass()
client_id = "4034599" # Vk application ID
token, user_id = login.auth(email, password, client_id, "friends,messages")
friends_list = list()
STATE = "MENU"

def sigterm_handler():
	if stat=="MENU":
		sys.exit(0)
	else:
		show_list()

def call_api(method, params, token):
	params["access_token"]= token
	url = "https://api.vk.com/method/%s?%s" % (method, urlencode(params))
	r = requests.get(url)
	try:
		return r.json()["response"]
	except KeyError: 
		print r.json()
Ejemplo n.º 33
0
def comparison_detail_csv ():
    """Endpoint. Serve a CSV table. (see also :func:`comparison_detail`)"""

    auth ()

    return csvify (_ComparisonDetailRowCalcFields._fields, comparison_detail ())
Ejemplo n.º 34
0
Archivo: main.py Proyecto: devolt5/ntg
def relatives_csv(passage_or_id, hs_hsnr_id):
    """Output a table of the nearest relatives of a manuscript.

    Output a table of the nearest relatives/ancestors/descendants of a
    manuscript and what they attest.

    """

    auth()

    type_ = request.args.get('type') or 'rel'
    limit = int(request.args.get('limit') or 0)
    labez = request.args.get('labez') or 'all'
    mode = request.args.get('mode') or 'sim'
    include = request.args.getlist('include[]') or []
    fragments = request.args.getlist('fragments[]') or []

    view = 'affinity_view' if mode == 'rec' else 'affinity_p_view'

    where = ''
    if type_ == 'anc':
        where = ' AND older < newer'
    if type_ == 'des':
        where = ' AND older >= newer'

    if labez == 'all':
        where += " AND labez !~ '^z'"
    elif labez == 'all+lac':
        pass
    else:
        where += " AND labez = '%s'" % labez

    if 'fragments' in fragments:
        frag_where = ''
    else:
        frag_where = 'AND aff.common > aff.ms1_length / 2'

    limit = '' if limit == 0 else ' LIMIT %d' % limit

    with current_app.config.dba.engine.begin() as conn:

        passage = Passage(conn, passage_or_id)
        ms = Manuscript(conn, hs_hsnr_id)
        rg_id = passage.request_rg_id(request)

        exclude = get_excluded_ms_ids(conn, include)

        # Get the X most similar manuscripts and their attestations
        res = execute(
            conn, """
        /* get the LIMIT closest ancestors for this node */
        WITH ranks AS (
          SELECT ms_id1, ms_id2,
            rank () OVER (ORDER BY affinity DESC, common, older, newer DESC, ms_id2) AS rank,
            affinity
          FROM {view} aff
          WHERE ms_id1 = :ms_id1 AND aff.rg_id = :rg_id AND ms_id2 NOT IN :exclude
            AND newer > older {frag_where}
          ORDER BY affinity DESC
        )

        SELECT r.rank,
               aff.ms_id2 as ms_id,
               ms.hs,
               ms.hsnr,
               aff.ms2_length,
               aff.common,
               aff.equal,
               aff.older,
               aff.newer,
               aff.unclear,
               aff.common - aff.equal - aff.older - aff.newer - aff.unclear as norel,
               CASE WHEN aff.newer < aff.older THEN ''
                    WHEN aff.newer = aff.older THEN '-'
                    ELSE '>'
               END as direction,
               aff.affinity,
               a.labez,
               a.certainty
        FROM
          {view} aff
        JOIN apparatus_view_agg a
          ON aff.ms_id2 = a.ms_id
        JOIN manuscripts ms
          ON aff.ms_id2 = ms.ms_id
        LEFT JOIN ranks r
          ON r.ms_id2 = aff.ms_id2
        WHERE aff.ms_id2 NOT IN :exclude AND aff.ms_id1 = :ms_id1
              AND aff.rg_id = :rg_id AND aff.common > 0
              AND a.pass_id = :pass_id {where} {frag_where}
        ORDER BY affinity DESC, r.rank, newer DESC, older DESC, hsnr
        {limit}
        """,
            dict(parameters,
                 where=where,
                 frag_where=frag_where,
                 ms_id1=ms.ms_id,
                 hsnr=ms.hsnr,
                 pass_id=passage.pass_id,
                 rg_id=rg_id,
                 limit=limit,
                 view=view,
                 exclude=exclude))

        Relatives = collections.namedtuple(
            'Relatives',
            'rank ms_id hs hsnr length common equal older newer unclear norel direction affinity labez certainty'
        )
        return csvify(Relatives._fields, list(map(Relatives._make, res)))
Ejemplo n.º 35
0
Archivo: main.py Proyecto: devolt5/ntg
def manuscript_full_json(passage_or_id, hs_hsnr_id):
    """Endpoint.  Serve information about a manuscript.

    :param string hs_hsnr_id: The hs, hsnr or id of the manuscript.

    """

    auth()

    hs_hsnr_id = request.args.get('ms_id') or hs_hsnr_id

    with current_app.config.dba.engine.begin() as conn:
        passage = Passage(conn, passage_or_id)
        ms = Manuscript(conn, hs_hsnr_id)
        rg_id = passage.request_rg_id(request)

        if ms.ms_id is None:
            return cache(
                make_json_response(None, 400,
                                   'Bad request: No such manuscript.'))

        json = ms.to_json()
        json['length'] = ms.get_length(rg_id)

        # Get the attestation(s) of the manuscript (may be uncertain eg. a/b/c)
        res = execute(
            conn, """
        SELECT labez, clique, labez_clique, certainty
        FROM apparatus_view_agg
        WHERE ms_id = :ms_id AND pass_id = :pass_id
        """, dict(parameters, ms_id=ms.ms_id, pass_id=passage.pass_id))

        row = res.fetchone()
        if row is not None:
            json['labez'], json['clique'], json['labez_clique'], json[
                'certainty'] = row

        # Get the affinity of the manuscript to all manuscripts
        res = execute(
            conn, """
        SELECT avg (a.affinity) as aa,
        percentile_cont(0.5) WITHIN GROUP (ORDER BY a.affinity) as ma
        FROM affinity a
        WHERE a.ms_id1 = :ms_id1 AND a.rg_id = :rg_id
        """, dict(parameters, ms_id1=ms.ms_id, rg_id=rg_id))

        json['aa'], json['ma'] = 0.0, 0.0
        row = res.fetchone()
        if row is not None:
            json['aa'], json['ma'] = row

        # Get the affinity of the manuscript to MT
        #
        # For a description of mt and mtp see the comment in
        # ActsMsListValPh3.pl and
        # http://intf.uni-muenster.de/cbgm/actsPh3/guide_en.html#Ancestors

        res = execute(
            conn, """
        SELECT a.affinity as mt, a.equal::float / c.length as mtp
        FROM affinity a
        JOIN ms_ranges c
          ON (a.ms_id1, a.rg_id) = (c.ms_id, c.rg_id)
        WHERE a.ms_id1 = :ms_id1 AND a.ms_id2 = 2 AND a.rg_id = :rg_id
        """, dict(parameters, ms_id1=ms.ms_id, rg_id=rg_id))

        json['mt'], json['mtp'] = 0.0, 0.0
        row = res.fetchone()
        if row is not None:
            json['mt'], json['mtp'] = row

        return cache(make_json_response(json))
Ejemplo n.º 36
0
Archivo: main.py Proyecto: devolt5/ntg
def suggest_json():
    """Endpoint.  The suggestion drop-downs in the navigator.

    Serves a list of books, chapters, verses, or words that the user can enter
    in the navigation gadget.  It suggests only entities that are actually in
    the database.

    """

    auth()

    # the name of the current field
    field = request.args.get('currentfield')

    # the term the user entered in the current field
    term = request.args.get('term') or ''
    term = '^' + re.escape(term.split('-')[0])

    # terms entered in previous fields
    siglum = request.args.get('siglum') or ''
    chapter = request.args.get('chapter') or 0
    verse = request.args.get('verse') or 0

    Words = collections.namedtuple(
        'Words', 'kapanf, versanf, wortanf, kapend, versend, wortend, lemma')

    res = []
    with current_app.config.dba.engine.begin() as conn:

        if field == 'siglum':
            # only show those books that actually are in the database
            res = execute(
                conn, """
            SELECT DISTINCT siglum, siglum, book, bk_id
            FROM passages_view b
            WHERE siglum ~ :term OR book ~ :term
            ORDER BY bk_id
            """, dict(parameters, term=term))
            return flask.json.jsonify([{
                'value': r[0],
                'label': r[1],
                'description': r[2]
            } for r in res])

        if field == 'chapter':
            res = execute(
                conn, """
            SELECT range, range
            FROM ranges_view
            WHERE siglum = :siglum AND range ~ '[1-9][0-9]*' AND range ~ :term
            ORDER BY range::integer
            """, dict(parameters, siglum=siglum, term=term))
            return flask.json.jsonify([{
                'value': r[0],
                'label': r[1]
            } for r in res])

        if field == 'verse':
            res = execute(
                conn, """
            SELECT DISTINCT verse, verse
            FROM passages_view
            WHERE variant AND siglum = :siglum AND chapter = :chapter AND verse::varchar ~ :term
            ORDER BY verse
            """, dict(parameters, siglum=siglum, chapter=chapter, term=term))
            return flask.json.jsonify([{
                'value': r[0],
                'label': r[1]
            } for r in res])

        if field == 'word':
            res = execute(
                conn, """
            SELECT chapter, verse, word,
                            adr2chapter (p.endadr), adr2verse (p.endadr), adr2word (p.endadr),
                            COALESCE (string_agg (n.lemma, ' ' ORDER BY n.begadr), '') as lemma
            FROM passages_view p
            LEFT JOIN nestle n
              ON (p.passage @> n.passage)
            WHERE variant AND siglum = :siglum AND chapter = :chapter AND verse = :verse AND word::varchar ~ :term
            GROUP BY chapter, verse, word, p.endadr
            ORDER BY word, adr2verse (p.endadr), adr2word (p.endadr)
            """,
                dict(parameters,
                     siglum=siglum,
                     chapter=chapter,
                     verse=verse,
                     term=term))
            res = map(Words._make, res)
            res = map(_f_map_word, res)
            return flask.json.jsonify([{
                'value': r[0],
                'label': r[1],
                'description': r[2]
            } for r in res])

    return flask.json.jsonify([])
Ejemplo n.º 37
0
def comparison_summary_csv ():
    """Endpoint. Serve a CSV table. (see also :func:`comparison_summary`)"""

    auth ()

    return csvify (_ComparisonRowCalcFields._fields, comparison_summary ())
Ejemplo n.º 38
0
if __name__ == '__main__':
    uname = raw_input("\033[32;1musername: \033[0m")
    error_count = 0  # 错误次数
    count = 0  # 用于控制提供用户名和密码输入口的重复次数

    while error_count < 3 and count < 10:
        passwd = raw_input("password: "******"the user:%s is locked" % uname
            break

        # 用户认证环节,分三种情况:用户不存在,用户密码都输对,用户存在但密码输错
        mark = login.auth(uname, passwd)
        if mark == '0':
            print 'not find the user:'******'username: '******'11':
            print 'Welcome ~~~'
            break
        else:
            print 'Your password is wrong,plz input again.'
            error_count += 1
            # 如果密码输错三次,则将该账号写进锁文件中
            if error_count == 3:
                f3 = open('../file/account_lock.txt', 'a+')
                f3.write("%s\n" % uname)  # 将被锁的用户写入锁文件
                f3.close()
Ejemplo n.º 39
0
import login

# Take username
username = input("Enter a username: "******"Enter a password: "******"Login Successful")

# Name was found but password was invalid
elif logAtt == 'bad pass':

    # 3 additional tries allowed
    for i in range(0, 3):
        print(f"Incorrect: {3-i} tries remaining")
        password = input("Enter a password: "******"Login Successful")
            break

        # Password was incorrect
        else:

            # Attempts ran out
            if i == 2:
Ejemplo n.º 40
0
# Imports
import getpass
import login as LoginClient
import entry as EntryClient
import gen as QRClient
import selector as SelectionTool

print("Welcome to the QueensQR Data Entry Utility")
print("Please Login")

# Login database user
usr = input("username: "******"password: "******"\n")
    mongo = LoginClient.auth(usr, pwd)
except Exception as err:
    print("Login Error", err)
else:
    pass

print(mongo)
print("\n")
print("Logged in")

# Get DB object and collection of buildings

db = mongo.apscm3

collection = db.buildings