Search is not available for this dataset
text
stringlengths
75
104k
def range(self, key, size=None, unique=True): """Returns a generator of nodes' configuration available in the continuum/ring. :param key: the key to look for. :param size: limit the list to at most this number of nodes. :param unique: a node may only appear once in the list (def...
def patch_memcache(): """Monkey patch python-memcached to implement our consistent hashring in its node selection and operations. """ def _init(self, servers, *k, **kw): self._old_init(servers, *k, **kw) nodes = {} for server in self.servers: conf = { ...
def _create_ring(self, nodes): """Generate a ketama compatible continuum/ring. """ for node_name, node_conf in nodes: for w in range(0, node_conf['vnodes'] * node_conf['weight']): self._distribution[node_name] += 1 self._ring[self.hashi('%s-%s' % (node...
def _remove_node(self, node_name): """Remove the given node from the continuum/ring. :param node_name: the node name. """ try: node_conf = self._nodes.pop(node_name) except Exception: raise KeyError('node \'{}\' not found, available nodes: {}'.format( ...
def hashi(self, key, replica=0): """Returns a ketama compatible hash from the given key. """ dh = self._listbytes(md5(str(key).encode('utf-8')).digest()) rd = replica * 4 return ( (dh[3 + rd] << 24) | (dh[2 + rd] << 16) | (dh[1 + rd] << 8) | dh[0 + rd])
def _hashi_weight_generator(self, node_name, node_conf): """Calculate the weight factor of the given node and yield its hash key for every configured replica. :param node_name: the node name. """ ks = (node_conf['vnodes'] * len(self._nodes) * node_conf['weight']) /...
def _create_ring(self, nodes): """Generate a ketama compatible continuum/ring. """ _weight_sum = 0 for node_conf in self._nodes.values(): _weight_sum += node_conf['weight'] self._weight_sum = _weight_sum _distribution = Counter() _keys = [] _r...
def _remove_node(self, node_name): """Remove the given node from the continuum/ring. :param node_name: the node name. """ try: self._nodes.pop(node_name) except Exception: raise KeyError('node \'{}\' not found, available nodes: {}'.format( ...
def get_numpy_status(): """ Returns a dictionary containing a boolean specifying whether NumPy is up-to-date, along with the version string (empty string if not installed). """ numpy_status = {} try: import numpy numpy_version = numpy.__version__ numpy_status['up_to_d...
def lapmod(n, cc, ii, kk, fast=True, return_cost=True, fp_version=FP_DYNAMIC): """Solve sparse linear assignment problem using Jonker-Volgenant algorithm. n: number of rows of the assignment cost matrix cc: 1D array of all finite elements of the assignement cost matrix ii: 1D array of indice...
def register_provider(cls, provider): """Register method to keep list of providers.""" def decorator(subclass): """Register as decorator function.""" cls._providers[provider] = subclass subclass.name = provider return subclass return decorator
def tar_to_bigfile(self, fname, outfile): """Convert tar of multiple FASTAs to one file.""" fnames = [] tmpdir = mkdtemp() # Extract files to temporary directory with tarfile.open(fname) as tar: tar.extractall(path=tmpdir) for root, _, files in os.wal...
def download_genome(self, name, genome_dir, localname=None, mask="soft", regex=None, invert_match=False, version=None): """ Download a (gzipped) genome file to a specific directory Parameters ---------- name : str Genome / species name genome_dir : s...
def find_plugins(): """Locate and initialize all available plugins. """ plugin_dir = os.path.dirname(os.path.realpath(__file__)) plugin_dir = os.path.join(plugin_dir, "plugins") plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith(".py")] sys.path.insert(0, plugin_dir) for p...
def convert(name): """Convert CamelCase to underscore Parameters ---------- name : str Camelcase string Returns ------- name : str Converted name """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def init_plugins(): """Return dictionary of available plugins Returns ------- plugins : dictionary key is plugin name, value Plugin object """ find_plugins() d = {} for c in Plugin.__subclasses__(): ins = c() if ins.name() in config.get("plugin", []): ...
def activate(name): """Activate plugin. Parameters ---------- name : str Plugin name. """ if name in plugins: plugins[name].activate() else: raise Exception("plugin {} not found".format(name))
def deactivate(name): """Deactivate plugin. Parameters ---------- name : str Plugin name. """ if name in plugins: plugins[name].deactivate() else: raise Exception("plugin {} not found".format(name))
def manage_config(cmd, *args): """Manage genomepy config file.""" if cmd == "file": print(config.config_file) elif cmd == "show": with open(config.config_file) as f: print(f.read()) elif cmd == "generate": fname = os.path.join( user_config_dir("genomep...
def list_available_genomes(provider=None): """ List all available genomes. Parameters ---------- provider : str, optional List genomes from specific provider. Genomes from all providers will be returned if not specified. Returns ------- list with genome names """ ...
def list_installed_genomes(genome_dir=None): """ List all available genomes. Parameters ---------- genome_dir : str Directory with installed genomes. Returns ------- list with genome names """ if not genome_dir: genome_dir = config.get("genome_dir", None) if...
def search(term, provider=None): """ Search for a genome. If provider is specified, search only that specific provider, else search all providers. Both the name and description are used for the search. Seacrch term is case-insensitive. Parameters ---------- term : str Sear...
def install_genome(name, provider, version=None, genome_dir=None, localname=None, mask="soft", regex=None, invert_match=False, annotation=False): """ Install a genome. Parameters ---------- name : str Genome name provider : str Provider name version : str Version (...
def _weighted_selection(l, n): """ Selects n random elements from a list of (weight, item) tuples. Based on code snippet by Nick Johnson """ cuml = [] items = [] total_weight = 0.0 for weight, item in l: total_weight += weight cuml.append(total_weight) it...
def generate_exports(): """Print export commands for setting environment variables. """ env = [] for name in list_installed_genomes(): try: g = Genome(name) env_name = re.sub(r'[^\w]+', "_", name).upper() env.append("export {}={}".format(env_name, g.filename)) except: p...
def generate_env(fname=None): """Generate file with exports. By default this is in .config/genomepy/exports.txt. Parameters ---------- fname: strs, optional Name of the output file. """ config_dir = user_config_dir("genomepy") if os.path.exists(config_dir): fname = os....
def manage_plugins(command, plugin_names=None): """Enable or disable plugins. """ if plugin_names is None: plugin_names = [] active_plugins = config.get("plugin", []) plugins = init_plugins() if command == "enable": for name in plugin_names: if name not in plugins: ...
def gap_sizes(self): """Return gap sizes per chromosome. Returns ------- gap_sizes : dict a dictionary with chromosomes as key and the total number of Ns as values """ if not self._gap_sizes: gap_file = self.props["gaps"]["gap...
def get_random_sequences(self, n=10, length=200, chroms=None, max_n=0.1): """Return random genomic sequences. Parameters ---------- n : int , optional Number of sequences to return. length : int , optional Length of sequences to return. chroms :...
def search(term, provider=None): """Search for genomes that contain TERM in their name or description.""" for row in genomepy.search(term, provider): print("\t".join([x.decode('utf-8', 'ignore') for x in row]))
def install(name, provider, genome_dir, localname, mask, regex, match, annotation): """Install genome NAME from provider PROVIDER in directory GENOME_DIR.""" genomepy.install_genome( name, provider, genome_dir=genome_dir, localname=localname, mask=mask, regex=regex, invert_match=not(mat...
def generate_gap_bed(fname, outname): """ Generate a BED file with gap locations. Parameters ---------- fname : str Filename of input FASTA file. outname : str Filename of output BED file. """ f = Fasta(fname) with open(outname, "w") as bed: for chrom in f.keys...
def generate_sizes(name, genome_dir): """Generate a sizes file with length of sequences in FASTA file.""" fa = os.path.join(genome_dir, name, "{}.fa".format(name)) sizes = fa + ".sizes" g = Fasta(fa) with open(sizes, "w") as f: for seqname in g.keys(): f.write("{}\t{}\n".format(s...
def filter_fasta(infa, outfa, regex=".*", v=False, force=False): """Filter fasta file based on regex. Parameters ---------- infa : str Filename of input fasta file. outfa : str Filename of output fasta file. Cannot be the same as infa. regex : str, optional Regular...
def cmd_ok(cmd): """Returns True if cmd can be run. """ try: sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE) except sp.CalledProcessError: # bwa gives return code of 1 with no argument pass except: sys.stderr.write("{} not found, skipping\n".format(cmd)) r...
def run_index_cmd(name, cmd): """Run command, show errors if the returncode is non-zero.""" sys.stderr.write("Creating {} index...\n".format(name)) # Create index p = sp.Popen(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE) stdout, stderr = p.communicate() if p.returncode != 0: sys.stde...
def scan_cgroups(subsys_name, filters=list()): """ It returns a control group hierarchy which belong to the subsys_name. When collecting cgroups, filters are applied to the cgroups. See pydoc of apply_filters method of CGroup for more information about the filters. """ status = SubsystemStatus()...
def walk_cgroups(cgroup, action, opaque): """ The function applies the action function with the opaque object to each control group under the cgroup recursively. """ action(cgroup, opaque) for child in cgroup.childs: walk_cgroups(child, action, opaque)
def get_cgroup(fullpath): """ It returns a CGroup object which is pointed by the fullpath. """ # Canonicalize symbolic links fullpath = os.path.realpath(fullpath) status = SubsystemStatus() name = None for name, path in status.paths.items(): if path in fullpath: brea...
def _parse_proc_cgroups(self): """Parse /proc/cgroups""" """ #subsys_name hierarchy num_cgroups enabled cpuset 0 1 1 ns 0 1 1 cpu 1 10 1 cpuacct 0 1 1 memory 0 1 1 devices 0 1 1 freezer 0 1 1 net_cls 0 1 1 """ for l...
def _parse_proc_mount(self): """Parse /proc/mounts""" """ cgroup /cgroup/cpu cgroup rw,relatime,cpuacct,cpu,release_agent=/sbin/cgroup_clean 0 0 cgroup /cgroup/memory cgroup rw,relatime,memory 0 0 cgroup /cgroup/blkio cgroup rw,relatime,blkio 0 0 cgroup /cgroup/freezer c...
def parse(content): """ Parse rdma.curren and rdma.max Example contents: mlx4_0 hca_handle=2 hca_object=2000 ocrdma1 hca_handle=3 hca_object=max >>> RdmaStat.parse("mlx4_0 hca_handle=2 hca_object=2000\\nocrdma1 hca_handle=3 hca_object=max") {'mlx4_0': {'hca_handle':...
def apply_filters(self, filters): """ It applies a specified filters. The filters are used to reduce the control groups which are accessed by get_confgs, get_stats, and get_defaults methods. """ _configs = self.configs _stats = self.stats self.configs = {} ...
def get_configs(self): """ It returns a name and a current value pairs of control files which are categorised in the configs group. """ configs = {} for name, default in self.configs.items(): cls = default.__class__ path = self.paths[name] ...
def get_stats(self): """ It returns a name and a value pairs of control files which are categorised in the stats group. """ stats = {} for name, cls in self.stats.items(): path = self.paths[name] if os.path.exists(path): try: ...
def update(self): """It updates process information of the cgroup.""" pids = fileops.readlines(self.paths['cgroup.procs']) self.pids = [int(pid) for pid in pids if pid != ''] self.n_procs = len(pids)
def register(self, arguments=list()): """ Register a target file with arguments (if required) to a event_control file which we want to be notified events. """ target_name = self.target_name if target_name in ['memory.usage_in_bytes', 'memory.memsw.usage_in_bytes']: ...
def wait(self): """ It returns when an event which we have configured by set_threshold happens. Note that it blocks until then. """ ret = os.read(self.event_fd, 64 / 8) return struct.unpack('Q', ret)
def _build_process_container_tree(self, pids): """ tops = [1,2,3] childs = {1: [4,5], 2: [6,7], 3: [], 4: []} """ containers = [] procs = [] ppids = [] childs = {} for pid in pids: proc = process.Process(pid) procs.append(pr...
def loads(data, conf=True): """ Load an nginx configuration from a provided string. :param str data: nginx configuration :param bool conf: Load object(s) into a Conf object? """ f = Conf() if conf else [] lopen = [] index = 0 while True: m = re.compile(r'^\s*events\s*{', re...
def dumpf(obj, path): """ Write an nginx configuration to file. :param obj obj: nginx object (Conf, Server, Container) :param str path: path to nginx configuration on disk :returns: path the configuration was written to """ with open(path, 'w') as f: dump(obj, f) return path
def remove(self, *args): """ Remove object(s) from the Conf. :param *args: Any objects to remove from the Conf. :returns: full list of Conf's child objects """ for x in args: self.children.remove(x) return self.children
def filter(self, btype='', name=''): """ Return child object(s) of this Conf that satisfy certain criteria. :param str btype: Type of object to filter by (e.g. 'Key') :param str name: Name of key OR container value to filter by :returns: full list of matching child objects ...
def as_strings(self): """Return the entire Conf as nginx config strings.""" ret = [] for x in self.children: if isinstance(x, (Key, Comment)): ret.append(x.as_strings) else: for y in x.as_strings: ret.append(y) i...
def add(self, *args): """ Add object(s) to the Container. :param *args: Any objects to add to the Container. :returns: full list of Container's child objects """ self.children.extend(args) bump_child_depth(self, self._depth) return self.children
def as_list(self): """Return all child objects in nested lists of strings.""" return [self.name, self.value, [x.as_list for x in self.children]]
def as_dict(self): """Return all child objects in nested dict.""" dicts = [x.as_dict for x in self.children] return {'{0} {1}'.format(self.name, self.value): dicts}
def as_strings(self): """Return the entire Container as nginx config strings.""" ret = [] container_title = (INDENT * self._depth) container_title += '{0}{1} {{\n'.format( self.name, (' {0}'.format(self.value) if self.value else '') ) ret.append(container_titl...
def as_strings(self): """Return key as nginx config string.""" if self.value == '' or self.value is None: return '{0};\n'.format(self.name) if '"' not in self.value and (';' in self.value or '#' in self.value): return '{0} "{1}";\n'.format(self.name, self.value) r...
def convert_aws_args(aws_args): """Convert old style options into arguments to boto3.session.Session.""" if not isinstance(aws_args, dict): raise errors.InvalidConfiguration( 'Elastic DocManager config option "aws" must be a dict' ) old_session_kwargs = dict( region="regi...
def run(self): """Periodically sends buffered operations and/or commit. """ if not self._should_auto_commit and not self._should_auto_send: return last_send, last_commit = 0, 0 while not self._stopped: if self._should_auto_commit: if last_c...
def _index_and_mapping(self, namespace): """Helper method for getting the index and type from a namespace.""" index, doc_type = namespace.split(".", 1) return index.lower(), doc_type
def _stream_search(self, *args, **kwargs): """Helper method for iterating over ES search results.""" for hit in scan( self.elastic, query=kwargs.pop("body", None), scroll="10m", **kwargs ): hit["_source"]["_id"] = hit["_id"] yield hit["_source"]
def search(self, start_ts, end_ts): """Query Elasticsearch for documents in a time range. This method is used to find documents that may be in conflict during a rollback event in MongoDB. """ return self._stream_search( index=self.meta_index_name, body={"...
def commit(self): """Send buffered requests and refresh all indexes.""" self.send_buffered_operations() retry_until_ok(self.elastic.indices.refresh, index="")
def add_upsert(self, action, meta_action, doc_source, update_spec): """ Function which stores sources for "insert" actions and decide if for "update" action has to add docs to get source buffer """ # Whenever update_spec is provided to this method # it means that...
def add_doc_to_update(self, action, update_spec, action_buffer_index): """ Prepare document for update based on Elasticsearch response. Set flag if document needs to be retrieved from Elasticsearch """ doc = { "_index": action["_index"], "_type": action["...
def should_get_id(self, action): """ Mark document to retrieve its source from Elasticsearch. Returns: True - if marking document for the first time in this bulk False - if document has been already marked """ mapping_ids = self.doc_to_get.setdefault(actio...
def get_docs_sources_from_ES(self): """Get document sources using MGET elasticsearch API""" docs = [doc for doc, _, _, get_from_ES in self.doc_to_update if get_from_ES] if docs: documents = self.docman.elastic.mget(body={"docs": docs}, realtime=True) return iter(documents...
def update_sources(self): """Update local sources based on response from Elasticsearch""" ES_documents = self.get_docs_sources_from_ES() for doc, update_spec, action_buffer_index, get_from_ES in self.doc_to_update: if get_from_ES: # Update source based on response fr...
def add_to_sources(self, action, doc_source): """Store sources locally""" mapping = self.sources.setdefault(action["_index"], {}).setdefault( action["_type"], {} ) mapping[action["_id"]] = doc_source
def get_from_sources(self, index, doc_type, document_id): """Get source stored locally""" return self.sources.get(index, {}).get(doc_type, {}).get(document_id, {})
def clean_up(self): """Do clean-up before returning buffer""" self.action_buffer = [] self.sources = {} self.doc_to_get = {} self.doc_to_update = []
def get_buffer(self): """Get buffer which needs to be bulked to elasticsearch""" # Get sources for documents which are in Elasticsearch # and they are not in local buffer if self.doc_to_update: self.update_sources() ES_buffer = self.action_buffer self.clean_...
def run(self): """Continously scan for BLE advertisements.""" self.socket = self.bluez.hci_open_dev(self.bt_device_id) filtr = self.bluez.hci_filter_new() self.bluez.hci_filter_all_events(filtr) self.bluez.hci_filter_set_ptype(filtr, self.bluez.HCI_EVENT_PKT) self.socket...
def set_scan_parameters(self, scan_type=ScanType.ACTIVE, interval_ms=10, window_ms=10, address_type=BluetoothAddressType.RANDOM, filter_type=ScanFilter.ALL): """"sets the le scan parameters Args: scan_type: ScanType.(PASSIVE|ACTIVE) interval: ms (as f...
def toggle_scan(self, enable, filter_duplicates=False): """Enables or disables BLE scanning Args: enable: boolean value to enable (True) or disable (False) scanner filter_duplicates: boolean value to enable/disable filter, that omits duplicated packets""" ...
def process_packet(self, pkt): """Parse the packet and call callback if one of the filters matches.""" # check if this could be a valid packet before parsing # this reduces the CPU load significantly if not ( \ ((self.mode & ScannerMode.MODE_IBEACON) and (pkt[19:23] == b"\x4...
def save_bt_addr(self, packet, bt_addr): """Add to the list of mappings.""" if isinstance(packet, EddystoneUIDFrame): # remove out old mapping new_mappings = [m for m in self.eddystone_mappings if m[0] != bt_addr] new_mappings.append((bt_addr, packet.properties)) ...
def get_properties(self, packet, bt_addr): """Get properties of beacon depending on type.""" if is_one_of(packet, [EddystoneTLMFrame, EddystoneURLFrame, \ EddystoneEncryptedTLMFrame, EddystoneEIDFrame]): # here we retrieve the namespace and instance which corres...
def properties_from_mapping(self, bt_addr): """Retrieve properties (namespace, instance) for the specified bt address.""" for addr, properties in self.eddystone_mappings: if addr == bt_addr: return properties return None
def terminate(self): """Signal runner to stop and join thread.""" self.toggle_scan(False) self.keep_going = False self.join()
def data_to_uuid(data): """Convert an array of binary data to the iBeacon uuid format.""" string = data_to_hexstring(data) return string[0:8]+'-'+string[8:12]+'-'+string[12:16]+'-'+string[16:20]+'-'+string[20:32]
def bt_addr_to_string(addr): """Convert a binary string to the hex representation.""" addr_str = array.array('B', addr) addr_str.reverse() hex_str = hexlify(addr_str.tostring()).decode('ascii') # insert ":" seperator between the bytes return ':'.join(a+b for a, b in zip(hex_str[::2], hex_str[1::...
def is_one_of(obj, types): """Return true iff obj is an instance of one of the types.""" for type_ in types: if isinstance(obj, type_): return True return False
def is_packet_type(cls): """Check if class is one the packet types.""" from .packet_types import EddystoneUIDFrame, EddystoneURLFrame, \ EddystoneEncryptedTLMFrame, EddystoneTLMFrame, \ EddystoneEIDFrame, IBeaconAdvertisement, \ ...
def bin_to_int(string): """Convert a one element byte string to signed int for python 2 support.""" if isinstance(string, str): return struct.unpack("b", string)[0] else: return struct.unpack("b", bytes([string]))[0]
def get_mode(device_filter): """Determine which beacons the scanner should look for.""" from .device_filters import IBeaconFilter, EddystoneFilter, BtAddrFilter, EstimoteFilter if device_filter is None or len(device_filter) == 0: return ScannerMode.MODE_ALL mode = ScannerMode.MODE_NONE for ...
def matches(self, filter_props): """Check if the filter matches the supplied properties.""" if filter_props is None: return False found_one = False for key, value in filter_props.items(): if key in self.properties and value != self.properties[key]: ...
def parse_packet(packet): """Parse a beacon advertisement packet.""" frame = parse_ltv_packet(packet) if frame is None: frame = parse_ibeacon_packet(packet) return frame
def parse_ltv_packet(packet): """Parse a tag-length-value style beacon packet.""" try: frame = LTVFrame.parse(packet) for ltv in frame: if ltv['type'] == SERVICE_DATA_TYPE: data = ltv['value'] if data["service_identifier"] == EDDYSTONE_UUID: ...
def parse_eddystone_service_data(data): """Parse Eddystone service data.""" if data['frame_type'] == EDDYSTONE_UID_FRAME: return EddystoneUIDFrame(data['frame']) elif data['frame_type'] == EDDYSTONE_TLM_FRAME: if data['frame']['tlm_version'] == EDDYSTONE_TLM_ENCRYPTED: return Ed...
def parse_estimote_service_data(data): """Parse Estimote service data.""" if data['frame_type'] & 0xF == ESTIMOTE_TELEMETRY_FRAME: protocol_version = (data['frame_type'] & 0xF0) >> 4 if data['frame']['subframe_type'] == ESTIMOTE_TELEMETRY_SUBFRAME_A: return EstimoteTelemetryFrameA(da...
def parse_motion_state(val): """Convert motion state byte to seconds.""" number = val & 0b00111111 unit = (val & 0b11000000) >> 6 if unit == 1: number *= 60 # minutes elif unit == 2: number *= 60 * 60 # hours elif unit == 3 and number < 32: ...
def scan_codes(code_types, image): """ Get *code_type* codes from a PIL Image. *code_type* can be any of zbar supported code type [#zbar_symbologies]_: - **EAN/UPC**: EAN-13 (`ean13`), UPC-A (`upca`), EAN-8 (`ean8`) and UPC-E (`upce`) - **Linear barcode**: Code 128 (`code128`), Code 93 (`code93`),...
def copy_image_on_background(image, color=WHITE): """ Create a new image by copying the image on a *color* background. Args: image (PIL.Image.Image): Image to copy color (tuple): Background color usually WHITE or BLACK Returns: PIL.Image.Image """ background = Image.ne...
def monkey_patch(cls): """Monkey path zbarlight C extension on Read The Docs""" on_read_the_docs = os.environ.get('READTHEDOCS', False) if on_read_the_docs: sys.modules['zbarlight._zbarlight'] = cls
def fill(framebuf, color): """completely fill/clear the buffer with a color""" if color: fill = 0xFF else: fill = 0x00 for i in range(len(framebuf.buf)): framebuf.buf[i] = fill
def fill_rect(framebuf, x, y, width, height, color): """Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws both the outline and interior.""" # pylint: disable=too-many-arguments for _x in range(x, x+width): offset = 7 - _x & 0x07 ...
def set_pixel(framebuf, x, y, color): """Set a given pixel to a color.""" index = (y >> 3) * framebuf.stride + x offset = y & 0x07 framebuf.buf[index] = (framebuf.buf[index] & ~(0x01 << offset)) | ((color != 0) << offset)