Example #1
0
def test_update_missing():
    model.update({'id': '0', 'msg': 'test-0 updated', 'msg2': 'New message'})
    assert ([{
        'id': '0',
        'msg': 'test-0 updated',
        'msg2': 'New message'
    }], True) == model.getTasks()
Example #2
0
def update(table):
    condition = view.single_input(
        table, 'Enter requirement of row to be changed:')
    query = view.multiple_input(table, 'Enter new fields values:')

    model.update(table, condition, query)
    display_secondary_menu(table, 'Update was made successfully')
Example #3
0
def update(tname):
    condition = reader.single_input(tname,
                                    'Enter requirement of row to be changed:')
    query = reader.multiple_input(tname, 'Enter new fields values:')

    model.update(tname, condition, query)
    show_table_menu(tname, 'Update was made successfully')
Example #4
0
def is_valid_solution(model, x, sol):
    prev_ub = np.copy(x.UB)
    x.UB = binarize(sol)
    model.optimize()
    status = model.status
    x.UB = prev_ub
    model.update()
    return status == GRB.OPTIMAL
Example #5
0
def test_update():
    assert True == model.add({'id': '0', 'msg': 'test-0'})
    model.update({'id': '0', 'msg': 'test-0 updated', 'msg2': 'New message'})
    assert ([{
        'id': '0',
        'msg': 'test-0 updated',
        'msg2': 'New message'
    }], True) == model.getTasks()
Example #6
0
def trainProc(model, data):
    # something about model training
    for line in data:
        text = line['text']
        label = line['label']
        model.predict(text)
    model.update()
    print('training done')
    return model
Example #7
0
def make_dual_model(tiger):
    model = gp.Model()
    n = tiger.S.shape[1]
    m = tiger.S.shape[0]
    yS = model.addMVar(shape=m, lb=-GRB.INFINITY, name="yS")
    yL = model.addMVar(shape=n, lb=-GRB.INFINITY, ub=0.0, name="yL")
    yU = model.addMVar(shape=n, name="yU")
    model.addConstr(tiger.S.T @ yS + np.eye(n) @ yL +
                    np.eye(n) @ yU == tiger.c)
    model.setObjective(tiger.b @ yS + tiger.lb @ yL + tiger.ub @ yU)
    model.update()
    return model, (yS, yL, yU)
Example #8
0
def run(arg):
    action = []
    if ROLL == arg:
        action = [.1, .1, -.1, -.1]

    while (1):
        start = time.time()
        m.update()
        m.act(action)

        step()
        keys = p.getKeyboardEvents()

        stop = time.time()
        delta = stop - start
        if delta < TIME_STEP_S:
            time.sleep(TIME_STEP_S - delta)
Example #9
0
def index():
    if request.method == 'POST':
        url = request.form['url']
        predict = model.predict(url)
        value = predict[1]
        clickbait = predict[2]
        text = predict[3]
        article_title = predict[0]
        model.update(value)
        model.update(clickbait)
        return render_template('results.html',
                               value=value,
                               clickbait=clickbait,
                               text=text,
                               article_title=article_title,
                               url=url)
    else:
        return render_template('index.html')
Example #10
0
def add_fva_bounds(model, v, frac=1.0):
    model.Params.OutputFlag = 0

    if frac is not None:
        base.add_objective_constraint(model, frac)

    orig_obj = model.getObjective()
    orig_sense = model.ModelSense

    for i in range(v.shape[0]):
        model.setObjective(v[i] + 0, GRB.MINIMIZE)
        model.optimize()
        v[i].LB = v[i].X

        model.setObjective(v[i] + 0, GRB.MAXIMIZE)
        model.optimize()
        v[i].UB = v[i].X

    model.setObjective(orig_obj, orig_sense)
    model.update()
Example #11
0
File: app.py Project: brisad/todo
def edit_item():
    if not session.get('logged_in'):
        abort(401)

    try:
        progress = float(request.form['progress'])
        if progress < 0:
            progress = 0
        if progress > 1:
            progress = 1
    except ValueError:
        flash("Invalid value for progress")
        return redirect(url_for('root'))

    try:
        model.update(db_items(),
                     request.form['name'], progress, request.form['description'])
    except model.DataError:
        flash("Failed to update item")
        return redirect(url_for('root'))

    return redirect(url_for('root'))
Example #12
0
    def post_data(self, request, component):
        log.debug("posting data for %s", component)

        session = self.__SessionMaker()

        for metric, value in request.args.iteritems():
            # truncate metric to 128 characters
            metric = metric[:128]

            # See if it is in the database
            row = session.query(Data).filter(Data.component == component).filter(Data.metric == metric).all()

            if len(row) > 0:
                model = row[0]
            else:
                model = Data(component, metric)

            model.update(int(value))
            session.merge(model)

        session.commit()

        return ""
Example #13
0
def run_game():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode((settings.game_width, settings.game_height))
    pygame.display.set_caption("Snakes")

    screen.fill(settings.bg_color)
    model.draw_grid(screen, settings)
    model.new_food(screen, settings)

    while True:
        keypress.keycheck(screen, settings)

        if settings.game_over:
            model.game_over(screen, settings)
            if settings.play_again:
                break
        else:
            model.update(screen, settings)
            model.collisions_check(screen, settings)

        pygame.display.flip()

    return settings.play_again
Example #14
0
def login():
        u,p=view.showLogin()
        user= model.login(u,p)
        #print(user)
        if user is not None :
            print("sucessfull login", user)
            if user.get('admin',0) == 1:
                #print('user is a admin')
                d=view.showAdminScreen()
                
                if d[-1] ==1: 
                    saveusr(d[0])
                elif d[-1]==2:
                    model.update(d[0],d[1],d[2])
                elif d[-1]==3: 
                    data=model.searchData(d[0],int(d[1]))
                    print(data)
                    view.displayAccounts(data)
                elif d[-1]==4:
                    s=model.sort1(d[0],d[1])
                    view.displayAccounts(s)
            else:
                print('User is not admin')
                d= view.showTransaction()
                choice=d['choice']
                if choice == 1:
                    model.updatetxn(d['amount'],d['credit'],user.get('accno',0))
                elif choice == 2:
                    view.displayAccounts(model.searchData(d['accno'],d['amount']))
                    view.displayTransactions(model.getTransactions(d['amount']))
                elif choice == 3:
                    d = model.sort2(d['column_name'],d['order'],d['accno'])
                    #print(amt,credit,choice,d)
                    view.displayTransactions(d)
        else:
            print("login not suceesfull")
Example #15
0
def update_model():
    global state

    logfile.write(str(time.time()) + ": UPDATE POST\n")

    viewUpdate = request.get_json()
    print("got update: " + str(viewUpdate))

    nextState = model.update(viewUpdate["action"], viewUpdate["state"])

    print("update is: " + str(nextState))
    logfile.write(
        str(time.time()) + ": UPDATED STATE IS " + str(nextState) + "\n")

    return flask.jsonify(nextState)
Example #16
0
def update_table(table_num):
    table = tables[table_num]
    table_columns = columns[table]
    while True:
        print("Choose column to update:")
        view.table_columns_names(table_num)
        chosen_column_num = input()
        if re.match(r'^[1-{}]{}$'.format(len(table_columns), "{1}"),
                    chosen_column_num):
            set_column = table_columns[int(chosen_column_num) - 1]
            print("Input value: ")
            print("UPDATE {} SET {} = ...".format(table, set_column))
            set_value = "'" + input() + "'"
            print("Choose column to update by:")
            view.table_columns_names(table_num)
            chosen_column_num = input()
            if re.match(r'^[1-{}]{}$'.format(len(table_columns), "{1}"),
                        chosen_column_num):
                where_column = table_columns[int(chosen_column_num) - 1]
                print("Input value: ")
                print("UPDATE {} SET {} = {} WHERE {} = ...".format(
                    table, set_column, set_value, where_column))
                where_value = "'" + input() + "'"
                print("UPDATE {} SET {} = {} WHERE {} = {}".format(
                    table, set_column, set_value, where_column, where_value))
                set = " SET {} = {}".format(set_column, set_value)
                where = " WHERE {} = {}".format(where_column, where_value)
                res = model.update(table, set, where)
                return res
            elif chosen_column_num == '0':
                return
            else:
                print("No such option. Check your input")
        elif chosen_column_num == '0':
            return
        else:
            print("No such option. Check your input")
Example #17
0
    def update(self, batch_size):
        def get_Q_for_actions(params, observations):
            """Calculate Q values for action that was taken"""
            pred_Q_values = m.batch_func(m.predict)(params, observations)
            pred_Q_values = index_Q_at_action(pred_Q_values, actions)
            return pred_Q_values

        (
            obs,
            actions,
            r,
            next_obs,
            dones,
        ) = self.buffer.sample_batch(batch_size)

        max_next_Q_values = self.get_max_Q_values(next_obs)
        target_Q_values = self.get_target_Q_values(r, dones, max_next_Q_values)

        #  Caclulate loss and perform gradient descent
        loss, self.params = m.update(get_Q_for_actions, self.params, obs,
                                     target_Q_values, self.lr)

        self.steps_trained += 1
        return loss
Example #18
0
 def start_loop(self):
     """Continuously updates the tiles on the canvas using Conway's rules"""
     self.current_grid = model.update(self.current_grid)
     self.update_tiles()
     self.loop = self.master.after(UPDATE_INTERVAL, self.start_loop)
Example #19
0
 def put(self, name):
     args = parser.parse_args()
     model.update(name, args['phone'])
     return args['phone'], 201
Example #20
0
def set_range_value(id, prop, value, allowed_values):
    if lib.value_in_range(value, allowed_values):
        return response.send_if_found(model.update(id, {prop: value}))
    else:
        return response.generic_failure("Cannot update: invalid value.", 400)
Example #21
0
 def PUT(self, id):
     new_name = web.data()
     return response.send_if_found(model.update(id, {"name": new_name}))
Example #22
0
# print(real_img_arr[0])
# print(real_img_arr[0].shape)

real_img_tensor = torch.from_numpy(real_img).float()

loader = Data.DataLoader(dataset=real_img_tensor,
                         batch_size=BATCH_SIZE,
                         shuffle=True,
                         num_workers=2)

G = Generator().to(device)
D = Discriminator().to(device)

optimizer_g = optim.Adam(G.parameters(), lr=LR, betas=(0.5, 0.99))
optimizer_d = optim.Adam(D.parameters(), lr=LR, betas=(0.5, 0.99))
# optimizer_g = optim.RMSprop(G.parameters(), lr=LR)
# optimizer_d = optim.RMSprop(D.parameters(), lr=LR)

for i in range(EPOCH):
    #train
    print("start training epoch" + str(i))

    update(loader, G, D, optimizer_d, optimizer_g)
    #for j in range(D_UPD_NUM):
    #    update_d(loader, G, D, optimizer_d)
    #for j in range(G_UPD_NUM):
    #    update_g(BATCH_SIZE, ITER_NUM, G, D, optimizer_g)
    if (i % 5 == 4):
        torch.save(G.state_dict(), model_folder_path + 'G' + str(i) + '.pkl')
        torch.save(D.state_dict(), model_folder_path + 'D' + str(i) + '.pkl')
def main(args):
    r"""
  >>> import model
  >>> import control
  >>> from bs4 import BeautifulSoup as BS
  >>> docs = [{"id":"1","name":"Mike","email":"[email protected]"}]
  >>> model.find = lambda x=None: {"docs":docs}
  >>> res = control.main({})
  >>> html = BS(res["body"], "lxml")
  >>> print(html.find("tbody"))
  <tbody>
  <tr>
  <td scope="row">
  <input name="id" type="radio" value="1"/>
  </td>
  <td>Mike</td>
  <td>[email protected]</td>
  </tr>
  </tbody>
  >>> res = control.main({"op":"new"})
  >>> inp = BS(res["body"], "lxml").find_all("input")
  >>> print(*inp, sep="\n")
  <input name="op" type="hidden" value="save"/>
  <input class="form-control" id="name" name="name" type="text" value=""/>
  <input class="form-control" id="email" name="email" type="email" value=""/>
  >>> res = control.main({"op":"edit", "id":"1"})
  >>> inp = BS(res["body"], "lxml").find_all("input")
  >>> print(*inp, sep="\n")
  <input name="id" type="hidden" value="1"/>
  <input name="op" type="hidden" value="save"/>
  <input class="form-control" id="name" name="name" type="text" value="Mike"/>
  <input class="form-control" id="email" name="email" type="email" value="[email protected]"/>
  >>> model.insert = control.inspect
  >>> args = {"op":"save", "name":"Miri","email":"[email protected]"}
  >>> x = control.main(args)
  >>> print(control.spy)
  {'name': 'Miri', 'email': '[email protected]'}
  >>> model.update = control.inspect
  >>> args = {"op":"save", "id": "1", "name":"Mike","email":"[email protected]"}
  >>> x = control.main(args)
  >>> print(control.spy)
  {'id': '1', 'name': 'Mike', 'email': '[email protected]'}
    """
    op = args.get("op")
    if op == "new":
        body = view.form(fill({}))
        return {"body": view.wrap(body)}
    if op == "edit" and "id" in args:
        res = model.find(args["id"])
        rec = res["docs"][0]
        body = view.form(rec)
        return {"body": view.wrap(body)}
    if op == "save":
        if "id" in args:
            model.update(fill(args))
        else:
            model.insert(fill(args))
    if op == "delete" and "id" in args:
        model.delete(args["id"])
    data = model.find()["docs"]
    body = view.table(data)
    return {"body": view.wrap(body)}
Example #24
0
            lo, hi = start_idx[minibatch_idx], end_idx[minibatch_idx]

            m_vars['Y_batch'] = m_vars['Y_train'][lo:hi]
            m_vars['X_batch'] = m_vars['X_train'][lo:hi]
            m_vars['Y_batch_T'] = m_vars['Y_batch'].T
            m_vars['X_batch_T'] = m_vars['X_batch'].T
            m_vars['gamma'] = lr[iter_idx]

            print "Iter:", iter_idx,
            # Gamma : learning rate at current time step
            print "\tGamma: %6g" % m_vars['gamma'],
            print "\tUpdate Time: %.3f seconds" % update_time

            # Updates
            start_iter_t = time.time()
            m_vars = update(m_opts, m_vars)
            update_time = time.time() - start_iter_t

            if display_flag:  # Train precision
                Y_train_pred, _ = predict(m_opts, m_vars, m_vars['X_batch'])
                p_scores = precisionAtK(Y_train_pred, m_vars['Y_batch'],
                                        m_opts['performance_k'])
                if m_opts['verbose']:
                    print "Train score:",
                    for i in p_scores:
                        print " %0.4f" % i,
                    print ""

            if test_flag:  # Test precision
                start_test_t = time.time()
                if m_opts['test_chunks'] == 1:
def main(args):
    r"""
  >>> import model, control, rest
  >>> rest.load_props()
  >>> from bs4 import BeautifulSoup as BS
  >>> docs = [{"id":"1","name":"Mike","email":"[email protected]"}]
  >>> model.find = lambda bookmark=None: {"docs":docs}
  >>> res = control.main({"__ow_method":"get"})
  >>> html = BS(res["body"], "lxml")
  >>> print(html.find("tbody"))
  <tbody>
  <tr>
  <td scope="row">
  <input name="id" type="radio" value="1"/>
  </td>
  <td>Mike</td>
  <td>[email protected]</td>
  <td></td>
  </tr>
  </tbody>
  >>> res = control.main({"__ow_method":"get", "op":"new"})
  >>> inp = BS(res["body"], "lxml").find_all("input")
  >>> print(*inp, sep="\n")
  <input class="form-control" id="photo" name="photo" type="file"/>
  <input class="form-control" id="name" name="name" type="text" value=""/>
  <input class="form-control" id="email" name="email" type="email" value=""/>
  >>> res = control.main({"__ow_method":"get", "op":"edit", "id":"1"})
  >>> inp = BS(res["body"], "lxml").find_all("input")
  >>> print(*inp, sep="\n")
  <input name="id" type="hidden" value="1"/>
  <input class="form-control" id="photo" name="photo" type="file"/>
  <input class="form-control" id="name" name="name" type="text" value="Mike"/>
  <input class="form-control" id="email" name="email" type="email" value="[email protected]"/>
  >>> model.insert = control.inspect
  >>> ctype = "multipart/form-data; boundary=------------------------ff26122a2a4ed25b"
  >>> body = "LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS1mZjI2MTIyYTJhNGVkMjViDQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9Im5hbWUiDQoNCmhlbGxvDQotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLWZmMjYxMjJhMmE0ZWQyNWINCkNvbnRlbnQtRGlzcG9zaXRpb246IGZvcm0tZGF0YTsgbmFtZT0iZW1haWwiDQoNCmhAbC5vDQotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLWZmMjYxMjJhMmE0ZWQyNWItLQ0K"
  >>> args = {"__ow_method":"post", "__ow_body":body, "__ow_headers": {"content-type": ctype} }
  >>> _ = control.main(args)
  >>> print(control.spy)
  {'name': 'hello', 'email': '[email protected]'}
  >>> model.update = control.inspect
  >>> ctype = "multipart/form-data; boundary=------------------------7a256bc140953925"
  >>> body = "LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS03YTI1NmJjMTQwOTUzOTI1DQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9Im5hbWUiDQoNCm1pa2UNCi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tN2EyNTZiYzE0MDk1MzkyNQ0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJlbWFpbCINCg0KbUBzLmMNCi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tN2EyNTZiYzE0MDk1MzkyNQ0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJpZCINCg0KMTIzDQotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTdhMjU2YmMxNDA5NTM5MjUtLQ0K"
  >>> args = {"__ow_method":"post", "__ow_body":body, "__ow_headers": {"content-type": ctype} }
  >>> x = control.main(args)
  >>> print(control.spy)
  {'id': '123', 'name': 'mike', 'email': '[email protected]'}
    """
    # extract photo
    if "__ow_path" in args:
        path = args["__ow_path"]
        if len(path) > 1:
            doc = model.find(path[1:])["docs"][0]
            return {
                "body": doc["photo"],
                "headers": {
                    "Content-Type": doc["photo_mime"]
                }
            }
    # post data
    if "__ow_body" in args:
        fields, files = form_parse(args)
        filled = fill(fields, files)
        if "id" in fields:
            model.update(filled)
        else:
            model.insert(filled)

    # handle other ops
    op = ""
    if args["__ow_method"] == "get":
        op = args.get("op")
    if op == "new":
        body = view.form(fill({}, {}))
        return {"body": view.wrap(body)}
    if op == "edit" and "id" in args:
        res = model.find(args["id"])
        rec = res["docs"][0]
        body = view.form(rec)
        return {"body": view.wrap(body)}
    if op == "delete" and "id" in args:
        model.delete(args["id"])

    # paginated rendering
    curr = args.get("bookmark")
    query = model.find(bookmark=curr)
    data = query["docs"]
    next = ""
    if len(data) == model.find_limit:
        next = query.get("bookmark")
    body = view.table(data, next, model.last_error)
    if model.last_error:
        model.last_error = None
    return {"body": view.wrap(body)}
Example #26
0
 def PUT(self, id):
     new_name = web.data()
     return response.send_if_found(model.update(id, {'name': new_name}))
Example #27
0
def set_range_value(id, prop, value, allowed_values):
    if lib.value_in_range(value, allowed_values):
        return response.send_if_found(model.update(id, {prop: value}))
    else:
        return response.generic_failure('Cannot update: invalid value.', 400)
Example #28
0
        if option == "r":
            rows = db.read()
            print(
                "--------------------------------------------------------------------------------------------"
            )
            for row in range(len(rows)):
                print("Serviço: {}  | Usuário: {}  | Senha: {}  | ID: {}  ".
                      format(rows[row][1], rows[row][2], rows[row][3],
                             rows[row][0]))
                print(
                    "--------------------------------------------------------------------------------------------"
                )

        #Update ------------------------------------------------------------
        if option == "u":
            db.update()

        #Delete ------------------------------------------------------------
        if option == "d":
            db.delete()

        #Exit ------------------------------------------------------------
        if option == "e":
            for i in range(1, 4):
                os.system("clear")
                print("Exiting sistem... ", i)
                time.sleep(1)
            os.system("clear")
            break

        input("PRESS ENTER TO CONTINUE...")
Example #29
0
import model
import plot

# ------------------ #
#  Initialise model  #
# ------------------ #
box1, box2, glob = model.initialise()


# --------------------------- #
#  Integrate forward in time  #
# --------------------------- #
for n in range(nt):
    
    # Update fluxes, moisture, circulation using current temperatures
    model.update(n, box1, box2, glob)

    # Step temperatures forward
    model.step(n, box1, box2, glob)

    # Print every 'n_print' steps
    if n % n_print == 0:
        years, months, days = model.simulation_time(n)
        print "Simulation time: %dy, %dm, %dd" %(years, months, days)

    # Save every n_save steps (exluding step 0)
    if (n+1) % n_save == 0:
        years, months, days = model.simulation_time(n)
        "Saving time series at simulation time: %d years, %d months, %d days" %(years, months, days)
        
        model.save(n+1, box1, box2, glob)
Example #30
0
 def put(self, user_id, item_id, evaluation):
     new_scores = model.update(user_id, item_id, evaluation)
     return {'renewed': new_scores}
Example #31
0
while True:
    menu_item = view.main_menu()
    print(menu_item)
    if menu_item == '1':
        attrs = view.insert_menu()
        try:
            getattr(model, f'insert_{attrs[0]}')(attrs[1].split(','))
        except:
            print("Oops, table doesn't exists")

    elif menu_item == '2':
        attrs = view.delete_menu()
        model.delete(*attrs)
    elif menu_item == '3':
        attrs = view.update_menu()
        model.update(*attrs)
    elif menu_item == '4':
        attrs = view.random_menu()
        try:
            view.show_random_query(
                getattr(model, f'random_{attrs[0]}')(int(attrs[1])))
        except:
            print("Oops, table doesn't exists")
    elif menu_item == '5':
        attrs = view.select_menu()
        f_name = [
            'student_grade', 'teacher_subject', 'student_teacher_subject'
        ][int(attrs[0]) - 1]
        time_before = time.time()
        try:
            query, rows = getattr(model, f_name)(*attrs[1].split(','))
Example #32
0
            print(data.provide_data)
            model.forward(Batch([current_obs.reshape(1, 1, 128, 128)]))
            Q_values = model.get_outputs()[0].asnumpy()
            action = np.argmax(Q_values)
        
        next_obs, reward, done, _ = env.step(action)
        next_obs = preprocess(next_obs)

        episode_reward += reward

        if render:
            env.render()

        buffer.add_experience((current_obs, action, reward, next_obs, done))
        # print('buffer size:', len(buffer)) # around 50 per episode

        if buffer.is_full():
            print('buffer full')
        
        current_obs = next_obs
        exploration_rate -= exploration_step
        
    # if the buffer is filled enough, update the model
    if len(buffer) > training_batch_size and update_freq % i == 0:
        # update the model
        batch = buffer.sample(training_batch_size)
        update(model, batch, batch_size, i, discount_factor)
    
    print('Episode #{} reward: {}'.format(i, episode_reward))
    print()
Example #33
0
def update(subject):
    print(request)
    return model.update(subject, request.json)