def find(self, title):

        if title not in self._titles:
            raise KeyError(title)
        return self._titles[title][0]

Return the first worksheet with the given title.

Args:
        title(str): title/name of the worksheet to return

Returns:
        WorkSheet: contained worksheet object

Raises:
        KeyError: if the spreadsheet has no no worksheet with the given ``title``


def _transform(transformer_chain: Sequence[Tuple[DataTransformer, Type]], data: S, context: PipelineContext = None) -> T:

    for transformer, target_type in transformer_chain:
        # noinspection PyTypeChecker
        data = transformer.transform(target_type, data, context)
    return data

Transform data to a new type.

Args:
        transformer_chain: A sequence of (transformer, type) pairs to convert the data.
        data: The data to be transformed.
        context: The context of the transformations (mutable).

Returns:
        The transformed data.


def hrs_84_and_db12_8_or_20_6(self, value=None):

        if value is not None:
            try:
                value = float(value)
            except ValueError:
                raise ValueError(
                    'value {} need to be of type float '
                    'for field `hrs_84_and_db12_8_or_20_6`'.format(value))

        self._hrs_84_and_db12_8_or_20_6 = value

Corresponds to IDD Field `hrs_84_and_db12_8_or_20_6`
    Number of hours between 8 AM and 4 PM (inclusive) with dry-bulb temperature between 12.8 and 20.6 C

Args:
        value (float): value for IDD Field `hrs_84_and_db12_8_or_20_6`
            if `value` is None it will not be checked against the
            specification and is assumed to be a missing value

Raises:
        ValueError: if `value` is not a valid value


def LateBind(self, target=None):

    if not issubclass(target, RDFProtoStruct):
      raise TypeError("Field %s expects a protobuf, but target is %s" %
                      (self, target))

    self.late_bound = False

    # The target type is now resolved.
    self.type = target

    # Register us in our owner.
    self.owner.AddDescriptor(self)

Late binding callback.

    This method is called on this field descriptor when the target RDFValue
    class is finally defined. It gives the field descriptor an opportunity to
    initialize after the point of definition.

Args:
        target: The target nested class.

Raises:
        TypeError: If the target class is not of the expected type.


def children(self, as_resources=False):

		children = [o for s,p,o in self.rdf.graph.triples((None, self.rdf.prefixes.ldp.contains, None))]

		# if as_resources, issue GET requests for children and return
		if as_resources:
			logger.debug('retrieving children as resources')
			children = [ self.repo.get_resource(child) for child in children ]

		return children

method to return hierarchical  children of this resource

Args:
    as_resources (bool): if True, opens each as appropriate resource type instead of return URI only

Returns:
    (list): list of resources


def collect_hunt_results(self, hunt):

    if not os.path.isdir(self.output_path):
      os.makedirs(self.output_path)

    output_file_path = os.path.join(
        self.output_path, '.'.join((self.hunt_id, 'zip')))

    if os.path.exists(output_file_path):
      print('{0:s} already exists: Skipping'.format(output_file_path))
      return None

    self._check_approval_wrapper(
        hunt, self._get_and_write_archive, hunt, output_file_path)

    results = self._extract_hunt_results(output_file_path)
    print('Wrote results of {0:s} to {1:s}'.format(
        hunt.hunt_id, output_file_path))
    return results

Download current set of files in results.

Args:
        hunt: The GRR hunt object to download files from.

Returns:
        list: tuples containing:
        str: human-readable description of the source of the collection. For
            example, the name of the source host.
        str: path to the collected data.

Raises:
        ValueError: if approval is needed and approvers were not specified.


def complement(self, alphabet):

        states = sorted(self.states, key=attrgetter('initial'), reverse=True)
        for state in states:
            if state.final:
                state.final = False
            else:
                state.final = True

Returns the complement of DFA

Args:
        alphabet (list): The input alphabet

Returns:
        None


def _CreateDictReader(self, line_reader):

    delimiter = self.DELIMITER
    quotechar = self.QUOTE_CHAR
    magic_test_string = self._MAGIC_TEST_STRING
    # Python 3 csv module requires arguments to constructor to be of type str.
    if py2to3.PY_3:
      delimiter = delimiter.decode(self._encoding)
      quotechar = quotechar.decode(self._encoding)
      magic_test_string = magic_test_string.decode(self._encoding)

    return csv.DictReader(
        line_reader, delimiter=delimiter, fieldnames=self.COLUMNS,
        quotechar=quotechar, restkey=magic_test_string,
        restval=magic_test_string)

Returns a reader that processes each row and yields dictionaries.

    csv.DictReader does this job well for single-character delimiters; parsers
    that need multi-character delimiters need to override this method.

Args:
        line_reader (iter): yields lines from a file-like object.

Returns:
        iter: a reader of dictionaries, as returned by csv.DictReader().


Convert the color from YUV coordinates to RGB.

    Parameters:
        :y:
        The Y component value [0...1]
        :u:
        The U component value [-0.436...0.436]
        :v:
        The V component value [-0.615...0.615]

Returns:
        The color as an (r, g, b) tuple in the range:
        r[0...1],
        g[0...1],
        b[0...1]

    >>> '(%g, %g, %g)' % yuv_to_rgb(0.5925, -0.2916, 0.3575)
    '(0.999989, 0.500015, -6.3276e-05)'


def define_grid(self, matrix):

        self.style['grid-template-areas'] = ''.join("'%s'"%(' '.join(x)) for x in matrix)

Populates the Table with a list of tuples of strings.

Args:
        matrix (list): list of iterables of strings (lists or something else).
            Items in the matrix have to correspond to a key for the children.


def capture_widget(widget, path=None):

    if use_qt5:
        pixmap = widget.grab()
    else:
        pixmap = QtGui.QPixmap.grabWidget(widget)

    if path:
        pixmap.save(path)

    else:
        image_buffer = QtCore.QBuffer()
        image_buffer.open(QtCore.QIODevice.ReadWrite)

        pixmap.save(image_buffer, "PNG")

        return image_buffer.data().data()

Grab an image of a Qt widget

Args:
        widget: The Qt Widget to capture
        path (optional): The path to save to. If not provided - will return image data.

Returns:
        If a path is provided, the image will be saved to it.
        If not, the PNG buffer will be returned.


def gcopy(pattern, destination):

    for item in glob.glob(pattern):
        if not copy(item, destination):
            return False
    return True

Copy all file found by glob.glob(pattern) to destination directory.

Args:
        pattern (str): Glob pattern
        destination (str): Path to the destination directory.

Returns:
        bool: True if the operation is successful, False otherwise.


def create_switch(type, settings, pin):

	switch = None
	if type == "A":
		group, device = settings.split(",")
		switch = pi_switch.RCSwitchA(group, device)

	elif type == "B":
		addr, channel = settings.split(",")
		addr = int(addr)
		channel = int(channel)
		switch = pi_switch.RCSwitchB(addr, channel)

	elif type == "C":
		family, group, device = settings.split(",")
		group = int(group)
		device = int(device)
		switch = pi_switch.RCSwitchC(family, group, device)

	elif type == "D":
		group, device = settings.split(",")
		device = int(device)
		switch = pi_switch.RCSwitchD(group, device)

	else:
		print "Type %s is not supported!" % type
		sys.exit()

	switch.enableTransmit(pin)
	return switch

Create a switch.

Args:
        type: (str): type of the switch [A,B,C,D]
        settings (str): a comma separted list
        pin (int): wiringPi pin

Returns:
        switch


def set_charge_and_spin(self, charge, spin_multiplicity=None):

        self._charge = charge
        nelectrons = 0
        for site in self._sites:
            for sp, amt in site.species.items():
                if not isinstance(sp, DummySpecie):
                    nelectrons += sp.Z * amt
        nelectrons -= charge
        self._nelectrons = nelectrons
        if spin_multiplicity:
            if (nelectrons + spin_multiplicity) % 2 != 1:
                raise ValueError(
                    "Charge of {} and spin multiplicity of {} is"
                    " not possible for this molecule".format(
                        self._charge, spin_multiplicity))
            self._spin_multiplicity = spin_multiplicity
        else:
            self._spin_multiplicity = 1 if nelectrons % 2 == 0 else 2

Set the charge and spin multiplicity.

Args:
        charge (int): Charge for the molecule. Defaults to 0.
        spin_multiplicity (int): Spin multiplicity for molecule.
            Defaults to None, which means that the spin multiplicity is
            set to 1 if the molecule has no unpaired electrons and to 2
            if there are unpaired electrons.


def _get_object_from_version(cls, operations, ident):

        version, objname = ident.split(".")

        module_ = operations.get_context().script.get_revision(version).module
        obj = getattr(module_, objname)
        return obj

Returns a Python object from an Alembic migration module (script).

Args:
        operations: instance of ``alembic.operations.base.Operations``
        ident: string of the format ``version.objname``

Returns:
        the object whose name is ``objname`` within the Alembic migration
        script identified by ``version``


def add_info_field(self, field):

        if field in self.info_dict:
            msg = "New info field [{}] already exists.".format(field)
            raise KeyError(msg)

        if "=" in field:
            key, value = field.split("=")
            self.info_dict[key] = value
        else:
            self.info_dict[field] = field

        self._join_info_fields()

Adds new info field (flag or key=value pair).

Args:
        field: String flag (e.g. "SOMATIC") or key-value ("NEW_DP=42")

Raises:
        KeyError: if info field already exists


def _bash_comp_command(self, cmd, add_help=True):

        out = ['-h', '--help'] if add_help else []
        cmd_dict = self._opt_cmds[cmd] if cmd else self._opt_bare
        for opt, sct in cmd_dict:
            out.extend(_names(self._conf[sct], opt))
        return out

Build a list of all options for a given command.

Args:
        cmd (str): command name, set to None or '' for bare command.
        add_help (bool): add an help option.

Returns:
        list of str: list of CLI options strings.


def validate(self, corpus):

        invalid_utterances = {}

        for utterance in corpus.utterances.values():
            if self.label_list_idx in utterance.label_lists.keys():
                ll = utterance.label_lists[self.label_list_idx]

                if len(ll) < self.min_number_of_labels:
                    invalid_utterances[utterance.idx] = 'Only {} labels'.format(len(ll))
            else:
                invalid_utterances[utterance.idx] = 'No label-list {}'.format(self.label_list_idx)

        passed = len(invalid_utterances) <= 0
        info = {
            'Min. number of labels': str(self.min_number_of_labels),
            'Label-List ID': self.label_list_idx
        }

        return base.InvalidUtterancesResult(passed, invalid_utterances, name=self.name(), info=info)

Perform the validation on the given corpus.

Args:
        corpus (Corpus): The corpus to test/validate.

Returns:
        InvalidUtterancesResult: Validation result.


def get_boards(board_name_list, *args, **kwargs):

    if isinstance(board_name_list, basestring):
        board_name_list = board_name_list.split()
    return [Board(name, *args, **kwargs) for name in board_name_list]

Given a list of boards, return :class:`basc_py4chan.Board` objects.

Args:
        board_name_list (list): List of board names to get, eg: ['b', 'tg']

Returns:
        dict of :class:`basc_py4chan.Board`: Requested boards.


def parse_simple_id(chrom, pos, ref, alt):

    return '_'.join([chrom, pos, ref, alt])

Parse the simple id for a variant

    Simple id is used as a human readable reference for a position, it is
    in no way unique.

Args:
        chrom(str)
        pos(str)
        ref(str)
        alt(str)

Returns:
        simple_id(str): The simple human readable variant id


def __squid_to_guid(self, squid):

        if not squid:
            return ''
        squid_match = self.__squid_pattern.match(squid)
        guid = ''
        if squid_match is not None:
            guid = '{' +\
                squid_match.group(1)[::-1]+'-' +\
                squid_match.group(2)[::-1]+'-' +\
                squid_match.group(3)[::-1]+'-' +\
                squid_match.group(4)[::-1]+squid_match.group(5)[::-1] + '-'
            for index in range(6, 12):
                guid += squid_match.group(index)[::-1]
            guid += '}'
        return guid

Squished GUID (SQUID) to GUID.

    A SQUID is a Squished/Compressed version of a GUID to use up less space
    in the registry.

Args:
        squid (str): Squished GUID.

Returns:
        str: the GUID if a valid SQUID provided.


def Overlay_setShowFPSCounter(self, show):

		assert isinstance(show, (bool,)
		    ), "Argument 'show' must be of type '['bool']'. Received type: '%s'" % type(
		    show)
		subdom_funcs = self.synchronous_command('Overlay.setShowFPSCounter', show
		    =show)
		return subdom_funcs

Function path: Overlay.setShowFPSCounter
    Domain: Overlay
    Method name: setShowFPSCounter

    Parameters:
    Required arguments:
        'show' (type: boolean) -> True for showing the FPS counter
    No return value.

    Description: Requests that backend shows the FPS counter


def __init__(self, length=None, experimenter=None):

        super().__init__(action_type=ActionType.OFPAT_EXPERIMENTER)
        self.length = length
        self.experimenter = experimenter

Create ActionExperimenterHeader with the optional parameters below.

Args:
        experimenter (int): The experimenter field is the Experimenter ID,
            which takes the same form as in struct ofp_experimenter.


def __strip_tags(self, node: yaml.Node) -> None:

        if isinstance(node, yaml.SequenceNode):
            for subnode in node.value:
                self.__strip_tags(subnode)
        elif isinstance(node, yaml.MappingNode):
            node.tag = 'tag:yaml.org,2002:map'
            for key_node, value_node in node.value:
                self.__strip_tags(key_node)
                self.__strip_tags(value_node)

Strips tags from mappings in the tree headed by node.

    This keeps yaml from constructing any objects in this tree.

Args:
        node: Head of the tree to strip


def parseEquation(self, inp):

        inp = MathService._preprocess(inp)
        split = inp.split(' ')

        # Recursive call on unary operators
        for i, w in enumerate(split):
            if w in self.__unaryOperators__:
                op = self.__unaryOperators__[w]

                # Split equation into halves
                eq1 = ' '.join(split[:i])
                eq2 = ' '.join(split[i + 1:])

                # Calculate second half
                result = MathService._applyUnary(self.parseEquation(eq2), op)

                return self.parseEquation(eq1 + " " + str(result))

        def extractNumbersAndSymbols(inp):
            numbers = []
            symbols = []

            # Divide into values (numbers), operators (symbols)
            next_number = ""
            for w in inp.split(' '):
                if w in self.__binaryOperators__:
                    symbols.append(self.__binaryOperators__[w])

                    if next_number:
                        numbers.append(next_number)
                        next_number = ""

                else:
                    if next_number:
                        next_number += " "
                    next_number += w

            if next_number:
                numbers.append(next_number)

            # Cast numbers from words to integers
            def convert(n):
                if n in self.__constants__:
                    return self.__constants__[n]

                converter = NumberService()
                return converter.parse(n)

            numbers = [convert(n) for n in numbers]

            return numbers, symbols

        numbers, symbols = extractNumbersAndSymbols(inp)

        return MathService._calculate(numbers, symbols)

Solves the equation specified by the input string.

Args:
        inp (str): An equation, specified in words, containing some
            combination of numbers, binary, and unary operations.

Returns:
        The floating-point result of carrying out the computation.


def hint_for_accuracy(self, accuracy="normal"):

        if not self.has_dojo_report:
            return Hint(ecut=0., pawecutdg=0.)

        # Get hints from dojoreport. Try first in hints then in ppgen_hints.
        if "hints" in self.dojo_report:
            return Hint.from_dict(self.dojo_report["hints"][accuracy])
        elif "ppgen_hints" in self.dojo_report:
            return Hint.from_dict(self.dojo_report["ppgen_hints"][accuracy])
        return Hint(ecut=0., pawecutdg=0.)

Returns a :class:`Hint` object with the suggested value of ecut [Ha] and
    pawecutdg [Ha] for the given accuracy.
    ecut and pawecutdg are set to zero if no hint is available.

Args:
        accuracy: ["low", "normal", "high"]


def from_dict(cls, content):

        # Do we really need this constructor? Could use DidlObject(**content)
        # instead.  -- We do now
        if 'resources' in content:
            content['resources'] = [DidlResource.from_dict(x)
                                    for x in content['resources']]
        return cls(**content)

Create an instance from a dict.

    An alternative constructor. Equivalent to ``DidlObject(**content)``.

Args:
        content (dict): a dict containing metadata information. Required.
            Valid keys are the same as the parameters for `DidlObject`.


def ReadFrom(self, byte_stream):

    try:
      return self._struct.unpack_from(byte_stream)
    except (TypeError, struct.error) as exception:
      raise IOError('Unable to read byte stream with error: {0!s}'.format(
          exception))

Read values from a byte stream.

Args:
        byte_stream (bytes): byte stream.

Returns:
        tuple[object, ...]: values copies from the byte stream.

Raises:
        IOError: if byte stream cannot be read.
        OSError: if byte stream cannot be read.


def verify_oauth2_token(id_token, request, audience=None):

    return verify_token(
        id_token, request, audience=audience,
        certs_url=_GOOGLE_OAUTH2_CERTS_URL)

Verifies an ID Token issued by Google's OAuth 2.0 authorization server.

Args:
        id_token (Union[str, bytes]): The encoded token.
        request (google.auth.transport.Request): The object used to make
            HTTP requests.
        audience (str): The audience that this token is intended for. This is
            typically your application's OAuth 2.0 client ID. If None then the
            audience is not verified.

Returns:
        Mapping[str, Any]: The decoded token.


def __init__(self,
                 unique_identifier=None):

        super(RevokeResponsePayload, self).__init__(
            tag=enums.Tags.RESPONSE_PAYLOAD)
        if unique_identifier is None:
            self.unique_identifier = attributes.UniqueIdentifier()
        else:
            self.unique_identifier = unique_identifier
        self.validate()

Construct a RevokeResponsePayload object.

Args:
        unique_identifier (UniqueIdentifier): The UUID of a managed
            cryptographic object.


def show_bokehjs(bokehjs_action, develop=False):

    print()
    if develop:
        print("Installed Bokeh for DEVELOPMENT:")
    else:
        print("Installed Bokeh:")
    if bokehjs_action in ['built', 'installed']:
        print("  - using %s built BokehJS from bokehjs/build\n" % (bright(yellow("NEWLY")) if bokehjs_action=='built' else bright(yellow("PREVIOUSLY"))))
    else:
        print("  - using %s BokehJS, located in 'bokeh.server.static'\n" % bright(yellow("PACKAGED")))
    print()

Print a useful report after setuptools output describing where and how
    BokehJS is installed.

Args:
        bokehjs_action (str) : one of 'built', 'installed', or 'packaged'
            how (or if) BokehJS was installed into the python source tree

        develop (bool, optional) :
            whether the command was for "develop" mode (default: False)

Returns:
        None


def field_to_markdown(field):

    if "title" in field:
        field_title = "**{}**".format(field["title"])
    else:
        raise Exception("Es necesario un `title` para describir un campo.")

    field_type = " ({})".format(field["type"]) if "type" in field else ""
    field_desc = ": {}".format(
        field["description"]) if "description" in field else ""

    text_template = "{title}{type}{description}"
    text = text_template.format(title=field_title, type=field_type,
                                description=field_desc)

    return text

Genera texto en markdown a partir de los metadatos de un `field`.

Args:
        field (dict): Diccionario con metadatos de un `field`.

Returns:
        str: Texto que describe un `field`.


def _CopyFromDateTimeValues(self, date_time_values):

    year = date_time_values.get('year', 0)
    month = date_time_values.get('month', 0)
    day_of_month = date_time_values.get('day_of_month', 0)
    hours = date_time_values.get('hours', 0)
    minutes = date_time_values.get('minutes', 0)
    seconds = date_time_values.get('seconds', 0)

    self._normalized_timestamp = None
    self._number_of_seconds = self._GetNumberOfSecondsFromElements(
        year, month, day_of_month, hours, minutes, seconds)
    self._time_elements_tuple = (
        year, month, day_of_month, hours, minutes, seconds)

    self.is_local_time = False

Copies time elements from date and time values.

Args:
        date_time_values  (dict[str, int]): date and time values, such as year,
        month, day of month, hours, minutes, seconds, microseconds.


def GetSubkeyByName(self, name):

    pyregf_key = self._pyregf_key.get_sub_key_by_name(name)
    if not pyregf_key:
      return None

    key_path = key_paths.JoinKeyPath([self._key_path, pyregf_key.name])
    return REGFWinRegistryKey(pyregf_key, key_path=key_path)

Retrieves a subkey by name.

Args:
        name (str): name of the subkey.

Returns:
        WinRegistryKey: Windows Registry subkey or None if not found.


def tracer_diffusion_coefficient( self ):

        if self.has_run:
            return self.atoms.sum_dr_squared() / ( 6.0 * float( self.number_of_atoms ) * self.lattice.time )
        else:
            return None

Tracer diffusion coefficient, D*.

Args:
        None

Returns:
        (Float): The tracer diffusion coefficient, D*.


def time_stats(self, **kwargs):

        # Use the existing time_stats attribute if it exist, otherwise make an
        # API call
        if 'time_stats' in self.attributes:
            return self.attributes['time_stats']

        path = '%s/%s/time_stats' % (self.manager.path, self.get_id())
        return self.manager.gitlab.http_get(path, **kwargs)

Get time stats for the object.

Args:
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabTimeTrackingError: If the time tracking update cannot be done


def match_tracks(self, model_tracks, obs_tracks, unique_matches=True, closest_matches=False):

        if unique_matches:
            pairings = self.track_matcher.match_tracks(model_tracks, obs_tracks, closest_matches=closest_matches)
        else:
            pairings = self.track_matcher.neighbor_matches(model_tracks, obs_tracks)
        return pairings

Match forecast and observed tracks.

Args:
        model_tracks:
        obs_tracks:
        unique_matches:
        closest_matches:

    Returns:


def potential_purviews(self, direction, mechanism):

        all_purviews = utils.powerset(self._node_indices)
        return irreducible_purviews(self.cm, direction, mechanism,
                                    all_purviews)

All purviews which are not clearly reducible for mechanism.

Args:
        direction (Direction): |CAUSE| or |EFFECT|.
        mechanism (tuple[int]): The mechanism which all purviews are
            checked for reducibility over.

Returns:
        list[tuple[int]]: All purviews which are irreducible over
        ``mechanism``.


def fetch_or_load(spec_path):

    headers = {}

    try:
        modified = datetime.utcfromtimestamp(os.path.getmtime(spec_path))
        date = modified.strftime("%a, %d %b %Y %I:%M:%S UTC")
        headers["If-Modified-Since"] = date
    except OSError as error:
        if error.errno != errno.ENOENT:
            raise

    request = urllib.Request(VALIDATION_SPEC, headers=headers)
    response = urllib.urlopen(request, cafile=certifi.where())

    if response.code == 200:
        with open(spec_path, "w+b") as spec:
            spec.writelines(response)
            spec.seek(0)
            return html.parse(spec)

    with open(spec_path) as spec:
        return html.parse(spec)

Fetch a new specification or use the cache if it's current.

Args:
        cache_path:

            the path to a cached specification


def convert_elementwise_sub(
    params, w_name, scope_name, inputs, layers, weights, names
):

    print('Converting elementwise_sub ...')
    model0 = layers[inputs[0]]
    model1 = layers[inputs[1]]

    if names == 'short':
        tf_name = 'S' + random_string(7)
    elif names == 'keep':
        tf_name = w_name
    else:
        tf_name = w_name + str(random.random())

    sub = keras.layers.Subtract(name=tf_name)
    layers[scope_name] = sub([model0, model1])

Convert elementwise subtraction.

Args:
        params: dictionary with layer parameters
        w_name: name prefix in state_dict
        scope_name: pytorch scope name
        inputs: pytorch node inputs
        layers: dictionary with keras tensors
        weights: pytorch state_dict
        names: use short names for keras layers


def make_qs(n, m=None):

    try:
        import sympy
    except ImportError:
        raise ImportError("This function requires sympy. Please install it.")
    if m is None:
        syms = sympy.symbols(" ".join(f"q{i}" for i in range(n)))
        if isinstance(syms, tuple):
            return syms
        else:
            return (syms,)
    syms = sympy.symbols(" ".join(f"q{i}" for i in range(n, m)))
    if isinstance(syms, tuple):
        return syms
    else:
        return (syms,)

Make sympy symbols q0, q1, ...

Args:
        n(int), m(int, optional):
            If specified both n and m, returns [qn, q(n+1), ..., qm],
            Only n is specified, returns[q0, q1, ..., qn].

Returns:
        tuple(Symbol): Tuple of sympy symbols.


def to_representation(self, instance):

        if self.id_only():
            return instance.pk

        pk = getattr(instance, 'pk', None)
        if not settings.ENABLE_SERIALIZER_OBJECT_CACHE or pk is None:
            return self._to_representation(instance)
        else:
            if pk not in self.obj_cache:
                self.obj_cache[pk] = self._to_representation(instance)
            return self.obj_cache[pk]

Modified to_representation method. Optionally may cache objects.

Args:
        instance: A model instance or data object.

Returns:
        Instance ID if the serializer is meant to represent its ID.
        Otherwise, a tagged data dict representation.


def _MakeCacheInvariant(self, urn, age):

    precondition.AssertType(urn, Text)
    return "%s:%s" % (urn, self.ParseAgeSpecification(age))

Returns an invariant key for an AFF4 object.

    The object will be cached based on this key. This function is specifically
    extracted to ensure that we encapsulate all security critical aspects of the
    AFF4 object so that objects do not leak across security boundaries.

Args:
        urn: The urn of the object.
        age: The age policy used to build this object. Should be one of
        ALL_TIMES, NEWEST_TIME or a range.

Returns:
        A key into the cache.


def chat_meMessage(self, *, channel: str, text: str, **kwargs) -> SlackResponse:

        kwargs.update({"channel": channel, "text": text})
        return self.api_call("chat.meMessage", json=kwargs)

Share a me message into a channel.

Args:
        channel (str): The channel id. e.g. 'C1234567890'
        text (str): The message you'd like to share. e.g. 'Hello world'


def new(self, file_type):
        # type: (str) -> None

        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('UDF ICB Tag already initialized')

        self.prior_num_direct_entries = 0  # FIXME: let the user set this
        self.strategy_type = 4
        self.strategy_param = 0  # FIXME: let the user set this
        self.max_num_entries = 1
        if file_type == 'dir':
            self.file_type = 4
        elif file_type == 'file':
            self.file_type = 5
        elif file_type == 'symlink':
            self.file_type = 12
        else:
            raise pycdlibexception.PyCdlibInternalError("Invalid file type for ICB; must be one of 'dir', 'file', or 'symlink'")

        self.parent_icb_log_block_num = 0  # FIXME: let the user set this
        self.parent_icb_part_ref_num = 0  # FIXME: let the user set this
        self.flags = 560  # hex 0x230 == binary 0010 0011 0000

        self._initialized = True

A method to create a new UDF ICB Tag.

    Parameters:
    file_type - What file type this represents, one of 'dir', 'file', or 'symlink'.

Returns:
    Nothing.


def run(self, dag):

        if self.layout is None:
            if self.property_set["layout"]:
                self.layout = self.property_set["layout"]
            else:
                self.layout = Layout.generate_trivial_layout(*dag.qregs.values())

        self.property_set['is_swap_mapped'] = True

        for gate in dag.twoQ_gates():
            physical_q0 = self.layout[gate.qargs[0]]
            physical_q1 = self.layout[gate.qargs[1]]

            if self.coupling_map.distance(physical_q0, physical_q1) != 1:
                self.property_set['is_swap_mapped'] = False
                return

If `dag` is mapped to `coupling_map`, the property
    `is_swap_mapped` is set to True (or to False otherwise).

Args:
        dag (DAGCircuit): DAG to map.


def create_function(self, vpc_config):

        zip_file = 'lambda-holder.zip'
        with zipfile.ZipFile(zip_file, mode='w') as zipped:
            zipped.writestr('index.py', 'print "Hello world"')

        contents = ''
        with open('lambda-holder.zip', 'rb') as openfile:
            contents = openfile.read()

        LOG.info('Creating lambda function: %s', self.app_name)

        try:
            self.lambda_client.create_function(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Code={'ZipFile': contents},
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                Publish=False,
                VpcConfig=vpc_config,
                Tags={'app_group': self.group,
                      'app_name': self.app_name})
        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.critical(message)
                raise SystemExit(message)

            raise

        LOG.info("Successfully created Lambda function and alias")

Create lambda function, configures lambda parameters.

    We need to upload non-zero zip when creating function. Uploading
    hello_world python lambda function since AWS doesn't care which
    executable is in ZIP.

Args:
        vpc_config (dict): Dictionary of SubnetIds and SecurityGroupsIds for using
                        a VPC in lambda


def _take_screenshot(self, screenshot=False, name_prefix='unknown'):

        if isinstance(screenshot, bool):
            if not screenshot:
                return
            return self._save_screenshot(name_prefix=name_prefix)
        if isinstance(screenshot, Image.Image):
            return self._save_screenshot(screen=screenshot, name_prefix=name_prefix)

        raise TypeError("invalid type for func _take_screenshot: "+ type(screenshot))

This is different from _save_screenshot.
    The return value maybe None or the screenshot path

Args:
        screenshot: bool or PIL image


def _tensor_product(self, other, reverse=False):

        # Convert other to Stinespring
        if not isinstance(other, Stinespring):
            other = Stinespring(other)

        # Tensor stinespring ops
        sa_l, sa_r = self._data
        sb_l, sb_r = other._data

        # Reshuffle tensor dimensions
        din_a, dout_a = self.dim
        din_b, dout_b = other.dim
        dtr_a = sa_l.shape[0] // dout_a
        dtr_b = sb_l.shape[0] // dout_b
        if reverse:
            shape_in = (dout_b, dtr_b, dout_a, dtr_a, din_b * din_a)
            shape_out = (dout_b * dtr_b * dout_a * dtr_a, din_b * din_a)
        else:
            shape_in = (dout_a, dtr_a, dout_b, dtr_b, din_a * din_b)
            shape_out = (dout_a * dtr_a * dout_b * dtr_b, din_a * din_b)

        # Compute left stinepsring op
        if reverse:
            input_dims = self.input_dims() + other.input_dims()
            output_dims = self.output_dims() + other.output_dims()
            sab_l = np.kron(sb_l, sa_l)
        else:
            input_dims = other.input_dims() + self.input_dims()
            output_dims = other.output_dims() + self.output_dims()
            sab_l = np.kron(sa_l, sb_l)
        # Reravel indicies
        sab_l = np.reshape(
            np.transpose(np.reshape(sab_l, shape_in), (0, 2, 1, 3, 4)),
            shape_out)

        # Compute right stinespring op
        if sa_r is None and sb_r is None:
            sab_r = None
        else:
            if sa_r is None:
                sa_r = sa_l
            elif sb_r is None:
                sb_r = sb_l
            if reverse:
                sab_r = np.kron(sb_r, sa_r)
            else:
                sab_r = np.kron(sa_r, sb_r)
            # Reravel indicies
            sab_r = np.reshape(
                np.transpose(np.reshape(sab_r, shape_in), (0, 2, 1, 3, 4)),
                shape_out)
        return Stinespring((sab_l, sab_r), input_dims, output_dims)

Return the tensor product channel.

Args:
        other (QuantumChannel): a quantum channel subclass.
        reverse (bool): If False return self ⊗ other, if True return
                        if True return (other ⊗ self) [Default: False]

Returns:
        Stinespring: the tensor product channel as a Stinespring object.

Raises:
        QiskitError: if other cannot be converted to a channel.


def expand_benchmark_name(bm_name, bench_groups):

    expansion = bench_groups.get(bm_name)
    if expansion:
        for name in expansion:
            for name in expand_benchmark_name(name, bench_groups):
                yield name
    else:
        yield bm_name

Recursively expand name benchmark names.

Args:
        bm_name: string naming a benchmark or benchmark group.

Yields:
        Names of actual benchmarks, with all group names fully expanded.


def run(self, sensor_graph, model):

        # This check can be done if there is 1 input and it is count == 1
        # and the stream type is input or unbuffered

        did_downgrade = False

        for node, inputs, _outputs in sensor_graph.iterate_bfs():
            can_downgrade = False

            if node.func_name != u'copy_all_a':
                continue

            input_a, trigger_a = node.inputs[0]

            # We can always downgrade unbuffered non-counter
            if input_a.selector.match_type in (DataStream.InputType, DataStream.UnbufferedType):
                can_downgrade = True
            elif isinstance(trigger_a, InputTrigger) and trigger_a.comp_string == u'==' and trigger_a.use_count and trigger_a.reference == 1:
                can_downgrade = True
            elif isinstance(trigger_a, TrueTrigger) and not input_a.selector.buffered:
                # We can only downgrade an always trigger if we know the node before this will not
                # generate more than one reading at a time.  Since in that case, we get readings one at a
                # time and we don't accumulate them so there will be at most one reading to copy.
                # So, we need to check the node that produces input A to this node and see if we can
                # prove that it will produce at most one reading at a time.
                can_downgrade = True
                for in_node in inputs:
                    if input_a.matches(in_node.stream) and in_node.func_name == u'copy_all_a' and in_node.input_a.match_type not in (DataStream.InputType, DataStream.UnbufferedType):
                        can_downgrade = False
                        break

            if can_downgrade:
                did_downgrade = True
                node.set_func(u'copy_latest_a', sensor_graph.find_processing_function(u'copy_latest_a'))

        return did_downgrade

Run this optimization pass on the sensor graph

    If necessary, information on the device model being targeted
    can be found in the associated model argument.

Args:
        sensor_graph (SensorGraph): The sensor graph to optimize
        model (DeviceModel): The device model we're using


def autocorr(x):

    y = x - x.mean()
    n = len(y)
    result = fftconvolve(y, y[::-1])
    acorr = result[len(result) // 2:]
    acorr /= np.arange(n, 0, -1)
    acorr /= acorr[0]
    return acorr

Compute autocorrelation using FFT for every lag for the input array
    https://en.wikipedia.org/wiki/Autocorrelation#Efficient_computation.

Args:
        x (array-like): An array containing MCMC samples.

Returns:
        np.ndarray: An array of the same size as the input array.


def to_query(self, fields=None):

    # Do import here to avoid top-level circular dependencies.
    from . import _query
    if fields is None:
      fields = '*'
    elif isinstance(fields, list):
      fields = ','.join(fields)
    return _query.Query('SELECT %s FROM %s' % (fields, self._repr_sql_()), context=self._context)

Return a Query for this Table.

Args:
        fields: the fields to return. If None, all fields will be returned. This can be a string
        which will be injected into the Query after SELECT, or a list of field names.

Returns:
        A Query object that will return the specified fields from the records in the Table.


def parse_relations(
    belstr: str, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:

    quotes = char_locs["quotes"]
    quoted_range = set([i for start, end in quotes.items() for i in range(start, end)])

    for match in relations_pattern_middle.finditer(belstr):
        (start, end) = match.span(1)
        # log.debug(f'Relation-middle {match}')
        end = end - 1  # adjust end to match actual end character index
        if start != end:
            test_range = set(range(start, end))
        else:
            test_range = set(start)

        # Skip if relation overlaps with quoted string
        if test_range.intersection(quoted_range):
            continue

        span_key = (start, end)
        parsed[span_key] = {
            "type": "Relation",
            "name": match.group(1),
            "span": (start, end),
        }

    for match in relations_pattern_end.finditer(belstr):
        (start, end) = match.span(1)
        log.debug(f"Relation-end {match}")
        end = end - 1  # adjust end to match actual end character index
        if start != end:
            test_range = set(range(start, end))
        else:
            test_range = set(start)

        # Skip if relation overlaps with quoted string
        if test_range.intersection(quoted_range):
            continue

        span_key = (start, end)
        parsed[span_key] = {
            "type": "Relation",
            "name": match.group(1),
            "span": (start, end),
        }

    return parsed, errors

Parse relations from BEL string

Args:
        belstr: BEL string as one single string (not list of chars)
        char_locs: paren, comma and quote char locations
        parsed: data structure for parsed functions, relations, nested
        errors: error messages

Returns:
        (parsed, errors):


def fast_roc(actuals, controls):

    assert(type(actuals) is np.ndarray)
    assert(type(controls) is np.ndarray)

    actuals = np.ravel(actuals)
    controls = np.ravel(controls)
    if np.isnan(actuals).any():
        raise RuntimeError('NaN found in actuals')
    if np.isnan(controls).any():
        raise RuntimeError('NaN found in controls')

    thresholds = np.hstack([-np.inf, np.unique(actuals), np.inf])[::-1]
    true_pos_rate = np.empty(thresholds.size)
    false_pos_rate = np.empty(thresholds.size)
    num_act = float(len(actuals))
    num_ctr = float(len(controls))

    for i, value in enumerate(thresholds):
        true_pos_rate[i] = (actuals >= value).sum() / num_act
        false_pos_rate[i] = (controls >= value).sum() / num_ctr
    auc = np.dot(np.diff(false_pos_rate), true_pos_rate[0:-1])
    # treat cases where TPR of one is not reached before FPR of one
    # by using trapezoidal integration for the last segment
    # (add the missing triangle)
    if false_pos_rate[-2] == 1:
        auc += ((1-true_pos_rate[-3])*.5*(1-false_pos_rate[-3]))
    return (auc, true_pos_rate, false_pos_rate)

approximates the area under the roc curve for sets of actuals and controls.
    Uses all values appearing in actuals as thresholds and lower sum
    interpolation. Also returns arrays of the true positive rate and the false
    positive rate that can be used for plotting the roc curve.

    Parameters:
        actuals : list
            A list of numeric values for positive observations.
        controls : list
            A list of numeric values for negative observations.


def update_factor_providers(self, factor_name, name, body):

        url = self._url('factors/{}/providers/{}'.format(factor_name, name))
        return self.client.put(url, data=body)

Get Guardian factor providers.

    Returns provider configuration

Args:
        factor_name (str): Either push-notification or sms
        name (str): Name of the provider

        body (dict):
        See: https://auth0.com/docs/api/management/v2#!/Guardian/put_twilio


def sample(self, features):

    logits, losses = self(features)  # pylint: disable=not-callable
    if self._target_modality_is_real:
      return logits, logits, losses  # Raw numbers returned from real modality.
    if self.hparams.sampling_method == "argmax":
      samples = tf.argmax(logits, axis=-1)
    else:
      assert self.hparams.sampling_method == "random"

      def multinomial_squeeze(logits, temperature=1.0):
        logits_shape = common_layers.shape_list(logits)
        reshaped_logits = (
            tf.reshape(logits, [-1, logits_shape[-1]]) / temperature)
        choices = tf.multinomial(reshaped_logits, 1)
        choices = tf.reshape(choices, logits_shape[:-1])
        return choices

      samples = multinomial_squeeze(logits, self.hparams.sampling_temp)

    return samples, logits, losses

Run the model and extract samples.

Args:
        features: an map of string to `Tensor`.

Returns:
        samples: an integer `Tensor`.
        logits: a list of `Tensor`s, one per datashard.
        losses: a dictionary: {loss-name (string): floating point `Scalar`}.


def GetSubkeyByIndex(self, index):

    if not self._registry_key and self._registry:
      self._GetKeyFromRegistry()

    subkeys = list(self._subkeys.values())

    if index < 0 or index >= len(subkeys):
      raise IndexError('Index out of bounds.')

    return subkeys[index]

Retrieves a subkey by index.

Args:
        index (int): index of the subkey.

Returns:
        WinRegistryKey: Windows Registry subkey or None if not found.

Raises:
        IndexError: if the index is out of bounds.


def cancel_id(cls, id):

        conn = Qubole.agent()
        data = {"status": "kill"}
        return conn.put(cls.element_path(id), data)

Cancels command denoted by this id

Args:
        `id`: command id


def delete_user(self, user):

        self.project_service.set_auth(self._token_project)
        self.project_service.delete_user(user)

Delete the given user.

Args:
        user (string): User name.

Raises:
        requests.HTTPError on failure.


def BuildArtifactsRegistry(
      cls, artifact_definitions_path, custom_artifacts_path):

    if artifact_definitions_path and not os.path.isdir(
        artifact_definitions_path):
      raise errors.BadConfigOption(
          'No such artifacts filter file: {0:s}.'.format(
              artifact_definitions_path))

    if custom_artifacts_path and not os.path.isfile(custom_artifacts_path):
      raise errors.BadConfigOption(
          'No such artifacts filter file: {0:s}.'.format(custom_artifacts_path))

    registry = artifacts_registry.ArtifactDefinitionsRegistry()
    reader = artifacts_reader.YamlArtifactsReader()

    try:
      registry.ReadFromDirectory(reader, artifact_definitions_path)

    except (KeyError, artifacts_errors.FormatError) as exception:
      raise errors.BadConfigOption((
          'Unable to read artifact definitions from: {0:s} with error: '
          '{1!s}').format(artifact_definitions_path, exception))

    if custom_artifacts_path:
      try:
        registry.ReadFromFile(reader, custom_artifacts_path)

      except (KeyError, artifacts_errors.FormatError) as exception:
        raise errors.BadConfigOption((
            'Unable to read artifact definitions from: {0:s} with error: '
            '{1!s}').format(custom_artifacts_path, exception))

    return registry

Build Find Specs from artifacts or filter file if available.

Args:
        artifact_definitions_path (str): path to artifact definitions file.
        custom_artifacts_path (str): path to custom artifact definitions file.

Returns:
        artifacts.ArtifactDefinitionsRegistry: artifact definitions registry.

Raises:
        RuntimeError: if no valid FindSpecs are built.


def _ProduceSingleContent(self, mod, showprivate=False, showinh=False):

        try:
            all = mod[1].__all__
        except AttributeError:
            raise RuntimeError('Module (%s) MUST have `__all__` defined.' % mod[1].__name__)
        try:
            name = mod[1].__displayname__
        except AttributeError:
            name = mod[0]
        try:
            category = mod[1].__category__
            self.__categories.setdefault(category, 0)
            self.__categories[category] += 1
        except AttributeError:
            pass
        feats = inspect.getmembers(mod[1])
        fname = 'content/' + mod[1].__name__.replace('.', '/').replace(' ', '-')+'.rst'
        feats = [f for f in feats if f[0] in all and (showprivate or not f[0][0:1] == '_')]
        with open(fname, 'w') as fid:
            fid.write(Classifier.GetModuleText(name, mod[1].__name__, showprivate=showprivate))

            for f in feats:
                # Check for a __displayname__
                if inspect.isclass(f[1]) or inspect.isfunction(f[1]):
                    try:
                        featname = f[1].__displayname__
                    except AttributeError:
                        featname = f[1].__name__
                    try:
                        category = f[1].__category__
                        self.__categories.setdefault(category, 0)
                        self.__categories[category] += 1
                    except AttributeError:
                        pass
                    # Make the auto doc rst
                    if inspect.isclass(f[1]):
                        fid.write(Classifier.GetClassText(featname, '%s.%s' % (mod[1].__name__, f[1].__name__), showprivate=showprivate, showinh=showinh))
                    elif inspect.isfunction(f[1]):
                         fid.write(Classifier.GetFunctionText(featname, '%s.%s' %  (mod[1].__name__, f[1].__name__)))

            fid.close()
        return '\n   %s' % (fname.split('/')[-1])

An internal helper to create a page for a single module. This will
    automatically generate the needed RSF to document the module
    and save the module to its own page in its appropriate location.

Args:
        mod (module): The single module to document as its own page
        showprivate (bool): A flag for whether or not to display private members

Returns:
        str: The file name ready to be appended to a toctree


def __init__(self, predicate, if_true, if_false):

        super(TernaryConditional, self).__init__(predicate, if_true, if_false)
        self.predicate = predicate
        self.if_true = if_true
        self.if_false = if_false
        self.validate()

Construct an expression that evaluates a predicate and returns one of two results.

Args:
        predicate: Expression to evaluate, and based on which to choose the returned value
        if_true: Expression to return if the predicate was true
        if_false: Expression to return if the predicate was false

Returns:
        new TernaryConditional object


def labels2onehot(labels: [List[str], List[List[str]], np.ndarray], classes:  [list, np.ndarray]) -> np.ndarray:

    n_classes = len(classes)
    y = []
    for sample in labels:
        curr = np.zeros(n_classes)
        if isinstance(sample, list):
            for intent in sample:
                if intent not in classes:
                    log.warning('Unknown intent {} detected. Assigning no class'.format(intent))
                else:
                    curr[np.where(np.array(classes) == intent)[0]] = 1
        else:
            curr[np.where(np.array(classes) == sample)[0]] = 1
        y.append(curr)
    y = np.asarray(y)
    return y

Convert labels to one-hot vectors for multi-class multi-label classification

Args:
        labels: list of samples where each sample is a class or a list of classes which sample belongs with
        classes: array of classes' names

Returns:
        2d array with one-hot representation of given samples


def calculate(self, token_list_x, token_list_y):

        match_list = [tanimoto_value for tanimoto_value in token_list_x if tanimoto_value in token_list_y]
        return float(len(match_list) / (len(token_list_x) + len(token_list_y) - len(match_list)))

Calculate similarity with the Tanimoto coefficient.

    Concrete method.

Args:
        token_list_x:    [token, token, token, ...]
        token_list_y:    [token, token, token, ...]

Returns:
        Similarity.


def test(verbosity=1):  # pragma: no cover

    import unittest
    from .tests import test_suite

    # Testing
    unittest.TextTestRunner(verbosity=verbosity).run(test_suite)

Executes all the tests for pyplink.

Args:
        verbosity (int): The verbosity level for :py:mod:`unittest`.

    Just set ``verbosity`` to an integer higher than ``1`` to have more
    information about the tests.


def signature_cert_chain_url(url):

    r = urlparse(url)
    if not r.scheme.lower() == 'https':
        warnings.warn('Certificate URL scheme is invalid.')
        return False
    if not r.hostname.lower() == 's3.amazonaws.com':
        warnings.warn('Certificate URL hostname is invalid.')
        return False
    if not os.path.normpath(r.path).startswith('/echo.api/'):
        warnings.warn('Certificate URL path is invalid.')
        return False
    if r.port and not r.port == 443:
        warnings.warn('Certificate URL port is invalid.')
        return False
    return True

Validate URL specified by SignatureCertChainUrl.

    See `validate.request` for additional info.

Args:
        url: str. SignatureCertChainUrl header value sent by request.

Returns:
        bool: True if valid, False otherwise.


def validateLogicalInterfaceConfiguration(self, logicalInterfaceId):

        req = ApiClient.oneLogicalInterfaceUrl % (self.host, "/draft", logicalInterfaceId)
        body = {"operation" : "validate-configuration"}
        resp = requests.patch(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body),
               verify=self.verify)
        if resp.status_code == 200:
            self.logger.debug("Validation for logical interface configuration succeeded")
        else:
            raise ibmiotf.APIException(resp.status_code, "Validation for logical interface configuration failed", resp)
        return resp.json()

Validate the logical interface configuration.
    Parameters:
        - logicalInterfaceId (string)
    Throws APIException on failure.


def copy_file_links(self, src):
        # type: (RockRidge) -> None

        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('Rock Ridge extension not yet initialized')

        # First, get the src data
        if src.dr_entries.px_record is None:
            if src.ce_entries.px_record is None:
                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')
            num_links = src.ce_entries.px_record.posix_file_links
        else:
            num_links = src.dr_entries.px_record.posix_file_links

        # Now apply it to this record.
        if self.dr_entries.px_record is None:
            if self.ce_entries.px_record is None:
                raise pycdlibexception.PyCdlibInvalidInput('No Rock Ridge file links')
            self.ce_entries.px_record.posix_file_links = num_links
        else:
            self.dr_entries.px_record.posix_file_links = num_links

Copy the number of file links from the source Rock Ridge entry into
    this Rock Ridge entry.

    Parameters:
    src - The source Rock Ridge entry to copy from.

Returns:
    Nothing.


def reconstruct_hostname(self, port_override=None):

    url = self.server
    port = port_override or self.port
    if port and ((self.url_scheme == 'https' and str(port) != '443') or
                 (self.url_scheme != 'https' and str(port) != '80')):
      url += ':{0}'.format(port)

    return url

Reconstruct the hostname of a request.

    This is based on the URL reconstruction code in Python PEP 333:
    http://www.python.org/dev/peps/pep-0333/#url-reconstruction.  Rebuild the
    hostname from the pieces available in the environment.

Args:
        port_override: str, An override for the port on the returned hostname.

Returns:
        The hostname portion of the URL from the request, not including the
        URL scheme.


def write_summaries(self, tagged_data, experiment_name, run_name):

    logger.debug('Writing summaries for %s tags', len(tagged_data))
    # Connection used as context manager for auto commit/rollback on exit.
    # We still need an explicit BEGIN, because it doesn't do one on enter,
    # it waits until the first DML command - which is totally broken.
    # See: https://stackoverflow.com/a/44448465/1179226
    with self._db:
      self._db.execute('BEGIN TRANSACTION')
      run_id = self._maybe_init_run(experiment_name, run_name)
      tag_to_metadata = {
          tag: tagdata.metadata for tag, tagdata in six.iteritems(tagged_data)
      }
      tag_to_id = self._maybe_init_tags(run_id, tag_to_metadata)
      tensor_values = []
      for tag, tagdata in six.iteritems(tagged_data):
        tag_id = tag_to_id[tag]
        for step, wall_time, tensor_proto in tagdata.values:
          dtype = tensor_proto.dtype
          shape = ','.join(str(d.size) for d in tensor_proto.tensor_shape.dim)
          # Use tensor_proto.tensor_content if it's set, to skip relatively
          # expensive extraction into intermediate ndarray.
          data = self._make_blob(
              tensor_proto.tensor_content or
              tensor_util.make_ndarray(tensor_proto).tobytes())
          tensor_values.append((tag_id, step, wall_time, dtype, shape, data))
      self._db.executemany(
          ,
          tensor_values)

Transactionally writes the given tagged summary data to the DB.

Args:
        tagged_data: map from tag to TagData instances.
        experiment_name: name of experiment.
        run_name: name of run.


def raise_for_status(
    status: int, headers: MutableMapping, data: MutableMapping
) -> None:

    if status != 200:
        if status == 429:

            if isinstance(data, str):
                error = data
            else:
                error = data.get("error", "ratelimited")

            try:
                retry_after = int(headers.get("Retry-After", 1))
            except ValueError:
                retry_after = 1
            raise exceptions.RateLimited(retry_after, error, status, headers, data)
        else:
            raise exceptions.HTTPException(status, headers, data)

Check request response status

Args:
        status: Response status
        headers: Response headers
        data: Response data

Raises:
        :class:`slack.exceptions.RateLimited`: For 429 status code
        :class:`slack.exceptions:HTTPException`:


def _get_populate_values(self, instance) -> Tuple[str, str]:

        return [
            (
                lang_code,
                self._get_populate_from_value(
                    instance,
                    self.populate_from,
                    lang_code
                ),
            )
            for lang_code, _ in settings.LANGUAGES
        ]

Gets all values (for each language) from the
    specified's instance's `populate_from` field.

Args:
        instance:
            The instance to get the values from.

Returns:
        A list of (lang_code, value) tuples.


def __init__(self, filename, filename_info, filetype_info):

        super(VIIRSActiveFiresTextFileHandler, self).__init__(filename, filename_info, filetype_info)

        if not os.path.isfile(filename):
            return

        self.file_content = dd.read_csv(filename, skiprows=15, header=None,
                                        names=["latitude", "longitude",
                                               "T13", "Along-scan", "Along-track", "detection_confidence",
                                               "power"])

Makes sure filepath is valid and then reads data into a Dask DataFrame

Args:
        filename: Filename
        filename_info: Filename information
        filetype_info: Filetype information


def generate_jwt_token(user, authsys, **kwargs):

    # Local import to prevent app startup failures
    from cloud_inquisitor.config import dbconfig

    token = {
        'auth_system': authsys,
        'exp': time.time() + dbconfig.get('session_expire_time'),
        'roles': [role.name for role in user.roles]
    }

    if kwargs:
        token.update(**kwargs)

    enc = jwt.encode(token, get_jwt_key_data(), algorithm='HS512')
    return enc.decode()

Generate a new JWT token, with optional extra information. Any data provided in `**kwargs`
    will be added into the token object for auth specific usage

Args:
        user (:obj:`User`): User object to generate token for
        authsys (str): The auth system for which the token was generated
        **kwargs (dict): Any optional items to add to the token

Returns:
        Encoded JWT token


def read_tracers_h5(xdmf_file, infoname, snapshot, position):

    xdmf_root = xmlET.parse(str(xdmf_file)).getroot()
    tra = {}
    tra[infoname] = [{}, {}]  # two blocks, ordered by cores
    if position:
        for axis in 'xyz':
            tra[axis] = [{}, {}]
    for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'):
        ibk = int(elt_subdomain.get('Name').startswith('meshYang'))
        if position:
            for data_attr in elt_subdomain.findall('Geometry'):
                for data_item, axis in zip(data_attr.findall('DataItem'),
                                           'xyz'):
                    icore, data = _get_field(xdmf_file, data_item)
                    tra[axis][ibk][icore] = data
        for data_attr in elt_subdomain.findall('Attribute'):
            if data_attr.get('Name') != infoname:
                continue
            icore, data = _get_field(xdmf_file, data_attr.find('DataItem'))
            tra[infoname][ibk][icore] = data
    for info in tra:
        tra[info] = [trab for trab in tra[info] if trab]  # remove empty blocks
        for iblk, trab in enumerate(tra[info]):
            tra[info][iblk] = np.concatenate([trab[icore]
                                              for icore in range(len(trab))])
    return tra

Extract tracers data from hdf5 files.

Args:
        xdmf_file (:class:`pathlib.Path`): path of the xdmf file.
        infoname (str): name of information to extract.
        snapshot (int): snapshot number.
        position (bool): whether to extract position of tracers.

Returns:
        dict of list of numpy.array:
            Tracers data organized by attribute and block.


def pyrdf(value, class_type=None, datatype=None, **kwargs):

    if isinstance(value, BaseRdfDataType):
        return value
    if isinstance(value, dict):
        value = value.copy()
        class_type = value.pop('type')
        try:
            datatype = value.pop('datatype')
        except KeyError:
            datatype = __TYPE_MATCH__[class_type]
        kwargs = value
        value = kwargs.pop('value')
    if not class_type:
        class_type = 'literal'
    if not datatype:
        datatype = type(value)
    try:
        # print("pyrdf: ", value, " class_type: ", class_type, " datatype: ", datatype)
        return __DT_LOOKUP__[class_type][datatype](value, **kwargs)
    except KeyError:
        rtn_val = BaseRdfDataType(value)
        rtn_val.datatype = Uri(datatype)
        return rtn_val

Coverts an input to one of the rdfdatatypes classes

Args:
        value: any rdfdatatype, json dict or vlaue
        class_type: "literal", "uri" or "blanknode"
        datatype: "xsd:string", "xsd:int" , etc
    kwargs:
        lang: language tag


def commit_offsets_async(self, offsets, callback=None):

        self._invoke_completed_offset_commit_callbacks()
        if not self.coordinator_unknown():
            future = self._do_commit_offsets_async(offsets, callback)
        else:
            # we don't know the current coordinator, so try to find it and then
            # send the commit or fail (we don't want recursive retries which can
            # cause offset commits to arrive out of order). Note that there may
            # be multiple offset commits chained to the same coordinator lookup
            # request. This is fine because the listeners will be invoked in the
            # same order that they were added. Note also that BaseCoordinator
            # prevents multiple concurrent coordinator lookup requests.
            future = self.lookup_coordinator()
            future.add_callback(lambda r: functools.partial(self._do_commit_offsets_async, offsets, callback)())
            if callback:
                future.add_errback(lambda e: self.completed_offset_commits.appendleft((callback, offsets, e)))

        # ensure the commit has a chance to be transmitted (without blocking on
        # its completion). Note that commits are treated as heartbeats by the
        # coordinator, so there is no need to explicitly allow heartbeats
        # through delayed task execution.
        self._client.poll(timeout_ms=0) # no wakeup if we add that feature

        return future

Commit specific offsets asynchronously.

Args:
        offsets (dict {TopicPartition: OffsetAndMetadata}): what to commit
        callback (callable, optional): called as callback(offsets, response)
            response will be either an Exception or a OffsetCommitResponse
            struct. This callback can be used to trigger custom actions when
            a commit request completes.

Returns:
        kafka.future.Future


def _get_type(points, soma_class):

    assert soma_class in (SOMA_CONTOUR, SOMA_CYLINDER)

    npoints = len(points)
    if soma_class == SOMA_CONTOUR:
        return {0: None,
                1: SomaSinglePoint,
                2: None}.get(npoints, SomaSimpleContour)

    if(npoints == 3 and
       points[0][COLS.P] == -1 and
       points[1][COLS.P] == 1 and
       points[2][COLS.P] == 1):
        L.warning('Using neuromorpho 3-Point soma')
        # NeuroMorpho is the main provider of morphologies, but they
        # with SWC as their default file format: they convert all
        # uploads to SWC.  In the process of conversion, they turn all
        # somas into their custom 'Three-point soma representation':
        #  http://neuromorpho.org/SomaFormat.html

        return SomaNeuromorphoThreePointCylinders

    return {0: None,
            1: SomaSinglePoint}.get(npoints, SomaCylinders)

get the type of the soma

Args:
        points: Soma points
        soma_class(str): one of 'contour' or 'cylinder' to specify the type


def has_all_nonzero_neurite_radii(neuron, threshold=0.0):

    bad_ids = []
    seen_ids = set()
    for s in _nf.iter_sections(neuron):
        for i, p in enumerate(s.points):
            info = (s.id, i)
            if p[COLS.R] <= threshold and info not in seen_ids:
                seen_ids.add(info)
                bad_ids.append(info)

    return CheckResult(len(bad_ids) == 0, bad_ids)

Check presence of neurite points with radius not above threshold

Args:
        neuron(Neuron): The neuron object to test
        threshold: value above which a radius is considered to be non-zero

Returns:
        CheckResult with result including list of (section ID, point ID) pairs
        of zero-radius points


def scroll(self, x, y):

        assert isinstance(x, _INTTYPES), "x must be an integer, got %s" % repr(x)
        assert isinstance(y, _INTTYPES), "y must be an integer, got %s" % repr(x)
        def getSlide(x, length):

            if x > 0:
                srcx = 0
                length -= x
            elif x < 0:
                srcx = abs(x)
                x = 0
                length -= srcx
            else:
                srcx = 0
            return x, length, srcx
        def getCover(x, length):

            cover = (0, length) # everything covered
            uncover = None  # nothing uncovered
            if x > 0: # left side uncovered
                cover = (x, length - x)
                uncover = (0, x)
            elif x < 0: # right side uncovered
                x = abs(x)
                cover = (0, length - x)
                uncover = (length - x, x)
            return cover, uncover

        width, height = self.get_size()
        if abs(x) >= width or abs(y) >= height:
            return self.clear() # just clear the console normally

        # get the ranges of the areas that will be uncovered
        coverX, uncoverX = getCover(x, width)
        coverY, uncoverY = getCover(y, height)
        # so at this point we know that coverX and coverY makes a rect that
        # encases the area that we end up blitting to.  uncoverX/Y makes a
        # rect in the corner of the uncovered area.  So we need to combine
        # the uncoverX/Y with coverY/X to make what's left of the uncovered
        # area.  Explaining it makes it mush easier to do now.

        # But first we need to blit.
        x, width, srcx = getSlide(x, width)
        y, height, srcy = getSlide(y, height)
        self.blit(self, x, y, width, height, srcx, srcy)
        if uncoverX: # clear sides (0x20 is space)
            self.draw_rect(uncoverX[0], coverY[0], uncoverX[1], coverY[1],
                           0x20, self._fg, self._bg)
        if uncoverY: # clear top/bottom
            self.draw_rect(coverX[0], uncoverY[0], coverX[1], uncoverY[1],
                           0x20, self._fg, self._bg)
        if uncoverX and uncoverY: # clear corner
            self.draw_rect(uncoverX[0], uncoverY[0], uncoverX[1], uncoverY[1],
                           0x20, self._fg, self._bg)

Scroll the contents of the console in the direction of x,y.

    Uncovered areas will be cleared to the default background color.
    Does not move the virutal cursor.

Args:
        x (int): Distance to scroll along the x-axis.
        y (int): Distance to scroll along the y-axis.

Returns:
        Iterator[Tuple[int, int]]: An iterator over the (x, y) coordinates
        of any tile uncovered after scrolling.

    .. seealso:: :any:`set_colors`


def __init__(self, port=None, queue_id=None):

        super().__init__(action_type=ActionType.OFPAT_ENQUEUE, length=16)
        self.port = port
        self.queue_id = queue_id

Create an ActionEnqueue with the optional parameters below.

Args:
        port (physical port or :attr:`.Port.OFPP_IN_PORT`): Queue's port.
        queue_id (int): Where to enqueue the packets.


def get_welcome(self, connId='default'):

        thisConn = self.__getConnection(connId)
        outputMsg = ""
        try:
            outputMsg += thisConn.getwelcome()
        except ftplib.all_errors as e:
            raise FtpLibraryError(str(e))
        if self.printOutput:
            logger.info(outputMsg)
        return outputMsg

Returns wlecome message of FTP server.
    Parameters:
    - connId(optional) - connection identifier. By default equals 'default'


def AssertType(value, expected_type):

  if not isinstance(value, expected_type):
    message = "Expected type `%r`, but got value `%r` of type `%s`"
    message %= (expected_type, value, type(value))
    raise TypeError(message)

Ensures that given value has certain type.

Args:
        value: A value to assert the type for.
        expected_type: An expected type for the given value.

Raises:
        TypeError: If given value does not have the expected type.


def find_module_id_defining_flag(self, flagname, default=None):

    registered_flag = self._flags().get(flagname)
    if registered_flag is None:
      return default
    for module_id, flags in six.iteritems(self.flags_by_module_id_dict()):
      for flag in flags:
        # It must compare the flag with the one in _flags. This is because a
        # flag might be overridden only for its long name (or short name),
        # and only its short name (or long name) is considered registered.
        if (flag.name == registered_flag.name and
            flag.short_name == registered_flag.short_name):
          return module_id
    return default

Return the ID of the module defining this flag, or default.

Args:
        flagname: str, name of the flag to lookup.
        default: Value to return if flagname is not defined. Defaults
        to None.

Returns:
        The ID of the module which registered the flag with this name.
        If no such module exists (i.e. no flag with this name exists),
        we return default.


def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP:

    return Bsp(x, y, w, h)

Create a new BSP instance with the given rectangle.

Args:
        x (int): Rectangle left coordinate.
        y (int): Rectangle top coordinate.
        w (int): Rectangle width.
        h (int): Rectangle height.

Returns:
        BSP: A new BSP instance.

    .. deprecated:: 2.0
        Call the :any:`BSP` class instead.


def _bfd_rx(self, **kwargs):

        method_name = 'rbridge_id_router_router_bgp_router_bgp_attributes_' \
                      'bfd_interval_min_rx'
        bfd_rx = getattr(self._rbridge, method_name)
        config = bfd_rx(**kwargs)
        if kwargs['delete']:
            tag = 'min-rx'
            config.find('.//*%s' % tag).set('operation', 'delete')
            pass
        return config

Return the BFD minimum receive interval XML.

    You should not use this method.
    You probably want `BGP.bfd`.

Args:
        min_rx (str): BFD receive interval in milliseconds (300, 500, etc)
        delete (bool): Remove the configuration if ``True``.

Returns:
        XML to be passed to the switch.

Raises:
        None


def _verify_docker_image_size(self, image_name):

    shell_call(['docker', 'pull', image_name])
    try:
      image_size = subprocess.check_output(
          ['docker', 'inspect', '--format={{.Size}}', image_name]).strip()
      image_size = int(image_size)
    except (ValueError, subprocess.CalledProcessError) as e:
      logging.error('Failed to determine docker image size: %s', e)
      return False
    logging.info('Size of docker image %s is %d', image_name, image_size)
    if image_size > MAX_DOCKER_IMAGE_SIZE:
      logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE)
    return image_size <= MAX_DOCKER_IMAGE_SIZE

Verifies size of Docker image.

Args:
        image_name: name of the Docker image.

Returns:
        True if image size is within the limits, False otherwise.


def get_pattern_link_topattern(self, patternnumber):

        _checkPatternNumber(patternnumber)

        address = _calculateRegisterAddress('linkpattern', patternnumber)
        return self.read_register(address)

Get the 'linked pattern' value for a given pattern.

Args:
        patternnumber (integer): From 0-7

Returns:
        The 'linked pattern' value (int).


def get_lanczos_eig(self, compute_m=True, feed_dict=None):

    if compute_m:
      min_eig, min_vec = self.sess.run([self.m_min_eig, self.m_min_vec], feed_dict=feed_dict)

    else:
      min_eig, min_vec = self.sess.run([self.h_min_eig, self.h_min_vec], feed_dict=feed_dict)

    return min_vec, min_eig

Computes the min eigen value and corresponding vector of matrix M or H
    using the Lanczos algorithm.

Args:
        compute_m: boolean to determine whether we should compute eig val/vec
        for M or for H. True for M; False for H.
        feed_dict: dictionary mapping from TF placeholders to values (optional)

Returns:
        min_eig_vec: Corresponding eigen vector to min eig val
        eig_val: Minimum eigen value


def query(self, query):

    # run the query on the child datastore
    cursor = self.child_datastore.query(query)

    # chain the deserializing generator to the cursor's result set iterable
    cursor._iterable = deserialized_gen(self.serializer, cursor._iterable)

    return cursor

Returns an iterable of objects matching criteria expressed in `query`
    De-serializes values on the way out, using a :ref:`deserialized_gen` to
    avoid incurring the cost of de-serializing all data at once, or ever, if
    iteration over results does not finish (subject to order generator
    constraint).

Args:
        query: Query object describing the objects to return.

    Raturns:
        iterable cursor with all objects matching criteria


def asm_module(exprs, dst_reg, sym_to_reg, triple_or_target=None):

    if not llvmlite_available:
        raise RuntimeError("llvmlite module unavailable! can't assemble...")

    target = llvm_get_target(triple_or_target)

    M = ll.Module()
    fntype = ll.FunctionType(ll.VoidType(), [])
    func = ll.Function(M, fntype, name='__arybo')
    func.attributes.add("naked")
    func.attributes.add("nounwind")
    BB = func.append_basic_block()

    IRB = ll.IRBuilder()
    IRB.position_at_end(BB)

    sym_to_value = {sym: IRB.load_reg(IntType(reg[1]), reg[0], reg[0]) for sym,reg in six.iteritems(sym_to_reg)}

    ret = to_llvm_ir(exprs, sym_to_value, IRB)
    IRB.store_reg(ret, IntType(dst_reg[1]), dst_reg[0])
    # See https://llvm.org/bugs/show_bug.cgi?id=15806
    IRB.unreachable()

    return M

Generate an LLVM module for a list of expressions

Args:
        * See :meth:`arybo.lib.exprs_asm.asm_binary` for a description of the list of arguments

    Output:
        * An LLVM module with one function named "__arybo", containing the
        translated expression.

    See :meth:`arybo.lib.exprs_asm.asm_binary` for an usage example.


def get_token(self,
                  token_name,
                  project_name,
                  dataset_name):

        return self.resources.get_token(token_name,
                                        project_name,
                                        dataset_name)

Get a token with the given parameters.

Args:
        project_name (str): Project name
        dataset_name (str): Dataset name project is based on
        token_name (str): Token name

Returns:
        dict: Token info


def remove(self,
               entity_id,
               property_uri,
               value):

        if not entity_id.startswith("http"):
            entity_uri = urllib.parse.urljoin(self.base_url, entity_id)
        else:
            entity_uri = entity_id
        sparql_template = Template()
        sparql = sparql_template.substitute(
            prefix=build_prefixes(self.namespaces),
            entity=entity_uri,
            prop_name=property_uri,
            value_str=self.__value_format__(value))
        delete_property_request = urllib.request.Request(
            entity_uri,
            data=sparql.encode(),
            method='PATCH',
            headers={'Content-Type': 'application/sparql-update'})
        response = urllib.request.urlopen(delete_property_request)
        if response.code < 400:
            return True
        return False

Method removes a triple for the given/subject.

Args:
        entity_id(string): Fedora Object ID, ideally URI of the subject
        property_uri(string):
        value(string):

Returns:
        boolean: True if triple was removed from the object


def last_revision(self, mod: YangIdentifier) -> ModuleId:

        revs = [mn for mn in self.modules if mn[0] == mod]
        if not revs:
            raise ModuleNotRegistered(mod)
        return sorted(revs, key=lambda x: x[1])[-1]

Return the last revision of a module that's part of the data model.

Args:
        mod: Name of a module or submodule.

Raises:
        ModuleNotRegistered: If the module `mod` is not present in the
            data model.


def list_files(base_path, ext=None):

    if not os.path.isdir(base_path):
        raise ValueError("Path does not exist: %s" % base_path)

    files = []
    for entry in os.listdir(base_path):
        if os.path.isfile(os.path.join(base_path, entry)):
            _, entry_ext = os.path.splitext(entry)
            entry_ext = entry_ext.lstrip('.')

            if (ext is None) or \
                (isinstance(ext, str) and entry_ext == ext) or \
                (isinstance(ext, list) and entry_ext in ext):
                files.append(entry)

    return files

Lists all of the files in the given base directory, optionally only
    including whose extension(s) match the ext string/list of strings.
    This is non-recursive.

Args:
        base_path: The directory in which to search.
        ext: The extension(s) to match in the given directory. If None, this
            matches all file extensions.

Returns:
        A list of filenames relative to the given base path.


def get_catalog_courses(self, catalog_id):

        return self._load_data(
            self.CATALOGS_COURSES_ENDPOINT.format(catalog_id),
            default=[]
        )

Return the courses included in a single course catalog by ID.

Args:
        catalog_id (int): The catalog ID we want to retrieve.

Returns:
        list: Courses of the catalog in question


def push_plugin(self, name):

        url = self._url('/plugins/{0}/pull', name)

        headers = {}
        registry, repo_name = auth.resolve_repository_name(name)
        header = auth.get_config_header(self, registry)
        if header:
            headers['X-Registry-Auth'] = header
        res = self._post(url, headers=headers)
        self._raise_for_status(res)
        return self._stream_helper(res, decode=True)

Push a plugin to the registry.

Args:
        name (string): Name of the plugin to upload. The ``:latest``
            tag is optional, and is the default if omitted.

Returns:
        ``True`` if successful


def setdocument(self, doc):

        assert isinstance(doc, Document)

        if not self.doc:
            self.doc = doc
            if self.id:
                if self.id in doc:
                    raise DuplicateIDError(self.id)
                else:
                    self.doc.index[id] = self

        for e in self: #recursive for all children
            if isinstance(e,AbstractElement): e.setdocument(doc)

Associate a document with this element.

Args:
        doc (:class:`Document`): A document

    Each element must be associated with a FoLiA document.


def decompress_decoder_1d(x, hparams, name=None):

  x = tf.expand_dims(x, axis=2)
  output = decompress_decoder(x, hparams,
                              strides=(2, 1),
                              kernel=(hparams.kernel_size, 1),
                              name=name)
  return tf.squeeze(output, axis=2)

Decoder that decompresses 1-D inputs by 2**num_compress_steps.

Args:
        x: Tensor of shape [batch, compress_length, channels].
        hparams: HParams.
        name: string, variable scope.

Returns:
        Tensor of shape [batch, length, hparams.hidden_size].


def unpack(self, gpsd_socket_response):

        try:
            fresh_data = json.loads(gpsd_socket_response)  # The reserved word 'class' is popped from JSON object class
            package_name = fresh_data.pop('class', 'ERROR')  # gpsd data package errors are also 'ERROR'.
            package = getattr(self, package_name, package_name)  # packages are named for JSON object class
            for key in package.keys():
                package[key] = fresh_data.get(key, 'n/a')  # Restores 'n/a' if key is absent in the socket response

        except AttributeError:  # 'str' object has no attribute 'keys'
            sys.stderr.write('There is an unexpected exception in DataStream.unpack')
            return

        except (ValueError, KeyError) as error:
            sys.stderr.write(str(error))  # Extra data or aberrant data in stream.
            return

Sets new socket data as DataStream attributes in those initialised dictionaries

Args:
        gpsd_socket_response (json object):
    Provides:
    self attribute dictionaries, e.g., self.TPV['lat'], self.SKY['gdop']

Raises:
    AttributeError: 'str' object has no attribute 'keys' when the device falls out of the system
    ValueError, KeyError: most likely extra, or mangled JSON data, should not happen, but that
    applies to a lot of things.


def update(self, resource, timeout=-1):

        self.__set_default_values(resource)
        uri = self._client.build_uri(resource['logicalSwitch']['uri'])
        return self._client.update(resource, uri=uri, timeout=timeout)

Updates a Logical Switch.

Args:
        resource (dict): Object to update.
        timeout:
            Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
            in OneView, just stop waiting for its completion.

Returns:
        dict: Updated resource.


def __init__(self, options={}):

        settings = {
            'currency': {
                'symbol': "$",
                'format': "%s%v",
                'decimal': ".",
                'thousand': ",",
                'precision': 2,
                'grouping': 3
            },
            'number': {
                'precision': 0,
                'grouping': 3,
                'thousand': ",",
                'decimal': "."
            }
        }
        if options:
            settings.update(options)

        self.settings = settings

Summary.

Args:
        options (dict, optional): settings configuration object.


def memory_write32(self, addr, data, zone=None):

        return self.memory_write(addr, data, zone, 32)

Writes words to memory of a target system.

Args:
        self (JLink): the ``JLink`` instance
        addr (int): start address to write to
        data (list): list of words to write
        zone (str): optional memory zone to access

Returns:
        Number of words written to target.

Raises:
        JLinkException: on memory access error.


def AddKeywordsForName(self, name, keywords):

    data_store.DB.IndexAddKeywordsForName(self.urn, name, keywords)

Associates keywords with name.

    Records that keywords are associated with name.

Args:
        name: A name which should be associated with some keywords.
        keywords: A collection of keywords to associate with name.


def listtransactions(self, user_id="", count=10, start_at=0):

        txlist = self.rpc.call("listtransactions", user_id, count, start_at)
        self.logger.debug("Got transaction list for " + str(user_id))
        return txlist

List all transactions associated with this account.

Args:
        user_id (str): this user's unique identifier
        count (int): number of transactions to return (default=10)
        start_at (int): start the list at this transaction (default=0)

Returns:
        list [dict]: transactions associated with this user's account


def __init__(self, item_id, desc,  # pylint: disable=too-many-arguments
                 resources, uri, metadata_dict, music_service=None):

        _LOG.debug('%s.__init__ with item_id=%s, desc=%s, resources=%s, '
                   'uri=%s, metadata_dict=..., music_service=%s',
                   self.__class__.__name__, item_id, desc, resources, uri,
                   music_service)
        super(MusicServiceItem, self).__init__(metadata_dict)
        self.item_id = item_id
        self.desc = desc
        self.resources = resources
        self.uri = uri
        self.music_service = music_service

Init music service item

Args:
        item_id (str): This is the Didl compatible id NOT the music item id
        desc (str): A DIDL descriptor, default ``'RINCON_AssociatedZPUDN'
        resources (list): List of DidlResource
        uri (str): The uri for the location of the item
        metdata_dict (dict): Mapping of metadata
        music_service (MusicService): The MusicService instance the item
            originates from


def GetFieldValuesTuple(self, trip_id):

    result = []
    for fn in self._FIELD_NAMES:
      if fn == 'trip_id':
        result.append(trip_id)
      else:
        # Since we'll be writting to an output file, we want empty values to be
        # outputted as an empty string
        result.append(getattr(self, fn) or '' )
    return tuple(result)

Return a tuple that outputs a row of _FIELD_NAMES to be written to a
    GTFS file.

Args:
    trip_id: The trip_id of the trip to which this StopTime corresponds.
            It must be provided, as it is not stored in StopTime.


def lines_from_string(string, as_interned=False):

    if as_interned:
        return [sys.intern(line) for line in string.splitlines()]
    return string.splitlines()

Create a list of file lines from a given string.

Args:
        string (str): File string
        as_interned (bool): List of "interned" strings (default False)

Returns:
        strings (list): File line list


def delete_existing_cname(env, zone_id, dns_name):

    client = boto3.Session(profile_name=env).client('route53')
    startrecord = None
    newrecord_name = dns_name
    startrecord = find_existing_record(env, zone_id, newrecord_name, check_key='Type', check_value='CNAME')
    if startrecord:
        LOG.info("Deleting old record: %s", newrecord_name)
        _response = client.change_resource_record_sets(
            HostedZoneId=zone_id, ChangeBatch={'Changes': [{
                'Action': 'DELETE',
                'ResourceRecordSet': startrecord
            }]})
        LOG.debug('Response from deleting %s: %s', dns_name, _response)

Delete an existing CNAME record.

    This is used when updating to multi-region for deleting old records. The
    record can not just be upserted since it changes types.

Args:
        env (str): Deployment environment.
        zone_id (str): Route53 zone id.
        dns_name (str): FQDN of application's dns entry to add/update.


def persist_time(run, session, timings):

    from benchbuild.utils import schema as s

    for timing in timings:
        session.add(
            s.Metric(name="time.user_s", value=timing[0], run_id=run.id))
        session.add(
            s.Metric(name="time.system_s", value=timing[1], run_id=run.id))
        session.add(
            s.Metric(name="time.real_s", value=timing[2], run_id=run.id))

Persist the run results in the database.

Args:
        run: The run we attach this timing results to.
        session: The db transaction we belong to.
        timings: The timing measurements we want to store.


def _convert_to_eval_metric(metric_fn):

  def problem_metric_fn(*args):

    (scores, weights) = metric_fn(*args)

    # The tf.metrics.mean function assures correct aggregation.
    return tf.metrics.mean(scores, weights)
  return problem_metric_fn

Wrap a metric fn that returns scores and weights as an eval metric fn.

    The input metric_fn returns values for the current batch. The wrapper
    aggregates the return values collected over all of the batches evaluated.

Args:
        metric_fn: function that returns scores and weights for the current batch's
        logits and predicted labels.

Returns:
        function that aggregates the scores and weights from metric_fn.


def at(self, instant):

        for event in self:
            if event.begin <= instant <= event.end:
                yield event

Iterates (in chronological order) over all events that are occuring during `instant`.

Args:
        instant (Arrow object)


def get_minimizer_options(method):

    if method == 'Powell':
        return {'patience': 2,
                'patience_line_search': None,
                'reset_method': 'EXTRAPOLATED_POINT'}

    elif method == 'Nelder-Mead':
        return {'patience': 200,
                'alpha': 1.0, 'beta': 0.5, 'gamma': 2.0, 'delta': 0.5, 'scale': 0.1,
                'adaptive_scales': True}

    elif method == 'Levenberg-Marquardt':
        return {'patience': 250, 'step_bound': 100.0, 'scale_diag': 1, 'usertol_mult': 30}

    elif method == 'Subplex':
        return {'patience': 10,
                'patience_nmsimplex': 100,
                'alpha': 1.0, 'beta': 0.5, 'gamma': 2.0, 'delta': 0.5, 'scale': 1.0, 'psi': 0.0001, 'omega': 0.01,
                'adaptive_scales': True,
                'min_subspace_length': 'auto',
                'max_subspace_length': 'auto'}

    raise ValueError('Could not find the specified method "{}".'.format(method))

Return a dictionary with the default options for the given minimization method.

Args:
        method (str): the name of the method we want the options off

Returns:
        dict: a dictionary with the default options


def expect_exitstatus(self, exit_status):

        self.expect_end()
        logger.debug("Checking exit status of '{0}', output so far: {1}".format(
            self.name, self.get_output()))
        if self._spawn.exitstatus is None:
            raise WrongExitStatusException(
                instance=self, expected=exit_status, output=self.get_output())

        if self._spawn.exitstatus is not exit_status:
            raise WrongExitStatusException(
                instance=self,
                expected=exit_status,
                got=self._spawn.exitstatus,
                output=self.get_output())

Wait for the running program to finish and expect some exit status.

Args:
        exit_status (int):  The expected exit status.

Raises:
        WrongExitStatusException: The produced exit status is not the expected one.


def ParseFileObject(self, parser_mediator, file_object):

    msiecf_file = pymsiecf.file()
    msiecf_file.set_ascii_codepage(parser_mediator.codepage)

    try:
      msiecf_file.open_file_object(file_object)
    except IOError as exception:
      parser_mediator.ProduceExtractionWarning(
          'unable to open file with error: {0!s}'.format(exception))
      return

    try:
      self._ParseItems(parser_mediator, msiecf_file)
    finally:
      msiecf_file.close()

Parses a MSIE Cache File (MSIECF) file-like object.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        file_object (dfvfs.FileIO): file-like object.


def collections(tag, collectionName, token='', version=''):

    if tag not in _COLLECTION_TAGS:
        raise PyEXception('Tag must be in %s' % str(_COLLECTION_TAGS))
    return _getJson('stock/market/collection/' + tag + '?collectionName=' + collectionName, token, version)

Returns an array of quote objects for a given collection type. Currently supported collection types are sector, tag, and list

    https://iexcloud.io/docs/api/#collections

Args:
        tag (string);  Sector, Tag, or List
        collectionName (string);  Associated name for tag
        token (string); Access token
        version (string); API version

Returns:
        dict: result


def _post_process_apply(self, result_data, axis, try_scale=True):

        if try_scale:
            try:
                internal_index = self.compute_index(0, result_data, True)
            except IndexError:
                internal_index = self.compute_index(0, result_data, False)
            try:
                internal_columns = self.compute_index(1, result_data, True)
            except IndexError:
                internal_columns = self.compute_index(1, result_data, False)
        else:
            internal_index = self.compute_index(0, result_data, False)
            internal_columns = self.compute_index(1, result_data, False)
        if not axis:
            index = internal_index
            # We check if the two columns are the same length because if
            # they are the same length, `self.columns` is the correct index.
            # However, if the operation resulted in a different number of columns,
            # we must use the derived columns from `self.compute_index()`.
            if len(internal_columns) != len(self.columns):
                columns = internal_columns
            else:
                columns = self.columns
        else:
            columns = internal_columns
            # See above explanation for checking the lengths of columns
            if len(internal_index) != len(self.index):
                index = internal_index
            else:
                index = self.index
        return self.__constructor__(result_data, index, columns)

Recompute the index after applying function.

Args:
        result_data: a BaseFrameManager object.
        axis: Target axis along which function was applied.

Returns:
        A new PandasQueryCompiler.


def download(branch=None, build=True, installdir="MalmoPlatform"):

    if branch is None:
        branch = malmo_version

    subprocess.check_call(["git", "clone", "-b", branch, "https://github.com/Microsoft/malmo.git", installdir])

    return setup(build=build, installdir=installdir)

Download Malmo from github and build (by default) the Minecraft Mod.
    Example usage: import malmoenv.bootstrap; malmoenv.bootstrap.download()

Args:
    branch: optional branch to clone. TODO Default is release version.
    build: build the Mod unless build arg is given as False.
    installdir: the install dir name. Defaults to MalmoPlatform.

Returns:
    The path for the Malmo Minecraft mod.


def __init__(self, encoding='utf-8'):

    super(StdoutOutputWriter, self).__init__(sys.stdout, encoding=encoding)

Initializes a stdout output writer.

Args:
        encoding (Optional[str]): output encoding.


def user(self, email):

        LOG.info("Fetching user %s", email)
        user_obj = self.user_collection.find_one({'_id': email})

        return user_obj

Fetch a user from the database.

Args:
        email(str)

Returns:
        user_obj(dict)


def _create_plugin(self, config):

        if config is None:
            raise ValueError('No plugin config to create plugin from.')

        name = config.pop('name', None)
        if name is None:
            raise(cfg.AitConfigMissing('plugin name'))

        # TODO I don't think we actually care about this being unique? Left over from
        # previous conversations about stuff?
        module_name = name.rsplit('.', 1)[0]
        class_name = name.rsplit('.', 1)[-1]
        if class_name in [x.name for x in (self.outbound_streams +
                                           self.inbound_streams +
                                           self.servers +
                                           self.plugins)]:
            raise ValueError(
                'Plugin "{}" already loaded. Only one plugin of a given name is allowed'.
                format(class_name)
            )

        plugin_inputs = config.pop('inputs', None)
        if plugin_inputs is None:
            log.warn('No plugin inputs specified for {}'.format(name))
            plugin_inputs = [ ]

        subscribers = config.pop('outputs', None)
        if subscribers is None:
            log.warn('No plugin outputs specified for {}'.format(name))
            subscribers = [ ]

        # try to create plugin
        module = import_module(module_name)
        plugin_class = getattr(module, class_name)
        instance = plugin_class(plugin_inputs,
                                subscribers,
                                zmq_args={'zmq_context': self.broker.context,
                                          'zmq_proxy_xsub_url': self.broker.XSUB_URL,
                                          'zmq_proxy_xpub_url': self.broker.XPUB_URL},
                                **config
        )

        return instance

Creates a plugin from its config.

    Params:
        config:       plugin configuration as read by ait.config

Returns:
        plugin:       a Plugin

Raises:
        ValueError:   if any of the required config values are missing


def select_if(df, fun):

    def _filter_f(col):
        try:
            return fun(df[col])
        except:
            return False

    cols = list(filter(_filter_f, df.columns))
    return df[cols]

Selects columns where fun(ction) is true

Args:
        fun: a function that will be applied to columns


def Remove(self, row):

        if row == 0 or row > self.size:
            raise TableError("Attempt to remove header row")
        new_table = []
        # pylint: disable=E1103
        for t_row in self._table:
            if t_row.row != row:
                new_table.append(t_row)
                if t_row.row > row:
                    t_row.row -= 1
        self._table = new_table

Removes a row from the table.

Args:
        row: int, the row number to delete. Must be >= 1, as the header
        cannot be removed.

Raises:
        TableError: Attempt to remove nonexistent or header row.