Exemple #1
0
def dashboard():
    ''' Codigo que maneja el dashboard de la aplicacion. '''

    createDB()
    products = queryDB('SELECT id, name FROM products;')

    kwargs = {}
    kwargs['title'] = PAGE_DASHBOARD[1]
    kwargs['serverAddr'] = CONFIG['NC_ADDRESS']
    kwargs['serverPort'] = CONFIG['SERVER_PORT']
    kwargs['products'] = products
    kwargs['selected_product'] = CONFIG['CURRENT_PRODUCT']

    if request.method == 'POST':

        currentProduct = int(request.form['currentProduct'])
        min_weight, max_weight = queryDB(
            'SELECT min_weight, max_weight FROM products WHERE id = ?',
            (currentProduct, ),
            one=True)

        if app.mutex.acquire(False):
            CONFIG['CURRENT_PRODUCT'] = currentProduct
            utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            kwargs['selected_product'] = currentProduct
            print(currentProduct)
            arduino.setWeights(min_weight, max_weight)
            flash('Se cambio el producto actual!')
            app.mutex.release()
        else:
            flash(u'Dispositivo ocupado, alguien más intenta actualizarlo!')

    destroyDB()

    return render_template('dashboard.html', **kwargs)
Exemple #2
0
def dashboard():
    """ Codigo que maneja el dashboard de la aplicacion. """

    createDB()
    products = queryDB("SELECT id, name FROM products;")

    kwargs = {}
    kwargs["title"] = PAGE_DASHBOARD[1]
    kwargs["serverAddr"] = CONFIG["NC_ADDRESS"]
    kwargs["serverPort"] = CONFIG["SERVER_PORT"]
    kwargs["products"] = products
    kwargs["selected_product"] = CONFIG["CURRENT_PRODUCT"]

    if request.method == "POST":

        currentProduct = int(request.form["currentProduct"])
        min_weight, max_weight = queryDB(
            "SELECT min_weight, max_weight FROM products WHERE id = ?", (currentProduct,), one=True
        )

        if app.mutex.acquire(False):
            CONFIG["CURRENT_PRODUCT"] = currentProduct
            utils.writeConfig(CONFIG, APP_CONFIG_PATH)
            kwargs["selected_product"] = currentProduct
            print(currentProduct)
            arduino.setWeights(min_weight, max_weight)
            flash("Se cambio el producto actual!")
            app.mutex.release()
        else:
            flash(u"Dispositivo ocupado, alguien más intenta actualizarlo!")

    destroyDB()

    return render_template("dashboard.html", **kwargs)
Exemple #3
0
def add(site, qid):
    if not isfile(db_file):
        createDB()
    qData = getQuestionData(site, qid)
    print('adding question')
    addQuestion(site, qData)
    print('question added')
Exemple #4
0
 def record(self):
     db.createDB()
     for link, content in self.dict.items():            
         if link != None and len(link) > 0 and content != None and len(content) > 0:                
             print(link, content)
             db.recordLink(link, content)
     db.printDB()
Exemple #5
0
def generateDb():
    removeDbIfExists()
    limit = 100
    params = {'token': groupmeToken, 'limit': limit}
    spotifyIds = set()
    data = getGroupmeData(params, spotifyIds)
    data.reverse()
    musicRecords = appendSpotifyData(data)
    db.createDB()
    db.createMusicRecord(musicRecords)
    return 'the db was created successfully'
Exemple #6
0
def products(page):
    """ Codigo que maneja el listado de productos de la aplicacion. """

    createDB()
    count = queryDB("SELECT count(*) from products;", one=True)[0]

    kwargs = {}

    minID = (page - 1) * CONFIG["PRODUCTS_PER_PAGE"] + 1
    maxID = page * CONFIG["PRODUCTS_PER_PAGE"]
    kwargs["products"] = queryDB("SELECT id, name FROM products WHERE id >= ? and id <= ?", (str(minID), str(maxID)))
    destroyDB()

    if not kwargs["products"] and page != 1:
        abort(404)

    kwargs["page"] = page
    kwargs["pagination"] = Pagination(page, CONFIG["PRODUCTS_PER_PAGE"], count)
    kwargs["title"] = PAGE_PRODUCTS[1]

    return render_template("products.html", **kwargs)
Exemple #7
0
def products(page):
    ''' Codigo que maneja el listado de productos de la aplicacion. '''

    createDB()
    count = queryDB('SELECT count(*) from products;', one=True)[0]

    kwargs = {}

    minID = (page - 1) * CONFIG['PRODUCTS_PER_PAGE'] + 1
    maxID = page * CONFIG['PRODUCTS_PER_PAGE']
    kwargs['products'] = queryDB(
        'SELECT id, name FROM products WHERE id >= ? and id <= ?',
        (str(minID), str(maxID)))
    destroyDB()

    if not kwargs['products'] and page != 1:
        abort(404)

    kwargs['page'] = page
    kwargs['pagination'] = Pagination(page, CONFIG['PRODUCTS_PER_PAGE'], count)
    kwargs['title'] = PAGE_PRODUCTS[1]

    return render_template('products.html', **kwargs)
Exemple #8
0
    def run(self):
        log.log.log(1, 'main task start')
        fltr = filter()
        db.createDB()
        self.resQueArray.create(self.thrNum)
        thrQuitNum = self.thrNum
        quit = False
        resWaitTimeoutRetry = self.maxRetry

        self.stat.init(self.depth, 10)
        self.stat.start()

        # start threads
        log.log.log(1, 'start sub threads')
        for i in range(self.thrNum):
            thr = threading.Thread(target=self.subTask)
            thr.start()

        # send key to all threads
        self.distributeKey(self.keyObj)

        # send init task
        self.setInitTask()

        while quit != True:
            resObj = self.resQueArray.getObj()
            if resObj != None:
                resWaitTimeoutRetry = self.maxRetry # reset retry times
                link, content, level, thrQuit = resObj

                if level <= self.depth  and level != -1 and link != None:
                    ignore = False
                    for ignoreSite in self.ignoreSiteList:
                        if link.find(ignoreSite) != -1:
                            ignore = True
                            self.ntfStatTaskConsumed(level)
                            print('ignore link:', link, 'match:', ignoreSite)
                            break
                    if ignore != True: # proc resource here
                        if fltr.isDataExists(link) != True:
                            self.recordLink(link, content, db)
                            self.stat.addNodeRecordCnt(level)

                            if level < self.depth:
                                taskObj = (link, level)
                                self.taskQue.put(taskObj)
                        else:
                            self.ntfStatTaskConsumed(level)

                if thrQuit == True: # a thread quit
                    thrQuitNum = thrQuitNum - 1
                if thrQuitNum == 0: # all threads quit
                    quit = True
            elif quit != True: # resource queue is empty, and quit flag isn't set
                if resWaitTimeoutRetry == 0: # wait long enough, trigger all thread to quit
                    log.log.logMsgWithIntValue(2, 'kill all thread', thrQuitNum)
                    self.stopAllThread()
                    time.sleep(1)
                elif self.taskQue.empty() != True: # still has task undone, maybe all threads are busy, wait 1 sec
                    time.sleep(1)
                    log.log.log(2, 'still has task undone, just wait a second')
                else: # all task done, resource is empty, start quit countdown
                    log.log.logMsgWithIntValue(2, 'all task done, resource is empty, start quit countdown', resWaitTimeoutRetry)
                    resWaitTimeoutRetry = resWaitTimeoutRetry - 1
                    time.sleep(1)
        # end of while, ready to quit main thread

        thr.join()
        self.stat.stop()
        print('------searchResult------:')
        db.printDB()
        log.log.log(1, 'main task end.')
        db.delRecord(None, None)
Exemple #9
0
import sqlite3
import math
import time
from tools import deserialization, serialization, addTransparency, cut_by_ratio
from db import createDB

colorStorage = deserialization('color-mapping.pkl')
print('缓存存在:{}个图片'.format(len(colorStorage)))

(conn,c) = createDB()

for row in c.execute('SELECT count(r) FROM images'):
    print(row)


for row in c.execute("select sqrt(33.66), square(8)"):
    print(row)


# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
Exemple #10
0
def product(id=None):
    """ Codigo que maneja un producto. """

    createDB()

    kwargs = {}
    kwargs["product"] = (None, "", "", "")
    kwargs["measurements"] = []
    kwargs["title"] = "Crear producto"
    kwargs["mode"] = "insert"
    kwargs["serverAddr"] = CONFIG["NC_ADDRESS"]
    kwargs["serverPort"] = CONFIG["SERVER_PORT"]

    if id is not None:
        kwargs["mode"] = "update"
        if request.method == "GET":
            product = queryDB("SELECT * FROM products WHERE id = ?;", (id,))
            if product:
                kwargs["product"] = product[0]
                measurements = queryDB("SELECT * FROM measurements WHERE product_id = ? LIMIT 25;", (id,))
                kwargs["measurements"] = measurements
                kwargs["title"] = product[0][1]
            else:
                abort(404)
        else:
            # Leemos el formulario y actualizamos.
            name = request.form["name"]
            minWeight = request.form["minWeight"]
            maxWeight = request.form["maxWeight"]
            if isFloat(minWeight) and isFloat(maxWeight) and float(minWeight) < float(maxWeight) and len(name) > 0:
                alterDB(
                    "UPDATE products SET name = ?, min_weight = ?, max_weight = ? WHERE id = ?;",
                    (name, minWeight, maxWeight, id),
                )
                flash("Producto actualizado!")
            else:
                flash("Datos invalidos!")

            kwargs["product"] = (id, name, minWeight, maxWeight)
            kwargs["title"] = name
            kwargs["mode"] = "update"
            measurements = queryDB("SELECT * FROM measurements WHERE product_id = ? LIMIT 25;", (id,))
            kwargs["measurements"] = measurements
    else:
        if request.method == "POST":
            # Creamos el producto.
            name = request.form["name"]
            minWeight = request.form["minWeight"]
            maxWeight = request.form["maxWeight"]
            if isFloat(minWeight) and isFloat(maxWeight) and float(minWeight) < float(maxWeight) and len(name) > 0:
                id = alterDB(
                    "INSERT INTO products(name, min_weight, max_weight) VALUES (?,?,?);", (name, minWeight, maxWeight)
                )
                flash("Producto creado!")
                return redirect(url_for("products"))
            else:
                flash("Datos invalidos!")
                kwargs["product"] = (None, name, minWeight, maxWeight)

    destroyDB()

    return render_template("product.html", **kwargs)
Exemple #11
0
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
import sqlite3
import db
import subprocess
from subprocess import call
import tkinter.font as font

db.createDB()

root = Tk()
root.title("Password Manager")
root.geometry("500x550")
menu = Menu(root)
root.config(menu=menu)





def password_recover():
	recoverWin = Tk()
	recoverWin.title("Recover Password")
	recoverWin.geometry("400x400")
	v2 = StringVar()
	v2.set("one")

	#-------- L A Y O U T   D E S I G N -----------------
	title = Label(recoverWin, text="Recover Password", font=("Arial", 20, "bold"))
	title.grid(row=0, columnspan=1, column=0)
Exemple #12
0
	os.remove(tempfile[1])
	originalhash = hash.sha512file(file)
	info = mp3info(title, artist, album, unicode(strippedhash), unicode(originalhash), unicode(str(os.path.abspath(file)).decode('utf-8')), mtime)
	if not update:
		print(info,"Ins")
		db.insertIntoDB(dbcursor, info)
	else:
		#print(info,"upd")
		db.updateDB(dbcursor, info)
	dbconn.commit()

# Initial setup of DB
# We keep the connection & cursor seperate so we can do commits when we want
dbPath = os.path.abspath("mp3dedup.db")
if not os.path.isfile(dbPath):
	db.createDB(dbPath)
dbconn = db.startDB(dbPath)
dbcursor = dbconn.cursor()
# End initial setup

# Walk the directory structure looking for MP3 files
for root, subfolders, files in os.walk(sys.argv[1]):
	# Mention what path we're working in.
	print("Working in", os.path.abspath(root))
	# Since root contains the working folder, and we'll move onto subfolders later, 
	# We only care about the filename
	for filename in files:
		# So, for each file, check if it has an MP3 extension
		if re.search(".mp3",filename,re.IGNORECASE):
			# If is does, hash & add it to the db
			hashAndAdd(os.path.abspath(join(root,filename)))
Exemple #13
0
def product(id=None):
    ''' Codigo que maneja un producto. '''

    createDB()

    kwargs = {}
    kwargs['product'] = (None, '', '', '')
    kwargs['measurements'] = []
    kwargs['title'] = 'Crear producto'
    kwargs['mode'] = 'insert'
    kwargs['serverAddr'] = CONFIG['NC_ADDRESS']
    kwargs['serverPort'] = CONFIG['SERVER_PORT']

    if (id is not None):
        kwargs['mode'] = 'update'
        if request.method == 'GET':
            product = queryDB('SELECT * FROM products WHERE id = ?;', (id, ))
            if product:
                kwargs['product'] = product[0]
                measurements = queryDB(
                    'SELECT * FROM measurements WHERE product_id = ? LIMIT 25;',
                    (id, ))
                kwargs['measurements'] = measurements
                kwargs['title'] = product[0][1]
            else:
                abort(404)
        else:
            # Leemos el formulario y actualizamos.
            name = request.form['name']
            minWeight = request.form['minWeight']
            maxWeight = request.form['maxWeight']
            if isFloat(minWeight) and isFloat(maxWeight) and float(
                    minWeight) < float(maxWeight) and len(name) > 0:
                alterDB(
                    'UPDATE products SET name = ?, min_weight = ?, max_weight = ? WHERE id = ?;',
                    (name, minWeight, maxWeight, id))
                flash('Producto actualizado!')
            else:
                flash('Datos invalidos!')

            kwargs['product'] = (id, name, minWeight, maxWeight)
            kwargs['title'] = name
            kwargs['mode'] = 'update'
            measurements = queryDB(
                'SELECT * FROM measurements WHERE product_id = ? LIMIT 25;',
                (id, ))
            kwargs['measurements'] = measurements
    else:
        if request.method == 'POST':
            # Creamos el producto.
            name = request.form['name']
            minWeight = request.form['minWeight']
            maxWeight = request.form['maxWeight']
            if isFloat(minWeight) and isFloat(maxWeight) and float(
                    minWeight) < float(maxWeight) and len(name) > 0:
                id = alterDB(
                    'INSERT INTO products(name, min_weight, max_weight) VALUES (?,?,?);',
                    (name, minWeight, maxWeight))
                flash('Producto creado!')
                return redirect(url_for('products'))
            else:
                flash('Datos invalidos!')
                kwargs['product'] = (None, name, minWeight, maxWeight)

    destroyDB()

    return render_template('product.html', **kwargs)
Exemple #14
0
async def on_message(message):    
    if message.author.id == '241726136629854208':
        if 'lost' in message.content.lower() and 'game' in message.content.lower():
            await message.channel.send('f**k you')
    
    if message.author.id != client.user.id:
        if 'corn' in message.content.lower():
            if random.randrange(0, 2) == 1:
                await message.channel.send(u'\U0001F33D\U0001F33D\U0001F33D IT\'S RAINING CORN! \U0001F33D\U0001F33D\U0001F33D');
        if message.content == 'same':
            await message.channel.send('same')
    
    if random.randrange(0, 15) == 5:
        await message.add_reaction(u'\U0001F33D')
        
    # check if we should process messages for this channel
    msgChannel = message.channel.id
    if msgChannel == config.listenID or config.listenID == 'NONE':
        # check if this is a command for this bot
        if message.content.startswith(config.cmdPrefix):
            # parse the command
            cmd = ParseMessage(message)
            gameFileName = cmd.game + '_' + config.statsFileName

            print('\n[INFO] Command: %s' % cmd.command)
            print('[INFO] Arguments: %s' % cmd.args)

            # get invoking member
            msgAuthor = message.author
            # check permission for command
            permission = config.checkPermission(msgAuthor, cmd.command)

            if permission:
                # main command for adding win and lose information
                # syntax: !updategame game='game' winner='winner' losers='losers'
                if cmd.command == 'UPDATESTATS':
                    # send a typing message because why not
                    await message.channel.trigger_typing()
                    
                    # make sure the required arguments were provided
                    if cmd.game == 'NONE' or cmd.winner == 'NONE' or cmd.losers == 'NONE':
                        # error message if game not specified
                        if cmd.game == 'NONE':
                            print('[ERROR] No game specified')
                            await message.channel.send('Error: No game specified.')
                        # error message if winner not specified
                        if cmd.winner == 'NONE':
                            print('[ERROR] No winner specified')
                            await message.channel.send('Error: No winner specified.')
                        #error message if losers not specified
                        if cmd.losers == 'NONE':
                            print('[ERROR] No losers specified')
                            await message.channel.send('Error: No losers specified.')
                    else:
                        # print some info to terminal
                        print('[INFO] Game: %s' % cmd.game)
                        print('[INFO] Winner: %s' % cmd.winner)
                        print('[INFO] Losers: %s' % cmd.losers)

                        # try updating the stats
                        status = incrementStats(message.channel, gameFileName, cmd.winner, cmd.losers)
                        await message.channel.send(status)
                        await message.channel.send('<:trains:324019973607653378>')

                # command for adding a player to a database
                # syntax: !addplayer game='game' name='name'
                elif cmd.command == 'ADDPLAYER':
                    # send a typing message because why not
                    await message.channel.trigger_typing()
                    
                    # make sure the required arguments were provided
                    if cmd.game == 'NONE' or cmd.name == 'NONE':
                        # error message if game not specified
                        if cmd.game == 'NONE':
                            print('[ERROR] No game specified')
                            await message.channel.send('Error: No game specified.')
                        # error message if player not specified
                        if cmd.name == 'NONE':
                            print('[ERROR] No player specified')
                            await message.channel.send('Error: No player specified.')
                    else:
                        # print some info to terminal
                        print('[INFO] Game: %s' % cmd.game)
                        print('[INFO] Player: %s' % cmd.name)

                        # add the player
                        status = editPlayer(message.channel, gameFileName, cmd.name, editType='ADD')
                        await message.channel.send(status)

                # command for removing a player from a database
                # syntax: !removeplayer game='game' name='name'
                elif cmd.command == 'REMOVEPLAYER':
                    # send a typing message because why not
                    await message.channel.trigger_typing()
                    
                    # make sure the required arguments were provided
                    if cmd.game == 'NONE' or cmd.name == 'NONE':
                        # error message if game not specified
                        if cmd.game == 'NONE':
                            print('[ERROR] No game specified')
                            await message.channel.send('Error: No game specified.')
                        # error message if player not specified
                        if cmd.name == 'NONE':
                            print('[ERROR] No player specified')
                            await message.channel.send('Error: No player specified.')
                    else:
                        # print some info to terminal
                        print('[INFO] Game: %s' % cmd.game)
                        print('[INFO] Player: %s' % cmd.name)

                        # remove the player
                        status = editPlayer(message.channel, gameFileName, cmd.name, editType='REMOVE')
                        await message.channel.send(status)

                # command for setting a players win and loss stats
                # syntax: !setplayer game='game' name='name' wins='wins' losses='losses'
                elif cmd.command == 'SETPLAYER':
                    # send a typing message because why not
                    await message.channel.trigger_typing()
                    
                    # make sure the required arguments were provided
                    if cmd.game == 'NONE' or cmd.name == 'NONE' or cmd.wins == 'NONE' or cmd.losses == 'NONE':
                        # error message if game not specified
                        if cmd.game == 'NONE':
                            print('[ERROR] No game specified')
                            await message.channel.send('Error: No game specified.')
                        # error message if player not specified
                        if cmd.name == 'NONE':
                            print('[ERROR] No player specified')
                            await message.channel.send('Error: No player specified.')
                        # error message if wins not specified
                        if cmd.wins == 'NONE':
                            print('[ERROR] No wins specified')
                            await message.channel.send('Error: No wins specified.')
                        # error message if losses not specified
                        if cmd.losses == 'NONE':
                            print('[ERROR] No losses specified')
                            await message.channel.send('Error: No losses specified.')
                    else:
                        # print some info to terminal
                        print('[INFO] Game: %s' % cmd.game)
                        print('[INFO] Player: %s' % cmd.name)

                        # update the players stats
                        status = editPlayer(message.channel, gameFileName, cmd.name, editType='EDIT', wins=cmd.wins, losses=cmd.losses)
                        await message.channel.send(status)

                # command for displaying game stats
                # syntax: !stats game='game' (optional) sort='sort'
                elif cmd.command == 'STATS':
                    # send a typing message because why not
                    await message.channel.trigger_typing()
                    
                    # make sure the required arguments were provided
                    if cmd.game == 'NONE':
                        # error message if game not specified
                        if cmd.game == 'NONE':
                            print('[ERROR] No game specified')
                            await message.channel.send('Error: No game specified.')
                    else:
                        # print some info to terminal
                        print('[INFO] Game: %s' % cmd.game)
                        print('[INFO] Sorting Type: %s' % cmd.sort)

                        statsMsg = dumpStats(message.channel, gameFileName, sortType=cmd.sort)
                        await message.channel.send(statsMsg)

                elif cmd.command == 'GAMEHELP':
                    # send a typing message because why not
                    await message.channel.trigger_typing()
                    
                    if cmd.nonKeyed == 'NONE':
                        # return default help message
                        helpMsg = help.helpMessage('LIST')
                    else:
                        # return a help message for the specified command
                        helpMsg = help.helpMessage(cmd.nonKeyed)
                    # send message
                    await message.channel.send(helpMsg)

                # command for creating a new game database
                # syntax: !addgame game
                elif cmd.command == 'ADDGAME':
                    # send a typing message because why not
                    await message.channel.trigger_typing()
                    
                    # make sure the required arguments were provided
                    if cmd.nonKeyed == 'NONE':
                        print('[ERROR] No game specified')
                        await message.channel.send('Error: No game specified.')
                    else:
                        # print some info to terminal
                        print('[INFO] Game: %s' % cmd.game)

                        gameFileName = cmd.nonKeyed + '_' + config.statsFileName
                        if createDB(gameFileName):
                            print('[INFO] New database created')
                            await message.channel.send('New database created!')
                        else:
                            await message.channel.send('Error: Problem creating database')
                elif cmd.command == 'NATE':
                    # send a typing message because why not
                    await message.channel.trigger_typing()
                    
                    await message.channel.send('no u')

            # failed permission check or game check
            else:
                if not permission:
                    print('[ERROR] %s does not have permission to use this command' % msgAuthor.name)
                    await message.channel.send('Error: You do not have permission to use that command')
Exemple #15
0
import os

from tornado import web, ioloop
from db import createDB
from handlers import IndexHandler, SocketHandler, FriendHandler, GetHandler

settings = {
    "template_path": os.path.join(os.path.dirname(__file__), "templates"),
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "debug": True,
    "autoreload": True
}

application = web.Application([
    (r'/', IndexHandler),
    (r'/index', IndexHandler),
    (r'/socket', SocketHandler),
    (r'/friend', FriendHandler),
    (r'/get', GetHandler)
], **settings)

port = int(os.environ.get('PORT', 8080))

if __name__ == '__main__':
    application.listen(port)
    createDB()
    ioloop.IOLoop.instance().start()
Exemple #16
0
label = Label(frame, text='Atualizar o banco de dados:')
label.grid(row=4, column=1)

label = Label(frame, text='Deletar alguns dados do banco:')
label.grid(row=6, column=1)

label = Label(frame, text='Consulta 1:')
label.grid(row=8, column=1)

label = Label(frame, text='Consulta 2:')
label.grid(row=10, column=1)

label = Label(frame, text='Consulta 3:')
label.grid(row=12, column=1)

Criar = Button(frame, text="Criar", command=lambda: db.createDB())
Criar.grid(row=1, column=1, sticky=W + E)

Popular = Button(frame, text="Popular", command=lambda: pop.popular())
Popular.grid(row=3, column=1, sticky=W + E)

Atualizar = Button(frame, text="Atualizar", command=lambda: upd.atualizar())
Atualizar.grid(row=5, column=1, sticky=W + E)

Excluir = Button(frame, text="Excluir", command=lambda: delt.excluir())
Excluir.grid(row=7, column=1, sticky=W + E)

Consulta1 = Button(frame, text="Consulta", command=lambda: Consulta1())
Consulta1.grid(row=9, column=1, sticky=W + E)

Consulta2 = Button(frame, text="Consulta 2", command=lambda: Consulta2())