sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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()])): ...
add explicit hydrogens to atoms :return: number of added atoms
entailment
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 pr...
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 structure scaffold withou...
entailment
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))]
check valences of all atoms :return: list of invalid atoms
entailment
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 ==...
return VF2 GraphMatcher MoleculeContainer < MoleculeContainer MoleculeContainer < CGRContainer
entailment
def to_datetime(date): """Turn a date into a datetime at midnight. """ return datetime.datetime.combine(date, datetime.datetime.min.time())
Turn a date into a datetime at midnight.
entailment
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_iterab...
Yield an IssueSnapshot for each time the issue size changed
entailment
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( l...
Yield an IssueSnapshot for each time the issue changed status or resolution
entailment
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...
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.
entailment
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)
Lists existing catalogs respect to ui view template format
entailment
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 ...
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.
entailment
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"]["Ca...
Saves the catalog data to given key Cancels if the cmd is cancel Notifies user with the process.
entailment
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
converts DD-MM-YYYY to YYYY-MM-DDT00:00:00Z
entailment
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
converts YYYY-MM-DDT00:00:00Z to DD-MM-YYYY
entailment
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(...
converts some (tr) non-ascii chars to ascii counterparts, then return the result as lowercase
entailment
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 ...
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 values from th...
entailment
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( ...
Perform the version upgrade on the database.
entailment
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: I...
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
entailment
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....
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' fie...
entailment
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 = UserSessi...
open websocket connection
entailment
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() e...
Authenticate user with given credentials. Connects user's queue and exchange
entailment
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()
Show :attr:`LoginForm` form.
entailment
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
:param mapping: generator :return: filtered generator
entailment
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(s...
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
entailment
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 N...
return the cached value or default if it can't be found :param default: default value :return: cached value
entailment
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 setti...
set cache value :param val: any picklable object :param lifetime: exprition time in sec :return: val
entailment
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)
Add given value to item (list) Args: val: A JSON serializable object. Returns: Cache backend response.
entailment
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
Get all list items. Returns: Cache backend response.
entailment
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))
Removes given item from the list. Args: val: Item Returns: Cache backend response.
entailment
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 ...
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.
entailment
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 = s...
Deletes session if keepalive request expired otherwise updates the keepalive timestamp value
entailment
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['possi...
Sends a message to possible owners of the current workflows next lane. Args: **kwargs: ``current`` and ``possible_owners`` are required. sender (User): User object
entailment
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()
Encrypts password of the user.
entailment
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.curre...
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.
entailment
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.cu...
It controls errors. If there is an error, returns channel list screen with error message.
entailment
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") ...
Features of new channel are specified like channel's name, owner etc.
entailment
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=f...
It saves new channel according to specified channel features.
entailment
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 = ...
It is a channel choice list and chosen channels at previous step shouldn't be on the screen.
entailment
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."...
It controls errors. It generates an error message if zero or more than one channels are selected.
entailment
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_o...
A channel can be splitted to new channel or other existing channel. It creates subscribers list as selectable to moved.
entailment
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( sel...
It controls subscribers choice and generates error message if there is a non-choice.
entailment
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'] ...
Channels and theirs subscribers are moved completely to new channel or existing channel.
entailment
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_...
After splitting operation, only chosen subscribers are moved to new channel or existing channel.
entailment
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_chann...
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
entailment
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) """ ...
It shows incorrect operations or successful operation messages. Args: title (string): title of message box box_type (string): type of message box (warning, info)
entailment
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' name...
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.
entailment
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 ...
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
entailment
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 ...
Yields the sequence of prime numbers via the Sieve of Eratosthenes.
entailment
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,...
Morgan like algorithm for graph nodes ordering :return: dict of atom-weight pairs
entailment
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:...
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
entailment
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 ...
Finds value of ``Piece`` :type: piece: Piece :type: ref_color: Color :rtype: int
entailment
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:...
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
entailment
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)
Calls the white player's ``generate_move()`` method and updates the board with the move returned.
entailment
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)
Calls the black player's ``generate_move()`` method and updates the board with the move returned.
entailment
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), HTT...
Return a list of fields' mappings
entailment
def post_field_cache(self, field_cache): """Where field_cache is a list of fields' mappings""" index_pattern = self.field_cache_to_index_pattern(field_cache) # self.pr_dbg("request/post: %s" % index_pattern) resp = requests.post(self.post_url, data=index_pattern).text # resp = {"...
Where field_cache is a list of fields' mappings
entailment
def field_cache_to_index_pattern(self, field_cache): """Return a .kibana index-pattern doc_type""" mapping_dict = {} mapping_dict['customFormats'] = "{}" mapping_dict['title'] = self.index_pattern # now post the data into .kibana mapping_dict['fields'] = json.dumps(field_...
Return a .kibana index-pattern doc_type
entailment
def check_mapping(self, m): """Assert minimum set of fields in cache, does not validate contents""" if 'name' not in m: self.pr_dbg("Missing %s" % "name") return False # self.pr_dbg("Checking %s" % m['name']) for x in ['analyzed', 'indexed', 'type', 'scripted', 'c...
Assert minimum set of fields in cache, does not validate contents
entailment
def get_index_mappings(self, index): """Converts all index's doc_types to .kibana""" fields_arr = [] for (key, val) in iteritems(index): # self.pr_dbg("\tdoc_type: %s" % key) doc_mapping = self.get_doc_type_mappings(index[key]) # self.pr_dbg("\tdoc_mapping: %s...
Converts all index's doc_types to .kibana
entailment
def get_doc_type_mappings(self, doc_type): """Converts all doc_types' fields to .kibana""" doc_fields_arr = [] found_score = False for (key, val) in iteritems(doc_type): # self.pr_dbg("\t\tfield: %s" % key) # self.pr_dbg("\tval: %s" % val) add_it = Fal...
Converts all doc_types' fields to .kibana
entailment
def get_field_mappings(self, field): """Converts ES field mappings to .kibana field mappings""" retdict = {} retdict['indexed'] = False retdict['analyzed'] = False for (key, val) in iteritems(field): if key in self.mappings: if (key == 'type' and ...
Converts ES field mappings to .kibana field mappings
entailment
def is_kibana_cache_incomplete(self, es_cache, k_cache): """Test if k_cache is incomplete Assume k_cache is always correct, but could be missing new fields that es_cache has """ # convert list into dict, with each item's ['name'] as key k_dict = {} for field in k...
Test if k_cache is incomplete Assume k_cache is always correct, but could be missing new fields that es_cache has
entailment
def list_to_compare_dict(self, list_form): """Convert list into a data structure we can query easier""" compare_dict = {} for field in list_form: if field['name'] in compare_dict: self.pr_dbg("List has duplicate field %s:\n%s" % (field['nam...
Convert list into a data structure we can query easier
entailment
def compare_field_caches(self, replica, original): """Verify original is subset of replica""" if original is None: original = [] if replica is None: replica = [] self.pr_dbg("Comparing orig with %s fields to replica with %s fields" % (len(origi...
Verify original is subset of replica
entailment
def start_daemon_thread(target, args=()): """starts a deamon thread for a given target function and arguments.""" th = Thread(target=target, args=args) th.daemon = True th.start() return th
starts a deamon thread for a given target function and arguments.
entailment
def serialize_dict_keys(d, prefix=""): """returns all the keys in a dictionary. >>> serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } }) ['a', 'a.b', 'a.b.c', 'a.b.b'] """ keys = [] for k, v in d.iteritems(): fqk = '%s%s' % (prefix, k) keys.append(fqk) if isinstance(v, ...
returns all the keys in a dictionary. >>> serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } }) ['a', 'a.b', 'a.b.c', 'a.b.b']
entailment
def set_user(self, user): """ Writes user data to session. Args: user: User object """ self.session['user_id'] = user.key self.session['user_data'] = user.clean_value() role = self.get_role() # TODO: this should be remembered from previous lo...
Writes user data to session. Args: user: User object
entailment
def contains_opposite_color_piece(self, square, position): """ Finds if square on the board is occupied by a ``Piece`` belonging to the opponent. :type: square: Location :type: position: Board :rtype: bool """ return not position.is_square_empty(square) a...
Finds if square on the board is occupied by a ``Piece`` belonging to the opponent. :type: square: Location :type: position: Board :rtype: bool
entailment
def gettext(message, domain=DEFAULT_DOMAIN): """Mark a message as translateable, and translate it. All messages in the application that are translateable should be wrapped with this function. When importing this function, it should be renamed to '_'. For example: .. code-block:: python from z...
Mark a message as translateable, and translate it. All messages in the application that are translateable should be wrapped with this function. When importing this function, it should be renamed to '_'. For example: .. code-block:: python from zengine.lib.translation import gettext as _ p...
entailment
def gettext_lazy(message, domain=DEFAULT_DOMAIN): """Mark a message as translatable, but delay the translation until the message is used. Sometimes, there are some messages that need to be translated, but the translation can't be done at the point the message itself is written. For example, the names of ...
Mark a message as translatable, but delay the translation until the message is used. Sometimes, there are some messages that need to be translated, but the translation can't be done at the point the message itself is written. For example, the names of the fields in a Model can't be translated at the point ...
entailment
def ngettext(singular, plural, n, domain=DEFAULT_DOMAIN): """Mark a message as translateable, and translate it considering plural forms. Some messages may need to change based on a number. For example, consider a message like the following: .. code-block:: python def alert_msg(msg_count): pri...
Mark a message as translateable, and translate it considering plural forms. Some messages may need to change based on a number. For example, consider a message like the following: .. code-block:: python def alert_msg(msg_count): print( 'You have %d %s' % (msg_count, 'message' if msg_count...
entailment
def ngettext_lazy(singular, plural, n, domain=DEFAULT_DOMAIN): """Mark a message with plural forms translateable, and delay the translation until the message is used. Works the same was a `ngettext`, with a delaying functionality similiar to `gettext_lazy`. Args: singular (unicode): The singul...
Mark a message with plural forms translateable, and delay the translation until the message is used. Works the same was a `ngettext`, with a delaying functionality similiar to `gettext_lazy`. Args: singular (unicode): The singular form of the message. plural (unicode): The plural form of t...
entailment
def _wrap_locale_formatter(fn, locale_type): """Wrap a Babel data formatting function to automatically format for currently installed locale.""" def wrapped_locale_formatter(*args, **kwargs): """A Babel formatting function, wrapped to automatically use the currently installed language. ...
Wrap a Babel data formatting function to automatically format for currently installed locale.
entailment
def install_language(cls, language_code): """Install the translations for language specified by `language_code`. If we don't have translations for this language, then the default language will be used. If the language specified is already installed, then this is a no-op. """ # ...
Install the translations for language specified by `language_code`. If we don't have translations for this language, then the default language will be used. If the language specified is already installed, then this is a no-op.
entailment
def install_locale(cls, locale_code, locale_type): """Install the locale specified by `language_code`, for localizations of type `locale_type`. If we can't perform localized formatting for the specified locale, then the default localization format will be used. If the locale specified ...
Install the locale specified by `language_code`, for localizations of type `locale_type`. If we can't perform localized formatting for the specified locale, then the default localization format will be used. If the locale specified is already installed for the selected type, then this is a no-...
entailment
def _rotate_vector(x, y, x2, y2, x1, y1): """ rotate x,y vector over x2-x1, y2-y1 angle """ angle = atan2(y2 - y1, x2 - x1) cos_rad = cos(angle) sin_rad = sin(angle) return cos_rad * x + sin_rad * y, -sin_rad * x + cos_rad * y
rotate x,y vector over x2-x1, y2-y1 angle
entailment
def _build_static_table_mapping(): """ Build static table mapping from header name to tuple with next structure: (<minimal index of header>, <mapping from header value to it index>). static_table_mapping used for hash searching. """ static_table_mapping = {} for index, (name, value) in enum...
Build static table mapping from header name to tuple with next structure: (<minimal index of header>, <mapping from header value to it index>). static_table_mapping used for hash searching.
entailment
def get_by_index(self, index): """ Returns the entry specified by index Note that the table is 1-based ie an index of 0 is invalid. This is due to the fact that a zero value index signals that a completely unindexed header follows. The entry will either be from...
Returns the entry specified by index Note that the table is 1-based ie an index of 0 is invalid. This is due to the fact that a zero value index signals that a completely unindexed header follows. The entry will either be from the static table or the dynamic table depe...
entailment
def add(self, name, value): """ Adds a new entry to the table We reduce the table size if the entry will make the table size greater than maxsize. """ # We just clear the table if the entry is too big size = table_entry_size(name, value) if size > self._m...
Adds a new entry to the table We reduce the table size if the entry will make the table size greater than maxsize.
entailment
def search(self, name, value): """ Searches the table for the entry specified by name and value Returns one of the following: - ``None``, no match at all - ``(index, name, None)`` for partial matches on name only. - ``(index, name, value)`` for perfec...
Searches the table for the entry specified by name and value Returns one of the following: - ``None``, no match at all - ``(index, name, None)`` for partial matches on name only. - ``(index, name, value)`` for perfect matches.
entailment
def _shrink(self): """ Shrinks the dynamic table to be at or below maxsize """ cursize = self._current_size while cursize > self._maxsize: name, value = self.dynamic_entries.pop() cursize -= table_entry_size(name, value) self._current_size = cursiz...
Shrinks the dynamic table to be at or below maxsize
entailment
def add(self, name, value): # type: (str, str) -> None """Adds a new value for the given key.""" self._last_key = name if name in self: self._dict[name] = value self._as_list[name].append(value) else: self[name] = value
Adds a new value for the given key.
entailment
def get_all(self): # type: () -> typing.Iterable[typing.Tuple[str, str]] """Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name. """ for name, values in six.iteritems(self._as_list): ...
Returns an iterable of all (name, value) pairs. If a header has multiple values, multiple pairs will be returned with the same name.
entailment
def safe_print(ustring, errors='replace', **kwargs): """ Safely print a unicode string """ encoding = sys.stdout.encoding or 'utf-8' if sys.version_info[0] == 3: print(ustring, **kwargs) else: bytestr = ustring.encode(encoding, errors=errors) print(bytestr, **kwargs)
Safely print a unicode string
entailment
def edit_permissions(self): """Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects field: .. code-block:: python { "type": "tree-toggle", "action": "set_permission", ...
Creates the view used to edit permissions. To create the view, data in the following format is passed to the UI in the objects field: .. code-block:: python { "type": "tree-toggle", "action": "set_permission", "tree": [ ...
entailment
def _permission_trees(permissions): """Get the cached permission tree, or build a new one if necessary.""" treecache = PermissionTreeCache() cached = treecache.get() if not cached: tree = PermissionTreeBuilder() for permission in permissions: tree....
Get the cached permission tree, or build a new one if necessary.
entailment
def _apply_role_tree(self, perm_tree, role): """In permission tree, sets `'checked': True` for the permissions that the role has.""" role_permissions = role.get_permissions() for perm in role_permissions: self._traverse_tree(perm_tree, perm)['checked'] = True return perm_tree
In permission tree, sets `'checked': True` for the permissions that the role has.
entailment
def _traverse_tree(tree, path): """Traverses the permission tree, returning the permission at given permission path.""" path_steps = (step for step in path.split('.') if step != '') # Special handling for first step, because the first step isn't under 'objects' first_step = path_steps.ne...
Traverses the permission tree, returning the permission at given permission path.
entailment
def _format_subtree(self, subtree): """Recursively format all subtrees.""" subtree['children'] = list(subtree['children'].values()) for child in subtree['children']: self._format_subtree(child) return subtree
Recursively format all subtrees.
entailment
def apply_change(self): """Applies changes to the permissions of the role. To make a change to the permission of the role, a request in the following format should be sent: .. code-block:: python { 'change': { 'id'...
Applies changes to the permissions of the role. To make a change to the permission of the role, a request in the following format should be sent: .. code-block:: python { 'change': { 'id': 'workflow2.lane1.task1', ...
entailment
def seek(self, offset): """ shifts on a given number of record in the original file :param offset: number of record """ if self._shifts: if 0 <= offset < len(self._shifts): current_pos = self._file.tell() new_pos = self._shifts[offset] ...
shifts on a given number of record in the original file :param offset: number of record
entailment
def tell(self): """ :return: number of records processed from the original file """ if self._shifts: t = self._file.tell() return bisect_left(self._shifts, t) raise self._implement_error
:return: number of records processed from the original file
entailment
def write(self, data): """ write single molecule into file """ m = self._convert_structure(data) self._file.write(self._format_mol(*m)) self._file.write('M END\n') for k, v in data.meta.items(): self._file.write(f'> <{k}>\n{v}\n') self._file...
write single molecule into file
entailment
def save_workflow_to_cache(self, serialized_wf_instance): """ If we aren't come to the end of the wf, saves the wf state and task_data to cache Task_data items that starts with underscore "_" are treated as local and does not passed to subsequent task steps. """ ...
If we aren't come to the end of the wf, saves the wf state and task_data to cache Task_data items that starts with underscore "_" are treated as local and does not passed to subsequent task steps.
entailment
def get_pool_context(self): # TODO: Add in-process caching """ Builds context for the WF pool. Returns: Context dict. """ context = {self.current.lane_id: self.current.role, 'self': self.current.role} for lane_id, role_id in self.current.pool.items():...
Builds context for the WF pool. Returns: Context dict.
entailment
def load_workflow_from_cache(self): """ loads the serialized wf state and data from cache updates the self.current.task_data """ if not self.current.new_token: self.wf_state = self.current.wf_cache.get(self.wf_state) self.current.task_data = self.wf_state[...
loads the serialized wf state and data from cache updates the self.current.task_data
entailment
def serialize_workflow(self): """ Serializes the current WF. Returns: WF state data. """ self.workflow.refresh_waiting_tasks() return CompactWorkflowSerializer().serialize_workflow(self.workflow, i...
Serializes the current WF. Returns: WF state data.
entailment
def load_or_create_workflow(self): """ Tries to load the previously serialized (and saved) workflow Creates a new one if it can't """ self.workflow_spec = self.get_worfklow_spec() return self._load_workflow() or self.create_workflow()
Tries to load the previously serialized (and saved) workflow Creates a new one if it can't
entailment
def find_workflow_path(self): """ Tries to find the path of the workflow diagram file in `WORKFLOW_PACKAGES_PATHS`. Returns: Path of the workflow spec file (BPMN diagram) """ for pth in settings.WORKFLOW_PACKAGES_PATHS: path = "%s/%s.bpmn" % (pth,...
Tries to find the path of the workflow diagram file in `WORKFLOW_PACKAGES_PATHS`. Returns: Path of the workflow spec file (BPMN diagram)
entailment
def get_worfklow_spec(self): """ Generates and caches the workflow spec package from BPMN diagrams that read from disk Returns: SpiffWorkflow Spec object. """ # TODO: convert from in-process to redis based caching if self.current.workflow_name not in ...
Generates and caches the workflow spec package from BPMN diagrams that read from disk Returns: SpiffWorkflow Spec object.
entailment
def _save_or_delete_workflow(self): """ Calls the real save method if we pass the beggining of the wf """ if not self.current.task_type.startswith('Start'): if self.current.task_name.startswith('End') and not self.are_we_in_subprocess(): self.wf_state['finishe...
Calls the real save method if we pass the beggining of the wf
entailment