text
stringlengths
18
773k
def create(self, key, value): """Atomically create the given key only if the key doesn't exist. This verifies that the create_revision of a key equales to 0, then creates the key with the value. This operation takes place in a transaction. :param key: key in etcd to create ...
def put(self, key, value, lease=None): """Put puts the given key into the key-value store. A put request increments the revision of the key-value store and generates one event in the event history. :param key: :param value: :param lease: :return: boolean ...
def get(self, key, metadata=False, sort_order=None, sort_target=None, **kwargs): """Range gets the keys in the range from the key-value store. :param key: :param metadata: :param sort_order: 'ascend' or 'descend' or None :param sort_target: 'key' or 'version' or 'cre...
def get_all(self, sort_order=None, sort_target='key'): """Get all keys currently stored in etcd. :returns: sequence of (value, metadata) tuples """ return self.get( key=_encode(b'\0'), metadata=True, sort_order=sort_order, sort_target=sort...
def get_prefix(self, key_prefix, sort_order=None, sort_target=None): """Get a range of keys with a prefix. :param sort_order: 'ascend' or 'descend' or None :param key_prefix: first key in range :returns: sequence of (value, metadata) tuples """ return self.get(key_prefi...
def replace(self, key, initial_value, new_value): """Atomically replace the value of a key with a new value. This compares the current value of a key, then replaces it with a new value if it is equal to a specified value. This operation takes place in a transaction. :param key:...
def delete(self, key, **kwargs): """DeleteRange deletes the given range from the key-value store. A delete request increments the revision of the key-value store and generates a delete event in the event history for every deleted key. :param key: :param kwargs: :return:...
def delete_prefix(self, key_prefix): """Delete a range of keys with a prefix in etcd.""" return self.delete( key_prefix, range_end=_encode(_increment_last_byte(key_prefix)))
def transaction(self, txn): """Txn processes multiple requests in a single transaction. A txn request increments the revision of the key-value store and generates events with the same revision for every completed request. It is not allowed to modify the same key several times within one...
def watch(self, key, **kwargs): """Watch a key. :param key: key to watch :returns: tuple of ``events_iterator`` and ``cancel``. Use ``events_iterator`` to get the events of key changes and ``cancel`` to cancel the watch request """ event_queu...
def watch_prefix(self, key_prefix, **kwargs): """The same as ``watch``, but watches a range of keys with a prefix.""" kwargs['range_end'] = \ _increment_last_byte(key_prefix) return self.watch(key_prefix, **kwargs)
def watch_once(self, key, timeout=None, **kwargs): """Watch a key and stops after the first event. :param key: key to watch :param timeout: (optional) timeout in seconds. :returns: event """ event_queue = queue.Queue() def callback(event): event_queu...
def watch_prefix_once(self, key_prefix, timeout=None, **kwargs): """Watches a range of keys with a prefix, similar to watch_once""" kwargs['range_end'] = \ _increment_last_byte(key_prefix) return self.watch_once(key_prefix, timeout=timeout, **kwargs)
def create_timer(cb: Callable[[float], None], interval: float, delay_policy: TimerDelayPolicy = TimerDelayPolicy.DEFAULT, loop: Optional[asyncio.BaseEventLoop] = None) -> asyncio.Task: ''' Schedule a timer with the given callable and the interval in seconds. The interval va...
def revoke(self): """LeaseRevoke revokes a lease. All keys attached to the lease will expire and be deleted. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the respon...
def ttl(self): """LeaseTimeToLive retrieves lease information. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. :return: """ result = sel...
def keys(self): """Get the keys associated with this lease. :return: """ result = self.client.post(self.client.get_url("/kv/lease/timetolive"), json={"ID": self.id, "keys": True}) keys = result['keys'] if ...
def apartial(coro, *args, **kwargs): ''' Wraps a coroutine function with pre-defined arguments (including keyword arguments). It is an asynchronous version of :func:`functools.partial`. ''' @functools.wraps(coro) async def wrapped(*cargs, **ckwargs): return await coro(*args, *cargs, **...
def lru_cache(maxsize: int = 128, typed: bool = False, expire_after: float = None): ''' A simple LRU cache just like :func:`functools.lru_cache`, but it works for coroutines. This is not as heavily optimized as :func:`functools.lru_cache` which uses an internal C implementat...
def get_services(self): """ get_services makes call to services end point of api.embed.ly to fetch the list of supported providers and their regexes """ if self.services: return self.services url = 'http://api.embed.ly/1/services/python' http = http...
def _get(self, version, method, url_or_urls, **kwargs): """ _get makes the actual call to api.embed.ly """ if not url_or_urls: raise ValueError('%s requires a url or a list of urls given: %s' % (method.title(), url_or_urls)) # a flag we c...
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. From django.utils.encoding.py in 1.4.2+, minus the dependency on Six. To support Python 2 and 3 with a single code base, define a __str__ method ...
def _encode(data): """Encode the given data using base-64 :param data: :return: base-64 encoded string """ if not isinstance(data, bytes_types): data = six.b(str(data)) return base64.b64encode(data).decode("utf-8")
def _decode(data): """Decode the base-64 encoded string :param data: :return: decoded data """ if not isinstance(data, bytes_types): data = six.b(str(data)) return base64.b64decode(data.decode("utf-8"))
def _increment_last_byte(data): """Get the last byte in the array and increment it :param bytes_string: :return: """ if not isinstance(data, bytes_types): if isinstance(data, six.string_types): data = data.encode('utf-8') else: data = six.b(str(data)) s =...
def metadata(self): """Return dict representation of this cookbook's metadata.rb .""" self.metadata_path = os.path.join(self.path, 'metadata.rb') if not os.path.isfile(self.metadata_path): raise ValueError("Cookbook needs metadata.rb, %s" % self.metadata_...
def berksfile(self): """Return this cookbook's Berksfile instance.""" self.berks_path = os.path.join(self.path, 'Berksfile') if not self._berksfile: if not os.path.isfile(self.berks_path): raise ValueError("No Berksfile found at %s" % ...
def from_dict(cls, dictionary): """Create a MetadataRb instance from a dict.""" cookbooks = set() # put these in order groups = [cookbooks] for key, val in dictionary.items(): if key == 'depends': cookbooks.update({cls.depends_statement(cbn, meta) ...
def depends_statement(cookbook_name, metadata=None): """Return a valid Ruby 'depends' statement for the metadata.rb file.""" line = "depends '%s'" % cookbook_name if metadata: if not isinstance(metadata, dict): raise TypeError("Stencil dependency options for %s " ...
def parse(self): """Parse the metadata.rb into a dict.""" data = utils.ruby_lines(self.readlines()) data = [tuple(j.strip() for j in line.split(None, 1)) for line in data] depends = {} for line in data: if not len(line) == 2: continue ...
def merge(self, other): """Add requirements from 'other' metadata.rb into this one.""" if not isinstance(other, MetadataRb): raise TypeError("MetadataRb to merge should be a 'MetadataRb' " "instance, not %s.", type(other)) current = self.to_dict() ...
def parse(self): """Parse this Berksfile into a dict.""" self.flush() self.seek(0) data = utils.ruby_lines(self.readlines()) data = [tuple(j.strip() for j in line.split(None, 1)) for line in data] datamap = {} for line in data: if len(l...
def from_dict(cls, dictionary): """Create a Berksfile instance from a dict.""" cookbooks = set() sources = set() other = set() # put these in order groups = [sources, cookbooks, other] for key, val in dictionary.items(): if key == 'cookbook': ...
def cookbook_statement(cookbook_name, metadata=None): """Return a valid Ruby 'cookbook' statement for the Berksfile.""" line = "cookbook '%s'" % cookbook_name if metadata: if not isinstance(metadata, dict): raise TypeError("Berksfile dependency hash for %s " ...
def merge(self, other): """Add requirements from 'other' Berksfile into this one.""" if not isinstance(other, Berksfile): raise TypeError("Berksfile to merge should be a 'Berksfile' " "instance, not %s.", type(other)) current = self.to_dict() new =...
def manifest(self): """The manifest definition of the stencilset as a dict.""" if not self._manifest: with open(self.manifest_path) as man: self._manifest = json.load(man) return self._manifest
def stencils(self): """List of stencils.""" if not self._stencils: self._stencils = self.manifest['stencils'] return self._stencils
def get_stencil(self, stencil_name, **options): """Return a Stencil instance given a stencil name.""" if stencil_name not in self.manifest.get('stencils', {}): raise ValueError("Stencil '%s' not declared in StencilSet " "manifest." % stencil_name) stencil...
def _determine_selected_stencil(stencil_set, stencil_definition): """Determine appropriate stencil name for stencil definition. Given a fastfood.json stencil definition with a stencil set, figure out what the name of the stencil within the set should be, or use the default """ if 'stencil' not in s...
def _build_template_map(cookbook, cookbook_name, stencil): """Build a map of variables for this generated cookbook and stencil. Get template variables from stencil option values, adding the default ones like cookbook and cookbook year. """ template_map = { 'cookbook': {"name": cookbook_name...
def _render_binaries(files, written_files): """Write binary contents from filetable into files. Using filetable for the input files, and the list of files, render all the templates into actual files on disk, forcing to overwrite the file as appropriate, and using the given open mode for the file. "...
def _render_templates(files, filetable, written_files, force, open_mode='w'): """Write template contents from filetable into files. Using filetable for the rendered templates, and the list of files, render all the templates into actual files on disk, forcing to overwrite the file as appropriate, and us...
def build_cookbook(build_config, templatepack_path, cookbooks_home, force=False): """Build a cookbook from a fastfood.json file. Can build on an existing cookbook, otherwise this will create a new cookbook for you based on your templatepack. """ with open(build_config) as cfg: ...
def process_stencil(cookbook, cookbook_name, template_pack, force_argument, stencil_set, stencil, written_files): """Process the stencil requested, writing any missing files as needed. The stencil named 'stencilset_name' should be one of templatepack's stencils. """ # force can ...
def create_new_cookbook(cookbook_name, cookbooks_home): """Create a new cookbook. :param cookbook_name: Name of the new cookbook. :param cookbooks_home: Target dir for new cookbook. """ cookbooks_home = utils.normalize_path(cookbooks_home) if not os.path.exists(cookbooks_home): raise V...
def ruby_lines(text): """Tidy up lines from a file, honor # comments. Does not honor ruby block comments (yet). """ if isinstance(text, basestring): text = text.splitlines() elif not isinstance(text, list): raise TypeError("text should be a list or a string, not %s" ...
def deepupdate(original, update, levels=5): """Update, like dict.update, but deeper. Update 'original' from dict/iterable 'update'. I.e., it recurses on dicts 'levels' times if necessary. A standard dict.update is levels=0 """ if not isinstance(update, dict): update = dict(update) ...
def write_statements(self, statements): """Insert the statements into the file neatly. Ex: statements = ["good 'dog'", "good 'cat'", "bad 'rat'", "fat 'emu'"] # stream.txt ... animals = FileWrapper(open('stream.txt')) good 'cow' nice 'man' bad 'news' ...
def _fastfood_build(args): """Run on `fastfood build`.""" written_files, cookbook = food.build_cookbook( args.config_file, args.template_pack, args.cookbooks, args.force) if len(written_files) > 0: print("%s: %s files written" % (cookbook, len...
def _fastfood_list(args): """Run on `fastfood list`.""" template_pack = pack.TemplatePack(args.template_pack) if args.stencil_set: stencil_set = template_pack.load_stencil_set(args.stencil_set) print("Available Stencils for %s:" % args.stencil_set) for stencil in stencil_set.stencils...
def _fastfood_show(args): """Run on `fastfood show`.""" template_pack = pack.TemplatePack(args.template_pack) if args.stencil_set: stencil_set = template_pack.load_stencil_set(args.stencil_set) print("Stencil Set %s:" % args.stencil_set) print(' Stencils:') for stencil in st...
def _release_info(): """Check latest fastfood release info from PyPI.""" pypi_url = 'http://pypi.python.org/pypi/fastfood/json' headers = { 'Accept': 'application/json', } request = urllib.Request(pypi_url, headers=headers) response = urllib.urlopen(request).read().decode('utf_8') da...
def getenv(option_name, default=None): """Return the option from the environment in the FASTFOOD namespace.""" env = "%s_%s" % (NAMESPACE.upper(), option_name.upper()) return os.environ.get(env, default)
def main(argv=None): """fastfood command line interface.""" # pylint: disable=missing-docstring import argparse import traceback class HelpfulParser(argparse.ArgumentParser): def error(self, message, print_help=False): if 'too few arguments' in message: sys.argv....
def get_friendly_title(err): """Turn class, instance, or name (str) into an eyeball-friendly title. E.g. FastfoodStencilSetNotListed --> 'Stencil Set Not Listed' """ if isinstance(err, basestring): string = err else: try: string = err.__name__ except AttributeErr...
def _validate(self, key, cls=None): """Verify the manifest schema.""" if key not in self.manifest: raise ValueError("Manifest %s requires '%s'." % (self.manifest_path, key)) if cls: if not isinstance(self.manifest[key], cls): r...
def stencil_sets(self): """List of stencil sets.""" if not self._stencil_sets: self._stencil_sets = self.manifest['stencil_sets'] return self._stencil_sets
def load_stencil_set(self, stencilset_name): """Return the Stencil Set from this template pack.""" if stencilset_name not in self._stencil_sets: if stencilset_name not in self.manifest['stencil_sets'].keys(): raise exc.FastfoodStencilSetNotListed( "Stencil...
def qstring(option): """Custom quoting method for jinja.""" if (re.match(NODE_ATTR_RE, option) is None and re.match(CHEF_CONST_RE, option) is None): return "'%s'" % option else: return option
def render_templates_generator(*files, **template_map): """Render jinja templates according to template_map. Yields (path, result) """ for path in files: if not os.path.isfile(path): raise ValueError("Template file %s not found" % os.path.relpath(path)) ...
def generate(self, model, outfolder): """ Generate artifacts for given model. Attributes: model: Model for which to generate code. outfolder: Folder where code files are created. """ _logger.info('Generating code t...
def run(self, element, outfolder): """Apply this task to model element.""" filepath = self.relative_path_for_element(element) if outfolder and not os.path.isabs(filepath): filepath = os.path.join(outfolder, filepath) _logger.debug('{!r} --> {!r}'.format(element, filepath)) ...
def create_template_context(self, element, **kwargs): """Code generation context, specific to template and current element.""" context = dict(element=element, **kwargs) if self.global_context: context.update(**self.global_context) return context
def _validated(self, value): """Format the value or raise a :exc:`ValidationError` if an error occurs.""" if value is None: return None if isinstance(value, bson.ObjectId): return value try: return bson.ObjectId(value) except (ValueError, Attri...
def create_environment(self, **kwargs): """ Return a new Jinja environment. Derived classes may override method to pass additional parameters or to change the template loader type. """ return jinja2.Environment( loader=jinja2.FileSystemLoader(self.tem...
def pairs(a): """Return array of pairs of adjacent elements in a. >>> pairs([1, 2, 3, 4]) array([[1, 2], [2, 3], [3, 4]]) """ a = np.asarray(a) return as_strided(a, shape=(a.size - 1, 2), strides=a.strides * 2)
def transcript_sort_key(transcript): """ Key function used to sort transcripts. Taking the negative of protein sequence length and nucleotide sequence length so that the transcripts with longest sequences come first in the list. This couldn't be accomplished with `reverse=True` since we're also sort...
def best_transcript(transcripts): """ Given a set of coding transcripts, choose the one with the longest protein sequence and in cases of ties use the following tie-breaking criteria: - transcript sequence (including UTRs) - transcript name (so TP53-001 should come before TP53-202) "...
def predict_epitopes_from_args(args): """ Returns an epitope collection from the given commandline arguments. Parameters ---------- args : argparse.Namespace Parsed commandline arguments for Topiary """ mhc_model = mhc_binding_predictor_from_args(args) variants = variant_collect...
def get_random_word(dictionary, min_word_length=3, max_word_length=8): """ Returns a random word from the dictionary """ while True: # Choose a random word word = choice(dictionary) # Stop looping as soon as we have a valid candidate if len(word) >= min_word_length a...
def pw(min_word_length=3, max_word_length=8, max_int_value=1000, number_of_elements=4, no_special_characters=False): """ Generate a password """ # Set the position of the integer int_position = set_int_position(number_of_elements) # Load dictionary dictionary = load_dictionary() p...
def main(): """ Main method """ # Options global args parser = argparse.ArgumentParser() parser.add_argument("-n", "--min_word_length", type=int, help="Minimum length for each word", default=3) parser.add_argument("-x", "--max_word_length", type=int, ...
def protein_subsequences_around_mutations(effects, padding_around_mutation): """ From each effect get a mutant protein sequence and pull out a subsequence around the mutation (based on the given padding). Returns a dictionary of subsequences and a dictionary of subsequence start offsets. """ pro...
def check_padding_around_mutation(given_padding, epitope_lengths): """ If user doesn't provide any padding around the mutation we need to at least include enough of the surrounding non-mutated esidues to construct candidate epitopes of the specified lengths. """ min_required_padding = max(epitop...
def peptide_mutation_interval( peptide_start_in_protein, peptide_length, mutation_start_in_protein, mutation_end_in_protein): """ Half-open interval of mutated residues in the peptide, determined from the mutation interval in the original protein sequence. Parameters ...
def from_dict(cls, indicator): """ Create an indicator object from a dictionary. :param indicator: The dictionary. :return: The indicator object. """ tags = indicator.get('tags') if tags is not None: tags = [Tag.from_dict(tag) for tag in tags] ...
def to_dict(self, remove_nones=False): """ Creates a dictionary representation of the indicator. :param remove_nones: Whether ``None`` values should be filtered out of the dictionary. Defaults to ``False``. :return: A dictionary representation of the indicator. """ if ...
def filter_false_positive(df, process_time): """ method that takes in FireEye (FE) alerts and filters FE-tests and False Positives :param process_time: :param df: :return: """ result = [] track = [] count = 0 for o in df['alerts']: count += 1 if 'closedState' in o...
def filter_webapp_attack(df, process_time): """ A function that filters out the BASH SHELLSHOCK alert data obtained from FireEye :param df: a DataFrame object :param process_time: :return: """ result = [] track = [] for o in df: if 'METHODOLOGY - WEB APP ATTACK' in o['message...
def process_alert(file_name): """ A function that removes the alerts property from the FireEye alert and transform the data into a JSON ready format :param file_name: :return: """ processed_line = open(file_name, 'r').read() char_pos = processed_line.find("}") new_line = "{" + processed...
def apply_filter( filter_fn, collection, result_fn=None, filter_name="", collection_name=""): """ Apply filter to effect collection and print number of dropped elements Parameters ---------- """ n_before = len(collection) filtered = [x for x in collec...
def filter_silent_and_noncoding_effects(effects): """ Keep only variant effects which result in modified proteins. Parameters ---------- effects : varcode.EffectCollection """ return apply_filter( filter_fn=lambda effect: isinstance(effect, NonsilentCodingMutation), collecti...
def apply_variant_expression_filters( variants, gene_expression_dict, gene_expression_threshold, transcript_expression_dict, transcript_expression_threshold): """ Filter a collection of variants by gene and transcript expression thresholds Parameters ---------- ...
def apply_effect_expression_filters( effects, gene_expression_dict, gene_expression_threshold, transcript_expression_dict, transcript_expression_threshold): """ Filter collection of varcode effects by given gene and transcript expression thresholds. Parameters ...
def submit_indicators(self, indicators, enclave_ids=None, tags=None): """ Submit indicators directly. The indicator field ``value`` is required; all other metadata fields are optional: ``firstSeen``, ``lastSeen``, ``sightings``, ``notes``, and ``source``. The submission must specify enclaves fo...
def get_indicators(self, from_time=None, to_time=None, enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None, start_page=0, page_size=None): """ Creates a generator from the |get_indicators_page| method that returns each successive indicator as an ...
def _get_indicators_page_generator(self, from_time=None, to_time=None, page_number=0, page_size=None, enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None): """ Creates a generator from the |get_indicators_page| method that returns each successive page. ...
def get_indicators_page(self, from_time=None, to_time=None, page_number=None, page_size=None, enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None): """ Get a page of indicators matching the provided filters. :param int from_time: start of time window in mi...
def search_indicators(self, search_term=None, enclave_ids=None, from_time=None, to_time=None, indicator_types=None, tags=None, excluded_tags=None): """ ...
def _search_indicators_page_generator(self, search_term=None, enclave_ids=None, from_time=None, to_time=None, indicator_types=None, ...
def search_indicators_page(self, search_term=None, enclave_ids=None, from_time=None, to_time=None, indicator_types=None, tags=None, ex...
def get_related_indicators(self, indicators=None, enclave_ids=None): """ Uses the |get_related_indicators_page| method to create a generator that returns each successive report. :param list(string) indicators: list of indicator values to search for :param list(string) enclave_ids: list ...
def get_indicator_metadata(self, value): """ Provide metadata associated with a single indicators, including value, indicatorType, noteCount, sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has READ access to. ...
def get_indicators_metadata(self, indicators): """ Provide metadata associated with an list of indicators, including value, indicatorType, noteCount, sightings, lastSeen, enclaveIds, and tags. The metadata is determined based on the enclaves the user making the request has READ access to...
def get_indicator_details(self, indicators, enclave_ids=None): """ NOTE: This method uses an API endpoint that is intended for internal use only, and is not officially supported. Provide a list of indicator values and obtain details for all of them, including indicator_type, priority_level, ...
def add_terms_to_whitelist(self, terms): """ Add a list of terms to the user's company's whitelist. :param terms: The list of terms to whitelist. :return: The list of extracted |Indicator| objects that were whitelisted. """ resp = self._client.post("whitelist", json=ter...
def delete_indicator_from_whitelist(self, indicator): """ Delete an indicator from the user's company's whitelist. :param indicator: An |Indicator| object, representing the indicator to delete. """ params = indicator.to_dict() self._client.delete("whitelist", params=par...
def get_community_trends(self, indicator_type=None, days_back=None): """ Find indicators that are trending in the community. :param indicator_type: A type of indicator to filter by. If ``None``, will get all types of indicators except for MALWARE and CVEs (this convention is for pa...
def get_whitelist_page(self, page_number=None, page_size=None): """ Gets a paginated list of indicators that the user's company has whitelisted. :param int page_number: the page number to get. :param int page_size: the size of the page to be returned. :return: A |Page| of |Indic...
def get_related_indicators_page(self, indicators=None, enclave_ids=None, page_size=None, page_number=None): """ Finds all reports that contain any of the given indicators and returns correlated indicators from those reports. :param indicators: list of indicator values to search for :par...