self._status = int(code)<EOL>

Defines the response status code.

Arguments:
    code (int): response status code.

Returns:
    self: ``pook.Response`` current instance.


args = []<EOL>for key in ('<STR_LIT>', '<STR_LIT:status>', '<STR_LIT:body>'):<EOL><INDENT>value = getattr(self, '<STR_LIT>'.format(key))<EOL>args.append('<STR_LIT>'.format(key, value))<EOL><DEDENT>return '<STR_LIT>'.format('<STR_LIT>'.join(args))<EOL>

Returns an human friendly readable instance data representation.

Returns:
    str


if not arguments:<EOL><INDENT>arguments = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>wordlist, sowpods, by_length, start, end = argument_parser(arguments)<EOL>for word in wordlist:<EOL><INDENT>pretty_print(<EOL>word,<EOL>anagrams_in_word(word, sowpods, start, end),<EOL>by_length,<EOL>)<EOL><DEDENT>


Argparse logic, command line options.

    Args:
        args: sys.argv[1:], everything passed to the program after its name

    Returns:
        A tuple of:
            a list of words/letters to search
            a boolean to declare if we want to use the sowpods words file
            a boolean to declare if we want to output anagrams by length
            a string of starting characters to find anagrams based on
            a string of ending characters to find anagrams based on

    Raises:
        SystemExit if the user passes invalid arguments, --version or --help


def word_list(sowpods=False, start="<STR_LIT>", end="<STR_LIT>"):

location = os.path.join(<EOL>os.path.dirname(os.path.realpath(__file__)),<EOL>"<STR_LIT>",<EOL>)<EOL>if sowpods:<EOL><INDENT>filename = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>filename = "<STR_LIT>"<EOL><DEDENT>filepath = os.path.join(location, filename)<EOL>with open(filepath) as wordfile:<EOL><INDENT>for word in wordfile.readlines():<EOL><INDENT>word = word.strip()<EOL>if start and end and word.startswith(start) and word.endswith(end):<EOL><INDENT>yield word<EOL><DEDENT>elif start and word.startswith(start) and not end:<EOL><INDENT>yield word<EOL><DEDENT>elif end and word.endswith(end) and not start:<EOL><INDENT>yield word<EOL><DEDENT>elif not start and not end:<EOL><INDENT>yield word<EOL><DEDENT><DEDENT><DEDENT>

Opens the word list file.

    Args:
        sowpods: a boolean to declare using the sowpods list or TWL (default)
        start: a string of starting characters to find anagrams based on
        end: a string of ending characters to find anagrams based on

    Yeilds:
        a word at a time out of 178691 words for TWL, 267751 for sowpods. Much
        less if either start or end are used (filtering is applied here)


def word_score(word, input_letters, questions=<NUM_LIT:0>):

score = <NUM_LIT:0><EOL>bingo = <NUM_LIT:0><EOL>filled_by_blanks = []<EOL>rack = list(input_letters)  <EOL>for letter in word:<EOL><INDENT>if letter in rack:<EOL><INDENT>bingo += <NUM_LIT:1><EOL>score += letter_score(letter)<EOL>rack.remove(letter)<EOL><DEDENT>else:<EOL><INDENT>filled_by_blanks.append(letter_score(letter))<EOL><DEDENT><DEDENT>for blank_score in sorted(filled_by_blanks, reverse=True):<EOL><INDENT>if questions > <NUM_LIT:0>:<EOL><INDENT>score += blank_score<EOL>questions -= <NUM_LIT:1><EOL><DEDENT><DEDENT>if bingo > <NUM_LIT:6>:<EOL><INDENT>score += <NUM_LIT:50><EOL><DEDENT>return score<EOL>

Checks the Scrabble score of a single word.

    Args:
        word: a string to check the Scrabble score of
        input_letters: the letters in our rack
        questions: integer of the tiles already on the board to build on

    Returns:
        an integer Scrabble score amount for the word


def anagrams_in_word(word, sowpods=False, start="<STR_LIT>", end="<STR_LIT>"):

input_letters, blanks, questions = blank_tiles(word)<EOL>for tile in start + end:<EOL><INDENT>input_letters.append(tile)<EOL><DEDENT>for word in word_list(sowpods, start, end):<EOL><INDENT>lmap = _letter_map(input_letters)<EOL>used_blanks = <NUM_LIT:0><EOL>for letter in word:<EOL><INDENT>if letter in lmap:<EOL><INDENT>lmap[letter] -= <NUM_LIT:1><EOL>if lmap[letter] < <NUM_LIT:0>:<EOL><INDENT>used_blanks += <NUM_LIT:1><EOL>if used_blanks > (blanks + questions):<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>used_blanks += <NUM_LIT:1><EOL>if used_blanks > (blanks + questions):<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>yield (word, word_score(word, input_letters, questions))<EOL><DEDENT><DEDENT>

Finds anagrams in word.

    Args:
        word: the string to base our search off of
        sowpods: boolean to declare TWL or SOWPODS words file
        start: a string of starting characters to find anagrams based on
        end: a string of ending characters to find anagrams based on

    Yields:
        a tuple of (word, score) that can be made with the input_word


lmap = {}<EOL>for letter in word:<EOL><INDENT>try:<EOL><INDENT>lmap[letter] += <NUM_LIT:1><EOL><DEDENT>except KeyError:<EOL><INDENT>lmap[letter] = <NUM_LIT:1><EOL><DEDENT><DEDENT>return lmap<EOL>

Creates a map of letter use in a word.

    Args:
        word: a string to create a letter map from

    Returns:
        a dictionary of {letter: integer count of letter in word}


with io.open(filename, encoding="<STR_LIT:utf-8>") as version_file:<EOL><INDENT>version_match = re.search(r'<STR_LIT>',<EOL>version_file.read(), re.M)<EOL><DEDENT>if version_match:<EOL><INDENT>return version_match.group(<NUM_LIT:1>)<EOL><DEDENT>return "<STR_LIT>"<EOL>

Uses re to pull out the assigned value to __version__ in filename.


tags = VcfRecord._EMPTY_SET<EOL>if self.sample_tag_values:<EOL><INDENT>first_sample = list(self.sample_tag_values.keys())[<NUM_LIT:0>]<EOL>tags = set(self.sample_tag_values[first_sample].keys())<EOL><DEDENT>return tags<EOL>


def add_sample_tag_value(self, tag_name, new_sample_values):

if tag_name in self.format_tags:<EOL><INDENT>msg = "<STR_LIT>".format(tag_name)<EOL>raise KeyError(msg)<EOL><DEDENT>if not self._samples_match(new_sample_values):<EOL><INDENT>raise KeyError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>for sample in self.sample_tag_values.keys():<EOL><INDENT>value = str(new_sample_values[sample])<EOL>self.sample_tag_values[sample][tag_name] = value<EOL><DEDENT>

Appends a new format tag-value for all samples.

        Args:
            tag_name: string tag name; must not already exist
            new_sample

        Raises:
            KeyError: if tag_name to be added already exists


stringifier = [self.chrom, self.pos, self.vcf_id, self.ref, self.alt,<EOL>self.qual, self.filter, self.info,<EOL>self._format_field()]<EOL>for sample in self.sample_tag_values:<EOL><INDENT>stringifier.append(self._sample_field(sample))<EOL><DEDENT>return "<STR_LIT:\t>".join(stringifier) + "<STR_LIT:\n>"<EOL>

Returns tab-delimited, newline terminated string of VcfRecord.


global log_filename<EOL>log_filename = os.path.join(os.getcwd(), "<STR_LIT>")<EOL>if args.log_file:<EOL><INDENT>_validate_log_file(args.log_file)<EOL>log_filename = args.log_file<EOL><DEDENT>logging.basicConfig(format=_FILE_LOG_FORMAT,<EOL>level="<STR_LIT>",<EOL>datefmt=_DATE_FORMAT,<EOL>filename=log_filename)<EOL>global _verbose<EOL>if args.verbose:<EOL><INDENT>_verbose = args.verbose<EOL><DEDENT>start_time = datetime.now().strftime(_DATE_FORMAT)<EOL>global _logging_dict<EOL>_logging_dict = {'<STR_LIT:user>': getpass.getuser(),<EOL>'<STR_LIT:host>': socket.gethostname(),<EOL>'<STR_LIT>': start_time,<EOL>'<STR_LIT>': args.subparser_name}<EOL>

Sets command name and formatting for subsequent calls to logger


message = self._remessage_invalid_subparser(message)<EOL>raise utils.UsageError(message)<EOL>


(prefix_to_readers,<EOL>filter_files,<EOL>unclaimed_set) = self._find_varscan_files(file_readers)<EOL>prefix_by_patients = self._split_prefix_by_patient(prefix_to_readers)<EOL>self._validate_vcf_readers(prefix_by_patients)<EOL>vcf_hc_pairs = self._pair_files(prefix_to_readers, filter_files)<EOL>self._validate_vcf_hc_pairs(vcf_hc_pairs)<EOL>vcf_readers = self._create_vcf_readers(vcf_hc_pairs)<EOL>return list(unclaimed_set), vcf_readers<EOL>

Recognizes and claims VarScan VCFs form the set of all input VCFs.

        Each defined caller has a chance to evaluate and claim all the incoming
        files as something that it can process. Since VarScan can claim
        high-confidence files as well, this process is significantly more
        complex than for other callers.

        Args:
            file_readers: the collection of currently unclaimed files

        Returns:
            A tuple of unclaimed readers and VarScanVcfReaders.


<EOL>if self.formsets:<EOL><INDENT>for formset in self.formsets.values():<EOL><INDENT>for form in formset.forms:<EOL><INDENT>if form.has_changed():<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return bool(self.changed_data)<EOL>

Return True if data differs from initial.


relation_name = related.get_accessor_name()<EOL>rel_field = related.field<EOL>rel_model = related.related_model<EOL>superclass = rel_model._default_manager.__class__<EOL>class DeferringRelatedManager(superclass):<EOL><INDENT>def __init__(self, instance):<EOL><INDENT>super(DeferringRelatedManager, self).__init__()<EOL>self.model = rel_model<EOL>self.instance = instance<EOL><DEDENT>def _get_cluster_related_objects(self):<EOL><INDENT>try:<EOL><INDENT>return self.instance._cluster_related_objects<EOL><DEDENT>except AttributeError:<EOL><INDENT>cluster_related_objects = {}<EOL>self.instance._cluster_related_objects = cluster_related_objects<EOL>return cluster_related_objects<EOL><DEDENT><DEDENT>def get_live_query_set(self):<EOL><INDENT>return self.get_live_queryset()<EOL><DEDENT>def get_live_queryset(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>return original_manager_cls(self.instance).get_queryset()<EOL><DEDENT>def get_queryset(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>results = self.instance._cluster_related_objects[relation_name]<EOL><DEDENT>except (AttributeError, KeyError):<EOL><INDENT>return self.get_live_queryset()<EOL><DEDENT>return FakeQuerySet(related.related_model, results)<EOL><DEDENT>def _apply_rel_filters(self, queryset):<EOL><INDENT>return queryset._next_is_sticky()<EOL><DEDENT>def get_prefetch_queryset(self, instances, queryset=None):<EOL><INDENT>if queryset is None:<EOL><INDENT>db = self._db or router.db_for_read(self.model, instance=instances[<NUM_LIT:0>])<EOL>queryset = super(DeferringRelatedManager, self).get_queryset().using(db)<EOL><DEDENT>rel_obj_attr = rel_field.get_local_related_value<EOL>instance_attr = rel_field.get_foreign_related_value<EOL>instances_dict = dict((instance_attr(inst), inst) for inst in instances)<EOL>query = {'<STR_LIT>' % rel_field.name: instances}<EOL>qs = queryset.filter(**query)<EOL>for rel_obj in qs:<EOL><INDENT>instance = instances_dict[rel_obj_attr(rel_obj)]<EOL>setattr(rel_obj, rel_field.name, instance)<EOL><DEDENT>cache_name = rel_field.related_query_name()<EOL>return qs, rel_obj_attr, instance_attr, False, cache_name, False<EOL><DEDENT>def get_object_list(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>cluster_related_objects = self._get_cluster_related_objects()<EOL>try:<EOL><INDENT>object_list = cluster_related_objects[relation_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>object_list = list(self.get_live_queryset())<EOL>cluster_related_objects[relation_name] = object_list<EOL><DEDENT>return object_list<EOL><DEDENT>def add(self, *new_items):<EOL><INDENT>"""<STR_LIT>"""<EOL>items = self.get_object_list()<EOL>for target in new_items:<EOL><INDENT>item_matched = False<EOL>for i, item in enumerate(items):<EOL><INDENT>if item == target:<EOL><INDENT>items[i] = target<EOL>item_matched = True<EOL>break<EOL><DEDENT><DEDENT>if not item_matched:<EOL><INDENT>items.append(target)<EOL><DEDENT>setattr(target, related.field.name, self.instance)<EOL><DEDENT>if rel_model._meta.ordering and len(items) > <NUM_LIT:1>:<EOL><INDENT>sort_by_fields(items, rel_model._meta.ordering)<EOL><DEDENT><DEDENT>def remove(self, *items_to_remove):<EOL><INDENT>"""<STR_LIT>"""<EOL>items = self.get_object_list()<EOL>items[:] = [item for item in items if item not in items_to_remove]<EOL><DEDENT>def create(self, **kwargs):<EOL><INDENT>items = self.get_object_list()<EOL>new_item = related.related_model(**kwargs)<EOL>items.append(new_item)<EOL>return new_item<EOL><DEDENT>def clear(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>self.set([])<EOL><DEDENT>def set(self, objs, bulk=True, clear=False):<EOL><INDENT>objs = list(objs)<EOL>cluster_related_objects = self._get_cluster_related_objects()<EOL>for obj in objs:<EOL><INDENT>setattr(obj, related.field.name, self.instance)<EOL><DEDENT>if rel_model._meta.ordering and len(objs) > <NUM_LIT:1>:<EOL><INDENT>sort_by_fields(objs, rel_model._meta.ordering)<EOL><DEDENT>cluster_related_objects[relation_name] = objs<EOL><DEDENT>def commit(self):<EOL><INDENT>"""<STR_LIT>"""<EOL>if self.instance.pk is None:<EOL><INDENT>raise IntegrityError("<STR_LIT>" % relation_name)<EOL><DEDENT>try:<EOL><INDENT>final_items = self.instance._cluster_related_objects[relation_name]<EOL><DEDENT>except (AttributeError, KeyError):<EOL><INDENT>return<EOL><DEDENT>original_manager = original_manager_cls(self.instance)<EOL>live_items = list(original_manager.get_queryset())<EOL>for item in live_items:<EOL><INDENT>if item not in final_items:<EOL><INDENT>item.delete()<EOL><DEDENT><DEDENT>for item in final_items:<EOL><INDENT>original_manager.add(item, bulk=False)<EOL><DEDENT>del self.instance._cluster_related_objects[relation_name]<EOL><DEDENT><DEDENT>return DeferringRelatedManager<EOL>

Create a DeferringRelatedManager class that wraps an ordinary RelatedManager
with 'deferring' behaviour: any updates to the object set (via e.g. add() or clear())
are written to a holding area rather than committed to the database immediately.
Writing to the database is deferred until the model is saved.


return [<EOL>field for field in model._meta.get_fields()<EOL>if isinstance(field, ParentalManyToManyField)<EOL>]<EOL>

Return a list of ParentalManyToManyFields on the given model,
including ones attached to ancestors of the model


return [<EOL>field for field in model._meta.get_fields()<EOL>if isinstance(field.remote_field, ParentalKey)<EOL>]<EOL>

Return a list of RelatedObject records for child relations of the given model,
including ones attached to ancestors of the model


@classmethod<EOL><INDENT>def from_serializable_data(cls, data, check_fks=True, strict_fks=False):<DEDENT>

obj = model_from_serializable_data(cls, data, check_fks=check_fks, strict_fks=strict_fks)<EOL>if obj is None:<EOL><INDENT>return None<EOL><DEDENT>child_relations = get_all_child_relations(cls)<EOL>for rel in child_relations:<EOL><INDENT>rel_name = rel.get_accessor_name()<EOL>try:<EOL><INDENT>child_data_list = data[rel_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT>related_model = rel.related_model<EOL>if hasattr(related_model, '<STR_LIT>'):<EOL><INDENT>children = [<EOL>related_model.from_serializable_data(child_data, check_fks=check_fks, strict_fks=True)<EOL>for child_data in child_data_list<EOL>]<EOL><DEDENT>else:<EOL><INDENT>children = [<EOL>model_from_serializable_data(related_model, child_data, check_fks=check_fks, strict_fks=True)<EOL>for child_data in child_data_list<EOL>]<EOL><DEDENT>children = filter(lambda child: child is not None, children)<EOL>setattr(obj, rel_name, children)<EOL><DEDENT>return obj<EOL>

Build an instance of this model from the JSON-like structure passed in,
recursing into related objects as required.
If check_fks is true, it will check whether referenced foreign keys still
exist in the database.
- dangling foreign keys on related objects are dealt with by either nullifying the key or
dropping the related object, according to the 'on_delete' setting.
- dangling foreign keys on the base object will be nullified, unless strict_fks is true,
in which case any dangling foreign keys with on_delete=CASCADE will cause None to be
returned for the entire object.


child_relation_names = [rel.get_accessor_name() for rel in get_all_child_relations(self)]<EOL>child_m2m_field_names = [field.name for field in get_all_child_m2m_relations(self)]<EOL>update_fields = kwargs.pop('<STR_LIT>', None)<EOL>if update_fields is None:<EOL><INDENT>real_update_fields = None<EOL>relations_to_commit = child_relation_names<EOL>m2m_fields_to_commit = child_m2m_field_names<EOL><DEDENT>else:<EOL><INDENT>real_update_fields = []<EOL>relations_to_commit = []<EOL>m2m_fields_to_commit = []<EOL>for field in update_fields:<EOL><INDENT>if field in child_relation_names:<EOL><INDENT>relations_to_commit.append(field)<EOL><DEDENT>elif field in child_m2m_field_names:<EOL><INDENT>m2m_fields_to_commit.append(field)<EOL><DEDENT>else:<EOL><INDENT>real_update_fields.append(field)<EOL><DEDENT><DEDENT><DEDENT>super(ClusterableModel, self).save(update_fields=real_update_fields, **kwargs)<EOL>for relation in relations_to_commit:<EOL><INDENT>getattr(self, relation).commit()<EOL><DEDENT>for field in m2m_fields_to_commit:<EOL><INDENT>getattr(self, field).commit()<EOL><DEDENT>

Save the model and commit all child relations.


child_relation_names = (<EOL>[rel.get_accessor_name() for rel in get_all_child_relations(self)] +<EOL>[field.name for field in get_all_child_m2m_relations(self)]<EOL>)<EOL>if any(name in kwargs for name in child_relation_names):<EOL><INDENT>kwargs_for_super = kwargs.copy()<EOL>relation_assignments = {}<EOL>for rel_name in child_relation_names:<EOL><INDENT>if rel_name in kwargs:<EOL><INDENT>relation_assignments[rel_name] = kwargs_for_super.pop(rel_name)<EOL><DEDENT><DEDENT>super(ClusterableModel, self).__init__(*args, **kwargs_for_super)<EOL>for (field_name, related_instances) in relation_assignments.items():<EOL><INDENT>setattr(self, field_name, related_instances)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>super(ClusterableModel, self).__init__(*args, **kwargs)<EOL><DEDENT>

Extend the standard model constructor to allow child object lists to be passed in
via kwargs


raise NotImplementedError<EOL>

Subclasses have to override this method to implement the actual
        handler function code. This method is called with asset as argument.
        Depending on the type of the handler, this method must change asset
        state (as it does in :class:`~gears.processors.Directivesprocessor`)
        or return some value (in case of asset compressors).


return self.environment.preprocessors.get(self.mimetype)<EOL>

The list of preprocessors used to build asset.


return self.environment.postprocessors.get(self.mimetype)<EOL>

The list of postprocessors used to build asset.


return self.preprocessors + list(reversed(self.compilers)) + self.postprocessors<EOL>

The list of all processors (preprocessors, compilers,
        postprocessors) used to build asset.


paths = [self.path]<EOL>if os.path.basename(self.path_without_suffix) != '<STR_LIT:index>':<EOL><INDENT>path = os.path.join(self.path_without_suffix, '<STR_LIT:index>')<EOL>paths.append(path + '<STR_LIT>'.join(self.suffix))<EOL><DEDENT>return paths<EOL>

The list of logical paths which are used to search for an asset.
        This property makes sense only if the attributes was created with
        logical path.

        It is assumed that the logical path can be a directory containing a
        file named ``index`` with the same suffix.

        Example::

            >>> attrs = AssetAttributes(environment, 'js/app.js')
            >>> attrs.search_paths
            ['js/app.js', 'js/app/index.js']

            >>> attrs = AssetAttributes(environment, 'js/app/index.js')
            >>> attrs.search_paths
            ['js/models/index.js']


if self.suffix:<EOL><INDENT>return self.path[:-len('<STR_LIT>'.join(self.suffix))]<EOL><DEDENT>return self.path<EOL>

The relative path to asset without suffix.
        Example::

            >>> attrs = AssetAttributes(environment, 'js/app.js')
            >>> attrs.path_without_suffix
            'js/app'


if isinstance(item, AssetAttributes):<EOL><INDENT>for path in item.search_paths:<EOL><INDENT>try:<EOL><INDENT>return self.find(path, logical)<EOL><DEDENT>except FileNotFound:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>raise FileNotFound(item.path)<EOL><DEDENT>if logical:<EOL><INDENT>asset_attributes = AssetAttributes(self, item)<EOL>suffixes = self.suffixes.find(asset_attributes.mimetype)<EOL>if not suffixes:<EOL><INDENT>return self.find(item)<EOL><DEDENT>path = asset_attributes.path_without_suffix<EOL>for suffix in suffixes:<EOL><INDENT>try:<EOL><INDENT>return self.find(path + suffix)<EOL><DEDENT>except FileNotFound:<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for finder in self.finders:<EOL><INDENT>try:<EOL><INDENT>absolute_path = finder.find(item)<EOL><DEDENT>except FileNotFound:<EOL><INDENT>continue<EOL><DEDENT>return AssetAttributes(self, item), absolute_path<EOL><DEDENT><DEDENT>raise FileNotFound(item)<EOL>

Find files using :attr:`finders` registry. The ``item`` parameter
        can be an instance of :class:`~gears.asset_attributes.AssetAttributes`
        class, a path to the asset or a logical path to the asset. If ``item``
        is a logical path, `logical` parameter must be set to ``True``.

        Returns a tuple with :class:`~gears.asset_attributes.AssetAttributes`
        instance for found file path as first item, and absolute path to this
        file as second item.

        If nothing is found, :class:`gears.exceptions.FileNotFound` exception
        is rased.


if finder in self:<EOL><INDENT>self.remove(finder)<EOL><DEDENT>

Remove passed ``finder`` from the list of finders. If ``finder``
        does not found in the registry, nothing happens.


if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>paths = []<EOL>for finder in self.finders:<EOL><INDENT>if hasattr(finder, '<STR_LIT>'):<EOL><INDENT>paths.extend(finder.paths)<EOL><DEDENT><DEDENT>self._paths = paths<EOL><DEDENT>return self._paths<EOL>

The list of search paths. It is built from registered finders, which
        has ``paths`` property. Can be useful for compilers to resolve internal
        dependencies.


self.register('<STR_LIT>', '<STR_LIT>')<EOL>self.register('<STR_LIT>', '<STR_LIT>')<EOL>

Register MIME types for ``.js`` and ``.css`` extensions.


return functor.map(func)<EOL>

Applies a function to the data 'inside' a functor.

    Uses functools.singledispatch so you can write your own functors
    for use with the library.


try:<EOL><INDENT>self._lens_contains_remove<EOL><DEDENT>except AttributeError:<EOL><INDENT>message = '<STR_LIT>'<EOL>raise NotImplementedError(message.format(type(self)))<EOL><DEDENT>else:<EOL><INDENT>return self._lens_contains_remove(item)<EOL><DEDENT>

Takes a collection and an item and returns a new collection
    of the same type with that item removed. The notion of "contains"
    is defined by the object itself; the following must be ``True``:

    .. code-block:: python

        item not in contains_remove(obj, item)

    This function is used by some lenses (particularly ContainsLens)
    to remove items from containers when necessary.

    The corresponding method call for this hook is
    ``obj._lens_contains_remove(item)``.

    There is no default implementation.


return self.item<EOL>

Unwraps the value, returning it is there is one, else
        returning the guard.


def Error(self, exception, message=None):<EOL>

return self._compose_optic(optics.ErrorIso(exception, message))<EOL>

An optic that raises an exception whenever it tries to focus
        something. If `message is None` then the exception will be
        raised unmodified. If `message is not None` then when the lens
        is asked to focus something it will run `message.format(state)`
        and the exception will be called with the resulting formatted
        message as it's only argument. Useful for debugging.

            >>> from lenses import lens
            >>> lens.Error(Exception())
            UnboundLens(ErrorIso(Exception()))
            >>> lens.Error(Exception, '{}')
            UnboundLens(ErrorIso(<...Exception...>, '{}'))
            >>> lens.Error(Exception).get()(True)
            Traceback (most recent call last):
              File "<stdin>", line 1, in ?
            Exception
            >>> lens.Error(Exception('An error occurred')).set(False)(True)
            Traceback (most recent call last):
              File "<stdin>", line 1, in ?
            Exception: An error occurred
            >>> lens.Error(ValueError, 'applied to {}').get()(True)
            Traceback (most recent call last):
              File "<stdin>", line 1, in ?
            ValueError: applied to True


return self._compose_optic(optics.GetitemLens(key))<EOL>

A lens that focuses an item inside a container. Analogous to
        `operator.itemgetter`.

            >>> from lenses import lens
            >>> lens[0]
            UnboundLens(GetitemLens(0))
            >>> lens.GetItem(0)
            UnboundLens(GetitemLens(0))
            >>> lens[0].get()([1, 2, 3])
            1
            >>> lens['hello'].get()({'hello': 'world'})
            'world'
            >>> lens[0].set(4)([1, 2, 3])
            [4, 2, 3]
            >>> lens['hello'].set('universe')({'hello': 'world'})
            {'hello': 'universe'}


return self._compose_optic(optics.ItemLens(key))<EOL>

A lens that focuses a single item (key-value pair) in a
        dictionary by its key. Set an item to `None` to remove it from
        the dictionary.

            >>> from lenses import lens
            >>> from collections import OrderedDict
            >>> data = OrderedDict([(1, 10), (2, 20)])
            >>> lens.Item(1)
            UnboundLens(ItemLens(1))
            >>> lens.Item(1).get()(data)
            (1, 10)
            >>> lens.Item(3).get()(data) is None
            True
            >>> lens.Item(1).set((1, 11))(data)
            OrderedDict([(1, 11), (2, 20)])
            >>> lens.Item(1).set(None)(data)
            OrderedDict([(2, 20)])


def call(self, method_name, *args, **kwargs):<EOL>

caller = operator.methodcaller(method_name, *args, **kwargs)<EOL>return self.modify(caller)<EOL>

Call a method on the focus. The method must return a new
        value for the focus.

            >>> from lenses import lens
            >>> lens[2].call('upper')(['alpha', 'beta', 'gamma'])
            ['alpha', 'beta', 'GAMMA']

        As a shortcut, you can include the name of the method you want
        to call immediately after `call_`:

            >>> lens[2].call_upper()(['alpha', 'beta', 'gamma'])
            ['alpha', 'beta', 'GAMMA']


def call_mut(self, method_name, *args, **kwargs):<EOL>

shallow = False<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>shallow = kwargs['<STR_LIT>']<EOL>del kwargs['<STR_LIT>']<EOL><DEDENT>def func(a):<EOL><INDENT>a = copy.copy(a) if shallow else copy.deepcopy(a)<EOL>getattr(a, method_name)(*args, **kwargs)<EOL>return cast(B, a)<EOL><DEDENT>return self.modify(func)<EOL>

Call a method on the focus that will mutate it in place.
        Works by making a deep copy of the focus before calling the
        mutating method on it. The return value of that method is ignored.
        You can pass a keyword argument shallow=True to only make a
        shallow copy.

            >>> from lenses import lens
            >>> lens[0].call_mut('sort')([[3, 1, 2], [5, 4]])
            [[1, 2, 3], [5, 4]]

        As a shortcut, you can include the name of the method you want
        to call immediately after `call_mut_`:

            >>> lens[0].call_mut_sort()([[3, 1, 2], [5, 4]])
            [[1, 2, 3], [5, 4]]


return self._compose_optic(optics.JustPrism())<EOL>

A prism that focuses the value inside a `lenses.maybe.Just`
        object.

            >>> from lenses import lens
            >>> from lenses.maybe import Just, Nothing
            >>> lens.Just()
            UnboundLens(JustPrism())
            >>> lens.Just().collect()(Just(1))
            [1]
            >>> lens.Just().collect()(Nothing())
            []
            >>> lens.Just().set(2)(Just(1))
            Just(2)
            >>> lens.Just().set(2)(Nothing())
            Nothing()


return self._compose_optic(optics.NormalisingIso(setter))<EOL>

An isomorphism that applies a function as it sets a new
        focus without regard to the old state. It will get foci without
        transformation. This lens allows you to pre-process values before
        you set them, but still get values as they exist in the state.
        Useful for type conversions or normalising data.

        For best results, your normalisation function should be
        idempotent.  That is, applying the function twice should have
        no effect::

            setter(setter(value)) == setter(value)

        Equivalent to `Isomorphism((lambda s: s), setter)`.

            >>> from lenses import lens
            >>> def real_only(num):
            ...     return num.real
            ...
            >>> lens.Norm(real_only)
            UnboundLens(NormalisingIso(<function real_only at ...>))
            >>> lens[0].Norm(real_only).get()([1.0, 2.0, 3.0])
            1.0
            >>> lens[0].Norm(real_only).set(4+7j)([1.0, 2.0, 3.0])
            [4.0, 2.0, 3.0]

        Types with constructors that do conversion are often good targets
        for this lens:

            >>> lens[0].Norm(int).set(4.0)([1, 2, 3])
            [4, 2, 3]
            >>> lens[1].Norm(int).set('5')([1, 2, 3])
            [1, 5, 3]


return self._compose_optic(optics.FilteringPrism(predicate))<EOL>

A prism that only focuses a value if the predicate returns
        `True` when called with that value as an argument. Best used
        when composed after a traversal. It only prevents the traversal
        from visiting foci, it does not filter out values the way that
        python's regular `filter` function does.

            >>> from lenses import lens
            >>> lens.Filter(all)
            UnboundLens(FilteringPrism(<built-in function all>))
            >>> data = [[1, 2], [0], ['a'], ['', 'b']]
            >>> lens.Each().Filter(all).collect()(data)
            [[1, 2], ['a']]
            >>> lens.Each().Filter(all).set(2)(data)
            [2, [0], 2, ['', 'b']]

        The filtering is done to foci before the lens' manipulation is
        applied. This means that the resulting foci can still violate
        the predicate if the manipulating function doesn't respect it:

            >>> lens.Each().Filter(bool).set(None)(['', 2, ''])
            ['', None, '']


return self._compose_optic(<EOL>optics.ItemsTraversal() & optics.GetitemLens(<NUM_LIT:1>)<EOL>)<EOL>

A traversal focusing the values of a dictionary. Analogous to
        `dict.values`.

            >>> from lenses import lens
            >>> from collections import OrderedDict
            >>> data = OrderedDict([(1, 10), (2, 20)])
            >>> lens.Values()
            UnboundLens(ItemsTraversal() & GetitemLens(1))
            >>> lens.Values().collect()(data)
            [10, 20]
            >>> lens.Values().modify(lambda n: n + 1)(data)
            OrderedDict([(1, 11), (2, 21)])


return self._compose_optic(optics.ItemByValueLens(value))<EOL>

A lens that focuses a single item (key-value pair) in a
        dictionary by its value. Set an item to `None` to remove it
        from the dictionary. This lens assumes that there will only be
        a single key with that particular value. If you violate that
        assumption then you're on your own.

            >>> from lenses import lens
            >>> from collections import OrderedDict
            >>> data = OrderedDict([(1, 10), (2, 20)])
            >>> lens.ItemByValue(10)
            UnboundLens(ItemByValueLens(10))
            >>> lens.ItemByValue(10).get()(data)
            (1, 10)
            >>> lens.ItemByValue(30).get()(data) is None
            True
            >>> lens.ItemByValue(10).set((3, 10))(data)
            OrderedDict([(2, 20), (3, 10)])
            >>> lens.ItemByValue(10).set(None)(data)
            OrderedDict([(2, 20)])


return self._compose_optic(optics.Lens(getter, setter))<EOL>

An optic that wraps a pair of getter and setter functions. A
        getter function is one that takes a state and returns a value
        derived from that state. A setter function takes an old state
        and a new value and uses them to construct a new state.

            >>> from lenses import lens
            >>> def getter(state):
            ...     'Get the average of a list'
            ...     return sum(state) // len(state)
            ...
            >>> def setter(old_state, value):
            ...     'Set the average of a list by changing the final value'
            ...     target_sum = value * len(old_state)
            ...     prefix = old_state[:-1]
            ...     return prefix + [target_sum - sum(prefix)]
            ...
            >>> average_lens = lens.Lens(getter, setter)
            >>> average_lens
            UnboundLens(Lens(<function getter...>, <function setter...>))
            >>> average_lens.get()([1, 2, 4, 5])
            3
            >>> average_lens.set(4)([1, 2, 3])
            [1, 2, 9]
            >>> (average_lens - 1)([1, 2, 3])
            [1, 2, 0]


return self._compose_optic(optics.Getter(getter))<EOL>

An optic that wraps a getter function. A getter function is
        one that takes a state and returns a value derived from that
        state. The function is called on the focus before it is returned.

            >>> from lenses import lens
            >>> lens.F(abs)
            UnboundLens(Getter(<built-in function abs>))
            >>> lens.F(abs).get()(-1)
            1
            >>> lens.Each().F(abs).collect()([-1, 2, -3])
            [1, 2, 3]

        This optic cannot be used to set or modify values.


def modifier(state):<EOL><INDENT>return self._optic.over(state, func)<EOL><DEDENT>return modifier<EOL>

Apply a function to the focus.

            >>> from lenses import lens
            >>> convert_item_one_to_string = lens[1].modify(str)
            >>> convert_item_one_to_string([1, 2, 3])
            [1, '2', 3]
            >>> add_ten_to_item_one = lens[1].modify(lambda n: n + 10)
            >>> add_ten_to_item_one([1, 2, 3])
            [1, 12, 3]


def getter(state):<EOL><INDENT>return self._optic.to_list_of(state)<EOL><DEDENT>return getter<EOL>

Get multiple values focused by the lens. Returns them as
        a list.

            >>> from lenses import lens
            >>> collect_each_first = lens.Each()[0].collect()
            >>> collect_each_first([(1, 2), (3, 4), (5, 6)])
            [1, 3, 5]


return self._optic.to_list_of(self._state)[<NUM_LIT:0>]<EOL>

Get the first value focused by the lens.

            >>> from lenses import bind
            >>> bind([1, 2, 3]).get()
            [1, 2, 3]
            >>> bind([1, 2, 3])[0].get()
            1


def setter(state):<EOL><INDENT>return self._optic.set(state, newvalue)<EOL><DEDENT>return setter<EOL>

Set the focus to `newvalue`.

            >>> from lenses import lens
            >>> set_item_one_to_four = lens[1].set(4)
            >>> set_item_one_to_four([1, 2, 3])
            [1, 4, 3]


return self._optic.kind().__name__<EOL>


optics = [<EOL>Equality,<EOL>Isomorphism,<EOL>Prism,<EOL>Review,<EOL>Lens,<EOL>Traversal,<EOL>Getter,<EOL>Setter,<EOL>Fold,<EOL>]<EOL>for optic in optics:<EOL><INDENT>if self._is_kind(optic):<EOL><INDENT>return optic<EOL><DEDENT><DEDENT>

Returns a class representing the 'kind' of optic.


return not self.unpack(state).is_nothing()<EOL>

Returns `True` when the state would be successfully focused
        by this prism, otherwise `False`.

            >>> from lenses.maybe import Nothing, Just
            >>> def pack(focus):
            ...     return focus
            >>> def unpack(state):
            ...     if state > 0:
            ...         return Just(state)
            ...     return Nothing()
            >>> positive = Prism(unpack, pack)
            >>> positive.has(-1)
            False
            >>> positive.has(1)
            True


if not self._is_kind(Setter):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>pure = lambda a: Identity(a)<EOL>func = lambda a: Identity(value)<EOL>return self.apply(func, pure, state).unwrap()<EOL>

Sets all the foci within `state` to `value`.

        Requires kind Setter. This method will raise TypeError when the
        optic has no way to set foci.


if not self._is_kind(Fold):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>pure = lambda a: Const([])<EOL>func = lambda a: Const([a])<EOL>return self.apply(func, pure, state).unwrap()<EOL>

Returns a list of all the foci within `state`.

        Requires kind Fold. This method will raise TypeError if the
        optic has no way to get any foci.


return self.func(Functorisor(pure, f), state)<EOL>

Runs the lens over the `state` applying `f` to all the foci
        collecting the results together using the applicative functor
        functions defined in `lenses.typeclass`. `f` must return an
        applicative functor. For the case when no focus exists you must
        also provide a `pure` which should take a focus and return the
        pure form of the functor returned by `f`.


return cls((randint(<NUM_LIT:0>, MAXX), randint(<NUM_LIT:0>, MAXY)))<EOL>

produces a random vector inside the play area.


state = GameState()<EOL>print(state)<EOL>while state.running:<EOL><INDENT>input = get_single_char()<EOL>state, should_advance = state.handle_input(input)<EOL>if should_advance:<EOL><INDENT>state = state.advance_robots()<EOL>state = state.check_game_end()<EOL><DEDENT>print(state)<EOL><DEDENT>print(state.message)<EOL>

The main function. Instantiates a GameState object and then
    enters a REPL-like main loop, waiting for input, updating the state
    based on the input, then outputting the new state.


if self.player in self.crashes.union(self.robots):<EOL><INDENT>return self.end_game('<STR_LIT>')<EOL><DEDENT>elif not self.robots:<EOL><INDENT>return self.end_game('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return self<EOL><DEDENT>

Checks for the game's win/lose conditions and 'alters' the
        game state to reflect the condition found. If the game has not
        been won or lost then it just returns the game state
        unaltered.


return '<STR_LIT:X>' if self._count('<STR_LIT:X>') <= self._count('<STR_LIT:O>') else '<STR_LIT:O>'<EOL>


if self.board[y][x] == '<STR_LIT:U+0020>':<EOL><INDENT>return lens.board[y][x].set(self.player)(self)<EOL><DEDENT>return self<EOL>

Return a board with a cell filled in by the current player. If
        the cell is already occupied then return the board unchanged.


def __init__(self, ptype='<STR_LIT>', legislature=None):

assert(ptype in ['<STR_LIT>', '<STR_LIT>'])<EOL>assert(legislature in ['<STR_LIT>', '<STR_LIT>', None])<EOL>self.legislature = legislature<EOL>self.ptype = ptype<EOL>self.ptype_plural = ptype + '<STR_LIT:s>'<EOL>self.base_url = '<STR_LIT>' % (legislature or '<STR_LIT>', self.ptype_plural)<EOL>

type: depute or senateur
legislature: 2007-2012 or None


context.set_code(grpc.StatusCode.UNIMPLEMENTED)<EOL>context.set_details('<STR_LIT>')<EOL>raise NotImplementedError('<STR_LIT>')<EOL>


warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>return self.element_by(condition)<EOL>


def export_obj(filename, cutout, level=<NUM_LIT:0>):

if "<STR_LIT>" not in filename:<EOL><INDENT>filename = filename + "<STR_LIT>"<EOL><DEDENT>vs, fs = mcubes.marching_cubes(cutout, level)<EOL>mcubes.export_obj(vs, fs, filename)<EOL>

Converts a dense annotation to a obj, using Marching Cubes (PyMCubes).

Arguments:
    filename (str): The filename to write out to
    cutout (numpy.ndarray): The dense annotation
    level (int): The level at which to run mcubes

Returns:
    boolean success


def export_ply(filename, cutout, level=<NUM_LIT:0>):

if "<STR_LIT>" not in filename:<EOL><INDENT>filename = filename + "<STR_LIT>"<EOL><DEDENT>vs, fs = mcubes.marching_cubes(cutout, level)<EOL>with open(filename, '<STR_LIT:w>') as fh:<EOL><INDENT>lines = [<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" + str(len(vs)),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>" + str(len(fs)),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>]<EOL>fh.writelines(lines)<EOL>for v in vs:<EOL><INDENT>fh.write("<STR_LIT>".format(v[<NUM_LIT:0>], v[<NUM_LIT:1>], v[<NUM_LIT:2>]))<EOL><DEDENT>for f in fs:<EOL><INDENT>fh.write("<STR_LIT>".format(f[<NUM_LIT:0>], f[<NUM_LIT:1>], f[<NUM_LIT:2>]))<EOL><DEDENT><DEDENT>

Converts a dense annotation to a .PLY, using Marching Cubes (PyMCubes).

Arguments:
    filename (str): The filename to write out to
    cutout (numpy.ndarray): The dense annotation
    level (int): The level at which to run mcubes

Returns:
    boolean success


def add_project(self, project_name, token_name=None, public=None):

self.project = (project_name.strip().replace("<STR_LIT:U+0020>", "<STR_LIT>"),<EOL>token_name.strip().replace("<STR_LIT:U+0020>", "<STR_LIT>"), public)<EOL>

Arguments:
    project_name (str): Project name is the specific project within
        a dataset's name. If there is only one project associated
        with a dataset then standard convention is to name the
        project the same as its associated dataset.
    token_name (str): The token name is the default token. If you
        do not wish to specify one, a default one will be created for
        you with the same name as the project name. However, if the
        project is private you must specify a token.
    public (int): This option allows users to specify if they want
        the project/channels to be publicly viewable/search-able.
        (1, 0) = (TRUE, FALSE)

Returns:
    None


def nd_json_list(self, dataset, project, channel_list, metadata):

nd_dict = {}<EOL>nd_dict['<STR_LIT>'] = self.dataset_dict(*dataset)<EOL>nd_dict['<STR_LIT>'] = self.project_dict(*project)<EOL>nd_dict['<STR_LIT>'] = metadata<EOL>nd_dict['<STR_LIT>'] = {}<EOL>for channel_name, value in channel_list.items():<EOL><INDENT>nd_dict['<STR_LIT>'].append(self.channel_dict(*value))<EOL><DEDENT>return json.dumps(nd_dict, sort_keys=True, indent=<NUM_LIT:4>)<EOL>


def add_dataset(self, dataset_name, imagesize, voxelres, offset=None,<EOL>timerange=None, scalinglevels=None, scaling=None):

self.dataset = (dataset_name.strip().replace("<STR_LIT:U+0020>", "<STR_LIT>"), imagesize,<EOL>voxelres, offset, timerange, scalinglevels, scaling)<EOL>

Add a new dataset to the ingest.

Arguments:
    dataset_name (str): Dataset Name is the overarching name of the
        research effort. Standard naming convention is to do
        LabNamePublicationYear or LeadResearcherCurrentYear.
    imagesize (int, int, int): Image size is the pixel count
        dimensions of the data. For example is the data is stored
        as a series of 100 slices each 2100x2000 pixel TIFF images,
        the X,Y,Z dimensions are (2100, 2000, 100).
    voxelres (float, float, float): Voxel Resolution is the number
        of voxels per unit pixel. We store X,Y,Z voxel resolution
        separately.
    offset (int, int, int): If your data is not well aligned and
        there is "excess" image data you do not wish to examine, but
        are present in your images, offset is how you specify where
        your actual image starts. Offset is provided a pixel
        coordinate offset from origin which specifies the "actual"
        origin of the image. The offset is for X,Y,Z dimensions.
    timerange (int, int): Time Range is a parameter to support
        storage of Time Series data, so the value of the tuple is a
        0 to X range of how many images over time were taken. It
        takes 2 inputs timeStepStart and timeStepStop.
    scalinglevels (int): Scaling levels is the number of levels the
        data is scalable to (how many zoom levels are present in the
        data). The highest resolution of the data is at scaling level
        0, and for each level up the data is down sampled by 2x2
        (per slice). To learn more about the sampling service used,
        visit the the propagation service page.
    scaling (int): Scaling is the scaling method of the data being
        stored. 0 corresponds to a Z-slice orientation (as in a
        collection of tiff images in which each tiff is a slice on
        the z plane) where data will be scaled only on the xy plane,
        not the z plane. 1 corresponds to an isotropic orientation
        (in which each tiff is a slice on the y plane) where data
        is scaled along all axis.

Returns:
    None


def identify_imagesize(self, image_type, image_path='<STR_LIT>'):

dims = ()<EOL>try:<EOL><INDENT>if (image_type.lower() == '<STR_LIT>'):<EOL><INDENT>dims = np.shape(ndpng.load('<STR_LIT>'.format(<EOL>image_path, image_type<EOL>)))<EOL><DEDENT>elif (image_type.lower() == '<STR_LIT>' or image_type.lower() == '<STR_LIT>'):<EOL><INDENT>dims = np.shape(ndtiff.load('<STR_LIT>'.format(<EOL>image_path, image_type<EOL>)))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>except:<EOL><INDENT>raise OSError('<STR_LIT>'.format(<EOL>image_path,<EOL>image_type<EOL>))<EOL><DEDENT>return dims[::-<NUM_LIT:1>]<EOL>

Identify the image size using the data location and other parameters


def post_data(self, file_name=None, legacy=False,<EOL>verifytype=VERIFY_BY_SLICE):

if (file_name is None):<EOL><INDENT>complete_example = (<EOL>self.dataset, self.project, self.channels, self.metadata)<EOL>data = json.loads(self.nd_json(*complete_example))<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>with open(file_name) as data_file:<EOL><INDENT>data = json.load(data_file)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>raise OSError("<STR_LIT>")<EOL><DEDENT><DEDENT>self.put_data(data)<EOL>

Arguments:
    file_name (str): The file name of the json file to post (optional).
        If this is left unspecified it is assumed the data is in the
        AutoIngest object.
    dev (bool): If pushing to a microns dev branch server set this
        to True, if not leave False.
    verifytype (enum): Set http verification type, by checking the
        first slice is accessible or by checking channel folder.
        NOTE: If verification occurs by folder there is NO image size
        or type verification. Enum: [Folder, Slice]

Returns:
    None


return self.resources.list_datasets(get_global_public)<EOL>

Lists datasets in resources. Setting 'get_global_public' to 'True'
will retrieve all public datasets in cloud. 'False' will get user's
public datasets.

Arguments:
    get_global_public (bool): True if user wants all public datasets in
                              cloud. False if user wants only their
                              public datasets.

Returns:
    dict: Returns datasets in JSON format


return self.resources.list_projects(dataset_name)<EOL>

Lists a set of projects related to a dataset.

Arguments:
    dataset_name (str): Dataset name to search projects for

Returns:
    dict: Projects found based on dataset query


return self.resources.delete_token(token_name,<EOL>project_name,<EOL>dataset_name)<EOL>

Delete a token with the given parameters.
Arguments:
    project_name (str): Project name
    dataset_name (str): Dataset name project is based on
    token_name (str): Token name
    channel_name (str): Channel name project is based on
Returns:
    bool: True if project deleted, false if not deleted.


def post_cutout(self, token, channel,<EOL>x_start,<EOL>y_start,<EOL>z_start,<EOL>data,<EOL>resolution=<NUM_LIT:0>):

return self.data.post_cutout(token, channel,<EOL>x_start,<EOL>y_start,<EOL>z_start,<EOL>data,<EOL>resolution)<EOL>

Post a cutout to the server.

Arguments:
    token (str)
    channel (str)
    x_start (int)
    y_start (int)
    z_start (int)
    data (numpy.ndarray): A numpy array of data. Pass in (x, y, z)
    resolution (int : 0): Resolution at which to insert the data

Returns:
    bool: True on success

Raises:
    RemoteDataUploadError: if there's an issue during upload.


return self.resources.get_dataset(name)<EOL>

Returns info regarding a particular dataset.

Arugments:
    name (str): Dataset name

Returns:
    dict: Dataset information


if not endpoint.startswith('<STR_LIT:/>'):<EOL><INDENT>endpoint = "<STR_LIT:/>" + endpoint<EOL><DEDENT>return self.protocol + "<STR_LIT>" + self.hostname + endpoint<EOL>

Get the base URL of the Remote.

Arguments:
    None
Returns:
    `str` base URL


url = self.url() + "<STR_LIT>".format(dataset_name)+ "<STR_LIT>".format(project_name)+ "<STR_LIT>".format(token_name)<EOL>req = self.remote_utils.delete_url(url)<EOL>if req.status_code is not <NUM_LIT>:<EOL><INDENT>raise RemoteDataUploadError("<STR_LIT>".format(req.text))<EOL><DEDENT>if req.content == "<STR_LIT>" or req.content == b'<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>


url = self.url() + "<STR_LIT>"<EOL>req = self.remote_utils.get_url(url)<EOL>if req.status_code is not <NUM_LIT:200>:<EOL><INDENT>raise RemoteDataNotFoundError('<STR_LIT>'.format(req.text))<EOL><DEDENT>else:<EOL><INDENT>return req.json()<EOL><DEDENT>

Lists a set of tokens that are public in Neurodata.
Arguments:
Returns:
    dict: Public tokens found in Neurodata


url = self.url() + "<STR_LIT>".format(dataset_name)+ "<STR_LIT>"<EOL>req = self.remote_utils.get_url(url)<EOL>if req.status_code is not <NUM_LIT:200>:<EOL><INDENT>raise RemoteDataNotFoundError('<STR_LIT>'.format(req.text))<EOL><DEDENT>else:<EOL><INDENT>return req.json()<EOL><DEDENT>


self._check_channel(channel_name)<EOL>if channel_type not in ['<STR_LIT:image>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError('<STR_LIT>' +<EOL>'<STR_LIT>')<EOL><DEDENT>if readonly * <NUM_LIT:1> not in [<NUM_LIT:0>, <NUM_LIT:1>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>url = self.url() + "<STR_LIT>".format(dataset_name)+ "<STR_LIT>".format(project_name) +"<STR_LIT>".format(channel_name)<EOL>json = {<EOL>"<STR_LIT>": channel_name,<EOL>"<STR_LIT>": channel_type,<EOL>"<STR_LIT>": dtype,<EOL>"<STR_LIT>": startwindow,<EOL>"<STR_LIT>": endwindow,<EOL>'<STR_LIT>': start_time,<EOL>'<STR_LIT>': end_time,<EOL>'<STR_LIT>': readonly,<EOL>'<STR_LIT>': propagate,<EOL>'<STR_LIT>': resolution,<EOL>'<STR_LIT>': channel_description<EOL>}<EOL>req = self.remote_utils.post_url(url, json=json)<EOL>if req.status_code is not <NUM_LIT>:<EOL><INDENT>raise RemoteDataUploadError('<STR_LIT>'.format(req.text))<EOL><DEDENT>if req.content == "<STR_LIT>" or req.content == b'<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Create a new channel on the Remote, using channel_data.

Arguments:
    channel_name (str): Channel name
    project_name (str): Project name
    dataset_name (str): Dataset name
    channel_type (str): Type of the channel (e.g. `neurodata.IMAGE`)
    dtype (str): The datatype of the channel's data (e.g. `uint8`)
    startwindow (int): Window to start in
    endwindow (int): Window to end in
    readonly (int): Can others write to this channel?
    propagate (int): Allow propogation? 1 is True, 0 is False
    resolution (int): Resolution scaling
    channel_description (str): Your description of the channel

Returns:
    bool: `True` if successful, `False` otherwise.

Raises:
    ValueError: If your args were bad :(
    RemoteDataUploadError: If the channel data is valid but upload
        fails for some other reason.


def get_propagate_status(self, token, channel):

url = self.url('<STR_LIT>'.format(token, channel))<EOL>req = self.remote_utils.get_url(url)<EOL>if req.status_code is not <NUM_LIT:200>:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(token, channel))<EOL><DEDENT>return req.text<EOL>

Get the propagate status for a token/channel pair.

Arguments:
    token (str): The token to check
    channel (str): The channel to check

Returns:
    str: The status code


return "<STR_LIT>".format(<EOL>self.hostname,<EOL>self.protocol,<EOL>self.meta_url,<EOL>self.meta_protocol<EOL>)<EOL>

Return a string representation that can be used to reproduce this
instance. `eval(repr(this))` should return an identical copy.

Arguments:
    None

Returns:
    str: Representation of reproducible instance.


super(Exception, self).__init__(message)<EOL>


def get_cutout(self, token, channel,<EOL>x_start, x_stop,<EOL>y_start, y_stop,<EOL>z_start, z_stop,<EOL>t_start=<NUM_LIT:0>, t_stop=<NUM_LIT:1>,<EOL>resolution=<NUM_LIT:1>,<EOL>block_size=DEFAULT_BLOCK_SIZE,<EOL>neariso=False):

if block_size is None:<EOL><INDENT>block_size = self.get_block_size(token, resolution)<EOL><DEDENT>origin = self.get_image_offset(token, resolution)<EOL>if (z_stop - z_start) < <NUM_LIT:16>:<EOL><INDENT>z_slices = <NUM_LIT:16><EOL><DEDENT>else:<EOL><INDENT>z_slices = z_stop - z_start<EOL><DEDENT>size = (x_stop - x_start) * (y_stop - y_start) * z_slices * <NUM_LIT:4><EOL>if six.PY2:<EOL><INDENT>dl_func = self._get_cutout_blosc_no_chunking<EOL><DEDENT>elif six.PY3:<EOL><INDENT>dl_func = self._get_cutout_no_chunking<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if size < self._chunk_threshold:<EOL><INDENT>vol = dl_func(token, channel, resolution,<EOL>x_start, x_stop,<EOL>y_start, y_stop,<EOL>z_start, z_stop,<EOL>t_start, t_stop,<EOL>neariso=neariso)<EOL>vol = numpy.rollaxis(vol, <NUM_LIT:1>)<EOL>vol = numpy.rollaxis(vol, <NUM_LIT:2>)<EOL>return vol<EOL><DEDENT>else:<EOL><INDENT>from ndio.utils.parallel import block_compute<EOL>blocks = block_compute(x_start, x_stop,<EOL>y_start, y_stop,<EOL>z_start, z_stop,<EOL>origin, block_size)<EOL>vol = numpy.zeros(((z_stop - z_start),<EOL>(y_stop - y_start),<EOL>(x_stop - x_start)))<EOL>for b in blocks:<EOL><INDENT>data = dl_func(token, channel, resolution,<EOL>b[<NUM_LIT:0>][<NUM_LIT:0>], b[<NUM_LIT:0>][<NUM_LIT:1>],<EOL>b[<NUM_LIT:1>][<NUM_LIT:0>], b[<NUM_LIT:1>][<NUM_LIT:1>],<EOL>b[<NUM_LIT:2>][<NUM_LIT:0>], b[<NUM_LIT:2>][<NUM_LIT:1>],<EOL><NUM_LIT:0>, <NUM_LIT:1>,<EOL>neariso=neariso)<EOL>if b == blocks[<NUM_LIT:0>]:  <EOL><INDENT>vol = numpy.zeros(((z_stop - z_start),<EOL>(y_stop - y_start),<EOL>(x_stop - x_start)), dtype=data.dtype)<EOL><DEDENT>vol[b[<NUM_LIT:2>][<NUM_LIT:0>] - z_start: b[<NUM_LIT:2>][<NUM_LIT:1>] - z_start,<EOL>b[<NUM_LIT:1>][<NUM_LIT:0>] - y_start: b[<NUM_LIT:1>][<NUM_LIT:1>] - y_start,<EOL>b[<NUM_LIT:0>][<NUM_LIT:0>] - x_start: b[<NUM_LIT:0>][<NUM_LIT:1>] - x_start] = data<EOL><DEDENT>vol = numpy.rollaxis(vol, <NUM_LIT:1>)<EOL>vol = numpy.rollaxis(vol, <NUM_LIT:2>)<EOL>return vol<EOL><DEDENT>

Get volumetric cutout data from the neurodata server.

Arguments:
    token (str): Token to identify data to download
    channel (str): Channel
    resolution (int): Resolution level
    Q_start (int): The lower bound of dimension 'Q'
    Q_stop (int): The upper bound of dimension 'Q'
    block_size (int[3]): Block size of this dataset. If not provided,
        ndio uses the metadata of this tokenchannel to set. If you find
        that your downloads are timing out or otherwise failing, it may
        be wise to start off by making this smaller.
    neariso (bool : False): Passes the 'neariso' param to the cutout.
        If you don't know what this means, ignore it!

Returns:
    numpy.ndarray: Downloaded data.


def get_xy_slice(self, token, channel,<EOL>x_start, x_stop,<EOL>y_start, y_stop,<EOL>z_index,<EOL>resolution=<NUM_LIT:0>):

vol = self.get_cutout(token, channel, x_start, x_stop, y_start,<EOL>y_stop, z_index, z_index + <NUM_LIT:1>, resolution)<EOL>vol = numpy.squeeze(vol)  <EOL>return vol<EOL>

Return a binary-encoded, decompressed 2d image. You should
specify a 'token' and 'channel' pair.  For image data, users
should use the channel 'image.'

Arguments:
    token (str): Token to identify data to download
    channel (str): Channel
    resolution (int): Resolution level
    Q_start (int):` The lower bound of dimension 'Q'
    Q_stop (int): The upper bound of dimension 'Q'
    z_index (int): The z-slice to image

Returns:
    str: binary image data


req = requests.post(self.meta_url("<STR_LIT>" + token),<EOL>json=data, verify=False)<EOL>if req.status_code != <NUM_LIT:200>:<EOL><INDENT>raise RemoteDataUploadError(<EOL>"<STR_LIT>" + req.json()['<STR_LIT:message>']<EOL>)<EOL><DEDENT>return req.json()<EOL>

Insert new metadata into the OCP metadata database.

Arguments:
    token (str): Token of the datum to set
    data (str): A dictionary to insert as metadata. Include `secret`.

Returns:
    json: Info of the inserted ID (convenience) or an error message.

Throws:
    RemoteDataUploadError: If the token is already populated, or if
        there is an issue with your specified `secret` key.


def add_subvolume(self, token, channel, secret,<EOL>x_start, x_stop,<EOL>y_start, y_stop,<EOL>z_start, z_stop,<EOL>resolution, title, notes):

md = self.get_metadata(token)['<STR_LIT>']<EOL>if '<STR_LIT>' in md:<EOL><INDENT>subvols = md['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>subvols = []<EOL><DEDENT>subvols.append({<EOL>'<STR_LIT>': token,<EOL>'<STR_LIT>': channel,<EOL>'<STR_LIT>': x_start,<EOL>'<STR_LIT>': x_stop,<EOL>'<STR_LIT>': y_start,<EOL>'<STR_LIT>': y_stop,<EOL>'<STR_LIT>': z_start,<EOL>'<STR_LIT>': z_stop,<EOL>'<STR_LIT>': resolution,<EOL>'<STR_LIT:title>': title,<EOL>'<STR_LIT>': notes<EOL>})<EOL>return self.set_metadata(token, {<EOL>'<STR_LIT>': secret,<EOL>'<STR_LIT>': subvols<EOL>})<EOL>

Adds a new subvolume to a token/channel.

Arguments:
    token (str): The token to write to in LIMS
    channel (str): Channel to add in the subvolume. Can be `None`
    x_start (int): Start in x dimension
    x_stop (int): Stop in x dimension
    y_start (int): Start in y dimension
    y_stop (int): Stop in y dimension
    z_start (int): Start in z dimension
    z_stop (int): Stop in z dimension
    resolution (int): The resolution at which this subvolume is seen
    title (str): The title to set for the subvolume
    notes (str): Optional extra thoughts on the subvolume

Returns:
    boolean: success


r = self.remote_utils.get_url(self.url() + "<STR_LIT>")<EOL>return r.json()<EOL>

Get a list of public tokens available on this server.

Arguments:
    None

Returns:
    str[]: list of public tokens


r = self.remote_utils.get_url(self.url() + "<STR_LIT>".format(token))<EOL>return r.json()<EOL>

Return the project info for a given token.

Arguments:
    token (str): Token to return information for

Returns:
    JSON: representation of proj_info


return self.get_proj_info(token)['<STR_LIT>']<EOL>

Wraps get_proj_info to return a dictionary of just the channels of
a given project.

Arguments:
    token (str): Token to return channels for

Returns:
    JSON: dictionary of channels.


md = self.get_metadata(token)['<STR_LIT>']<EOL>if '<STR_LIT>' in md:<EOL><INDENT>return md['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Return a list of subvolumes taken from LIMS, if available.

Arguments:
    token (str): The token to read from in LIMS

Returns:
    dict: or None if unavailable


return list(self.get_public_datasets_and_tokens().keys())<EOL>

NOTE: VERY SLOW!
Get a list of public datasets. Different than public tokens!

Arguments:
    None

Returns:
    str[]: list of public datasets


return "<STR_LIT>".format(<EOL>self.hostname,<EOL>self.protocol,<EOL>self.email<EOL>)<EOL>

Returns a string representation that can be used to reproduce this
instance. `eval(repr(this))` should return an identical copy.

Arguments:
    None

Returns:
    str: Representation of reproducible instance.


def convert_graph(self, graph_file, input_format, output_formats,<EOL>email=None, use_threads=False, callback=None):

if email is None:<EOL><INDENT>email = self.email<EOL><DEDENT>if input_format not in GraphFormats._any:<EOL><INDENT>raise ValueError("<STR_LIT>".format(input_format))<EOL><DEDENT>if not set(output_formats) <= set(GraphFormats._any):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if use_threads and callback is not None:<EOL><INDENT>if not hasattr(callback, '<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(inspect.getargspec(callback).args) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>if not (os.path.exists(graph_file)):<EOL><INDENT>raise ValueError("<STR_LIT>".format(graph_file))<EOL><DEDENT>url = "<STR_LIT>".format(<EOL>email,<EOL>input_format,<EOL>'<STR_LIT:U+002C>'.join(output_formats)<EOL>)<EOL>if "<STR_LIT:U+0020>" in url:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if use_threads:<EOL><INDENT>convert_thread = threading.Thread(<EOL>target=self._run_convert_graph,<EOL>args=[url, graph_file, callback]<EOL>)<EOL>convert_thread.start()<EOL><DEDENT>else:<EOL><INDENT>return self._run_convert_graph(url, graph_file)<EOL><DEDENT>return<EOL>

Convert a graph from one GraphFormat to another.

Arguments:
    graph_file (str): Filename of the file to convert
    input_format (str): A grute.GraphFormats
    output_formats (str[]): A grute.GraphFormats
    email (str: self.email)*: The email to notify
    use_threads (bool: False)*: Whether to use Python threads to run
        computation in the background when waiting for the server
    callback (function: None)*: The function to run upon completion of
        the call, if using threads. (Will not be called if use_threads
        is set to False.)

Returns:
    HTTP Response if use_threads=False. Else, no return value.

Raises:
    RemoteDataUploadError: If there's an issue uploading the data
    RemoteError: If there's a server-side issue
    ValueError: If there's a problem with the supplied arguments


super(grute, self).__init__(hostname, protocol)<EOL>self.email = email<EOL>

Initialize a new grute remote.

Arguments:
    hostname (str: "openconnecto.me"): The hostname where grute lives
    protocol (str: "http"): The protocol over which to access grute
    email (str: ""): The email to which completion notifications should
        be sent (unless overridden in individual calls). Note that the
        completion URLs are also accessible via this Python API.


if type(json) is str:<EOL><INDENT>json = jsonlib.loads(json)<EOL><DEDENT>out_ramons = []<EOL>for (rid, rdata) in six.iteritems(json):<EOL><INDENT>_md = rdata['<STR_LIT>']<EOL>r = AnnotationType.RAMON(rdata['<STR_LIT:type>'])(<EOL>id=rid,<EOL>author=_md['<STR_LIT>'],<EOL>status=_md['<STR_LIT:status>'],<EOL>confidence=_md['<STR_LIT>'],<EOL>kvpairs=copy.deepcopy(_md['<STR_LIT>'])<EOL>)<EOL>if rdata['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>r.segmentclass = _md.get('<STR_LIT>')<EOL>r.neuron = _md.get('<STR_LIT>')<EOL>if '<STR_LIT>' in _md:<EOL><INDENT>r.synapses = _md['<STR_LIT>'][:]<EOL><DEDENT>if '<STR_LIT>' in _md:<EOL><INDENT>r.organelles = _md['<STR_LIT>'][:]<EOL><DEDENT><DEDENT>elif rdata['<STR_LIT:type>'] in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>if '<STR_LIT>' in _md:<EOL><INDENT>r.segments = _md['<STR_LIT>'][:]<EOL><DEDENT><DEDENT>elif rdata['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>r.organelle_class = _md['<STR_LIT>'][:]<EOL><DEDENT>elif rdata['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>r.synapse_type = _md.get('<STR_LIT>')<EOL>r.weight = _md.get('<STR_LIT>')<EOL><DEDENT>out_ramons.append(r)<EOL><DEDENT>return out_ramons<EOL>

Converts JSON to a python list of RAMON objects. if `cutout` is provided,
the `cutout` attribute of the RAMON object is populated. Otherwise, it's
left empty. `json` should be an ID-level dictionary, like so:

    {
        16: {
            type: "segment",
            metadata: {
                . . .
            }
        },
    }

NOTE: If more than one item is in the dictionary, then a Python list of
RAMON objects is returned instead of a single RAMON.

Arguments:
    json (str or dict): The JSON to import to RAMON objects
    cutout: Currently not supported.

Returns:
    [RAMON]


if issubclass(type(ramon), RAMONBase) is False:<EOL><INDENT>raise InvalidRAMONError("<STR_LIT>")<EOL><DEDENT>import h5py<EOL>import numpy<EOL>if hdf5 is None:<EOL><INDENT>tmpfile = tempfile.NamedTemporaryFile(delete=False)<EOL><DEDENT>else:<EOL><INDENT>tmpfile = hdf5<EOL><DEDENT>with h5py.File(tmpfile.name, "<STR_LIT:a>") as hdf5:<EOL><INDENT>grp = hdf5.create_group(str(ramon.id))<EOL>grp.create_dataset("<STR_LIT>", (<NUM_LIT:1>,),<EOL>numpy.uint32,<EOL>data=AnnotationType.get_int(type(ramon)))<EOL>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>if ramon.cutout is not None:<EOL><INDENT>grp.create_dataset('<STR_LIT>', ramon.cutout.shape,<EOL>ramon.cutout.dtype, data=ramon.cutout)<EOL>grp.create_dataset('<STR_LIT>', (<NUM_LIT:1>,),<EOL>numpy.uint32, data=ramon.resolution)<EOL>grp.create_dataset('<STR_LIT>', (<NUM_LIT:3>,),<EOL>numpy.uint32, data=ramon.xyz_offset)<EOL><DEDENT><DEDENT>metadata = grp.create_group('<STR_LIT>')<EOL>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,),<EOL>dtype=h5py.special_dtype(vlen=str),<EOL>data=ramon.author)<EOL>fstring = StringIO()<EOL>csvw = csv.writer(fstring, delimiter='<STR_LIT:U+002C>')<EOL>csvw.writerows([r for r in six.iteritems(ramon.kvpairs)])<EOL>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,),<EOL>dtype=h5py.special_dtype(vlen=str),<EOL>data=fstring.getvalue())<EOL>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,), numpy.float,<EOL>data=ramon.confidence)<EOL>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,), numpy.uint32,<EOL>data=ramon.status)<EOL>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>metadata.create_dataset('<STR_LIT>',<EOL>data=numpy.asarray(ramon.segments,<EOL>dtype=numpy.uint32))<EOL><DEDENT>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,), numpy.uint32,<EOL>data=ramon.synapse_type)<EOL><DEDENT>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,),<EOL>numpy.float, data=ramon.weight)<EOL><DEDENT>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,),<EOL>numpy.uint32, data=ramon.neuron)<EOL><DEDENT>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,), numpy.uint32,<EOL>data=ramon.segmentclass)<EOL><DEDENT>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>metadata.create_dataset('<STR_LIT>', (len(ramon.synapses),),<EOL>numpy.uint32, data=ramon.synapses)<EOL><DEDENT>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>metadata.create_dataset('<STR_LIT>',<EOL>(len(ramon.organelles),),<EOL>numpy.uint32,<EOL>data=ramon.organelles)<EOL><DEDENT>if hasattr(ramon, '<STR_LIT>'):<EOL><INDENT>metadata.create_dataset('<STR_LIT>', (<NUM_LIT:1>,),<EOL>numpy.uint32,<EOL>data=ramon.organelle_class)<EOL><DEDENT>hdf5.flush()<EOL>tmpfile.seek(<NUM_LIT:0>)<EOL>return tmpfile<EOL><DEDENT>return False<EOL>

Exports a RAMON object to an HDF5 file object.

Arguments:
    ramon (RAMON): A subclass of RAMONBase
    hdf5 (str): Export filename

Returns:
    hdf5.File

Raises:
    InvalidRAMONError: if you pass a non-RAMON object


if type(ramons) is not list:<EOL><INDENT>ramons = [ramons]<EOL><DEDENT>out_ramons = {}<EOL>for r in ramons:<EOL><INDENT>out_ramons[r.id] = {<EOL>"<STR_LIT:id>": r.id,<EOL>"<STR_LIT:type>": _reverse_ramon_types[type(r)],<EOL>"<STR_LIT>": vars(r)<EOL>}<EOL><DEDENT>return out_ramons<EOL>

Converts a RAMON object list to a JSON-style dictionary. Useful for going
from an array of RAMONs to a dictionary, indexed by ID.

Arguments:
    ramons (RAMON[]): A list of RAMON objects
    flatten (boolean: False): Not implemented

Returns:
    dict: A python dictionary of RAMON objects.


self.xyz_offset = xyz_offset<EOL>self.resolution = resolution<EOL>self.cutout = cutout<EOL>self.voxels = voxels<EOL>RAMONBase.__init__(self, id=id, confidence=confidence,<EOL>kvpairs=kvpairs,<EOL>status=status, author=author)<EOL>

Initialize a new RAMONVolume object. Inherits attributes from RAMONBase
as well as:

Arguments:
    xyz_offset (int[3] : (0, 0, 0)): x,y,z coordinates of the minimum
        corner of the cube (if data is a cutout), otherwise empty
    resolution (int : 0): level in the database resolution hierarchy
    cutout (numpy.ndarray): dense matrix of data
    voxels: Unused for now


self.id = id<EOL>self.confidence = confidence<EOL>self.kvpairs = kvpairs<EOL>self.status = status<EOL>self.author = author<EOL>

Initialize a new RAMONBase object with default attributes.

Arguments:
    id (int): Unique 32-bit ID value assigned by OCP database
    confidence (float): Value 0-1 indicating confidence in annotation
    kvpairs (dict): A collection of key-value pairs
    status (string): Status of annotation in database
    author (string): Username of the person who created the annotation


dimensions = len(voxels[<NUM_LIT:0>])<EOL>for d in range(len(dimensions)):<EOL><INDENT>size.append(max([i[d] for i in voxels]))<EOL><DEDENT>result = numpy.zeros(dimensions)<EOL>for v in voxels:<EOL><INDENT>result[v] = <NUM_LIT:1><EOL><DEDENT>return result<EOL>

Converts a voxel list to an ndarray.

Arguments:
    voxels (tuple[]): A list of coordinates indicating coordinates of
        populated voxels in an ndarray.

Returns:
    numpy.ndarray The result of the transformation.


<EOL>nifti_filename = os.path.expanduser(nifti_filename)<EOL>try:<EOL><INDENT>nifti_img = nib.Nifti1Image(numpy_data, numpy.eye(<NUM_LIT:4>))<EOL>nib.save(nifti_img, nifti_filename)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise ValueError("<STR_LIT>".format(nifti_filename))<EOL><DEDENT>return nifti_filename<EOL>

Export a numpy array to a nifti file.  TODO: currently using dummy
headers and identity matrix affine transform. This can be expanded.

Arguments:
    nifti_filename (str): A filename to which to save the nifti data
    numpy_data (numpy.ndarray): The numpy array to save to nifti

Returns:
    String. The expanded filename that now holds the nifti data


<EOL>files = glob.glob(png_filename_base)<EOL>files.sort()<EOL>numpy_data = []<EOL>for f in files:<EOL><INDENT>numpy_data.append(load(f))<EOL><DEDENT>return numpy.concatenate(numpy_data)<EOL>

Import all files matching the filename base given with `png_filename_base`.
Images are ordered by alphabetical order, which means that you *MUST* 0-pad
your numbers if they span a power of ten (e.g. 0999-1000 or 09-10). This is
handled automatically by its complementary function, `png.save_collection`.
Also, look at how nicely these documentation lines are all the same length!

Arguments:
    png_filename_base (str): An asterisk-wildcard string that should refer
        to all PNGs in the stack. All *s are replaced according to regular
        cmd-line expansion rules. See the 'glob' documentation for details
Returns:
    A numpy array holding a 3D dataset


<EOL>files = glob.glob(tiff_filename_base)<EOL>files.sort()<EOL>numpy_data = []<EOL>for f in files:<EOL><INDENT>numpy_data.append(load(f))<EOL><DEDENT>return numpy.concatenate(numpy_data)<EOL>

Import all files matching the filename base given via `tiff_filename_base`.
Images are ordered by alphabetical order, which means that you *MUST* 0-pad
your numbers if they span a power of ten (e.g. 0999-1000 or 09-10). This is
handled automatically by the complement function, `save_collection`.
Also, look at how nicely these documentation lines are all the same length!

Arguments:
    tiff_filename_base:     An asterisk-wildcard string that should refer
                            to all TIFFs in the stack. All * are replaced
                            according to command-line expansion rules.

Returns:
    A numpy array holding a 3D dataset


d={'<STR_LIT>':frame}         <EOL>d.update(frame.f_globals)  <EOL>d.update(frame.f_locals)<EOL>i = code.InteractiveConsole(d)<EOL>message  = "<STR_LIT>"<EOL>message += '<STR_LIT>'.join(traceback.format_stack(frame))<EOL>i.interact(message)<EOL>

Interrupt running process, and provide a python prompt for
    interactive debugging.

    source: http://stackoverflow.com/questions/132058/showing-the-stack-trace-from-a-running-python-application


def add_task(self, func, *args, **kargs):

self.tasks.put((func, args, kargs))<EOL>


Run this function inside a different thread.

    :param transport: transport handler. We need to pass it in since any
        assertion we do inside this thread gets silently swallowed, so we
        need a way to return the results to the main thread.
    :type transport: MockTransportHandler


Main function to log all the annotations stored during the entire
        request. This is done if the request is sampled and the response was
        a success. It also logs the service (`ss` and `sr`) or the client
        ('cs' and 'cr') annotations.


return '<STR_LIT>'.format(random.getrandbits(<NUM_LIT:64>))<EOL>

Returns a 64 bit UTF-8 encoded string. In the interests of simplicity,
    this is always cast to a `str` instead of (in py2 land) a unicode string.
    Certain clients (I'm looking at you, Twisted) don't enjoy unicode headers.

    :returns: random 16-character string


from py_zipkin.storage import ThreadLocalStack<EOL>log.warning('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return ThreadLocalStack().push(zipkin_attr)<EOL>

Stores the zipkin attributes to thread local.

    .. deprecated::
       Use the Tracer interface which offers better multi-threading support.
       push_zipkin_attrs will be removed in version 1.0.

    :param zipkin_attr: tuple containing zipkin related attrs
    :type zipkin_attr: :class:`zipkin.ZipkinAttrs`


<EOL>if self._is_local_root_span:<EOL><INDENT>if self.sample_rate is not None:<EOL><INDENT>if self.zipkin_attrs_override andnot self.zipkin_attrs_override.is_sampled:<EOL><INDENT>return True, create_attrs_for_span(<EOL>sample_rate=self.sample_rate,<EOL>trace_id=self.zipkin_attrs_override.trace_id,<EOL>)<EOL><DEDENT>elif not self.zipkin_attrs_override:<EOL><INDENT>return True, create_attrs_for_span(<EOL>sample_rate=self.sample_rate,<EOL>use_128bit_trace_id=self.use_128bit_trace_id,<EOL>)<EOL><DEDENT><DEDENT>if self.firehose_handler and not self.zipkin_attrs_override:<EOL><INDENT>return True, create_attrs_for_span(<EOL>sample_rate=<NUM_LIT:0.0>,<EOL>use_128bit_trace_id=self.use_128bit_trace_id,<EOL>)<EOL><DEDENT>return False, self.zipkin_attrs_override<EOL><DEDENT>else:<EOL><INDENT>existing_zipkin_attrs = self.get_tracer().get_zipkin_attrs()<EOL>if existing_zipkin_attrs:<EOL><INDENT>return False, ZipkinAttrs(<EOL>trace_id=existing_zipkin_attrs.trace_id,<EOL>span_id=generate_random_64bit_string(),<EOL>parent_span_id=existing_zipkin_attrs.span_id,<EOL>flags=existing_zipkin_attrs.flags,<EOL>is_sampled=existing_zipkin_attrs.is_sampled,<EOL>)<EOL><DEDENT><DEDENT>return False, None<EOL>

Returns the current ZipkinAttrs and generates new ones if needed.

        :returns: (report_root_timestamp, zipkin_attrs)
        :rtype: (bool, ZipkinAttrs)


_validate_args(kwargs)<EOL>kwargs['<STR_LIT>'] = Kind.SERVER<EOL>super(zipkin_server_span, self).__init__(*args, **kwargs)<EOL>

Logs a zipkin span with server annotations.

        See :class:`zipkin_span` for arguments


self.span_name = name<EOL>if self.logging_context:<EOL><INDENT>self.logging_context.span_name = name<EOL><DEDENT>

Overrides the current span name.

        This is useful if you don't know the span name yet when you create the
        zipkin_span object. i.e. pyramid_zipkin doesn't know which route the
        request matched until the function wrapped by the context manager
        completes.

        :param name: New span name
        :type name: str


transport = TMemoryBuffer()<EOL>protocol = TBinaryProtocol(transport)<EOL>thrift_span.write(protocol)<EOL>return bytes(transport.getvalue())<EOL>

Returns a TBinaryProtocol encoded Thrift span.

:param thrift_span: thrift object to encode.
:returns: thrift object in TBinaryProtocol format bytes.


<EOL>ann_type = zipkin_core.AnnotationType.STRING<EOL>return [<EOL>create_binary_annotation(key, str(value), ann_type, host)<EOL>for key, value in binary_annotations.items()<EOL>]<EOL>

Reformat binary annotations dict to return list of zipkin_core objects. The
value of the binary annotations MUST be in string format.

:param binary_annotations: dict with key, value being the name and value
                           of the binary annotation being logged.
:type host: :class:`zipkin_core.Endpoint`
:returns: a list of binary annotation zipkin_core objects
:rtype: list


self.trace_id = trace_id<EOL>self.name = name<EOL>self.parent_id = parent_id<EOL>self.span_id = span_id<EOL>self.kind = kind<EOL>self.timestamp = timestamp<EOL>self.duration = duration<EOL>self.local_endpoint = local_endpoint<EOL>self.remote_endpoint = remote_endpoint<EOL>self.debug = debug<EOL>self.shared = shared<EOL>self.annotations = annotations or {}<EOL>self.tags = tags or {}<EOL>if not isinstance(kind, Kind):<EOL><INDENT>raise ZipkinError(<EOL>'<STR_LIT>'.format(kind))<EOL><DEDENT>if local_endpoint and not isinstance(local_endpoint, Endpoint):<EOL><INDENT>raise ZipkinError(<EOL>'<STR_LIT>')<EOL><DEDENT>if remote_endpoint and not isinstance(remote_endpoint, Endpoint):<EOL><INDENT>raise ZipkinError(<EOL>'<STR_LIT>')<EOL><DEDENT>

Creates a new Span.

        :param trace_id: Trace id.
        :type trace_id: str
        :param name: Name of the span.
        :type name: str
        :param parent_id: Parent span id.
        :type parent_id: str
        :param span_id: Span id.
        :type span_id: str
        :param kind: Span type (client, server, local, etc...)
        :type kind: Kind
        :param timestamp: start timestamp in seconds.
        :type timestamp: float
        :param duration: span duration in seconds.
        :type duration: float
        :param local_endpoint: the host that recorded this span.
        :type local_endpoint: Endpoint
        :param remote_endpoint: the remote service.
        :type remote_endpoint: Endpoint
        :param debug: True is a request to store this span even if it
            overrides sampling policy.
        :type debug: bool
        :param shared: True if we are contributing to a span started by
            another tracer (ex on a different host).
        :type shared: bool
        :param annotations: Optional dict of str -> timestamp annotations.
        :type annotations: dict
        :param tags: Optional dict of str -> str span tags.
        :type tags: dict


def fits(self, current_count, current_size, max_size, new_span):

return current_size + len(new_span) <= max_size<EOL>

Checks if the new span fits in the max payload size.


return <NUM_LIT:2> + current_count + current_size + len(new_span) <= max_size<EOL>

Checks if the new span fits in the max payload size.

        Json lists only have a 2 bytes overhead from '[]' plus 1 byte from
        ',' between elements


json_span = {<EOL>'<STR_LIT>': span.trace_id,<EOL>'<STR_LIT:id>': span.span_id,<EOL>}<EOL>if span.name:<EOL><INDENT>json_span['<STR_LIT:name>'] = span.name<EOL><DEDENT>if span.parent_id:<EOL><INDENT>json_span['<STR_LIT>'] = span.parent_id<EOL><DEDENT>if span.timestamp:<EOL><INDENT>json_span['<STR_LIT>'] = int(span.timestamp * <NUM_LIT>)<EOL><DEDENT>if span.duration:<EOL><INDENT>json_span['<STR_LIT>'] = int(span.duration * <NUM_LIT>)<EOL><DEDENT>if span.shared is True:<EOL><INDENT>json_span['<STR_LIT>'] = True<EOL><DEDENT>if span.kind and span.kind.value is not None:<EOL><INDENT>json_span['<STR_LIT>'] = span.kind.value<EOL><DEDENT>if span.local_endpoint:<EOL><INDENT>json_span['<STR_LIT>'] = self._create_json_endpoint(<EOL>span.local_endpoint,<EOL>False,<EOL>)<EOL><DEDENT>if span.remote_endpoint:<EOL><INDENT>json_span['<STR_LIT>'] = self._create_json_endpoint(<EOL>span.remote_endpoint,<EOL>False,<EOL>)<EOL><DEDENT>if span.tags and len(span.tags) > <NUM_LIT:0>:<EOL><INDENT>json_span['<STR_LIT>'] = span.tags<EOL><DEDENT>if span.annotations:<EOL><INDENT>json_span['<STR_LIT>'] = [<EOL>{<EOL>'<STR_LIT>': int(timestamp * <NUM_LIT>),<EOL>'<STR_LIT:value>': key,<EOL>}<EOL>for key, timestamp in span.annotations.items()<EOL>]<EOL><DEDENT>encoded_span = json.dumps(json_span)<EOL>return encoded_span<EOL>


if encoding == Encoding.V1_THRIFT:<EOL><INDENT>return _V1ThriftEncoder()<EOL><DEDENT>if encoding == Encoding.V1_JSON:<EOL><INDENT>return _V1JSONEncoder()<EOL><DEDENT>if encoding == Encoding.V2_JSON:<EOL><INDENT>return _V2JSONEncoder()<EOL><DEDENT>if encoding == Encoding.V2_PROTO3:<EOL><INDENT>return _V2ProtobufEncoder()<EOL><DEDENT>raise ZipkinError('<STR_LIT>'.format(encoding))<EOL>

Creates encoder object for the given encoding.

    :param encoding: desired output encoding protocol.
    :type encoding: Encoding
    :return: corresponding IEncoder object
    :rtype: IEncoder


<EOL>if isinstance(message, six.string_types):<EOL><INDENT>if six.PY2:<EOL><INDENT>message = six.b(message)  <EOL><DEDENT>else:<EOL><INDENT>message = message.encode('<STR_LIT:utf-8>')  <EOL><DEDENT><DEDENT>if len(message) < <NUM_LIT:2>:<EOL><INDENT>raise ZipkinError("<STR_LIT>")<EOL><DEDENT>if six.byte2int(message) <= <NUM_LIT:16>:<EOL><INDENT>if six.byte2int(message) == <NUM_LIT:10> and six.byte2int(message[<NUM_LIT:1>:<NUM_LIT:2>]) != <NUM_LIT:0>:<EOL><INDENT>return Encoding.V2_PROTO3<EOL><DEDENT>return Encoding.V1_THRIFT<EOL><DEDENT>str_msg = message.decode('<STR_LIT:utf-8>')<EOL>if str_msg[<NUM_LIT:0>] == '<STR_LIT:[>':<EOL><INDENT>span_list = json.loads(str_msg)<EOL>if len(span_list) > <NUM_LIT:0>:<EOL><INDENT>for span in span_list:<EOL><INDENT>if any(word in span for word in _V2_ATTRIBUTES):<EOL><INDENT>return Encoding.V2_JSON<EOL><DEDENT>elif (<EOL>'<STR_LIT>' in span or<EOL>(<EOL>'<STR_LIT>' in span and<EOL>'<STR_LIT>' in span['<STR_LIT>']<EOL>)<EOL>):<EOL><INDENT>return Encoding.V1_JSON<EOL><DEDENT><DEDENT>return Encoding.V2_JSON<EOL><DEDENT><DEDENT>raise ZipkinError("<STR_LIT>")<EOL>

Returns the span type and encoding for the message provided.

    The logic in this function is a Python port of
    https://github.com/openzipkin/zipkin/blob/master/zipkin/src/main/java/zipkin/internal/DetectingSpanDecoder.java

    :param message: span to perform operations on.
    :type message: byte array
    :returns: span encoding.
    :rtype: Encoding


raise NotImplementedError()<EOL>

Decodes an encoded list of spans.

        :param spans: encoded list of spans
        :type spans: bytes
        :return: list of spans
        :rtype: list of Span


decoded_spans = []<EOL>transport = TMemoryBuffer(spans)<EOL>if six.byte2int(spans) == TType.STRUCT:<EOL><INDENT>_, size = read_list_begin(transport)<EOL><DEDENT>else:<EOL><INDENT>size = <NUM_LIT:1><EOL><DEDENT>for _ in range(size):<EOL><INDENT>span = zipkin_core.Span()<EOL>span.read(TBinaryProtocol(transport))<EOL>decoded_spans.append(self._decode_thrift_span(span))<EOL><DEDENT>return decoded_spans<EOL>


parent_id = None<EOL>local_endpoint = None<EOL>annotations = {}<EOL>tags = {}<EOL>kind = Kind.LOCAL<EOL>remote_endpoint = None<EOL>timestamp = None<EOL>duration = None<EOL>if thrift_span.parent_id:<EOL><INDENT>parent_id = self._convert_unsigned_long_to_lower_hex(<EOL>thrift_span.parent_id,<EOL>)<EOL><DEDENT>if thrift_span.annotations:<EOL><INDENT>annotations, local_endpoint, kind, timestamp, duration =self._decode_thrift_annotations(thrift_span.annotations)<EOL><DEDENT>if thrift_span.binary_annotations:<EOL><INDENT>tags, local_endpoint, remote_endpoint =self._convert_from_thrift_binary_annotations(<EOL>thrift_span.binary_annotations,<EOL>)<EOL><DEDENT>trace_id = self._convert_trace_id_to_string(<EOL>thrift_span.trace_id,<EOL>thrift_span.trace_id_high,<EOL>)<EOL>return Span(<EOL>trace_id=trace_id,<EOL>name=thrift_span.name,<EOL>parent_id=parent_id,<EOL>span_id=self._convert_unsigned_long_to_lower_hex(thrift_span.id),<EOL>kind=kind,<EOL>timestamp=self.seconds(timestamp or thrift_span.timestamp),<EOL>duration=self.seconds(duration or thrift_span.duration),<EOL>local_endpoint=local_endpoint,<EOL>remote_endpoint=remote_endpoint,<EOL>shared=(kind == Kind.SERVER and thrift_span.timestamp is None),<EOL>annotations=annotations,<EOL>tags=tags,<EOL>)<EOL>

Decodes a thrift span.

        :param thrift_span: thrift span
        :type thrift_span: thrift Span object
        :returns: span builder representing this span
        :rtype: Span


local_endpoint = None<EOL>kind = Kind.LOCAL<EOL>all_annotations = {}<EOL>timestamp = None<EOL>duration = None<EOL>for thrift_annotation in thrift_annotations:<EOL><INDENT>all_annotations[thrift_annotation.value] = thrift_annotation.timestamp<EOL>if thrift_annotation.host:<EOL><INDENT>local_endpoint = self._convert_from_thrift_endpoint(<EOL>thrift_annotation.host,<EOL>)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in all_annotations and '<STR_LIT>' not in all_annotations:<EOL><INDENT>kind = Kind.CLIENT<EOL>timestamp = all_annotations['<STR_LIT>']<EOL>duration = all_annotations['<STR_LIT>'] - all_annotations['<STR_LIT>']<EOL><DEDENT>elif '<STR_LIT>' not in all_annotations and '<STR_LIT>' in all_annotations:<EOL><INDENT>kind = Kind.SERVER<EOL>timestamp = all_annotations['<STR_LIT>']<EOL>duration = all_annotations['<STR_LIT>'] - all_annotations['<STR_LIT>']<EOL><DEDENT>annotations = {<EOL>name: self.seconds(ts) for name, ts in all_annotations.items()<EOL>if name not in _DROP_ANNOTATIONS<EOL>}<EOL>return annotations, local_endpoint, kind, timestamp, duration<EOL>

Accepts a thrift annotation and converts it to a v1 annotation.

        :param thrift_annotations: list of thrift annotations.
        :type thrift_annotations: list of zipkin_core.Span.Annotation
        :returns: (annotations, local_endpoint, kind)


ipv4 = None<EOL>ipv6 = None<EOL>port = struct.unpack('<STR_LIT:H>', struct.pack('<STR_LIT:h>', thrift_endpoint.port))[<NUM_LIT:0>]<EOL>if thrift_endpoint.ipv4 != <NUM_LIT:0>:<EOL><INDENT>ipv4 = socket.inet_ntop(<EOL>socket.AF_INET,<EOL>struct.pack('<STR_LIT>', thrift_endpoint.ipv4),<EOL>)<EOL><DEDENT>if thrift_endpoint.ipv6:<EOL><INDENT>ipv6 = socket.inet_ntop(socket.AF_INET6, thrift_endpoint.ipv6)<EOL><DEDENT>return Endpoint(<EOL>service_name=thrift_endpoint.service_name,<EOL>ipv4=ipv4,<EOL>ipv6=ipv6,<EOL>port=port,<EOL>)<EOL>

Accepts a thrift decoded endpoint and converts it to an Endpoint.

        :param thrift_endpoint: thrift encoded endpoint
        :type thrift_endpoint: thrift endpoint
        :returns: decoded endpoint
        :rtype: Encoding


if kind == Kind.CLIENT:<EOL><INDENT>return zipkin_pb2.Span.CLIENT<EOL><DEDENT>elif kind == Kind.SERVER:<EOL><INDENT>return zipkin_pb2.Span.SERVER<EOL><DEDENT>elif kind == Kind.PRODUCER:<EOL><INDENT>return zipkin_pb2.Span.PRODUCER<EOL><DEDENT>elif kind == Kind.CONSUMER:<EOL><INDENT>return zipkin_pb2.Span.CONSUMER<EOL><DEDENT>return None<EOL>

Converts py_zipkin's Kind to Protobuf's Kind.

    :param kind: py_zipkin's Kind.
    :type kind: py_zipkin.Kind
    :return: correcponding protobuf's kind value.
    :rtype: zipkin_pb2.Span.Kind


pb_list = zipkin_pb2.ListOfSpans()<EOL>pb_list.spans.extend(pb_spans)<EOL>return pb_list.SerializeToString()<EOL>

Encode list of protobuf Spans to binary.

    :param pb_spans: list of protobuf Spans.
    :type pb_spans: list of zipkin_pb2.Span
    :return: encoded list.
    :rtype: bytes


pb_annotations = []<EOL>for value, ts in annotations.items():<EOL><INDENT>pb_annotations.append(zipkin_pb2.Annotation(<EOL>timestamp=int(ts * <NUM_LIT:1000> * <NUM_LIT:1000>),<EOL>value=value,<EOL>))<EOL><DEDENT>return pb_annotations<EOL>

Converts py_zipkin's annotations dict to protobuf.

    :param annotations: annotations dict.
    :type annotations: dict
    :return: corresponding protobuf's list of annotations.
    :rtype: list


pb_endpoint = zipkin_pb2.Endpoint()<EOL>if endpoint.service_name:<EOL><INDENT>pb_endpoint.service_name = endpoint.service_name<EOL><DEDENT>if endpoint.port and endpoint.port != <NUM_LIT:0>:<EOL><INDENT>pb_endpoint.port = endpoint.port<EOL><DEDENT>if endpoint.ipv4:<EOL><INDENT>pb_endpoint.ipv4 = socket.inet_pton(socket.AF_INET, endpoint.ipv4)<EOL><DEDENT>if endpoint.ipv6:<EOL><INDENT>pb_endpoint.ipv6 = socket.inet_pton(socket.AF_INET6, endpoint.ipv6)<EOL><DEDENT>return pb_endpoint<EOL>

Converts py_zipkin's Endpoint to Protobuf's Endpoint.

    :param endpoint: py_zipkins' endpoint to convert.
    :type endpoint: py_zipkin.encoding.Endpoint
    :return: corresponding protobuf's endpoint.
    :rtype: zipkin_pb2.Endpoint


raise NotImplementedError('<STR_LIT>')<EOL>

Sends the encoded payload over the transport.

        :argument payload: encoded list of spans.


@nox.session(python=['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>@nox.parametrize('<STR_LIT>',<EOL>['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>def compatibility(session, install):

session.install('<STR_LIT>', '<STR_LIT>')<EOL>session.install(install)<EOL>_run_tests(session)<EOL>

Run the unit test suite with each support library and Python version.


session.install('<STR_LIT>')<EOL>session.run('<STR_LIT>',<EOL>'<STR_LIT>')<EOL>

Run flake8.
    Returns a failure if flake8 finds linting errors or sufficiently
    serious code quality issues.


session.install('<STR_LIT>', '<STR_LIT>')<EOL>session.install('<STR_LIT>')<EOL>session.run(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL>


def text_width(self, text: str) -> float:

width, _ = self._font.getsize(text)<EOL>return width<EOL>

Returns the width, in pixels, of a string in DejaVu Sans 110pt.


@staticmethod<EOL><INDENT>def from_json(f: TextIO) -> '<STR_LIT>':<DEDENT>

o = json.load(f)<EOL>return PrecalculatedTextMeasurer(o['<STR_LIT>'],<EOL>o['<STR_LIT>'],<EOL>o['<STR_LIT>'])<EOL>

Return a PrecalculatedTextMeasurer given a JSON stream.

        See precalculate_text.py for details on the required format.


def write_json(f: TextIO, deja_vu_sans_path: str,<EOL>measurer: text_measurer.TextMeasurer,<EOL>encodings: Iterable[str]) -> None:

supported_characters = list(<EOL>generate_supported_characters(deja_vu_sans_path))<EOL>kerning_characters = '<STR_LIT>'.join(<EOL>generate_encodeable_characters(supported_characters, encodings))<EOL>char_to_length = calculate_character_to_length_mapping(measurer,<EOL>supported_characters)<EOL>pair_to_kerning = calculate_pair_to_kern_mapping(measurer, char_to_length,<EOL>kerning_characters)<EOL>json.dump(<EOL>{'<STR_LIT>': statistics.mean(char_to_length.values()),<EOL>'<STR_LIT>': char_to_length,<EOL>'<STR_LIT>': kerning_characters,<EOL>'<STR_LIT>': pair_to_kerning},<EOL>f, sort_keys=True, indent=<NUM_LIT:1>)<EOL>

Write the data required by PrecalculatedTextMeasurer to a stream.


def badge(left_text: str, right_text: str, left_link: Optional[str] = None,<EOL>right_link: Optional[str] = None,<EOL>whole_link: Optional[str] = None, logo: Optional[str] = None,<EOL>left_color: str = '<STR_LIT>', right_color: str = '<STR_LIT>',<EOL>measurer: Optional[text_measurer.TextMeasurer] = None,<EOL>embed_logo: bool = False) -> str:

if measurer is None:<EOL><INDENT>measurer = (<EOL>precalculated_text_measurer.PrecalculatedTextMeasurer<EOL>.default())<EOL><DEDENT>if (left_link or right_link) and whole_link:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>template = _JINJA2_ENVIRONMENT.get_template('<STR_LIT>')<EOL>if logo and embed_logo:<EOL><INDENT>logo = _embed_image(logo)<EOL><DEDENT>svg = template.render(<EOL>left_text=left_text,<EOL>right_text=right_text,<EOL>left_text_width=measurer.text_width(left_text) / <NUM_LIT>,<EOL>right_text_width=measurer.text_width(right_text) / <NUM_LIT>,<EOL>left_link=left_link,<EOL>right_link=right_link,<EOL>whole_link=whole_link,<EOL>logo=logo,<EOL>left_color=_NAME_TO_COLOR.get(left_color, left_color),<EOL>right_color=_NAME_TO_COLOR.get(right_color, right_color),<EOL>)<EOL>xml = minidom.parseString(svg)<EOL>_remove_blanks(xml)<EOL>xml.normalize()<EOL>return xml.documentElement.toxml()<EOL>

Creates a github-style badge as an SVG image.

    >>> badge(left_text='coverage', right_text='23%', right_color='red')
    '<svg...</svg>'
    >>> badge(left_text='build', right_text='green', right_color='green',
    ...       whole_link="http://www.example.com/")
    '<svg...</svg>'

    Args:
        left_text: The text that should appear on the left-hand-side of the
            badge e.g. "coverage".
        right_text: The text that should appear on the right-hand-side of the
            badge e.g. "23%".
        left_link: The URL that should be redirected to when the left-hand text
            is selected.
        right_link: The URL that should be redirected to when the right-hand
            text is selected.
        whole_link: The link that should be redirected to when the badge is
            selected. If set then left_link and right_right may not be set.
        logo: A url representing a logo that will be displayed inside the
            badge. Can be a data URL e.g. "data:image/svg+xml;utf8,<svg..."
        left_color: The color of the part of the badge containing the left-hand
            text. Can be an valid CSS color
            (see https://developer.mozilla.org/en-US/docs/Web/CSS/color) or a
            color name defined here:
            https://github.com/badges/shields/blob/master/lib/colorscheme.json
        right_color: The color of the part of the badge containing the
            right-hand text. Can be an valid CSS color
            (see https://developer.mozilla.org/en-US/docs/Web/CSS/color) or a
            color name defined here:
            https://github.com/badges/shields/blob/master/lib/colorscheme.json
        measurer: A text_measurer.TextMeasurer that can be used to measure the
            width of left_text and right_text.
        embed_logo: If True then embed the logo image directly in the badge.
            This can prevent an HTTP request and some browsers will not render
            external image referenced. When True, `logo` must be a HTTP/HTTPS
            URI or a filesystem path. Also, the `badge` call may raise an
            exception if the logo cannot be loaded, is not an image, etc.


return clspath.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL>

Split of clspath into module and class name.

    NOTE(willkg): This is really simple. Maybe we should use something more
    sophisticated?


good_backends = []<EOL>for backend in backends:<EOL><INDENT>clspath = backend['<STR_LIT:class>']<EOL>options = backend.get('<STR_LIT>', {})<EOL>if isinstance(clspath, str):<EOL><INDENT>modpath, clsname = split_clspath(clspath)<EOL>try:<EOL><INDENT>__import__(modpath)<EOL>module = sys.modules[modpath]<EOL>cls = getattr(module, clsname)<EOL><DEDENT>except Exception:<EOL><INDENT>logger.exception('<STR_LIT>', clspath)<EOL>if raise_errors:<EOL><INDENT>raise<EOL><DEDENT>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>cls = clspath<EOL><DEDENT>try:<EOL><INDENT>good_backends.append(cls(options))<EOL><DEDENT>except Exception:<EOL><INDENT>logger.exception(<EOL>'<STR_LIT>',<EOL>clspath,<EOL>options<EOL>)<EOL>if raise_errors:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>_change_metrics(good_backends)<EOL>

Instantiate and configures backends.

    :arg list-of-dicts backends: the backend configuration as a list of dicts where
        each dict specifies a separate backend.

        Each backend dict consists of two things:

        1. ``class`` with a value that is either a Python class or a dotted
           Python path to one

        2. ``options`` dict with options for the backend in question to
           configure it

        See the documentation for the backends you're using to know what is
        configurable in the options dict.

    :arg raise_errors bool: whether or not to raise an exception if something
        happens in configuration; if it doesn't raise an exception, it'll log
        the exception

    For example, this sets up a
    :py:class:`markus.backends.logging.LoggingMetrics` backend::

        markus.configure([
            {
                'class': 'markus.backends.logging.LoggingMetrics',
                'options': {
                    'logger_name': 'metrics'
                }
            }
        ])

    You can set up as many backends as you like.

    .. Note::

       During application startup, Markus should get configured before the app
       starts generating metrics. Any metrics generated before Markus is
       configured will get dropped.

       However, anything can call :py:func:`markus.get_metrics` and get a
       :py:class:`markus.main.MetricsInterface` before Markus has been
       configured including at module load time.


def timer_decorator(self, stat, tags=None):

def _inner(fun):<EOL><INDENT>@wraps(fun)<EOL>def _timer_decorator(*args, **kwargs):<EOL><INDENT>with self.timer(stat, tags):<EOL><INDENT>return fun(*args, **kwargs)<EOL><DEDENT><DEDENT>return _timer_decorator<EOL><DEDENT>return _inner<EOL>

Timer decorator for easily computing timings.

        :arg string stat: A period delimited alphanumeric key.

        :arg list-of-strings tags: Each string in the tag consists of a key and
            a value separated by a colon. Tags can make it easier to break down
            metrics for analysis.

            For example ``['env:stage', 'compressed:yes']``.

        For example:

        >>> mymetrics = get_metrics(__name__)

        >>> @mymetrics.timer_decorator('long_function')
        ... def long_function():
        ...     # perform some thing we want to keep metrics on
        ...     pass

        .. Note::

           All timings generated with this are in milliseconds.


def timing(self, stat, value, tags=None):

full_stat = self._full_stat(stat)<EOL>for backend in _get_metrics_backends():<EOL><INDENT>backend.timing(full_stat, value=value, tags=tags)<EOL><DEDENT>

Record a timing value.

        Record the length of time of something to be added to a set of values from
        which a statistical distribution is derived.

        Depending on the backend, you might end up with count, average, median,
        95% and max for a set of timing values.

        This is useful for analyzing how long things take to occur. For
        example, how long it takes for a function to run, to upload files, or
        for a database query to execute.

        :arg string stat: A period delimited alphanumeric key.

        :arg int value: A timing in milliseconds.

        :arg list-of-strings tags: Each string in the tag consists of a key and
            a value separated by a colon. Tags can make it easier to break down
            metrics for analysis.

            For example ``['env:stage', 'compressed:yes']``.

        For example:

        >>> import time
        >>> import markus

        >>> metrics = markus.get_metrics('foo')
        >>> def upload_file(payload):
        ...     start_time = time.perf_counter()  # this is in seconds
        ...     # upload the file
        ...     timing = (time.perf_counter() - start_time) * 1000.0  # convert to ms
        ...     metrics.timing('upload_file_time', value=timing)

        .. Note::

           If you're timing a function or a block of code, it's probably more
           convenient to use :py:meth:`markus.main.MetricsInterface.timer` or
           :py:meth:`markus.main.MetricsInterface.timer_decorator`.


def incr(self, stat, value=<NUM_LIT:1>, tags=None):

full_stat = self._full_stat(stat)<EOL>for backend in _get_metrics_backends():<EOL><INDENT>backend.incr(full_stat, value=value, tags=tags)<EOL><DEDENT>

Incr is used for counting things.

        :arg string stat: A period delimited alphanumeric key.

        :arg int value: A value to increment the count by. Usually this is 1.

        :arg list-of-strings tags: Each string in the tag consists of a key and
            a value separated by a colon. Tags can make it easier to break down
            metrics for analysis.

            For example ``['env:stage', 'compressed:yes']``.

        For example:

        >>> import markus

        >>> metrics = markus.get_metrics('foo')
        >>> def chop_vegetable(kind):
        ...     # chop chop chop
        ...     metrics.incr('vegetable', value=1)

        You can also use incr to decrement by passing a negative value.