Esempio n. 1
0
async def save_session(ctx):
    global sess
    if not sess:
        await ctx.send('There is no current session.')
    else:
        utils.save_session(sess, f'Sessions/{sess.name}.json')
        await ctx.send('Successfully saved session.')
Esempio n. 2
0
async def new_session(ctx, *, arg):
    global sess
    if sess:
        utils.save_session(sess, f'Sessions/{sess.name}.json')
    session_name = arg
    sess = classes.Session(session_name)
    await ctx.send(f'Made session: {session_name}.')
Esempio n. 3
0
async def load_session(ctx, *, arg):
    global sess
    if sess:
        utils.save_session(sess, f'Sessions/{sess.name}.json')
    session_name = arg
    sess = utils.load_session(f'Sessions/{session_name}.json')
    await ctx.send(f'Loaded session: {session_name}.')
Esempio n. 4
0
def confirm(ctx, code):
    """Confirms email by code"""
    response = get_client().user.confirm(code=code)
    msg = 'Email successfully confirmed! You are logged in as %s' % (
        response['email'], )
    save_session(email=response['email'], session_id=response['sessionId'])
    click.echo(msg)
Esempio n. 5
0
    def play(self, f=None, dev=0):
        cap = cv.VideoCapture(dev)
        pausa = False
        img_index = 0
        roi_index = 0

        #creating the time name value of the session
        time_session = strftime('%d_%m', gmtime())
        path = 'images/' + time_session + '/'

        if not os.path.exists(path + 'save.pkl'):
            img_index = 0
            roi_index = 0
        else:
            img_list,img_index = utils.load_session(path)

        while True:
            key = cv.waitKey(1) & 0xFF
            ret, self.frame = cap.read()
            #set the function mark_corner to left click
            cv.setMouseCallback('frame', self.mark_corner)

            if key == 27:
                cap.release()
                break

            if key == 32:
                pausa = not pausa

            #creates a capture
            if key == ord('c'):
                if not os.path.exists(path):
                    os.makedirs(path)
                cv.imwrite(path + '/img' + str(img_index) + '.png', self.frame)
                print('#Capture: img' + str(img_index))
                img_index+=1

            if key == ord('t') and self.roi_capt:
                cv.imwrite(path + '/roi' + '.png', self.roi)

            #saves the current session
            if key == ord('s'):
                utils.save_session(path)

            if pausa:
                continue


            if self.roi_capt:
                self.roi = self.roi_capture(self.frame,
                                      (self.ix, self.iy), (self.jx, self.jy), f, (255, 255, 255))
            cv.imshow('frame',self.frame)

        cv.destroyAllWindows()
Esempio n. 6
0
def login(request):
    data = {'ret_code': 0, 'ret_data': {}}
    try:
        if request.method == 'POST':
            req_data = json.loads(request.body)
        else:
            req_data = request.GET

        jscode = req_data['jscode']
        sess = utils.http_get(config.JSCODE_SESSION_URL + jscode)
        if 'openid' in sess:
            sess_key = utils.save_session(sess)
            if sess_key:
                data['ret_code'] = 1
                data['sess_key'] = sess_key
            else:
                data['msg'] = 'save session error.'
            mark.info('%s\t%s\t%s\tlogin' %
                      (sess['openid'], utils.getuip(request),
                       time.strftime("%Y-%m-%d %H:%M:%S")))
        else:
            data['msg'] = 'fetch session error'
            logger.error(str(sess))

    except Exception as err:
        data['msg'] = 'program or internet error.'
        logger.error(str(err))

    res = json.dumps(data, ensure_ascii=False)
    return HttpResponse(res, content_type="application/json")
Esempio n. 7
0
def fit(model, training_data, validation_data, optim, start_epoch, args):
    loss = torch.nn.BCELoss()
    for epoch in tqdm(range(start_epoch, start_epoch + args.n_epochs)):
        # training loop
        # ----------------------------------------------------------------------
        model.train()
        for data, _ in training_data:
            for _, picture in enumerate(data):
                picture = picture.view(picture.size(0), -1)
                if use_cuda:
                    picture = picture.cuda()
                training_loss = loss_calc(model, loss, picture, optim)
                if args.comet:
                    args.experiment.log_metric("Training Loss", training_loss)

        # test loop
        # ----------------------------------------------------------------------
        if ((epoch + 1) % args.test_every == 0):
            model.eval()
            with torch.no_grad():
                for data, _ in validation_data:
                    for _, picture in enumerate(data):
                        picture = picture.view(picture.size(0), -1)
                        if use_cuda:
                            picture = picture.cuda()
                        val_loss = loss_calc(model, loss, picture)
                        if args.comet:
                            args.experiment.log_metric("Validation Loss",
                                                       val_loss,
                                                       step=epoch)
                        image = picture

        if ((epoch + 1) % args.save_every == 0):
            save_session(model, optim, args, epoch)

        last_epoch = epoch
    save_session(model, optim, args, last_epoch)
Esempio n. 8
0
def _handle_login(args: List[str]):
    if args:
        print("Please do not put arguments after `login`")
        return

    if get_session() is not None:
        print("Warning: Existing login will be overriden. Continue? [y/n]")
        while True:
            choice = input().strip()
            if choice.lower() == "y":
                break
            elif choice.lower() == "n" or choice.lower() == "":
                return
            else:
                print("Input not understood, try again")

    s = cfscrape.create_scraper()

    r1 = s.get(get_login_url())

    if r1.status_code != 200:
        print("Cannot connect to dmoj.ca: error code [{}]".format(
            r1.status_code))
        return

    if "csrftoken" not in r1.cookies:
        print("Missing CSRF token")
        return

    username = ""
    while not username:
        username = input("Enter your username: "******"Username cannot be empty. To stop, press Ctrl-D.")

    password = ""
    while not password:
        password = getpass("Enter your password: "******"Password cannot be empty. To stop, press Ctrl-D.")

    r2 = s.post(r1.url,
                data={
                    "username": username,
                    "password": password,
                    "csrfmiddlewaretoken": r1.cookies["csrftoken"]
                },
                headers={"referer": r1.url})

    if r2.status_code != 200:
        print("Cannot connect to dmoj.ca: error code [{}]".format(
            r1.status_code))
        return

    if '<p class="error">Invalid username or password.</p>' in r2.text:
        print("Error: Login Failed")
        return

    if r2.url.startswith("https://dmoj.ca/accounts/2fa"):
        code_2fa = ""
        while not code_2fa:
            code_2fa = input("Enter your 2FA code: ").strip().lower()
            if code_2fa and code_2fa.isdigit():
                pass
            else:
                print(
                    "The 2FA code is normally 6 to 10 digits. To quit, press Ctrl-D"
                )
                code_2fa = ""

        r3 = s.post(r2.url,
                    data={
                        "totp_token": code_2fa,
                        "csrfmiddlewaretoken": r2.cookies["csrftoken"]
                    },
                    headers={"referer": r2.url})
        if r3.status_code != 200:
            print("Error: Status Code {}".format(r3.status_code))
            return
        if '<p class="error">Invalid two-factor authentication token.</p>' in r3.text:
            print("2 Factor Authentication Failed")
            return

    print("Login Successful!")
    s.cookies["dmoj-cli-username"] = username
    save_session(s)
Esempio n. 9
0
#     op_sys='Mac+OS+X+10.0',
#     newcc='',
#     component='Systeem',
#     version='3.0',
#     cc='',
#     priority='P1',
#     bug_severity='normal',
#     target_milestone='---',
#     bug_file_loc='',
#     flag_type-2='X',
#     flag_type-1='X',
#     short_desc='Fedora+user+ID',
#     dependson='',
#     blocked='',
#     comment='',
#     knob='none',
#     resolution='FIXED',
#     dup_id='',
#     assigned_to='a.e.nonhebel%40tudelft.nl',
#     form_name='process_bug,

def bugzilla_login(session):
    request = session.post(settings.BUGZILLA_LOGIN_URL,
                           data=settings.BUGZILLA_LOGIN_DATA)

if __name__ == '__main__':
    try:
        main(convert.session, *sys.argv[1:])
    finally:
        utils.save_session(convert.session)
Esempio n. 10
0
            selected = []
            for card in get_cards(board):
                bug_id = get_bug_id(card)
                partial = 'deel ' in card.name
                if board.id == settings.ACTIVE_BOARD:
                    selected.append(card)
                elif bug_id and bug_id in active_bugs and not partial:
                    print 'Deleting duplicate card %r (in active)' % card
                    print 'Original: %r' % active_bugs[bug_id]
                    card.delete()
                elif bug_id and bug_id in archived_bugs and not partial \
                        and board.id != settings.ARCHIVE_BOARD:
                    print 'Deleting duplicate card %r (in archive)' % card
                    card.delete()
                else:
                    selected.append(card)

        # selected = sorted(selected, key=lambda c: c.name)

        # print 'Got %d cards' % len(selected)

        # if len(selected) == 1:
        #     update_card(*selected)
        # else:
        #     # pool = multiprocessing.Pool(4)
        #     # pool.map(update_card, selected)
        #     map(update_card, selected)

    utils.save_session(session)

Esempio n. 11
0
async def upkeep():
    global sess
    if not sess:
        return
    utils.save_session(sess, f'Sessions/{sess.name}.json')
    print(f'Saved state for the day. {datetime.datetime.today()}')
Esempio n. 12
0
def login(ctx, email, password):
    """Authenticates against the API"""
    save_session(email=email,
                 session_id=get_client().user.login(email=email,
                                                    password=password))
    click.echo('Successfully logged in!')
Esempio n. 13
0
        + Q value distributions for distributional methods
        """
        if done:
            end_time = time.time()
            episode_time = end_time - start_time
            # +1 to account for 0 indexing. +0 on ep_timesteps since it will increment +1 even if done=True
            print(
                f"Total T: {t+1} Episode Num: {episode_num+1} Episode T: {episode_timesteps} Reward: {episode_reward:.2f}"
            )
            if args.comet:
                args.experiment.log_metric("Training Episode Reward",
                                           episode_reward,
                                           step=t)

                # Different step here
                utils.save_session(model.Q, args, episode_num)
                args.experiment.log_metric("Episode Timestep",
                                           episode_timesteps,
                                           step=episode_num)
                args.experiment.log_metric("Training Episode Reward",
                                           episode_reward,
                                           step=episode_num)
                args.experiment.log_metric("Wall Time",
                                           time.time(),
                                           step=episode_num)
                args.experiment.log_metric("Episode Length",
                                           episode_time,
                                           step=episode_num)

                # Debug: Changed to log_parameter
                args.experiment.log_parameter("Action Sequence",