Ejemplo n.º 1
0
def create_data(filename):
	try:
		db.load_db(filename)
	except Exception:
		db._reset_db()

		db.add_bottle_type('Johnnie Walker', 'black label', 'blended scotch')
		db.add_to_inventory('Johnnie Walker', 'black label', '1 gallon')
		db.add_to_inventory('Johnnie Walker', 'black label', '500 ml')

		db.add_bottle_type('Uncle Herman\'s', 'moonshine', 'blended scotch')
		db.add_to_inventory('Uncle Herman\'s', 'moonshine', '5 liter')

		db.add_bottle_type('Gray Goose', 'vodka', 'unflavored vodka')
		db.add_to_inventory('Gray Goose', 'vodka', '1 liter')

		db.add_bottle_type('Rossi', 'extra dry vermouth', 'vermouth')
		db.add_to_inventory('Rossi', 'extra dry vermouth', '24 oz')

		db.add_bottle_type('Jose Cuervo', 'Silver', 'tequila')
		db.add_to_inventory('Jose Cuervo', 'Silver', '1 liter')

		r = recipes.Recipe('scotch on the rocks', [('blended scotch','4 oz')])
		db.add_recipe(r)
		r = recipes.Recipe('vodka martini', [('unflavored vodka', '6 oz'),('vermouth', '1.5 oz')])
		db.add_recipe(r)
		r = recipes.Recipe('vomit inducing martini', [('orange juice','6 oz'),('vermouth','1.5 oz')])
		db.add_recipe(r)
		r = recipes.Recipe('whiskey bath', [('blended scotch', '2 liter')])
		db.add_recipe(r)
Ejemplo n.º 2
0
def test_rpc_inventory():
    db.load_db('Database')

    #making an empty environ dictionary
    environ = {}
    environ['PATH_INFO'] = '/rpc'
    d = dict(method= 'liquor_inventory',params=[], id=1)
    encoded = simplejson.dumps(d)
    environ['wsgi.input'] = StringIO(encoded) 
    environ['CONTENT_LENGTH'] = len(encoded) 
    environ['REQUEST_METHOD'] = 'POST' 
   
    #making a start_response function 
    d = {}
    def my_start_response(s, h, return_in=d):
        d['status'] = s
        d['headers'] = h

    app_obj = app.SimpleApp()
    results = app_obj(environ, my_start_response)

    text = "".join(results)
    status, headers = d['status'], d['headers']
   
    assert text.find('Johnnie Walker') != -1, text
    assert text.find('Rossi') != -1, text
    assert text.find('moonshine') != -1, text
    assert text.find('vodka') != -1, text
    assert ('Content-Type', 'application/json') in headers
    assert status == '200 OK'
Ejemplo n.º 3
0
def insert_movies_to_db():
    to_db = None
    with open('movies.csv', 'rb') as fin:
        dr = csv.DictReader(fin)
        to_db = [(i['movieId'], i['title'], i['genres'].split('|')[0])
                 for i in dr]
    db.load_db(to_db)
Ejemplo n.º 4
0
def test_rpc_add_liquor_type():
    db.load_db('Database')

    #making an empty environ dictionary
    environ = {}
    environ['PATH_INFO'] = '/rpc'
    d = dict(method= 'add_liquor_type',params=[("Marco Botros","vodka","like the moon")], id=1)
    encoded = simplejson.dumps(d)
    environ['wsgi.input'] = StringIO(encoded) 
    environ['CONTENT_LENGTH'] = len(encoded) 
    environ['REQUEST_METHOD'] = 'POST' 
   
    #making a start_response function 
    d = {}
    def my_start_response(s, h, return_in=d):
        d['status'] = s
        d['headers'] = h

    app_obj = app.SimpleApp()
    results = app_obj(environ, my_start_response)

    text = "".join(results)
    status, headers = d['status'], d['headers']
   
    assert db._check_bottle_type_exists('Marco Botros', 'vodka')
    assert ('Content-Type', 'application/json') in headers
    assert status == '200 OK'
Ejemplo n.º 5
0
def test_rpc_convert():
    #making an empty environ dictionary
    db.load_db('Database')
    environ = {}
    environ['PATH_INFO'] = '/rpc'
    d = dict(method= 'convert_units_to_ml',params=['1 oz'], id=1)
    dataE = simplejson.dumps(d)
    environ['wsgi.input'] = StringIO(dataE) 
    environ['CONTENT_LENGTH'] = len(dataE) 
    environ['REQUEST_METHOD'] = 'POST' 
   
    #making a start_response function 
    d = {}
    def my_start_response(s, h, return_in=d):
        d['status'] = s
        d['headers'] = h

    app_obj = app.SimpleApp()
    results = app_obj(environ, my_start_response)

    text = "".join(results)
    status, headers = d['status'], d['headers']
   
    assert '29.5735' in results[0], results[0]
    assert text.find('29.5735') != -1, text
    assert ('Content-Type', 'application/json') in headers
    assert status == '200 OK'
Ejemplo n.º 6
0
def test_rpc_recipes():
    db.load_db("Database")

    #making an empty environ dictionary
    environ = {}
    environ['PATH_INFO'] = '/rpc'
    d = dict(method= 'recipes_names',params=[], id=1)
    encoded = simplejson.dumps(d)
    environ['wsgi.input'] = StringIO(encoded) 
    environ['CONTENT_LENGTH'] = len(encoded) 
    environ['REQUEST_METHOD'] = 'POST' 
   
    #making a start_response function 
    d = {}
    def my_start_response(s, h, return_in=d):
        d['status'] = s
        d['headers'] = h

    app_obj = app.SimpleApp()
    results = app_obj(environ, my_start_response)

    text = "".join(results)
    status, headers = d['status'], d['headers']
  
    assert text.find('scotch on the rocks') != -1, text
    assert text.find('vodka martini') != -1, text
    assert ('Content-Type', 'application/json') in headers
    assert status == '200 OK'
Ejemplo n.º 7
0
def test_rpc_add_to_inventory():
    db.load_db('Database')

    #making an empty environ dictionary
    environ = {}
    environ['PATH_INFO'] = '/rpc'
    d = dict(method= 'add_recipe',params=['THE DUDE',[("Marco Botros","3 oz"),('vodka','1 liter')]], id=1)
    encoded = simplejson.dumps(d)
    environ['wsgi.input'] = StringIO(encoded) 
    environ['CONTENT_LENGTH'] = len(encoded) 
    environ['REQUEST_METHOD'] = 'POST' 
   
    #making a start_response function 
    d = {}
    def my_start_response(s, h, return_in=d):
        d['status'] = s
        d['headers'] = h

    app_obj = app.SimpleApp()
    results = app_obj(environ, my_start_response)

    text = "".join(results)
    status, headers = d['status'], d['headers']
  	
    assert db.get_recipe('THE DUDE'),db._recipes_db
    assert ('Content-Type', 'application/json') in headers
    assert status == '200 OK'
Ejemplo n.º 8
0
def test_get_liquor_inventory():
	db.load_db('db')
	environ = {}
	environ['PATH_INFO'] = '/rpc'
	environ['REQUEST_METHOD'] = 'get_liquor_inventoryPOST'



	d = dict(method = 'get_liquor_inventory', params=[], id=1)
	encoded = simplejson.dumps(d)	
	output = StringIO.StringIO(encoded)


	environ['wsgi.input'] = output
	environ['CONTENT_LENGTH'] = len(output.getvalue())

	headers = { 'Content-Type' : 'application/json' }

	def my_start_response(s, headers, return_in=d):
		d['status'] = s
		d['headers'] = headers


	app_obj = app.SimpleApp()
	json_response = app_obj(environ, my_start_response)
	json_response = json_response[0]
	response = simplejson.loads(json_response)

	print response['result'][0]
	assert response['result'][0] == ['Captain Morgan', 'rum']
Ejemplo n.º 9
0
def load_database(filename):
	try:
		#Try to load from database
		f_name = os.path.dirname(__file__) + filename
	   	db.load_db(f_name)
		#print "Loaded from database"

	except Exception:
		#If the file was not found add items
		add_items()
		#print 'Added db'
		pass
Ejemplo n.º 10
0
def setUpWebServer():
    filename = 'database.db'
    load_db(filename)
    port = random.randint(8000, 9999)
    
    app = SimpleApp()
    
    httpd = make_server('', port, app)
    print "Serving on port %d..." % port
    print "Try using a Web browser to go to http://%s:%d/" % \
        (socket.getfqdn(), port)
    httpd.serve_forever()
Ejemplo n.º 11
0
def WebServer():
    import random, socket

    port = random.randint(8000, 9999)

    filename = "myDatabase"
    load_db(filename)
    app = SimpleApp()

    httpd = make_server("", port, app)
    print "Serving on port %d..." % port
    print "Try using a Web browser to go to http://%s:%d/" % (socket.getfqdn(), port)
    httpd.serve_forever()
Ejemplo n.º 12
0
def get_app_settings():
    return {
        'autoreload': to_bool(os.getenv('AUTORELOAD')),
        'debug': to_bool(os.getenv('DEBUG')),
        'serve_traceback': to_bool(os.getenv('SERVE_TRACEBACK')),
        'db': load_db(get_db_settings())
    }
Ejemplo n.º 13
0
def has_buy_recently(qq, delta):
    db = load_db()

    if key_buy_time not in db:
        return False

    buy_time = db[key_buy_time].get(str(qq), "2021-01-01 00:00:00")

    return parse_time(buy_time) >= datetime.now() - delta
Ejemplo n.º 14
0
def save_buy_timestamp(qq):
    db = load_db()

    if key_buy_time not in db:
        db[key_buy_time] = {}

    db[key_buy_time][str(qq)] = format_time(datetime.now())

    save_db(db)
Ejemplo n.º 15
0
def has_buy_in_an_hour(qq):
    db = load_db()

    if key_buy_time not in db:
        return False

    buy_time = db[key_buy_time].get(str(qq), "2021-01-01 00:00:00")

    return parse_time(buy_time) >= datetime.now() - timedelta(hours=1)
Ejemplo n.º 16
0
    def load_database(self):
	try:
        	db.load_db(_path_db)
	except:

        	db.add_bottle_type('Johnnie Walker', 'black label', 'blended scotch')
        	db.add_to_inventory('Johnnie Walker', 'black label', '500 ml')
        	db.add_bottle_type('Uncle Herman\'s', 'moonshine', 'blended scotch')
        	db.add_to_inventory('Uncle Herman\'s', 'moonshine', '5 liter')
        	db.add_bottle_type('Gray Goose', 'vodka', 'unflavored vodka')
        	db.add_to_inventory('Gray Goose', 'vodka', '1 liter')
        	db.add_bottle_type('Rossi', 'extra dry vermouth', 'vermouth')
        	db.add_to_inventory('Rossi', 'extra dry vermouth', '24 oz')
        	r1 = recipes.Recipe('vomit inducing martini', [('orange juice','6 oz'),('vermouth','1.5 oz')])
        	r2 = recipes.Recipe('scotch on the rocks', [('blended scotch', '4 oz')])
        	r3 = recipes.Recipe('vodka martini', [('unflavored vodka', '6 oz'),('vermouth', '1.5 oz')])
        	db.add_recipe(r1)
        	db.add_recipe(r2)
        	db.add_recipe(r3)
Ejemplo n.º 17
0
def create_data():
    try:
        db.load_db('database')
    except Exception:
        db._reset_db()

        db.add_bottle_type('Johnnie Walker', 'black label', 'blended scotch')
        db.add_to_inventory('Johnnie Walker', 'black label', '500 ml')

        db.add_bottle_type('Uncle Herman\'s', 'moonshine', 'blended scotch')
        db.add_to_inventory('Uncle Herman\'s', 'moonshine', '5 liter')

        db.add_bottle_type('Gray Goose', 'vodka', 'unflavored vodka')
        db.add_to_inventory('Gray Goose', 'vodka', '1 liter')

        db.add_bottle_type('Rossi', 'extra dry vermouth', 'vermouth')
        db.add_to_inventory('Rossi', 'extra dry vermouth', '24 oz')

        r = recipes.Recipe('scotch on the rocks', [('blended scotch', '2 oz')])
        r2 = recipes.Recipe('vodka martini', [('unflavored vodka', '6 oz'), ('vermouth', '1.5 oz')])
        db.add_recipe(r)
        db.add_recipe(r2)
Ejemplo n.º 18
0
def main(args):
    try:
        logging.basicConfig(level=args.log_level)
    except ValueError as e:
        print('Unable to initialise logging: %s' % e)
        raise SystemExit
    logging.info('Starting the server...')
    logging.info('Version: %s.', server_version())
    config.config = config.Config.load(args.config_file)
    from db import load_db, dump_db
    load_db()
    from networking import factory
    listener = reactor.listenTCP(config.config.port,
                                 factory,
                                 interface=config.config.interface)
    logging.info('Listening on %s:%d.', listener.interface, listener.port)
    from log_handler import LogHandler
    logging.getLogger().addHandler(LogHandler())
    reactor.run()
    logging.info('Server shutting down.')
    dump_db()
    config.config.dump(args.config_file)
Ejemplo n.º 19
0
def load_external_artist_list(top, nodefile, dbpath=None):
    if dbpath:
        db.load_db(dbpath)
    for i, line in enumerate(open('top_artists.txt')):
        if i < top:
            fields = line.strip().split()
            uri = fields[0]
            count = int(fields[1])
            name = ' '.join(fields[2:])

            if uri not in known_artists:
                print "NEW", i, uri, count, name
                artist = None
                if dbpath:
                    artist = db.get_artist(uri)
                if not artist:
                    artist = spotify.artist(uri)
                else:
                    print "  cache hit for", name
                known_artists.add(uri)
                queue_append(artist)
                print >> nodefile, json.dumps(artist)
        else:
            break
Ejemplo n.º 20
0
def load_external_artist_list(top, nodefile, dbpath=None):
    if dbpath:
        db.load_db(dbpath)
    for i, line in enumerate(open('top_artists.txt')):
        if i < top:
            fields = line.strip().split()
            uri = fields[0]
            count = int(fields[1])
            name = ' '.join(fields[2:])

            if uri not in known_artists:
                print "NEW", i, uri, count, name
                artist = None
                if dbpath:
                    artist = db.get_artist(uri)
                if not artist:
                    artist = spotify.artist(uri)
                else:
                    print "  cache hit for", name
                known_artists.add(uri)
                queue_append(artist)
                print >> nodefile,  json.dumps(artist)
        else:
            break
Ejemplo n.º 21
0
from db import load_db
import sys
import re

db = load_db()

if len(sys.argv) < 1:
    print("usage", sys.argv[0], "template")
    exit()

template_name = sys.argv[1].lower()
regexp = re.compile("{{" + template_name + ".*?}}", flags=re.DOTALL)


def parse_page(page):
    result = dict()
    text = page["wikitext"].lower()
    if template_name not in text:
        return {}

    re_results = regexp.findall(text)
    for j in re_results:
        if "|" in j:
            result.update({page["title"]: len(j.split("|"))})
        else:
            result.update({page["title"]: 0})
    return result


match_list = dict()
for i in db.values():
Ejemplo n.º 22
0
        'spotify:artist:3WrFJ7ztbogyGnTHbHJFl2',  # the beatles
        'spotify:artist:6eUKZXaKkcviH0Ku9w2n3V',  # ed sheeran
        'spotify:artist:36QJpDe2go2KgaRleHCDTp',  # led zeppelin
    ]

    args = sys.argv[1:]
    prefix = "./"

    while args:
        arg = args.pop(0)

        if arg == '--path':
            prefix = args.pop(0)

        elif arg == '--load':
            db.load_db(prefix)

            artists = db.get_all_artists()

            for uri, artist in artists.items():
                known_artists.add(uri)

            edges = db.get_all_edges()

            for source, targets in edges.items():
                check_ta_uri('load expanded', source)
                expanded_artists.add(source)

            for uri, artist in artists.items():
                if uri not in expanded_artists:
                    queue_append(artist)
Ejemplo n.º 23
0
# -*- coding: iso-8859-1 -*-
from wsgiref.simple_server import make_server
import urlparse
import simplejson
import db, recipes
import sys
import os
import css_html
import jinja2
import test_load_recipe


sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
try:
    _path_db = os.path.dirname(__file__) + '/../database'
    db.load_db(_path_db)
except:
    _path_db = os.path.dirname(__file__) + '../database'  
    db.load_db(_path_db)
#Input different data







dispatch = {
    '/' : 'index',
    '/recipe' : 'recipe',
    '/inventory' : 'inventory',
Ejemplo n.º 24
0
import eyed3
import db

""" testing:
artist: https://music.youtube.com/channel/UChmAdYjOdnnrSA2kBMKdoYw
playlist: https://music.youtube.com/playlist?list=OLAK5uy_m9Ce3WCVVZXhHZNwdzaPQcY725pY9vIg0
browse: https://music.youtube.com/browse/MPREb_L3mB1OJ9weN
song: https://music.youtube.com/watch?v=_mapaZYhg7c&list=RDAMVM_mapaZYhg7c
"""

# setup youtube music
# YTMusic.setup(filepath="headers_auth.json")
# ytmusic = YTMusic("headers_auth.json")
ytmusic = YTMusic()

cache = db.load_db()

ARTIST, PLAYLIST, SONG = 0, 1, 2

def get_browse_id(url: str) -> str:
    """ Returns the browse id from a playlist url. """
    session = HTMLSession()
    r = session.get(url)
    t = r.html.html
    i = t.find("browseId") + 13
    l = t[i:].find("\\")
    bid = t[i: i + l]
    # re-search if found browse id is not valid
    while bid == "SPunlimited":
        t = t[i + l:]
        i = t.find("browseId") + 13
Ejemplo n.º 25
0
        'spotify:artist:3WrFJ7ztbogyGnTHbHJFl2', # the beatles
        'spotify:artist:6eUKZXaKkcviH0Ku9w2n3V', # ed sheeran
        'spotify:artist:36QJpDe2go2KgaRleHCDTp', # led zeppelin
    ]

    args = sys.argv[1:]
    prefix = "./"

    while args:
        arg = args.pop(0)

        if arg == '--path':
            prefix = args.pop(0)

        elif arg == '--load':
            db.load_db(prefix)

            artists = db.get_all_artists()

            for uri, artist in artists.items():
                known_artists.add(uri)

            edges = db.get_all_edges()

            for source, targets in edges.items():
                check_ta_uri('load expanded', source)
                expanded_artists.add(source)

            for uri, artist in artists.items():
                if uri not in expanded_artists:
                    queue_append(artist)
Ejemplo n.º 26
0
 def load_db(self, filename):
     db.load_db(filename)
Ejemplo n.º 27
0
            current_series = [pic]
            series.append(current_series)
        else:
            if (pic[0] - last_datetime).total_seconds() > 4:
                # The pictures are not taken within less than 5 seconds, so
                # start a new series now:
                current_series = [pic]
                series.append(current_series)
            else:
                # The pictures is taken less than 5 seconds after the previous
                # one, so add it to the series:
                current_series.append(pic)
        last_datetime = pic[0]
    return remove_single_entries(series)


(series, singleshots) = detect_series(
    db.load_db('photos.db', db.PicturesSort.by_date_time))

target_path = '.\\SampleOutput\\'

for x in series:
    series_no = x[0][0].strftime('%Y-%m-%d-%H-%M-%S')
    series_path = os.path.abspath(os.path.join(target_path, series_no))
    if not (os.path.isdir(series_path) and os.path.exists(series_path)):
        os.makedirs(series_path)
    for pic in x:
        target_file = os.path.join(series_path, os.path.basename(pic[1]))
        print('Copying {0} to {1}'.format(pic[1], target_file))
        shutil.copyfile(pic[1], target_file)
Ejemplo n.º 28
0
def main(args):
    filename = args[1]
    db.load_db(filename)
Ejemplo n.º 29
0
 def load_db_file(self, file_name):
     db.load_db(file_name)
Ejemplo n.º 30
0
def load_db(file_name):
	    db.load_db(file_name)
Ejemplo n.º 31
0
### make a directory to store the generated html files
try:
    os.mkdir('html')
except OSError:
    # already exists
    pass

### Initialize the html templates - http://jinja.pocoo.org/docs/api/
env = Environment( loader = PackageLoader('drinkz', 'html-templates') )
print env
    
### POPULATE DB (from file or inline)

try:
    db.load_db('initDatabase')
except:
    db.add_bottle_type('Johnnie Walker', 'black label', 'blended scotch')
    db.add_to_inventory('Johnnie Walker', 'black label', '500 ml')

    db.add_bottle_type('Uncle Herman\'s', 'moonshine', 'blended scotch')
    db.add_to_inventory('Uncle Herman\'s', 'moonshine', '5 liter')
                    
    db.add_bottle_type('Gray Goose', 'vodka', 'unflavored vodka')
    db.add_to_inventory('Gray Goose', 'vodka', '1 liter')

    db.add_bottle_type('Rossi', 'extra dry vermouth', 'vermouth')
    db.add_to_inventory('Rossi', 'extra dry vermouth', '24 oz')

    r = recipes.Recipe('scotch on the rocks', [('blended scotch',
                                                    '4 oz')])
Ejemplo n.º 32
0
from drinkz import recipes

dispatch = {
    '/' : 'index',
    '/recipes' : 'recipes',
    '/error' : 'error',
    '/inventory' : 'inventory',
    '/liquor_types' : 'liquor_types',
    '/form' : 'form',
    '/recv' : 'recv',
    '/rpc'  : 'dispatch_rpc'
}

html_headers = [('Content-type', 'text/html')]

db.load_db("Database")

begining = """ \
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <title> %s </title>
        <script>
            function alertThem(){
                alert("Hi you are awesome");
            }
        </script>
        <style type="text/css"> 
            h2{
                color: #B0171F;
Ejemplo n.º 33
0
def initDB():
    db.load_db('../bin/database')