Пример #1
0
def prob_lose_from_box_greater(n, p, j):
    asdf = 1. / (j - 1)**p * (1. - n * c(n - 1, p - 1) * beta(p, n - p + 1) *
                              betainc(p, n - p + 1,
                                      float(j - 1) / j))
    #asdf = n*c(n-1, p-1) * 1. / (j-1)**p * (betainc(p,n-p+1,1.) - betainc(p, n-p+1, float(j-1)/j))
    #print 'n, p, j quantity:', n, p, j, asdf
    return c(n - 1, p - 1) * sum(1. / j**
                                 (p + k) * c(n - p, k) / c(n - 1, p + k - 1)
                                 for k in xrange(j - p, n - p + 1)) + asdf
Пример #2
0
 def status(self):
     """
     show status
     """
     try:
         pid = open(self.config["swall"]["pidfile"], 'r').read()
         message = c("swall is running[%s]...\n" % pid, 'g')
     except IOError:
         message = c("swall is not running!\n", 'r')
     sys.stdout.write(message)
     sys.stdout.flush()
Пример #3
0
 def main(self):
     """
     init zookeeper
     """
     self.parse_args()
     keeper = Keeper(self.config)
     if keeper.init_db(self.options.force):
         sys.stdout.write(c("init zookeeper db ok\n", 'g'))
     else:
         sys.stdout.write(c("init zookeeper db fail\n", 'r'))
     sys.stdout.flush()
Пример #4
0
def common_get_info():
    """
    get install info
    @return list:
    """
    list_info = []
    print utils.c("请输参数信息(如:115 10.221.8.99 2014-01-17 10:00:00 支持多个服,输入!结束):", 'b')
    while 1:
        tmp_line = raw_input()
        if tmp_line == '!': break
        if len(tmp_line.split()) != 4:
            print utils.c("输入的数据'%s'格式错误" % tmp_line, 'r')
            return []
        list_info.append(tmp_line)
    return list_info
Пример #5
0
def maybe_download_mnist(dataset_dirpath, dataset_dirname, set_name):
    dataset_path = os.path.join(dataset_dirpath, dataset_dirname)
    base_url = 'http://yann.lecun.com/exdb/mnist/'

    train_filenames = [
        'train-images-idx3-ubyte.gz',
        'train-labels-idx1-ubyte.gz',
    ]
    val_filenames = ['t10k-images-idx3-ubyte.gz', 't10k-labels-idx1-ubyte.gz']

    assert set_name in ['train', 'val']
    filenames = train_filenames if set_name == 'train' else val_filenames

    # check existance
    if os.path.exists(dataset_path):
        print(c('mnist dataset already exists: {}'.format(dataset_path),
                'red'))
        return

    # start downloading mnist dataset
    for filename in filenames:
        url = base_url + filename
        with log(
                'download mnist dataset from {}'.format(url),
                'downloaded mnist dataset {} to {}'.format(
                    filename, dataset_path)):
            _download_gz_dataset(url, dataset_dirpath, dataset_dirname)
Пример #6
0
def loss(img, delta, weights):
    y_pred = utils.predict_t(img+delta, weights)
    y_true = tf.convert_to_tensor(np.array([0,0,1,0,0,0,0,0,0,0]).transpose().astype("float32"))
    y_pred = tf.reshape(y_pred,(10,1))
    print(cce(y_true, y_pred))
    loss_v = cce(y_true, y_pred)+lambda_tv*utils.TV(delta)+lambda_c*utils.c(delta)
    return loss_v
Пример #7
0
def maybe_download_lsun(dataset_dirpath,
                        dataset_dirname,
                        category,
                        set_name,
                        tag='latest'):
    dataset_path = os.path.join(dataset_dirpath, dataset_dirname)
    url = 'http://lsun.cs.princeton.edu/htbin/download.cgi?tag={tag}' \
        '&category={category}&set={set_name}'.format(**locals())

    # check existance
    if os.path.exists(dataset_path):
        print(c('lsun dataset already exists: {}'.format(dataset_path), 'red'))
        return

    # start downloading lsun dataset
    with log('download lsun dataset from {}'.format(url),
             'downloaded lsun dataset to {}'.format(dataset_path)):
        _download_zip_dataset(url, dataset_dirpath, dataset_dirname)
Пример #8
0
    def _update_r(self, s_val: float) -> None:
        """Update r vector and R matrix
		s_val:      signal value
		"""
        self.R = self.lambda_ * self.R + self.a @ ct(self.a)
        self.r = self.lambda_ * self.r + s_val * c(self.a)
Пример #9
0
#!/usr/bin/env python
import numpy as np
from utils import fact, c, multinomial, partitions, permutations
"""
Basic idea: compress state space by representing permutations as products of
cycles.  It's not the permutation itself that matters; it's just the
out-of-order # of elements in each cycle. This is isomorphic with # ways to
partition 11 things = 56, small enough to do linear algebra and solve for the
expected # steps to terminate for each state in the Markov chain (involves
inverting a 56 x 56 matrix). From here, it's just a bunch of messy counting.
"""

N = 11
nways_to_choose_swap = c(N, 3) * fact(3)


def canon(part):
    return tuple(sorted(part))


def same_ns(part):
    ret = [1]
    cur_i = 0
    for i in xrange(1, len(part)):
        if part[i] == part[cur_i]:
            ret[-1] += 1
        else:
            ret.append(1)
            cur_i = i
    return ret
Пример #10
0
def show_main():
    """
    显示功能列表
    return type_opts dict:操作类型信息
    """
    os.system("clear")
    type_opts = utils.read_config(ctype="optype")
    print utils.c("==============================================================", 'y')
    print utils.c("操作类型\t| 说明")
    print utils.c("--------------------------------------------------------------", 'y')
    for optype in type_opts.iterkeys():
        print "%s\t| %s" % (utils.c(optype, 'g'), utils.c(type_opts[optype]))
    print "%s\t\t| 退出此程序" % utils.c("exit ", 'g')
    print utils.c("==============================================================", 'y')
    return type_opts
Пример #11
0
    def main(self, game_type, server_ip, sub_cmd):
        # args, kwargs = parse_args_and_kwargs(self.args[1:])
        kwargs = {}
        self.game_type = game_type
        self.server_ip = "%s" % server_ip
        #self.cmd = "cmd.call"
        #self.cmd = "manage_server.%s" % sub_cmd
        if '&' in sub_cmd:
            self.cmd = "manage_game.%s" % sub_cmd.split('&')[0]
            self.version= "%s" % sub_cmd.split('&')[1]
            self.server_status= "%s" % sub_cmd.split('&')[2]
            #self.parse_args(['ctl', self.game_type, self.server_ip, self.cmd, self.sub_cmd])
            self.sub_cmd = str(self.version) + '&' + str(self.server_status)
            self.parse_args(['ctl', self.game_type, self.server_ip, self.cmd, self.sub_cmd])
        else:
            self.cmd = "manage_game.%s" % sub_cmd

        #self.sub_cmd = sub_cmd
        #self.sub_cmd = "manage_server.start_server"
            self.sub_cmd = ""
        #self.sub_cmd = "game"
        
            self.parse_args(['ctl', self.game_type, self.server_ip, self.cmd, self.sub_cmd])
        args = [self.game_type, self.server_ip, self.cmd, self.sub_cmd]
        # if len(args) < 2:
        #     self.print_help()
        #     sys.exit(1)
            #解析参数,获取位置参数和关键字参数

        cli = Client(
            # globs=args[1],
            globs = self.server_ip,
            exclude_globs=self.options.exclude,
            # role=args[0],
            role=self.game_type,
            nthread=int(self.options.nthread),
            conf_dir=self.options.config_dir
        )
        rets = {}

        if self.cmd == "sys.job_info":
        # if args[2] == "sys.job_info":            
            if len(args[3:]) == 0 and len(kwargs) == 0:
                sys.stderr.write(c("jid needed for sys.job_info\n", 'r'))
                sys.stderr.flush()
            else:
                rets = cli.job_info(*args[3:], **kwargs)
        else:
            # cli.submit_job(args[2], *args[3:], **kwargs)

            cli.submit_job(self.cmd, self.sub_cmd, **kwargs)
            rets = cli.get_return(self.options.timeout)
            

        # rets = {'game': {'swall_sa_server_172.17.0.2': 1}}
        if rets:
            rets = sort_ret(rets)
        else:
            # print c('#' * 50, 'y')
            # return color(rets.get("msg"), 'r')
            return rets.get("msg")
            # print c('#' * 50, 'y')
            sys.exit(1)

        nfail = 0
        for ret in rets:
            if not ret[2]:
                nfail += 1

        if not self.options.is_raw:
            format_ret = enumerate(
                # [u"%s %s : %s" % (u"[%s]" % c(ret[0], 'y'), c(ret[1], 'b'), color(format_obj(ret[2]))) for ret in rets])
                [u"%s %s : %s" % (u"[%s]" % ret[0], ret[1], format_obj(ret[2])) for ret in rets])
            
        else:
            format_ret = enumerate(
                [u"%s %s : %s" % (u"[%s]" % ret[0], ret[1], ret[2]) for ret in rets])
            
        # print c('#' * 50, 'y')
        for index, item in format_ret:
            return rets
            # return item.encode("utf-8")

        # print c('#' * 50, 'y')

        if locals().get('index') >= 0:
            index += 1
        else:
            index = 0
Пример #12
0
from utils import ConstHelper as c

# offsets in EOT file structure.
EOT_OFFSET = c({
    'LENGTH': 0,
    'FONT_LENGTH': 4,
    'VERSION': 8,
    'CHARSET': 26,
    'MAGIC': 34,
    'FONT_PANOSE': 16,
    'ITALIC': 27,
    'WEIGHT': 28,
    'UNICODE_RANGE': 36,
    'CODEPAGE_RANGE': 52,
    'CHECKSUM_ADJUSTMENT': 60,
})


#  Offsets in different SFNT (TTF) structures.
SFNT_OFFSET = c({
    # sfntHeader:
    'NUMTABLES': 4,

    # TableDirectoryEntry
    'TABLE_TAG': 0,
    'TABLE_OFFSET': 8,
    'TABLE_LENGTH': 12,

    # OS2Table
    'OS2_WEIGHT': 4,
    'OS2_FONT_PANOSE': 32,
Пример #13
0
from utils import ConstHelper as c

# offsets in EOT file structure.
EOT_OFFSET = c({
    'LENGTH': 0,
    'FONT_LENGTH': 4,
    'VERSION': 8,
    'CHARSET': 26,
    'MAGIC': 34,
    'FONT_PANOSE': 16,
    'ITALIC': 27,
    'WEIGHT': 28,
    'UNICODE_RANGE': 36,
    'CODEPAGE_RANGE': 52,
    'CHECKSUM_ADJUSTMENT': 60,
})

#  Offsets in different SFNT (TTF) structures.
SFNT_OFFSET = c({
    # sfntHeader:
    'NUMTABLES': 4,

    # TableDirectoryEntry
    'TABLE_TAG': 0,
    'TABLE_OFFSET': 8,
    'TABLE_LENGTH': 12,

    # OS2Table
    'OS2_WEIGHT': 4,
    'OS2_FONT_PANOSE': 32,
    'OS2_UNICODE_RANGE': 42,
Пример #14
0
def agent(obs, config):
    start_time = perf_counter()
    global size
    global me
    global num_converts
    global prev_board
    global do_tta
    global steps_since_slow_epoch

    conf = config

    board = Board(obs, config)
    if board.step == 0: prev_board = board
    me = board.current_player
    set_turn_data(board)
    ship_converts(board)

    # convert to game format
    step, halite, ship, base, cargo, ph, threat = processStep3(
        obs, conf, config)

    # check if we will do TTA this step
    do_tta = (step >= TTA_START_STEP) and (steps_since_slow_epoch >=
                                           TTA_STABLE_STEPS)

    # featurise
    input_stack = getInputStack3(obs,
                                 step,
                                 halite,
                                 ship,
                                 base,
                                 cargo,
                                 ph,
                                 threat,
                                 action_map,
                                 first_player=obs['player'])
    #input_stack = randomtoroidalcrop_single(input_stack, 0, 0)
    input_stack = padit(input_stack[:, :, :])

    if not do_tta:

        input_stack = torch.as_tensor(input_stack).unsqueeze(0).to(device)
        policy_output = model(input_stack)[:, :5, :, :].to(
            device)  # Discard Spawn/Convert predictions
        nn_ship_actions = Softmax(1)(
            policy_output).cpu().detach().numpy()[:, :, 5:26, 5:26]

    else:  # build TTA batch

        input_stack = np.repeat(input_stack[np.newaxis, :, :], 5, axis=0)
        input_stack[1] = randomtoroidalcrop_single(input_stack[1], 0, 10)
        input_stack[2] = randomtoroidalcrop_single(input_stack[2], 10, 0)
        input_stack[3] = randomtoroidalcrop_single(input_stack[3], 10, 10)
        input_stack[4] = randomtoroidalcrop_single(input_stack[4], 5, 5)
        input_stack = torch.as_tensor(input_stack).to(device)

        # predict
        policy_output = model(input_stack)[:, :5, :, :].to(
            device)  # Discard Spawn, Convert predictions

        # revert TTA back
        nn_ship_actions = policy_output.cpu().detach().numpy()
        nn_ship_actions[1] = randomtoroidalcrop_single(nn_ship_actions[1], 0,
                                                       -10)
        nn_ship_actions[2] = randomtoroidalcrop_single(nn_ship_actions[2], -10,
                                                       -0)
        nn_ship_actions[3] = randomtoroidalcrop_single(nn_ship_actions[3], -10,
                                                       -10)
        nn_ship_actions[4] = randomtoroidalcrop_single(nn_ship_actions[4], -5,
                                                       -5)

        nn_ship_actions = softmax_scipy(nn_ship_actions, axis=1)[:, :, 5:26,
                                                                 5:26]

    actions = {}

    # my assets -- to predict which step to take
    my_ships = obs['players'][obs['player']][SHIPS]
    my_bases = obs['players'][obs['player']][BASES]
    my_halite = obs['players'][obs['player']][HALITE]
    all_ships = {}
    for player in range(len(obs['players'])):
        all_ships.update(obs['players'][player][SHIPS])
    ship_list = list(my_ships.items())
    base_list = list(my_bases.items())
    ship_id_to_idx = {
        ship_key: ship_idx
        for ship_idx, (ship_key, ship_info) in enumerate(ship_list)
    }

    # score matrix -- can only pick valid actions
    C = -10000 * np.ones((len(my_ships) + len(my_bases),
                          size * size + len(my_ships) + len(my_bases)))

    # add ships to scoring matrix
    for ship_idx, (ship_key, ship_info) in enumerate(ship_list):
        x, y = xy(ship_info[POSITION])
        ship_pred_actions = nn_ship_actions[0, :, x, y]

        raw_ship_pred_actions = np.copy(ship_pred_actions)

        restore_sum = np.sum(ship_pred_actions[1:5])
        ship_pred_actions[1:5] = np.where(ship_pred_actions[1:5] > 0.,
                                          ship_pred_actions[1:5], 0)
        if np.sum(ship_pred_actions[1:5]) > 0:
            ship_pred_actions[1:5] *= restore_sum / sum(ship_pred_actions[1:5])

        restore_sum = np.sum(ship_pred_actions[1:5])
        if restore_sum > 1e-6:
            ship_pred_actions[1:5] = ship_pred_actions[1:5]**PRED_PWR
            ship_pred_actions[1:5] *= restore_sum / sum(ship_pred_actions[1:5])

        ship_ranked_actions = np.zeros((5, ), dtype=np.float32)
        for rank in range(0, np.sum(ship_pred_actions > 1e-6)):
            while True:
                action = int(random.choice(np.flatnonzero(ship_pred_actions)))

                if random.random() < ship_pred_actions[action]:
                    ship_ranked_actions[
                        action] = 5 - rank + raw_ship_pred_actions[action]
                    ship_pred_actions[action] = 0
                    if np.sum(ship_pred_actions) > 0:
                        ship_pred_actions = ship_pred_actions / np.sum(
                            ship_pred_actions)
                    else:
                        ship_pred_actions = 0
                    break

        C[ship_idx, x + size * y] = ship_ranked_actions[0]
        C[ship_idx, x + size * c(y - 1)] = ship_ranked_actions[1]  # NORTH
        C[ship_idx, c(x + 1) + size * y] = ship_ranked_actions[2]  # EAST
        C[ship_idx, x + size * c(y + 1)] = ship_ranked_actions[3]  # SOUTH
        C[ship_idx, c(x - 1) + size * y] = ship_ranked_actions[4]  # WEST

        if AVOID_STUPID_MOVES:  # Prevent stupid moves. Sometimes helps, but probably not needed
            pt = board.ships[ship_key].position
            if turn.avoid[ship_key][pt]: C[ship_idx, x + size * y] -= 1500
            if turn.avoid[ship_key][move(pt, NORTH)]:
                C[ship_idx, x + size * c(y - 1)] -= 1000
            if turn.avoid[ship_key][move(pt, EAST)]:
                C[ship_idx, c(x + 1) + size * y] -= 1000
            if turn.avoid[ship_key][move(pt, SOUTH)]:
                C[ship_idx, x + size * c(y + 1)] -= 1000
            if turn.avoid[ship_key][move(pt, WEST)]:
                C[ship_idx, c(x - 1) + size * y] -= 1000

        if BASE_RAID_AT_GAME_END:  # Kamikaze into enemy bases
            ship = board.ships[ship_key]
            if board.step > STEP_BASE_RAID and ship.halite == 0:
                if turn.num_ships > 5:
                    d, sy_pt = nearest_shipyard(
                        ship.position, board.players[turn._id].shipyards)
                    if d < 20:
                        acts, steps, distance = dirs_to(ship.position, sy_pt)
                        C[ship_idx, x + size * y] -= 1500  # not idle
                        if NORTH in acts:
                            C[ship_idx, x + size * c(y - 1)] += 2500  # NORTH
                        if EAST in acts:
                            C[ship_idx, c(x + 1) + size * y] += 2500  # EAST
                        if SOUTH in acts:
                            C[ship_idx, x + size * c(y + 1)] += 2500  # SOUTH
                        if WEST in acts:
                            C[ship_idx, c(x - 1) + size * y] += 2500  # WEST

    shipyard_actions(board)

    # add bases to scoring matrix
    for base_idx, (base_key, base_info) in enumerate(base_list):
        x, y = xy(base_info)
        spawn_yesno = False
        for sy in me.shipyards:
            if sy.position[0] == x and (20 - sy.position[1]) == y:
                if sy.next_action == SPAWN:
                    spawn_yesno = True

        if my_halite >= conf.spawnCost:
            C[len(my_ships) + base_idx, x + size * y] = spawn_yesno * 10
            C[len(my_ships) + base_idx,
              size * size + len(my_ships) + base_idx] = 5
        else:
            C[len(my_ships) + base_idx,
              size * size + len(my_ships) + base_idx] = 10

    #-------------- PROTECTOR SECTION ------------------#
    # In each step, try to have 1 ship closer than the closest enemy ship. If not, we
    # move towards our shipyard. This allows protectors to still mine when no threat

    # For each shipyard, get closest friendly & enemy ship
    protectors = {}
    attackers = {}
    assigned_ships = set()
    for sy in me.shipyards:

        ship = board.cells[sy.position].ship
        if ship is not None and ship.player_id == me.id and board.step > 150:
            continue

        # If the action is SPAWN then we can skip
        if sy.next_action == SPAWN:
            continue

        syx, syy = sy.position.x, 20 - sy.position.y
        sy_dists = flood_dist(syx, syy, size, size)

        protector_dists = {}
        attacker_dists = {}
        for ship_key, ship_info in all_ships.items():
            if ship_key in assigned_ships:
                continue
            shipx, shipy = xy(ship_info[POSITION])
            if ship_key in my_ships:  # For our own ships, use A* distance
                # Prefer 0 ship first, then the heaviest ship, to protect, it will
                # deposit its ore first and become a 0-ship.
                d = sy_dists[shipx, shipy]
                protector_dists[ship_key] = (d, -ship_info[CARGO])
            else:  # For enemies, use L1 distance
                d = sy_dists[shipx, shipy]
                attacker_dists[ship_key] = (d, -ship_info[CARGO])

        if len(protector_dists) > 0 and len(attacker_dists) > 0:
            sorted_protector_dist = sorted(protector_dists.items(),
                                           key=lambda x: x[1])
            protector = min(protector_dists.items(), key=lambda x: x[1])
            attacker = min(attacker_dists.items(), key=lambda x: x[1])

            # If the second-closet ship is 1 move away (and closest enemy  > 1), then he probably wants to
            # deposit, so we make it the protector (HACK TO AVOID DEADLOCK AT OWN BASE)
            if len(sorted_protector_dist) > 1 and sorted_protector_dist[0][1][
                    0] == 0 and sorted_protector_dist[1][1][
                        0] == 1 and sorted_protector_dist[1][1][
                            -1] != 0 and attacker[1][0] > 1:
                protector = sorted_protector_dist[1]
            protectors[sy] = protector
            assigned_ships.add(protector[0])
            attackers[sy] = attacker

    for sy in attackers:
        # If closest is further than d=1 but closer than friendly ship
        #  with buffer), than we need to move towards our SY.
        syx, syy = sy.position.x, 20 - sy.position.y
        for ship_idx, (ship_key, ship_info) in enumerate(ship_list):
            if ship_key == protectors[sy][0]:
                x, y = xy(ship_info[POSITION])
                break

        if (protectors[sy][1][0] < attackers[sy][1][0] < protectors[sy][1][0] +
                3) or (protectors[sy][1][0] == attackers[sy][1][0]
                       and -protectors[sy][1][-1] <= -attackers[sy][1][-1]):
            acts = find_steps_to(Point(x, y), Point(syx, syy))
            ship_idx = ship_id_to_idx[protectors[sy][0]]
            if len(acts) > 0:
                C[ship_idx, x + size * y] -= 20000  # not idle
            else:
                C[ship_idx, x + size * y] += 20000  # idle

            if NORTH in acts:
                C[ship_idx, x + size * c(y - 1)] += 20000  # NORTH
            if EAST in acts: C[ship_idx, c(x + 1) + size * y] += 20000  # EAST
            if SOUTH in acts:
                C[ship_idx, x + size * c(y + 1)] += 20000  # SOUTH
            if WEST in acts: C[ship_idx, c(x - 1) + size * y] += 20000  # WEST

    entity_idxs, assignments = scipy.optimize.linear_sum_assignment(
        C, maximize=True)

    # iterate over ships, assign them action
    assigned = dict(zip(entity_idxs, assignments))

    remaining_str = ""
    converting_str = ""
    moving_str = ""
    protecting_str = ""
    protecting_list = []
    moving_list = []

    if turn.last_episode:  # Last step, convert laden ships to bases
        for ship_idx, (ship_key, ship_info) in enumerate(ship_list):
            x, y = xy(ship_info[POSITION])

            if ship_info[CARGO] > conf.convertCost:
                actions[ship_key] = 'CONVERT'
    else:

        # Ship_converts() has already decided conversion.
        # Need to read it back as ML bot is driving action thrugh another mechanism.
        ships_to_convert = []
        for ship in me.ships:
            if ship.next_action == CONVERT:
                ships_to_convert.append(ship.position)

        for ship_idx, (ship_key, ship_info) in enumerate(ship_list):
            x, y = xy(ship_info[POSITION])

            # TEAM XY and MY XY are different: MY Y = 20 - TEAM Y
            converting = False
            for s_to_c in ships_to_convert:
                if s_to_c[0] == x and (20 - s_to_c[1]) == y:
                    if (my_halite + ship_info[CARGO]
                        ) >= conf.convertCost:  # just in case
                        actions[ship_key] = 'CONVERT'
                        my_halite -= conf.convertCost
                        converting_str += '{} at ({},{}), '.format(
                            ship_key, x, y)
                        converting = True
                        turn.taken[s_to_c] = 1
                        num_converts += 1

            if not converting:

                xt, yt = xy(assigned[ship_idx])
                if x == xt and y == yt:
                    remaining_str += '{} at ({},{}), '.format(ship_key, x, y)
                else:
                    moving_list.append([ship_key, x, y, xt, yt])
                    a = None
                    if c(xt - x) == 1: a = 'EAST'
                    elif c(yt - y) == 1: a = 'SOUTH'
                    elif c(x - xt) == 1: a = 'WEST'
                    elif c(y - yt) == 1: a = 'NORTH'
                    if a is not None:
                        actions[ship_key] = a

                    turn.taken[move(board.ships[ship_key].position,
                                    act(a))] = 1

    #--------------- SPAWN SECTION --------------------#
    spawning_str = ""
    for base_idx, (base_key, base_info) in enumerate(base_list):
        if assigned[len(my_ships) + base_idx] >= size * size:
            continue
            # no spawn
        else:

            if my_halite >= conf.spawnCost:
                my_halite -= conf.spawnCost
                actions[base_key] = 'SPAWN'
                spawning_str += '({},{})'.format(*xy(base_info))
                turn.taken[board.shipyards[base_key].position] = 1
    # -------------------------------------------------------#

    #--------------- PROTECTOR SECTION --------------------#
    # # Find protectors (currently on own shipyards)
    protectors = {}
    for sy in me.shipyards:
        ship = board.cells[sy.position].ship
        if ship is not None and ship.player_id == me.id:
            protectors[sy.position] = ship
    # Go back to protect if there's no new ship coming in
    for pt, ship in protectors.items():
        if not turn.taken[pt] and ship.id in actions.keys():
            protecting_list.append(ship.id)
            del actions[ship.id]  # stay idle to protect
    # -------------------------------------------------------#

    # Print actions
    for ship_key, x, y, xt, yt in moving_list:
        if ship_key in protecting_list:
            protecting_str += "{} at ({},{}), ".format(ship_key, x, y)
        else:
            moving_str += '{} from ({},{}) to ({},{}), '.format(
                ship_key, x, y, xt, yt)

    prev_board = board

    if (perf_counter() - start_time) * 1e3 > TTA_SLOW_EPOCH_TRIGGER:
        steps_since_slow_epoch = 0
    else:
        steps_since_slow_epoch += 1

    return actions
Пример #15
0
def openqq_init_do(list_info, opts):
    """
    开放平台大区、支付、域名等创建和配置
    @list_info list:["115 10.221.8.99 2014-01-17 10:00:00","116 10.221.8.100 2014-01-17 12:00:00"]
    @return game_zones dict:{"519":"570","520":"571","521":"572"}
    """

    #登陆开放平台
    log("开始登陆平台")
    test_dir_no = 25
    openqq = openQQ.OpenQQ(opts)
    openqq.login()
    log_ret = openqq.login()
    log(log_ret.split("'")[-4])
    mc_gtk = openqq.getACSRFToken()

    log("开始获取游戏区服信息")
    cur_games = openqq.get_games()
    log("获取游戏区服信息完毕")
    print utils.c("##############################", 'y')
    game_zones = {}
    for item in list_info:
        #安装测试区
        server_id, server_ip, online_date, online_time = item.split()
        log("开始安装测试%s服" % server_id)
        test_info = add_test_server(openqq, cur_games, test_dir_no, "测试%s服" % server_id)
        if test_info:
            log(u"游戏%s服对应的zoneid是 %s,域名是 %s" % (server_id, test_info[0], test_info[1]))
        else:
            log(u"游戏%s服创建测试大区失败")
            continue

        #支付配置
        zoneid, domain = test_info
        game_zones[str(server_id)] = zoneid
        #add_pay_entry(openqq, zoneid)

        #绑定域名
        log("开始进行域名解析")
        mod = int(server_id) % 4
        router_info = {
            0: "10.168.0.128",
            1: "10.168.0.60",
            2: "10.168.0.61",
            3: "10.168.0.93"
        }
        router_ip = router_info.get(mod)

        msg, retcode = bind_domain(openqq, domain, router_ip, mc_gtk, 80)
        log("游戏%s服,router(%s) %s " % (server_id, "80", msg))

        gateway_port = opts["game_ports"].get("game_%s" % server_ip)
        if gateway_port:
            msg, retcode = bind_domain(openqq, domain, server_ip, mc_gtk, gateway_port)
            log("游戏%s服,游戏网关(%s)%s " % (server_id, gateway_port, msg))
        else:
            log("游戏%s服,游戏网关获取失败,不能继续解析,请手动解析" % server_id)

        #修改服务器状态,去掉游戏服的“荐”,“新“这些状态标志
        ret = openqq.change_server_status(test_dir_no, zoneid, 1, 0, 0)
        ret_code, msg = re.findall(r'"(iRet|ret)":"?(\d+)"?.+"msg":"([^"]+)"', ret)[0][1:]
        msg = msg.decode("unicode_escape")
        if ret_code != "0":
            log('游戏%s服,修改服务器状态失败' % server_id)
        else:
            log('游戏%s服,修改服务器状态成功' % server_id)

        #修改游戏服为正式服,初始化的大区是处于测试状态
        (ret_code, state) = openqq.update_staus(test_dir_no, zoneid, 1)
        if int(ret_code) == 0:
            log("游戏%s服,修改节点状态成功" % server_id)
        else:
            log("游戏%s服,修改节点状态失败" % server_id)

    print utils.c("##############################", 'y')
    log("开始发布游戏")
    retcode = pub_game(openqq)
    if retcode:
        log("游戏发布成功")
    else:
        log("游戏发布失败,请手动发布")

    #log("开始同步沙箱")
    #ret_code = update_zone(openqq, 0)
    #if ret_code:
    #    log("沙箱同步成功")
    #else:
    #    log("沙箱同步失败")

    log("跳过现网同步,请手动同步")
    #log("开始同步现网")
    #ret_code = update_zone(openqq, 1)
    #if ret_code:
    #    log("现网同步成功")
    #else:
    #    log("现网同步失败")

    return game_zones
Пример #16
0
Idea: write S(L) as a summation, sum over terms with
same power of 5. Tricky part is computing the coefficient;
for this we can use identity

sum(c(n,i) for i in xrange(k+1)) == c(n+1,k+1)
"""

N = 50*10**6
prime = sieve(N)

pi = [0]*(N+1)
for i in xrange(2,N+1):
    pi[i] = pi[i-1] + prime[i]

def check(n):
    ret = 0
    for k in xrange(pi[n]+1):
        ret += 6*c(n-1,k)*5**(n-1-k)
    return ret

mod = 10**9+7
ans=0
stop = 0
for diff in tqdm.tqdm(xrange(1, N+1)):
    while stop<N and stop+1-pi[stop+1]<=diff:
        stop += 1
    ans += 6*c(stop,stop-diff,mod)*pow(5,diff-1,mod) % mod
    ans %= mod

print ans
Пример #17
0
def check(n):
    ret = 0
    for k in xrange(pi[n]+1):
        ret += 6*c(n-1,k)*5**(n-1-k)
    return ret
Пример #18
0
def prob_lose_from_box_less(n, p, j):
    return 1. / p**p * sum(
        c(p - 1, k) * float(p - j)**(p - 1 - k) for k in xrange(j, p))
Пример #19
0
#!/usr/bin/env python
from utils import c

# first, figure out that:
# e(n,p) == (1-p)**(n+1)*sum(k**n*p**k,k,1,oo)
# then refer to the following pages :)
# http://mathworld.wolfram.com/Polylogarithm.html
# http://mathworld.wolfram.com/EulerianNumber.html

mod = 10**9 + 7
N = 10**7
K = 4 * 10**6

ans = 0
for j in xrange(N - K + 1):
    ans = (ans + pow(-1, j) * c(N + 1, j, mod) * pow(N - K + 1 - j, N, mod) %
           mod) % mod
print ans