def __add__(self, other, return_class=True): """ Adds something to this dimension if other is a scalar, @return: Another Dimension instance if other is another class instance, @return: A scalar value """ if isinstance(other, self.__class__): #We're subtracting/adding another class, result should be a scalar other = other.decimal_degree return_class = False elif isinstance(other, BaseDimension): #This will start to make sense for derivative classes. If something is an Instance of BaseDimension but not of the same class, #Then you've passed in a another type of dimension and should convert it first! raise TypeError(u"{my_class} object calculation expected a {my_class}, but you gave a {other_class}. Please convert it to the same type of dimension first.".format( my_class=self.__class__.__name__, other_class=other.__class__.__name__) ) else: other = d(other) #Otherwise, try to cast it to a Decimal # if return_class: #Assumes we want to return an instance of the class return self.__class__(self.decimal_degree + other) else: return d(self.decimal_degree + other)
def fast_dca(msa1hot, weights, penalty=4.5): """Return a shrunk covariance inversion.""" # pylint: disable=too-many-locals # device = msa1hot.device nr, nc, ns = msa1hot.shape x = msa1hot.view(nr, -1) num_points = weights.sum() - torch.sqrt(weights.mean()) mean = (x * weights[:, None]).sum(dim=0, keepdims=True) / num_points x = (x - mean) * torch.sqrt(weights[:, None]) cov = (x.t() @ x) / num_points cov_reg = cov + torch.eye(nc * ns).to(d()) * penalty / torch.sqrt(weights.sum()) inv_cov = torch.inverse(cov_reg) x1 = inv_cov.view(nc, ns, nc, ns) x2 = x1.transpose(1, 2).contiguous() features = x2.reshape(nc, nc, ns * ns) x3 = torch.sqrt((x1[:, :-1, :, :-1] ** 2).sum(dim=(1, 3))) * ( 1 - torch.eye(nc).to(d()) ) apc = x3.sum(dim=0, keepdims=True) * x3.sum(dim=1, keepdims=True) / x3.sum() contacts = (x3 - apc) * (1 - torch.eye(nc).to(d())) return torch.cat((features, contacts[:, :, None]), dim=2)
def prep_seq(a3m, wmin=0.8, ns=21): """Return a one-hot encoded MSA for the given sequences.""" nrow, ncol = a3m.shape msa1hot = F.one_hot(a3m, ns).float().to(d()) w = reweight(msa1hot, wmin).float().to(d()) # 1d sequence f1d_seq = msa1hot[0, :, :20].float() f1d_pssm = msa2pssm(msa1hot, w) f1d = torch.cat((f1d_seq, f1d_pssm), dim=1) f1d = f1d[None, :, :].reshape((1, ncol, 42)) # 2d sequence f2d_dca = ( fast_dca(msa1hot, w) if nrow > 1 else torch.zeros((ncol, ncol, 442)).float() ) f2d_dca = f2d_dca[None, :, :, :] f2d_dca = f2d_dca.to(d()) f2d = torch.cat( ( f1d[:, :, None, :].repeat(1, 1, ncol, 1), f1d[:, None, :, :].repeat(1, ncol, 1, 1), f2d_dca, ), dim=-1, ) f2d = f2d.view(1, ncol, ncol, 442 + 2 * 42) return f2d.permute((0, 3, 2, 1)), msa1hot
def brute_force_dist(input_points): min_distance = d(input_points[0], input_points[1]) for i, point1 in enumerate(input_points): for point2 in input_points[i + 1:]: if d(point1, point2) < min_distance: min_distance = d(point1, point2) return min_distance
def bann_player(self, pid): l("Player", pid, "is being banned.") self.banned_players.append(pid) while self.current_player_thread.is_alive(): d("Killing it!") terminate_thread(self.current_player_thread) self.current_player_thread.join(0.01) # Wait ten ms between each kill attempt l("Banned players:", self.banned_players)
def brute_force_all(input_points): point_min1, point_min2, min_distance = 0, 1, d(input_points[0], input_points[1]) for i, point1 in enumerate(input_points): for j, point2 in enumerate(input_points[i + 1:], i + 1): if d(point1, point2) < min_distance: point_min1, point_min2, min_distance = input_points[ i], input_points[j], d(point1, point2) return point_min1, point_min2, min_distance
def _check_player_agreements(self, tr): # Make a copy of the data of the transaction... data = dict(tr.get_data()) data2 = dict(tr.get_data()) try: return ( self.players[tr.player_1].agree_with_transaction(data) == self.passwords[tr.player_1] and self.players[tr.player_2].agree_with_transaction(data2) == self.passwords[tr.player_2] ) except Exception as e: d(e) return False
def load(self): """Load stored models.""" self.models = [0] * len(self.model_paths) # self.cuda_streams = [torch.cuda.Stream() for i in self.model_paths] for i, model_path in enumerate(self.model_paths): print(f"Loading {model_path}...") self.models[i] = trRosettaNetwork() # .share_memory() self.models[i].load_state_dict( torch.load(model_path, map_location=torch.device(d())) ) self.models[i].to(d()).eval()
def play_round(self, current_round): d('Dummy player', self.player_id, 'is playing yay!') tr = ( self.player_id, self.players_ids[self.player_id-1], # Just transfer money to the player that is player just before us Resources.CASH, self.resources[Resources.CASH]/2 ) self.interface['make_transaction']( type="UnidirectionalTransaction", args=tr, calling_player=self, )
def __init__(self, player_id, players_ids, starting_resources, password, interface): """ :param player_id: int The id of the currently being created player :param players_ids: [int] The ids of the players in the order players are going to play :param interface: {string: function} interface to be used by the player to make actions on the game :param starting_resources: {Resource: int} the amount of each resource we have at the beginning """ super(AbstractPlayer, self).__init__() self.player_id = player_id self.interface = interface self.players_ids = players_ids self.resources = starting_resources self.passwd = password d("Instantiating player", self.player_id, "with password", self.passwd)
def __init__(self, seq_L, bkg_dir, weights=None): """Construct a loss object.""" super().__init__() bkg = self.get_best_bkg_match(bkg_dir, seq_L) self.bd = torch.from_numpy(bkg["dist"]).permute(2, 1, 0).to(d()).unsqueeze(0) self.bo = torch.from_numpy(bkg["omega"]).permute(2, 1, 0).to( d()).unsqueeze(0) self.bt = torch.from_numpy(bkg["theta"]).permute(2, 1, 0).to( d()).unsqueeze(0) self.bp = torch.from_numpy(bkg["phi"]).permute(2, 1, 0).to(d()).unsqueeze(0) self.w = weights or Structural_Background_Loss.DEFAULT_WEIGHTS
def check_th7(g, c): # O(V^3) bfg = nx.MultiDiGraph() bfg.add_weighted_edges_from([(e[1], e[0], w(g, e)) for e in g.edges]) bfg.add_weighted_edges_from([ (v, u, W[u, v] - 1) for u in g.nodes for v in g.nodes if (u, v) in W and (u, v) in D and D[u, v] > c and not (D[u, v] - d(g, v) > c or D[u, v] - d(g, u) > c) ]) root = 'root' bfg.add_weighted_edges_from([(root, n, 0) for n in bfg.nodes]) try: return nx.single_source_bellman_ford_path_length(bfg, root) except nx.exception.NetworkXUnbounded: return None
def _calc_degreeminutes(decimal_degree): ''' Calculate degree, minute second from decimal degree ''' sign = cmp(decimal_degree, 0) # Store whether the coordinate is negative or positive decimal_degree = abs(decimal_degree) degree = decimal_degree//1 # Truncate degree to be an integer decimal_minute = (decimal_degree - degree)*d("60") # Calculate the decimal minutes minute = decimal_minute//1 # Truncate minute to be an integer second = (decimal_minute - minute)*d("60") # Calculate the decimal seconds # Finally, re-impose the appropriate sign degree = degree*sign minute = minute*sign second = second*sign return (degree, minute, decimal_minute, second)
def preprocess(msa_file=None, wmin=0.8, ns=21, use_random_seq=False): """Return a one-hot encoded MSA from a random sequence or an `.a3m` file.""" if use_random_seq: a3m = torch.randint(0, 20, (1, 67), device=d(), requires_grad=False) elif msa_file: a3m = torch.from_numpy(parse_a3m(msa_file)).long() return prep_seq(a3m, wmin=wmin, ns=ns)
def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: """ Function that encodes the source sequence. :param x: Our vectorized source sequence. [Batch_size x seq_len] :param mask: Mask to be passed to the SelfAttention Block when encoding the x sequence -> check SelfAttention. :returns: - predicted log-probability vectors for each token based on the preceding tokens. [Batch_size x seq_len x n_classes] """ tokens = self.token_embedding(x) b, t, e = tokens.size() positions = self.pos_embedding(torch.arange( t, device=d()))[None, :, :].expand(b, t, e) x = tokens + positions x = self.do(x) for tblock in self.tblocks: x = tblock(x, mask) mask = mask.squeeze(1).float() expanded_mask = torch.repeat_interleave(mask, e, 1).view(b, t, e) x = torch.mul(expanded_mask, x) x = x.max(dim=1)[0] if self.max_pool else x.mean( dim=1) # pool over the time dimension x = self.toprobs(x) return F.log_softmax(x, dim=1)
def decode(self, trg: torch.Tensor, trg_mask: torch.Tensor, memory: torch.Tensor, src_mask: torch.Tensor) -> torch.Tensor: """ Function that encodes the target sequence. :param trg: Our vectorized target sequence. [Batch_size x trg_seq_len] :param trg_mask: Mask to be passed to the SelfAttention Block when encoding the trg sequence-> check SelfAttention. :param memory: Our src sequence encoded by the encoding function. This will be used as a memory over the source sequence. :param src_mask: Mask to be passed to the SelfAttention Block when computing attention over the source sequence/memory. -> check SelfAttention. :returns: - Returns the log probabilities of the next word over the entire target sequence. [Batch_size x trg_seq_len x vocab_size] """ tokens = self.token_embedding(trg) b, t, e = tokens.size() positions = self.pos_embedding(torch.arange(t, device=d()))[None, :, :].expand(b, t, e) x = tokens + positions trg_mask = trg_mask & subsequent_mask(t).type_as(trg_mask) for block in self.decoding_blocks: x = block(x, memory, src_mask, trg_mask) x = self.toprobs(x.view(b*t, e)).view(b, t, self.vocab_size) return F.log_softmax(x, dim=2)
def __init__(self, motif_npz_path, mask=None, save_dir=None, keys=None): """Construct a loss object. Args: motif_npz_path: t, p, d, o for the target structure mask: binary mask of shape [LxL] that indicates where to apply the loss keys (optional): only apply the `motif_loss` to certain components (default: ["dist", "omega", "theta", "phi"]) """ super().__init__() self.device = torch.device(d()) self.motif = dict(np.load(motif_npz_path)) self.mask = mask self.keys = keys or Motif_Satisfaction.DEFAULT_KEYS self.seq_L = self.mask.shape[0] save_dir = Path(save_dir) if save_dir else None # If the target is larger than the sequence, crop out a section of seq_L x seq_L: # start_i = 0 # Start at the top left for key in self.keys: # self.motif[key] = self.motif[key][start_i: start_i + self.seq_L, start_i : start_i + self.seq_L] if save_dir: plot_values = self.motif[key].copy() plot_values[plot_values == 0] = cfg.limits[key][1] np.fill_diagonal(plot_values, 0) plot_distogram( plot_values, save_dir / f"_{key}_target.jpg", clim=cfg.limits[key], ) # Get the bin_indices for each of the motif_targets: # TODO make this allow linear combinations of the two closest bins self.bin_indices = {} for key in self.keys: indices = np.abs(cfg.bin_dict_np[key][np.newaxis, np.newaxis, :] - self.motif[key][:, :, np.newaxis]).argmin(axis=-1) # Fix the no-contact locations: no_contact_locations = np.argwhere(self.motif[key] == 0) indices[no_contact_locations[:, 0], no_contact_locations[:, 1]] = 0 self.bin_indices[key] = (torch.from_numpy(indices).long().to( d()).unsqueeze(0))
def wd(g, show=False): """ Given a synchronous circuit :math:`G`, this algorithm computes :math:`W(u, v)` and :math:`D(u, v)` for all :math:`u,v \in V` such that :math:`u` is connected to :math:`v` in :math:`G`. +------------------+----------------+ | Time complexity | :math:`O(V^3)` | +------------------+----------------+ | Space complexity | :math:`O(V^2)` | +------------------+----------------+ :param g: A NetworkX (Multi)DiGraph representing a synchronous circuit. :param show: Print the matrices. :return: Matrices W and D in the form ``dict<(u,v), int>``. """ # STEP 1 # Weight each edge (u,?) in E with the ordered pair (w(e), -d(u)). g = g.copy() for e in g.edges: g.edges[e]['weight'] = MyTuple((w(g, e), -d(g, e[0]))) # STEP 2 # Using the weighting from Step 1, compute the weight of the shortest path joining each connected pair of vertices # by solving an all-pairs shortest-paths algorithm -- Floyd-Warshall. # In the all-pairs algorithm, add two weights by performing component-wise addition, and compare weights using # lexicographic ordering. sp = nx.floyd_warshall(g) # O(V^2) for u in sp: for v in sp[u]: if sp[u][v] == 0: sp[u][v] = MyTuple((0, 0)) # STEP 3 # For each shortest path weight (x, y) between two vertices u and v, set W(u, v) <- x and D(u, v) <- d(v) - y. W = {(u, v): sp[u][v][0] for u in g.nodes for v in g.nodes if sp[u][v] != np.inf} D = {(u, v): d(g, v) - sp[u][v][1] for u in g.nodes for v in g.nodes if sp[u][v] != np.inf} if show: print('Matrix W') print_wd(W) print('Matrix D') print_wd(D) return W, D
def play_round(self, round_number): d("Cheater player", self.player_id, "is playing, yay!") # Try to make schedule transaction with anyone that accepts it, to sell whatever they accepts # and try to set a impossible deadline (> the end of the game) # or just never pay them back #@TODO try: self.try_forever(round_number) # Test code for bad players # import time # while True: # time.sleep(10000) except Exception as ex: d("Gotcha! Now I am going to just hold this CPU!", ex) # import time # while True: # time.sleep(10000) self.play_round(round_number)
def agree_with_transaction(self, tr_data_dict): d("Cheater player asked about", tr_data_dict) if tr_data_dict['player_2'] == self.player_id: if '_deadline' in tr_data_dict['transaction_2to1']: d('Cheater player', self.player_id, "is accepting the transaction") else: d('Cheater player', self.player_id, "is refusing the transaction because delay_2to1 no in tr_data_dict",) return False return self.passwd else: d('Cheater player', self.player_id, "is refusing the transaction the receiving player is not myself:", tr_data_dict['player_2'], "myself=", self.player_id) return False
def normalised(self, val=None, as_float=False): """ Returns the specified value to fit the prescribed ranges and range rules """ if val is None: val = self.decimal_degree val = d(val) #Cast to Decimal range_high = d(self.range_high) range_low = d(self.range_low) if self.range_rotates: #Cycles through the range n_val = (val + range_high)%(range_high - range_low) + range_low else: #Oscillates between range extremes: range_range = range_high - range_low n_passes, residual = divmod((val - range_low),range_range) if n_passes % 2: #If odd, subtract residual off the high n_val = range_high - residual else: #If even, add it to the low n_val = range_low + residual return n_val
def closest_split_pair(Px, Py, pair_dist): best_pair = pair_dist[0], pair_dist[1] delta = pair_dist[2] xm = Px[len(Px) // 2][0] Sy = [x for x in Py if xm - delta <= x[0] <= xm + delta] best = delta for i, point1 in enumerate(Sy): for point2 in Sy[i + 1:i + 8]: current_dist = d(point1, point2) if current_dist < best: best_pair = point1, point2 best = current_dist return best_pair[0], best_pair[1], best
def __cmp__(self, other): """ Compares two dimension instances """ if isinstance(other, self.__class__): #Same thing as other = other.decimal_degree elif isinstance(other, BaseDimension): #This will start to make sense for derivative classes. If something is an Instance of BaseDimension but not of the same class, #Then you've passed in a another type of dimension and should convert it first! raise TypeError(u"{my_class} object calculation expected a {my_class}, but you gave a {other_class}. Please convert it to the same type of dimension first.".format( my_class=self.__class__.__name__, other_class=other.__class__.__name__) ) else: other = d(other) #Otherwise, try to cast it to a Decimal return cmp(self.decimal_degree, other.decimal_degree)
def test_random_wd(self): """ Check that the computed :math:`W` and :math:`D` matrices correspond to the definition. """ for _ in range(10): g = gen_random_circuit() W, D = wd(g) for u in g.nodes: for v in g.nodes: if nx.has_path(g, u, v): if u == v: self.assertEqual(W[u, v], 0) self.assertEqual(D[u, v], d(g, u)) else: self.assertEqual(W[u, v], min([w_path(g, p) for p in nx.all_simple_paths(g, u, v)])) self.assertEqual(D[u, v], max([d_path(g, p) for p in nx.all_simple_paths(g, u, v) if w_path(g, p) == W[u, v]])) else: self.assertFalse((u, v) in W) self.assertFalse((u, v) in D)
def cp(g, return_delta=False): """ Compute the clock period of a synchronous circuit. +------------------+------------------+ | Time complexity | :math:`O(E)` | +------------------+------------------+ | Space complexity | :math:`O(V + E)` | +------------------+------------------+ :param g: A NetworkX (Multi)DiGraph representing a synchronous circuit. :param return_delta: Whether to return the computed :math:`\Delta` or not (used in other algorithms). :return: The clock period of the given circuit. """ # STEP 1 # Let G0 be the sub-graph of G that contains precisely those edges e with register count w(e) = 0. zero_edges = list(filter(lambda e: w(g, e) == 0, g.edges)) g0 = nx.MultiDiGraph() g0.add_nodes_from(g.nodes(data=True)) g0.add_edges_from(zero_edges) delta = dict() # STEP 2 # By condition W2, G0 is acyclic. Perform a topological sort on G0, totally ordering its vertices so that if there # is an edge from vertex u to vertex v in G0, then u precedes v in the total order. Go though the vertices in the # order defined by the topological sort. for v in nx.topological_sort(g0): # O(V + E) # STEP 3 # On visiting each vertex v, compute the quantity delta(v) as follows: # a. If there is no incoming edge to v, set delta(v) <- d(v). # b. Otherwise, set delta(v) <- d(v) + max { delta(u) : u -e-> v and w(e) = 0 }. delta[v] = d(g0, v) if g0.in_degree(v) > 0: delta[v] += max(list(map(lambda e: delta[e[0]], g0.in_edges(v)))) # STEP 4 # The clock period is max { delta(v) }. if return_delta: return max(delta.values()), delta return max(delta.values())
def encode(self, src: torch.Tensor, src_mask: torch.Tensor) -> torch.Tensor: """ Function that encodes the source sequence. :param src: Our vectorized source sequence. [Batch_size x seq_len] :param src_mask: Mask to be passed to the SelfAttention Block when encoding the src sequence-> check SelfAttention. :returns: - Returns the source sequence embedded [Batch_size x seq_len x embedding_size] """ tokens = self.token_embedding(src) b, t, e = tokens.size() positions = self.pos_embedding(torch.arange(t, device=d()))[None, :, :].expand(b, t, e) embed = tokens + positions embed = self.do(embed) for block in self.encoding_blocks: embed = block(embed, src_mask) return embed
def make_transaction(self, **kwargs): """ Submits a transaction to the judging party. The judging party will go through standard checks to see if the calling player has the right to submit a transaction, then it will try to validate the transaction and potentially refuse it. For a complete description of what happens when a transaction is submitted to the judging party, please refer to the paper, located in the `paper/` directory. :param{AbstractPlayer} calling_player: The player that is calling the method (typically, `self`) :param{string} type: The type of transaction to be performed :param{dict} args: Arguments to be passed to the transaction """ try: d("make_transaction()") d("Banned players", self.banned_players) if self.current_pid in self.banned_players: return # Just return until it times out # The calling player has to be the current player, only the current player is allowed to submit transactions # during her own turn. When calling make_transaction the player has to pass itself as a parameter to prove who # she claims she is. In case this does not match the comparison with the current player, it means the calling # player is trying to submit transaction while it is not her turn and thus she is cheating, so we ban her. if kwargs['calling_player'] is not self.players[self.current_pid]: # bann_player takes the player id as a parameter but all we have is the player object reference itself # so we need to first retrieve its id, which is nothing else than the index in the players' list # @TODO stop using the index of the list as the id, move to a dict {id: player_reference} self.bann_player(self.players.index(kwargs['calling_player'])) raise PlayerBannedException("Attempted to submit a transaction while it was not her turn.") if self.current_player_transaction_attempts >= ALLOWED_TRANSACTIONS_ATTEMPTS_PER_ROUND \ or self.current_player_transactions >= ALLOWED_TRANSACTIONS_PER_ROUND: self.bann_player(self.current_pid) raise PlayerBannedException("Attempted too many transactions.") self.current_player_transaction_attempts += 1 d("Current player already attempted", self.current_player_transaction_attempts, "during current turn.") try: type_str = kwargs['type'] args = kwargs['args'] except KeyError as ex: d(ex) return False d("make_transaction() with:", str(type_str), str('args')) try: transaction = self.transaction_types[type_str](*args) except Exception as e: d(e) return False d("Instantiated transaction", transaction) if not isinstance(transaction, AbstractTransaction): d("Not an instance of AbstractTransaction") return False else: d("Is a rightful instance") if not self._check_player_agreements(transaction): d("A player refused the transaction") return False d("Was agreed by all players") d("Validating transaction...") valid_transaction = transaction.is_valid(self) d("Transaction validation ended.") if valid_transaction is True: # Note that there will not be any concurrent modification between the check of the transaction and d("WATWATWAT") l("WATWATWAT") l("Transaction is valid, applying it") transaction.apply(self) self.current_player_transactions += 1 d("Current player has already done", self.current_player_transactions, "in its current turn.") # Transaction is applied, tick the clock self.clock.tick() return True d("WUTWUTWUT") l("WUTWUTWUT") # The transaction was not valid d("Transaction is invalid") return False except Exception as e: # If anything failed, the transaction should not be accepted d("Something went wrong:", e) d("As a consequence, we refuse the transaction.") return False
import json import requests import matplotlib.pyplot as plt from utils import deObfuscate as d with open('config.json', 'r') as f: config = json.load(f) verbose = True APIKEY = d(config["APIKEY"]) contract = "0xf08253ebb55c5da33d637ad201a00760776f1d3b" startBlock = 5188000 txEndpoint = f"https://api.bscscan.com/api?module=account&action=txlist&address={contract}&startblock={startBlock}%20&endblock=99999999&sort=asc&apikey={APIKEY}" def getResults(txEndpoint): response = requests.get(txEndpoint) response = json.loads(response.text) return response["result"] def getDistances(): results = getResults(txEndpoint) dist = 0 prior = results[0]["blockNumber"] distances = [] for x in (results[1:]): dist = int(x["blockNumber"]) - int(prior) prior = x["blockNumber"] distances += [(x["blockNumber"], dist)]
# -*- mode: python; coding: utf-8 -*- __author__ = "Alvaro Lopez Ortega" __email__ = "*****@*****.**" __license__ = "MIT" import gitlog import projects from utils import date_to_unix as d releases = [ {"name": "Austin", "period": (d(2010,1), d(2010,10)), "projects": ['openstack']}, {"name": "Bexar", "period": (d(2010,10), d(2011,2)), "projects": ['openstack']}, {"name": "Cactus", "period": (d(2011,2), d(2011,4)), "projects": ['openstack']}, {"name": "Diablo", "period": (d(2011,4), d(2012,1)), "projects": ['openstack']}, {"name": "Essex", "period": (d(2012,1), d(2012,4)), "projects": ['openstack']}, {"name": "Folsom", "period": (d(2012,4), d(2012,9)), "projects": ['openstack']}, {"name": "Grizzly", "period": (d(2012,9), d(2013,3)), "projects": ['openstack']}, ] def get_all_releases_dicts (): # Add a 'global' release rel = releases[:] rel += [{"name": "Global", "period": (rel[0]['period'][0], rel[-1]['period'][1]), "projects": ["openstack"]}] # Figure out project on each release for project in projects.get_project_list():
import json import requests import time import os import subprocess from utils import deObfuscate as d with open('config.json', 'r') as f: config = json.load(f) # VARIABLE # TYPE (DEFAULT) : <DESCRIPTION>. MYADDRESS = d(config["MYADDRESS"] ) # STR (None) : Base64 encoded Public eth/bsc address. APIKEY = d( config["APIKEY"]) # STR (None) : Base64 encoded bscScan.com API key.
def play_round(self): d("Players ids:", self.players_ids) for pid in self.players_ids: d("=" * 30, "Changing player") # This is a quick and dirty fix, @TODO d("Banned players", self.banned_players) if pid in self.banned_players: d("Player", pid, "has been banned, passing this turn.") continue d("Current player id:", pid) self.current_player_transaction_attempts = 0 self.current_player_transactions = 0 p = self.players[pid] t = None self.current_pid = pid try: t = time() import threading self.current_player_thread = threading.Thread( target=player_thread, args=(p, self.clock.current_turn_number()) ) self.current_player_thread.start() self.current_player_thread.join(PLAYER_TIMEOUT) if self.current_player_thread.is_alive(): l("#"*100) l("Player", self.current_pid, "timed out! After", time() - t) l("#"*100) self.bann_player(pid) except PlayerBannedException: # This is a quick and dirty fix, @TODO self.bann_player(pid) except SystemExit as ex: l("Player", self.current_pid, "timed out (exception)! After", time() - t) self.bann_player(pid) d(ex) return False # @TODO # This displays the state of the game l(self.game) self.clock.tick() if self.clock.is_over(): l("Game Over") return False return True
def set_minute(self, minute): self.minute = d(minute)
def set_second(self, second): self.second = d(second)
def _calc_decimaldegree(degree, minute, second): ''' Calculate decimal degree form degree, minute, second ''' return d(degree) + d(minute)/d("60.0") + d(second)/d("3600.0")
def set_degree(self, degree): self.degree = d(degree)
def to_tensor(value): """Return a pytorch tensor from a python list.""" return torch.from_numpy(np.asarray(value)).float().to(d())
def agree_with_transaction(self, tr_data_dict): d('DummyPlayer', self.player_id, "accepts transaction", tr_data_dict['_id']) return self.passwd