Пример #1
0
def login():
    data = request.json

    if data:
        dataDict = json.loads(json.dumps(data))
        if 'user' in dataDict and 'pass' in dataDict:
            cnx, cur = helper.start()
            query = 'SELECT `id` FROM Client WHERE `username`=%s AND `password`=%s'
            cur.execute(query, (dataDict['user'], dataDict['pass']))
            theid = cur.fetchone()
            helper.stop(cnx, cur)

            if theid[0] > 0:
                if dataDict['booking']:
                    # deal with booking
                    cnx, cur = helper.start()
                    query = 'SELECT MAX(id) FROM Booking WHERE `client` = %s AND `start_time` >= %s'
                    cur.execute(query, (theid[0], datetime.datetime.now()))
                    ids = cur.fetchone()
                    helper.stop(cnx, cur)

                    return Response(json.dumps({'bookings': ids}),
                                    status=200,
                                    mimetype='application/json')
                else:
                    return Response(status=200)
            else:
                return helper.error()
        else:
            return helper.error()
    else:
        return helper.error()
Пример #2
0
def _extract_words(f_name):
    """
    Index and count the words in a raw data file.
    :param f_name: the raw data file
    :return: the word:index dict, the index:word dict, and the word count
    """
    word_dict = {}
    idx_dict = {}
    word_cnt = []
    wc = 0
    if os.path.isfile(f_name):
        with open(f_name) as f:
            for line in f:
                obj = json.loads(line)
                # process words in the text
                for t in _extract(obj["text"]):
                    # update the word counts
                    if t not in word_dict:
                        word_dict[t] = wc
                        idx_dict[wc] = t
                        wc += 1
                        word_cnt.append(1)
                    else:
                        word_cnt[word_dict[t]] += 1
        return word_dict, idx_dict, word_cnt
    else:
        error("parse dict - not a file: %s" % f_name)
Пример #3
0
    def copyResNoOverwrite(self, src, dst):
        if not os.path.exists(src):
            helper.error("src folder not exist: " + src)

        if not os.path.exists(dst):
            helper.error("dst folder not exist: " + dst)

        files = os.listdir(src)
        if not files:
            return

        for item in files:
            srcItem = src + '/' + item
            dstItem = dst + '/' + item

            if os.path.isdir(srcItem):
                if not os.path.exists(dstItem):
                    os.mkdir(dstItem)

                buildLog("copy dir: " + srcItem + " to " + dstItem)
                self.copyResNoOverwrite(srcItem, dstItem)

            elif os.path.isfile(srcItem):
                if not os.path.exists(dstItem):
                    helper.watchExecuteCommand('cp', srcItem + ' ' + dstItem)
                else:
                    buildLog("skip exist item: " + dstItem)

        return
Пример #4
0
def _main(model, dataset):
    """
    The main procedure for making predictions
    :param model: the name of the model used
    :param dataset: train or dev or test
    :return: None
    """
    # check the parameters passed
    if model not in ["baseline", "hashing", "cluster"] \
            or dataset not in ["train", "dev", "test"]:
        _usage()
    # the model file
    model_file = "models/model_%s.txt" % model
    # the data file
    data_file = "datasets/yelp_reviews_%s_%s.txt" % (dataset, model)
    if not os.path.isfile(data_file):
        error("predict main - not a file: %s" % dataset)

    # parse the data
    x, y = parse_matrix(data_file)
    # parse the model
    w = parse_model(model_file)
    # init the classifier
    rmlr = RMLRClassifier(w=w)
    # make predictions
    hard, soft = rmlr.predict(x)
    # write the results to file
    _write_to_file(model, dataset, hard, soft)
    # if testing on the training set, report the evaluation results
    if dataset == "train":
        y = np.asarray(np.argmax(y.todense(), 1))
        accu = np.sum(y == hard) / float(y.shape[0])
        rmse = np.sqrt((y - soft).T * (y - soft) / y.shape[0])
        print accu, rmse
Пример #5
0
def hwInterface(func):
    if func != top.name:
        ftemp = helper.fileOpen(buildDir + "/ss_" + func +
                                "/solution1/syn/vhdl/" + func + ".vhd")
    else:
        ftemp = helper.fileOpen(buildDir + "/ds_" + func + "/" + func + ".vhd")
    startLine = -1
    endLine = -1
    buff = []
    i = 0
    for line in ftemp:
        if "entity " + func + " is" in line:
            startLine = i + 2
            break
        i = i + 1
    i = 0
    ftemp.seek(0)
    for line in ftemp:
        if "end;" in line:
            endLine = i
            break
        if i >= startLine:
            buff.append(line)
        i = i + 1
    if startLine == -1 or endLine == -1:
        helper.error(
            "Error: Cannot find entity declaration of the top function (" +
            str(startLine) + ", " + str(endLine) + ")")
        assert 0
    i = startLine
    temp = hwPort()
    temp.begin = startLine
    temp.end = endLine
    temp.buff = buff
    return temp
Пример #6
0
    def __init__(self, package, pins, meta):
        self.meta = meta
        
        package = package.strip()
        self.pins = pins
        self.data = dict()

        try:
            f = open("packages/{0}".format(package))
        except:
            error("can not find package '{0}'".format(package))
            return
        ### let's parse the file
        self.definition=dict(pin=None, c=None, ch=None, e=None, name="-")
        for line in f.read().split("\n"):
            if line.strip() == "":
                continue
            if line[0] == "#":
                continue
            key, value = line.split(" ", 1)
            key = key[1:]
            if key.lower() in self.definition:
                self.definition[key.lower().strip()] = value.strip()
            else:
                error("Package: '{0}' not a definition".format(key))
Пример #7
0
    def register(self):
        if self.logged():
            return error("You are already logged")

        email = request.values.get("email")
        password = request.values.get("password")
        fname = request.values.get("fname")
        lname = request.values.get("lname")
        role = request.values.get("role")
        avatar = request.values.get("avatar")
        status = request.values.get("status")

        if (not (type(email) is unicode)) or (len(email) < 5):
            return error("Incorrect e-mail")

        if (not (type(password) is unicode)) or (len(password) < 5):
            return error("Incorrect password")

        if self._data.exists(email):
            return error("User with this e-mail already exists")

        try:
            self._data.add({"email": email,
                            "password": sha512(password),
                            "fname": fname,
                            "lname": lname,
                            "role": role,
                            "avatar": avatar,
                            "status": status})
            return write("Well done")
        except:
            return error("Registration failed")
Пример #8
0
def parse_matrix(f_name):
    """
    Parse the data (x's and y's) and return them as scipy csr sparse matrices.
    :param f_name: the file containing x vectors and y
    :return: x, y as scipy csr sparse matrices.
    """
    if os.path.isfile(f_name):
        rat_x = []
        rat_y = []
        rat_data = []
        cnt_x = []
        cnt_y = []
        cnt_data = []
        with open(f_name) as f:
            for i, line in enumerate(f):
                rat, vec = line.split("\t")
                if vec.strip() == "":
                    continue
                rat_x.append(i)
                rat_y.append(0 if int(rat) == 0 else int(rat) - 1)
                rat_data.append(1)
                for idx, cnt in [(ic.split(":"))
                                 for ic in vec.strip().split(" ")]:
                    cnt_x.append(i)
                    cnt_y.append(idx)
                    cnt_data.append(int(cnt))
        x = sparse.csr_matrix((cnt_data, (cnt_x, cnt_y)))
        y = sparse.csr_matrix((rat_data, (rat_x, rat_y)))
        return x, y
    else:
        error("parse matrix - not a file: %s" % f_name)
Пример #9
0
    def all(self):
        if not self.logged():
            return error("You not logged")

        try:
            return write(self._data.all())
        except:
            return error("Invalid request")
Пример #10
0
 def get_submodules(self, module=None):
     if module is None:
         if self.last_module is None:
             hlp.error(custom_msg='No module added in database yet!', fatal=False)
             return None
         else:
             module = self.last_module
     return self.design[module]['submodules']
Пример #11
0
    def delete(self):
        if not self.logged():
            return error("You not logged")

        try:
            id = int(request.values.get("id"))
            self._data.delete(id)
            return write("Well done")
        except:
            return error("Invalid request")
Пример #12
0
 def addLine(self, line):
     m = re.match("^([\d]+)\s*->\s*\$([\d]+)\s*$", line)
     if not m:
         splitedLine = line.split(" ", 1)
         name = splitedLine[1].strip()
         if name != "NC":
             error("can not define new pins here, just NC or references to existing ones")
         self.addPin(int(splitedLine[0]), None)
     else:
         self.addPin(*map(int, m.groups()))
Пример #13
0
def dump(node, indLvl=0, *, ctx: Ctx = Ctx.default, recursive=False):
    if node == ...:
        return ind('`WFE', indLvl)
    if isinstance(node, chipo.AstStatement):
        assert False, h.error("undefined dump(AstStatement)", node)
    elif isinstance(node, chipo.AstProcStatement):
        assert False, h.error("undefined dump(AstProcStatement)", node)
    elif isinstance(node, chipo.AstNode):
        assert False, h.error("undefined dump(AstNode)", node)
    elif isinstance(node, chipo.Type):
        assert False, h.error("undefined dump(Type)", node)
    assert False, h.error("unhandled dump case", node)
Пример #14
0
    def get(self, param):
        if not self.logged():
            return error("You not logged")

        try:
            if type(param) is int:
                return write(self._data.get(param))
            elif type(param) is unicode:
                return write(self._data.get(param))
            else:
                return write(self._data.get(session["email"]))
        except:
            return error("Invalid request")
Пример #15
0
 def getSide(self, side):
     if side not in "TLRB":
         error("pffff!")
     if self.data.values() == [[],[],[],[]]:
         count = len(self.pins.data)
         halfe = count/2
         if side == "L":
             return range(1,halfe+1)
         elif side == "R":
             return range(halfe+1,count+1)[::-1]
         elif side == "T":
             return [None]*4
     return self.data[side]
Пример #16
0
def _main(model):
    """
    Main procedure for training.
    The trained model will be written to files
    :param model: baseline or hashing or cluster
    :return: None.
    """
    train_file = "datasets/yelp_reviews_train_%s.txt" % model
    if not os.path.isfile(train_file):
        error("train main - not a file: %s" % train_file)
    x, y = parse_matrix(train_file)
    rmlr = RMLRClassifier(x, y)
    rmlr.train()
    _write_to_file(rmlr.get_w(), model)
Пример #17
0
    def login(self):
        if self.logged():
            return error("You are already logged")

        email = request.values.get("email")
        password = request.values.get("password")

        if email is not None and \
           password is not None and \
           self._data.valid(email, sha512(password)):
            session["email"] = email
            return write("Well done")
        else:
            return error("Incorrect login or password")
Пример #18
0
def parse_model(f_name):
    """
    Parse the parameters (w's) and return a (5 by m) numpy matrix.
    :param f_name: the file containing the model
    :return: a (5 by m) numpy matrix
    """
    if os.path.isfile(f_name):
        with open(f_name) as f:
            w = [[], [], [], [], []]
            for i, line in enumerate(f):
                for v in line.strip().split(" "):
                    w[i].append(float(v))
            return np.matrix(w)
    else:
        error("parse model - not a file: %s" % f_name)
Пример #19
0
def register_user():
    if request.method == "GET":
        return render_template("authentication/register.html")
    elif request.method == "POST":
        nivel = 1
        if not request.form.get('cuil'):
            return error("Revise el cuil e intente nuevamente")
        if not request.form.get('username'):
            return error("Revise el username e intente nuevamente")
        if not request.form.get('reparticion'):
            return error("Revise la reparticion e intente nuevamente")
        if not request.form.get('email'):
            return error("Revise el email e intente nuevamente")
        if not request.form.get('nombre'):
            return error("Revise el nombre e intente nuevamente")
        if not request.form.get('apellido'):
            return error("Revise el apellido e intente nuevamente")
        try:
            if session["rol"] != 3:
                rol = 1
            else:
                rol = request.form.get('rol')
            cuil = request.form.get('cuil'),
            username = request.form.get('username'),
            password = generate_password_hash(request.form.get('password')),
            reparticion = request.form.get('reparticion'),
            email = request.form.get('email'),
            nombre = request.form.get('nombre'),
            apellido = request.form.get('apellido'),
            rol = rol,
            nivel = nivel
            register_query(cuil, username, password, reparticion, email,
                           nombre, apellido, rol, nivel)
            body = "This is message from" + request.form.get("email") + "\r\n"
            html = """<html>
            <p style='margin: 0px 0px 8px; text-overflow: ellipsis; overflow-wrap: break-word; color: rgb(23, 43, 77); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Ubuntu, "Droid Sans", "Helvetica Neue", sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;'>Desde la Secretar&iacute;a de Modernizaci&oacute;n comunicamos que fue habilitado para la capacitaci&oacute;n en la Plataforma GDE Training.</p>
            <p style='margin: 0px 0px 8px; text-overflow: ellipsis; overflow-wrap: break-word; color: rgb(23, 43, 77); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Ubuntu, "Droid Sans", "Helvetica Neue", sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;'>Para ingreso&nbsp;<a href="https://www.gdetraining.com/" rel="noreferrer nofollow" style="background-color: transparent; color: rgb(23, 43, 77);" target="_blank">https://www.gdetraining.com/</a><br>Usuario:""" + request.form.get(
                'username') + """<br>Clave:""" + request.form.get(
                    'password') + """</p>
            <p style='margin: 0px 0px 8px; text-overflow: ellipsis; overflow-wrap: break-word; color: rgb(23, 43, 77); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Ubuntu, "Droid Sans", "Helvetica Neue", sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;'>La capacitaci&oacute;n finaliza el 25 de febrero del corriente a&ntilde;o, espacio en el cu&aacute;l deber&aacute; completar todas las actividades requeridas.</p>
            <p style='margin: 0px; text-overflow: ellipsis; overflow-wrap: break-word; color: rgb(23, 43, 77); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Ubuntu, "Droid Sans", "Helvetica Neue", sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;'>Canales de comunicaci&oacute;n para acceder a tutores<br>What app 388 4383563 7-13h d&iacute;as laborables<br>Mail&nbsp;<a href="mailto:[email protected]" style="background-color: transparent; color: rgb(23, 43, 77);">[email protected]</a></p>
            </html>"""
            subject = 'Confirmacion de registro Secretaria de modernizacion'
            recipient = request.form.get("email")
            try:
                send_email(body, html, subject, recipient)
            except:
                error(
                    "Hubo un error al enviar el mail. Enviarlo manualmente o revisar el mail"
                )
            return redirect(url_for("cursos"))
        except:
            return error("Revise los campos e intente nuevamente")
Пример #20
0
 def expand(self):
     if self.logic_ is None:
         if self.name is None:
             raise ValueError(helper.error('An Fsm must be named', self))
         self.oprefix = "SM_" + self.name.upper() + "_"
         if self.behav:  # non synthesizable, if need to debug generation
             rstLst = (x <= x.default for x in self.body.assigned())
             rstLst = sorted(rstLst, key=lambda x: x.lhs.name)
             loopName = f"_loop"
             clocked = chipo.Clocked(self.clock,
                                     self.reset,
                                     name=f"{self.name}_clocked")
             clocked += \
                 chipo.Block(
                     chipo.If(self.reset.offExpr())[
                         chipo.Block(
                             chipo.While(1)[
                                 tuple(self.body.stmts),
                                 ...
                             ], name=loopName)
                     ],
                     *rstLst,
                     ...,
                 )
             clocked.hasWfe = True
             clocked.autoReset = False
             self.logic_ = clocked
         else:  # synthesizable output
             self.body = chipo.Block(
                 chipo.While(1).Do(..., *self.body.stmts))
             self.root = self.toDAG()
             self.mergeStates(self.root)
             self.logic_ = self.dumpTree(self.root)
     return self.logic_
Пример #21
0
 def delete_specific_issue(self, issue_id=None):
     if not self.logged():
         return error("You not logged")
     new_issue = {}
     new_issue["issues.$.status"] = "removed"
     self._data.update_issue(backlog_id=1, issue_id=issue_id, new_issue=new_issue)
     return self.get_specific_issue(issue_id)
Пример #22
0
def _parse_word_dict(dict_f_name):
    """
    Read in the dictionary file and convert the dictionary
    to a python dict
    :param dict_f_name: dictionary file
    :return: dict of the dictionary { word: index, ... }
    """
    if os.path.isfile(dict_f_name):
        word_dict = {}
        with open(dict_f_name) as f:
            for line in f:
                w, idx = line.strip().split(" ")
                word_dict[w.strip()] = int(idx)
        return word_dict
    else:
        error("Dict not exists: %s" % dict_f_name)
Пример #23
0
def _parse_json(model, f_name):
    """
    Parse the raw data into its sparse matrix representation format
    using the precomputed dictionary, and write the results to a file.
    :param model: whether baseline or hashing
    :param f_name: the json file to be parsed
    :return: None.
    """
    # get the word index dictionary corresponding to the feature model type
    if model == "baseline":
        word_dict = _parse_word_dict("baseline_dict.txt")
    elif model == "hashing":
        word_dict = _parse_word_dict("hashing_dict.txt")
    elif model == "cluster":
        word_dict = _parse_word_dict("cluster_dict.txt")
    else:
        error("Unknown model type %s" % model)

    if os.path.isfile(f_name):
        if _svm:
            model += "svm"
        out = open(
            "datasets/%s_%s.txt" %
            (f_name[f_name.rfind("/") + 1:].split(".")[0], model), "w")
        with open(f_name) as f:
            for line in f:
                obj = json.loads(line)
                txt = obj["text"]
                rat = obj["stars"] if "stars" in obj else 0
                out.write("%d \t" % rat)
                features = []
                for t in _extract(txt):
                    if t in word_dict:
                        while len(features) <= word_dict[t]:
                            features.append(0)
                        features[word_dict[t]] += 1
                for i, c in enumerate(features):
                    if c == 0:
                        continue
                    if _svm:
                        i += 1
                    out.write("%d:%d " % (i, c))
                out.write("\n")
        out.close()
    else:
        error("parse json - not a file: %s" % f_name)
Пример #24
0
def _stopwords():
    """
    Read the stop words file, and return a set of stop words.
    :return: a set of stop words.
    """
    global _stopword_set
    if _stopword_set:
        return _stopword_set
    f_name = "stopword.list"
    if os.path.isfile(f_name):
        res = set()
        with open(f_name) as f:
            for line in f:
                res.add(line.strip())
        _stopword_set = res
        return res
    else:
        error("stop words - not a file: %s" % f_name)
Пример #25
0
    def change(self):
        if not self.logged():
            return error("You not logged")

        user = {"email": request.values.get("email"),
                "password": request.values.get("password"),
                "fname": request.values.get("fname"),
                "lname": request.values.get("lname"),
                "role": request.values.get("role"),
                "avatar": request.values.get("avatar"),
                "status": request.values.get("status")}

        try:
            id = int(request.values.get("id"))
            self._data.edit(id, user)
            return write("Well done")
        except:
            return error("Invalid request")
Пример #26
0
    def update_specific_issue(self, param=None, issue_id=None):
        if not self.logged():
            return error("You not logged")
        new_issue = {}

        for key, value in param.items():
            new_issue["issues.$."+key] = value

        self._data.update_issue(backlog_id=1, issue_id=issue_id, new_issue=new_issue)
        return self.get_specific_issue(issue_id)
Пример #27
0
def login():
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        #Check if user exists
        if User.query.filter_by(username=username).first() != None:
            user = User.query.filter_by(username=username).first()
            #Check if password matches
            queried_hash = user.passwordhash
            if checkpassword(password,queried_hash) == True:
                login_user(user,remember=True,duration = timedelta(days=10))
                return redirect("/")
            else:
                return error("Wrong Password")

        else:
            return error("Cannot match username")

    else:
        return render_template("login.html")
Пример #28
0
def parse(fileName):
    f = file(fileName)
    data = f.read()

    metaTopics = ["NAME", "TAGS"]
    topics = metaTopics + ["PINS", "PACKAGE", "SCHEMATIC"]

    meta = Meta()
    pins = Pins(meta)
    packages = []
    schematic = Schematic(pins, meta)

    for line in data.split("\n"):
        line = line.strip()
        if len(line) == 0:
            continue
        if line[0] == "#":
            continue
        if line[0] == '*':
            splitedLine = line[1:].split(" ")
            topic = splitedLine[0]
            if len(splitedLine) != 0:
                data = " ".join(splitedLine[1:]).split(",")
            else:
                data = []
            if topic not in topics:
                error("%s: topic not known" % topic)

            if topic in metaTopics:
                meta.addData(topic, data)
            elif topic == "PINS":
                currentTopic = pins
            elif topic == "PACKAGE":
                currentTopic = Package(data[0], pins, meta)
                packages.append(currentTopic)
            elif topic == "SCHEMATIC":
                currentTopic = schematic
        else:
            currentTopic.addLine(line)

    return meta, packages, schematic
Пример #29
0
def fingerprint(stl_file, num_of_slices, num_of_peaks_to_keep, fan_value,
                rotation, interp, star_rotate):
    """
    Generate the fingerprint of a STL file and store it in the hash table.
    stl_file            : STL input file name.
    num_of_slices       : Number of slices to split the STL file to
    num_of_peaks_to_keep: Number of peaks to keep after filtering the rest out
    fan_value           : Degree to which a fingerprint can be paired with its neighbors
    """
    # Parse STL and interpolate points
    points_array = stl_to_points_array(stl_file, interp)
    # Scale points
    scaled_points_array = scale_points(points_array, _hp.GRID_SIZE)
    # Find the signatures for each axis in parallel
    neighborhood_dict = mp.Manager().dict()
    processes = []
    for axis in _hp.Axis:
        total_rotations = 1
        if rotation:
            total_rotations = 4
        for rot90_times in range(total_rotations):
            # parallel_slice_fft_and_hash( axis, scaled_points_array, num_of_peaks_to_keep, num_of_slices, fan_value, neighborhood_dict, rot90_times, star_rotate )
            p = mp.Process(target=parallel_slice_fft_and_hash,
                           args=(axis, scaled_points_array,
                                 num_of_peaks_to_keep, num_of_slices,
                                 fan_value, neighborhood_dict, rot90_times,
                                 star_rotate))
            processes.append(p)
            p.start()
    # Join the processes
    for p in processes:
        p.join()
    neighborhoods = neighborhood_dict
    _hp.log('len(neighborhoods): ' + str(len(neighborhoods)))
    if len(neighborhoods) == 0:
        print()
        _hp.error(
            'No signatures generated. Try either decreasing the fan-value or increasing the number of slices.'
        )
    # Return the list of hashes
    return neighborhoods
Пример #30
0
def lounger_info():
    data = request.json

    if data:
        dataDict = json.loads(json.dumps(data))
        if 'id' in dataDict:
            if dataDict['id'] > 0:
                info = lounger.getLoungerInfo(dataDict['id'])
                if info:
                    return Response(json.dumps({'lounger': {
                        info[0]: info[1]
                    }}),
                                    status=200,
                                    mimetype='application/json')
                else:
                    return error()
            else:
                return error()
        else:
            return error()
    else:
        return error()
Пример #31
0
def sendConsulta():
    try:
        body = "Este mensaje fue enviado por: " + session['email'] + "\r\n"
        html = """<html>
            <h5>Duda o Consulta:</h5> """ + session['email'] + """
            </html>
            """ + request.form.get("textArea")
        subject = request.form.get("asunto")
        recipient = "*****@*****.**"
        send_email(body, html, subject, recipient)
        return exito("Su mensaje fue enviado con exito")
    except:
        return error("Revise los campos e intente nuevamente")
Пример #32
0
def register():
    if request.method == "POST":
        username = request.form.get("username")
        user = User(username = username,passwordhash = hashpassword(request.form.get("password")))
        print(User.query.filter_by(username = username).first())
        if User.query.filter_by(username = username).first() == None:
            db.session.add(user)
            db.session.commit()
            return redirect("/")
        else:
            return error("Username already exists. Please select another username")
    else:
        return render_template("/register.html")
Пример #33
0
    def checkBuildEnv(self):
        # android environment
        self.repoDir = self.sdkDir + '/extras/android/m2repository'

        self.androidJar = self.sdkDir + '/platforms/android-' + self.target + '/android.jar'

        buildLog('androidJar path: ' + self.androidJar)

        if not os.path.isfile(self.androidJar):
            helper.error('Target: ' + self.target + ' is not installed')

        # build tools
        buildToolDir = self.sdkDir + '/build-tools/' + self.tools

        if not os.path.exists(buildToolDir):
            helper.error('no build tools find: ' + buildToolDir)

        print('build tools-dir:' + str(buildToolDir))

        self.buildToolDir = buildToolDir
        self.toolsDir = self.sdkDir + '/tools'

        self.aapt = self.buildToolDir + '/aapt'
        self.dx = self.buildToolDir + '/dx'
        self.zipalign = self.buildToolDir + '/zipalign'

        if not os.path.isfile(self.aapt):
            helper.error('aapt is not exist: ' + self.aapt)

        if not os.path.isfile(self.dx):
            helper.error('dx is not exist: ' + self.dx)

        if not os.path.isfile(self.zipalign):
            helper.error('zipalign is not exist: ' + self.aapt)

        helper.watchExecuteCommand('which', 'javac')
        helper.watchExecuteCommand('which', 'jarsigner')
        return
Пример #34
0
def sendMail():
    try:
        body = "This is message from" + request.form.get("email") + "\r\n"
        html = """<html>
            <h5>Mail del usuario que realizo la consulta:</h5> """ + request.form.get(
            "email") + """
            </html>
            """ + request.form.get("textArea")
        subject = request.form.get("asunto")
        recipient = '*****@*****.**'
        send_email(body, html, subject, recipient)
        return exito("Su mensaje fue enviado con exito")
    except:
        return error("Revise los campos e intente nuevamente")
Пример #35
0
def _clz_word_mat(f_name):
    """
    Generate the matrix which is the input to clustering.
    The matrix is 10000 by 5 (number of words, number of ratings).
    The matrix will be written to the file rating_words_condense.txt
    in sparse matrix format.
    :param f_name: the raw json file
    :return: None
    """
    if os.path.isfile(f_name):
        # parse the dictionary containing the top 10000 words
        word_dict = _parse_word_dict("10000word_dict.txt")
        # rating dimension
        x = []
        # word dimension
        y = []
        # occurrence
        data = []
        with open(f_name) as f:
            for line in f:
                obj = json.loads(line)
                txt = obj["text"]
                if "stars" not in obj:
                    raise ValueError("rating doesn't exist.")
                rat = obj["stars"]
                for t in _extract(txt):
                    if t in word_dict:
                        x.append(word_dict[t])
                        y.append(rat - 1)
                        data.append(1)
        A = sparse.coo_matrix((data, (x, y))).tocsr()
        with open("rating_words_condense.txt", "w") as f:
            for i, j in zip(A.nonzero()[0], A.nonzero()[1]):
                # word index, rating, count
                f.write("%d %d %d\n" % (i, j, A[i, j]))
    else:
        error("class word matrix - not a file: %s" % f_name)
Пример #36
0
    def add_subissue(self, issue_id, param=None):
        if not self.logged():
            return error("You not logged")
        new_subissue = dict(
            name=param.get("name") if param.get("name") else "",
            description=param.get("description") if param.get("description") else "",
            assign_to=param.get("assign_to") if param.get("assign_to") else "",
            kind=param.get("kind") if param.get("kind") else "",
            status=param.get("status") if param.get("status") else "",
            comments=param.get("comments") if param.get("comments") else list(),
            estimate=param.get("estimate") if param.get("estimate") else None,
        )

        _subissue_id = self._data.create_subissue(166, issue_id, new_subissue)
        return self.get_specific_subissue(issue_id, _subissue_id)
Пример #37
0
def login():
    username = request.form.get("username")
    if request.method == "POST":
        user = login_query(username)
        if len(user) != 1 or not check_password_hash(
                user[0]["usu_Password"], request.form.get("password")):
            return error("Revise los campos e intente nuevamente")
        session["user_id"] = user[0]["usu_Id"]
        session['logged_in'] = True
        session['rol'] = user[0]["usu_Rol"]
        session['email'] = user[0]["usu_Email"]
        session['nivel'] = user[0]["usu_Nivel"]
        return redirect("/")
    elif request.method == "GET":
        return render_template("authentication/login.html")
Пример #38
0
    def add(self, param=None):
        if not self.logged():
            return error("You not logged")
        new_subissue = dict(
            name=param.get("name") if param.get("name") else "",
            description=param.get("description") if param.get("description") else "",
            assign_to=param.get("assign_to") if param.get("assign_to") else None,
            kind=param.get("kind") if param.get("kind") else "",
            status=param.get("status") if param.get("status") else "",
            estimate=param.get("estimate") if param.get("estimate") else None,
            parent=param.get("parent") if param.get("parent") else None,
        )

        _subissue_id = self._data.add(new_subissue)
        return self.get_by_id(_subissue_id)
Пример #39
0
 def __init__(self, clock, reset, *, keep, name=None, vld=None, rdy=None):
     varname.Named.__init__(self, name)
     self.clock, self.reset = clock, reset
     self.keep = list(keep)
     self.body = chipo.Block()
     self.vld_up = vld
     self.rdy_dn = rdy
     self.vld = chipo.Signal(1, name='vld') if vld else None
     self.rdy = chipo.Signal(1, name='rdy') if rdy else None
     if rdy and not vld:
         raise ValueError(
             helper.error("If rdy provided, vld must be provided too",
                          self))
     self.logic_ = None
     self.outs_ = None
Пример #40
0
 def add_issue(self, param=None):
     if not self.logged():
         return error("You not logged")
     new_issue = dict(
             name = param.get("name", ""),
             description = param.get("description", ""),
             kind = param.get("kind", ""),
             subissues = param.get("subissues", list()),
             status = param.get("status", ""),
             comments = param.get("comments", list()),
             sprint = param.get("sprint", None),
             estimate = param.get("estimate", None)
             )
     
     _issue_id = self._data.create_issue(1, new_issue)
     return self.get_specific_issue(_issue_id)
Пример #41
0
    def fetch(self, **kwargs):
        cid = kwargs.get("cid")
        param = kwargs.get("param")
        method = kwargs.get("method")

        if cid is None and method == "GET":
            return self.get_all()
        if cid and method == "GET":
            return self.get_by_id(cid)
        if cid is None and method == "POST":
            return self.add(param)
        if cid and method == "PUT":
            return self.edit(param, cid)
        if cid and method == "DELETE":
            return self.delete(cid)
        return error("Invalid request")
Пример #42
0
 def add_issue(self, param=None):
     if not self.logged():
         return error("You not logged")
     new_issue = dict(
             name = param.get("name") if param.get("name") else "",
             description = param.get("description") if param.get("description") else "",
             kind = param.get("kind") if param.get("kind") else "",
             subissues = param.get("subissues") if param.get("subissues") else list(),
             status = param.get("status") if param.get("status") else "",
             comments = param.get("comments") if param.get("comments") else list(),
             sprint = param.get("sprint") if param.get("sprint") else None,
             estimate = param.get("estimate") if param.get("estimate") else None
             )
     
     _issue_id = self._data.create_issue(166, new_issue)
     return self.get_specific_issue(_issue_id)
Пример #43
0
def _(node, indLvl=0, *, ctx: Ctx = Ctx.default, recursive=False):
    if len(node.elifBlock) != len(node.elifCond):
        raise TypeError(
            h.error(
                "In If/Elif/Else structure, at least one Elif has no condition",
                node))
    v = dbgStr(node) + \
        ind('if (' + dump(node.cond, ctx=ctx) + ')', indLvl) + ' ' + \
        dump(node.trueBlock, indLvl, ctx=ctx)
    for i, b in enumerate(node.elifBlock):
        v += '\n' + \
             ind('else if (' + dump(node.elifCond[i], ctx=ctx) + ')',
                 indLvl) + ' ' + dump(b, indLvl, ctx=ctx)
    if node.falseBlock.asList():
        v += "\n" + \
             ind("else ", indLvl) + dump(node.falseBlock, indLvl, ctx=ctx)
    return v
Пример #44
0
    def fetch(self, **kwargs):
        cid = kwargs.get("cid")
        param = kwargs.get("param")
        method = kwargs.get("method")

        if cid is None and method == "GET":
        	return self.get_issues()
        if cid and method == "GET":
        	return self.get_specific_issue(cid)
        if cid is None and method == "POST":
        	return self.add_issue(param)
        if cid and method == "PUT":
            return self.update_specific_issue(param, cid)
        if cid and method == "DELETE":
            return self.delete_specific_issue(cid)


        return error("Invalid request")
Пример #45
0
 def expand(self):
     if self.logic_ is None:
         if self.name is None:
             raise ValueError(helper.error('A Pipeline must be named',
                                           self))
         stages = []
         curr = []
         body = self.body.asList() + [...]
         for stm in body:
             if stm == ...:
                 stages.append(Stage(curr))
                 curr = []
             else:
                 curr.append(stm)
         self.logic_, sigs = self.processStages(stages)
         self.outs_ = helper.Struct()
         for s in sigs:
             self.outs_[s.origName] = s
     return tuple(self.logic_)
Пример #46
0
 def update_specific_issue(self, param=None, issue_id=None):
     if not self.logged():
         return error("You not logged")
     new_issue = {}
     if param.get("name"):
         new_issue["issues.$.name"] = param.get("name")
     if param.get("description"):
         new_issue["issues.$.description"] = param.get("description")
     if param.get("kind"):
         new_issue["issues.$.kind"] = param.get("kind")
     if param.get("subissues"):
         new_issue["issues.$.subissues"] = param.get("subissues")
     if param.get("status"):
         new_issue["issues.$.status"] = param.get("status")
     if param.get("sprint"):
         new_issue["issues.$.sprint"] = param.get("sprint")
     if param.get("estimate"):
         new_issue["issues.$.estimate"] = param.get("estimate")
     self._data.update_issue(backlog_id=1, issue_id=issue_id, new_issue=new_issue)
     return self.get_specific_issue(issue_id)
Пример #47
0
    def fetch(self, **kwargs):
        action = kwargs.get("action")
        param = kwargs.get("param")

        if action == "login":
            return self.login()
        elif action == "logout":
            return self.logout()
        elif action == "register":
            return self.register()
        elif action == "delete":
            return self.delete()
        elif action == "get" or action is None:
            return self.get(param)
        elif action == "change":
            return self.change()
        elif action == "all":
            return self.all()
        else:
            return error("Invalid request")
Пример #48
0
    def edit(self, param=None, subissue_id=None):  # ???
        if not self.logged():
            return error("You not logged")
        new_subissue = {}
        if param.get("name"):
            new_subissue["name"] = param.get("name")
        if param.get("description"):
            new_subissue["description"] = param.get("description")
        if param.get("assign_to"):
            new_subissue["assign_to"] = param.get("assign_to")
        if param.get("kind"):
            new_subissue["kind"] = param.get("kind")
        if param.get("status"):
            new_subissue["status"] = param.get("status")
        if param.get("estimate"):
            new_subissue["estimate"] = param.get("estimate")
        if param.get("parent"):
            new_subissue["parent"] = param.get("parent")

        self._data.edit(subissue_id, new_subissue)
        return self.get_by_id(subissue_id)
Пример #49
0
 def addLine(self, line):
     if line[0] != "$":
         print line[0]
         error("Pins: parse error at %s" % line)
     data = re.split("\s+", line[1:], 2)
     if len(data) < 2:
         error("Pins: sorry")
     elif len(data) == 2:
         num,val = data
         description = val
     elif len(data) == 3:
         num,val,description = data
     try:
         num = int(num)
     except:
         error("not a number at %s" % line)
     self.addPin(num, (val,description))
Пример #50
0
 def addLine(self, line):
     if line[0] not in "TLRB":
         error("side %s does not exist, only R, L, T, and B are valid")
     side = line[0]
     pins = line[1:].split(",")
     parsedPins = []
     for pin in pins:
         pin = pin.strip()
         if len(pin) == 0:
             parsedPins.append(None)
             continue
         if pin[0] != "$":
             error("SCHEMATIC: pins should have a $")
         try:
             num = int(pin[1:])
         except:
             error("SCHEMATIC: pins must be integers")
         parsedPins.append(num)
     self.addSide(side, parsedPins)
Пример #51
0
    def parseManifestFile(self):
        maniFile = 'src/main/AndroidManifest.xml'

        if not os.path.exists(maniFile):
            helper.error("src/main/AndroidManifest.xml")

        with open(maniFile) as mfd:
            contents = mfd.read()

        found = re.search(r'package="(com\.ljj\.fragplugin\.[^"]+)"', contents)
        if not found:
            helper.error('not package name found in manifest file')

        print('plugin package: ' + found.group(1))

        self.package = found.group(1)
        if os.path.basename(self.package.replace('.',
                                                 '/')) != pluginPackageName:
            helper.error('The fold name: ' + pluginName +
                         ' NOT equal to plugin name: ' + self.package)

        return
Пример #52
0
def arrayExtr(func):
    ftemp = helper.fileOpen(buildDir + "/" + func + ".cpp")
    for line in ftemp:
        if " " + func + "(" in line.replace(
                "\t", "") or " " + func + " " in line.replace("\t", ""):
            break
    ftemp.close()
    if " " + func + "(" not in line.replace(
            "\t", "") and " " + tfunc + " " not in line.replace("\t", ""):
        helper.error(
            "Error: Cannot find the function prototype of the top function.")
        assert 0
    aL = arrayList()
    while " ," in line:
        line.replace(" ,", ",")
    while "[" in line and "]" in line:
        aL.nL.append(line[line.rfind(" ", 0, line.find("[")) +
                          1:line.find("[")])
        aL.sL.append(int(line[line.find("[") + 1:line.find("]")]))
        line = line.replace(
            line[line.rfind(" ", 0, line.find("[")) + 1:line.find("]") + 1],
            "", 1)

    if func != top.name:
        temp = ""
        for line in fL.hwPort[fL.name.index(func)].buff:
            temp = temp + line
        for name in aL.nL:
            if temp.count(name + "_address") == 0:
                helper.error("Error: The array " + name + " in function " +
                             func + " is not implementedre. Please check!")
            elif temp.count(name + "_address") > 2:
                helper.error(
                    "Error: Counting the number of memory port wrong!")
            aL.pN.append(temp.count(name + "_address"))
    return aL
Пример #53
0
def run_epoches(images, labels, test_images, test_labels, n=100, alpha=0.7):
    """Run n number of epoches."""
    mse_weights = np.random.randn(784, 10) / 100
    mse_bias = np.random.randn(10, 1) / 100
    
    entropy_weights = np.random.randn(784, 10) / 100
    entropy_bias = np.random.randn(10, 1) / 100

    # for plot
    x_axis = []
    training_mse = []
    training_entropy = []
    test_mse = []
    test_entropy = []

    for i in range(n):
        eta = alpha / math.pow(i + 1, 0.5)
        batches = helper.generate_batches(images, labels)
        for batch in batches:
            gradient_mse_w = compute_gradient_mse(batch, mse_weights, mse_bias, 'w')
            gradient_mse_b = compute_gradient_mse(batch, mse_weights, mse_bias, 'b')
            
            gradient_entropy_w = \
                compute_gradient_entropy(batch, entropy_weights, entropy_bias, 'w')
            gradient_entropy_b = \
                compute_gradient_entropy(batch, entropy_weights, entropy_bias, 'b')

            mse_weights = mse_weights - eta * gradient_mse_w
            mse_bias = mse_bias - eta * gradient_mse_b
            
            entropy_weights = entropy_weights - eta * gradient_entropy_w
            entropy_bias = entropy_bias - eta * gradient_entropy_b

        #storing info every 10 epochs
        if i % 10 == 0:

            x_axis.append(i)
            y1 = helper.error(mse_weights, mse_bias, images, labels)
            training_mse.append(1 - y1)
            
            y2 = helper.error(entropy_weights, entropy_bias, images, labels)
            training_entropy.append(1 - y2)
           
            y3 = helper.error(mse_weights, mse_bias, test_images, test_labels)
            test_mse.append(1 - y3)
            
            y4 = helper.error(entropy_weights, entropy_bias,
                    test_images, test_labels)
            test_entropy.append(1 - y4)

            print 'epoch=', i
            print 'error rate on training set using mean squared error', y1
            print 'error rate on training set using cross-entropy error', y2
            print 'error rate on test set using mean squared error', y3
            print 'error rate on test set using cross-entropy error', y4

    p1, = plt.plot(x_axis, training_mse, 'r')
    p2, = plt.plot(x_axis, training_entropy, 'b')
    p3, = plt.plot(x_axis, test_mse, 'g')
    p4, = plt.plot(x_axis, test_entropy, 'k')
    plt.legend([p1, p2, p3, p4],
        ['training accuracy, mse', 'training accuracy, entropy',
            'test accuracy, mse', 'test accuracy, entropy'])
    plt.show()
Пример #54
0
    def fetch(self, **kwargs):
        action = kwargs.get("action")
        param = kwargs.get("param")

        return error("Invalid request")
Пример #55
0
 def get_specific_issue(self, issue_id):
     if not self.logged():
         return error("You not logged")
     data = self._data.get_issue_by_id(backlog_id=1, issue_id=issue_id)
     return write(data)
Пример #56
0
 def get_issues(self):
     if not self.logged():
         return error("You not logged")
     data = self._data.get_all_issues(backlog_id=1)
     return write(data)
Пример #57
0
    def run(self, input_dir, progress_log):
        flickr = FlickrAPI(self.config.flickr_api_key, self.config.flickr_api_secret, username=self.config.flickr_user_id)
        (token, frob) = flickr.get_token_part_one(perms='write')

        if not token:
            raw_input("Press ENTER after you authorized this program")

        tok = flickr.get_token_part_two((token, frob))
        sets = flickr.photosets_getList(api_key=self.config.flickr_api_key).find('photosets').findall('photoset')

        # login to smugmug
        smapi = SmugMugAPI(self.config.smugmug_api_key)
        result=smapi.login_withPassword (EmailAddress = self.config.smugmug_email, Password = self.config.smugmug_passwd)
        smSessionId = result.Login[0].Session[0]["id"]

        previous_uploads = set()
        if path.exists(progress_log):
            with open(progress_log, 'r') as log_stream:
                for line in log_stream:
                    previous_uploads.add(line.strip())
        helper.log("found %s previous upload(s)" % len(previous_uploads))

#        for u in previous_uploads:
#            helper.log("'%s'" % u)

        with open(progress_log, 'a') as log_stream:
            sm_albums = self.sorted_albums(smapi, smSessionId)
            for album in sm_albums:
                photoset = self.derive_photo_set_name(sm_albums, album)
                dirName = helper.build_album_dirname(album["Title"], album["id"])

                helper.log("%s -> '%s'@flickr" % (dirName, photoset))

                # get images from disk
                for f in os.listdir(input_dir + "/" + dirName):
                    if not f.upper().endswith("JPG"):
                        continue

                    img_fn = input_dir + "/" + dirName + "/" + f

                    # skips if we've already uploaded this image
                    if img_fn in previous_uploads:
                        helper.log("%s (skipping)" % img_fn)
                        continue

                    meta = yaml.load(file(img_fn + ".yaml", 'r'))

                    photo_id = self.upload(flickr, img_fn, meta)
                    if photo_id is None:
                        helper.error("error uploading image " + img_fn + " (continuing)")
                        continue

                    log_stream.write("%s\n" % img_fn)
                    log_stream.flush()

                    try :
                        # create a photoset for this album
                        if not self.set_exists(photoset, sets):
                            # if you create a set with a primary photo it is implicitly added to the set
                            helper.log("creating photoset '%s'" % photoset)
                            flickr.photosets_create(api_key=self.config.flickr_api_key, title=photoset, primary_photo_id=photo_id)
                            # reload the sets
                            sets = flickr.photosets_getList(api_key=self.config.flickr_api_key).find('photosets').findall('photoset')
                        else:
                            # add it to an existing set
                            #print "adding photo %s to set %s" % (photo_id, photoset)
                            theSet = self.set_with_name(sets, photoset)
                            flickr.photosets_addPhoto(api_key=self.config.flickr_api_key,photoset_id=theSet.attrib['id'], photo_id=photo_id)
                    except Exception, e:
                        # here's what can happen: you add a photo successfully; flickr gives
                        # you an id, you try to immediately reference that id to add the photo
                        # to a set and it complains that the photo doesn't exist.  My guess
                        # is that this is a master/slave delay, we just log such errors
                        traceback.print_exc(file=sys.stderr)
Пример #58
0
def not_found(e):
    return error("Invalid request"), 404
Пример #59
0
if os.getuid() == 0:
    root = True
else:
    root = False

# define script args
parser = argparse.ArgumentParser(
    description='Universal Post Install by https://linuxhub.it')
parser.add_argument('-gtk', action='store_true', help='run in GTK mode')
args = parser.parse_args()

# start the script
if args.gtk == True:
    if gui == True:
        if root == True:
            helper.load_script(type="gtk")
        else:
            dialog = models.Dialog(
                "UPI - Error!",
                "The flag (-gtk) needs the program to run as sudo! <a href=\"https://github.com/mirkobrombin/Universal-Post-Install/blob/master/README.md\" "
                "title=\"see here\">see here</a> how to do it", True, 580, 200,
                True, False)
            dialog.run()
    else:
        helper.error(
            "It is not possible to start in GUI mode on this system. The python-gi package is not installed."
        )
else:
    helper.load_script()
Пример #60
0
    def logout(self):
        if not self.logged():
            return error("You not logged")

        session.pop('email', None)
        return write("Well done")