def getListDoorSensors():
    dao = DAO()
    sensors = dao.getListDoorSensors()
    d_list = []
    for sensor in sensors:
        d_list.append({'id_sensor': sensor.id, 'name' : sensor.name,'pin' : sensor.pin_number, 'current' : sensor.current_value})
    return json.dumps(d_list)
Example #2
0
class DisenadorDAO:
    """docstring for ClassName"""
    def __init__(self):
        self.conn = DAO()
        self.sql = ""

    def Create(self, Disenador):
        self.conn.reconnect()
        self.sql = """insert into {0}.Disenador ( idDisenador,paisOrigen, pasaporte) values ({1}, '{2}','{3}')""".format(
            self.conn.getSCHEMA(), Disenador.getId(), Disenador.getpasaporte(),
            Disenador.getpaisOrigen())
        try:
            cn = self.conn.getConnection()
            cur = cn.cursor()
            cur.execute(self.sql, )
            cur.close()
            cn.commit()
            self.msj = "Disenador Creado Exitosamente"
        except (Exception, psycopg2.DatabaseError) as error:
            self.msj = "Lamentamos informar le que a ocurrido un error:  {0}".format(
                error)
        finally:
            if cn is not None:
                cn.close()
        return self.msj
def getListCameraSensors():
    dao = DAO()
    sensors = dao.getListCameraSensors()
    c_list = []
    for sensor in sensors:
        c_list.append({'id_sensor': sensor.id, 'name' : sensor.name,'ip_address' : sensor.ip_address, 'current' : sensor.current_value, 'login' : sensor.login, 'password' : sensor.password}) 
    return json.dumps(c_list)
def rebuild_model():
    model._Base.metadata.create_all(model._engine)
    d = DAO()

    d.signup("Luso", "*****@*****.**", "1111", "666-666")

    t1 = model.Table("4")
    t2 = model.Table("8")
    t3 = model.Table("2")
    t4 = model.Table("8")
    t5 = model.Table("4")

    p1 = model.Product("Ensalada César", "Una ensalada riquísima", "en", 8)
    p2 = model.Product("Filete César", "Un filete riquísimo", "ca", 12)
    p3 = model.Product("Pasta César", "Una pasta riquísima", "pa", 9)
    p4 = model.Product("Pizza César", "Una pizza riquísima", "pi", 15)

    session = model.loadSession()

    session.add(t1)
    session.add(t2)
    session.add(t3)
    session.add(t4)
    session.add(t5)

    session.add(p1)
    session.add(p2)
    session.add(p3)
    session.add(p4)

    session.commit()
Example #5
0
def update_numeracao():
    form_data = request.form
    id_numeracao = request.form['id_numeracao']

    DAO.update(form_data, id_numeracao, Numeracao)
    flash('A numeração foi atualizada com sucesso!')
    return redirect(url_for('index'))
def getListTempSensors():
    dao = DAO()
    sensors = dao.getListTempSensors()
    t_list = []
    for sensor in sensors:
        t_list.append({'id_sensor': sensor.id, 'name' : sensor.name,'directory' : sensor.directory_number, 'current' : sensor.current_value}) 
    return json.dumps(t_list)
Example #7
0
def update_user():
    form_data = request.form
    id_user = request.form['id_user']

    DAO.update(form_data, id_user, Users)
    flash('O Usuário foi atualizado com sucesso!')
    return redirect(url_for('users.userList'))
Example #8
0
class ProfesionalDAO:
    """docstring for ClassName"""
    def __init__(self):
        self.conn = DAO()
        self.sql = ""

    def Create(self, Profesional):
        nameSecuen = ""
        self.conn.reconnect()
        self.sql = """insert into {0}.Profesional (idProfesional, EgresadoUniversidadProfesional, estudiosProfesional) values ({1}, '{2}','{3}')""".format(
            self.conn.getSCHEMA(), Profesional.getId(),
            Profesional.getEgresadoUniversidad(), Profesional.getestudios())
        try:
            nameSecuen = "seq_{0}".format(Persona.__class__.__name__)
            cn = self.conn.getConnection()
            cur = cn.cursor()
            cur.execute(self.sql, )
            cur.close()
            cn.commit()
            self.msj = "Profesional Creado Exitosamente"
        except (Exception, psycopg2.DatabaseError) as error:
            self.msj = "Lamentamos informar le que a ocurrido un error:  {0}".format(
                error)
        finally:
            if cn is not None:
                cn.close()
        return self.msj
Example #9
0
 def add(self, download, parent=QModelIndex()):
     if not DAO.already_downloaded(download.url):
         self.beginInsertRows(parent, 0, 0)
         download = DAO.merge(download)
         self.datas.append(download)
         self.endInsertRows()
         return True
Example #10
0
 def add(self, download, parent=QModelIndex()):
     if not DAO.already_downloaded(download.url):
         self.beginInsertRows(parent, 0, 0)
         download = DAO.merge(download)
         self.datas.append(download)
         self.endInsertRows()
         return True
Example #11
0
    def handleFriendRequest(self, username, otherUsername):
        """
        Gestion de la réception d'une demande d'ami

        :param username: L'émetteur de la requête
        :type username: str
        :param otherUsername: L'utilisateur concerné par la demande
        :type otherUsername: str
        :return:
        :rtype: None
        """
        notification = "{:s} sent you a friend request!".format(username)

        # Enregistrement de la demande dans la base de donnée
        db = DAO("Users.db")
        db.addReceivedFriendRequest(otherUsername, username)
        db.addSentFriendRequest(username, otherUsername)
        db.addNotification(otherUsername, notification)
        db.close()

        # Envoi de la demande à l'ami s'il est actuellement connecté
        friendSocket = self.getClientSocketByUsername(otherUsername)
        if friendSocket:
            reply = {"request": "friendRequest", "username": username}
            self.send(friendSocket, reply)
def setTempSensor():
    idSensor = request.form['id_capt_temp']
    nameSensor =u'CAPTEUR'
    min_tempSensor = request.form['capt_min_tmp']
    max_tempSensor = request.form['capt_max_tmp']
    dao = DAO()
    dao.setTempSensor(id_sensor=int(idSensor), name=nameSensor,min_temp=int(min_tempSensor),max_temp=int(max_tempSensor))
    return min_tempSensor+" "+max_tempSensor+" "+idSensor
Example #13
0
def numeracao_retificada(id_numeracao):
    cross_ret = DAO.search_numeracao_retificada(id_numeracao)
    id_numeracao_retificada = cross_ret.fk_numeracao_retificada
    numeracao_retificada = DAO.search_by_id(id_numeracao_retificada, NumeracaoRetificada)

    flash('Se trata de uma numeração que foi retificada, conteudo apenas para historico!')
    return render_template('numeracaoR.html', titulo='Numeracao antes da retificação de Numeração',
                           numeracao=numeracao_retificada, id_numeracao=id_numeracao, retificada=True)
Example #14
0
def deploy():
    if request.method == 'POST':
        data = request.json
        print(jsonify(data))
        DAO.insert_mysql(data)

        return jsonify(data)
    else:
        data = DAO.get_dadozs()

        return jsonify(data)
Example #15
0
def build_msg(params, list_of_characters, list_of_regions):
    """
    @do :       Interprete la liste de parametre de la commande
    @args :     String[] params -> liste des termes de la commande
                String[] characters -> liste de IA disponibles
                String[] regions -> liste des regions disponibles
    @return :   DAO -> message DAO si la commande est correcte
                None -> si incorrecte ou DAO non necessaire
    """

    msg = DAO()
    msg.type = params[0]

    if len(params) > 1:
        if msg.type == "cmd":
            dao = cmd_handler(params[1:], list_of_characters, list_of_regions,
                              msg)
            return [dao]

        elif msg.type == "sys":
            dao = sys_handler(params[1:], msg)
            return [dao]

        elif msg.type == "info":
            info_handler(params[1:], list_of_characters, list_of_regions)
            return None

        elif msg.type == "run":
            dao_list = run_handler(params[1], list_of_characters,
                                   list_of_regions)
            return dao_list

        elif msg.type == "help":
            if params[1] == "type":
                show_help_type()
            elif params[1] == "cmd":
                show_help_cmd()
            elif params[1] == "sys":
                show_help_sys()
            elif params[1] == "info":
                show_help_info()

        else:
            print(ERROR + "ERR > " + params[0] + " : Type invalide.")
            print(ERROR + "Tapez \"help\" pour plus d'information")

    else:
        if msg.type == "help":
            show_help()

        else:
            print(ERROR + "ERR > Pas d'action renseignee")
            print(ERROR + "Tapez \"help\" pour plus d'information")
def addStateToScenario():
    id_scenario = int(request.form['id_scenario'])
    type_sensor = request.form['type']
    id_sensor = int(request.form['id'])
    operator = request.form['operator']
    value = float(request.form['value'])
    if type_sensor != 'temperature':
	operator = u"null"

    dao = DAO()
    dao.createState(id_scenario, id_sensor, type_sensor, value, operator)
    return json.dumps({'success': 'true', 'id_scenario' : id_scenario})
def getListScenarios():
    dao = DAO()
    scenarios = dao.getListScenarios()
    states = dao.getListStates()
    sc_list = []
    for scenario in scenarios:
	st_list = []
	for state in states :
		if state.id_scenario == scenario.id:
			capteur = dao.getSensor(state.id_sensor, state.type_sensor)
			st_list.append({'id': state.id, 'id_capteur' : state.id_sensor, 'name': capteur.name, 'type': state.type_sensor, 'value' : state.value, 'operator' : state.operator}) 
        sc_list.append({'id': scenario.id, 'name' : scenario.name, 'states' : st_list}) 
    return json.dumps(sc_list)
Example #18
0
    def handleSendMessage(self, username, otherUsername, message):
        """
        Gestion de la réception d'une requête d'envoi de message à un autre
        utilisateur

        :param username: L'émetteur de la requête
        :type username: str
        :param otherUsername: L'utilisateur devant recevoir le message
        :type otherUsername: str
        :param message: Le message
        :type message: str
        :return:
        :rtype: None
        """
        notification = "You received a message from {:s}!".format(username)

        # Mise à jour de la base de données
        db = DAO("Users.db")
        db.addMessage(username, otherUsername, message)
        db.addNotification(otherUsername, notification)
        db.close()

        # Envoi du message au récepteur s'il est connecté
        otherUserSocket = self.getClientSocketByUsername(otherUsername)
        if otherUserSocket:
            reply = {
                "request": "sendMessage",
                "otherUsername": username,
                "message": message
            }
            self.send(otherUserSocket, reply)
def createScenario():
    name = request.form['name']
    type_sensor = request.form['type']
    id_sensor = int(request.form['id'])
    operator = request.form['operator']
    value = float(request.form['value'])
    message = request.form['message']
    time = int(request.form['time'])
    if type_sensor != 'temperature':
	operator = u"null"

    dao = DAO()
    id_scenario = dao.createScenario(name, message, time)
    dao.createState(id_scenario, id_sensor, type_sensor, value, operator)
    return json.dumps({'success': 'true', 'id_scenario' : id_scenario})
Example #20
0
 def generate_downloads(self, list_data):
     downloads = []
     for d in list_data:
         download = DAO.download(d['url'], d['category'], d['description'],
                                 d['name'])
         downloads.append(download)
     self.emit(SIGNAL("refresh(PyQt_PyObject)"), downloads)
Example #21
0
def search_video_capture():
    form = search_input_form(request.form)
    if request.method == "POST":
        #get the search input data
        search_object = form.search.data
        # call the DAO function to search all images name which contain the object from mysql, it will return a list of images name
        records = DAO.search_image_from_videocapture(search_object)
        if records == 0:
            message = "There is no video capture contains this object"
            return render_template('searchImageNoFound.html',
                                   form=form,
                                   message=message)
        #if there is no image
        photo = []
        time = records[1]
        for index in range(len(records[0])):
            #photo_data = DAO.retrieve_photo(image_list[index])
            database_image = (base64.b64encode(
                records[0][index])).decode('ascii')
            photo.append(database_image)
            time.append(records[1][index])
        length = len(records[0])
        #return template display all the images with captrue time
        return render_template("searchVideoCaptureResult.html",
                               photo=photo,
                               time=time,
                               length=length,
                               search_object=search_object)
    return render_template('searchVideoCapture.html', form=form)
Example #22
0
File: Video.py Project: joubu/CDL
    def __init__(self, listAvailables_ui, categoriesList_ui):
        QObject.__init__(self)
        self.ui_categoriesList = categoriesList_ui
        self.refresh_categoriesList(DAO.categories())

        QObject.connect(self.ui_categoriesList, SIGNAL("play(PyQt_PyObject)"),
                        self.play)
Example #23
0
def gen_tag_list():
    tag_page_list = []
    with DAO("TAG_PAGE_LIST") as dao:
        for tag_dict in dao.run(
                f'select DISTINCT TAG_NAME from TAG_PAGE_LIST'):
            tag_page_list.append(tag_dict["TAG_NAME"])
    return tag_page_list
Example #24
0
def numeracaoU(id_numeracao):
    numeracao = DAO.search_by_id(id_numeracao, Numeracao)
    file_list = return_files_numeracao(id_numeracao, Files)
    file_path = Configs.get_file_path()
    return render_template('numeracaoU.html', titulo='Edição de Numeração', numeracao=numeracao,
                           id_numeracao=id_numeracao, files=file_list, retificacao=False, file_path=file_path,
                           insert=True)
Example #25
0
 def __init__(self, category_name, page_name):
     super().__init__()
     with DAO(category_name) as dao:
         result_list = dao.run(
             f'select * from {category_name} where title = "{page_name}"')
         result = result_list[0]
         self.comdict.update(result)
Example #26
0
File: Video.py Project: joubu/CDL
    def __init__(self, listAvailables_ui, categoriesList_ui):
        QObject.__init__(self)
        self.ui_categoriesList = categoriesList_ui
        self.refresh_categoriesList(DAO.categories())

        QObject.connect(self.ui_categoriesList, SIGNAL("play(PyQt_PyObject)"), 
                self.play)
Example #27
0
def authenticate():
    login = request.form['user']
    passw = request.form['passw']

    validacao_db = validar_db(login)
    validacao_ad = validar_AD(login, passw)

    # verifica no banco de dados e no LDAP da prodam se o usuario existe
    if validacao_ad and validacao_db:
        session['logged_user'] = login
        session.permanent = True
        username = DAO.search_by_login(login, Users)
        flash('Bem vindo(a), ' + username + '!')
        next = request.form['next']
        return redirect(next)

    # verifica apenas no LDAP da prodam se o usuario existe
    elif validacao_ad:
        session['logged_user'] = login
        session.permanent = True
        flash('Bem vindo(a), ' + login + '!')
        next = request.form['next']
        return redirect(next)
    else:
        flash('Nao foi possivel fazer login')
        return redirect(url_for('login'))
Example #28
0
    def __init__(self, tag_name):
        super().__init__()
        tag_page_list = []
        with DAO("TAG_PAGE_LIST") as dao:
            result = dao.run(
                f'select * from TAG_PAGE_LIST where TAG_NAME = "{tag_name}"')
            for row in result:
                for page_dict in PAGE_DICT_LIST:
                    if row["BOOK_ID"] == page_dict["book_id"]:
                        tag_page_list.append(page_dict)

        self.comdict.update({"all_relation": tag_page_list})
Example #29
0
def search_image():
    form = search_input_form(request.form)
    if request.method == "POST":
        #get the search input data
        search_object = form.search.data
        # call the DAO function to search all images name which contain the object from mysql, it will return a list of images name
        record = DAO.search_image_name_from_object(search_object)
        #if there is no image
        if record == 0:
            message = "There is no image contains this object"
            return render_template('searchImageNoFound.html',
                                   form=form,
                                   message=message)
        # convert list of image name to array of images name
        list_image_name = []
        for index in range(len(record)):
            list_image_name.append(record[index][0])
        #remove duplicate image
        image_list = list(dict.fromkeys(list_image_name))
        #create an array to contain the original photos of searching object
        photo = []
        #create an array to contain the detection photos of searching object
        newphoto = []
        #with each image name corresponding with the searching object, retrieve photo data by the image name from mysql and put in a list
        for index in range(len(image_list)):
            photo_data = DAO.retrieve_photo(image_list[index])
            database_image = (base64.b64encode(photo_data[0])).decode('ascii')
            photo.append(database_image)
        for index in range(len(image_list)):
            newrecord_photo = DAO.retrieve_photo_detection(image_list[index])
            newdatabase_image = (base64.b64encode(
                newrecord_photo[0])).decode('ascii')
            newphoto.append(newdatabase_image)

        #return template with a list of photos contain searching object in original and deteection format
        return render_template("searchImageResult.html",
                               photo=photo,
                               newphoto=newphoto,
                               object=search_object)
    return render_template('searchImage.html', form=form)
Example #30
0
    def handleSignInRequest(self, clientSocket, username, password):
        """
        Permet de gérer la récpetion d'une reqête de connexion à l'application

        :param clientSocket: Le socket correspondant à l'utilisateur
        :type clientSocket: socket.socket
        :param username: Le nom d'utilisateur
        :type username: str
        :param password: Le mot de passe de l'utilisateur
        :type password: str
        :return:
        :rtype: None
        """
        reply = {"request": "signIn", "isValid": False, "userData": None}

        db = DAO("Users.db")

        # Vérification du mot de passe
        if db.userIsValid(username, password):

            reply["userData"] = db.getUserInfos(username)
            reply["isValid"] = True

            # Enregistrement du nom d'utilisateur; le serveur peut alors
            # l'utiliser pour trouver le socket correspondant à cet utilisateur
            self.registerClientUsername(clientSocket, username)

        db.close()

        # Envoi de la validation au client
        self.send(clientSocket, reply)
Example #31
0
class Preferences(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.ui = Ui_Preferences()
        self.ui.setupUi(self)
        self.ui.lineEditPlayer.setText(config.player)
        self.ui.lineEditDirUser.setText(config.dir_user)

        for c in config.categories:
            cb = self.findChild(QCheckBox, c.name)
            if cb:
                cb.setCheckState(Qt.Checked)

    def tr(self):
        self.ui.retranslateUi(self)

    @pyqtSlot()
    def on_buttonBox_accepted(self):
        new_dir_user = unicode(self.ui.lineEditDirUser.text())
        if config.dir_user != new_dir_user:
            try:
                os.renames(config.dir_user, new_dir_user)
                config.dir_user = new_dir_user
            except Exception, e:
                r = QMessageBox.critical(
                    self, "Path", "Le chemin %s n'existe pas" % new_dir_user)
                print e
                return

        config.player = unicode(self.ui.lineEditPlayer.text())
        config.categories = []
        for cb in self.findChildren(QCheckBox):
            if cb.isChecked():
                cat = DAO.category(unicode(cb.objectName()))
                config.categories.append(cat)
        DAO.commit()
        self.emit(SIGNAL("configChanged(PyQt_PyObject)"), config.categories)
        self.close()
Example #32
0
    def handleOtherUserProfileRequest(self, username, otherUsername):
        """
        Permet de gérer une requête d'affichage du profil d'un autre
        utilisateur

        :param username: Le nom d'utilisateur de l'émetteur de la requête
        :type username: str
        :param otherUsername: L'autre utilisateur
        :type otherUsername: str
        :return:
        :rtype: None
        """
        # Récupération des données dans la base donnée
        db = DAO("Users.db")
        reply = {
            "request": "displayOtherUserProfile",
            "otherUserInfos": db.getOtherUserInfos(username, otherUsername)
        }
        db.close()

        # Envoi des données à l'utilisateur
        userSocket = self.getClientSocketByUsername(username)
        self.send(userSocket, reply)
Example #33
0
    def handleAddComment(self, username, otherUsername, comment):
        """
        Permet de gérer la réception d'un commentaire d'une publication

        :param username: L'émetteur du commentaire
        :type username: str
        :param otherUsername: L'auteur de la publication
        :type otherUsername: str
        :param comment: Les données concernant le commentaire
        :type comment: dict
        :return:
        :rtype: None
        """
        notification = "{:s} commented one of your publications!"\
            .format(otherUsername)

        db = DAO("Users.db")
        db.addCommentToPublication(otherUsername, comment)
        db.addNotification(otherUsername, notification)

        # Envoi du commentaire à l'auteur de la publication
        userSocket = self.getClientSocketByUsername(otherUsername)
        if userSocket:
            reply = {"request": "comment", "comment": comment}
            self.send(userSocket, reply)

        # Envoi du commentaire aux amis de l'auteur de la publication
        for friend in db.getFriends(otherUsername):
            if db.addCommentToFeed(friend, comment):
                friendSocket = self.getClientSocketByUsername(friend)
                if friendSocket and \
                        (friend != otherUsername) and \
                        (friend != username):
                    reply = {"request": "feedComment", "comment": comment}
                    self.send(friendSocket, reply)

        db.close()
Example #34
0
    def handleSearchRequest(self, username, searchInput):
        """
        Permet de gérer une reqête de recherche d'autres utilisateurs

        :param username: L'utilisateur ayant envoyé la requête
        :type username: str
        :param searchInput: La recherche entrée par l'utilisateur
        :type searchInput: str
        :return:
        :rtype: None
        """
        # Récupération des donées de recherche
        firstWord = searchInput[0]
        secondWord = searchInput[1] if len(searchInput) == 2 else None

        # Recherche dans la base données
        db = DAO("Users.db")
        results = db.search(firstWord, secondWord)
        db.close()

        # Envoi des résultats au client
        reply = {"request": "search", "results": results}
        userSocket = self.getClientSocketByUsername(username)
        self.send(userSocket, reply)
Example #35
0
def register():
    form = RegistrationForm(request.form)
    # check if there is request method to register, get the user information and execute mysql statement to insert database
    if request.method == "POST" and form.validate():
        #get data from input form
        username = form.username.data
        email = form.email.data
        firstname = form.firstname.data
        lastname = form.lastname.data
        password = form.password.data
        user = DAO.check_username(username)
        if user:
            message = "That username is already taken, please choose another"
            return render_template('register.html', form=form, message=message)
        #if not, insert new user information to database
        else:

            register = DAO.register(username, password, email, firstname,
                                    lastname)
            if register == True:
                session['name'] = username
                return redirect(url_for('home'))
    # if there is not request method, or input data don't meet requirements, show the register page
    return render_template("register.html", form=form)
Example #36
0
def login():
    #check if there is request method to login, get the user information and execute mysql statement to log in
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        login = DAO.login(username, password)
        if login == False:
            message = "Wrong username or password"
            return render_template('login.html', message=message)
        #otherwise redirect to home page of application
        else:
            session['name'] = username
            return render_template('home.html')
    #if there is not request method, show the login page
    else:
        return render_template('login.html')
Example #37
0
    def handleNotificationsRead(self, username):
        """
        Gestion d'une requête d'indication que les notifications ont été lues

        :param username: L'émetteur de la requête
        :type username: str
        :return:
        """
        db = DAO("Users.db")
        db.markNotificationsAsRead(username)
        db.close()
Example #38
0
File: CDL.py Project: joubu/CDL
    def refresh_downloads_list(self):
        def threadListNewVideos(self):
            self.ui.wait.emit(SIGNAL("open()"))
            list_data = []
            for c in config.categories:
                list_data.extend(c.find_new_videos_availables(config.blacklist))
            self.emit(SIGNAL("construct_downloads(PyQt_PyObject)"), list_data)
            self.ui.wait.emit(SIGNAL("close()"))

        if self.downloadsManager.nb_downloads_in_progress != 0:
            r = QMessageBox.critical(self, "Veuillez patienter !", 
                    u"Tous les téléchargements ne sont pas terminés, veuillez patienter quelques instants avant de raffraichir cette liste")
            return

        config.blacklist
        config.categories = [DAO.merge(x) for x in config.categories]

        threading.Thread(target=threadListNewVideos, args=[self]).start()
Example #39
0
    def handleChangePrivacySettings(self, username, setting):
        """
        Gestion d'une requête de changement de préférence de privacité

        :param username: L'émetteur de la requête
        :type username: str
        :param setting: Le nouveau paramètre de privacité
        :type setting: str
        :return:
        :rtype: None
        """
        db = DAO("Users.db")
        db.updatePrivacySetting(username, setting)
        db.close()
Example #40
0
    def refresh_downloads_list(self):
        def threadListNewVideos(self):
            self.ui.wait.emit(SIGNAL("open()"))
            list_data = []
            for c in config.categories:
                list_data.extend(c.find_new_videos_availables(
                    config.blacklist))
            self.emit(SIGNAL("construct_downloads(PyQt_PyObject)"), list_data)
            self.ui.wait.emit(SIGNAL("close()"))

        if self.downloadsManager.nb_downloads_in_progress != 0:
            r = QMessageBox.critical(
                self, "Veuillez patienter !",
                u"Tous les téléchargements ne sont pas terminés, veuillez patienter quelques instants avant de raffraichir cette liste"
            )
            return

        config.blacklist
        config.categories = [DAO.merge(x) for x in config.categories]

        threading.Thread(target=threadListNewVideos, args=[self]).start()
Example #41
0
    def handleSignUpRequest(self, clientSocket, userData):
        """
        Permet de gérer la réception d'une requête d'enregistrement à l'application

        :param clientSocket: Le socket correspondant à l'utilisateur
        :type clientSocket: socket.socket
        :param userData: Les données correspondantes à la requête
        :type userData: dict
        :return:
        :rtype: None
        """
        reply = {"request": "signUp", "isValid": False}

        # Modification de la base de donnée si la requête est valide
        db = DAO("Users.db")
        if not (db.usernameExists(userData["username"])
                or db.passwordExists(userData["password"])):
            reply["isValid"] = True
            db.addUser(userData)
        db.close()

        # Envoi de la validation au client
        self.send(clientSocket, reply)
Example #42
0
	for i in range(len(laenge)-1):
		for l in range(6):	
			if ref[i,l]!=-1:
				uebergabe=zeros([laenge[int(ref[i,l])]])
				for z in range(int(laenge[int(ref[i,l])])):
					uebergabe[z]=id_lst[int(gruppen[int(ref[i,l])][z])]
				draw_dyade(int(stelle[i,0]),int(stelle[i,1]),uebergabe)
				stelle[ref[i,l],0]=stelle[i,0]
				stelle[ref[i,l],1]=stelle[i,1]+1
				stelle[i,0]+=laenge[ref[i,l]]
	plt.title(Titel)
	plt.show()


#################
daten=DAO()
id_lst_c=sys.argv[1][1:-1].split(',')
stress=int(sys.argv[2])
if stress==1:
	Titel='Stressfrei'
elif stress==4:
	Titel='Gestresst'
elif stress==5:
	Titel='Stressfrei & Gestresst'
elif stress==8:
	Titel='Stressfrei & Gestresst'
id_lst=[]
for i in id_lst_c:
	id_lst.append(int(i))
daten_roh=daten.req_rel_auf(id_lst,stress)
if stress==5:
Example #43
0
# 
# print ids;
# 
# # Bestimme die Indexnummer fuer die uebergebene Dyade
# dyaden_ids=[]
# for i in range(dyade_num):
# 	dyaden_ids+=[ids[i]]
# ind=dyaden_ids.index(str(dyade_in))
# 
# 
# #Entferne alle Zustaende mit z<=0 und z>16
# zeitreihen_trimmed_m0=[]
# zeitreihen_trimmed_m2=[]


dao=DAO()
zeitreihe_unstress=dao.req_zeitreihen([dyade_in],DAO.NOT_STRESS)[0,0]
zeitreihe_stress=dao.req_zeitreihen([dyade_in],DAO.STRESS)[0,0]


print "ZR:"+str(zeitreihe_unstress)
ind=dao.id_lst.index(str(dyade_in)) # Dyaden Indizes Liste

zeitreihen_trimmed_m0=[]
zeitreihen_trimmed_m2=[]                                    
for i in zeitreihe_unstress:                                  
    if(i>0 and i<17): # wenn gueltiger Dyadenwert
	       zeitreihen_trimmed_m0+=[i-1]

for i in zeitreihe_stress:
	if(i>0 and i<17): # wenn gueltiger Dyadenwert
Example #44
0
# -*-coding:Latin-1 -*

import os
from DAO import DAO

os.system("rm bddSQLite")

dao = DAO()
dao.initTablesSQL()
dao.createTempSensor(u'capteur_de_temp_1', 10)
dao.createTempSensor(u'capteur_de_temp_cuisine', 8)
dao.createTempSensor(u'Temp_Salon', 6)

s = dao.getTempSensor(6)
dao.currentTemp(s[0].id,22)
s = dao.getTempSensor(8)
dao.currentTemp(s[0].id,30.245)
s = dao.getTempSensor(10)
dao.currentTemp(s[0].id,9)

dao.createDoorSensor(u'capteur_de_porte_1', 1)
dao.createDoorSensor(u'porte_cuisine', 7)

#s = dao.getDoorSensor(1)
#dao.currentDoor(s[0].id,0)
#s = dao.getDoorSensor(7)
#dao.currentDoor(s[0].id,1)


Example #45
0
 def refresh(self, downloads):
     self.model.clear()
     for download in downloads:
         self.model.add(download)
     DAO.commit()
Example #46
0
 def delete_download(self, download):
     self.ui_downloads_list.remove(download)
     DAO.commit()
Example #47
0
File: Video.py Project: joubu/CDL
 def add(self, video):
     self.insertRows(0, 1)
     self.datas.append(video)
     self.sort(self.sorting_column)
     DAO.commit()
Example #48
0
    def __init__(self, parent=None):
        QListView.__init__(self, parent)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.model = DownloadsModel(parent, DAO.downloads())
        self.setModel(self.model)
Example #49
0
File: Video.py Project: joubu/CDL
 def play(self, video):
     if not video:
         return
     playerProcess = PlayerProcess(DAO.player(), video)
     playerProcess.start()
     video.marked_as_seen(True)
Example #50
0
from pylab import show, plot, xlabel, ylabel, rand, scatter
import pickle
from scipy import zeros, corrcoef
from numpy.random import random
from numpy import ones
from pylab import figure,hist,mean,text
import sys
import numpy
sys.path.append(".")
from hierarchische_clusterung import gruppen_erzeugen 
sys.path.append("../")
from DAO import DAO
import tkMessageBox


dao=DAO();
reqs=DAO.convertToList(sys.argv[1])
zeitreihen=dao.req_zeitreihen(reqs,DAO.STRESS|DAO.NOT_STRESS)
dyade_num=len(reqs)

# Entferne alle Zustaende mit 0
zeitreihen_trimmed=zeros([dyade_num,2,6000])
lens=zeros([dyade_num,3])

# Erstelle getrimmte Zeitreihe ohne 0 ( keine Daten) Zustaende
print "Trimming start"
for d in range(dyade_num):
	for m in range(2):
		a=0
		for i in zeitreihen[d,m]:
			if(i>0 and i<17):
Example #51
0
File: CDL.py Project: joubu/CDL
 def generate_downloads(self, list_data):
     downloads = []
     for d in list_data:
         download = DAO.download(d['url'], d['category'], d['description'], d['name'])
         downloads.append(download)
     self.emit(SIGNAL("refresh(PyQt_PyObject)"), downloads)
Example #52
0
import pickle
from pylab import plot, figure, show, scatter, xlabel, ylabel, zeros, random, subplot, ones, text, hist, rand	

import sys
sys.path.append("../")
from hierarchische_clusterung import gruppen_erzeugen
from DAO import DAO
data_path=''

dao=DAO();
dyaden_ids=dao.convertToList(sys.argv[1])
zeitreihen=dao.req_zeitreihen(dyaden_ids,DAO.NOT_STRESS|DAO.STRESS)

dyade_num=len(dyaden_ids)

# Bestimme fuer eine bestimmte Dyade die Staytime im ungestressten und gestressten Zustand
# Fuer die Auswertung interessiert lediglich das Verhalten der Mutter
#
# Die Zustaende sind von 1-16. Der Zustand 0 steht fuer "Keine Daten"
# Deswegen wird vor dem Einlesen jeder zust. -1 gerechnet
#
# Frage: Welche Zeitreihe ist M --> die 2., deswegen Mod.
# 
# Klassifikation nach relativer Aenderung der Zustandsaenderg.rate
"""
Auswertung:
	- Fig. 1, ziemlich gleichverteilt im Intervall 0-0,6
	- im Mittel nimmt die Rate nur geringfuegig ab
	- Klass. moeglich nach Abnahme und Zunahme
"""
#
def removeScenario():
	id_scenario = int(request.args['id_scenario'])
	dao = DAO()
	dao.removeScenario(id_scenario)
	return json.dumps({'success': 'true'})
Example #54
0
File: Video.py Project: joubu/CDL
 def marked_as_seen(self, seen=True):
     video = self.ui_categoriesList.videoSelected()
     video.marked_as_seen(seen)
     self.ui_categoriesList.marked_as_seen_selected(seen)
     DAO.commit()
Example #55
0
File: CDL.py Project: joubu/CDL
 def blacklist(self, download):
     config.blacklist.append(download)
     DAO.commit()
Example #56
0
File: Video.py Project: joubu/CDL
 def remove(self, video):
     i = self.datas.index(video)
     self.removeRows(i, 1)
     self.datas.remove(video)
     video.delete()
     DAO.commit()
# -*- coding: utf-8 -*-
import model
from DAO import DAO

model._Base.metadata.create_all(model._engine)
d = DAO()

d.signup("Luso", "*****@*****.**", "1111", "666-666")

p1 = model.Product("Red Bull sin azúcar", "La versión sin azúcar de la popular bebida Red Bull", 100.20)
p2 = model.Product("CocaCola Zero", "Bebe CocaCola sin preocuparte por engordar", 60.99)
p3 = model.Product("Fanta Zero", "Bebe Fanta sin preocuparte por engordar", 55.99)

session = model.loadSession()

session.add(p1)
session.add(p2)
session.add(p3)

session.commit()
Example #58
0
 def clear(self):
     DAO.commit()
     for i in xrange(len(self.datas)):
         self.remove(self.datas[-1])
     DAO.commit()
Example #59
0
File: CDL.py Project: joubu/CDL
from DAO import DAO
from Download import *
from Video import *

debug = False
#debug = True

# Quit sur CTRL-C
signal.signal(signal.SIGINT, signal.SIG_DFL)

if not os.path.exists('/usr/bin/flvstreamer'):
    print "flvstreamer must be installed"
    exit(1)


config = DAO.init()
config.categories




class Ui_Wait(QProgressDialog):
    def __init__(self, parent=None):
        QProgressDialog.__init__(self, u"Recherche des nouvelles vidéos en cours ...",
                "Fermer", 0, 0)
        self.setModal(True)
        self.setWindowTitle(u"Recherche ...")
        self.setCancelButton(None)

    def open(self):
        self.show()