code stringlengths 1 18.2k |
|---|
def _parse_quit(client, command, actor, args): """Parse a QUIT and update channel states, then dispatch events. Note that two events are dispatched here: - QUIT, because a user quit the server - MEMBERS, for each channel the user is no longer in """ actor = User(actor) _, _, message = args.partition(':') client.dispatc... |
def _parse_kick(client, command, actor, args): """Parse a KICK and update channel states, then dispatch events. Note that two events are dispatched here: - KICK, because a user was kicked from the channel - MEMBERS, because the channel's members changed """ actor = User(actor) args, _, message = args.partition(' :') ch... |
def _parse_topic(client, command, actor, args): """Parse a TOPIC and update channel state, then dispatch a TOPIC event.""" channel, _, topic = args.partition(" :") channel = client.server.get_channel(channel) channel.topic = topic or None if actor: actor = User(actor) client.dispatch_event("TOPIC", actor, channel, topi... |
def _parse_welcome(client, command, actor, args): """Parse a WELCOME and update user state, then dispatch a WELCOME event.""" _, _, hostmask = args.rpartition(' ') client.user.update_from_hostmask(hostmask) client.dispatch_event("WELCOME", hostmask) |
def _parse_created(client, command, actor, args): """Parse CREATED and update the Host object.""" m = re.search("This server was created (.+)$", args) if m: client.server.created = m.group(1) |
def _parse_myinfo(client, command, actor, args): """Parse MYINFO and update the Host object.""" _, server, version, usermodes, channelmodes = args.split(None, 5)[:5] s = client.server s.host = server s.version = version s.user_modes = set(usermodes) s.channel_modes = set(channelmodes) |
def _parse_featurelist(client, command, actor, args): """Parse FEATURELIST and update the Host object.""" # Strip off ":are supported by this server" args = args.rsplit(":", 1)[0] # Strip off the nick; we know it's addressed to us. _, _, args = args.partition(' ') items = args.split() for item in items: feature, _, val... |
def _parse_namreply(client, command, actor, args): """Parse NAMREPLY and update a Channel object.""" prefixes = client._get_prefixes() channelinfo, _, useritems = args.partition(' :') _, _, channel = channelinfo.rpartition(' ') # channeltype channelname c = client.server.get_channel(channel) if not c: _log.warning("Ign... |
def _parse_endofnames(client, command, actor, args): """Parse an ENDOFNAMES and dispatch a NAMES event for the channel.""" args = args.split(" :", 1)[0] # Strip off human-readable message _, _, channel = args.rpartition(' ') channel = client.server.get_channel(channel) or channel.lower() client.dispatch_event('MEMBERS'... |
def _parse_mode(client, command, actor, args): """Parse a mode changes, update states, and dispatch MODE events.""" chantypes = client.server.features.get("CHANTYPES", "#") channel, _, args = args.partition(" ") args = args.lstrip(":") if channel[0] not in chantypes: # Personal modes for modes in args.split(): op, mode... |
if op == "+": user.modes.add(mode) else: user.modes.discard(mode) if op == "+": if mode in (always_arg_modes | set_arg_modes): chan.modes[mode] = argument elif mode in toggle_modes: chan.modes[mode] = True else: if mode in (always_arg_modes | set_arg_modes | toggle_modes): if mode in chan.modes: del chan.modes[mode] # ... |
def _parse_whois(client, command, actor, args): """Parse the content responses from a WHOIS query. Individual response lines are parsed and used to fill in data in a buffer, the full contents of which are then sent as the argument to the WHOIS event dispatched when an ENDOFWHOIS line is received from the server. """ _,... |
= int(response["idle"]) return if command == "WHOISCHANNELS": modes = "".join(client._get_prefixes()) print repr(modes) channels = args.lstrip(":").split() response["channels"] = dict( (chan.lstrip(modes), chan[0] if chan[0] in modes else "") for chan in channels) return if command == "WHOISACCOUNT": response["account"... |
def _parse_nick(client, command, actor, args): """Parse a NICK response, update state, and dispatch events. Note: this function dispatches both a NICK event and also one or more MEMBERS events for each channel the user that changed nick was in. """ old_nick, _, _ = actor.partition('!') new_nick = args if old_nick == cl... |
def _parse_invite(client, command, actor, args): """Parse an INVITE and dispatch an event.""" target, _, channel = args.rpartition(" ") client.dispatch_event("INVITE", actor, target, channel.lower()) |
def _parse_nicknameinuse(client, command, actor, args): """Parse a NICKNAMEINUSE message and dispatch an event. The parameter passed along with the event is the nickname which is already in use. """ nick, _, _ = args.rpartition(" ") client.dispatch_event("NICKNAMEINUSE", nick) |
def add_user(self, user): """Adds a user to the channel.""" if not isinstance(user, User): user = User(user) if user.nick in self.members: _log.warning("Ignoring request to add user '%s' to channel '%s' " "because that user is already in the member list.", user, self.name) return self.members[user.nick] = user _log.deb... |
def add_handler(self, event, handler): """Adds a handler for a particular event. Handlers are appended to the list, so a handler added earlier will be called before a handler added later. If you wish to insert a handler at another position, you should modify the event_handlers property directly: my_client.event_handler... |
def dispatch_event(self, event, *args): """Dispatches an event. Returns a boolean indicating whether or not a handler suppressed further handling of the event (even the last). """ if event not in self.event_handlers: _log.error("Dispatch requested for unknown event '%s'", event) return False elif event != "LINE": _log.... |
def connect(self, nick, username=None, realname=None, password=None, host=None, port=6667, ssl=None): """Connect to the server using the specified credentials. Note: if host is specified here, both the host and port arguments passed to Client.__init__ will be ignored. If the 'ssl' argument is boolean true, will use SSL... |
requested but no SSL support available!") return self.socket.connect((self.server.host, self.server.port)) self.connected = True _log.info("Connected to %s.", self.server.host) # Allow an event handler to supply a password instead, if it wants suppress_password = self.dispatch_event("PASSWORD") if password and not supp... |
def run(self): """Process events such as incoming data. This method blocks indefinitely. It will only return after the connection to the server is closed. """ self._stop = False # Allow re-starting the event loop while not self._stop: try: self._buffer += self.socket.recv(4096) except socket.error: raise lines = self._... |
def send(self, *args): """Sends a single raw message to the IRC server. Arguments are automatically joined by spaces. No newlines are allowed. """ msg = " ".join(a.nick if isinstance(a, User) else str(a) for a in args) if "\n" in msg: raise ValueError("Cannot send() a newline. Args: %s" % repr(args)) _log.debug("%s <--... |
def userinfo(self, username, realname=None): """Set the username and realname for this connection. Note: this should only be called once, on connect. (The default on-connect routine calls this automatically.) """ realname = realname or username _log.info("Requesting user info update: username=%s realname=%s", username,... |
def reply(self, incoming, user, message, prefix=None): """Replies to a user in a given channel or PM. If the specified incoming is a user, simply sends a PM to user. If the specified incoming is a channel, prefixes the message with the user's nick and sends it to the channel. This is specifically useful in creating res... |
def join(self, target, key=None): """Attempt to join a channel. The optional second argument is the channel key, if needed. """ chantypes = self.server.features.get("CHANTYPES", "#") if not target or target[0] not in chantypes: # Among other things, this prevents accidentally sending the # "JOIN 0" command which actual... |
def part(self, target, message=None): """Part a channel.""" if not self.server.in_channel(target): _log.warning("Ignoring request to part channel '%s' because we " "are not in that channel.", target) return return False self.send("PART", target, *([message] if message else [])) return True |
def kick(self, channel, nick, message=None): """Attempt to kick a user from a channel. If a message is not provided, defaults to own nick. """ self.send("KICK", channel, nick, ":%s" % (message or self.user.nick)) |
def mode(self, channel, add='', remove=''): """Add and/or remove modes for a given channel. The 'add' and 'remove' arguments may, if specified, be either sequences or dictionaries. If a dictionary is specified, the corresponding values will be passed as arguments (with expansion if necessary - {'b': ['foo','bar']} will... |
if invalid_modes: _log.warning("Ignoring the mode(s) '%s' because they are " "missing required arguments.", "".join(invalid_modes)) return modes & toggle_modes, [] # Okay, so arg is a dict modes_with_args = [] modes_without_args = set() for k,v in arg.iteritems(): if isinstance(v, str): v = [v] if k in argument_modes: ... |
now_modes) modes += "".join(" %s" % arg for mode,arg in now_modes) self.send("MODE", channel, "%s%s" % (op, modes)) _send_modes("+", add_modes, add_modes_args) _send_modes("-", remove_modes, remove_modes_args) |
def handle(self, event): """Decorator for adding a handler function for a particular event. Usage: my_client = Client() @my_client.handle("WELCOME") def welcome_handler(client, *params): # Do something with the event. pass """ def dec(func): self.add_handler(event, func) return func return dec |
def _get_prefixes(self): """Get the possible nick prefixes and associated modes for a client.""" prefixes = { "@": "o", "+": "v", } feature_prefixes = self.server.features.get('PREFIX') if feature_prefixes: modes = feature_prefixes[1:len(feature_prefixes)//2] symbols = feature_prefixes[len(feature_prefixes)//2+1:] pref... |
def get_asset_mdata(): """Return default mdata map for Asset""" return { 'copyright_registration': { 'element_label': { 'text': 'copyright registration', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'enter ... |
}, 'instructions': { 'text': 'enter no more than 256 characters.', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': False, 'read_only': False, 'linked': False, 'array': False, 'default_string_values': [{ 'text': '', 'languag... |
'date_time_set': [], }, 'distribute_alterations': { 'element_label': { 'text': 'distribute alterations', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'enter either true or false.', 'languageTypeId': str(DEF... |
'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': False, 'read_only': False, 'linked': False, 'array': False, 'default_date_time_values': [None], 'syntax': 'DATETIME', 'date_time_set': [], }, 'source': { 'element_label': { 'text': 'source', 'languageTypeId': str(DEFAULT_... |
str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': False, 'read_only': False, 'linked': False, 'array': False, 'default_boolean_values': [None], 'syntax': 'BOOLEAN', }, 'distribute_compositions': { 'element_label': { 'text': 'distribute composi... |
'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': False, 'read_only': False, 'linked': False, 'array': False, 'default_boolean_values': [None], 'syntax': 'BOOLEAN', }, } |
def get_asset_content_mdata(): """Return default mdata map for AssetContent""" return { 'url': { 'element_label': { 'text': 'url', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'enter no more than 256 charac... |
str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'required': False, 'read_only': False, 'linked': False, 'array': False, 'default_type_values': ['NoneType%3ANONE%40dlkit.mit.edu'], 'syntax': 'TYPE', 'type_set': [], }, 'asset': { 'element_label': { 'text': 'asset', 'languageTypeId': str(DEFAULT_LAN... |
def get_composition_mdata(): """Return default mdata map for Composition""" return { 'children': { 'element_label': { 'text': 'children', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'formatTypeId': str(DEFAULT_FORMAT_TYPE), }, 'instructions': { 'text': 'accepts an osid.id.Id[... |
def _compute_raw_moments(self, n_counter, k_counter): # The symbols for expectations are simply the first order raw moments. """ :param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments :type n_counter: list[:class:`~means.core.descriptors.Moment`] :param k_counter: a list of :... |
:math: '\log\mathbb{E} (x_i) = \log(\mathbb{E} (x_i) )+ \frac {\log (Var(x_i))}{2}' log_expectation_symbols = sp.Matrix([sp.log(e) - lv/sp.Integer(2) for e,lv in zip(expectation_symbols, log_variance_symbols)]) # Assign log variance symbols on the diagonal of size n_species by n_species log_variance_mat = sp.Matrix(n_s... |
def _get_log_covariance(self, log_variance_mat, log_expectation_symbols, covariance_matrix, x, y): r""" Compute log covariances according to:\\ :math:`\log{(Cov(x_i,x_j))} = \frac { 1 + Cov(x_i,x_j)}{\exp[\log \mathbb{E}(x_i) + \log \mathbb{E}(x_j)+\frac{1}{2} (\log Var(x_i) + \log Var(x_j)]}` :param log_variance_mat: ... |
sp.Integer(2)) return sp.log(sp.Integer(1) + covariance_matrix[x, y] / denom) # univariate case: log covariances are 0s. else: return sp.Integer(0) |
def get_assessment_parts_by_search(self, assessment_part_query, assessment_part_search): """Pass through to provider AssessmentPartSearchSession.get_assessment_parts_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): r... |
def get_sequence_rules_by_search(self, sequence_rule_query, sequence_rule_search): """Pass through to provider SequenceRuleSearchSession.get_sequence_rules_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise Permi... |
def get_sequence_rule_enablers_by_search(self, sequence_rule_enabler_query, sequence_rule_enabler_search): """Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template ... |
def image_name(self): """ The image_name of a container is the concatenation of the ``image_index``, ``image_name_prefix``, and ``name`` of the image. Also, if $EXTRA_IMAGE_NAME is defined, that is appended """ if getattr(self, "_image_name", NotSpecified) is NotSpecified: self._image_name = self.prefixed_image_name if... |
def container_name(self): """ The container_name is the concatenation of ``image_name`` and a uuid1 string We also remove the url portion of the ``image_name`` before using it. """ if getattr(self, "_container_name", NotSpecified) is NotSpecified: self.container_name = "{0}-{1}".format(self.image_name.replace("/", "--"... |
def container_id(self): """ Find a container id If one isn't already set, we ask docker for the container whose name is the same as the recorded container_name """ if getattr(self, "_container_id", None): return self._container_id try: containers = self.harpoon.docker_api.containers(all=True) except ValueError: log.war... |
def formatted_command(self): """ If we have ``bash``, then the command is ``/bin/bash -c <bash>``, whereas if the ``command`` is set, then we just return that. """ bash = self.bash if bash not in (None, "", NotSpecified) and callable(bash): bash = bash() if bash not in (None, "", NotSpecified): return "{0} -c {1}".form... |
def dependencies(self, images): """Yield just the dependency images""" for dep in self.commands.dependent_images: if not isinstance(dep, six.string_types): yield dep.name for image, _ in self.dependency_images(): yield image |
def cache_from_names(self): """Yield the image names to do --cache-from from""" cache_from = self.cache_from() if not cache_from or cache_from is NotSpecified: return if cache_from is True: yield self.image_name return for thing in cache_from: if not isinstance(thing, six.string_types): yield thing.image_name else: yie... |
def dependency_images(self, for_running=False): """ What images does this one require Taking into account parent image, and those in link and volumes.share_with options """ candidates = [] detach = dict((candidate, not options.attached) for candidate, options in self.dependency_options.items()) for link in self.links: ... |
def shared_volume_containers(self): """All the harpoon containers in volumes.share_with for this container""" for container in self.volumes.share_with: if not isinstance(container, six.string_types): yield container.name |
def find_missing_env(self): """Find any missing environment variables""" missing = [] for e in self.env: if e.default_val is None and e.set_val is None: if e.env_name not in os.environ: missing.append(e.env_name) if missing: raise BadOption("Some environment variables aren't in the current environment", missing=missing... |
def display_line(self): """A single line describing this image""" msg = ["Image {0}".format(self.name)] if self.image_index: msg.append("Pushes to {0}".format(self.image_name)) return ' : '.join(msg) |
def build_and_run(self, images): """Make this image and run it""" from harpoon.ship.builder import Builder Builder().make_image(self, images) try: Runner().run_container(self, images) except DockerAPIError as error: raise BadImage("Failed to start the container", error=error) |
def add_docker_file_to_tarfile(self, docker_file, tar): """Add a Dockerfile to a tarfile""" with hp.a_temp_file() as dockerfile: log.debug("Context: ./Dockerfile") dockerfile.write("\n".join(docker_file.docker_lines).encode('utf-8')) dockerfile.seek(0) tar.add(dockerfile.name, arcname="./Dockerfile") |
def make_context(self, docker_file=None): """Determine the docker lines for this image""" kwargs = {"silent_build": self.harpoon.silent_build, "extra_context": self.commands.extra_context} if docker_file is None: docker_file = self.docker_file with ContextBuilder().make_context(self.context, **kwargs) as ctxt: self.add... |
def conditions(self, start, last_attempt): """ Yield lines to execute in a docker context All conditions must evaluate for the container to be considered ready """ if time.time() - start > self.timeout: yield WaitCondition.Timedout return if last_attempt is not None and time.time() - last_attempt < self.wait_between_at... |
path in self.file_exists: yield 'cat {0} > /dev/null'.format(path) if self.command not in (None, "", NotSpecified): for command in self.command: yield command |
def git_root(self): """ Find the root git folder """ if not getattr(self, "_git_folder", None): root_folder = os.path.abspath(self.parent_dir) while not os.path.exists(os.path.join(root_folder, '.git')): if root_folder == '/': raise HarpoonError("Couldn't find a .git folder", start_at=self.parent_dir) root_folder = os.... |
def share_with_names(self): """The names of the containers that we share with the running container""" for container in self.share_with: if isinstance(container, six.string_types): yield container else: yield container.container_name |
def pair(self): """Get the name and value for this environment variable""" if self.set_val is not None: return self.env_name, self.set_val elif self.default_val is not None: return self.env_name, os.environ.get(self.env_name, self.default_val) else: return self.env_name, os.environ[self.env_name] |
def pair(self): """return (container_port, (ip, host_port)) or (container_port, host_port)""" if self.ip is NotSpecified: if self.ip is NotSpecified: second = self.host_port else: second = (self.ip, ) else: second = (self.ip, self.host_port) return self.container_port.port_str, second |
def port_pair(self): """The port and it's transport as a pair""" if self.transport is NotSpecified: return (self.port, "tcp") else: return (self.port, self.transport) |
def port_str(self): """The port and it's transport as a single string""" if self.transport is NotSpecified: return str(self.port) else: return "{0}/{1}".format(self.port, self.transport) |
def get_distance_function(distance): """ Returns the distance function from the string name provided :param distance: The string name of the distributions :return: """ # If we provided distance function ourselves, use it if callable(distance): return distance try: return _supported_distances_lookup()[distance] except K... |
def sum_of_squares(simulated_trajectories, observed_trajectories_lookup): """ Returns the sum-of-squares distance between the simulated_trajectories and observed_trajectories :param simulated_trajectories: Simulated trajectories :type simulated_trajectories: list[:class:`means.simulation.Trajectory`] :param observed_tr... |
def _distribution_distance(simulated_trajectories, observed_trajectories_lookup, distribution): """ Returns the distance between the simulated and observed trajectory, w.r.t. the assumed distribution :param simulated_trajectories: Simulated trajectories :type simulated_trajectories: list[:class:`means.simulation.Trajec... |
def _eval_density(means, variances,observed_values, distribution): """ Calculates gamma/lognormal/normal pdf given mean variance, x where x is the experimental species number measured at a particular timepoint. Returns ln(pdf) :param mean: mean :param var: variance :param observed_values: experimental species number me... |
means / b log_observed_values = np.log(observed_values) log_density = (a - 1.0) * log_observed_values - (observed_values / b) - a * np.log(b) - gammaln(a) elif distribution == 'normal': log_density = -(observed_values - means) ** 2 / (2 * variances) - np.log(np.sqrt(2 * np.pi * variances)) elif distribution == 'lognorm... |
def retrieve_author(id=None, username=None): """ Retrieve a SpigotAuthor via their id, or username. :param id: :param username: :return: """ if id is None and username is None: raise SpigotAuthorException("Unable to retrieve an Author without an Identifier") if id is None: return SpigotAuthor.from_username(username) el... |
def _escape_identifiers(self, item): """ This function escapes column and table names @param item: """ if self._escape_char == '': return item for field in self._reserved_identifiers: if item.find('.%s' % field) != -1: _str = "%s%s" % (self._escape_char, item.replace('.', '%s.' % self._escape_char)) # remove duplicates... |
def get(self, uri): """ Return node for uri or None if not exists: {uri: x, content: y} """ cache_key = self._build_cache_key(uri) value = self._get(cache_key) if value is not None: return self._decode_node(uri, value) |
def get_many(self, uris): """ Return request uri map of found nodes as dicts: {requested_uri: {uri: x, content: y}} """ cache_keys = dict((self._build_cache_key(uri), uri) for uri in uris) result = self._get_many(cache_keys) nodes = {} for cache_key in result: uri = cache_keys[cache_key] value = result[cache_key] node ... |
def set(self, uri, content): """ Cache node content for uri. No return. """ key, value = self._prepare_node(uri, content) self._set(key, value) |
def set_many(self, nodes): """ Takes nodes dict {uri: content, ...} as argument. No return. """ data = self._prepare_nodes(nodes) self._set_many(data) |
def delete(self, uri): """ Remove node uri from cache. No return. """ cache_key = self._build_cache_key(uri) self._delete(cache_key) |
def delete_many(self, uris): """ Remove many nodes from cache. No return. """ cache_keys = (self._build_cache_key(uri) for uri in uris) self._delete_many(cache_keys) |
def _build_cache_key(self, uri): """ Build sha1 hex cache key to handle key length and whitespace to be compatible with Memcached """ key = uri.clone(ext=None, version=None) if six.PY3: key = key.encode('utf-8') return sha1(key).hexdigest() |
def get_many(self, uris): """ Simple implementation, could be better implemented by backend not hitting db for every uri. """ nodes = {} for uri in uris: try: node = self.get(uri) except NodeDoesNotExist: continue else: nodes[uri] = node return nodes |
def set(self, uri, content, **meta): """ Dispatches private update/create handlers """ try: node = self._update(uri, content, **meta) created = False except NodeDoesNotExist: node = self._create(uri, content, **meta) created = True return self._serialize(uri, node), created |
def delete_many(self, uris): """ Simple implementation, could be better implemented by backend not hitting db for every uri. """ deleted_nodes = {} for uri in uris: node = self.delete(uri) if node: deleted_nodes[uri] = node return deleted_nodes |
def _serialize(self, uri, node): """ Serialize node result as dict """ meta = self._decode_meta(node['meta'], is_published=bool(node['is_published'])) return { 'uri': uri.clone(ext=node['plugin'], version=node['version']), 'content': node['content'], 'meta': meta } |
def _decode_meta(self, meta, **extra): """ Decode and load underlying meta structure to dict and apply optional extra values. """ _meta = json.loads(meta) if meta else {} _meta.update(extra) return _meta |
def _merge_meta(self, encoded_meta, meta): """ Merge new meta dict into encoded meta. Returns new encoded meta. """ new_meta = None if meta: _meta = self._decode_meta(encoded_meta) for key, value in six.iteritems(meta): if value is None: _meta.pop(key, None) else: _meta[key] = value new_meta = self._encode_meta(_meta) ... |
def _get_next_version(self, revisions): """ Calculates new version number based on existing numeric ones. """ versions = [0] for v in revisions: if v.isdigit(): versions.append(int(v)) return six.text_type(sorted(versions)[-1] + 1) |
def get_one_over_n_factorial(counter_entry): r""" Calculates the :math:`\frac{1}{\mathbf{n!}}` of eq. 6 (see Ale et al. 2013). That is the invert of a product of factorials. :param counter_entry: an entry of counter. That is an array of integers of length equal to the number of variables. For instance, `counter_entry` ... |
def derive_expr_from_counter_entry(expression, species, counter_entry): r""" Derives an given expression with respect to arbitrary species and orders. This is used to compute :math:`\frac{\partial^n \mathbf{n}a_l(\mathbf{x})}{\partial \mathbf{x^n}}` in eq. 6 :param expression: the expression to be derived :type express... |
v, c: [v] * c, species, counter_entry)) out_expr = expression for var in diff_vars: # If the derivative is already 0, we can return 0 if out_expr.is_Integer: return sp.Integer(0) out_expr = _cached_diff(out_expr, var) return out_expr |
def make_k_chose_e(e_vec, k_vec): """ Computes the product :math:`{\mathbf{n} \choose \mathbf{k}}` :param e_vec: the vector e :type e_vec: :class:`numpy.array` :param k_vec: the vector k :type k_vec: :class:`numpy.array` :return: a scalar """ return product([sp.factorial(k) / (sp.factorial(e) * sp.factorial(k - e)) for... |
def trim_ordered_range_list(ranges,start,finish): """A function to help with slicing a mapping Start with a list of ranges and get another list of ranges constrained by start (0-indexed) and finish (1-indexed) :param ranges: ordered non-overlapping ranges on the same chromosome :param start: start 0-indexed :param fini... |
#print 'fixstart '+str(original_rng.start)+' to '+str(rng.start) if finish > index and finish <= index+original_rng.length(): rng.end = original_rng.start+(finish-index)-1 done = True #print 'fixend '+str(original_rng.end)+' to '+str(rng.end) if finish <= index+original_rng.length(): # we are in the last exon we need i... |
def remove_transcript(self,tx_id): """Remove a transcript from the locus by its id :param tx_id: :type tx_id: string """ txs = self.get_transcripts() if tx_id not in [x.id for x in txs]: return tx = [x for x in txs if x.id==tx_id][0] for n in [x for x in self.g.get_nodes()]: if tx_id not in [y.id for y in n.payload]: c... |
def get_depth_per_transcript(self,mindepth=1): """ using all the transcripts find the depth """ bedarray = [] for tx in self.get_transcripts(): for ex in [x.range for x in tx.exons]: bedarray.append(ex) cov = ranges_to_coverage(bedarray) results = {} for tx in self.get_transcripts(): tlen = tx.length #mapped length bco... |
def range(self): """Return the range the transcript loci covers :return: range :rtype: GenomicRange """ chrs = set([x.range.chr for x in self.get_transcripts()]) if len(chrs) != 1: return None start = min([x.range.start for x in self.get_transcripts()]) end = max([x.range.end for x in self.get_transcripts()]) return Ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.