code
stringlengths
1
18.2k
a fasta record instead break
def fq_minimal(fq): """Minimal fastq metrics extractor. Quickly parse a fasta/fastq file - but makes expectations on the file format There will be dragons if unexpected format is used Expects a fastq_rich format, but extracts only timestamp and length """ try: while True: time = next(fq)[1:].split(" ")[4][11:-1] length...
def process_fastq_minimal(fastq, **kwargs): """Swiftly extract minimal features (length and timestamp) from a rich fastq file""" infastq = handle_compressed_input(fastq) try: df = pd.DataFrame( data=[rec for rec in fq_minimal(infastq) if rec], columns=["timestamp", "lengths"] ) except IndexError: logging.error("Fatal: ...
def _get_piece(string, index): """ Returns Piece subclass given index of piece. :type: index: int :type: loc Location :raise: KeyError """ piece = string[index].strip() piece = piece.upper() piece_dict = {'R': Rook, 'P': Pawn, 'B': Bishop, 'N': Knight, 'Q': Queen, 'K': King} try: return piece_dict[piece] except KeyErro...
def incomplete_alg(alg_str, input_color, position): """ Converts a string written in short algebraic form into an incomplete move. These incomplete moves do not have the initial location specified and therefore cannot be used to update the board. IN order to fully utilize incomplete move, it must be run through ``make_...
it returns a complete move. Examples: e4, Nf3, exd5, Qxf3, 00, 000, e8=Q :type: alg_str: str :type: input_color: Color """ edge_rank = 0 \ if input_color == color.white \ else 7 if alg_str is None or len(alg_str) <= 1: raise ValueError("algebraic string {} is invalid".format(alg_str)) # King-side castle if alg_str in [...
start_loc=Location(edge_rank, 4)) # Queen-side castle if alg_str in ["000", "ooo", "OOO", "0-0-0", "o-o-o", "O-O-O"]: return Move(end_loc=Location(edge_rank, 2), piece=King(input_color, Location(edge_rank, 4)), status=notation_const.QUEEN_SIDE_CASTLE, start_loc=Location(edge_rank, 4)) try: end_location = Location.from_...
# Non-pawn Piece movement if len(alg_str) == 3: possible_piece, start_location = _get_piece_start_location(end_location, input_color, _get_piece(alg_str, 0), position) return Move(end_loc=end_location, piece=possible_piece, status=notation_const.MOVEMENT, start_loc=start_location) # Multiple options (Capture or Piece m...
input_color: en_passant_pawn = position.piece_at_square(end_location.shift_back(input_color)) if type(en_passant_pawn) is Pawn and \ en_passant_pawn.color != input_color and \ position.is_square_empty(end_location): return Move(end_loc=end_location, piece=position.piece_at_square(pawn_location), status=notation_const.E...
ValueError("Promotion {} must be on the last rank".format(alg_str)) return Move(end_loc=promote_end_loc, piece=Pawn(input_color, promote_end_loc), status=notation_const.PROMOTE, promoted_to_piece=_get_piece(alg_str, 3), start_loc=promote_end_loc.shift_back(input_color)) # Non-pawn Piece movement with file specified (aR...
position, start_file=alg_str[1]) return Move(end_loc=end_location, piece=possible_piece, status=notation_const.MOVEMENT, start_loc=start_location) # Non-pawn Piece movement with rank specified (R1b7) elif alg_str[0].isupper() and alg_str[1].isdigit(): possible_piece, start_location = _get_piece_start_location(end_locat...
\ alg_str[4].isdigit: start_loc = Location.from_string(alg_str[:2]) return Move(end_loc=end_location, piece=_get_piece(alg_str, 2)(input_color, end_location), status=notation_const.MOVEMENT, start_loc=start_loc) # Multiple Piece capture options if alg_str[2].upper() == "X": # Piece capture with rank specified (R1xa1) i...
status=notation_const.CAPTURE, start_loc=start_location) # Pawn promotion with capture if len(alg_str) == 6 and alg_str[4] == "=": start_file = ord(alg_str[0]) - 97 promote_capture_end_loc = Location.from_string(alg_str[2:4]) return Move(end_loc=promote_capture_end_loc, piece=Pawn(input_color, promote_capture_end_loc),...
def make_legal(move, position): """ Converts an incomplete move (initial ``Location`` not specified) and the corresponding position into the a complete move with the most likely starting point specified. If no moves match, ``None`` is returned. :type: move: Move :type: position: Board :rtype: Move """ assert isinstance...
return legal_move elif move == legal_move: return legal_move raise ValueError("Move {} not legal in \n{}".format(repr(move), position))
def short_alg(algebraic_string, input_color, position): """ Converts a string written in short algebraic form, the color of the side whose turn it is, and the corresponding position into a complete move that can be played. If no moves match, None is returned. Examples: e4, Nf3, exd5, Qxf3, 00, 000, e8=Q :type: algebrai...
def long_alg(alg_str, position): """ Converts a string written in long algebraic form and the corresponding position into a complete move (initial location specified). Used primarily for UCI, but can be used for other purposes. :type: alg_str: str :type: position: Board :rtype: Move """ if alg_str is None or len(alg_st...
= Location.from_string(alg_str[:2]) piece = position.piece_at_square(start) if len(alg_str) == 4: return make_legal(Move(end_loc=end, piece=piece, status=notation_const.LONG_ALG, start_loc=start), position) promoted_to = _get_piece(alg_str, 4) if promoted_to is None or \ promoted_to is King or \ promoted_to is Pawn: ra...
def reset_query_marks(self): """ set or reset hyb and neighbors marks to atoms. """ for i, atom in self.atoms(): neighbors = 0 hybridization = 1 # hybridization 1- sp3; 2- sp2; 3- sp1; 4- aromatic for j, bond in self._adj[i].items(): if self._node[j].element != 'H': neighbors += 1 if hybridization in (3, 4): continue o...
== 3: hybridization = 3 elif order == 2: if hybridization == 2: hybridization = 3 else: hybridization = 2 atom._neighbors = neighbors atom._hybridization = hybridization self.flush_cache()
def implicify_hydrogens(self): """ remove explicit hydrogen if possible :return: number of removed hydrogens """ explicit = defaultdict(list) c = 0 for n, atom in self.atoms(): if atom.element == 'H': for m in self.neighbors(n): if self._node[m].element != 'H': explicit[m].append(n) for n, h in explicit.items(): atom =...
self._adj[n].items() if x not in hi]) == i: for x in hi: self.remove_node(x) c += 1 break self.flush_cache() return c
def explicify_hydrogens(self): """ add explicit hydrogens to atoms :return: number of added atoms """ tmp = [] for n, atom in self.atoms(): if atom.element != 'H': for _ in range(atom.get_implicit_h([x.order for x in self._adj[n].values()])): tmp.append(n) for n in tmp: self.add_bond(n, self.add_atom(H), Bond()) self.f...
def substructure(self, atoms, meta=False, as_view=True): """ create substructure containing atoms from nbunch list :param atoms: list of atoms numbers of substructure :param meta: if True metadata will be copied to substructure :param as_view: If True, the returned graph-view provides a read-only view of the original s...
s.implicify_hydrogens = s.reset_query_marks = frozen s.standardize = s.aromatize = frozen return s
def check_valence(self): """ check valences of all atoms :return: list of invalid atoms """ return [x for x, atom in self.atoms() if not atom.check_valence(self.environment(x))]
def _matcher(self, other): """ return VF2 GraphMatcher MoleculeContainer < MoleculeContainer MoleculeContainer < CGRContainer """ if isinstance(other, (self._get_subclass('CGRContainer'), MoleculeContainer)): return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y) raise TypeError('only cgr-cgr possib...
def to_datetime(date): """Turn a date into a datetime at midnight. """ return datetime.datetime.combine(date, datetime.datetime.min.time())
def iter_size_changes(self, issue): """Yield an IssueSnapshot for each time the issue size changed """ # Find the first size change, if any try: size_changes = list(filter(lambda h: h.field == 'Story Points', itertools.chain.from_iterable([c.items for c in issue.changelog.histories]))) except AttributeError: return # I...
# Return the size at creation time try: current_size = issue.fields.__dict__[self.fields['StoryPoints']] except: current_size = None size = (size_changes[0].fromString) if len(size_changes) else current_size # Issue was created yield IssueSizeSnapshot( change=None, key=issue.key, date=dateutil.parser.parse(issue.fields...
change.items: if item.field == 'Story Points': # StoryPoints value was changed size = item.toString yield IssueSizeSnapshot( change=item.field, key=issue.key, date=change_date, size=size )
def iter_changes(self, issue, include_resolution_changes=True): """Yield an IssueSnapshot for each time the issue changed status or resolution """ is_resolved = False # Find the first status change, if any try: status_changes = list(filter( lambda h: h.field == 'status', itertools.chain.from_iterable([c.items for c in ...
key=issue.key, date=dateutil.parser.parse(issue.fields.created), status=last_status, resolution=None, is_resolved=is_resolved ) for change in issue.changelog.histories: change_date = dateutil.parser.parse(change.created) resolutions = list(filter(lambda i: i.field == 'resolution', change.items)) is_resolved = (resoluti...
if include_resolution_changes: yield IssueSnapshot( change=item.field, key=issue.key, date=change_date, status=last_status, resolution=last_resolution, is_resolved=is_resolved )
def find_issues(self, criteria={}, jql=None, order='KEY ASC', verbose=False, changelog=True): """Return a list of issues with changelog metadata. Searches for the `issue_types`, `project`, `valid_resolutions` and 'jql_filter' set in the passed-in `criteria` object. Pass a JQL string to further qualify the query results...
(%s)' % ', '.join(['"%s"' % t for t in criteria['issue_types']])) if criteria.get('valid_resolutions', False): query.append('(resolution IS EMPTY OR resolution IN (%s))' % ', '.join(['"%s"' % r for r in criteria['valid_resolutions']])) if criteria.get('jql_filter') is not None: query.append('(%s)' % criteria['jql_filte...
issues = [] while True: try: if changelog: pageofissues = self.jira.search_issues(queryString, expand='changelog', maxResults=self.settings['max_results'],startAt=fromRow) else: pageofissues = self.jira.search_issues(queryString, maxResults=self.settings['max_results'],startAt=fromRow) fromRow = fromRow + int(self.sett...
"issues") return issues
def list_catalogs(self): """ Lists existing catalogs respect to ui view template format """ _form = CatalogSelectForm(current=self.current) _form.set_choices_of('catalog', [(i, i) for i in fixture_bucket.get_keys()]) self.form_out(_form)
def get_catalog(self): """ Get existing catalog and fill the form with the model data. If given key not found as catalog, it generates an empty catalog data form. """ catalog_data = fixture_bucket.get(self.input['form']['catalog']) # define add or edit based on catalog data exists add_or_edit = "Edit" if catalog_data.e...
data to form if catalog_data.exists: if type(catalog_data.data) == list: # if catalog data is an array it means no other language of value defined, therefor the value is turkish for key, data in enumerate(catalog_data.data): catalog_edit_form.CatalogDatas(catalog_key=key or "0", en='', tr=data) if type(catalog_data.dat...
will be saved, used in save_catalog form self.output["object_key"] = self.input['form']['catalog']
def save_catalog(self): """ Saves the catalog data to given key Cancels if the cmd is cancel Notifies user with the process. """ if self.input["cmd"] == 'save_catalog': try: edited_object = dict() for i in self.input["form"]["CatalogDatas"]: edited_object[i["catalog_key"]] = {"en": i["en"], "tr": i["tr"]} newobj = fixt...
"object_key"] except: raise HTTPError(500, "Form object could not be saved") if self.input["cmd"] == 'cancel': self.output["notify"] = "catalog: %s canceled." % self.input["object_key"]
def date_to_solr(d): """ converts DD-MM-YYYY to YYYY-MM-DDT00:00:00Z""" return "{y}-{m}-{day}T00:00:00Z".format(day=d[:2], m=d[3:5], y=d[6:]) if d else d
def solr_to_date(d): """ converts YYYY-MM-DDT00:00:00Z to DD-MM-YYYY """ return "{day}:{m}:{y}".format(y=d[:4], m=d[5:7], day=d[8:10]) if d else d
def to_safe_str(s): """ converts some (tr) non-ascii chars to ascii counterparts, then return the result as lowercase """ # TODO: This is insufficient as it doesn't do anything for other non-ascii chars return re.sub(r'[^0-9a-zA-Z]+', '_', s.strip().replace(u'ğ', 'g').replace(u'ö', 'o').replace( u'ç', 'c').replace(u'Ç'...
def merge_truthy(*dicts): """Merge multiple dictionaries, keeping the truthy values in case of key collisions. Accepts any number of dictionaries, or any other object that returns a 2-tuple of key and value pairs when its `.items()` method is called. If a key exists in multiple dictionaries passed to this function, the...
does not evaluate to True, then the value of the previous dictionary is kept. >>> merge_truthy({'a': 1, 'c': 4}, {'a': None, 'b': 2}, {'b': 3}) {'a': 1, 'b': 3, 'c': 4} """ merged = {} for d in dicts: for k, v in d.items(): merged[k] = v or merged.get(k, v) return merged
def perform(self): """Perform the version upgrade on the database. """ db_versions = self.table.versions() version = self.version if (version.is_processed(db_versions) and not self.config.force_version == self.version.number): self.log( u'version {} is already installed'.format(version.number) ) return self.start() try...
def _perform_version(self, version): """Inner method for version upgrade. Not intended for standalone use. This method performs the actual version upgrade with all the pre, post operations and addons upgrades. :param version: The migration version to upgrade to :type version: Instance of Version class """ if version.is...
pre-operations' % self.config.mode) for operation in version.pre_operations(mode=self.config.mode): operation.execute(self.log) self.perform_addons() self.log(u'execute base post-operations') for operation in version.post_operations(): operation.execute(self.log) if self.config.mode: self.log(u'execute %s post-operatio...
def logout(current): """ Log out view. Simply deletes the session object. For showing logout message: 'show_logout_message' field should be True in current.task_data, Message should be sent in current.task_data with 'logout_message' field. Message title should be sent in current.task_data with 'logout_title' field. cur...
current.output['title'] = current.task_data.get('logout_title', None) current.output['msg'] = current.task_data.get('logout_message', None)
def _do_upgrade(self): """ open websocket connection """ self.current.output['cmd'] = 'upgrade' self.current.output['user_id'] = self.current.user_id self.terminate_existing_login() self.current.user.bind_private_channel(self.current.session.sess_id) user_sess = UserSessionID(self.current.user_id) user_sess.set(self.cu...
def do_view(self): """ Authenticate user with given credentials. Connects user's queue and exchange """ self.current.output['login_process'] = True self.current.task_data['login_successful'] = False if self.current.is_auth: self._do_upgrade() else: try: auth_result = self.current.auth.authenticate( self.current.input['...
def show_view(self): """ Show :attr:`LoginForm` form. """ self.current.output['login_process'] = True if self.current.is_auth: self._do_upgrade() else: self.current.output['forms'] = LoginForm(current=self.current).serialize()
def skip(mapping): """ :param mapping: generator :return: filtered generator """ found = set() for m in mapping: matched_atoms = set(m.values()) if found.intersection(matched_atoms): continue found.update(matched_atoms) yield m
def __get_mapping(self, structures): """ match each pattern to each molecule. if all patterns matches with all molecules return generator of all possible mapping. :param structures: disjoint molecules :return: mapping generator """ for c in permutations(structures, len(self.__patterns)): for m in product(*(x.get_substr...
def get(self, default=None): """ return the cached value or default if it can't be found :param default: default value :return: cached value """ d = cache.get(self.key) return ((json.loads(d.decode('utf-8')) if self.serialize else d) if d is not None else default)
def set(self, val, lifetime=None): """ set cache value :param val: any picklable object :param lifetime: exprition time in sec :return: val """ cache.set(self.key, (json.dumps(val) if self.serialize else val), lifetime or settings.DEFAULT_CACHE_EXPIRE_TIME) return val
def add(self, val): """ Add given value to item (list) Args: val: A JSON serializable object. Returns: Cache backend response. """ return cache.lpush(self.key, json.dumps(val) if self.serialize else val)
def get_all(self): """ Get all list items. Returns: Cache backend response. """ result = cache.lrange(self.key, 0, -1) return (json.loads(item.decode('utf-8')) for item in result if item) if self.serialize else result
def remove_item(self, val): """ Removes given item from the list. Args: val: Item Returns: Cache backend response. """ return cache.lrem(self.key, json.dumps(val))
def flush(cls, *args): """ Removes all keys of this namespace Without args, clears all keys starting with cls.PREFIX if called with args, clears keys starting with given cls.PREFIX + args Args: *args: Arbitrary number of arguments. Returns: List of removed keys. """ return _remove_keys([], [(cls._make_key(args) if args...
def update_or_expire_session(self): """ Deletes session if keepalive request expired otherwise updates the keepalive timestamp value """ if not hasattr(self, 'key'): return now = time.time() timestamp = float(self.get() or 0) or now sess_id = self.sess_id or UserSessionID(self.user_id).get() if sess_id and now - timest...
def send_message_for_lane_change(sender, **kwargs): """ Sends a message to possible owners of the current workflows next lane. Args: **kwargs: ``current`` and ``possible_owners`` are required. sender (User): User object """ current = kwargs['current'] owners = kwargs['possible_owners'] if 'lane_change_invite' in curren...
= datetime.today() for recipient in owners: inv = TaskInvitation( instance=wfi, role=recipient, wf_name=wfi.wf.name, progress=30, start_date=today, finish_date=today + timedelta(15) ) inv.title = current.task_data.get('INVITATION_TITLE') or wfi.wf.title inv.save() # try to send notification, if it fails go on try: reci...
def set_password(sender, **kwargs): """ Encrypts password of the user. """ if sender.model_class.__name__ == 'User': usr = kwargs['object'] if not usr.password.startswith('$pbkdf2'): usr.set_password(usr.password) usr.save()
def channel_list(self): """ Main screen for channel management. Channels listed and operations can be chosen on the screen. If there is an error message like non-choice, it is shown here. """ if self.current.task_data.get('msg', False): if self.current.task_data.get('target_channel_key', False): self.current.output['ms...
= channel.owner.username _form.ChannelList(choice=False, name=channel.name, owner=owner_name, key=channel.key) _form.new_channel = fields.Button(_(u"Merge At New Channel"), cmd="create_new_channel") _form.existing_channel = fields.Button(_(u"Merge With An Existing Channel"), cmd="choose_existing_channel") _form.find_ch...
def channel_choice_control(self): """ It controls errors. If there is an error, returns channel list screen with error message. """ self.current.task_data['control'], self.current.task_data['msg'] \ = self.selection_error_control(self.input['form']) if self.current.task_data['control']: self.current.task_data['option']...
def create_new_channel(self): """ Features of new channel are specified like channel's name, owner etc. """ self.current.task_data['new_channel'] = True _form = NewChannelForm(Channel(), current=self.current) _form.title = _(u"Specify Features of New Channel to Create") _form.forward = fields.Button(_(u"Create"), flow=...
def save_new_channel(self): """ It saves new channel according to specified channel features. """ form_info = self.input['form'] channel = Channel(typ=15, name=form_info['name'], description=form_info['description'], owner_id=form_info['owner_id']) channel.blocking_save() self.current.task_data['target_channel_key'] = ...
def choose_existing_channel(self): """ It is a channel choice list and chosen channels at previous step shouldn't be on the screen. """ if self.current.task_data.get('msg', False): self.show_warning_messages() _form = ChannelListForm() _form.title = _(u"Choose a Channel Which Will Be Merged With Chosen Channels") for c...
def existing_choice_control(self): """ It controls errors. It generates an error message if zero or more than one channels are selected. """ self.current.task_data['existing'] = False self.current.task_data['msg'] = _(u"You should choose just one channel to do operation.") keys, names = self.return_selected_form_items(...
def split_channel(self): """ A channel can be splitted to new channel or other existing channel. It creates subscribers list as selectable to moved. """ if self.current.task_data.get('msg', False): self.show_warning_messages() self.current.task_data['split_operation'] = True channel = Channel.objects.get(self.current.t...
Channel"), cmd="choose_existing_channel") self.form_out(_form)
def subscriber_choice_control(self): """ It controls subscribers choice and generates error message if there is a non-choice. """ self.current.task_data['option'] = None self.current.task_data['chosen_subscribers'], names = self.return_selected_form_items( self.input['form']['SubscriberList']) self.current.task_data[ '...
def move_complete_channel(self): """ Channels and theirs subscribers are moved completely to new channel or existing channel. """ to_channel = Channel.objects.get(self.current.task_data['target_channel_key']) chosen_channels = self.current.task_data['chosen_channels'] chosen_channels_names = self.current.task_data['cho...
def move_chosen_subscribers(self): """ After splitting operation, only chosen subscribers are moved to new channel or existing channel. """ from_channel = Channel.objects.get(self.current.task_data['chosen_channels'][0]) to_channel = Channel.objects.get(self.current.task_data['target_channel_key']) with BlockSave(Subsc...
def copy_and_move_messages(from_channel, to_channel): """ While splitting channel and moving chosen subscribers to new channel, old channel's messages are copied and moved to new channel. Args: from_channel (Channel object): move messages from channel to_channel (Channel object): move messages to channel """ with Block...
def show_warning_messages(self, title=_(u"Incorrect Operation"), box_type='warning'): """ It shows incorrect operations or successful operation messages. Args: title (string): title of message box box_type (string): type of message box (warning, info) """ msg = self.current.task_data['msg'] self.current.output['msgbox'...
def return_selected_form_items(form_info): """ It returns chosen keys list from a given form. Args: form_info: serialized list of dict form data Returns: selected_keys(list): Chosen keys list selected_names(list): Chosen channels' or subscribers' names. """ selected_keys = [] selected_names = [] for chosen in form_info...
def selection_error_control(self, form_info): """ It controls the selection from the form according to the operations, and returns an error message if it does not comply with the rules. Args: form_info: Channel or subscriber form from the user Returns: True or False error message """ keys, names = self.return_selected_...
least two channel to merge operation at a new channel.") elif form_info['existing_channel'] and chosen_channels_number == 0: return False, _( u"You should choose at least one channel to merge operation with existing channel.") elif form_info['find_chosen_channel'] and chosen_channels_number != 1: return False, _(u"You ...
def _eratosthenes(): """Yields the sequence of prime numbers via the Sieve of Eratosthenes.""" d = {} # map each composite integer to its first-found prime factor for q in count(2): # q gets 2, 3, 4, 5, ... ad infinitum p = d.pop(q, None) if p is None: # q not a key in D, so q is prime, therefore, yield it yield q
# mark q squared as not-prime (with q as first-found prime factor) d[q * q] = q else: # let x <- smallest (N*p)+q which wasn't yet known to be composite # we just learned x is composite, with p first-found prime factor, # since p is the first-found prime factor of q -- find and mark it x = p + q while
x in d: x += p d[x] = p
def atoms_order(self): """ Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs """ if not len(self): # for empty containers return {} elif len(self) == 1: # optimize single atom containers return dict.fromkeys(self, 2) params = {n: (int(node), tuple(sorted(int(edge) for edge in self._adj[n...
for x, y in sorted(params.items(), key=itemgetter(1))} tries = len(self) * 4 numb = len(set(weights.values())) stab = 0 while tries: oldnumb = numb neweights = {} countprime = iter(primes) # weights[n] ** 2 NEED for differentiation of molecules like A-B or any other complete graphs. tmp = {n: reduce(mul, (weights[x] fo...
(neweights.get(y) or neweights.setdefault(y, next(countprime))) for x, y in sorted(tmp.items(), key=itemgetter(1))} numb = len(set(weights.values())) if numb == len(self): # each atom now unique break elif numb == oldnumb: x = Counter(weights.values()) if x[min(x)] > 1: if stab == 3: break elif stab >= 2: break stab +=...
of attempts exceeded. uniqueness has decreased. next attempt will be made') tries = 1 else: warning('morgan. number of attempts exceeded') return weights
def init_manual(cls, pawn_value, knight_value, bishop_value, rook_value, queen_value, king_value): """ Manual init method for external piece values :type: PAWN_VALUE: int :type: KNIGHT_VALUE: int :type: BISHOP_VALUE: int :type: ROOK_VALUE: int :type: QUEEN_VALUE: int """ piece_values = cls() piece_values.PAWN_VALUE = p...
def val(self, piece, ref_color): """ Finds value of ``Piece`` :type: piece: Piece :type: ref_color: Color :rtype: int """ if piece is None: return 0 if ref_color == piece.color: const = 1 else: const = -1 if isinstance(piece, Pawn): return self.PAWN_VALUE * const elif isinstance(piece, Queen): return self.QUEEN_VALUE *...
isinstance(piece, Knight): return self.KNIGHT_VALUE * const elif isinstance(piece, King): return self.KING_VALUE * const return 0
def play(self): """ Starts game and returns one of 3 results . Iterates between methods ``white_move()`` and ``black_move()`` until game ends. Each method calls the respective player's ``generate_move()`` method. :rtype: int """ colors = [lambda: self.white_move(), lambda: self.black_move()] colors = itertools.cycle(co...
def white_move(self): """ Calls the white player's ``generate_move()`` method and updates the board with the move returned. """ move = self.player_white.generate_move(self.position) move = make_legal(move, self.position) self.position.update(move)
def black_move(self): """ Calls the black player's ``generate_move()`` method and updates the board with the move returned. """ move = self.player_black.generate_move(self.position) move = make_legal(move, self.position) self.position.update(move)
def get_field_cache(self, cache_type='es'): """Return a list of fields' mappings""" if cache_type == 'kibana': try: search_results = urlopen(self.get_url).read().decode('utf-8') except HTTPError: # as e: # self.pr_err("get_field_cache(kibana), HTTPError: %s" % e) return [] index_pattern = json.loads(search_results) # R...