def filter_by_analysis_period(self, analysis_period):

        _filtered_data = self.filter_by_months_per_hour(
            analysis_period.months_per_hour)
        _filtered_data.header._analysis_period = analysis_period
        return _filtered_data

Filter the Data Collection based on an analysis period.

Args:
analysis period: A Ladybug analysis period

Return:
A new Data Collection with filtered data


def annotations_from_file(filename):

    import edflib
    e = edflib.EdfReader(filename, annotations_mode='all')
    return e.read_annotations()

Get a list of event annotations from an EDF (European Data Format file
or EDF+ file, using edflib.

Args:
filename: EDF+ file

Returns:
list: annotation events, each in the form [start_time, duration, text]


def __init__(self, rdfclass=None, **kwargs):

    super(RDFStructDictType, self).__init__(**kwargs)
    self._type = self.rdfclass = rdfclass

An arg which must be an RDFStruct.

Args:
rdfclass: The RDFStruct subclass that this arg must be.
**kwargs: Passthrough to base class.


def asym(scatterer, h_pol=True):
    if (scatterer.psd_integrator is not None):
        return scatterer.psd_integrator.get_angular_integrated(scatterer.psd, scatterer.get_geometry(), 'asym')
    old_geom = scatterer.get_geometry()
    cos_t0 = np.cos((scatterer.thet0 * deg_to_rad))
    sin_t0 = np.sin((scatterer.thet0 * deg_to_rad))
    p0 = (scatterer.phi0 * deg_to_rad)

    def integrand(thet, phi):
        (scatterer.phi, scatterer.thet) = ((phi * rad_to_deg), (thet * rad_to_deg))
        cos_T_sin_t = (0.5 * ((np.sin((2 * thet)) * cos_t0) + (((1 - np.cos((2 * thet))) * sin_t0) * np.cos((p0 - phi)))))
        I = sca_intensity(scatterer, h_pol)
        return (I * cos_T_sin_t)
    try:
        cos_int = dblquad(integrand, 0.0, (2 * np.pi), (lambda x: 0.0), (lambda x: np.pi))[0]
    finally:
        scatterer.set_geometry(old_geom)
    return (cos_int / sca_xsect(scatterer, h_pol))

Asymmetry parameter for the current setup, with polarization.

Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.

Returns:
The asymmetry parameter.


def __init__(self, resolver_context):

    super(NTFSFileSystem, self).__init__(resolver_context)
    self._file_object = None
    self._fsntfs_volume = None

Initializes a file system object.

Args:
resolver_context (Context): resolver context.


def update_port(self, port_information, id_or_uri, timeout=(- 1)):
    uri = (self._client.build_uri(id_or_uri) + '/ports')
    return self._client.update(port_information, uri, timeout)

Updates an interconnect port.

Args:
id_or_uri: Can be either the interconnect id or the interconnect uri.
port_information (dict): object to update
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.

Returns:
dict: The interconnect.


def variables(self, name):

        if isinstance(name, tuple):
            name = name[0]
        if name.startswith('@{'):
            name = '@' + name[2:-1]
        i = len(self)
        while i >= 0:
            i -= 1
            if name in self[i]['__variables__']:
                return self[i]['__variables__'][name]
        return False

Search for variable by name. Searches scope top down
Args:
name (string): Search term
Returns:
Variable object OR False


def _load_sentence_list(self, path):

        result = {}

        for entry in textfile.read_separated_lines_generator(path, separator='\t', max_columns=3):
            if self.include_languages is None or entry[1] in self.include_languages:
                result[entry[0]] = entry[1:]

        return result

Load and filter the sentence list.

Args:
path (str): Path to the sentence list.

Returns:
dict: Dictionary of sentences (id : language, transcription)


def __str__(self):

        d = enums.JLinkHaltReasons.__dict__
        s = next(k for k, v in d.items() if v == self.HaltReason)
        if self.dbgrq():
            return s
        return s.replace('_', ' ').title()

Returns a string representation of the instance.

Args:
self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance

Returns:
A string representation of the instance.


def get_template_files(self, template_id, filename):

        url = self.TEMPLATE_GET_FILES_URL + template_id
        request = self._get_request()

        return request.get_file(url, filename)

Download a PDF copy of a template's original files

Args:

template_id (str):  The id of the template to retrieve.

filename (str):     Filename to save the PDF file to. This should be a full path.

Returns:
Returns a PDF file


def _build(self, inputs_list):
    outputs = []
    for (idx, tensor) in enumerate(inputs_list):
        outputs.append(Linear(self._output_size, initializers=self._initializers, partitioners=self._partitioners, regularizers=self._regularizers, use_bias=((idx == 0) and self._use_bias))(tensor))
    return tf.add_n(outputs)

Connects the module into the graph.

If this is not the first time the module has been connected to the graph,
the Tensors provided here must have the same final dimensions as when called
the first time, in order for the existing variables to be the correct size
for the multiplication. The batch size may differ for each connection.

Args:
inputs_list: A list of 2D Tensors of rank 2, with leading batch dimension.

Returns:
A 2D Tensor of size [batch_size, output_size].


def count_up_to(self, limit):
    return gen_state_ops.resource_count_up_to(self.handle, limit=limit, T=self.dtype)

Increments this variable until it reaches `limit`.

When that Op is run it tries to increment the variable by `1`. If
incrementing the variable would bring it above `limit` then the Op raises
the exception `OutOfRangeError`.

If no error is raised, the Op outputs the value of the variable before
the increment.

This is essentially a shortcut for `count_up_to(self, limit)`.

Args:
limit: value at which incrementing the variable raises an error.

Returns:
A `Tensor` that will hold the variable value before the increment. If no
other Op modifies this variable, the values produced will all be
distinct.


def transform(self, value):
    with tf.name_scope((self._name + '/transform')):
        no_batch_dim = (value.shape.ndims == self._mean.shape.ndims)
        if no_batch_dim:
            value = value[(None, ...)]
        if self._center:
            value -= self._mean[(None, ...)]
        if self._scale:
            value /= tf.cond((self._count > 1), (lambda : (self._std() + 1e-08)), (lambda : tf.ones_like(self._var_sum)))[None]
        if self._clip:
            value = tf.clip_by_value(value, (- self._clip), self._clip)
        if no_batch_dim:
            value = value[0]
        return tf.check_numerics(value, 'value')

Normalize a single or batch tensor.

Applies the activated transformations in the constructor using current
estimates of mean and variance.

Args:
value: Batch or single value tensor.

Returns:
Normalized batch or single value tensor.


def line_starts_subpgm(line: str) -> Tuple[(bool, Optional[str])]:
    match = RE_SUB_START.match(line)
    if (match != None):
        f_name = match.group(1)
        return (True, f_name)
    match = RE_FN_START.match(line)
    if (match != None):
        f_name = match.group(1)
        return (True, f_name)
    return (False, None)

Indicates whether a line in the program is the first line of a subprogram
definition.

Args:
line
Returns:
(True, f_name) if line begins a definition for subprogram f_name;
(False, None) if line does not begin a subprogram definition.


def clean(self, value):

		if value is None and self._optional:
			return None

		for i in range(len(self._nodes)):

			if self._nodes[i].valid(value):

				return self._nodes[i].clean(value)

		raise ValueError('value', value)

Clean

Uses the valid method to check which type the value is, and then calls
the correct version of clean on that node

Arguments:
value {mixed} -- The value to clean

Returns:
mixed


def full_name_node(name, ctx=ast.Load()):
    names = name.split('.')
    names.reverse()
    node = ast.Name(id=names.pop(), ctx=ast.Load())
    while names:
        node = ast.Attribute(value=node, attr=names.pop(), ctx=ast.Load())
    node.ctx = ctx
    return node

Make an Attribute or Name node for name.

Translate a qualified name into nested Attribute nodes (and a Name node).

Args:
name: The name to translate to a node.
ctx: What context this name is used in. Defaults to Load()

Returns:
A Name or Attribute node.


def sequence_path(self, fasta_path):
    if (not fasta_path):
        self.sequence_dir = None
        self.sequence_file = None
    else:
        if (not op.exists(fasta_path)):
            raise OSError('{}: file does not exist'.format(fasta_path))
        if (not op.dirname(fasta_path)):
            self.sequence_dir = '.'
        else:
            self.sequence_dir = op.dirname(fasta_path)
        self.sequence_file = op.basename(fasta_path)
        tmp_sr = SeqIO.read(fasta_path, 'fasta')
        if (self.name == '<unknown name>'):
            self.name = tmp_sr.name
        if (self.description == '<unknown description>'):
            self.description = tmp_sr.description
        if (not self.dbxrefs):
            self.dbxrefs = tmp_sr.dbxrefs
        if (not self.features):
            self.features = tmp_sr.features
        if (not self.annotations):
            self.annotations = tmp_sr.annotations
        if (not self.letter_annotations):
            self.letter_annotations = tmp_sr.letter_annotations

Provide pointers to the paths of the FASTA file

Args:
fasta_path: Path to FASTA file


def get_source_var_declaration(self, var):
    return next((x.source_mapping for x in self.variables if (x.name == var)))

Return the source mapping where the variable is declared

Args:
var (str): variable name
Returns:
(dict): sourceMapping


def __init__(self, device, configs=None):
    self._device = device
    self._configs = configs

Constructor of the class.

The constructor is the only place to pass in a config. If you need to
change the config later, you should unregister the service instance
from `ServiceManager` and register again with the new config.

Args:
device: the device object this service is associated with.
config: optional configuration defined by the author of the service
class.


def join_dags(self, names=None):

        return self._client.send(
            Request(
                action='join_dags',
                payload={'names': names}
            )
        ).success

Wait for the specified dags to terminate.

This function blocks until the specified dags terminate. If no dags are specified
wait for all dags of the workflow, except the dag of the task calling this signal,
to terminate.

Args:
names (list): The names of the dags that have to terminate.

Returns:
bool: True if all the signal was sent successfully.


def to_string(cls, error_code):

        if error_code == cls.ERROR_UNKNOWN:
            return 'Unknown error.'
        elif error_code == cls.ERROR_NO_MORE_EVENTS:
            return 'There are no more available watchpoint units.'
        elif error_code == cls.ERROR_NO_MORE_ADDR_COMP:
            return 'No more address comparisons can be set.'
        elif error_code == cls.ERROR_NO_MORE_DATA_COMP:
            return 'No more data comparisons can be set.'
        elif error_code == cls.ERROR_INVALID_ADDR_MASK:
            return 'Invalid flags passed for the address mask.'
        elif error_code == cls.ERROR_INVALID_DATA_MASK:
            return 'Invalid flags passed for the data mask.'
        elif error_code == cls.ERROR_INVALID_ACCESS_MASK:
            return 'Invalid flags passed for the access mask.'
        return super(JLinkDataErrors, cls).to_string(error_code)

Returns the string message for the given error code.

Args:
cls (JLinkDataErrors): the ``JLinkDataErrors`` class
error_code (int): error code to convert

Returns:
An error string corresponding to the error code.

Raises:
ValueError: if the error code is invalid.


def create_attention_mask_from_sequences(self, query_ids: List[int], table_values: List[TableValue]) -> List[int]:
    return [1] * (1 + len(query_ids) + 1 + len(table_values))

Creates the attention mask according to the query token IDs and a list of table values.

Args:
query_ids (`List[int]`): list of token IDs corresponding to the ID.
table_values (`List[TableValue]`): lift of table values, which are named tuples containing the
token value, the column ID and the row ID of said token.

Returns:
`List[int]`: List of ints containing the attention mask values.


def _task_table(self, task_id):
    assert isinstance(task_id, ray.TaskID)
    message = self._execute_command(task_id, 'RAY.TABLE_LOOKUP', ray.gcs_utils.TablePrefix.RAYLET_TASK, '', task_id.binary())
    if (message is None):
        return {}
    gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(message, 0)
    assert (gcs_entries.EntriesLength() == 1)
    task_table_message = ray.gcs_utils.Task.GetRootAsTask(gcs_entries.Entries(0), 0)
    execution_spec = task_table_message.TaskExecutionSpec()
    task_spec = task_table_message.TaskSpecification()
    task = ray._raylet.Task.from_string(task_spec)
    function_descriptor_list = task.function_descriptor_list()
    function_descriptor = FunctionDescriptor.from_bytes_list(function_descriptor_list)
    task_spec_info = {'DriverID': task.driver_id().hex(), 'TaskID': task.task_id().hex(), 'ParentTaskID': task.parent_task_id().hex(), 'ParentCounter': task.parent_counter(), 'ActorID': task.actor_id().hex(), 'ActorCreationID': task.actor_creation_id().hex(), 'ActorCreationDummyObjectID': task.actor_creation_dummy_object_id().hex(), 'ActorCounter': task.actor_counter(), 'Args': task.arguments(), 'ReturnObjectIDs': task.returns(), 'RequiredResources': task.required_resources(), 'FunctionID': function_descriptor.function_id.hex(), 'FunctionHash': binary_to_hex(function_descriptor.function_hash), 'ModuleName': function_descriptor.module_name, 'ClassName': function_descriptor.class_name, 'FunctionName': function_descriptor.function_name}
    return {'ExecutionSpec': {'Dependencies': [execution_spec.Dependencies(i) for i in range(execution_spec.DependenciesLength())], 'LastTimestamp': execution_spec.LastTimestamp(), 'NumForwards': execution_spec.NumForwards()}, 'TaskSpec': task_spec_info}

Fetch and parse the task table information for a single task ID.

Args:
task_id: A task ID to get information about.

Returns:
A dictionary with information about the task ID in question.


def uniprot_reviewed_checker_batch(uniprot_ids):
    uniprot_ids = ssbio.utils.force_list(uniprot_ids)
    invalid_ids = [i for i in uniprot_ids if (not is_valid_uniprot_id(i))]
    uniprot_ids = [i for i in uniprot_ids if is_valid_uniprot_id(i)]
    if invalid_ids:
        warnings.warn('Invalid UniProt IDs {} will be ignored'.format(invalid_ids))
    Nmax = 200
    (N, rest) = divmod(len(uniprot_ids), Nmax)
    uni_rev_dict = {}
    if (rest > 0):
        N += 1
    for i in range(0, N):
        i1 = (i * Nmax)
        i2 = ((i + 1) * Nmax)
        if (i2 > len(uniprot_ids)):
            i2 = len(uniprot_ids)
        query = uniprot_ids[i1:i2]
        query_string = ''
        for x in query:
            query_string += (('id:' + x) + '+OR+')
        query_string = query_string.strip('+OR+')
        uni_rev_raw = StringIO(bsup.search(query_string, columns='id,reviewed', frmt='tab'))
        uni_rev_df = pd.read_table(uni_rev_raw, sep='\t', index_col=0)
        uni_rev_df = uni_rev_df.fillna(False)
        uni_rev_df = uni_rev_df[pd.notnull(uni_rev_df.Status)]
        uni_rev_df = uni_rev_df.replace(to_replace='reviewed', value=True)
        uni_rev_df = uni_rev_df.replace(to_replace='unreviewed', value=False)
        uni_rev_dict_adder = uni_rev_df.to_dict()['Status']
        uni_rev_dict.update(uni_rev_dict_adder)
    return uni_rev_dict

Batch check if uniprot IDs are reviewed or not

Args:
uniprot_ids: UniProt ID or list of UniProt IDs

Returns:
A dictionary of {UniProtID: Boolean}


def netflix(es, ps, e0, l=.0001):

    m = len(es)
    n = len(ps[0])

    X = np.stack(ps).T
    pTy = .5 * (n * e0**2 + (X**2).sum(axis=0) - n * np.array(es)**2)

    w = np.linalg.pinv(X.T.dot(X) + l * n * np.eye(m)).dot(pTy)

    return X.dot(w), w

Combine predictions with the optimal weights to minimize RMSE.

Args:
es (list of float): RMSEs of predictions
ps (list of np.array): predictions
e0 (float): RMSE of all zero prediction
l (float): lambda as in the ridge regression

Returns:
Ensemble prediction (np.array) and weights (np.array) for input predictions


def convert_compartment_entry(self, compartment, adjacencies):

        d = OrderedDict()
        d['id'] = compartment.id
        if adjacencies is not None:
            d['adjacent_to'] = adjacencies

        order = {key: i for i, key in enumerate(['name'])}
        prop_keys = set(compartment.properties)
        for prop in sorted(prop_keys,
                           key=lambda x: (order.get(x, 1000), x)):
            if compartment.properties[prop] is not None:
                d[prop] = compartment.properties[prop]

        return d

Convert compartment entry to YAML dict.

Args:
compartment: :class:`psamm.datasource.entry.CompartmentEntry`.
adjacencies: Sequence of IDs or a single ID of adjacent
compartments (or None).


def node_from_map(node_map: Mapping[str, node_def_pb2.NodeDef], name: str) -> node_def_pb2.NodeDef:
    stripped_name = node_name_from_input(name)
    if stripped_name not in node_map:
        raise ValueError("No node named '%s' found in map." % name)
    return node_map[stripped_name]

Pulls a node def from a dictionary for a given name.

Args:
node_map: Dictionary containing an entry indexed by name for every node.
name: Identifies the node we want to find.

Returns:
NodeDef of the node with the given name.

Raises:
ValueError: If the node isn't present in the dictionary.


def _bdtr(k, n, p):
    ones = tf.ones_like((n - k))
    k_eq_n = tf.equal(k, n)
    safe_dn = tf.where(k_eq_n, ones, (n - k))
    dk = tf.math.betainc(a=safe_dn, b=(k + 1), x=(1 - p))
    return tf.where(k_eq_n, ones, dk)

The binomial cumulative distribution function.

Args:
k: floating point `Tensor`.
n: floating point `Tensor`.
p: floating point `Tensor`.

Returns:
`sum_{j=0}^k p^j (1 - p)^(n - j)`.


def get_next_of_type(self, processor_type):

        with self._condition:
            if processor_type not in self:
                self.wait_for_registration(processor_type)
            try:
                processor = self[processor_type].next_processor()
            except NoProcessorVacancyError:
                processor = self.wait_for_vacancy(processor_type)
            processor.inc_occupancy()
            return processor

Get the next available processor of a particular type and increment
its occupancy counter.

Args:
processor_type (ProcessorType): The processor type associated with
a zmq identity.

Returns:
(Processor): Information about the transaction processor


def getMAC(self, bType=MacType.RandomMac):

        print '%s call getMAC' % self.port
        print bType

        if self.isPowerDown:
            macAddr64 = self.mac
        else:
            if bType == MacType.FactoryMac:
                macAddr64 = self.__sendCommand('eui64')[0]
            elif bType == MacType.HashMac:
                macAddr64 = self.__sendCommand('joinerid')[0]
            else:
                macAddr64 = self.__sendCommand('extaddr')[0]
        print macAddr64

        return int(macAddr64, 16)

get one specific type of MAC address
currently OpenThread only supports Random MAC address

Args:
bType: indicate which kind of MAC address is required

Returns:
specific type of MAC address


def has_ncols(state, incorrect_msg="Your query returned a table with {{n_stu}} column{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} column{{'s' if n_sol > 1 else ''}}."):
    has_result(state)
    n_stu = len(state.student_result)
    n_sol = len(state.solution_result)
    if (n_stu != n_sol):
        _msg = state.build_message(incorrect_msg, fmt_kwargs={'n_stu': n_stu, 'n_sol': n_sol})
        state.do_test(_msg)
    return state

Test whether the student and solution query results have equal numbers of columns.

Args:
incorrect_msg: If specified, this overrides the automatically generated feedback message
in case the number of columns in the student and solution query don't match.

:Example:

Consider the following solution and SCT: ::

# solution
SELECT artist_id as id, name FROM artists

# sct
Ex().has_ncols()

# passing submission
SELECT artist_id as id, name FROM artists

# failing submission (too little columns)
SELECT artist_id as id FROM artists

# passing submission (two columns, even though not correct ones)
SELECT artist_id, label FROM artists


def _ReadStructureFromFileObject(self, file_object, file_offset, data_type_map):
    context = None
    data = b''
    last_data_size = 0
    data_size = data_type_map.GetByteSize()
    if (not data_size):
        data_size = data_type_map.GetSizeHint()
    while (data_size != last_data_size):
        read_offset = (file_offset + last_data_size)
        read_size = (data_size - last_data_size)
        data_segment = self._ReadData(file_object, read_offset, read_size)
        data = b''.join([data, data_segment])
        try:
            context = dtfabric_data_maps.DataTypeMapContext()
            structure_values_object = data_type_map.MapByteStream(data, context=context)
            return (structure_values_object, data_size)
        except dtfabric_errors.ByteStreamTooSmallError:
            pass
        except dtfabric_errors.MappingError as exception:
            raise errors.ParseError('Unable to map {0:s} data at offset: 0x{1:08x} with error: {2!s}'.format(data_type_map.name, file_offset, exception))
        last_data_size = data_size
        data_size = data_type_map.GetSizeHint(context=context)
    raise errors.ParseError('Unable to read {0:s} at offset: 0x{1:08x}'.format(data_type_map.name, file_offset))

Reads a structure from a file-like object.

If the data type map has a fixed size this method will read the predefined
number of bytes from the file-like object. If the data type map has a
variable size, depending on values in the byte stream, this method will
continue to read from the file-like object until the data type map can be
successfully mapped onto the byte stream or until an error occurs.

Args:
file_object (dfvfs.FileIO): a file-like object to parse.
file_offset (int): offset of the structure data relative to the start
of the file-like object.
data_type_map (dtfabric.DataTypeMap): data type map of the structure.

Returns:
tuple[object, int]: structure values object and data size of
the structure.

Raises:
ParseError: if the structure cannot be read.
ValueError: if file-like object or data type map is missing.


def CsvToTable(self, buf, header=True, separator=","):

        self.Reset()

        header_row = self.row_class()
        if header:
            line = buf.readline()
            header_str = ""
            while not header_str:

                header_str = line.split("
                if not header_str:
                    line = buf.readline()

            header_list = header_str.split(separator)
            header_length = len(header_list)

            for entry in header_list:
                entry = entry.strip()
                if entry in header_row:
                    raise TableError("Duplicate header entry %r." % entry)

                header_row[entry] = entry
            header_row.row = 0
            self._table[0] = header_row

        for line in buf:

            if line.startswith("
                continue

            lst = line.split(separator)
            lst = [l.strip() for l in lst]
            if header and len(lst) != header_length:

                continue
            if not header:
                header_row = self.row_class()
                header_length = len(lst)
                header_row.values = dict(
                    zip(range(header_length), range(header_length))
                )
                self._table[0] = header_row
                header = True
                continue

            new_row = self.NewRow()
            new_row.values = lst
            header_row.row = self.size + 1
            self._table.append(new_row)

        return self.size

Parses buffer into tabular format.

Strips off comments (preceded by '#').
Optionally parses and indexes by first line (header).

Args:
buf: String file buffer containing CSV data.
header: Is the first line of buffer a header.
separator: String that CSV is separated by.

Returns:
int, the size of the table created.

Raises:
TableError: A parsing error occurred.


def get_converter_to_specific(self, dataset=None, mass=None, to_unit=None, from_unit=None):
    if (not dataset):
        dataset_number = self._validate_dataset_number(None)
        if (dataset_number is None):
            self._report_empty_dataset()
            return
        dataset = self.datasets[dataset_number]
    if (not mass):
        mass = dataset.mass
    if (not to_unit):
        to_unit_cap = self.cellpy_units['charge']
        to_unit_mass = self.cellpy_units['specific']
        to_unit = (to_unit_cap / to_unit_mass)
    if (not from_unit):
        from_unit_cap = self.raw_units['charge']
        from_unit_mass = self.raw_units['mass']
        from_unit = (from_unit_cap / from_unit_mass)
    return ((from_unit / to_unit) / mass)

get the convertion values

Args:
dataset: DataSet object
mass: mass of electrode (for example active material in mg)
to_unit: (float) unit of input, f.ex. if unit of charge
is mAh and unit of mass is g, then to_unit for charge/mass
will be 0.001 / 1.0 = 0.001
from_unit: float) unit of output, f.ex. if unit of charge
is mAh and unit of mass is g, then to_unit for charge/mass
will be 1.0 / 0.001 = 1000.0

Returns:
multiplier (float) from_unit/to_unit * mass


def GetMetadataAttribute(self, attribute_name):

    table_name = 'metadata'

    has_table = self._database_file.HasTable(table_name)
    if not has_table:
      return None

    column_names = ['value']
    condition = 'name == "{0:s}"'.format(attribute_name)

    values = list(self._database_file.GetValues(
        [table_name], column_names, condition))

    number_of_values = len(values)
    if number_of_values == 0:
      return None

    if number_of_values == 1:
      return values[0]['value']

    raise RuntimeError('More than one value found in database.')

Retrieves the metadata attribute.

Args:
attribute_name (str): name of the metadata attribute.

Returns:
str: the metadata attribute or None.

Raises:
RuntimeError: if more than one value is found in the database.


def __eq__(self, other: 'TensorFluent') -> 'TensorFluent':

        return self._binary_op(self, other, tf.equal, tf.float32)

Returns a TensorFluent for the equal relational operator.

Args:
self: The first operand.
other: The second operand.


def describe_file(module):

    descriptor = FileDescriptor()
    descriptor.package = util.get_package_for_module(module)

    if not descriptor.package:
        descriptor.package = None

    message_descriptors = []
    enum_descriptors = []

    for name in sorted(dir(module)):
        value = getattr(module, name)

        if isinstance(value, type):
            if issubclass(value, messages.Message):
                message_descriptors.append(describe_message(value))

            elif issubclass(value, messages.Enum):
                enum_descriptors.append(describe_enum(value))

    if message_descriptors:
        descriptor.message_types = message_descriptors

    if enum_descriptors:
        descriptor.enum_types = enum_descriptors

    return descriptor

Build a file from a specified Python module.

Args:
module: Python module to describe.

Returns:
Initialized FileDescriptor instance describing the module.


def categorical_partition_data(data):

    series = pd.Series(data)
    value_counts = series.value_counts(dropna=True)

    null_indexes = series.isnull()
    nonnull_count = (null_indexes == False).sum()

    weights = value_counts.values / nonnull_count
    return {
        "values": value_counts.index.tolist(),
        "weights": weights
    }

Convenience method for creating weights from categorical data.

Args:
data (list-like): The data from which to construct the estimate.

Returns:
A new partition object::

{
"partition": (list) The categorical values present in the data
"weights": (list) The weights of the values in the partition.
}


def mix(self, ca, cb, xb):
    r = (((1 - xb) * ca.red) + (xb * cb.red))
    g = (((1 - xb) * ca.green) + (xb * cb.green))
    b = (((1 - xb) * ca.blue) + (xb * cb.blue))
    a = (((1 - xb) * ca.alpha) + (xb * cb.alpha))
    return gdk.RGBA(red=r, green=g, blue=b, alpha=a)

Mix colors.

Args:
ca (gdk.RGBA): first color
cb (gdk.RGBA): second color
xb (float): between 0.0 and 1.0

Return:
gdk.RGBA: linear interpolation between ca and cb,
0 or 1 return the unaltered 1st or 2nd color respectively,
as in CSS.


def has_no_flat_neurites(neuron, tol=0.1, method='ratio'):

    return CheckResult(len(get_flat_neurites(neuron, tol, method)) == 0)

Check that a neuron has no flat neurites

Arguments:
neuron(Neuron): The neuron object to test
tol(float): tolerance
method(string): way of determining flatness, 'tolerance', 'ratio' \
as described in :meth:`neurom.check.morphtree.get_flat_neurites`

Returns:
CheckResult with result


def construct(cls, name, range=None):
    other = Requirement(None)
    other.name_ = name
    other.range_ = (VersionRange() if (range is None) else range)
    return other

Create a requirement directly from an object name and VersionRange.

Args:
name: Object name string.
range: VersionRange object. If None, an unversioned requirement is
created.


def _TestCase(self, shape, indices, scatter_op=state_ops.scatter_add):
    super(ScatterAddSubTest, self).setUp()
    with self.cached_session(use_gpu=False):
        p_init = np.random.rand(*shape).astype('f')
        vals_shape = [len(indices)] + shape[1:]
        vals_init = np.random.rand(*vals_shape).astype('f')
        v_i = [float(x) for x in vals_init.ravel()]
        p = variables.Variable(p_init)
        vals = constant_op.constant(v_i, shape=vals_shape, name='vals')
        ind = constant_op.constant(indices, dtype=dtypes.int32)
        p2 = scatter_op(p, ind, vals, name='updated_p')
        self.evaluate(variables.global_variables_initializer())
        result = self.evaluate(p2)
    for i, ind in enumerate(indices):
        if scatter_op == state_ops.scatter_add:
            p_init.reshape(shape[0], -1)[ind, :] += vals_init.reshape(vals_shape[0], -1)[i, :]
        else:
            p_init.reshape(shape[0], -1)[ind, :] -= vals_init.reshape(vals_shape[0], -1)[i, :]
    self.assertTrue(all((p_init == result).ravel()))

Run a random test case with the given shape and indices.

Args:
shape: Shape of the parameters array.
indices: One-dimensional array of ints, the indices of the last dimension
of the parameters to update.
scatter_op: ScatterAdd or ScatterSub.


def _generic_fit(fqdn, result, scorer, yP=None, *argl, **argd):
    out = None
    if (len(argl) > 0):
        machine = argl[0]
        out = {}
        if hasattr(machine, 'best_score_'):
            out['score'] = machine.best_score_
        yL = _do_auto_predict(*argl[0:2])
        yscore = scorer(fqdn, yL, yP, *argl, **argd)
        if (yscore is not None):
            out.update(yscore)
    return out

Performs the generic fit tests that are common to both classifier and
regressor; uses `scorer` to score the predicted values given by the machine
when tested against its training set.

Args:
scorer (function): called on the result of `machine.predict(Xtrain,
ytrain)`.


def GetTransactionResults(self):
    if (self.References is None):
        return None
    results = []
    realresults = []
    for ref_output in self.References.values():
        results.append(TransactionResult(ref_output.AssetId, ref_output.Value))
    for output in self.outputs:
        results.append(TransactionResult(output.AssetId, (output.Value * Fixed8((- 1)))))
    for (key, group) in groupby(results, (lambda x: x.AssetId)):
        sum = Fixed8(0)
        for item in group:
            sum = (sum + item.Amount)
        if (sum != Fixed8.Zero()):
            realresults.append(TransactionResult(key, sum))
    return realresults

Get the execution results of the transaction.

Returns:
None: if the transaction has no references.
list: of TransactionResult objects.


def predict(self, data, alpha=0.01, max_iter=2000, **kwargs):
    edge_model = GraphLasso(alpha=alpha, max_iter=max_iter)
    edge_model.fit(data.values)
    return nx.relabel_nodes(nx.DiGraph(edge_model.get_precision()), {idx: i for (idx, i) in enumerate(data.columns)})

Predict the graph skeleton.

Args:
data (pandas.DataFrame): observational data
alpha (float): regularization parameter
max_iter (int): maximum number of iterations

Returns:
networkx.Graph: Graph skeleton


def list_insights_components(access_token, subscription_id, resource_group):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', resource_group,
                        '/providers/microsoft.insights/',
                        '/components?api-version=', INSIGHTS_COMPONENTS_API])
    return do_get(endpoint, access_token)

List the Microsoft Insights components in a resource group.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.

Returns:
HTTP response. JSON body of components.


def add_middleware(middleware: EFBMiddleware):

    global middlewares
    if isinstance(middleware, EFBMiddleware):
        middlewares.append(middleware)
    else:
        raise TypeError("Middleware instance is expected")

Register a middleware with the coordinator.

Args:
middleware (EFBMiddleware): Middleware to register


def add_attribute(self, attribute_type, attribute_value):

        if not self.can_update():
            self._tcex.handle_error(910, [self.type])

        return self.tc_requests.add_attribute(
            self.api_type,
            self.api_sub_type,
            self.unique_id,
            attribute_type,
            attribute_value,
            owner=self.owner,
        )

Adds a attribute to a Group/Indicator or Victim

Args:
attribute_type:
attribute_value:

Returns: attribute json


def write_byte(self, value):

        if isinstance(value, bytes):
            self.stream.write(value)
        elif isinstance(value, str):
            self.stream.write(value.encode('utf-8'))
        elif isinstance(value, int):
            self.stream.write(bytes([value]))

Write a single byte to the stream.

Args:
value (bytes, str or int): value to write to the stream.


def CopyTextToLabel(cls, text, prefix=''):

    text = '{0:s}{1:s}'.format(prefix, text)
    return cls._INVALID_LABEL_CHARACTERS_REGEX.sub('_', text)

Copies a string to a label.

A label only supports a limited set of characters therefore
unsupported characters are replaced with an underscore.

Args:
text (str): label text.
prefix (Optional[str]): label prefix.

Returns:
str: label.


def new(self, val):
    if (len(self.things) >= self.max_things):
        raise LimitationError('too many things')
    self.things.add(val)
    return val

Add a new value to me.

Args:
val (LispVal): The value to be added.

Returns:
LispVal: The added value.

Raises:
~parthial.errs.LimitationError: If I already contain the maximum
number of elements.


def create_api_call(func, settings):

    def base_caller(api_call, _, *args):
        'Simply call api_call and ignore settings.'
        return api_call(*args)

    def inner(request, options=None):
        'Invoke with the actual settings.'
        this_options = _merge_options_metadata(options, settings)
        this_settings = settings.merge(this_options)
        if (this_settings.retry and this_settings.retry.retry_codes):
            api_call = gax.retry.retryable(func, this_settings.retry, **this_settings.kwargs)
        else:
            api_call = gax.retry.add_timeout_arg(func, this_settings.timeout, **this_settings.kwargs)
        api_call = _catch_errors(api_call, gax.config.API_ERRORS)
        return api_caller(api_call, this_settings, request)
    if settings.page_descriptor:
        if (settings.bundler and settings.bundle_descriptor):
            raise ValueError('The API call has incompatible settings: bundling and page streaming')
        api_caller = _page_streamable(settings.page_descriptor)
    elif (settings.bundler and settings.bundle_descriptor):
        api_caller = _bundleable(settings.bundle_descriptor)
    else:
        api_caller = base_caller
    return inner

Converts an rpc call into an API call governed by the settings.

In typical usage, ``func`` will be a callable used to make an rpc request.
This will mostly likely be a bound method from a request stub used to make
an rpc call.

The result is created by applying a series of function decorators defined
in this module to ``func``.  ``settings`` is used to determine which
function decorators to apply.

The result is another callable which for most values of ``settings`` has
has the same signature as the original. Only when ``settings`` configures
bundling does the signature change.

Args:
func (Callable[Sequence[object], object]): is used to make a bare rpc
call.
settings (_CallSettings): provides the settings for this call

Returns:
Callable[Sequence[object], object]: a bound method on a request stub used
to make an rpc call

Raises:
ValueError: if ``settings`` has incompatible values, e.g, if bundling
and page_streaming are both configured


def _BuildOobLink(self, param, mode):
    code = self.rpc_helper.GetOobCode(param)
    if code:
        parsed = list(parse.urlparse(self.widget_url))
        query = dict(parse.parse_qsl(parsed[4]))
        query.update({'mode': mode, 'oobCode': code})
        try:
            parsed[4] = parse.urlencode(query)
        except AttributeError:
            parsed[4] = urllib.urlencode(query)
        return (code, parse.urlunparse(parsed))
    raise errors.GitkitClientError('invalid request')

Builds out-of-band URL.

Gitkit API GetOobCode() is called and the returning code is combined
with Gitkit widget URL to building the out-of-band url.

Args:
param: dict of request.
mode: string, Gitkit widget mode to handle the oob action after user
clicks the oob url in the email.

Raises:
GitkitClientError: if oob code is not returned.

Returns:
A string of oob url.


def set_parameter(self, key, value):

        for x in self.transformed_structures:
            x.other_parameters[key] = value

Add parameters to the transmuter. Additional parameters are stored in
the as_dict() output.

Args:
key: The key for the parameter.
value: The value for the parameter.


def compile_initial_state(self, batch_size: Optional[int]=None) -> Sequence[tf.Tensor]:
    with self.graph.as_default():
        with tf.name_scope('initial_state'):
            self._initialize_initial_state_fluents()
            if (batch_size is None):
                return self.initial_state_fluents
            return self._compile_batch_fluents(self.initial_state_fluents, batch_size)

Returns a tuple of tensors representing the initial state fluents.

Args:
batch_size (Optional[int]): The batch size.

Returns:
Sequence[tf.Tensor]: A tuple of tensors.


def __init__(
      self, resolver_context, file_system, path_spec, is_root=False,
      is_virtual=False):

    super(SQLiteBlobFileEntry, self).__init__(
        resolver_context, file_system, path_spec, is_root=is_root,
        is_virtual=is_virtual)
    self._number_of_entries = None

    if is_virtual:
      self.entry_type = definitions.FILE_ENTRY_TYPE_DIRECTORY
    else:
      self.entry_type = definitions.FILE_ENTRY_TYPE_FILE

Initializes a file entry.

Args:
resolver_context (Context): resolver context.
file_system (FileSystem): file system.
path_spec (PathSpec): path specification.
is_root (Optional[bool]): True if the file entry is the root file entry
of the corresponding file system.
is_virtual (Optional[bool]): True if the file entry is a virtual file
entry emulated by the corresponding file system.


def replace_with_json(self, json):
    replacement = self.from_json(json)
    replacement._destructively_move(self)

Overwrite everything in this document with the JSON-encoded
document.

json (JSON-data) :
A JSON-encoded document to overwrite this one.

Returns:
None


def with_redis_cache(self, host: str, port: int, time_to_live: Union[int, timedelta]=DEFAULT_CACHE_ENTRY_TTL_SEC, *, request_coder: Optional[coders.Coder]=None, response_coder: Optional[coders.Coder]=None, **kwargs):
    if has_valid_redis_address(host, port):
        self._cache = RedisCache(host=host, port=port, time_to_live=time_to_live, request_coder=request_coder, response_coder=response_coder, **kwargs)
    return self

Configure the Redis cache to use with enrichment transform.

Args:
host (str): The hostname or IP address of the Redis server.
port (int): The port number of the Redis server.
time_to_live: `(Union[int, timedelta])` The time-to-live (TTL) for
records stored in Redis. Provide an integer (in seconds) or a
`datetime.timedelta` object.
request_coder: (Optional[`coders.Coder`]) coder for requests stored
in Redis.
response_coder: (Optional[`coders.Coder`]) coder for decoding responses
received from Redis.
kwargs: Optional additional keyword arguments that
are required to connect to your redis server. Same as `redis.Redis()`.


def serve(name: str='', port: int=5000) -> None:
    logging.info(' * Listening on port %s', port)
    httpd = HTTPServer((name, port), RequestHandler)
    httpd.serve_forever()

A basic way to serve the methods.

Args:
name: Server address.
port: Server port.


def get_players(self, team):
    team_id = self.__get_team_id(team)
    self.logger.debug(f'Getting players of team {team_id}.')
    return self._request('teams', team_id, 'players')

Loads the players of a team.

Args:
* team (:obj: json): a team in json format obtained from the service.

Returns:
* :obj: json: the players of the team


def derivative(self, rate):

        rate = self._validate_number_sequence(rate, 3)
        return 0.5 * self * Quaternion(vector=rate)

Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate`

Params:
rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively.

Returns:
A unit quaternion describing the rotation rate


def _profile_table(self, batch_id):

        message = self._execute_command(batch_id, "RAY.TABLE_LOOKUP",
                                        ray.gcs_utils.TablePrefix.PROFILE, "",
                                        batch_id.binary())

        if message is None:
            return []

        gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(
            message, 0)

        profile_events = []
        for i in range(gcs_entries.EntriesLength()):
            profile_table_message = (
                ray.gcs_utils.ProfileTableData.GetRootAsProfileTableData(
                    gcs_entries.Entries(i), 0))

            component_type = decode(profile_table_message.ComponentType())
            component_id = binary_to_hex(profile_table_message.ComponentId())
            node_ip_address = decode(
                profile_table_message.NodeIpAddress(), allow_none=True)

            for j in range(profile_table_message.ProfileEventsLength()):
                profile_event_message = profile_table_message.ProfileEvents(j)

                profile_event = {
                    "event_type": decode(profile_event_message.EventType()),
                    "component_id": component_id,
                    "node_ip_address": node_ip_address,
                    "component_type": component_type,
                    "start_time": profile_event_message.StartTime(),
                    "end_time": profile_event_message.EndTime(),
                    "extra_data": json.loads(
                        decode(profile_event_message.ExtraData())),
                }

                profile_events.append(profile_event)

        return profile_events

Get the profile events for a given batch of profile events.

Args:
batch_id: An identifier for a batch of profile events.

Returns:
A list of the profile events for the specified batch.


def build(self, var_list):
    if self.built:
        return
    super().build(var_list)
    self._momentums = self.add_optimizer_variables(var_list, 'momentum')

Initialize optimizer variables.

Lion optimizer has one variable `momentums`.

Args:
var_list: list of model variables to build Lion variables on.


def _RegisterDebuggee(self, service):
    try:
        request = {'debuggee': self._GetDebuggee()}
        try:
            response = service.debuggees().register(body=request).execute()
            project_number = response['debuggee'].get('project')
            self._project_number = (project_number or self._project_number)
            self._debuggee_id = response['debuggee']['id']
            native.LogInfo(('Debuggee registered successfully, ID: %s' % self._debuggee_id))
            self.register_backoff.Succeeded()
            return (False, 0)
        except BaseException:
            native.LogInfo(('Failed to register debuggee: %s, %s' % (request, traceback.format_exc())))
    except BaseException:
        native.LogWarning(('Debuggee information not available: ' + traceback.format_exc()))
    return (True, self.register_backoff.Failed())

Single attempt to register the debuggee.

If the registration succeeds, sets self._debuggee_id to the registered
debuggee ID.

Args:
service: client to use for API calls

Returns:
(registration_required, delay) tuple


def clone(self, uuid):
    request_url = (self._client.base_api_url + self.clone_url.format(id=uuid))
    response = self._client.session.post(request_url)
    self.validate_request_success(response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_201_CREATED)
    return self.response_data_to_model_instance(response.json())

Clone the task instance with given UUID.

Args:
uuid (str): The UUID of the task instance to clone.

Returns:
:class:`saltant.models.base_task_instance.BaseTaskInstance`:
A task instance model instance representing the task
instance created due to the clone.


def close_children_tasks(self, parent_task_name):

        if parent_task_name not in self.tasks:
            return

        while self.tasks:
            next_task = reversed(self.tasks.keys()).next()
            if next_task == parent_task_name:
                break
            del self.tasks[next_task]

Closes all the children tasks that were open

Args:
parent_task_name (str): Name of the parent task

Returns:
None


def get_config_path(module_id: str = None, ext: str = 'yaml') -> Path:

    if module_id:
        config_path = get_data_path(module_id)
    else:
        profile = coordinator.profile
        config_path = get_base_path() / 'profiles' / profile
    if not config_path.exists():
        config_path.mkdir(parents=True)
    return config_path / "config.{}".format(ext)

Get path for configuration file. Defaulted to
``~/.ehforwarderbot/profiles/profile_name/channel_id/config.yaml``.

This method creates the queried path if not existing. The config file will
not be created, however.

Args:
module_id (str): Module ID.
ext (Optional[Str]): Extension name of the config file.
Defaulted to ``"yaml"``.

Returns:
The path to the configuration file.


def tsqr(a):
    if (len(a.shape) != 2):
        raise Exception('tsqr requires len(a.shape) == 2, but a.shape is {}'.format(a.shape))
    if (a.num_blocks[1] != 1):
        raise Exception('tsqr requires a.num_blocks[1] == 1, but a.num_blocks is {}'.format(a.num_blocks))
    num_blocks = a.num_blocks[0]
    K = (int(np.ceil(np.log2(num_blocks))) + 1)
    q_tree = np.empty((num_blocks, K), dtype=object)
    current_rs = []
    for i in range(num_blocks):
        block = a.objectids[(i, 0)]
        (q, r) = ra.linalg.qr.remote(block)
        q_tree[(i, 0)] = q
        current_rs.append(r)
    for j in range(1, K):
        new_rs = []
        for i in range(int(np.ceil(((1.0 * len(current_rs)) / 2)))):
            stacked_rs = ra.vstack.remote(*current_rs[(2 * i):((2 * i) + 2)])
            (q, r) = ra.linalg.qr.remote(stacked_rs)
            q_tree[(i, j)] = q
            new_rs.append(r)
        current_rs = new_rs
    assert (len(current_rs) == 1), ('len(current_rs) = ' + str(len(current_rs)))
    if (a.shape[0] >= a.shape[1]):
        q_shape = a.shape
    else:
        q_shape = [a.shape[0], a.shape[0]]
    q_num_blocks = core.DistArray.compute_num_blocks(q_shape)
    q_objectids = np.empty(q_num_blocks, dtype=object)
    q_result = core.DistArray(q_shape, q_objectids)
    for i in range(num_blocks):
        q_block_current = q_tree[(i, 0)]
        ith_index = i
        for j in range(1, K):
            if (np.mod(ith_index, 2) == 0):
                lower = [0, 0]
                upper = [a.shape[1], core.BLOCK_SIZE]
            else:
                lower = [a.shape[1], 0]
                upper = [(2 * a.shape[1]), core.BLOCK_SIZE]
            ith_index
            q_block_current = ra.dot.remote(q_block_current, ra.subarray.remote(q_tree[(ith_index, j)], lower, upper))
        q_result.objectids[i] = q_block_current
    r = current_rs[0]
    return (q_result, ray.get(r))

Perform a QR decomposition of a tall-skinny matrix.

Args:
a: A distributed matrix with shape MxN (suppose K = min(M, N)).

Returns:
A tuple of q (a DistArray) and r (a numpy array) satisfying the
following.
- If q_full = ray.get(DistArray, q).assemble(), then
q_full.shape == (M, K).
- np.allclose(np.dot(q_full.T, q_full), np.eye(K)) == True.
- If r_val = ray.get(np.ndarray, r), then r_val.shape == (K, N).
- np.allclose(r, np.triu(r)) == True.


def __init__(self, band_type=None, rate=None, burst_size=None):

        super().__init__()
        self.band_type = band_type
        self.rate = rate
        self.burst_size = burst_size
        self.update_length()

Create a MeterBandHeader with the optional parameters below.

Args:
band_type (MeterBandType): One of OFPMBT_*.
rate (int): Rate for this band.
burst_size (int): Size of bursts.


def step(self, action):
    (observ, reward, done, info) = self._env.step(action)
    observ = self._convert_observ(observ)
    reward = self._convert_reward(reward)
    return (observ, reward, done, info)

Forward action to the wrapped environment.

Args:
action: Action to apply to the environment.

Raises:
ValueError: Invalid action.

Returns:
Converted observation, converted reward, done flag, and info object.


def add_outputs(self, **kwargs):
    self._closed()
    for (name, source_name) in kwargs.items():
        obj = {}
        obj['outputSource'] = source_name
        obj['type'] = self.step_output_types[source_name]
        self.wf_outputs[name] = obj

Add workflow outputs.

The output type is added automatically, based on the steps in the steps
library.

Args:
kwargs (dict): A dict containing ``name=source name`` pairs.
``name`` is the name of the workflow output (e.g.,
``txt_files``) and source name is the name of the step that
produced this output plus the output name (e.g.,
``saf-to-txt/out_files``).


def build_circle_dict(self, center_lat, center_lng, radius, stroke_color='
    circle = {'stroke_color': stroke_color, 'stroke_opacity': stroke_opacity, 'stroke_weight': stroke_weight, 'fill_color': fill_color, 'fill_opacity': fill_opacity, 'center': {'lat': center_lat, 'lng': center_lng}, 'radius': radius}
    return circle

Set a dictionary with the javascript class Circle parameters

This function sets a default drawing configuration if the user just
pass the rectangle bounds, but also allows to set each parameter
individually if the user wish so.

Args:
center_lat (float): The circle center latitude
center_lng (float): The circle center longitude
radius  (float): The circle radius, in meters
stroke_color (str): Sets the color of the rectangle border using
hexadecimal color notation
stroke_opacity (float): Sets the opacity of the rectangle border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels.
fill_color (str): Sets the color of the circle fill using
hexadecimal color notation
fill_opacity (float): Sets the opacity of the circle fill


def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
    super(Digest, self).read(istream, kmip_version=kmip_version)
    tstream = BytearrayStream(istream.read(self.length))
    self.hashing_algorithm.read(tstream, kmip_version=kmip_version)
    self.digest_value.read(tstream, kmip_version=kmip_version)
    self.key_format_type.read(tstream, kmip_version=kmip_version)
    self.is_oversized(tstream)
    self.validate()

Read the data encoding the Digest object and decode it into its
constituent parts.

Args:
istream (Stream): A data stream containing encoded object data,
supporting a read method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.


def set_schema_location(self, ns_uri, schema_location, replace=False):
    ni = self.__lookup_uri(ns_uri)
    if (ni.schema_location == schema_location):
        return
    elif (replace or (ni.schema_location is None)):
        ni.schema_location = schema_location
    elif (schema_location is None):
        ni.schema_location = None
    else:
        raise ConflictingSchemaLocationError(ns_uri, ni.schema_location, schema_location)

Sets the schema location of the given namespace.

If ``replace`` is ``True``, then any existing schema location is
replaced.  Otherwise, if the schema location is already set to a
different value, an exception is raised.  If the schema location is set
to None, it is effectively erased from this set (this is not considered
"replacement".)

Args:
ns_uri (str): The namespace whose schema location is to be set
schema_location (str): The schema location URI to set, or None
replace (bool): Whether to replace any existing schema location

Raises:
NamespaceNotFoundError: If the given namespace isn't in this set.
ConflictingSchemaLocationError: If replace is False,
schema_location is not None, and the namespace already has a
different schema location in this set.


def is_valid(self, value):

        if not self.is_array:
            return self._valid(value)

        if isinstance(value, (list, set, tuple)):
            return all([self._valid(item) for item in value])

        return self._valid(value)

Validate value before actual instance setting based on type.

Args:
value (object): The value object for validation.

Returns:
True if value validation succeeds else False.


def CompileReport(self, mediator):

    lines_of_text = ['Listing file paths and hashes']
    for pathspec, hashes in sorted(
        self._paths_with_hashes.items(),
        key=lambda tuple: tuple[0].comparable):

      path_string = self._GeneratePathString(mediator, pathspec, hashes)
      lines_of_text.append(path_string)

    lines_of_text.append('')
    report_text = '\n'.join(lines_of_text)
    return reports.AnalysisReport(plugin_name=self.NAME, text=report_text)

Compiles an analysis report.

Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.

Returns:
AnalysisReport: report.


def get_summed_cohp_by_label_and_orbital_list(self, label_list, orbital_list, divisor=1):

        first_cohpobject = self.get_orbital_resolved_cohp(label_list[0], orbital_list[0])
        summed_cohp = first_cohpobject.cohp.copy()
        summed_icohp = first_cohpobject.icohp.copy()
        for ilabel, label in enumerate(label_list[1:], 1):
            cohp_here = self.get_orbital_resolved_cohp(label, orbital_list[ilabel])
            summed_cohp[Spin.up] = np.sum([summed_cohp[Spin.up], cohp_here.cohp.copy()[Spin.up]], axis=0)
            if Spin.down in summed_cohp:
                summed_cohp[Spin.down] = np.sum([summed_cohp[Spin.down], cohp_here.cohp.copy()[Spin.down]], axis=0)
            summed_icohp[Spin.up] = np.sum([summed_icohp[Spin.up], cohp_here.icohp.copy()[Spin.up]], axis=0)
            if Spin.down in summed_icohp:
                summed_icohp[Spin.down] = np.sum([summed_icohp[Spin.down], cohp_here.icohp.copy()[Spin.down]], axis=0)

        divided_cohp = {}
        divided_icohp = {}
        divided_cohp[Spin.up] = np.divide(summed_cohp[Spin.up], divisor)
        divided_icohp[Spin.up] = np.divide(summed_icohp[Spin.up], divisor)
        if Spin.down in summed_cohp:
            divided_cohp[Spin.down] = np.divide(summed_cohp[Spin.down], divisor)
            divided_icohp[Spin.down] = np.divide(summed_icohp[Spin.down], divisor)

        return Cohp(efermi=first_cohpobject.efermi, energies=first_cohpobject.energies, cohp=divided_cohp,
                    are_coops=first_cohpobject.are_coops,
                    icohp=divided_icohp)

Returns a COHP object that includes a summed COHP divided by divisor

Args:
label_list: list of labels for the COHP that should be included in the summed cohp
orbital_list: list of orbitals for the COHPs that should be included in the summed cohp (same order as label_list)
divisor: float/int, the summed cohp will be divided by this divisor
Returns:
Returns a COHP object including a summed COHP


def _extract_response_chunks(self, all_responses, response_chunks, api_name):
    for response_chunk in response_chunks:
        if (not isinstance(response_chunk, list)):
            response_chunk = [response_chunk]
        for response in response_chunk:
            if (not response):
                continue
            if self._cache:
                self._cache.cache_value(api_name, response['resource'], response)
            all_responses[response['resource']] = response

Extracts and caches the responses from the response chunks in case
of the responses for the requests containing multiple concatenated
resources. Extracted responses are added to the already cached
responses passed in the all_responses parameter.

Args:
all_responses: a list containing already cached responses.
response_chunks: a list with response chunks.
api_name: a string name of the API.


def _lift_unlifted_variables(graph, variable_holder):
    with graph.as_default():
        global_collection_variables = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
        local_collection_variables = ops.get_collection(ops.GraphKeys.LOCAL_VARIABLES)
        existing_captures = {id(c) for c in graph.internal_captures}
        lifted_variables = {}

        def _should_lift_variable(v):
            return (v._in_graph_mode and v.graph.building_function) and isinstance(v, resource_variable_ops.BaseResourceVariable) and (id(v.handle) not in existing_captures)
        for old_variable in global_collection_variables:
            if _should_lift_variable(old_variable):
                new_variable = _lift_single_variable(old_variable, graph, variable_holder)
                lifted_variables[id(old_variable)] = new_variable
                existing_captures.add(id(old_variable.handle))
        for old_variable in local_collection_variables:
            if _should_lift_variable(old_variable):
                new_variable = _lift_single_variable(old_variable, graph, variable_holder)
                lifted_variables[id(old_variable)] = new_variable
                existing_captures.add(id(old_variable.handle))
                if new_variable._in_graph_mode:
                    outer_graph = new_variable.graph
                    global_collection = outer_graph.get_collection_ref(ops.GraphKeys.GLOBAL_VARIABLES)
                    global_collection.remove(new_variable)
                    outer_graph.add_to_collection(ops.GraphKeys.LOCAL_VARIABLES, new_variable)
        for collection_name in [ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.LOCAL_VARIABLES]:
            mutable_collection = ops.get_collection_ref(collection_name)
            for index, current in enumerate(mutable_collection):
                mutable_collection[index] = lifted_variables.get(id(current), current)
                if not resource_variable_ops.is_resource_variable(mutable_collection[index]):
                    logging.log_first_n(logging.WARN, 'Unable to create a python object for variable {} because it is a reference variable. It may not be visible to training APIs. If this is a problem, consider rebuilding the SavedModel after running tf.compat.v1.enable_resource_variables().'.format(mutable_collection[index]), 5)

Finds resource variables and lifts them into the outer context.

When we import a GraphDef inside a wrap_function, no Python graph building
code runs. This means we get VarHandleOps which create variable resources,
but no corresponding Python objects. Leaving them like this works but gives
the user no way to interact with or modify the variables outside the graph.

This method searches for variables and lifts them out as regular variable
objects when possible, indicating to the FuncGraph that they are captures.

Args:
graph: The FuncGraph to lift variables from.
variable_holder: A VariableHolder to record the lifted variables in.


def list(cls, session, endpoint_override=None, data=None):
    cls._check_implements('list')
    return cls((endpoint_override or ('/%s.json' % cls.__endpoint__)), data=data, session=session)

Return records in a mailbox.

Args:
session (requests.sessions.Session): Authenticated session.
endpoint_override (str, optional): Override the default
endpoint using this.
data (dict, optional): Data to provide as request parameters.

Returns:
RequestPaginator(output_type=helpscout.BaseModel): Results
iterator.


def van(first_enc,
        first_frame,
        current_enc,
        gt_image,
        reuse=False,
        scope_prefix='',
        hparams=None):

  with tf.variable_scope(scope_prefix + 'van', reuse=reuse):
    output_shape = first_frame.get_shape().as_list()
    output_shape[0] = -1

    first_depth = 64

    f_first_enc, _ = van_enc_2d(first_enc, first_depth)
    f_first_frame, image_enc_history = van_image_enc_2d(
        first_frame, first_depth, hparams=hparams)
    f_current_enc, van_higher_level = van_enc_2d(
        current_enc, first_depth, reuse=True)
    f_gt_image, _ = van_image_enc_2d(gt_image, first_depth, True,
                                     hparams=hparams)

    analogy_t = analogy_computation_2d(
        f_first_enc, f_first_frame, f_current_enc, first_depth)
    enc_img = f_current_enc + analogy_t

    img = van_dec_2d(
        enc_img, image_enc_history, output_shape, first_depth, hparams=hparams)

    batch_size = tf.to_float(tf.shape(first_enc)[0])
    r_loss = tf.nn.l2_loss(f_gt_image - f_current_enc - analogy_t) / batch_size

    return img, r_loss, van_higher_level

Implements a VAN.

Args:
first_enc: The first encoding.
first_frame: The first ground truth frame.
current_enc: The encoding of the frame to generate.
gt_image: The ground truth image, only used for regularization.
reuse: To reuse in variable scope or not.
scope_prefix: The prefix before the scope name.
hparams: The python hparams.

Returns:
The generated image.


def _einsum_equation(input_shapes, output_shape):
    ret = []
    next_letter = ord('a')
    dim_to_letter = {}
    for (shape_num, shape) in enumerate((input_shapes + [output_shape])):
        if (shape_num == len(input_shapes)):
            ret.append('->')
        elif (shape_num > 0):
            ret.append(',')
        for d in shape.dims:
            if (d not in dim_to_letter):
                dim_to_letter[d] = chr(next_letter)
                next_letter += 1
            ret.append(dim_to_letter[d])
    return ''.join(ret)

Turn shapes into an einsum equation.

e.g. "ij,jk->ik"

Args:
input_shapes: a list of Shapes
output_shape: a Shape
Returns:
a string


def parse(cls, args):

        try:
            (options, args) = cls.optparser.parse_args(args)
            if options.mode not in ["1", "2"]:
                raise ParseError("mode must be either '1' or '2'",
                                 cls.optparser.format_help())

            if (options.dbtap_id is None) or (options.db_table is None):
                raise ParseError("dbtap_id and db_table are required",
                                 cls.optparser.format_help())

        except OptionParsingError as e:
            raise ParseError(e.msg, cls.optparser.format_help())
        except OptionParsingExit as e:
            return None

        v = vars(options)
        v["command_type"] = "DbImportCommand"
        return v

Parse command line arguments to construct a dictionary of command
parameters that can be used to create a command

Args:
`args`: sequence of arguments

Returns:
Dictionary that can be used in create method

Raises:
ParseError: when the arguments are not correct


def bazel_command(self, subcommand: str='test', extra_options: Tuple[str, ...]=()) -> List[str]:
    options = _dict_to_cli_options(self.options)
    configs = [f'--config={config}' for config in self.configs]
    build_tag_filters = f'--build_tag_filters={','.join(self.build_tag_filters)}'
    test_tag_filters = f'--test_tag_filters={','.join(self.test_tag_filters)}'
    action_env = [f'--action_env={k}={v}' for k, v in self.action_env.items()]
    test_env = [f'--test_env={k}={v}' for k, v in self.test_env.items()]
    repo_env = [f'--repo_env={k}={v}' for k, v in self.repo_env.items()]
    override_repository = [f'--override_repository={k}={v}' for k, v in self.override_repository.items()]
    tag_filters = [build_tag_filters, test_tag_filters]
    all_options = tag_filters + configs + action_env + test_env + repo_env + override_repository + options + list(extra_options)
    return ['bazel', subcommand, *all_options, '--', *self.target_patterns]

Returns a bazel test command for this build.

Args:
subcommand: The subcommand to give to bazel. `test` by default.
extra_options: Extra options. For now just used to pass in `--nobuild`.

Returns: List of command line arguments


def _get_kind_name(item):
    if isinstance(item, (str, bytes)):
        kind = 'bytes_list'
    elif isinstance(item, int):
        kind = 'int64_list'
    elif isinstance(item, float):
        kind = 'float_list'
    elif isinstance(item, Any):
        kind = 'any_list'
    else:
        kind = 'node_list'
    return kind

Returns the kind name in CollectionDef.

Args:
item: A data item.

Returns:
The string representation of the kind in CollectionDef.


def data_period_end_day(self, value=None):
    if (value is not None):
        try:
            value = str(value)
        except ValueError:
            raise ValueError('value {} need to be of type str for field `data_period_end_day`'.format(value))
        if (',' in value):
            raise ValueError('value should not contain a comma for field `data_period_end_day`')
    self._data_period_end_day = value

Corresponds to IDD Field `data_period_end_day`

Args:
value (str): value for IDD Field `data_period_end_day`
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 _get_encoding(dom, default="utf-8"):

    encoding = dom.find("meta", {"http-equiv": "Content-Type"})

    if not encoding:
        return default

    encoding = encoding[0].params.get("content", None)

    if not encoding:
        return default

    return encoding.lower().split("=")[-1]

Try to look for meta tag in given `dom`.

Args:
dom (obj): pyDHTMLParser dom of HTML elements.
default (default "utr-8"): What to use if encoding is not found in
`dom`.

Returns:
str/default: Given encoding or `default` parameter if not found.


def _with_num_row_partitions(self, num_row_partitions):
    rank = self.rank
    if rank is None:
        raise ValueError('Rank must be known to adjust num_row_partitions')
    if not isinstance(num_row_partitions, int):
        raise ValueError('num_row_partitions must be an int')
    if num_row_partitions < 0:
        raise ValueError('num_row_partitions must be nonnegative')
    if num_row_partitions == self.num_row_partitions:
        return self
    if num_row_partitions >= rank:
        raise ValueError('num_row_partitions must be less than rank')
    if num_row_partitions > self.num_row_partitions:
        num_row_partitions_diff = num_row_partitions - self.num_row_partitions
        new_inner_rank = self.rank - num_row_partitions
        nvals = self._inner_shape_dim(0)
        more_rp = []
        for i in range(num_row_partitions_diff):
            nrows = nvals
            row_length = self._inner_shape_dim(i + 1)
            nvals = nrows * row_length
            rp = RowPartition.from_uniform_row_length(row_length, nrows=nrows, dtype=self.dtype)
            more_rp.append(rp)
        alt_inner = self._alt_inner_shape(new_inner_rank)
        return DynamicRaggedShape(list(self.row_partitions) + more_rp, alt_inner)
    else:
        assert num_row_partitions < self.num_row_partitions
        return DynamicRaggedShape(self.row_partitions[:num_row_partitions], self._alt_inner_shape(self.rank - num_row_partitions))

Creates an identical shape with the given num_row_partitions.

Note that the shape must be statically refactorable to this rank.
In particular:
* rank must be known.
* num_row_partitions must be a nonnegative int.
* num_row_partitions must be less than the rank of the shape
* num_row_partitions must be greater or equal to the index of any ragged
dimension.

Note that if the num_row_partitions is the same, self is returned.

Args:
num_row_partitions: the target num_row_partitions (must be a nonnegative
int).

Returns:
a shape with a (possibly) different num_row_partitions.

Raises:
ValueError: if the rank is unknown, the argument is not a nonnegative int,
or there is a dimension that is nonuniform.


def RegisterDefinition(self, data_type_definition):
    name_lower = data_type_definition.name.lower()
    if (name_lower in self._definitions):
        raise KeyError('Definition already set for name: {0:s}.'.format(data_type_definition.name))
    if (data_type_definition.name in self._aliases):
        raise KeyError('Alias already set for name: {0:s}.'.format(data_type_definition.name))
    for alias in data_type_definition.aliases:
        if (alias in self._aliases):
            raise KeyError('Alias already set for name: {0:s}.'.format(alias))
    self._definitions[name_lower] = data_type_definition
    for alias in data_type_definition.aliases:
        self._aliases[alias] = name_lower
    if (data_type_definition.TYPE_INDICATOR == definitions.TYPE_INDICATOR_FORMAT):
        self._format_definitions.append(name_lower)

Registers a data type definition.

The data type definitions are identified based on their lower case name.

Args:
data_type_definition (DataTypeDefinition): data type definitions.

Raises:
KeyError: if data type definition is already set for the corresponding
name.


def pluralize(singular):

    if singular in UNCOUNTABLES:
        return singular
    for i in IRREGULAR:
        if i[0] == singular:
            return i[1]
    for i in PLURALIZE_PATTERNS:
        if re.search(i[0], singular):
            return re.sub(i[0], i[1], singular)

Convert singular word to its plural form.

Args:
singular: A word in its singular form.

Returns:
The word in its plural form.


def create_services(self, compose_str: str) -> list:
    if (not self._manager):
        raise RuntimeError('Services can only be run on swarm manager nodes')
    services_ids = []
    try:
        service_config = yaml.load(compose_str)
        service_list = copy.deepcopy(service_config)
        service_config.pop('version')
        service_config.pop('services')
        for service_name in service_list['services']:
            service_exist = self._client.services.list(filters={'name': service_name})
            if (not service_exist):
                service_config['name'] = service_name
                service_spec = self._parse_services(service_config, service_name, service_list)
                created_service = self._client.services.create(**service_spec)
                service_id = created_service.short_id
                LOG.debug('Service created: %s', service_id)
                services_ids.append(service_id)
            else:
                LOG.debug('Services already exists')
    except yaml.YAMLError as exc:
        print(exc)
    return services_ids

Create new docker services.

Args:
compose_str (string): Docker compose 'file' string

Return:
service_names, list


def text_filepaths_for_task(self, tmp_dir, task_id):

    assert task_id >= 0
    assert task_id < self.num_train_shards + self.num_dev_shards
    if task_id < self.num_train_shards:
      return [
          f for i, f in enumerate(self.train_text_filepaths(tmp_dir))
          if i % self.num_train_shards == task_id
      ]
    else:
      return [
          f for i, f in enumerate(self.dev_text_filepaths(tmp_dir))
          if i % self.num_dev_shards == task_id - self.num_train_shards
      ]

List of input filepaths for a particular training or dev shard.

Args:
tmp_dir: a string
task_id: an integer less than self.num_shards
Returns:
a list of tuples (filepath, start_pos, num_bytes)


def disqualified(self, num, natural=True, **kwargs):

        search_type = 'natural' if natural else 'corporate'
        baseuri = (self._BASE_URI +
                   'disqualified-officers/{}/{}'.format(search_type, num))
        res = self.session.get(baseuri, params=kwargs)
        self.handle_http_error(res)
        return res

Search for disqualified officers by officer ID.

Searches for natural disqualifications by default. Specify
natural=False to search for corporate disqualifications.

Args:
num (str): Company number to search on.
natural (Optional[bool]): Natural or corporate search
kwargs (dict): additional keywords passed into
requests.session.get *params* keyword.


def global_idx_to_numeric_idx(self, axis, indices):

        assert axis in ["row", "col", "columns"]
        if axis == "row":
            return pandas.Index(
                pandas.Series(np.arange(len(self.index)), index=self.index)
                .loc[indices]
                .values
            )
        elif axis in ["col", "columns"]:
            return pandas.Index(
                pandas.Series(np.arange(len(self.columns)), index=self.columns)
                .loc[indices]
                .values
            )

Note: this function involves making copies of the index in memory.

Args:
axis: Axis to extract indices.
indices: Indices to convert to numerical.

Returns:
An Index object.


def _get_deprecated_positional_arguments(names_to_ok_vals, arg_spec):
    arg_space = arg_spec.args + arg_spec.kwonlyargs
    arg_name_to_pos = {name: pos for pos, name in enumerate(arg_space)}
    deprecated_positional_args = {}
    for arg_name, spec in iter(names_to_ok_vals.items()):
        if arg_name in arg_name_to_pos:
            pos = arg_name_to_pos[arg_name]
            deprecated_positional_args[arg_name] = DeprecatedArgSpec(pos, spec.has_ok_value, spec.ok_value)
    return deprecated_positional_args

Builds a dictionary from deprecated arguments to their spec.

Returned dict is keyed by argument name.
Each value is a DeprecatedArgSpec with the following fields:
position: The zero-based argument position of the argument
within the signature.  None if the argument isn't found in
the signature.
ok_values:  Values of this argument for which warning will be
suppressed.

Args:
names_to_ok_vals: dict from string arg_name to a list of values, possibly
empty, which should not elicit a warning.
arg_spec: Output from tf_inspect.getfullargspec on the called function.

Returns:
Dictionary from arg_name to DeprecatedArgSpec.


def ExpectingFunctionArgs(clean_lines, linenum):

  line = clean_lines.elided[linenum]
  return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
          (linenum >= 2 and
           (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
                  clean_lines.elided[linenum - 1]) or
            Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
                  clean_lines.elided[linenum - 2]) or
            Search(r'\bstd::m?function\s*\<\s*$',
                   clean_lines.elided[linenum - 1]))))

Checks whether where function type arguments are expected.

Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.

Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types.


def parse_variables_mapping(variables_mapping, ignore=False):
    run_times = 0
    parsed_variables_mapping = {}
    while (len(parsed_variables_mapping) != len(variables_mapping)):
        for var_name in variables_mapping:
            run_times += 1
            if (run_times > (len(variables_mapping) * 4)):
                not_found_variables = {key: variables_mapping[key] for key in variables_mapping if (key not in parsed_variables_mapping)}
                raise exceptions.VariableNotFound(not_found_variables)
            if (var_name in parsed_variables_mapping):
                continue
            value = variables_mapping[var_name]
            variables = extract_variables(value)
            if (var_name in variables):
                if ignore:
                    parsed_variables_mapping[var_name] = value
                    continue
                raise exceptions.VariableNotFound(var_name)
            if variables:
                if any([(_var_name not in parsed_variables_mapping) for _var_name in variables]):
                    continue
            parsed_value = parse_lazy_data(value, parsed_variables_mapping)
            parsed_variables_mapping[var_name] = parsed_value
    return parsed_variables_mapping

eval each prepared variable and function in variables_mapping.

Args:
variables_mapping (dict):
{
"varA": LazyString(123$varB),
"varB": LazyString(456$varC),
"varC": LazyString(${sum_two($a, $b)}),
"a": 1,
"b": 2,
"c": {"key": LazyString($b)},
"d": [LazyString($a), 3]
}
ignore (bool): If set True, VariableNotFound will be ignored.
This is used when initializing tests.

Returns:
dict: parsed variables_mapping should not contain any variable or function.
{
"varA": "1234563",
"varB": "4563",
"varC": "3",
"a": 1,
"b": 2,
"c": {"key": 2},
"d": [1, 3]
}


def read_config_info(ini_file):
    try:
        config = RawConfigParser()
        config.optionxform = (lambda option: option)
        config.read(ini_file)
        the_stuff = {}
        for section in config.sections():
            the_stuff[section] = {}
            for option in config.options(section):
                the_stuff[section][option] = config.get(section, option)
        return the_stuff
    except Exception as wtf:
        logging.error('Exception caught in read_config_info(): {}'.format(wtf))
        traceback.print_exc(file=sys.stdout)
        return sys.exit(1)

Read the INI file

Args:
ini_file - path to the file

Returns:
A dictionary of stuff from the INI file

Exits:
1 - if problems are encountered


def events(self):
    if (not self.__events):
        self.__events = Events(self.__connection)
    return self.__events

Gets the Events API client.

Returns:
Events:


def __call__(self, fn):

        if isinstance(fn, Response):
            return fn.mock
        if isinstance(fn, Mock):
            return fn

        if not isfunction(fn) and not ismethod(fn):
            raise TypeError('first argument must be a method or function')

        self._engine.remove_mock(self)

        @functools.wraps(fn)
        def decorator(*args, **kw):

            self._engine.add_mock(self)

            engine_active = self._engine.active
            if not engine_active:
                self._engine.activate()

            try:
                return fn(*args, **kw)
            finally:

                self._engine.remove_mock(self)

                if not engine_active:
                    self._engine.disable()

        return decorator

Overload Mock instance as callable object in order to be used
as decorator definition syntax.

Arguments:
fn (function): function to decorate.

Returns:
function or pook.Mock


def as_fn(self, *binding_order):
    if (len(binding_order) != len(self.unbound_vars)):
        raise ValueError('All vars must be specified.')
    for arg in binding_order:
        if (arg not in self.unbound_vars):
            raise ValueError(('Unknown binding: %s' % arg))

    def func(*args, **kwargs):
        'Constructs a template.'
        if (len(binding_order) != len(args)):
            raise ValueError(('Missing values, expects: %s' % binding_order))
        values = dict(zip(binding_order, args))
        values.update(kwargs)
        return self.construct(**values)
    func.__doc__ = _gen_ipython_string(func, binding_order, [], func.__doc__)
    return func

Creates a function by binding the arguments in the given order.

Args:
*binding_order: The unbound variables. This must include all values.
Returns:
A function that takes the arguments of binding_order.
Raises:
ValueError: If the bindings are missing values or include unknown values.


def noisy_moments(self, moments: 'Iterable[cirq.Moment]',
                      system_qubits: Sequence['cirq.Qid']
                     ) -> Sequence['cirq.OP_TREE']:

        if not hasattr(self.noisy_moment, '_not_overridden'):
            result = []
            for moment in moments:
                result.append(self.noisy_moment(moment, system_qubits))
            return result

        if not hasattr(self.noisy_operation, '_not_overridden'):
            result = []
            for moment in moments:
                result.append([self.noisy_operation(op) for op in moment])
            return result

        assert False, 'Should be unreachable.'

Adds possibly stateful noise to a series of moments.

Args:
moments: The moments to add noise to.
system_qubits: A list of all qubits in the system.

Returns:
A sequence of OP_TREEs, with the k'th tree corresponding to the
noisy operations for the k'th moment.


def parseString(inString, silence=False):

    parser = None
    rootNode= parsexmlstring_(inString, parser)
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'PcGts'
        rootClass = PcGts
    rootObj = rootClass.factory()
    rootObj.build(rootNode)

    if not silence:
        sys.stdout.write('<?xml version="1.0" ?>\n')
        rootObj.export(
            sys.stdout, 0, name_=rootTag,
            namespacedef_='xmlns:pc="http:
    return rootObj

Parse a string, create the object tree, and export it.

Arguments:
- inString -- A string.  This XML fragment should not start
with an XML declaration containing an encoding.
- silence -- A boolean.  If False, export the object.
Returns -- The root object in the tree.


def strace_clear_all(self):

        data = 0
        res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR_ALL, data)
        if res < 0:
            raise errors.JLinkException('Failed to clear all STRACE events.')

        return None

Clears all STRACE events.

Args:
self (JLink): the ``JLink`` instance.

Returns:
``None``

Raises:
JLinkException: on error.


def _properties_model_to_dict(properties):
    result = {}
    for attr in properties.__dict__:
        value = getattr(properties, attr)
        if (hasattr(value, '__module__') and ('models' in value.__module__)):
            value = _properties_model_to_dict(value)
        if (not ((value is None) or (isinstance(value, dict) and (not value)))):
            result[attr] = value
    return result

Convert properties model to dict.

Args:
properties: Properties model.

Returns:
dict: Converted model.


def optimize(onnx_model_path: Path) -> Path:
    from onnxruntime import InferenceSession, SessionOptions
    opt_model_path = generate_identified_filename(onnx_model_path, '-optimized')
    sess_option = SessionOptions()
    sess_option.optimized_model_filepath = opt_model_path.as_posix()
    _ = InferenceSession(onnx_model_path.as_posix(), sess_option)
    print(f'Optimized model has been written at {opt_model_path}: ✔')
    print('/!\\ Optimized model contains hardware specific operators which might not be portable. /!\\')
    return opt_model_path

Load the model at the specified path and let onnxruntime look at transformations on the graph to enable all the
optimizations possible

Args:
onnx_model_path: filepath where the model binary description is stored

Returns: Path where the optimized model binary description has been saved


class Conv1D(nn.Module):

    def __init__(self, nf, nx):
        super().__init__()
        self.nf = nf
        self.nx = nx
        self.weight = nn.Parameter(torch.empty(nx, nf))
        self.bias = nn.Parameter(torch.zeros(nf))
        nn.init.normal_(self.weight, std=0.02)

    def __repr__(self) -> str:
        return 'Conv1D(nf={nf}, nx={nx})'.format(**self.__dict__)

    def forward(self, x):
        size_out = x.size()[:-1] + (self.nf,)
        x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight)
        x = x.view(size_out)
        return x

1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2).

Basically works like a linear layer but the weights are transposed.

Args:
nf (`int`): The number of output features.
nx (`int`): The number of input features.


def _get_or_create_global_step_read(graph=None):
    graph = graph or ops.get_default_graph()
    global_step_read_tensor = _get_global_step_read(graph)
    if global_step_read_tensor is not None:
        return global_step_read_tensor
    global_step_tensor = get_global_step(graph)
    if global_step_tensor is None:
        return None
    with graph.as_default() as g, g.name_scope(None):
        with g.name_scope(global_step_tensor.op.name + '/'):
            if isinstance(global_step_tensor, variables.Variable):
                global_step_value = cond.cond(variable_v1.is_variable_initialized(global_step_tensor), global_step_tensor.read_value, lambda: global_step_tensor.initial_value)
            else:
                global_step_value = global_step_tensor
            global_step_read_tensor = global_step_value + 0
            ops.add_to_collection(GLOBAL_STEP_READ_KEY, global_step_read_tensor)
    return _get_global_step_read(graph)

Gets or creates global step read tensor in graph.

Args:
graph: The graph in which to create the global step read tensor. If missing,
use default graph.

Returns:
Global step read tensor if there is global_step_tensor else return None.


def rho_rec(self, g2):

        return (self.expnorm / np.sqrt(1 + self.gamma2 * g2) + (
            1 - self.expnorm) * np.exp(-0.25 * self.beta2 * g2))

Reciprocal space model charge value
for input squared reciprocal vector.
Args:
g2: Square of reciprocal vector

Returns:
Charge density at the reciprocal vector magnitude


def _ensure_unicode(text):

    if isinstance(text, six.binary_type):
        return text.decode(sys.getfilesystemencoding(), 'replace')
    else:
        return text

Ensures the text passed in becomes unicode
Args:
text (str|unicode)
Returns:
unicode


def read_accpro20(infile):

    with open(infile) as f:
        records = f.read().splitlines()

    accpro20_dict = {}
    for i, r in enumerate(records):
        if i % 2 == 0:

            accpro20_dict[records[i].split(' ')[0][1:]] = [int(x) for x in records[i + 1].split(' ')]

    return accpro20_dict

Read the accpro20 output (.acc20) and return the parsed FASTA records.

Keeps the spaces between the accessibility numbers.

Args:
infile: Path to .acc20 file

Returns:
dict: Dictionary of accessibilities with keys as the ID


def FoldByteStream(self, mapped_value, **kwargs):

    try:
      byte_stream = mapped_value.encode(self._data_type_definition.encoding)

    except Exception as exception:
      error_string = (
          'Unable to write: {0:s} to byte stream with error: {1!s}').format(
              self._data_type_definition.name, exception)
      raise errors.MappingError(error_string)

    return super(StringMap, self).FoldByteStream(byte_stream, **kwargs)

Folds the data type into a byte stream.

Args:
mapped_value (object): mapped value.

Returns:
bytes: byte stream.

Raises:
FoldingError: if the data type definition cannot be folded into
the byte stream.


def invoke(self):
    self._ensure_safe()
    self._interpreter.Invoke()

Invoke the interpreter.

Be sure to set the input sizes, allocate tensors and fill values before
calling this. Also, note that this function releases the GIL so heavy
computation can be done in the background while the Python interpreter
continues. No other function on this object should be called while the
invoke() call has not finished.

Raises:
ValueError: When the underlying interpreter fails raise ValueError.


def backward_transfer_pair(backward_channel: NettingChannelState, payer_transfer: LockedTransferSignedState, pseudo_random_generator: random.Random, block_number: BlockNumber) -> Tuple[(Optional[MediationPairState], List[Event])]:
    transfer_pair = None
    events: List[Event] = list()
    lock = payer_transfer.lock
    lock_timeout = BlockTimeout((lock.expiration - block_number))
    if is_channel_usable(backward_channel, lock.amount, lock_timeout):
        message_identifier = message_identifier_from_prng(pseudo_random_generator)
        refund_transfer = channel.send_refundtransfer(channel_state=backward_channel, initiator=payer_transfer.initiator, target=payer_transfer.target, amount=get_lock_amount_after_fees(lock, backward_channel), message_identifier=message_identifier, payment_identifier=payer_transfer.payment_identifier, expiration=lock.expiration, secrethash=lock.secrethash)
        transfer_pair = MediationPairState(payer_transfer, backward_channel.partner_state.address, refund_transfer.transfer)
        events.append(refund_transfer)
    return (transfer_pair, events)

Sends a transfer backwards, allowing the previous hop to try a new
route.

When all the routes available for this node failed, send a transfer
backwards with the same amount and secrethash, allowing the previous hop to
do a retry.

Args:
backward_channel: The original channel which sent the mediated transfer
to this node.
payer_transfer: The *latest* payer transfer which is backing the
mediation.
block_number: The current block number.

Returns:
The mediator pair and the correspoding refund event.


def run_tag_from_session_and_metric(session_name, metric_name):

  assert isinstance(session_name, six.string_types)
  assert isinstance(metric_name, api_pb2.MetricName)

  run = os.path.normpath(os.path.join(session_name, metric_name.group))
  tag = metric_name.tag
  return run, tag

Returns a (run,tag) tuple storing the evaluations of the specified metric.

Args:
session_name: str.
metric_name: MetricName protobuffer.
Returns: (run, tag) tuple.


def GetRootKey(self):
    regf_key = self._regf_file.get_root_key()
    if (not regf_key):
        return None
    return REGFWinRegistryKey(regf_key, key_path=self._key_path_prefix)

Retrieves the root key.

Returns:
WinRegistryKey: Windows Registry root key or None if not available.


def get_att_mats(translate_model):
    enc_atts = []
    dec_atts = []
    encdec_atts = []
    prefix = 'transformer/body/'
    postfix_self_attention = '/multihead_attention/dot_product_attention'
    if (translate_model.hparams.self_attention_type == 'dot_product_relative'):
        postfix_self_attention = '/multihead_attention/dot_product_attention_relative'
    postfix_encdec = '/multihead_attention/dot_product_attention'
    for i in range(translate_model.hparams.num_hidden_layers):
        enc_att = translate_model.attention_weights[('%sencoder/layer_%i/self_attention%s' % (prefix, i, postfix_self_attention))]
        dec_att = translate_model.attention_weights[('%sdecoder/layer_%i/self_attention%s' % (prefix, i, postfix_self_attention))]
        encdec_att = translate_model.attention_weights[('%sdecoder/layer_%i/encdec_attention%s' % (prefix, i, postfix_encdec))]
        enc_atts.append(enc_att)
        dec_atts.append(dec_att)
        encdec_atts.append(encdec_att)
    return (enc_atts, dec_atts, encdec_atts)

Get's the tensors representing the attentions from a build model.

The attentions are stored in a dict on the Transformer object while building
the graph.

Args:
translate_model: Transformer object to fetch the attention weights from.

Returns:
Tuple of attention matrices; (
enc_atts: Encoder self attention weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, inp_len, inp_len)
dec_atts: Decoder self attetnion weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, out_len, out_len)
encdec_atts: Encoder-Decoder attention weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, out_len, inp_len)
)


def _ParseContainerTable(self, parser_mediator, table, container_name):

    if table is None:
      raise ValueError('Missing table value.')

    for record_index, esedb_record in enumerate(table.records):
      if parser_mediator.abort:
        break

      if container_name == 'Content':
        value_mappings = self._CONTAINER_TABLE_VALUE_MAPPINGS
      else:
        value_mappings = None

      try:
        record_values = self._GetRecordValues(
            parser_mediator, table.name, esedb_record,
            value_mappings=value_mappings)

      except UnicodeDecodeError:
        parser_mediator.ProduceExtractionWarning((
            'Unable to retrieve record values from record: {0:d} '
            'in table: {1:s}').format(record_index, table.name))
        continue

      if (container_name in self._SUPPORTED_CONTAINER_NAMES or
          container_name.startswith('MSHist')):
        access_count = record_values.get('AccessCount', None)
        cached_filename = record_values.get('Filename', None)
        cached_file_size = record_values.get('FileSize', None)
        cache_identifier = record_values.get('CacheId', None)
        container_identifier = record_values.get('ContainerId', None)
        entry_identifier = record_values.get('EntryId', None)
        file_extension = record_values.get('FileExtension', None)
        redirect_url = record_values.get('RedirectUrl', None)
        sync_count = record_values.get('SyncCount', None)

        url = record_values.get('Url', '')

        if ord(url[0]) < 0x20 or ord(url[0]) == 0x7f:
          url = None

        request_headers = record_values.get('RequestHeaders', None)

        if not isinstance(request_headers, py2to3.UNICODE_TYPE):
          request_headers = None

        response_headers = record_values.get('ResponseHeaders', None)

        if not isinstance(response_headers, py2to3.UNICODE_TYPE):
          response_headers = None

        event_data = MsieWebCacheContainerEventData()
        event_data.access_count = access_count
        event_data.cached_filename = cached_filename
        event_data.cached_file_size = cached_file_size
        event_data.cache_identifier = cache_identifier
        event_data.container_identifier = container_identifier
        event_data.entry_identifier = entry_identifier
        event_data.file_extension = file_extension
        event_data.redirect_url = redirect_url
        event_data.request_headers = request_headers
        event_data.response_headers = response_headers
        event_data.sync_count = sync_count
        event_data.url = url

        timestamp = record_values.get('SyncTime', None)
        if timestamp:
          date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
          event = time_events.DateTimeValuesEvent(
              date_time, 'Synchronization time')
          parser_mediator.ProduceEventWithEventData(event, event_data)

        timestamp = record_values.get('CreationTime', None)
        if timestamp:
          date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
          event = time_events.DateTimeValuesEvent(
              date_time, definitions.TIME_DESCRIPTION_CREATION)
          parser_mediator.ProduceEventWithEventData(event, event_data)

        timestamp = record_values.get('ExpiryTime', None)
        if timestamp:
          date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
          event = time_events.DateTimeValuesEvent(
              date_time, definitions.TIME_DESCRIPTION_EXPIRATION)
          parser_mediator.ProduceEventWithEventData(event, event_data)

        timestamp = record_values.get('ModifiedTime', None)
        if timestamp:
          date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
          event = time_events.DateTimeValuesEvent(
              date_time, definitions.TIME_DESCRIPTION_MODIFICATION)
          parser_mediator.ProduceEventWithEventData(event, event_data)

        timestamp = record_values.get('AccessedTime', None)
        if timestamp:
          date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
          event = time_events.DateTimeValuesEvent(
              date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)
          parser_mediator.ProduceEventWithEventData(event, event_data)

        timestamp = record_values.get('PostCheckTime', None)
        if timestamp:
          date_time = dfdatetime_filetime.Filetime(timestamp=timestamp)
          event = time_events.DateTimeValuesEvent(
              date_time, 'Post check time')
          parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a Container_# table.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
table (pyesedb.table): table.
container_name (str): container name, which indicates the table type.

Raises:
ValueError: if the table value is missing.


def ParseStatusRow(self, parser_mediator, query, row, **unused_kwargs):

    query_hash = hash(query)

    event_data = TwitterAndroidStatusEventData()
    event_data.query = query
    event_data.identifier = self._GetRowValue(query_hash, row, '_id')
    event_data.author_identifier = self._GetRowValue(
        query_hash, row, 'author_id')
    event_data.username = self._GetRowValue(query_hash, row, 'username')
    event_data.content = self._GetRowValue(query_hash, row, 'content')
    event_data.favorited = self._GetRowValue(query_hash, row, 'favorited')
    event_data.retweeted = self._GetRowValue(query_hash, row, 'retweeted')

    timestamp = self._GetRowValue(query_hash, row, 'time')
    if timestamp:
      date_time = dfdatetime_java_time.JavaTime(timestamp=timestamp)
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_CREATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

Parses a status row from the database.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row resulting from query.