Example #1
0
def readBuffer():
    #    '''
    with open(infile, "rt") as f:
        buf = f.readlines()
    buf = map(lambda x: x[:-1], buf)
    '''
    buf = """5
2 3 2
1 1 1
2 1 1
2 1 2
3 2 3""".split("\n");
    #'''

    t = int(buf[0])
    buf = buf[1:]
    buf2 = []
    for _ in xrange(1, t + 1):
        K, C, S = parse(buf[0], "iii")
        buf = buf[1:]
        #w = [parse1(buf[i],"i") for i in xrange(n)]; buf=buf[n:];

        buf2.append([K, C, S])
        pass
    return buf2
Example #2
0
def parseInput(buf):
    buf = buf.split("\n")
    buf = filter(len, buf)

    t = int(buf[0])
    buf = buf[1:]
    outBuf = []
    for _ in xrange(1, t + 1):
        n, = parse(buf[0], "i")
        buf = buf[1:]
        w = [parse(buf[i], "i" * n) for i in xrange(2 * n - 1)]
        buf = buf[len(w):]

        outBuf.append([n, w])
        pass
    return outBuf
Example #3
0
def main():
    args = parse()
    env = gym.make(args.env)
    model = MPO(args.device,
                env,
                dual_constraint=args.dual_constraint,
                kl_mean_constraint=args.kl_mean_constraint,
                kl_var_constraint=args.kl_var_constraint,
                kl_constraint=args.kl_constraint,
                discount_factor=args.discount_factor,
                alpha=args.alpha,
                sample_process_num=args.sample_process_num,
                sample_episode_num=args.sample_episode_num,
                sample_episode_maxlen=args.sample_episode_maxlen,
                sample_action_num=args.sample_action_num,
                batch_size=args.batch_size,
                episode_rerun_num=args.episode_rerun_num,
                lagrange_iteration_num=args.lagrange_iteration_num)

    if args.load is not None:
        model.load_model(args.load)

    model.train(iteration_num=args.iteration_num,
                log_dir=args.log_dir,
                render=args.render,
                debug=args.debug)

    env.close()
Example #4
0
def run():
    global DIFF, PORT, HOSTNAME
    get_meraki_configs()

    try:
        parsed_args = argparser.parse(sys.argv[1:], VERSION)
    except argparser.UsageError as e:
        sys.stderr.write('Error: %s\n\n' % e)
        usage_and_die()


    DIFF = argparser.diff_for_args(parsed_args)

    if app.config['TESTING'] or app.config['DEBUG']:
        sys.stderr.write('Diff:\n%s' % DIFF)

    PORT = pick_a_port(parsed_args)

    if app.config.get('USE_HOSTNAME'):
        _hostname = platform.node()
        # platform.node will return empty string if it can't find the hostname
        if not _hostname:
            sys.stderr.write('Warning: hostname could not be determined')
        else:
            HOSTNAME = _hostname

    sys.stderr.write(
        '''Serving diffs on http://%s:%s
Close the browser tab or hit Ctrl-C when you're done.
'''
        % (HOSTNAME, PORT)
    )
    #Timer(0.1, open_browser).start()
    app.run(host=HOSTNAME, port=PORT)
Example #5
0
def readBuffer():
    #'''
    with open(infile, "rt") as f:
        buf = f.readlines()
    buf = map(lambda x: x[:-1], buf)
    '''
    buf = """4
200 1 2
250 233
180 100
100 3 3
500 500 500
500 500 600
500 140 1000
10 10 10
10 10 490
10 10 10
100 3 3
500 100 500
100 100 500
500 500 500
10 10 10
10 10 10
10 10 10
100 2 2
1000 1000
1000 1000
100 900
900 100
    """.split("\n");
    #'''

    t = int(buf[0])
    buf = buf[1:]
    buf2 = []
    for _ in xrange(1, t + 1):
        h, n, m = parse(buf[0], "iii")
        buf = buf[1:]
        c = [parse("%d %s" % (m, buf[i]), "iI0")[1] for i in xrange(n)]
        buf = buf[n:]
        f = [parse("%d %s" % (m, buf[i]), "iI0")[1] for i in xrange(n)]
        buf = buf[n:]

        buf2.append([h, n, m, c, f])
        pass
    return buf2
Example #6
0
    def parse_player(self, message: discord.Message):
        args = ('name', 'level')
        kwargs = {"str": 0, "dex": 0, "con": 0, "int": 0, "wis": 0, "cha": 0}

        try:
            parsed = argparser.parse(message, args, kwargs)
            # sort out namespace error, with str and int
            parsed['_str'] = parsed.pop('str')
            parsed['_int'] = parsed.pop('int')

            # pylint: disable=unexpected-keyword-arg
            char = player.Character(**parsed)
            return char
        except Exception as e:  # if encountering an error parsing arg as a player, return false
            print(e)
            return False
Example #7
0
def run():
    global DIFF, PORT
    try:
        parsed_args = argparser.parse(sys.argv[1:])
    except argparser.UsageError as e:
        sys.stderr.write('Error: %s\n\n' % e.message)
        usage_and_die()

    DIFF = argparser.diff_for_args(parsed_args)

    if app.config['TESTING'] or app.config['DEBUG']:
        sys.stderr.write('Diff:\n%s' % DIFF)

    PORT = pick_a_port(parsed_args)

    sys.stderr.write('''Serving diffs on http://localhost:%s
Close the browser tab or hit Ctrl-C when you're done.
''' % PORT)
    Timer(0.1, open_browser).start()
    app.run(host='0.0.0.0', port=PORT)
Example #8
0
def run():
    global DIFF, PORT
    try:
        parsed_args = argparser.parse(sys.argv[1:])
    except argparser.UsageError as e:
        sys.stderr.write('Error: %s\n\n' % e.message)
        usage_and_die()

    DIFF = argparser.diff_for_args(parsed_args)

    if app.config['TESTING'] or app.config['DEBUG']:
        sys.stderr.write('Diff:\n%s' % DIFF)

    PORT = pick_a_port(parsed_args)

    sys.stderr.write('''Serving diffs on http://localhost:%s
Close the browser tab or hit Ctrl-C when you're done.
''' % PORT)
    Timer(0.1, open_browser).start()
    app.run(host='0.0.0.0', port=PORT)
Example #9
0
def readBuffer():
    #'''
    with open(infile,"rt") as f: buf = f.readlines();
    buf=map(lambda x: x[:-1], buf);
    '''
    buf = """4
2 20 10
2 10 0
4 25 25 25 25
3 24 30 21
    """.split("\n");
    #'''

    t = int(buf[0]); buf=buf[1:];
    buf2 = [];
    for _ in xrange(1,t+1):
        n,arr = parse(buf[0],"iI0"); buf=buf[1:];
    
        buf2.append([n, arr]);
        pass;
    return buf2;
Example #10
0
def readBuffer():
    #'''
    with open(infile, "rt") as f:
        buf = f.readlines()
    buf = map(lambda x: x[:-1], buf)
    '''
    buf = """2
20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
20 120 266 858 1243 1657 1771 2328 2490 2665 2894 3117 4210 4454 4943 5690 6170 7048 7125 9512 9600
    """.split("\n");
    #'''

    t = int(buf[0])
    buf = buf[1:]
    buf2 = []
    for _ in xrange(1, t + 1):
        n, arr = parse(buf[0], "iI0")
        buf = buf[1:]

        buf2.append([n, arr])
        pass
    return buf2
Example #11
0
    hist_ckpt = '{}/{}/history/{}.pkl'.format(cfg.ckpt_folder, expt,
                                              model_name)
    logging.info('History: {}'.format(hist_ckpt))
    pkl.dump((loss_history, acc_history), open(hist_ckpt, 'wb'))

    for idx, clf in enumerate(clfs):
        model_ckpt = '{}/{}/models/{}_clf_{}.stop'.format(
            cfg.ckpt_folder, expt, model_name, idx)
        logging.info('Model: {}'.format(model_ckpt))
        torch.save(clf.state_dict(), model_ckpt)


if __name__ == '__main__':
    model = 'check_train'
    args = parse()
    model = '{}_{}{}_optim_{}_ei_{}_epochs_{}'.format(model, args.arch,
                                                      args.num_layers,
                                                      args.optimizer,
                                                      len(args.lr_clfs),
                                                      args.n_epochs)
    pr_time, fl_time = time_stp()
    logger(args.expt, model)

    log_time('Start', pr_time)
    sep()
    logging.info(json.dumps(args.__dict__, indent=2))

    main(
        expt=args.expt,
        model_name=model,
Example #12
0
            # the gevent_subprocess module. Blocks only
            # this greenlet until the process (playlist
            # item) ends.
            command = ["vlc", pl_item, "--play-and-exit", "--quiet"]
            if args.fullscreen:
                command.append("--fullscreen")

            subprocess.call(command)

        except queue.Empty:
            # Resume loop
            continue


if __name__ == '__main__':

    # get value from command line arguments
    args = argparser.parse()

    PORT = int(args.port)

    # Web server thread to be spawned later
    server = WSGIServer(('0.0.0.0', PORT), app)
    server_thread = gevent.spawn(server.serve_forever)

    # Player thread to be spawned later
    player_thread = gevent.spawn(player_worker, args)

    # Start the threads
    gevent.joinall([server_thread, player_thread])
Example #13
0
'''
buf = """3
2 5
0.6 0.6
1 20
1
3 4
1 0.9 0.1
""".split("\n");
#'''

t = int(buf[0])
buf = buf[1:]
buf2 = []
for i in xrange(1, t + 1):
    a, b = parse(buf[0], "ii")
    buf = buf[1:]
    _, p = parse(("%s " % a) + buf[0], "iF0")
    buf = buf[1:]

    buf2.append([a, b, p])

with open(outfile, "wt") as f:
    for rnd, [k, n, p] in enumerate(buf2):
        gp = 1.0
        good = [1.0]
        for i in xrange(k):
            gp *= p[i]
            good.append(gp)

        mv = n + 2
Example #14
0
            command = ["vlc", pl_item, "--play-and-exit", "--quiet"]
            print command
            if args.fullscreen:
                command.append("--fullscreen")

            print "cool"
            subprocess.call(command)
            print "wat"

        except queue.Empty:
            # Resume loop
            continue


if __name__ == '__main__':

    # get value from command line arguments
    args = argparser.parse()

    PORT = int(args.port)

    # Web server thread to be spawned later
    server = WSGIServer(('0.0.0.0', PORT), app)
    server_thread = gevent.spawn(server.serve_forever)

    # Player thread to be spawned later
    player_thread = gevent.spawn(player_worker, args)

    # Start the threads
    gevent.joinall([server_thread, player_thread])
                        'This is a mandatory option if choosing type 2.Location needs to be input in the following format, for example, chr12:1234..5678')
parser.add_argument('--seqfile', default='', help='This option allows user to specify a sequence filename whose upstream and downstream' + \
                        'region needs to be extracted. This is a mandatory option if choosing default type 1.')
parser.add_argument('--strand', default='+', help='This optional parameter allows a user to specify strand information.Correct strand is denoted by +' + \
                        'and reverse strand by -. Default is +')
parser.add_argument('--organism', default='Homo_sapiens', help='This optional parameter allows the program to search for the input sequence/coordinates ' + \
                        'in the specified genome. If not specified, will search against human genome.')
parser.add_argument('--bases', default=100, type=int, help='This parameter allows a user to specify how many bases upstream and downstream ' + \
                        'of the exon should be extracted. If not provided, it defaults to 100 bases upstream and downstream.')
parser.add_argument('--outfile', default='', help='This is an optional parameter to specify name for an output filename. ' + \
                        'Can be provided either as an absolute path or just filename alone. If not specified, will use a program generated filename.')
parser.add_argument('--meme', default=False, help='This is an optional parameter to specify if the output file needs to be sent to meme server ' + \
                        'for identification of motifs. By default, the switch is turned off.')

# The user supplied arguments are parsed
parsed_data = argparser.parse(parser)
mode = parsed_data['mode']
genome = parsed_data['org']
base_count = parsed_data['bases']
strand = parsed_data['strand']
location = parsed_data['location']
sequence_filename = parsed_data['seq_file']
meme_mode = parsed_data['meme']
sequence = ""

# Create output file name

if not parsed_data['outfile'] == '':
    if os.path.isabs(parsed_data['outfile']):
        out_name = parsed_data['outfile'].split('/')[-1]
        out_dir = parsed_data['outfile'].replace(out_name, '')
                        'This is a mandatory option if choosing type 2.Location needs to be input in the following format, for example, chr12:1234..5678')
parser.add_argument('--seqfile', default='', help='This option allows user to specify a sequence filename whose upstream and downstream' + \
                        'region needs to be extracted. This is a mandatory option if choosing default type 1.')
parser.add_argument('--strand', default='+', help='This optional parameter allows a user to specify strand information.Correct strand is denoted by +' + \
                        'and reverse strand by -. Default is +')
parser.add_argument('--organism', default='Homo_sapiens', help='This optional parameter allows the program to search for the input sequence/coordinates ' + \
                        'in the specified genome. If not specified, will search against human genome.')
parser.add_argument('--bases', default=100, type=int, help='This parameter allows a user to specify how many bases upstream and downstream ' + \
                        'of the exon should be extracted. If not provided, it defaults to 100 bases upstream and downstream.')
parser.add_argument('--outfile', default='', help='This is an optional parameter to specify name for an output filename. ' + \
                        'Can be provided either as an absolute path or just filename alone. If not specified, will use a program generated filename.')
parser.add_argument('--meme', default=False, help='This is an optional parameter to specify if the output file needs to be sent to meme server ' + \
                        'for identification of motifs. By default, the switch is turned off.')

# The user supplied arguments are parsed
parsed_data = argparser.parse(parser)
mode = parsed_data['mode']
genome = parsed_data['org']
base_count = parsed_data['bases']
strand = parsed_data['strand']
location = parsed_data['location']
sequence_filename = parsed_data['seq_file']
meme_mode = parsed_data['meme']
sequence = ""

# Create output file name

if not parsed_data['outfile'] == '':
    if os.path.isabs(parsed_data['outfile']):
        out_name = parsed_data['outfile'].split('/')[-1]
        out_dir = parsed_data['outfile'].replace(out_name, '')
Example #17
0
1
1 1
5
0 5
0 1
1 1
4 7
5 6 
""".split("\n");
#'''

t = int(buf[0])
buf = buf[1:]
buf2 = []
for i in xrange(1, t + 1):
    n, = parse(buf[0], "i")
    buf = buf[1:]
    w = [parse(buf[i], "ii") for i in xrange(n)]
    buf = buf[n:]

    buf2.append([n, w])


def rec(s, s0, s1):
    if (len(s0) + len(s1) == 0): return 0
    print "s0=%s, s1=%s" % (s0, s1)

    m1 = filter(lambda x: w[x][0] <= s, s0)
    m2a = filter(lambda x: w[x][1] <= s, s0)
    m2b = filter(lambda x: w[x][1] <= s, s1)