code stringlengths 1 18.2k |
|---|
def open_umanager(self): """Used to open an uManager session. """ if self.umanager_opened: return self.ser.write(self.cmd_umanager_invocation) # optimistic approach first: assume umanager is not invoked if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout*self.umanager_waitcoeff): self.umanager_ope... |
def close_umanager(self, force=False): """Used to close an uManager session. :param force: try to close a session regardless of a connection object internal state """ if not (force or self.umanager_opened): return # make sure we've got a fresh prompt self.ser.write(self.cr) if self.read_loop(lambda x: x.endswith(self.u... |
def download(self,data,um_update=False): """Used to download firmware or filter set. :param data: binary string to push via serial :param um_update: flag whether to update umanager """ self.open_umanager() self.ser.write(''.join((self.cmd_download,self.cr))) if self.read_loop(lambda x: x.endswith(self.xmodem_crc),self.... |
def list_current_filter_set(self,raw=False): """User to list a currently selected filter set""" buf = [] self.open_umanager() self.ser.write(''.join((self.cmd_current_filter_list,self.cr))) if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout,lambda x,y,z: buf.append(y.rstrip()[:-1])): if raw: rv =... |
def lrange(self, key, start, end): """ Returns the specified elements of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param int start: zero-based index to start retrieving elements from :param int end: zero-based index at which to stop retrieving elements :rtype: list :rai... |
will return 11 elements, that is, the rightmost item is included. This may or may not be consistent with behavior of range-related functions in your programming language of choice (think Ruby's ``Range.new``, ``Array#slice`` or Python's :func:`range` function). Out of range indexes will not produce an error. If start i... |
def ltrim(self, key, start, stop): """ Crop a list to the specified range. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param int start: zero-based index to first element to retain :param int stop: zero-based index of the last element to retain :returns: did the operation succeed? :rtype: bool :r... |
the end of the list, where -1 is the last element of the list, -2 the penultimate element and so on. Out of range indexes will not produce an error: if `start` is larger than the `end` of the list, or `start > end`, the result will be an empty list (which causes `key` to be removed). If `end` is larger than the end of ... |
to store logs for example. It is important to note that when used in this way LTRIM is an O(1) operation because in the average case just one element is removed from the tail of the list. .. note:: Time complexity: ``O(N)`` where `N` is the number of elements to be removed by the operation. """ return self._execute([b'... |
def lpush(self, key, *values): """ Insert all the specified values at the head of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the beginning of the list. Each value is inserted at the beginning of the list individ... |
other to the head of the list, from the leftmost element to the rightmost element. So for instance ``client.lpush('mylist', 'a', 'b', 'c')`` will result into a list containing ``c`` as first element, ``b`` as second element and ``a`` as third element. .. note:: **Time complexity**: ``O(1)`` """ return self._execute([b'... |
def lpushx(self, key, *values): """ Insert values at the head of an existing list. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the beginning of the list. Each value is inserted at the beginning of the list individually (see discussion b... |
def rpush(self, key, *values): """ Insert all the specified values at the tail of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the tail of the list. :returns: the length of the list after push operations :rtype: i... |
element. So for instance the command ``client.rpush('mylist', 'a', 'b', 'c')`` will result in a list containing ``a`` as first element, ``b`` as second element and ``c`` as third element. .. note:: **Time complexity**: ``O(1)`` """ return self._execute([b'RPUSH', key] + list(values)) |
def rpushx(self, key, *values): """ Insert values at the tail of an existing list. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the tail of the list. :returns: the length of the list after push operations or zero if `key` does not refer ... |
def encode_date_optional_time(obj): """ ISO encode timezone-aware datetimes """ if isinstance(obj, datetime.datetime): return timezone("UTC").normalize(obj.astimezone(timezone("UTC"))).strftime('%Y-%m-%dT%H:%M:%SZ') raise TypeError("{0} is not JSON serializable".format(repr(obj))) |
def file_handler(self, handler_type, path, prefixed_path, source_storage): """ Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to the queue for later processing. """ if self.faster: if prefixed_path not in self.found_files: self.found_files[prefixed_path] = (source_s... |
def delete_file(self, path, prefixed_path, source_storage): """ We don't need all the file_exists stuff because we have to override all files anyways. """ if self.faster: return True else: return super(Command, self).delete_file(path, prefixed_path, source_storage) |
def collect(self): """ Create some concurrent workers that process the tasks simultaneously. """ collected = super(Command, self).collect() if self.faster: self.worker_spawn_method() self.post_processor() return collected |
def gevent_spawn(self): """ Spawn worker threads (using gevent) """ monkey.patch_all(thread=False) joinall([spawn(self.gevent_worker) for x in range(self.queue_worker_amount)]) |
def gevent_worker(self): """ Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. """ while not self.task_queue.empty(): task_kwargs = self.task_queue.get() handler_type = task_kwargs.pop('handler_type') if handler_type == 'link': super(Command, self).link_file(*... |
def mp_spawn(self): """ Spawn worker processes (using multiprocessing) """ processes = [] for x in range(self.queue_worker_amount): process = multiprocessing.Process(target=self.mp_worker) process.start() processes.append(process) for process in processes: process.join() |
def mp_worker(self): """ Process one task after another by calling the handler (`copy_file` or `copy_link`) method of the super class. """ while not self.task_queue.empty(): task_kwargs = self.task_queue.get() handler_type = task_kwargs.pop('handler_type') if handler_type == 'link': super(Command, self).link_file(**tas... |
def _load_github_hooks(github_url='https://api.github.com'): """Request GitHub's IP block from their API. Return the IP network. If we detect a rate-limit error, raise an error message stating when the rate limit will reset. If something else goes wrong, raise a generic 503. """ try: resp = requests.get(github_url + '/... |
def is_github_ip(ip_str): """Verify that an IP address is owned by GitHub.""" if isinstance(ip_str, bytes): ip_str = ip_str.decode() ip = ipaddress.ip_address(ip_str) if ip.version == 6 and ip.ipv4_mapped: ip = ip.ipv4_mapped for block in load_github_hooks(): if ip in ipaddress.ip_network(block): return True return Fal... |
def check_signature(signature, key, data): """Compute the HMAC signature and test against a given hash.""" if isinstance(key, type(u'')): key = key.encode() digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest() # Covert everything to byte sequences if isinstance(digest, type(u'')): digest = digest.encode() i... |
def init_app(self, app, url='/hooks'): """Register the URL route to the application. :param app: the optional :class:`~flask.Flask` instance to register the extension :param url: the url that events will be posted to """ app.config.setdefault('VALIDATE_IP', True) app.config.setdefault('VALIDATE_SIGNATURE', True) @app.r... |
guid) else: return 'Hook not used\n' |
def register_hook(self, hook_name, fn): """Register a function to be called on a GitHub event.""" if hook_name not in self._hooks: self._hooks[hook_name] = fn else: raise Exception('%s hook already registered' % hook_name) |
def hook(self, hook_name): """A decorator that's used to register a new hook handler. :param hook_name: the event to handle """ def wrapper(fn): self.register_hook(hook_name, fn) return fn return wrapper |
def accept(self): """ Equivalent to socket.accept(), but transforms the socket into a websocket instance and sends a server handshake (after receiving a client handshake). Note that the handshake may raise a HandshakeError exception. """ sock, address = self.sock.accept() wsock = websocket(sock) wsock.secure = self.sec... |
def connect(self, address): """ Equivalent to socket.connect(), but sends an client handshake request after connecting. `address` is a (host, port) tuple of the server to connect to. """ self.sock.connect(address) ClientHandshake(self).perform() self.handshake_sent = True |
def send(self, *args): """ Send a number of frames. """ for frame in args: self.sock.sendall(self.apply_send_hooks(frame, False).pack()) |
def queue_send(self, frame, callback=None, recv_callback=None): """ Enqueue `frame` to the send buffer so that it is send on the next `do_async_send`. `callback` is an optional callable to call when the frame has been fully written. `recv_callback` is an optional callable to quickly set the `recv_callback` attribute to... |
def do_async_send(self): """ Send any queued data. This function should only be called after a write event on a file descriptor. """ assert len(self.sendbuf) nwritten = self.sock.send(self.sendbuf) nframes = 0 for entry in self.sendbuf_frames: frame, offset, callback = entry if offset <= nwritten: nframes += 1 if callb... |
def do_async_recv(self, bufsize): """ Receive any completed frames from the socket. This function should only be called after a read event on a file descriptor. """ data = self.sock.recv(bufsize) if len(data) == 0: raise socket.error('no data to receive') self.recvbuf += data while contains_frame(self.recvbuf): frame, ... |
def enable_ssl(self, *args, **kwargs): """ Transforms the regular socket.socket to an ssl.SSLSocket for secure connections. Any arguments are passed to ssl.wrap_socket: http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket """ if self.handshake_sent: raise SSLError('can only enable SSL before handshake') self.sec... |
def validate_nonce(nonce, secret): ''' Is the nonce one that was generated by this library using the provided secret? ''' nonce_components = nonce.split(':', 2) if not len(nonce_components) == 3: return False timestamp = nonce_components[0] salt = nonce_components[1] nonce_signature = nonce_components[2] calculated_non... |
def calculate_partial_digest(username, realm, password): ''' Calculate a partial digest that may be stored and used to authenticate future HTTP Digest sessions. ''' return md5.md5("%s:%s:%s" % (username.encode('utf-8'), realm, password.encode('utf-8'))).hexdigest() |
def build_digest_challenge(timestamp, secret, realm, opaque, stale): ''' Builds a Digest challenge that may be sent as the value of the 'WWW-Authenticate' header in a 401 or 403 response. 'opaque' may be any value - it will be returned by the client. 'timestamp' will be incorporated and signed in the nonce - it may be ... |
def calculate_request_digest(method, partial_digest, digest_response=None, uri=None, nonce=None, nonce_count=None, client_nonce=None): ''' Calculates a value for the 'response' value of the client authentication request. Requires the 'partial_digest' calculated from the realm, username, and password. Either call it wit... |
md5.md5("%s:%s" % (partial_digest, data)).hexdigest() return kd |
def get_nonce_timestamp(nonce): ''' Extract the timestamp from a Nonce. To be sure the timestamp was generated by this site, make sure you validate the nonce using validate_nonce(). ''' components = nonce.split(':',2) if not len(components) == 3: return None try: return float(components[0]) except ValueError: return No... |
def calculate_nonce(timestamp, secret, salt=None): ''' Generate a nonce using the provided timestamp, secret, and salt. If the salt is not provided, (and one should only be provided when validating a nonce) one will be generated randomly in order to ensure that two simultaneous requests do not generate identical nonces... |
def build_authorization_request(username, method, uri, nonce_count, digest_challenge=None, realm=None, nonce=None, opaque=None, password=None, request_digest=None, client_nonce=None): ''' Builds an authorization request that may be sent as the value of the 'Authorization' header in an HTTP request. Either a digest_chal... |
"were sent.") if digest_challenge: if isinstance(digest_challenge, types.StringType): digest_challenge_header = digest_challenge digest_challenge = parse_digest_challenge(digest_challenge_header) if not digest_challenge: raise Exception("The provided digest challenge header could not be parsed: %s" % digest_challenge_h... |
def parse_digest_response(digest_response_string): ''' Parse the parameters of a Digest response. The input is a comma separated list of token=(token|quoted-string). See RFCs 2616 and 2617 for details. Known issue: this implementation will fail if there are commas embedded in quoted-strings. ''' parts = parse_parts(dig... |
def parse_digest_challenge(authentication_header): ''' Parses the value of a 'WWW-Authenticate' header. Returns an object with properties corresponding to each of the recognized parameters in the header. ''' if not is_digest_challenge(authentication_header): return None parts = parse_parts(authentication_header[7:], de... |
def __edges(self, nbunch=None, keys=False): """ Iterates over edges in current :class:`BreakpointGraph` instance. Returns a generator over the edges in current :class:`BreakpointGraph` instance producing instances of :class:`bg.edge.BGEdge` instances wrapping around information in underlying MultiGraph object. :param n... |
def edges(self, nbunch=None, keys=False): """ Iterates over edges in current :class:`BreakpointGraph` instance. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__edges`. :param nbunch: a vertex to iterate over edges outgoing from, if not provided,iteration over all edges is performed. :type nbuch: any hashable... |
def add_edge(self, vertex1, vertex2, multicolor, merge=True, data=None): """ Creates a new :class:`bg.edge.BGEdge` object from supplied information and adds it to current instance of :class:`BreakpointGraph`. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__add_bgedge` method. :param vertex1: first vertex ins... |
def __add_bgedge(self, bgedge, merge=True): """ Adds supplied :class:`bg.edge.BGEdge` object to current instance of :class:`BreakpointGraph`. Checks that vertices in supplied :class:`bg.edge.BGEdge` instance actually are present in current :class:`BreakpointGraph` if **merge** option of provided. Otherwise a new edge i... |
def add_bgedge(self, bgedge, merge=True): """ Adds supplied :class:`bg.edge.BGEdge` object to current instance of :class:`BreakpointGraph`. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__add_bgedge` method. :param bgedge: instance of :class:`bg.edge.BGEdge` infromation form which is to be added to current :... |
def __get_vertex_by_name(self, vertex_name): """ Obtains a vertex object by supplied label Returns a :class:`bg.vertex.BGVertex` or its subclass instance :param vertex_name: a vertex label it is identified by. :type vertex_name: any hashable python object. ``str`` expected. :return: vertex with supplied label if presen... |
return ref_key return list(self.bg[result].keys())[0] return None |
def __get_edge_by_two_vertices(self, vertex1, vertex2, key=None): """ Returns an instance of :class:`bg.edge.BBGEdge` edge between to supplied vertices (if ``key`` is supplied, returns a :class:`bg.edge.BBGEdge` instance about specified edge). Checks that both specified vertices are in current :class:`BreakpointGraph` ... |
vertex2 in self.bg[vertex1]: if key is None: key = min(self.bg[vertex1][vertex2]) return BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=self.bg[vertex1][vertex2][key]["attr_dict"]["multicolor"], data=self.bg[vertex1][vertex2][key]["attr_dict"]["data"]) return None |
def get_edge_by_two_vertices(self, vertex1, vertex2, key=None): """ Returns an instance of :class:`bg.edge.BBGEdge` edge between to supplied vertices (if ``key`` is supplied, returns a :class:`bg.edge.BBGEdge` instance about specified edge). Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__get_edge_by_two_ver... |
def __get_edges_by_vertex(self, vertex, keys=False): """ Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident to it. Wraps each yie... |
if keys: yield bg_edge, key else: yield bg_edge |
def get_edges_by_vertex(self, vertex, keys=False): """ Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Proxies a call to :meth:`Breakpoint._Breakpoint__get_edges_by_vertex` method. :param vertex: a vertex object in current :class:`BreakpointGraph` object :type verte... |
def __edges_between_two_vertices(self, vertex1, vertex2, keys=False): """ Iterates over edges between two supplied vertices in current :class:`BreakpointGraph` Checks that both supplied vertices are present in current breakpoint graph and then yield all edges that are located between two supplied vertices. If keys opti... |
``edge, edge_id`` if keys specified) between two supplied vertices in current :class:`BreakpointGraph` wrapped in :class:`bg.vertex.BGVertex` :rtype: ``generator`` """ for vertex in vertex1, vertex2: if vertex not in self.bg: raise ValueError("Supplied vertex ({vertex_name}) is not present in current BreakpointGraph" "... |
def edges_between_two_vertices(self, vertex1, vertex2, keys=False): """ Iterates over edges between two supplied vertices in current :class:`BreakpointGraph` Proxies a call to :meth:`Breakpoint._Breakpoint__edges_between_two_vertices` method. :param vertex1: a first vertex out of two, edges of interest are incident to ... |
def connected_components_subgraphs(self, copy=True): """ Iterates over connected components in current :class:`BreakpointGraph` object, and yields new instances of :class:`BreakpointGraph` with respective information deep-copied by default (week reference is possible of specified in method call). :param copy: a flag to... |
def __delete_bgedge(self, bgedge, key=None, keep_vertices=False): """ Deletes a supplied :class:`bg.edge.BGEdge` from a perspective of multi-color substitution. If unique identifier ``key`` is not provided, most similar (from perspective of :meth:`bg.multicolor.Multicolor.similarity_score` result) edge between respecti... |
of multi-color substitution :type bgedge: :class:`bg.edge.BGEdge` :param key: unique identifier of existing edges in current :class:`BreakpointGraph` instance to be changed :type: any python object. ``int`` is expected. :return: ``None``, performed inplace changes. """ ##################################################... |
keep_vertices: self.bg.add_node(bgedge.vertex1) self.bg.add_node(bgedge.vertex2) else: candidate_data, candidate_id, candidate_score = self.__determine_most_suitable_edge_for_deletion(bgedge) if candidate_data is not None: candidate_data["attr_dict"]["multicolor"] -= bgedge.multicolor if len(self.bg[bgedge.vertex1][bge... |
def delete_edge(self, vertex1, vertex2, multicolor, key=None): """ Creates a new :class:`bg.edge.BGEdge` instance from supplied information and deletes it from a perspective of multi-color substitution. If unique identifier ``key`` is not provided, most similar (from perspective of :meth:`bg.multicolor.Multicolor.simil... |
to be changed :type: any python object. ``int`` is expected. :return: ``None``, performed inplace changes. """ self.__delete_bgedge(bgedge=BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=multicolor), key=key) |
def delete_bgedge(self, bgedge, key=None): """ Deletes a supplied :class:`bg.edge.BGEdge` from a perspective of multi-color substitution. If unique identifier ``key`` is not provided, most similar (from perspective of :meth:`bg.multicolor.Multicolor.similarity_score` result) edge between respective vertices is chosen f... |
def __split_bgedge(self, bgedge, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True, key=None): """ Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is provided) with respect to supplied guidance. If no... |
guidance: a guidance for underlying :class:`bg.multicolor.Multicolor` object to be split :type guidance: iterable where each entry is iterable with colors entries :param duplication_splitting: flag (**not** currently implemented) for a splitting of color-based splitting to take into account multiplicity of respective c... |
candidate_score = score if candidate_data is not None: new_multicolors = Multicolor.split_colors(multicolor=candidate_data["attr_dict"]["multicolor"], guidance=guidance, sorted_guidance=sorted_guidance, account_for_color_multiplicity_in_guidance=account_for_colors_multiplicity_in_guidance) self.__delete_bgedge(bgedge=B... |
def split_edge(self, vertex1, vertex2, multicolor, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True, key=None): """ Splits an edge in current :class:`BreakpointGraph` most similar to supplied data (if no unique identifier ``key`` is provided) with respect to supplied guidance. Prox... |
key: unique identifier of edge to be split :type key: any python object. ``int`` is expected :return: ``None``, performs inplace changes """ self.__split_bgedge(bgedge=BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=multicolor), guidance=guidance, sorted_guidance=sorted_guidance, account_for_colors_multiplicity_in_... |
def split_bgedge(self, bgedge, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True, key=None): """ Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is provided) with respect to supplied guidance. Proxies... |
def __split_all_edges_between_two_vertices(self, vertex1, vertex2, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True): """ Splits all edges between two supplied vertices in current :class:`BreakpointGraph` instance with respect to the provided guidance. Iterates over all edges betwe... |
self.bg.edges(nbunch=vertex1, keys=True) if v2 == vertex2] for key in edges_to_be_split_keys: self.__split_bgedge(BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=None), guidance=guidance, sorted_guidance=sorted_guidance, account_for_colors_multiplicity_in_guidance=account_for_colors_multiplicity_in_guidance, key=ke... |
def split_all_edges_between_two_vertices(self, vertex1, vertex2, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True): """ Splits all edges between two supplied vertices in current :class:`BreakpointGraph` instance with respect to the provided guidance. Proxies a call to :meth:`Breakp... |
def split_all_edges(self, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True): """ Splits all edge in current :class:`BreakpointGraph` instance with respect to the provided guidance. Iterate over all possible distinct pairs of vertices in current :class:`BreakpointGraph` instance and... |
def __delete_all_bgedges_between_two_vertices(self, vertex1, vertex2): """ Deletes all edges between two supplied vertices :param vertex1: a first out of two vertices edges between which are to be deleted :type vertex1: any python hashable object. :class:`bg.vertex.BGVertex` is expected :param vertex2: a second out of ... |
def delete_all_edges_between_two_vertices(self, vertex1, vertex2): """ Deletes all edges between two supplied vertices Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__delete_all_bgedges_between_two_vertices` method. :param vertex1: a first out of two vertices edges between which are to be deleted :type verte... |
def __merge_all_bgedges_between_two_vertices(self, vertex1, vertex2): """ Merges all edge between two supplied vertices into a single edge from a perspective of multi-color merging. :param vertex1: a first out of two vertices edges between which are to be merged together :type vertex1: any python hashable object. :clas... |
self.__add_bgedge(BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=multicolor), merge=True) |
def merge_all_edges_between_two_vertices(self, vertex1, vertex2): """ Merges all edge between two supplied vertices into a single edge from a perspective of multi-color merging. Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__merge_all_bgedges_between_two_vertices` :param vertex1: a first out of two vertices... |
def merge_all_edges(self): """ Merges all edges in a current :class`BreakpointGraph` instance between same pairs of vertices into a single edge from a perspective of multi-color merging. Iterates over all possible pairs of vertices in current :class:`BreakpointGraph` and merges all edges between respective pairs. :retu... |
def merge(cls, breakpoint_graph1, breakpoint_graph2, merge_edges=False): """ Merges two given instances of :class`BreakpointGraph` into a new one, that gather all available information from both supplied objects. Depending of a ``merge_edges`` flag, while merging of two dat structures is occurring, edges between simila... |
all information gathered from both supplied breakpoint graphs :rtype: :class`BreakpointGraph` """ result = cls() for bgedge in breakpoint_graph1.edges(): result.__add_bgedge(bgedge=bgedge, merge=merge_edges) for bgedge in breakpoint_graph2.edges(): result.__add_bgedge(bgedge=bgedge, merge=merge_edges) return result |
def __update(self, breakpoint_graph, merge_edges=False): """ Updates a current :class`BreakpointGraph` object with information from a supplied :class`BreakpointGraph` instance. Depending of a ``merge_edges`` flag, while updating of a current :class`BreakpointGraph` object is occuring, edges between similar vertices can... |
def update(self, breakpoint_graph, merge_edges=False): """ Updates a current :class`BreakpointGraph` object with information from a supplied :class`BreakpointGraph` instance. Proxoes a call to :meth:`BreakpointGraph._BreakpointGraph__update` method. :param breakpoint_graph: a breakpoint graph to extract information fro... |
def apply_kbreak(self, kbreak, merge=True): """ Check validity of supplied k-break and then applies it to current :class:`BreakpointGraph` Only :class:`bg.kbreak.KBreak` (or its heirs) instances are allowed as ``kbreak`` argument. KBreak must correspond to the valid kbreak and, since some changes to its internals might... |
infinity vertices). New edges of specified in kbreak multicolor are added between all pairs of vertices in kbreak.result_edges (except for paired infinity vertices). If after the kbreak application there is an infinity vertex, that now has no edges incident to it, it is deleted form the current :class:`BreakpointGraph`... |
argument") if not KBreak.valid_kbreak_matchings(kbreak.start_edges, kbreak.result_edges): raise ValueError("Supplied KBreak is not valid form perspective of starting/resulting sets of vertices") for vertex1, vertex2 in kbreak.start_edges: if vertex1.is_infinity_vertex and vertex2.is_infinity_vertex: ###################... |
multicolor that is specified for the kbreak # ############################################################################################################ if kbreak.multicolor <= bgedge.multicolor: break else: raise ValueError("Some targeted by kbreak edge with specified multicolor does not exists") for vertex1, vertex... |
if there are edges going to / from it # ############################################################################################################ if len(list(self.get_edges_by_vertex(vertex=vertex))) == 0: self.bg.remove_node(vertex) for vertex1, vertex2 in kbreak.result_edges: if vertex1.is_infinity_vertex and vert... |
def to_json(self, schema_info=True): """ JSON serialization method that account for all information-wise important part of breakpoint graph """ genomes = set() result = {} result["edges"] = [] for bgedge in self.edges(): genomes |= bgedge.multicolor.colors result["edges"].append(bgedge.to_json(schema_info=schema_info))... |
def from_json(cls, data, genomes_data=None, genomes_deserialization_required=True, merge=False): """ A JSON deserialization operation, that recovers a breakpoint graph from its JSON representation as information about genomes, that are encoded in breakpoint graph might be available somewhere else, but not the json obje... |
breakpoint graph deserialization. No \"genomes\" information found") for g_dict in source: ############################################################################################################ # # if explicitly specified in genome json object, it can be decoded using provided schema name, # of course a decoding ... |
############################################################################################################ # # if explicitly specified in vertex json object, it can be decoded using provided schema name, # of course a decoding breakpoint graph object shall be aware of such scheme # (it has to be specified in the `ver... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.