Ejemplo n.º 1
0
 def setUpClass(cls):
     model.connect_string = 'sqlite:///:memory:' 
     model.echo = True
     model.init()
     model.Task('task1', 'category1')
     model.Task('task2', 'category2')
     model.commit()
Ejemplo n.º 2
0
def init( config_file = None ):

    cfg = config.init( config_file )
    lib = cfg.get_path( 'library' )

    if( not os.path.isdir( lib ) ):
        os.makedirs( lib )

    model.init( os.path.join( lib, HIGURASHI_DB_NAME ) )
Ejemplo n.º 3
0
def sql():
    init()
    root = Tkinter.Tk()
    root.geometry('800x600')
    root.title('microRNA查询工具')
    root.option_add("*Font", "helvetica -12")

    main = Main(root)
    main.pack()

    root.mainloop()
Ejemplo n.º 4
0
def run():
    parser = argparse.ArgumentParser()
    parser.add_argument("model_dir",
                        help="directory where model files are stored")
    args = parser.parse_args()

    logger.debug("Init BERT models")
    model.init(args.model_dir)

    logger.debug("Run app")
    waitress.serve(app.run("0.0.0.0", port=1337))
Ejemplo n.º 5
0
def init(library_path=None):
    global _LIBRARY

    if (library_path is not None):
        _LIBRARY = library_path
    else:
        _LIBRARY = DEFAULT_LIBRARY

    if (not os.path.isdir(_LIBRARY)):
        os.makedirs(_LIBRARY)

    model.init(os.path.join(_LIBRARY, HIGURASHI_DB_NAME), _LIBRARY)
Ejemplo n.º 6
0
def main():
    # DB stuff
    connect()
    init()

    globalized.init()

    # TCP stuff
    listener = listen()

    # REST stuff
    launch()
Ejemplo n.º 7
0
def init( library_path = None ):
    global _LIBRARY

    if( library_path is not None ):
        _LIBRARY = library_path
    else:
        _LIBRARY = DEFAULT_LIBRARY

    if( not os.path.isdir( _LIBRARY ) ):
        os.makedirs( _LIBRARY )

    model.init( os.path.join( _LIBRARY, HIGURASHI_DB_NAME ),
                _LIBRARY )
Ejemplo n.º 8
0
    def setUp(self):

        class Brython(dict):
            def __init__(self):
                dict.__init__({})
                self.DOC, self.SVG, self.HTML, self.AJAX = [self]*4
                self.doc = dict(base=self)
                self['base'] = self['book'] = self
                self.cookie = '_xsrf=123456; '
                self.WIN, self.STORAGE, self.JSON, self.TIME = [self]*4
                self.__getitem__ = self.DIV = self.div = self.IMG = self.nop
                self.div = self.img = self.deploy = self.employ = self.nop
                self.show_front_menu = self.screen_context = self.nop
                self.aler = self.prom = self.conf = self.nop
                self.offsetLeft = self.offsetTop = self.menuX = self.menuY = 1
                self.Id = self.search = ''
                self.location = self.target = self
                self.aargs = self.items = self.evs = []

            def __le__(self, other):
                """
                shades brython append operator
                """
                pass

            def activate(self, **kwargs):
                self.aargs = kwargs

            def bind(self, ev, hook):
                self.evs.append(hook)
                return self

            def nop(self, *args, **kwargs):
                return self

            def __call__(self, *args, **kwargs):
                return self

        class _Gui(dict):

            def employ(self, **kwargs):
                print('setUp employ')
                #self['adm1n'].update(kwargs)
                return 'adm1n', 1

        self.control = model.init()
        self.br = Brython()
        self.br.dumps = json.dumps
        self.br.loads = json.loads
        self.app = Gui(self.br)
        self.app._locate = self.app._filter = MagicMock(name='locate')
        self.app.menuX = self.app.menuY = 1
        self.builder = Builder(self.br, self.control)
        self.builder.build_all(self.app)
        self.gui = _Gui()
        self.gui['adm1n'] = {}
        Gui.REV = {}
        self.control.ALL_THINGS = model.Thing.ALL_THINGS = {}
        self.control.items = []
Ejemplo n.º 9
0
def show_1(part):
    if request.method == 'GET':
        logfile.write(
            str(time.time()) + ": EXPERIMENT GET, part: " + part + "\n")

        if (part in ["1", "2", "3", "4"]):
            # Set the title for the top of the screen
            title = part

            # Set the link location
            if part == "1":
                link_loc = "/experiment/2"
            elif part == "2":
                link_loc = "/survey/1"
            elif part == "3":
                link_loc = "/experiment/4"
            elif part == "4":
                link_loc = "/survey/2"

            problem_text = render_template('problem' + part + '.html')

            data = {"title": title, "link": link_loc, "problem": problem_text}

            return render_template('enterEquation.html', data=data)

    else:
        logfile.write(
            str(time.time()) + ": EXPERIMENT POST, part: " + part + "\n")

        if (part in ["1", "2", "3", "4"]):
            #DO THE EQUATION SOLVING STUFF
            # Set the equation
            startEquation = request.form['equation']

            # Set the title for the top of the screen
            title = part

            # Set the link location
            if part == "1":
                link_loc = "/experiment/2"
                isActive = active_list[0]
            elif part == "2":
                link_loc = "/survey/1"
                isActive = active_list[0]
            elif part == "3":
                link_loc = "/experiment/4"
                isActive = active_list[1]
            elif part == "4":
                link_loc = "/survey/2"
                isActive = active_list[1]

            startState = model.init(startEquation, isActive)

            problem_text = render_template('problem' + part + '.html')

            data = {"title": title, "link": link_loc, "problem": problem_text}

            # return template
            return render_template('view2.html', state=startState, data=data)
Ejemplo n.º 10
0
def main(args):
    """
>>> import model, control, rest
>>> rest.load_props()
>>> model.init("advcruddb", "test", 2)
>>> _ = model.clean()
>>> body = "LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS05NTc0MmEwYmJkOGE5MjU3DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9InBob3RvIjsgZmlsZW5hbWU9ImhlbGxvLnR4dCINCkNvbnRlbnQtVHlwZTogdGV4dC9wbGFpbg0KDQpoZWxsbwoNCi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tOTU3NDJhMGJiZDhhOTI1Nw0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJuYW1lIg0KDQpoZWxsbw0KLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS05NTc0MmEwYmJkOGE5MjU3DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImVtYWlsIg0KDQpoQGwubw0KLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS05NTc0MmEwYmJkOGE5MjU3LS0NCg=="
>>> ctype = "multipart/form-data; boundary=------------------------95742a0bbd8a9257"
>>> args = { "__ow_body": body, "__ow_headers": { "content-type": ctype}, "__ow_method": "post" }
>>> _ = control.main(args)
>>> _id = model.find()["docs"][0]["_id"]
>>> args = { "__ow_path": "/"+_id}
>>> control.main(args)
{'body': 'aGVsbG8K', 'headers': {'Content-Type': 'text/plain'}}
    """
    model.init(args["db"], "contact", 2)
    return control.main(args)
Ejemplo n.º 11
0
 def test_insert_table_from_open_now(self):
     model.init('Chicago')
     model.insert_table_from_scrap('Chicago')
     baseurl='https://api.yelp.com/v3/businesses/search'
     headers={'Authorization': 'Bearer %s' % secret.api_key}
     params={}
     params['location']='Chicago'
     params['open_now']=True
     results=model.make_request_using_cache(baseurl,headers,params)
     model.insert_table_from_api(results,'bars')
     conn = sqlite3.connect('final507.sqlite')
     cur = conn.cursor()
     statement='select * from restaurants_info where id=?'
     cur.execute(statement,[results['businesses'][0]['id']])
     result=cur.fetchone()
     self.assertEqual(results['businesses'][0]['id'],result[0])
     conn.commit()
     conn.close()
Ejemplo n.º 12
0
 def test_plot_prepare_type(self):
     model.init('Chicago')
     model.insert_table_from_scrap('Chicago')
     baseurl='https://api.yelp.com/v3/businesses/search'
     headers={'Authorization': 'Bearer %s' % secret.api_key}
     params={}
     params['location']='Chicago'
     params['price']=2
     results=model.make_request_using_cache(baseurl,headers,params)
     model.insert_table_from_api(results,'bars')
     conn = sqlite3.connect('final507.sqlite')
     cur = conn.cursor()
     statement='select r.lati,r.logi,r.name,r.id from restaurants_info as r join city_info as c on c.Id=r.city where r.price=? and c.name =? limit 20'
     cur.execute(statement,('$$', 'Chicago'))
     result=cur.fetchall()
     data,style=model.plot_prepare(result)
     self.assertIsInstance(data,list)
     self.assertIsInstance(style,dict)
Ejemplo n.º 13
0
def start():
    import socket
    model.init()
    serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto=0)
    serv_sock.bind(('', 9090))
    serv_sock.listen(10)

    while True:
        client_sock, address = serv_sock.accept()
        print('Connected by', address)

        while True:
            data = client_sock.recv(64000)
            if not data:
                break
            request = pickle.loads(data)
            client_sock.sendall(check_request(request))

        client_sock.close()
Ejemplo n.º 14
0
def getCrimeType():
    crimeDate = request.args.get("cDate")
    crimeLng = request.args.get("cLng")
    crimeLtd = request.args.get("cLtd")
    df = pd.DataFrame({
        "crimeDate": [crimeDate],
        "crimeLng": [float(crimeLng)],
        "crimeLtd": [float(crimeLtd)]
    })
    crimeType = model.init(df, loaded_model)
    return jsonify(crimeType=str(crimeType[0]))
Ejemplo n.º 15
0
    def test_init(self):
        init('tmp/config.json')

        with self.subTest(i=0):
            self.assertEqual(Ocean.DEFAULT_SIZE, 100000)

        with self.subTest(i=1):
            self.assertEqual(Shark.FULLNESS, 100000)

        with self.subTest(i=2):
            self.assertEqual(Shark.REPRODUCTION, 100000)

        with self.subTest(i=3):
            self.assertEqual(Shark.LIFE, 100000)

        with self.subTest(i=4):
            self.assertEqual(Guppies.REPRODUCTION, 100000)

        with self.subTest(i=5):
            self.assertEqual(Guppies.LIFE, 100000)
Ejemplo n.º 16
0
def main():
    app = QtWidgets.QApplication(sys.argv)  # A new instance of QApplication
    online_bills, onsite_bills = init()
    # We set the form to be our ExampleApp (design)
    user_view = UserOP(online_bills, onsite_bills)
    user_view.show()  # Show the form
    # We set the form to be our ExampleApp (design)
    op_view = CounterOP(online_bills, onsite_bills, user_view)
    op_view.show()  # Show the form

    app.exec_()  # and execute the app
Ejemplo n.º 17
0
 def __init__(self, root):
     '''
     Init Form
     '''
     self.root = root
     self.createFrameTop()
     self.createFrameMiddle()
     self.createFrameBottom()
     self.matrix = model.init()
     self.root['bg'] = root_bg
     self.root.bind("<KeyPress> ", self.bind_key)
Ejemplo n.º 18
0
async def initial_startup():
    """
    Calls the init() method in the model and prepares the model to receive predictions. The init
    task may take a long time to complete, so the settings field ready_to_predict will be updated
    asynchronously when init() completes.

    :return: {"result": "starting"}
    """
    # Run startup task async
    init_task = asyncio.create_task(init())
    settings.ready_to_predict = True
    return {"result": "starting"}
Ejemplo n.º 19
0
 def __init__(self, root):
     '''
     Init Form
     '''
     self.root = root
     self.createFrameTop()
     self.createFrameMiddle()
     self.createFrameBottom()
     self.matrix = model.init()
     matrix_stack.append(self.matrix)
     matrix_stack_forward.append(self.matrix)
     self.btn_show_matrix(self.matrix)
     self.root.bind("<KeyPress> ", self.bind_key)
Ejemplo n.º 20
0
 def __init__(self, root):
     '''
     Init Form
     '''
     self.root = root
     self.createFrameTop()
     self.createFrameMiddle()
     self.createFrameBottom()
     self.matrix = model.init()
     matrix_stack.append(self.matrix)
     matrix_stack_forward.append(self.matrix)
     self.btn_show_matrix(self.matrix)
     self.root.bind("<KeyPress> ", self.bind_key)
Ejemplo n.º 21
0
def initialize():
    global m_k, tobn, k, samples, w_T, w_k, w_sum, w_X, E,P, update_int, topo, k_max, learn_stages 
    update_int = 2500
    k_max = 20
    k = 0
    learn_stages = 5
    topo = ['bppv', 'alc', 'mm', 'v_', 'rv', 'pv_', 'pv1', 'pv2', 'pv', 'v'] 
    #topo = bn.topo_ordered(m) 
    
    m_k = bnmodel.init(cpts)# create a model to modify
    for n in e:
        m[n].value = e[n]
        m_k[n].value = e[n]
    tobn = [m_k[node] for node in topo]
Ejemplo n.º 22
0
    def main(self):
        self.opts, args = self.parse_args()
        self.setup_logging()

        self.log.debug('Initializing database.')
        model.init(self.opts.dburi)
        self.session = model.Session()

        try:
            try:
                cmd = args.pop(0)
            except IndexError:
                cmd = 'status'

            if cmd == 'start':
                self.cmd_start(args)
            elif cmd == 'stop':
                self.cmd_stop(args)
            elif cmd == 'list':
                self.cmd_list(args)
            elif cmd == 'status':
                self.cmd_status(args)
            elif cmd == 'report':
                self.cmd_report(args)
            elif cmd == 'cancel':
                self.cmd_cancel(args)
            elif cmd == 'drop':
                self.cmd_drop(args)
            elif cmd == 'log':
                self.cmd_log(args)
            elif cmd == 'help':
                self.cmd_help(args)
            else:
                self.cmd_start([cmd] + args)
        except TrackerError, detail:
            self.log.error(detail)
            sys.exit(1)
Ejemplo n.º 23
0
def main():
    config = configparser.ConfigParser()
    config.read(CONFIG)
    try:
        config['DEFAULT']['model']
    except KeyError:
        config['DEFAULT']['model'] = 'dummy'
        with open(CONFIG, 'w') as fil:
            config.write(fil)

    if config['DEFAULT']['model'] == 'sqlite':
        ctr = model.MatchSqliteDb
    elif config['DEFAULT']['model'] == 'mysql':
        ctr = model.MatchMysqlDb
    elif config['DEFAULT']['model'] == 'postgresql':
        ctr = model.MatchPostgresqlDb
    elif config['DEFAULT']['model'] == 'dummy':
        ctr = model.MatchList
    else:
        print('WARNING: Config is broken!')
        sys.exit(1)

    model.init(ctr)
    choose_menu()
Ejemplo n.º 24
0
    def reset_game(self):
        '''
        reset game
        '''
        global play_flag
        self.matrix = model.init()

        model.g_score = 0
        self.label_top_list[1]['text'] = model.g_score

        del matrix_stack[0:]
        matrix_stack.append([self.matrix, model.g_score])
        self.btn_show_matrix(self.matrix)

        play_flag = True
        self.show_play_time()
Ejemplo n.º 25
0
    def __init__(self, panel, stepSize, speed, eccentricity, tilt, precession):
        self.panel = panel

        # Creates the animation
        self.animation = Scene(title="SolarSIM",
                               x=400,
                               y=0,
                               width=800,
                               height=800,
                               center=(0, 0, 0)).scene
        self.system = model.init(eccentricity, tilt, precession)

        # Set settings
        self.stepSize = stepSize
        self.speed = speed
        self.eccentricity = eccentricity
        self.tilt = tilt
        self.precession = precession
async def initial_startup():
    """
    Calls the init() method in the model and prepares the model to receive predictions. The init
    task may take a long time to complete, so the settings field ready_to_predict will be updated
    asynchronously when init() completes.

    :return: {"result": "starting"}
    """
    # Run startup task async
    load_dotenv()

    # Register the model to the server in a separate thread to avoid meddling with
    # initializing the service which might be used directly by other client later on
    future = pool.submit(register_model_to_server, os.getenv('SERVER_PORT'), os.getenv('PORT'), os.getenv('NAME'))

    init_task = asyncio.create_task(init())
    settings.ready_to_predict = True
    return {"result": "starting"}
Ejemplo n.º 27
0
def show_index():
    if request.method == 'GET':
        logfile.write(
            str(time.time()) + ": INDEX GET: EXPERIMENT GONE WRONG!!!\n")
        # begin.html, empty mathquill entry
        return render_template('begin.html')

    else:
        logfile.write(
            str(time.time()) +
            ": INDEX POST START: EXPERIMENT GONE WRONG!!!\n")
        # render view.html with initial state baked in
        startEquation = request.form['equation']
        startActive = request.form['active']
        print("got equation: " + startEquation)
        print("got active: " + startActive)

        startState = model.init(startEquation, startActive)

        print("start is: " + str(startState))
        logfile.write(
            str(time.time()) + ": START STATE IS " + str(startState) + "\n")

        return render_template('view.html', state=startState)
Ejemplo n.º 28
0
def main():
    model.init()
    model.train(data_collection.train_data)
Ejemplo n.º 29
0
import asyncio

from lib import wait_for_job, check_file_exists

repo_path = os.path.dirname(sys.path[0])
  
sys.path.append(os.path.join(repo_path, "src/gui"))
import model as M
import view as V
import controller as C

os.makedirs(os.path.join(repo_path, "test/scratch/seeds"))
shutil.copy(os.path.join(repo_path, "configuration.pysh"),
            os.path.join(repo_path, "test/scratch/seeds"))

M.init(None, os.path.join(repo_path, "test/scratch/seeds/configuration.pysh"))
V.init(None)
C.init(None)

os.makedirs(os.path.join(repo_path, "test/scratch/seeds/groundtruth-data/round1"))
shutil.copy(os.path.join(repo_path, "data/PS_20130625111709_ch3.wav"),
            os.path.join(repo_path, "test/scratch/seeds/groundtruth-data/round1"))

run(["hetero", "start", "1", "1", "1"])

shutil.copy(os.path.join(repo_path, "data/PS_20130625111709_ch3-annotated-person1.csv"),
            os.path.join(repo_path, "test/scratch/seeds/groundtruth-data/round1"))

V.context_ms_string.value = "204.8"
V.shiftby_ms_string.value = "0.0"
V.optimizer.value = "adam"
Ejemplo n.º 30
0
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)

PIECE_COLOURS = (WHITE, RED, GREEN, BLUE, YELLOW)

PIECE_WIDTH = 30
PIECE_HEIGHT = 30
PIECE_MARGIN = 2

pygame.init()
model.init()

windowSurface = pygame.display.set_mode((
    model.get_width() * (PIECE_WIDTH + PIECE_MARGIN),
    model.get_height() * (PIECE_HEIGHT + PIECE_MARGIN)
))
pygame.display.set_caption('Same Game')

clock = pygame.time.Clock()

while True:
    clock.tick(30)
    windowSurface.fill(BLACK)
    for y in range(model.get_height()):
        for x in range(model.get_width()):
            colour = model.get_block_colour(x, y)
Ejemplo n.º 31
0
		form.populate_obj(user)
		db_session.add(user)
		db_session.commit()
		login.login_user(user)
 		return redirect(url_for('index'))
	return render_template('form.html', form=form)


@app.route('/logout/')
def logout_view():
    #print "on logout"+ request.cookies	
    print request.session
    login.logout_user()
    return redirect(url_for('index'))

if __name__ == '__main__':
    # Initialize flask-login
	init_login()
	db_session = init('sqlite:///test.sqlite')
	
    # Create admin
	admin = admin.Admin(app, 'Auth', index_view=MyAdminIndexView())
    # Add view
	admin.add_view(MyModelView(User, db_session))
    # Create DB
     #db.create_all()
	#recreate()
    # Start app
        app.session_interface = RedisSessionInterface()
	app.run(debug=True)
Ejemplo n.º 32
0
                    except:
                        print schema
                        print row
                        raise

                setattr(inst, col_name, val)

            session.add(inst)

    session.commit()


if __name__ == "__main__":

    import sys
    import os

    if len(sys.argv) < 3:
        print "Usage: %s zip db" % (sys.argv[0])
        sys.exit(0)

    gtfs_zip = sys.argv[1]
    db_file = sys.argv[2]

    if os.path.isfile(db_file):
        os.remove(db_file)

    model.init(db_file)
    gtfs_db = gtfs.GtfsArchive(gtfs_zip)
    load_from_gtfs(gtfs_db)
Ejemplo n.º 33
0
from logging import Formatter, FileHandler
from forms import *
from flask_migrate import Migrate
from datetime import datetime
from model import Artist, Venue, Show, Genres, db, init

# ----------------------------------------------------------------------------#
# App Config.
# ----------------------------------------------------------------------------#

app = Flask(__name__)
moment = Moment(app)
app.config.from_object('config')
with app.app_context():
    db.init_app(app)
    init()
migrate = Migrate(app, db)

# ----------------------------------------------------------------------------#
# Filters.
# ----------------------------------------------------------------------------#


def format_datetime(value, format='medium'):
    date = dateutil.parser.parse(value)
    if format == 'full':
        format = "EEEE MMMM, d, y 'at' h:mma"
    elif format == 'medium':
        format = "EE MM, dd, y h:mma"
    return babel.dates.format_datetime(date, format)
Ejemplo n.º 34
0
 def setUp(self):
     model.connect_string = 'sqlite:///:memory:' 
     model.echo = True
     model.init()
Ejemplo n.º 35
0
#!/usr/bin/python

import model


model.init("/home/nori/Desktop/work/Trellonium/appkey.txt", "/home/nori/Desktop/work/Trellonium/secret.txt")


b = model.BoardProxy("52a113d948daf8a31e0043dd")
print b.members()
xs = b.lists()
print xs
print xs[0]["id"]


app = model.theApp
print app.token_url("bgnoritest")

app.token = file("/home/nori/Desktop/work/Trellonium/token.txt").read().split()

#c = model.CardProxy.create_card(idList=xs[0]["id"], name="by bot", due="null")

Ejemplo n.º 36
0
from flask import Flask, request, render_template, session, flash, redirect
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

from model import User, init,  recreate
app = Flask(__name__)
app.config.update(dict(
    DATABASE='/tmp/flaskr.db',
    DEBUG=True,
    SECRET_KEY='development key',
    USERNAME='******',
    PASSWORD='******'
))
session_db = init('sqlite:///prova.db')
admin = Admin(app)
recreate()
# Add administrative views here
admin.add_view(ModelView(User, session_db))

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] == 'USERNAME':
            error = 'Invalid username'
        elif request.form['password'] == 'PASSWORD':
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect('/admin')
Ejemplo n.º 37
0
def main(gui):
    print('Pyndorama 0.1.0')
    builder = Builder(gui, model.init())
    app = Main(builder, Gui(gui))
    app.build_all(builder)
Ejemplo n.º 38
0
#!/usr/bin/python2.7
import importance_sampler as ims
import model as m
import bntools
import bayesnet
import operator
import itertools

T = 5
json = m.get_json('bayesnets/alc_inheritance.json')
#json = m.get_json('bayesnets/bvg_example.json')
#json = m.get_json('bayesnets/medicalNetwork.json')
#json = m.get_json('bayesnets/toy.json')

model = m.init(json)
evidence = {'v_':False, 'rv':True, 'pv_':True }

X = [n for n in model if not n in evidence]
bntools.plot_net(model)

methods = ['VE', 'LW', 'GS', 'AIS']
runs = 5
R = bntools.foo(model, X, evidence, T, json, methods, runs)
bntools.plot_results(R)


Ejemplo n.º 39
0
  )

  args = parser.parse_args()
  hparams = args.__dict__
  
  # unused args provided by service
  hparams.pop('job_dir', None)
  hparams.pop('job-dir', None)

  output_dir = hparams.pop('output_dir')

  # Append trial_id to path if we are doing hptuning
  # This code can be removed if you are not using hyperparameter tuning
  output_dir = os.path.join(
      output_dir,
      json.loads(
          os.environ.get('TF_CONFIG', '{}')
      ).get('task', {}).get('trial', '')
  )

  # calculate train_steps if not provided
  if hparams['train_steps'] < 1:
     # 1,000 steps at batch_size of 100
     hparams['train_steps'] = (1000 * 100) // hparams['train_batch_size']
     print ("Training for {} steps".format(hparams['train_steps']))

  model.init(hparams)

  # Run the training job
  model.train_and_evaluate(output_dir, hparams)
Ejemplo n.º 40
0
def main():
    opts, args = parse_args()

    print 'Using database: %s' % (opts.dburi)

    session = model.init(opts.dburi, echo=opts.debug)

    for datafile in args:
        data = etree.parse(open(datafile))

        node_report = data.getroot()
        report = session.query(model.Report).get(
                node_report.get('report_timestamp'))

        if report:
            continue

        report = model.Report(report_timestamp =
                node_report.get('report_timestamp'))

        node_envoy = node_report.find('envoy')

        envoy = session.query(model.Envoy).get(node_envoy.get('serial_num'))
        if not envoy:
            envoy = model.Envoy(ip_addr = node_envoy.get('ip_addr'),
                    mac_addr = node_envoy.get('mac_addr'),
                    timezone = node_envoy.get('timezone'),
                    serial_num = node_envoy.get('serial_num'))

            session.add(envoy)

	envoy.sw_version = node_envoy.get('sw_version')

        for node_device in node_report.findall('device'):
            device = session.query(model.Device).get(node_device.get('eqid'))
            if not device:
                device = model.Device(eqid = node_device.get('eqid'),
                        part_num=node_device.get('part_num'),
                        device_type=node_device.get('device_type'),
                        envoy=envoy)
                session.add(device)

            device.image_bits = node_device.get('image_bits')
            device.admin_state = node_device.get('admin_state')
            device.condition_flags = node_device.get('condition_flags')
            device.observed_flags = node_device.get('observed_flags')
            device.control_bits = node_device.get('control_bits')

        for node_interval in node_report.findall('interval'):
            interval = session.query(model.Interval).get(
                    node_interval.get('id'))
            if interval:
                continue

            interval = model.Interval(
                    report=report,
                    id=node_interval.get('id'),
                    stat_duration=node_interval.get('stat_duration'),
                    interval_duration=node_interval.get('interval_duration'),
                    eqid=node_interval.get('eqid'),
                    end_date=node_interval.get('end_date'))

            stats = model.IntervalStats(
                    interval=interval)

            for i,v in enumerate(node_interval.get('stats').split(',')):
                setattr(stats, 'val%d' % i, v)

            session.add(stats)
            session.add(interval)

        for node_event in node_report.findall('event'):
            event = session.query(model.Event).get(
                    node_event.get('id'))
            if event:
                continue

            event = model.Event(
                    id = node_event.get('id'),
                    correlation_id = node_event.get('correlation_id'),
                    event_state = node_event.get('event_state'),
                    event_code = node_event.get('event_code'),
                    eqid = node_event.get('eqid'),
                    serial_num = node_event.get('serial_num'),
                    event_date = node_event.get('event_date'),
                    )

            device = session.query(model.Device).get(event.serial_num)
            if device:
                device.events.append(event)
            report.events.append(event)

            session.add(event)

        envoy.reports.append(report)
        session.add(report)
        session.commit()
Ejemplo n.º 41
0
    )
    parser.add_argument(
        '--job-dir',
        help='this model ignores this field, but it is required by gcloud',
        default='junk'
    )

    args = parser.parse_args()
    arguments = args.__dict__

    # unused args provided by service
    arguments.pop('job_dir', None)
    arguments.pop('job-dir', None)

    output_dir = arguments.pop('output_dir')
    model.init(arguments.pop('bucket'),
               arguments.pop('train_steps')
               )

    # Append trial_id to path if we are doing hptuning
    # This code can be removed if you are not using hyperparameter tuning
    output_dir = os.path.join(
        output_dir,
        json.loads(
            os.environ.get('TF_CONFIG', '{}')
        ).get('task', {}).get('trail', '')
    )

    # Run the training job
    learn_runner.run(model.experiment_fn, output_dir)
Ejemplo n.º 42
0
def init_db(settings):
    # TODO: Add logging
    # Create DB structure if needed
    print settings['sqlalchemy.url']
#    print settings[sqlalchemy.url]
    model.init(settings['sqlalchemy.url'])
Ejemplo n.º 43
0
import logging
from sys import argv

bokehlog = logging.getLogger("songexplorer")
bokehlog.setLevel(logging.INFO)
#bokehlog.info(...)

_, configuration_file = argv

import model as M
import view as V
import controller as C

doc = curdoc()

M.init(doc, configuration_file)
V.init(doc)
C.init(doc)

cluster_buttons = row(V.which_layer,
                      V.which_species,
                      V.which_word,
                      V.which_nohyphen,
                      V.which_kind,
                      column(V.color_picker, width=75, align='end'),
                      width=M.gui_width_pix - 75)
navigate_buttons = row(
    column(Spacer(height=41, width=40), column(V.panleft, width=50),
           Spacer(height=41, width=40), column(V.allleft, width=50)),
    column(V.zoomin, V.reset, V.zoomout, V.allout, width=50),
    column(Spacer(height=41, width=40), column(V.panright, width=50),
Ejemplo n.º 44
0
def ping_stop( stop_ids ):

    schedules = get_schedules()

    time = datetime.datetime.time( datetime.datetime.now() )
    time = time.second + time.minute * 60 + time.hour * 3600

    time_begin = time
    time_end = time + 3600

    session = model.Session()

    busses = session.query( model.StopTimes.stop_id, model.Trips.route_id, model.Trips.trip_headsign, model.StopTimes.departure_time ) \
            .filter( model.Trips.service_id.in_( schedules ) ) \
            .filter( model.StopTimes.stop_id.in_( stop_ids ) ) \
            .filter( model.Trips.trip_id == model.StopTimes.trip_id ) \
            .filter( model.StopTimes.departure_time > time_begin ) \
            .filter( model.StopTimes.departure_time <= time_end ) \
            .order_by( model.StopTimes.departure_time )

    return map( lambda x: ( x.stop_id, x.route_id, x.trip_headsign, x.departure_time ), list( busses ) )

if( __name__ == '__main__' ):

    model.init( 'grt.db' )

    for stop, route, name, time in ping_stop( [ '1966', '2678', '2779', '3589', '3631' ] ):
        print '%s: %02d:%02d - Route %s' % (
                stop, time / 3600, (time / 60) % 60, name )
Ejemplo n.º 45
0
def main():
    init()
    fit()
    predict(isOffline=ISOFFLINE)
Ejemplo n.º 46
0
if __name__ == "__main__":
    host = os.getenv("APP_HOST", "localhost")
    port = int(os.getenv("APP_PORT", "8080"))

    app = web.Application()
    app.router.add_route('POST',  '/login',          post_login)
    app.router.add_route('POST',  '/carts',          post_carts)
    app.router.add_route('PATCH', '/carts/{cartid}', patch_carts)
    app.router.add_route('GET',   '/foods',          get_foods)
    app.router.add_route('GET',   '/orders',         get_orders)
    app.router.add_route('POST',  '/orders',         post_orders)
    app.router.add_route('GET',   '/admin/orders',   get_admin_orders)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(model.init())
    handler = app.make_handler()
    f = loop.create_server(handler, host, port)
    srv = loop.run_until_complete(f)
    print('serving on', srv.sockets[0].getsockname())
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        loop.run_until_complete(handler.finish_connections(1.0))
        srv.close()
        loop.run_until_complete(model.close())
        loop.run_until_complete(srv.wait_closed())
        loop.run_until_complete(app.finish())
    loop.close()
Ejemplo n.º 47
0
    args = parser.parse_args()
    hparams = args.__dict__

    # unused args provided by service
    hparams.pop('job_dir', None)
    hparams.pop('job-dir', None)

    output_dir = hparams.pop('output_dir')

    # Append trial_id to path if we are doing hptuning
    # This code can be removed if you are not using hyperparameter tuning
    output_dir = os.path.join(
        output_dir,
        json.loads(os.environ.get('TF_CONFIG', '{}')).get('task',
                                                          {}).get('trial', ''))

    # calculate train_steps if not provided
    if hparams['train_steps'] < 1:
        # 1,000 steps at batch_size of 100
        hparams['train_steps'] = (1000 * 100) // hparams['train_batch_size']
        print("Training for {} steps".format(hparams['train_steps']))

    model.init(hparams)

    # Run the training job
    try:
        learn_runner.run(generate_experiment_fn(output_dir, hparams),
                         output_dir)
    except:
        traceback.print_exc()
Ejemplo n.º 48
0
def main():
    args = get_parser().parse_args()
    model.init(args.output)
    create_statuses()
    record_results(not args.clean, *args.files)
Ejemplo n.º 49
0
 def test_update_city_name(self):
 	new_city_name='Chicago'
 	model.init(new_city_name)
 	self.assertEqual(model.city_name,new_city_name)
Ejemplo n.º 50
0
def admin():
    model.init()
    ## add a guestbook entry
    return render_template("admin.html", entries=model.get_entries())
    # add a guestbook entry
    return render_template("addentry.html")


@app.route("/delete", methods=["POST"])
def delete_entry():
    delete_id = request.form["theid"]
    model.delete_entry(delete_id)
    return redirect("/")


@app.route("/edit", methods=["POST"])
def edit_entry():
    edit_id = request.form["theid"]
    new_text = request.form["message"]
    model.edit_entry(edit_id, new_text)
    return redirect("/")


@app.route("/postentry", methods=["POST"])
def postentry():
    name = request.form["name"]
    message = request.form["message"]
    model.add_entry(name, message)
    return redirect("/")


if __name__ == "__main__":
    model.init(app)
    app.run(debug=True)
Ejemplo n.º 52
0
from lib import wait_for_job, check_file_exists

repo_path = os.path.dirname(sys.path[0])

sys.path.append(os.path.join(repo_path, "src/gui"))
import model as M
import view as V
import controller as C

os.makedirs(os.path.join(repo_path, "test/scratch/freeze-classify"))
shutil.copy(os.path.join(repo_path, "configuration.pysh"),
            os.path.join(repo_path, "test/scratch/freeze-classify"))

M.init(
    None,
    os.path.join(repo_path, "test/scratch/freeze-classify/configuration.pysh"))
V.init(None)
C.init(None)

os.makedirs(
    os.path.join(repo_path,
                 "test/scratch/freeze-classify/groundtruth-data/round1"))
shutil.copy(
    os.path.join(repo_path, "data/PS_20130625111709_ch3.wav"),
    os.path.join(repo_path,
                 "test/scratch/freeze-classify/groundtruth-data/round1"))

run(["hetero", "start", "1", "1", "1"])

shutil.copy(
  parser.add_argument(
      '--job-dir',
      help='this model ignores this field, but it is required by gcloud',
      default='junk'
  )

  args = parser.parse_args()
  arguments = args.__dict__
  
  # unused args provided by service
  arguments.pop('job_dir', None)
  arguments.pop('job-dir', None)

  output_dir = arguments.pop('output_dir')
  model.init(arguments.pop('bucket'),
             arguments.pop('num_epochs')
            )

  # Append trial_id to path if we are doing hptuning
  # This code can be removed if you are not using hyperparameter tuning
  output_dir = os.path.join(
      output_dir,
      json.loads(
          os.environ.get('TF_CONFIG', '{}')
      ).get('task', {}).get('trail', '')
  )

  # Run the training job
  learn_runner.run(model.experiment_fn, output_dir)

Ejemplo n.º 54
0
    final_argument_whitespace = True
    has_content = False

    def run(self):
        content = (
            '<input type="checkbox" '
            'onChange="this.setAttribute('
            '\'checked\', this.checked?\'checked\':\'\');"/>')
        return [docutils.nodes.raw('', content, format='html')]

directives.register_directive('checkbox', Checkbox)
directives.register_directive('editable', Editable)
directives.register_directive('script', Script)
directives.register_directive('jquery', JQuery)
directives.register_directive('button', Button)

app.secret_key = 'MNOPQR'

if __name__ == '__main__':  # pragma: no cover
    arg_parser = argparse.ArgumentParser()  # pylint: disable=C0103
    arg_parser.add_argument(
        '-c', '--config',
        default='config_default.py',
        help='Choose your config file')
    parser_args = arg_parser.parse_args()  # pylint: disable=C0103
    CONFIG_FILE = getattr(parser_args, 'config')
    if CONFIG_FILE:
        app.config.from_pyfile(CONFIG_FILE)
    db_model.init(app)
    app.run(debug=True, threaded=True)
Ejemplo n.º 55
0
@app.route("/add")
def addentry():
    ## add a guestbook entry
    return render_template("addentry.html")


@app.route("/postentry", methods=["POST"])
def postentry():
    name = request.form["name"]
    message = request.form["message"]
    model.add_entry(name, message)
    return redirect("/admin")


@app.route("/admin")
def admin():
    return render_template("admin.html", entries=model.get_entries())


@app.route("/delete", methods=["POST"])
def postdelete():
    post_id = request.form['delete']
    model.delete_entry(post_id)
    return redirect('/admin')


if __name__ == "__main__":
    model.init()
    app.run(debug=True)
  parser.add_argument(
      '--job-dir',
      help='this model ignores this field, but it is required by gcloud',
      default='junk'
  )

  args = parser.parse_args()
  arguments = args.__dict__
  
  # unused args provided by service
  arguments.pop('job_dir', None)
  arguments.pop('job-dir', None)

  output_dir = arguments.pop('output_dir')
  model.init(arguments.pop('bucket'),
             arguments.pop('train_steps')
            )

  # Append trial_id to path if we are doing hptuning
  # This code can be removed if you are not using hyperparameter tuning
  output_dir = os.path.join(
      output_dir,
      json.loads(
          os.environ.get('TF_CONFIG', '{}')
      ).get('task', {}).get('trail', '')
  )

  # Run the training job
  learn_runner.run(model.experiment_fn, output_dir)