def delete(self, entity):

    key = _normalize_key(entity)
    if key is None:
      return self.ndb_delete(entity)
    self.deletes.append(key)

Registers entity to delete from datastore.

Args:
        entity: an entity, model instance, or key to delete.


def find_file_in_load_dirs(relpath):

    if relpath.startswith(os.path.sep):
        relpath = relpath.lstrip(os.path.sep)

    for ld in settings.DATA_DIRECTORIES:
        possible_path = os.path.join(ld, relpath)
        if os.path.exists(possible_path):
            return possible_path

If given relative path exists in one of DevAssistant load paths,
    return its full path.

Args:
        relpath: a relative path, e.g. "assitants/crt/test.yaml"

Returns:
        absolute path of the file, e.g. "/home/x/.devassistant/assistanta/crt/test.yaml
        or None if file is not found


def yesterdayDF(symbol, token='', version=''):

    y = yesterday(symbol, token, version)
    if y:
        df = pd.io.json.json_normalize(y)
        _toDatetime(df)
        _reindex(df, 'symbol')
    else:
        df = pd.DataFrame()
    return df

This returns previous day adjusted price data for one or more stocks

    https://iexcloud.io/docs/api/#previous-day-prices
    Available after 4am ET Tue-Sat

Args:
        symbol (string); Ticker to request
        token (string); Access token
        version (string); API version

Returns:
        DataFrame: result


def CER(prediction, true_labels):

  errors = (prediction != true_labels).sum()
  return float(errors)/len(prediction)

Calculates the classification error rate for an N-class classification problem

    Parameters:

    prediction (numpy.ndarray): A 1D :py:class:`numpy.ndarray` containing your
        prediction

    true_labels (numpy.ndarray): A 1D :py:class:`numpy.ndarray`
        containing the ground truth labels for the input array, organized in the
        same order.


def __deleteOutputCache(self, modelID):

    # If this is our output, we should close the connection
    if modelID == self._modelID and self._predictionLogger is not None:
      self._predictionLogger.close()
      del self.__predictionCache
      self._predictionLogger = None
      self.__predictionCache = None

Delete's the output cache associated with the given modelID. This actually
    clears up the resources associated with the cache, rather than deleting al
    the records in the cache

    Parameters:
    -----------------------------------------------------------------------
    modelID:      The id of the model whose output cache is being deleted


def get_tag(self, key, *, case_sensitive=True):

        key = key if case_sensitive else key.lower()
        for tag in self.resource.tags:
            if not case_sensitive:
                if tag.key.lower() == key:
                    return tag
            elif key == tag.key:
                return tag

        return None

Return a tag by key, if found

Args:
        key (str): Name/key of the tag to locate
        case_sensitive (bool): Should tag keys be treated case-sensitive (default: true)

Returns:
        `Tag`,`None`


def AddMonths(start_date, months):

  current_date = start_date
  i = 0
  while i < months:
    month_days = calendar.monthrange(current_date.year, current_date.month)[1]
    current_date += timedelta(days=month_days)
    i += 1
  return current_date

A simple convenience utility for adding months to a given start date.

    This increments the months by adding the number of days in the current month
    to the current month, for each month.

Args:
        start_date: date The date months are being added to.
        months: int The number of months to add.

Returns:
        A date equal to the start date incremented by the given number of months.


def __init__(self, app, env, region, prop_path, artifact_path, artifact_version, primary_region='us-east-1'):

        self.app_name = app
        self.env = env
        self.region = region
        self.artifact_path = artifact_path
        self.version = artifact_version
        self.properties = get_properties(prop_path, env=self.env, region=self.region)
        self.s3props = self.properties['s3']
        generated = get_details(app=app, env=env, region=region)

        include_region = True
        if self.region == primary_region:
            include_region = False
        if self.s3props.get('shared_bucket_master'):
            self.bucket = generated.shared_s3_app_bucket(include_region=include_region)
            self.s3path = app
        elif self.s3props.get('shared_bucket_target'):
            shared_app = self.s3props['shared_bucket_target']
            newgenerated = get_details(app=shared_app, env=env, region=region)
            self.bucket = newgenerated.shared_s3_app_bucket(include_region=include_region)
            self.s3path = app
        else:
            self.bucket = generated.s3_app_bucket(include_region=include_region)
            self.s3path = self.s3props['path'].lstrip('/')

        self.s3_version_uri = ''
        self.s3_latest_uri = ''
        self.setup_pathing()

S3 deployment object.

Args:
        app (str): Application name
        env (str): Environment/Account
        region (str): AWS Region
        prop_path (str): Path of environment property file
        artifact_path (str): Path to tar.gz artifact
        primary_region (str): The primary region for the application.


def _prefix_from_prefix_string(self, prefixlen_str):

        try:
            if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
                raise ValueError
            prefixlen = int(prefixlen_str)
            if not (0 <= prefixlen <= self._max_prefixlen):
               raise ValueError
        except ValueError:
            raise NetmaskValueError('%s is not a valid prefix length' %
                                    prefixlen_str)
        return prefixlen

Turn a prefix length string into an integer.

Args:
        prefixlen_str: A decimal string containing the prefix length.

Returns:
        The prefix length as an integer.

Raises:
        NetmaskValueError: If the input is malformed or out of range.


def recordsDF(token='', version=''):

    df = pd.DataFrame(records(token, version))
    _toDatetime(df)
    return df

https://iexcloud.io/docs/api/#stats-records

Args:
        token (string); Access token
        version (string); API version

Returns:
        DataFrame: result


def delete_records(server, token, data):

    method = 'DELETE'
    uri = 'https://' + server + '/zone'
    for i in data:
        connect.tonicdns_client(uri, method, token, i)

Delete records of specific domain.

Args:
        server: TonicDNS API server
        token:  TonicDNS API authentication token
        data:   Delete records

    ContentType: application/json
    x-authentication-token: token


def to_concat_skip_model(self, start_id, end_id):

        self.operation_history.append(("to_concat_skip_model", start_id, end_id))
        filters_end = self.layer_list[end_id].output.shape[-1]
        filters_start = self.layer_list[start_id].output.shape[-1]
        start_node_id = self.layer_id_to_output_node_ids[start_id][0]

        pre_end_node_id = self.layer_id_to_input_node_ids[end_id][0]
        end_node_id = self.layer_id_to_output_node_ids[end_id][0]

        skip_output_id = self._insert_pooling_layer_chain(start_node_id, end_node_id)

        concat_input_node_id = self._add_node(deepcopy(self.node_list[end_node_id]))
        self._redirect_edge(pre_end_node_id, end_node_id, concat_input_node_id)

        concat_layer = StubConcatenate()
        concat_layer.input = [
            self.node_list[concat_input_node_id],
            self.node_list[skip_output_id],
        ]
        concat_output_node_id = self._add_node(Node(concat_layer.output_shape))
        self._add_edge(concat_layer, concat_input_node_id, concat_output_node_id)
        self._add_edge(concat_layer, skip_output_id, concat_output_node_id)
        concat_layer.output = self.node_list[concat_output_node_id]
        self.node_list[concat_output_node_id].shape = concat_layer.output_shape

        # Add the concatenate layer.
        new_conv_layer = get_conv_class(self.n_dim)(
            filters_start + filters_end, filters_end, 1
        )
        self._add_edge(new_conv_layer, concat_output_node_id, end_node_id)
        new_conv_layer.input = self.node_list[concat_output_node_id]
        new_conv_layer.output = self.node_list[end_node_id]
        self.node_list[end_node_id].shape = new_conv_layer.output_shape

        if self.weighted:
            filter_shape = (1,) * self.n_dim
            weights = np.zeros((filters_end, filters_end) + filter_shape)
            for i in range(filters_end):
                filter_weight = np.zeros((filters_end,) + filter_shape)
                center_index = (i,) + (0,) * self.n_dim
                filter_weight[center_index] = 1
                weights[i, ...] = filter_weight
            weights = np.concatenate(
                (weights, np.zeros((filters_end, filters_start) + filter_shape)), axis=1
            )
            bias = np.zeros(filters_end)
            new_conv_layer.set_weights(
                (add_noise(weights, np.array([0, 1])), add_noise(bias, np.array([0, 1])))
            )

Add a weighted add concatenate connection from after start node to end node.

Args:
        start_id: The convolutional layer ID, after which to start the skip-connection.
        end_id: The convolutional layer ID, after which to end the skip-connection.


def _create_image_url(self, file_path, type_, target_size):

        if self.image_config is None:
            logger.warning('no image configuration available')
            return
        return ''.join([
            self.image_config['secure_base_url'],
            self._image_size(self.image_config, type_, target_size),
            file_path,
        ])

The the closest available size for specified image type.

Args:
        file_path (:py:class:`str`): The image file path.
        type_ (:py:class:`str`): The type of image to create a URL
        for, (``'poster'`` or ``'profile'``).
        target_size (:py:class:`int`): The size of image to aim for (used
        as either width or height).


def send_course_completion_statement(lrs_configuration, user, course_overview, course_grade):

    user_details = LearnerInfoSerializer(user)
    course_details = CourseInfoSerializer(course_overview)

    statement = LearnerCourseCompletionStatement(
        user,
        course_overview,
        user_details.data,
        course_details.data,
        course_grade,
    )
    EnterpriseXAPIClient(lrs_configuration).save_statement(statement)

Send xAPI statement for course completion.

Args:
        lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements.
        user (User): Django User object.
        course_overview (CourseOverview): Course over view object containing course details.
        course_grade (CourseGrade): course grade object.


def _QueryHashes(self, digests):

    url_parameters = {'apikey': self._api_key, 'resource': ', '.join(digests)}

    try:
      json_response = self.MakeRequestAndDecodeJSON(
          self._VIRUSTOTAL_API_REPORT_URL, 'GET', params=url_parameters)
    except errors.ConnectionError as exception:
      json_response = None
      logger.error('Unable to query VirusTotal with error: {0!s}.'.format(
          exception))

    return json_response

Queries VirusTotal for a specfic hashes.

Args:
        digests (list[str]): hashes to look up.

Returns:
        dict[str, object]: JSON response or None on error.


def repository_compare(self, from_, to, **kwargs):

        path = '/projects/%s/repository/compare' % self.get_id()
        query_data = {'from': from_, 'to': to}
        return self.manager.gitlab.http_get(path, query_data=query_data,
                                            **kwargs)

Return a diff between two branches/commits.

Args:
        from_(str): Source branch/SHA
        to(str): Destination branch/SHA
        **kwargs: Extra options to send to the server (e.g. sudo)

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabGetError: If the server failed to perform the request

Returns:
        str: The diff


def get_box_reminders(self, box_key):

		#required sanity check
		if box_key:
			return requests.codes.bad_request, None

		uri = '/'.join([self.api_uri,
						self.boxes_suffix,
						box_key,
						self.reminders_suffix
						])

		return self._req('get', uri)

Gets all reminders for a box

Args:
    reminder		updated reminder of StreakReminder type
    return			(status code, reminder dict)


def execute(self, sensor_graph, scope_stack):

        parent = scope_stack[-1]

        try:
            slot = parent.resolve_identifier('current_slot', SlotIdentifier)
        except UnresolvedIdentifierError:
            raise SensorGraphSemanticError("set config statement used outside of config block")

        if self.explicit_type is None or not isinstance(self.identifier, int):
            raise SensorGraphSemanticError("Config variable type definitions are not yet supported")

        if isinstance(self.value, (bytes, bytearray)) and not self.explicit_type == 'binary':
            raise SensorGraphSemanticError("You must pass the binary variable type when using encoded binary data")

        if not isinstance(self.value, (bytes, bytearray)) and self.explicit_type == 'binary':
            raise SensorGraphSemanticError("You must pass an encoded binary value with binary type config variables")

        sensor_graph.add_config(slot, self.identifier, self.explicit_type, self.value)

Execute this statement on the sensor_graph given the current scope tree.

    This adds a single config variable assignment to the current sensor graph

Args:
        sensor_graph (SensorGraph): The sensor graph that we are building or
            modifying
        scope_stack (list(Scope)): A stack of nested scopes that may influence
            how this statement allocates clocks or other stream resources.


def decode_schedule(string):

  splits = string.split()
  steps = [int(x[1:]) for x in splits[1:] if x[0] == '@']
  pmfs = np.reshape(
      [float(x) for x in splits[1:] if x[0] != '@'], [len(steps), -1])
  return splits[0], tuplize(steps), tuplize(pmfs)

Decodes a string into a schedule tuple.

Args:
        string: The string encoding of a schedule tuple.

Returns:
        A schedule tuple, see encode_schedule for details.


def AddArguments(cls, argument_group):

    argument_group.add_argument(
        '--server', dest='server', type=str, action='store',
        default=cls._DEFAULT_SERVER, metavar='HOSTNAME',
        help='The hostname or server IP address of the server.')
    argument_group.add_argument(
        '--port', dest='port', type=int, action='store',
        default=cls._DEFAULT_PORT, metavar='PORT',
        help='The port number of the server.')

Adds command line arguments the helper supports to an argument group.

    This function takes an argument parser or an argument group object and adds
    to it all the command line arguments this helper supports.

Args:
        argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
        argparse group.


def generate_full_symmops(symmops, tol):

    # Uses an algorithm described in:
    # Gregory Butler. Fundamental Algorithms for Permutation Groups.
    # Lecture Notes in Computer Science (Book 559). Springer, 1991. page 15
    UNIT = np.eye(4)
    generators = [op.affine_matrix for op in symmops
                  if not np.allclose(op.affine_matrix, UNIT)]
    if not generators:
        # C1 symmetry breaks assumptions in the algorithm afterwards
        return symmops
    else:
        full = list(generators)

        for g in full:
            for s in generators:
                op = np.dot(g, s)
                d = np.abs(full - op) < tol
                if not np.any(np.all(np.all(d, axis=2), axis=1)):
                    full.append(op)

        d = np.abs(full - UNIT) < tol
        if not np.any(np.all(np.all(d, axis=2), axis=1)):
            full.append(UNIT)
        return [SymmOp(op) for op in full]

Recursive algorithm to permute through all possible combinations of the
    initially supplied symmetry operations to arrive at a complete set of
    operations mapping a single atom to all other equivalent atoms in the
    point group.  This assumes that the initial number already uniquely
    identifies all operations.

Args:
        symmops ([SymmOp]): Initial set of symmetry operations.

Returns:
        Full set of symmetry operations.


def vstack(tup):

    # Follow numpy.vstack behavior for 1D arrays:
    arrays = list(tup)
    for i in range(len(arrays)):
        if arrays[i].ndim is 1:
            arrays[i] = arrays[i][np.newaxis, :]
    return concatenate(tup, axis=0)

Stack arrays in sequence vertically (row wise),
    handling ``RemoteArray`` and ``DistArray`` without moving data.

Args:
        tup (sequence of array_like)

Returns:
        res: `ndarray`, if inputs were all local
        `RemoteArray`, if inputs were all on the same remote engine
        `DistArray`, if inputs were already scattered on different engines


def set_tick(self, index, interval):

        name = self.tick_name(index)
        if name is None:
            return pack_error(ControllerSubsystem.SENSOR_GRAPH, Error.INVALID_ARRAY_KEY)

        self.ticks[name] = interval
        return Error.NO_ERROR

Update the a tick's interval.

Args:
        index (int): The index of the tick that you want to fetch.
        interval (int): The number of seconds between ticks.
            Setting this to 0 will disable the tick.

Returns:
        int: An error code.


def add_perfdata(self, *args, **kwargs):

        self._perfdata.append(Perfdata(*args, **kwargs))

add a perfdata to the internal perfdata list

Args:
        the same arguments as for Perfdata()


def load(self,cache_genotype=False,cache_phenotype=True):

        self.f = h5py.File(self.file_name,'r')
        self.pheno = self.f['phenotype']
        self.geno  = self.f['genotype']
        #TODO: load all row and column headers for genotype and phenotype

        #parse out thse we alwasy need for convenience
        self.genoM = self.geno['matrix']

        self.phenoM = self.pheno['matrix']
        self.sample_ID = self.geno['row_header']['sample_ID'][:]
        self.genoChrom = self.geno['col_header']['chrom'][:]
        self.genoPos   = self.geno['col_header']['pos'][:]
        if 'pos_cum' in list(self.geno['col_header'].keys()):
            self.genoPos_cum   = self.geno['col_header']['pos_cum'][:]
        else:
            self.genoPos_cum = None
        self.phenotype_ID = self.pheno['col_header']['phenotype_ID'][:]

        #cache?
        if cache_genotype:
            self.genoM = self.genoM[:]
        if cache_phenotype:
            self.phenoM = self.phenoM[:]

        # Additional pheno col header
        headers = list(self.pheno['col_header'].keys())
        if 'gene_ID' in headers:
            self.eqtl = True
            self.geneID = self.pheno['col_header']['gene_ID'][:]
            self.gene_pos = SP.array([self.pheno['col_header']['gene_chrom'][:],self.pheno['col_header']['gene_start'][:],self.pheno['col_header']['gene_end']],dtype='int').T
            self.geneIDs= list(set(self.geneID))
        else:
            self.eqtl = False
        if 'environment' in headers:
            self.E  = self.pheno['col_header/environment'][:]
            self.Es = list(set(self.E))
        else:
            self.E = None

        #dimensions
        self.N = self.genoM.shape[0]
        self.S = self.genoM.shape[1]
        self.P = self.phenoM.shape[1]
        assert (self.genoM.shape[0]==self.phenoM.shape[0]), 'dimension missmatch'

load data file

Args:
        cache_genotype:     load genotypes fully into memory (default: False)
        cache_phenotype:    load phentopyes fully intro memry (default: True)


def proc_ovrds(**kwargs):

    return [
        (k, v) for k, v in kwargs.items()
        if k not in list(ELEM_KEYS.keys()) + list(ELEM_KEYS.values()) + PRSV_COLS
    ]

Bloomberg overrides

Args:
        **kwargs: overrides

Returns:
        list of tuples

Example:
        >>> proc_ovrds(DVD_Start_Dt='20180101')
        [('DVD_Start_Dt', '20180101')]
        >>> proc_ovrds(DVD_Start_Dt='20180101', cache=True, has_date=True)
        [('DVD_Start_Dt', '20180101')]


def execute_cql_query(self, query, compression):

    self._seqid += 1
    d = self._reqs[self._seqid] = defer.Deferred()
    self.send_execute_cql_query(query, compression)
    return d

Executes a CQL (Cassandra Query Language) statement and returns a
    CqlResult containing the results.

    Parameters:
    - query
    - compression


def from_json(cls, data):

        # Check required and optional keys
        optional_keys = {'wind_direction': 0, 'rain': False, 'snow_on_ground': False}
        assert 'wind_speed' in data, 'Required key "wind_speed" is missing!'
        for key, val in optional_keys.items():
            if key not in data:
                data[key] = val

        return cls(data['wind_speed'], data['wind_direction'], data['rain'],
                   data['snow_on_ground'])

Create a Wind Condition from a dictionary.

Args:
        data = {
        "wind_speed": float,
        "wind_direction": float,
        "rain": bool,
        "snow_on_ground": bool}


def kmip_version(self, value):

        if isinstance(value, enums.KMIPVersion):
            self._kmip_version = value
        else:
            raise ValueError("KMIP version must be a KMIPVersion enumeration")

Set the KMIP version for the client.

Args:
        value (KMIPVersion): A KMIPVersion enumeration

Returns:
        None

Raises:
        ValueError: if value is not a KMIPVersion enumeration

Example:
        >>> client.kmip_version = enums.KMIPVersion.KMIP_1_1
        >>>


def discretize(self, data):

        ret = data.copy()
        for feature in self.lambdas:
            if len(data.shape) == 1:
                ret[feature] = int(self.lambdas[feature](ret[feature]))
            else:
                ret[:, feature] = self.lambdas[feature](
                    ret[:, feature]).astype(int)
        return ret

Discretizes the data.

Args:
        data: numpy 2d or 1d array

Returns:
        numpy array of same dimension, discretized.


def _create_w_objective(m, X, Z=None):

    genes, clusters = m.shape
    cells = X.shape[1]
    nonzeros = (X!=0)
    def objective(w):
        # convert w into a matrix first... because it's a vector for
        # optimization purposes
        w = w.reshape((m.shape[1], X.shape[1]))
        d = m.dot(w)+eps
        # derivative of objective wrt all elements of w
        # for w_{ij}, the derivative is... m_j1+...+m_jn sum over genes minus
        # x_ij
        temp = X/d
        m_sum = m.T.dot(nonzeros)
        m2 = m.T.dot(temp)
        deriv = m_sum - m2
        return np.sum(nonzeros*(d - X*np.log(d)))/genes, deriv.flatten()/genes
    return objective

Creates an objective function and its derivative for W, given M and X (data)

Args:
        m (array): genes x clusters
        X (array): genes x cells
        Z (array): zero-inflation parameters - genes x 1


def execute(api):

    try:
      return api.execute()
    except Exception as exception:
      now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
      _print_error('%s: Exception %s: %s' % (now, type(exception).__name__,
                                             str(exception)))
      # Re-raise exception to be handled by retry logic
      raise exception

Executes operation.

Args:
        api: The base API object

Returns:
        A response body object


def execute_code(self, code, filename=None, isolate=False):

        def _apply():
            self.compile_code(code=code,
                              filename=filename,
                              exec_namespace=self.globals)

        # we want to execute the code using self.globals - if for no other
        # reason that self.formatter is pointing at self.globals, so if we
        # passed in a copy, we would also need to make self.formatter "look" at
        # the same copy - but we don't want to "pollute" our namespace, because
        # the same executor may be used to run multiple packages. Therefore,
        # we save a copy of self.globals before execution, and restore it after
        #
        if isolate:
            saved_globals = dict(self.globals)

            try:
                _apply()
            finally:
                self.globals.clear()
                self.globals.update(saved_globals)
        else:
            _apply()

Execute code within the execution context.

Args:
        code (str or SourceCode): Rex code to execute.
        filename (str): Filename to report if there are syntax errors.
        isolate (bool): If True, do not affect `self.globals` by executing
            this code.


def GetPathSegmentAndSuffix(self, base_path, path):

    if path is None or base_path is None or not path.startswith(base_path):
      return None, None

    path_index = len(base_path)
    if base_path and not base_path.endswith(self.PATH_SEPARATOR):
      path_index += 1

    if path_index == len(path):
      return '', ''

    path_segment, _, suffix = path[path_index:].partition(self.PATH_SEPARATOR)
    return path_segment, suffix

Determines the path segment and suffix of the path.

    None is returned if the path does not start with the base path and
    an empty string if the path exactly matches the base path.

Args:
        base_path (str): base path.
        path (str): path.

Returns:
        tuple[str, str]: path segment and suffix string.


def Match(self, artifact=None, os_name=None, cpe=None, label=None):

    return [
        c for c in self.conditions if c.Match(artifact, os_name, cpe, label)
    ]

Test if host data should trigger a check.

Args:
        artifact: An artifact name.
        os_name: An OS string.
        cpe: A CPE string.
        label: A label string.

Returns:
        A list of conditions that match.


def HsvToRgb(h, s, v):

    if s==0: return (v, v, v)   # achromatic (gray)

    h /= 60.0
    h = h % 6.0

    i = int(h)
    f = h - i
    if not(i&1): f = 1-f     # if i is even

    m = v * (1.0 - s)
    n = v * (1.0 - (s * f))

    if i==0: return (v, n, m)
    if i==1: return (n, v, m)
    if i==2: return (m, v, n)
    if i==3: return (m, n, v)
    if i==4: return (n, m, v)
    return (v, m, n)

Convert the color from RGB coordinates to HSV.

    Parameters:
        :h:
        The Hus component value [0...1]
        :s:
        The Saturation component value [0...1]
        :v:
        The Value component [0...1]

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

    >>> Color.HslToRgb(30.0, 1.0, 0.5)
    (1.0, 0.5, 0.0)


def learn(self, grad_arr):

        if grad_arr.ndim > 3:
            grad_arr = grad_arr.reshape((
                grad_arr.shape[0],
                grad_arr.shape[1],
                -1
            ))
            grad_arr = grad_arr[:, -1]
        elif grad_arr.ndim == 3:
            grad_arr = grad_arr[:, -1]

        delta_arr, _, grads_list = self.__lstm_model.hidden_back_propagate(grad_arr)
        grads_list.insert(0, None)
        grads_list.insert(0, None)

        self.__lstm_model.optimize(
            grads_list,
            self.__learning_rate,
            1
        )

        return delta_arr

Update this Discriminator by ascending its stochastic gradient.

Args:
        grad_arr:   `np.ndarray` of gradients.

Returns:
        `np.ndarray` of delta or gradients.


def index_filename_rel_other_index(self, other: str) -> str:

        return relpath(self.index_filename, start=dirname(other))

Returns the filename of this index, relative to the director of another
    index. (For inserting a reference to this index into ``other``.)

Args:
        other: the other index

Returns:
        relative filename of our index


def GetVolumeByIndex(self, volume_index):

    if not self._is_parsed:
      self._Parse()
      self._is_parsed = True

    if volume_index < 0 or volume_index >= len(self._volume_identifiers):
      return None

    volume_identifier = self._volume_identifiers[volume_index]
    return self._volumes[volume_identifier]

Retrieves a specific volume based on the index.

Args:
        volume_index (int): index of the volume.

Returns:
        Volume: a volume or None if not available.


def _delete(self, identifier=None):

        query = text()
        self.backend.library.database.connection.execute(query, identifier=identifier)

Deletes given identifier from index.

Args:
        identifier (str): identifier of the document to delete.


def _prepare_babi_data(tmp_dir, data_dir):

  if not tf.gfile.Exists(data_dir):
    tf.gfile.MakeDirs(data_dir)

  file_path = os.path.join(tmp_dir, _TAR)
  headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) "
                           "AppleWebKit/537.36 (KHTML, like Gecko) "
                           "Chrome/63.0.3239.132 Safari/537.36"}
  resp = requests.get(_URL, headers=headers)
  with open(file_path, "wb") as f:
    f.write(resp.content)

  tar = tarfile.open(file_path)
  tar.extractall(tmp_dir)
  tar.close()

  return tmp_dir

Downloads and extracts the dataset.

Args:
        tmp_dir: temp directory to download and extract the dataset
        data_dir: The base directory where data and vocab files are stored.

Returns:
        tmp_dir: temp directory containing the raw data.


def recordbatch(self, auth, resource, entries, defer=False):

        return self._call('recordbatch', auth, [resource, entries], defer)

Records a list of historical entries to the resource specified.

    Calls a function that bulids a request that writes a list of historical entries to the
    specified resource.

Args:
        auth: Takes the device cik
        resource: Takes the dataport alias or rid.
        entries: A list of entries to write to the resource.


def _setup_selection_range(self, f_start=None, f_stop=None, t_start=None, t_stop=None, init=False):

        # This avoids resetting values
        if init is True:
            if t_start is None:
                t_start = self.t_begin
            if t_stop is None:
                t_stop = self.t_end
            if f_start is None:
                f_start = self.f_begin
            if f_stop is None:
                f_stop = self.f_end
        else:
            if f_start is None:
                f_start = self.f_start
            if f_stop is None:
                f_stop = self.f_stop
            if t_start is None:
                t_start = self.t_start
            if t_stop is None:
                t_stop = self.t_stop

        # By now, all values start/stop are populated.

        if t_stop >= 0 and t_start >= 0 and t_stop < t_start:
            t_stop, t_start = t_start,t_stop
            logger.warning('Given t_stop < t_start, assuming reversed values.')
        if f_stop and f_start and f_stop < f_start:
            f_stop, f_start = f_start,f_stop
            logger.warning('Given f_stop < f_start, assuming reversed values.')

        if t_start >= self.t_begin and t_start < self.t_end:
            self.t_start = int(t_start)
        else:
            if init is False or t_start != None:
                logger.warning('Setting t_start = %f, since t_start not given or not valid.'%self.t_begin)
            self.t_start = self.t_begin

        if t_stop <= self.t_end  and t_stop > self.t_begin:
            self.t_stop = int(t_stop)
        else:
            if init is False or t_stop:
                logger.warning('Setting t_stop = %f, since t_stop not given or not valid.'%self.t_end)
            self.t_stop = self.t_end

        if f_start >= self.f_begin and f_start < self.f_end:
            self.f_start = f_start
        else:
            if init is False or f_start:
                logger.warning('Setting f_start = %f, since f_start not given or not valid.'%self.f_begin)
            self.f_start = self.f_begin

        if f_stop <= self.f_end and f_stop > self.f_begin:
            self.f_stop = f_stop
        else:
            if init is False or f_stop:
                logger.warning('Setting f_stop = %f, since f_stop not given or not valid.'%self.f_end)
            self.f_stop = self.f_end

        # Now we have setup bounds, we can calculate shape of selection
        self.selection_shape = self._calc_selection_shape()

Making sure the selection if time and frequency are within the file limits.

Args:
        init (bool): If call during __init__


def dumps(o, encoder=None):

    retval = ""
    if encoder is None:
        encoder = TomlEncoder(o.__class__)
    addtoretval, sections = encoder.dump_sections(o, "")
    retval += addtoretval
    while sections:
        newsections = encoder.get_empty_table()
        for section in sections:
            addtoretval, addtosections = encoder.dump_sections(
                sections[section], section)

            if addtoretval or (not addtoretval and not addtosections):
                if retval and retval[-2:] != "\n\n":
                    retval += "\n"
                retval += "[" + section + "]\n"
                if addtoretval:
                    retval += addtoretval
            for s in addtosections:
                newsections[section + "." + s] = addtosections[s]
        sections = newsections
    return retval

Stringifies input dict as toml

Args:
        o: Object to dump into toml

        preserve: Boolean parameter. If true, preserve inline tables.

Returns:
        String containing the toml corresponding to dict


def _dirint_bins(ktp, alt, w, dktp):

    it = range(len(ktp))

    # Create kt_prime bins
    ktp_bin = [-1] * len(ktp)
    ktp_bin = [0 if ktp[i] >= 0 and ktp[i] < 0.24 else ktp_bin[i] for i in it]
    ktp_bin = [1 if ktp[i] >= 0.24 and ktp[i] < 0.4 else ktp_bin[i] for i in it]
    ktp_bin = [2 if ktp[i] >= 0.4 and ktp[i] < 0.56 else ktp_bin[i] for i in it]
    ktp_bin = [3 if ktp[i] >= 0.56 and ktp[i] < 0.7 else ktp_bin[i] for i in it]
    ktp_bin = [4 if ktp[i] >= 0.7 and ktp[i] < 0.8 else ktp_bin[i] for i in it]
    ktp_bin = [5 if ktp[i] >= 0.8 and ktp[i] <= 1 else ktp_bin[i] for i in it]

    # Create altitude angle bins
    alt_bin = [-1] * len(alt)
    alt_bin = [0 if alt[i] <= 90 and alt[i] > 65 else alt_bin[i] for i in it]
    alt_bin = [1 if alt[i] <= 65 and alt[i] > 50 else alt_bin[i] for i in it]
    alt_bin = [2 if alt[i] <= 50 and alt[i] > 35 else alt_bin[i] for i in it]
    alt_bin = [3 if alt[i] <= 35 and alt[i] > 20 else alt_bin[i] for i in it]
    alt_bin = [4 if alt[i] <= 20 and alt[i] > 10 else alt_bin[i] for i in it]
    alt_bin = [5 if alt[i] <= 10 else alt_bin[i] for i in it]

    # Create the bins for w based on dew point temperature
    w_bin = [-1] * len(w)
    w_bin = [0 if w[i] >= 0 and w[i] < 1 else w_bin[i] for i in it]
    w_bin = [1 if w[i] >= 1 and w[i] < 2 else w_bin[i] for i in it]
    w_bin = [2 if w[i] >= 2 and w[i] < 3 else w_bin[i] for i in it]
    w_bin = [3 if w[i] >= 3 else w_bin[i] for i in it]
    w_bin = [4 if w[i] == -1 else w_bin[i] for i in it]

    # Create delta_kt_prime binning.
    dktp_bin = [-1] * len(dktp)
    dktp_bin = [0 if dktp[i] >= 0 and dktp[i] < 0.015 else dktp_bin[i] for i in it]
    dktp_bin = [1 if dktp[i] >= 0.015 and dktp[i] < 0.035 else dktp_bin[i] for i in it]
    dktp_bin = [2 if dktp[i] >= 0.035 and dktp[i] < 0.07 else dktp_bin[i] for i in it]
    dktp_bin = [3 if dktp[i] >= 0.07 and dktp[i] < 0.15 else dktp_bin[i] for i in it]
    dktp_bin = [4 if dktp[i] >= 0.15 and dktp[i] < 0.3 else dktp_bin[i] for i in it]
    dktp_bin = [5 if dktp[i] >= 0.3 and dktp[i] <= 1 else dktp_bin[i] for i in it]
    dktp_bin = [6 if dktp[i] == -1 else dktp_bin[i] for i in it]

    return ktp_bin, alt_bin, w_bin, dktp_bin

Determine the bins for the DIRINT coefficients.

Args:
        ktp : Altitude-independent clearness index
        alt : Solar altitude angle
        w : precipitable water estimated from surface dew-point temperature
        dktp : stability index

Returns:
        tuple of ktp_bin, alt_bin, w_bin, dktp_bin


def _get_resource_hash(zone_name, record):

        record_data = defaultdict(int, record)
        if type(record_data['GeoLocation']) == dict:
            record_data['GeoLocation'] = ":".join(["{}={}".format(k, v) for k, v in record_data['GeoLocation'].items()])

        args = [
            zone_name,
            record_data['Name'],
            record_data['Type'],
            record_data['Weight'],
            record_data['Region'],
            record_data['GeoLocation'],
            record_data['Failover'],
            record_data['HealthCheckId'],
            record_data['TrafficPolicyInstanceId']
        ]

        return get_resource_id('r53r', args)

Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique
    resource IDs

Args:
        zone_name (`str`): The name of the DNS Zone the record belongs to
        record (`dict`): A record dict to generate the hash from

Returns:
        `str`


def _OpenFile(self, path):

    if not self._registry_file_reader:
      return None

    return self._registry_file_reader.Open(
        path, ascii_codepage=self._ascii_codepage)

Opens a Windows Registry file.

Args:
        path (str): path of the Windows Registry file.

Returns:
        WinRegistryFile: Windows Registry file or None if not available.


def mcf(n,c):

    model = Model("mcf")

    x,f = {},{}
    for i in range(1,n+1):
        for j in range(1,n+1):
            if i != j:
                x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j))
            if i != j and j != 1:
                for k in range(2,n+1):
                    if i != k:
                        f[i,j,k] = model.addVar(ub=1, vtype="C", name="f(%s,%s,%s)"%(i,j,k))

    for i in range(1,n+1):
        model.addCons(quicksum(x[i,j] for j in range(1,n+1) if j != i) == 1, "Out(%s)"%i)
        model.addCons(quicksum(x[j,i] for j in range(1,n+1) if j != i) == 1, "In(%s)"%i)

    for k in range(2,n+1):
        model.addCons(quicksum(f[1,i,k] for i in range(2,n+1) if (1,i,k) in f) == 1, "FlowOut(%s)"%k)
        model.addCons(quicksum(f[i,k,k] for i in range(1,n+1) if (i,k,k) in f) == 1, "FlowIn(%s)"%k)

        for i in range(2,n+1):
            if i != k:
                model.addCons(quicksum(f[j,i,k] for j in range(1,n+1) if (j,i,k) in f) == \
                                quicksum(f[i,j,k] for j in range(1,n+1) if (i,j,k) in f),
                                "FlowCons(%s,%s)"%(i,k))

    for (i,j,k) in f:
        model.addCons(f[i,j,k] <= x[i,j], "FlowUB(%s,%s,%s)"%(i,j,k))

    model.setObjective(quicksum(c[i,j]*x[i,j] for (i,j) in x), "minimize")

    model.data = x,f
    return model

mcf: multi-commodity flow formulation for the (asymmetric) traveling salesman problem
    Parameters:
        - n: number of nodes
        - c[i,j]: cost for traversing arc (i,j)
    Returns a model, ready to be solved.


def StatResultFromStatEntry(
    stat_entry):

  values = []
  for attr in _STAT_ATTRS[:10]:
    values.append(stat_entry.Get(attr))
  return os.stat_result(values)

Returns a `os.stat_result` with most information from `StatEntry`.

    This is a lossy conversion, only the 10 first stat_result fields are
    populated, because the os.stat_result constructor is inflexible.

Args:
        stat_entry: An instance of rdf_client_fs.StatEntry.

Returns:
        An instance of `os.stat_result` with basic fields populated.


def to_dict(self, rw = False):

		return {k:v for (k,v) in self.attributes.items()
				if (v is not None and (not rw or (k in self.rw_attr_keys)))}

Returns relevant attributes as a dict.

Args:
    rw 			if True only returns the read/write enabled object attributes


def value_to_string(self, obj):

        value = self._get_val_from_obj(obj)
        return self.get_prep_value(value)

Convert the field value from the provided model to a string.

    Used during model serialization.

Args:
        obj: db.Model, model object

Returns:
        string, the serialized field value


def push_file(self, local_source, remote_dir):

        remote_dest = remote_dir + '/' + os.path.basename(local_source)

        try:
            self.makedirs(remote_dir, exist_ok=True)
        except IOError as e:
            logger.exception("Pushing {0} to {1} failed".format(local_source, remote_dir))
            if e.errno == 2:
                raise BadScriptPath(e, self.hostname)
            elif e.errno == 13:
                raise BadPermsScriptPath(e, self.hostname)
            else:
                logger.exception("File push failed due to SFTP client failure")
                raise FileCopyException(e, self.hostname)
        try:
            self.sftp_client.put(local_source, remote_dest, confirm=True)
            # Set perm because some systems require the script to be executable
            self.sftp_client.chmod(remote_dest, 0o777)
        except Exception as e:
            logger.exception("File push from local source {} to remote destination {} failed".format(
                local_source, remote_dest))
            raise FileCopyException(e, self.hostname)

        return remote_dest

Transport a local file to a directory on a remote machine

Args:
        - local_source (string): Path
        - remote_dir (string): Remote path

Returns:
        - str: Path to copied file on remote machine

Raises:
        - BadScriptPath : if script path on the remote side is bad
        - BadPermsScriptPath : You do not have perms to make the channel script dir
        - FileCopyException : FileCopy failed.


def record(self):
        # type: () -> bytes

        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('TF record not yet initialized!')

        outlist = [b'TF', struct.pack('=BBB', RRTFRecord.length(self.time_flags), SU_ENTRY_VERSION, self.time_flags)]
        for fieldname in self.FIELDNAMES:
            field = getattr(self, fieldname)
            if field is not None:
                outlist.append(field.record())

        return b''.join(outlist)

Generate a string representing the Rock Ridge Time Stamp record.

    Parameters:
    None.

Returns:
    String containing the Rock Ridge record.


def accuracy_score(gold, pred, ignore_in_gold=[], ignore_in_pred=[]):

    gold, pred = _preprocess(gold, pred, ignore_in_gold, ignore_in_pred)

    if len(gold) and len(pred):
        acc = np.sum(gold == pred) / len(gold)
    else:
        acc = 0

    return acc

Calculate (micro) accuracy.

Args:
        gold: A 1d array-like of gold labels
        pred: A 1d array-like of predicted labels (assuming abstain = 0)
        ignore_in_gold: A list of labels for which elements having that gold
            label will be ignored.
        ignore_in_pred: A list of labels for which elements having that pred
            label will be ignored.

Returns:
        A float, the (micro) accuracy score


def mahalanobis_distances(df, axis=0):

    df = df.transpose() if axis == 1 else df
    means = df.mean()
    try:
        inv_cov = np.linalg.inv(df.cov())
    except LinAlgError:
        return pd.Series([np.NAN] * len(df.index), df.index,
                         name='Mahalanobis')
    dists = []
    for i, sample in df.iterrows():
        dists.append(mahalanobis(sample, means, inv_cov))

    return pd.Series(dists, df.index, name='Mahalanobis')

Returns a pandas Series with Mahalanobis distances for each sample on the
    axis.

    Note: does not work well when # of observations < # of dimensions
    Will either return NaN in answer
    or (in the extreme case) fail with a Singular Matrix LinAlgError

Args:
        df: pandas DataFrame with columns to run diagnostics on
        axis: 0 to find outlier rows, 1 to find outlier columns


def to_file(self, fp, format_, fps=None, **kwargs):

        impl = get_format_class(format_)
        impl.to_file(self, fp, format_, fps=fps, **kwargs)

Write subtitle file to file object.

    See :meth:`SSAFile.save()` for full description.

Note:
        This is a low-level method. Usually, one of :meth:`SSAFile.save()`
        or :meth:`SSAFile.to_string()` is preferable.

Args:
        fp (file object): A file object, ie. :class:`io.TextIOBase` instance.
            Note that the file must be opened in text mode (as opposed to binary).


def qualNormGaussian(data, qualitative):

    genes, cells = data.shape
    clusters = qualitative.shape[1]
    output = np.zeros((genes, clusters))
    missing_indices = []
    qual_indices = []
    for i in range(genes):
        if qualitative[i,:].max() == -1 and qualitative[i,:].min() == -1:
            missing_indices.append(i)
            continue
        qual_indices.append(i)
        threshold = (qualitative[i,:].max() - qualitative[i,:].min())/2.0
        kmeans = KMeans(n_clusters = 2).fit(data[i,:].reshape((1, cells)))
        assignments = kmeans.labels_
        means = kmeans.cluster_centers_
        high_mean = means.max()
        low_mean = means.min()
        for k in range(clusters):
            if qualitative[i,k]>threshold:
                output[i,k] = high_mean
            else:
                output[i,k] = low_mean
    if missing_indices:
        #generating centers for missing indices
        M_init = output[qual_indices, :]
        kmeans = KMeans(n_clusters = 2, init = M_init, max_iter = 1).fit(data[qual_indices, :])
        assignments = kmeans.labels_
        #assignments, means = poisson_cluster(data[qual_indices, :], clusters, output[qual_indices, :], max_iters=1)
        for ind in missing_indices:
            for k in range(clusters):
                output[ind, k] = np.mean(data[ind, assignments==k])
    # TODO: assign to closest
    return output

Generates starting points using binarized data. If qualitative data is missing for a given gene, all of its entries should be -1 in the qualitative matrix.

Args:
        data (array): 2d array of genes x cells
        qualitative (array): 2d array of numerical data - genes x clusters

Returns:
        Array of starting positions for state estimation or
        clustering, with shape genes x clusters


def set_target(self, target: EventDispatcherBase) -> None:

        if self._target is not None:
            raise PermissionError("The target property already has a valid value.")

        if not isinstance(target, EventDispatcherBase):
            raise TypeError("Invalid target type: {}".format(target))

        self._target = target

This method should be called by the event dispatcher that dispatches this event
    to set its target property.

Args:
        target (EventDispatcherBase): The event dispatcher that will dispatch this event.

Raises:
        PermissionError: If the target property of the event has already been set.
        TypeError: If `target` is not an `EventDispatcherBase` instance.


def remove_duplicate_sg(security_groups):

    for each_sg, duplicate_sg_name in SECURITYGROUP_REPLACEMENTS.items():
        if each_sg in security_groups and duplicate_sg_name in security_groups:
            LOG.info('Duplicate SG found. Removing %s in favor of %s.', duplicate_sg_name, each_sg)
            security_groups.remove(duplicate_sg_name)

    return security_groups

Removes duplicate Security Groups that share a same name alias

Args:
        security_groups (list): A list of security group id to compare against SECURITYGROUP_REPLACEMENTS

Returns:
        security_groups (list): A list of security groups with duplicate aliases removed


def _parse_batch_lastlog(last_log):

        regexp = re.compile('(-?[0-9]\d*):\W+(.*)')

        wrong_commands = list()
        for line in last_log:
            result = regexp.match(line)
            if result is not None:
                status_code = result.group(1)
                command = result.group(2)
                if int(status_code) < 0:
                    wrong_commands.append((status_code, command))

        return wrong_commands

This static method will help reading the result of the commit, command by command.

Args:
        last_log(list): A list containing, line by line, the result of committing the changes.

Returns:
        A list of tuples that went wrong. The tuple will contain (*status_code*, *command*)


def run(self, timeout=-1):

        def target():
            self.process = subprocess.Popen(self.cmd,
                                            stdout=self.stdout_dest,
                                            stderr=self.stderr_dest,
                                            shell=self.shell)
            stdout, stderr = self.process.communicate()

            # Decode output if the user wants, and if there is any.
            if self.decode_out:
                if stdout:
                    self.stdout = stdout.decode("utf-8")
                if stderr:
                    self.stderr = stderr.decode("utf-8")

        thread = threading.Thread(target=target)
        thread.start()

        if timeout > 0:
            thread.join(timeout)
            if thread.is_alive():
                self.process.terminate()
                thread.join()
                raise SubprocessError(("Reached timeout after {t} seconds"
                                       .format(t=timeout)))
        else:
            thread.join()

        return self.process.returncode, self.stdout, self.stderr

Run the subprocess.

Args:
        timeout (optional) If a positive real value, then timout after
            the given number of seconds.

Raises:
        SubprocessError If subprocess has not completed after "timeout"
            seconds.


def search_users(self, user):

        user_url = "%s/%s/%s" % (self.url, "user", user)
        response = self.jss.get(user_url)
        return LDAPUsersResults(self.jss, response)

Search for LDAP users.

Args:
        user: User to search for. It is not entirely clear how the
            JSS determines the results- are regexes allowed, or
            globbing?

Returns:
        LDAPUsersResult object.

Raises:
        Will raise a JSSGetError if no results are found.


def set_hash_value(self, key, field, value, pipeline=False):

        # FIXME(BMo): new name for this function -> save_dict_value ?
        if pipeline:
            self._pipeline.hset(key, field, str(value))
        else:
            self._db.hset(key, field, str(value))

Set the value of field in a hash stored at key.

Args:
        key (str): key (name) of the hash
        field (str): Field within the hash to set
        value: Value to set
        pipeline (bool): True, start a transaction block. Default false.


def to_wea(self, file_path, hoys=None):

        hoys = hoys or xrange(len(self.direct_normal_radiation.datetimes))
        if not file_path.lower().endswith('.wea'):
            file_path += '.wea'

        originally_ip = False
        if self.is_ip is True:
            self.convert_to_si()
            originally_ip = True

        # write header
        lines = [self._get_wea_header()]
        # write values
        datetimes = self.direct_normal_radiation.datetimes
        for hoy in hoys:
            dir_rad = self.direct_normal_radiation[hoy]
            dif_rad = self.diffuse_horizontal_radiation[hoy]
            line = "%d %d %.3f %d %d\n" \
                % (datetimes[hoy].month,
                   datetimes[hoy].day,
                   datetimes[hoy].hour + 0.5,
                   dir_rad, dif_rad)
            lines.append(line)

        file_data = ''.join(lines)
        write_to_file(file_path, file_data, True)

        if originally_ip is True:
            self.convert_to_ip()

        return file_path

Write an wea file from the epw file.

    WEA carries radiation values from epw. Gendaymtx uses these values to
    generate the sky. For an annual analysis it is identical to using epw2wea.

Args:
        file_path: Full file path for output file.
        hoys: List of hours of the year. Default is 0-8759.


def _get_and_write_fp(self, iso_path, outfp, blocksize):
        # type: (bytes, BinaryIO, int) -> None

        try:
            return self._get_file_from_iso_fp(outfp, blocksize, None, None, iso_path)
        except pycdlibexception.PyCdlibException:
            pass

        try:
            return self._get_file_from_iso_fp(outfp, blocksize, iso_path, None, None)
        except pycdlibexception.PyCdlibException:
            pass

        self._get_file_from_iso_fp(outfp, blocksize, None, iso_path, None)

An internal method to fetch a single file from the ISO and write it out
    to the file object.

    Parameters:
    iso_path - The absolute path to the file to get data from.
    outfp - The file object to write data to.
    blocksize - The blocksize to use when copying data.

Returns:
    Nothing.


def _ParseMRUListValue(self, registry_key):

    mrulist_value = registry_key.GetValueByName('MRUList')

    # The key exists but does not contain a value named "MRUList".
    if not mrulist_value:
      return None

    mrulist_entries_map = self._GetDataTypeMap('mrulist_entries')

    context = dtfabric_data_maps.DataTypeMapContext(values={
        'data_size': len(mrulist_value.data)})

    return self._ReadStructureFromByteStream(
        mrulist_value.data, 0, mrulist_entries_map, context=context)

Parses the MRUList value in a given Registry key.

Args:
        registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains
        the MRUList value.

Returns:
        mrulist_entries: MRUList entries or None if not available.


def get(self, position=0):

        n = len(self)
        if n == 1:
            return self[0]

        pos = position

        if self.length and self.autoscale:
            pos *= len(self)
            pos /= self.length

        pos *= self.scale
        pos += self.offset

        if not self.continuous:
            if not self.serpentine:
                return self[int(pos % n)]

            # We want a color sequence of length 2n-2
            # e.g. for n=5: a b c d | e d c b | a b c d ...
            m = (2 * n) - 2
            pos %= m
            if pos < n:
                return self[int(pos)]
            else:
                return self[int(m - pos)]

        if self.serpentine:
            pos %= (2 * n)
            if pos > n:
                pos = (2 * n) - pos
        else:
            pos %= n

        # p is a number in [0, n): scale it to be in [0, n-1)
        pos *= n - 1
        pos /= n

        index = int(pos)
        fade = pos - index
        if not fade:
            return self[index]

        r1, g1, b1 = self[index]
        r2, g2, b2 = self[(index + 1) % len(self)]
        dr, dg, db = r2 - r1, g2 - g1, b2 - b1

        return r1 + fade * dr, g1 + fade * dg, b1 + fade * db

Return a color interpolated from the Palette.

    In the case where continuous=False, serpentine=False, scale=1,
    autoscale=False, and offset=0, this is exactly the same as plain old []
    indexing, but with a wrap-around.

    The constructor parameters affect this result as documented in the
    constructor.

Args:
        ``position``:
        May be any integer or floating point number


def watchlist_movies(self, **kwargs):

        path = self._get_id_path('watchlist_movies')
        kwargs.update({'session_id': self.session_id})

        response = self._GET(path, kwargs)
        self._set_attrs_to_values(response)
        return response

Get the list of movies on an account watchlist.

Args:
        page: (optional) Minimum 1, maximum 1000.
        sort_by: (optional) 'created_at.asc' | 'created_at.desc'
        language: (optional) ISO 639-1 code.

Returns:
        A dict respresentation of the JSON returned from the API.


def FileEntryExistsByPathSpec(self, path_spec):

    # All checks for correct path spec is done in SQLiteBlobFile.
    # Therefore, attempt to open the path specification and
    # check if errors occurred.
    try:
      file_object = resolver.Resolver.OpenFileObject(
          path_spec, resolver_context=self._resolver_context)
    except (IOError, ValueError, errors.AccessError, errors.PathSpecError):
      return False

    file_object.close()
    return True

Determines if a file entry for a path specification exists.

Args:
        path_spec (PathSpec): path specification.

Returns:
        bool: True if the file entry exists.


def make_noise_surface(dims=DEFAULT_DIMS, blur=10, seed=None):

    if seed is not None:
        np.random.seed(seed)

    return gaussian_filter(np.random.normal(size=dims), blur)

Makes a surface by generating random noise and blurring it.

Args:
        dims (pair): the dimensions of the surface to create
        blur (float): the amount of Gaussian blur to apply
        seed (int): a random seed to use (optional)

Returns:
        surface: A surface.


def learn_sfa(self, mma=None):

        logging.info('Initializing learning procedure.')
        if mma:
            self._init_table_from_dfa(mma)
        else:
            self._init_table()

        logging.info('Generating a closed and consistent observation table.')
        while True:

            closed = False
            # Make sure that the table is closed
            while not closed:
                logging.debug('Checking if table is closed.')
                closed, s = self.observation_table.is_closed()
                if not closed:
                    logging.debug('Closing table.')
                    self._ot_make_closed(s)
                else:
                    logging.debug('Table closed.')

            # Create conjecture
            sfa = self.get_sfa_conjecture()

            logging.info('Generated conjecture machine with %d states.',
                         len(list(sfa.states)))

            # _check correctness
            logging.debug('Running equivalence query.')
            found, counter_example = self._equivalence_query(sfa)

            # Are we done?
            if found:
                logging.info('No counterexample found. Hypothesis is correct!')
                break

            # Add the new experiments into the table to reiterate the
            # learning loop
            logging.info(
                'Processing counterexample %s with length %d.',
                counter_example,
                len(counter_example))
            self._process_counter_example(sfa, counter_example)

        logging.info('Learning complete.')
        return '', sfa

Implements the high level loop of the algorithm for learning a
    Mealy machine.

Args:
        mma:

Returns:
        MealyMachine: A model for the Mealy machine to be learned.


def get_placeholders(arg, check_duplicates=False):

    placeholders = []
    last_match = None
    arg = normalize_placeholders(arg)
    for cur_match in re.finditer(r'\s*{{|}}\s*', arg):
        matched_text = cur_match.group().strip()
        if not last_match and matched_text == '{{':
            last_match = cur_match
            continue

        last_matched_text = '' if not last_match else last_match.group().strip()
        # Check if the positional argument is enclosed with {{ }} properly
        if (not last_matched_text and matched_text == '}}') or (last_matched_text == '{{' and matched_text != '}}'):
            raise CLIError(PLACEHOLDER_BRACKETS_ERROR.format(arg))
        elif last_matched_text == '{{' and matched_text == '}}':
            # Extract start and end index of the placeholder name
            start_index, end_index = last_match.span()[1], cur_match.span()[0]
            placeholders.append(arg[start_index: end_index].strip())
            last_match = None

    # last_match did not reset - that means brackets are not enclosed properly
    if last_match:
        raise CLIError(PLACEHOLDER_BRACKETS_ERROR.format(arg))

    # Make sure there is no duplicated placeholder names
    if check_duplicates and len(placeholders) != len(set(placeholders)):
        raise CLIError(DUPLICATED_PLACEHOLDER_ERROR.format(arg))

    return placeholders

Get all the placeholders' names in order.
    Use the regex below to locate all the opening ({{) and closing brackets (}}).
    After that, extract "stuff" inside the brackets.

Args:
        arg: The word which this function performs searching on.
        check_duplicates: True if we want to check for duplicated positional arguments.

Returns:
        A list of positional arguments in order.


def search(self,limit,start_date=None,end_date=None,clipper=None):

        search_string = self._query_builder(start_date,
                                            end_date,
                                            clipper
                                            )

        # Have to manually build the URI to bypass requests URI encoding
        # The api server doesn't accept encoded URIs
        #r = requests.get('%s?%s&&maxRecords=%s' % (self.api_url,
        #                                            search_string,
        #                                            limit))

        try:
            r = requests.get('%s?%s&&maxRecords=%s' % (self.api_url,
                                                    search_string,
                                                    limit))
            r.raise_for_status()
        except requests.HTTPError, e:
            exit ("site is not available")

        r_dict = json.loads(r.text)

        result={}

        if  (r_dict['features'] == 0):
            result['status'] = u'error'
            result['message'] = "error while loading datas"

        else:
            result['status'] = u'SUCCESS'
            result['total'] = len(r_dict['features'])
            result['limit'] = limit
            result['ID']=[i['id'] for i in r_dict['features']]
            result['downloads']=[{"download" : i['properties']['services']['download']['url'],
                                 "id" : i['id']}
                                  for i in r_dict['features']]
            result['results'] = {
                                "features": [{
                                  'properties':{'sceneID': i['id'],
                                  'sat_type': i['properties']['platform'],
                                  'thumbnail': i['properties']['thumbnail'],
                                  'date': i['properties']['completionDate'],
                                  'download': i['properties']['services']['download']['url']}
                                  ,
                                  'geometry': i['geometry'],
                                  "type": "Feature"}
                                 for i in r_dict['features']],
                                 "type": "FeatureCollection"
                                 }

        return result

The main method of Search class. It searches tTheia Landsat API
    Returns python dictionary

Args:
        start_date -- date string. format: YYYY-MM-DD
        end_date -- date string. format: YYYY-MM-DD
        limit -- integer specigying the maximum results return.
        clipper -- clipper object : clipper.bbox / clipper.town


def __init__(self, executable_path: _PATH = 'default', port: Union[int, str] = 5037, env: Dict = None, service_args: Union[list, tuple] = None) -> None:

        self._service_args = service_args or []

        super(Service, self).__init__(executable_path, port=port, env=env)

Creates a new instance of the Service.

Args:
        executable_path: Path to the AndroidDriver.
        port: Port the service is running on.
        env: Environment variables.
        service_args: List of args to pass to the androiddriver service.


def mapIdentityResponse(
        self, primarySubject, secondarySubject, vendorSpecific=None
    ):

        mmp_dict = {
            'primarySubject': primarySubject.toxml('utf-8'),
            'secondarySubject': secondarySubject.toxml('utf-8'),
        }
        return self.POST(['accounts', 'map'], fields=mmp_dict, headers=vendorSpecific)

CNIdentity.mapIdentity(session, subject) → boolean
    https://releases.dataone.org/online/api-
    documentation-v2.0.1/apis/CN_APIs.html#CNIdentity.mapIdentity.

Args:
        primarySubject:
        secondarySubject:
        vendorSpecific:

    Returns:


def activate(self, experiment_key, user_id, attributes=None):

    if not self.is_valid:
      self.logger.error(enums.Errors.INVALID_DATAFILE.format('activate'))
      return None

    if not validator.is_non_empty_string(experiment_key):
      self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('experiment_key'))
      return None

    if not isinstance(user_id, string_types):
      self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('user_id'))
      return None

    variation_key = self.get_variation(experiment_key, user_id, attributes)

    if not variation_key:
      self.logger.info('Not activating user "%s".' % user_id)
      return None

    experiment = self.config.get_experiment_from_key(experiment_key)
    variation = self.config.get_variation_from_key(experiment_key, variation_key)

    # Create and dispatch impression event
    self.logger.info('Activating user "%s" in experiment "%s".' % (user_id, experiment.key))
    self._send_impression_event(experiment, variation, user_id, attributes)

    return variation.key

Buckets visitor and sends impression event to Optimizely.

Args:
        experiment_key: Experiment which needs to be activated.
        user_id: ID for user.
        attributes: Dict representing user attributes and values which need to be recorded.

Returns:
        Variation key representing the variation the user will be bucketed in.
        None if user is not in experiment or if experiment is not Running.


def is_module_function(obj, prop):

    python_version = sys.version_info[0]
    if python_version == 3:
        unicode = str

    if prop and (isinstance(prop, str) or isinstance(prop, unicode)): #property
        if prop in dir(obj):
            if (
                    isinstance(getattr(obj, prop), FunctionType)
                    or isinstance(getattr(obj, prop), BuiltinFunctionType)
                    or inspect.ismethod(getattr(obj, prop))
            ):
            #inspect.ismethod for python2.7
            #isinstance(...) for python3.x
                return True
            else:
                ErrorHandler.prop_is_func_error(obj, prop)
        else:
            ErrorHandler.prop_in_obj_error(obj, prop)
    elif prop:
        ErrorHandler.prop_type_error(prop)
    return False

Checking and setting type to MODULE_FUNCTION

Args:
        obj: ModuleType
        prop: FunctionType

Returns:
        Boolean

Raises:
        prop_type_error: When the type of prop is not valid
        prop_in_obj_error: When prop is not in the obj(module/class)
        prop_is_func_error: When prop is not a callable stuff


def __init__(self, resolver_context):

    super(OSFile, self).__init__(resolver_context)
    self._file_object = None
    self._size = 0

Initializes a file-like object.

Args:
        resolver_context (Context): resolver context.


def reconstruct_text(tokens: List[Token]) -> str:

        return "".join([x.text_with_ws for x in tokens])

Given a list of tokens, reconstruct the original text with as much fidelity as possible.

Args:
        [tokens]:

    Returns: a string.


def BalanceFor(self, assetId):

        for key, fixed8 in self.Balances.items():
            if key == assetId:
                return fixed8
        return Fixed8(0)

Get the balance for a given asset id.

Args:
        assetId (UInt256):

Returns:
        Fixed8: balance value.


def __live_receivers(signal):

    with __lock:
        __purge()
        receivers = [funcref() for funcref in __receivers[signal]]

    return receivers

Return all signal handlers that are currently still alive for the
    input `signal`.

Args:
        signal: A signal name.

Returns:
        A list of callable receivers for the input signal.


def get_service_name(self, service_id: str) -> str:

        # Raise an exception if we are not a manager
        if not self._manager:
            raise RuntimeError('Only the Swarm manager node can retrieve all'
                               ' the services details.')

        service = self._client.services.get(service_id)
        return service.name

Get the name of the docker service.

    Only the manager nodes can retrieve service name

Args:
        service_id (string): List of service ID

Returns:
        string, name of the docker service


def check_cmms_gender(self, ind_object):

        ind_id = ind_object.individual_id.split('-')
        sex = ind_object.sex
        sex_code = int(ind_id[-1][:-1])# Males allways have odd numbers and womans even
        if (sex_code % 2 == 0 and sex != 2) or (sex_code % 2 != 0 and sex != 1):
            raise WrongGender(ind_object.individual_id, sex, sex_code)

        return True

Check if the phenotype is correct.

Args:
        ind_object  : An Individuals object

Yields:
        bool : True if phenotype status is correct
                False otherwise


def data(self, rows=None):

    rows = tf.range(self._capacity) if rows is None else rows
    assert rows.shape.ndims == 1
    episode = tools.nested.map(lambda var: tf.gather(var, rows), self._buffers)
    length = tf.gather(self._length, rows)
    return episode, length

Access a batch of episodes from the memory.

    Padding elements after the length of each episode are unspecified and might
    contain old data.

Args:
        rows: Episodes to select, defaults to all.

Returns:
        Tuple containing a tuple of transition quantities with batch and time
        dimensions, and a batch of sequence lengths.


def yesno(question, default=None):

    if default is not None:
        if isinstance(default, bool):
            pass
        else:
            default_ = default.upper()
            if default_ not in ('Y', 'YES', 'N', 'NO'):
                raise RuntimeError("Invalid default value: '{}'".format(default))
            default = default_ in ('Y', 'YES')

    while True:
        ans = input("{} ({}/{})? ".format(question, "Y" if default == True else "y",
                                         "N" if default == False else "n")).upper()
        if ans == "" and default is not None:
            ret = default
            break
        elif ans in ("N", "NO"):
            ret = False
            break
        elif ans in ("Y", "YES"):
            ret = True
            break
    return ret

Asks a yes/no question

Args:
        question: string **without** the question mark and without the options.
            Example: 'Create links'
        default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions of
            these valus (this argument is case-insensitive)

Returns:
        bool: True if user answered Yes, False otherwise


def add_filter(self, name, operator, value):

        self._filters.append({'name': name, 'operator': operator, 'value': value})

Add ThreatConnect API Filter for this resource request.

    External Reference:
        https://docs.threatconnect.com

Args:
        name (string): The filter field name.
        operator (string): The filter comparison operator.
        value (string): The filter value.


def from_json(cls, data):

        assert 'name' in data, 'Required keyword "name" is missing!'
        assert 'data_type' in data, 'Required keyword "data_type" is missing!'
        if cls._type_enumeration is None:
            cls._type_enumeration = _DataTypeEnumeration(import_modules=False)

        if data['data_type'] == 'GenericType':
            assert 'base_unit' in data, \
                'Keyword "base_unit" is missing and is required for GenericType.'
            return cls._type_enumeration._GENERICTYPE(data['name'], data['base_unit'])
        elif data['data_type'] in cls._type_enumeration._TYPES:
            clss = cls._type_enumeration._TYPES[data['data_type']]
            if data['data_type'] == data['name'].title().replace(' ', ''):
                return clss()
            else:
                instance = clss()
                instance._name = data['name']
                return instance
        else:
            raise ValueError(
                'Data Type {} could not be recognized'.format(data['data_type']))

Create a data type from a dictionary.

Args:
        data: Data as a dictionary.
            {
                "name": data type name of the data type as a string
                "data_type": the class name of the data type as a string
                "base_unit": the base unit of the data type
            }


def _handle_error_response(response_body):

    try:
        error_data = json.loads(response_body)
        error_details = '{}: {}'.format(
            error_data['error'],
            error_data.get('error_description'))
    # If no details could be extracted, use the response data.
    except (KeyError, ValueError):
        error_details = response_body

    raise exceptions.RefreshError(
        error_details, response_body)

Translates an error response into an exception.

Args:
        response_body (str): The decoded response data.

Raises:
        google.auth.exceptions.RefreshError


def convert_to_uri(self, value, strip_iri=True):

        parsed = self.parse_uri(str(value))

        try:
            new_uri = "%s%s" % (self.ns_dict[parsed[0]], parsed[1])
            if not strip_iri:
                return self.iri(new_uri)
            return new_uri
        except KeyError:
            return self.rpyhttp(value)

converts a prefixed rdf ns equivalent value to its uri form.
    If not found returns the value as is

Args:
        value: the URI/IRI to convert
        strip_iri: removes the < and > signs
        rdflib_uri: returns an rdflib URIRef


def wait(self, timeout=None):

    poll = 30
    while not self._is_complete:
      try:
        query_result = self._api.jobs_query_results(self._job_id,
                                                    project_id=self._context.project_id,
                                                    page_size=0,
                                                    timeout=poll * 1000)
      except Exception as e:
        raise e
      if query_result['jobComplete']:
        if 'totalBytesProcessed' in query_result:
          self._bytes_processed = int(query_result['totalBytesProcessed'])
        self._cache_hit = query_result.get('cacheHit', None)
        if 'totalRows' in query_result:
          self._total_rows = int(query_result['totalRows'])
        break

      if timeout is not None:
        timeout -= poll
        if timeout <= 0:
          break

    self._refresh_state()
    return self

Wait for the job to complete, or a timeout to happen.

    This is more efficient than the version in the base Job class, in that we can
    use a call that blocks for the poll duration rather than a sleep. That means we
    shouldn't block unnecessarily long and can also poll less.

Args:
    timeout: how long to wait (in seconds) before giving up; default None which means no timeout.

Returns:
    The QueryJob


def QA_fetch_user(user_cookie, db=DATABASE):

    collection = DATABASE.account

    return [res for res in collection.find({'user_cookie': user_cookie}, {"_id": 0})]

get the user

Args:
        user_cookie : str the unique cookie_id for a user
    Keyword Arguments:
        db: database for query

Returns:
        list ---  [ACCOUNT]


def execute(mp):

    # Reading and writing data works like this:
    with mp.open("file1", resampling="bilinear") as raster_file:
        if raster_file.is_empty():
            return "empty"
            # This assures a transparent tile instead of a pink error tile
            # is returned when using mapchete serve.
        dem = raster_file.read()
    return dem

Example process for testing.

    Inputs:
    -------
    file1
        raster file

    Parameters:
    -----------

    Output:
    -------
    np.ndarray


def _lookup_global(self, symbol):

        assert symbol.parts
        namespace = self.namespaces
        if len(symbol.parts) == 1:
            # If there is only one part, look in globals.
            namespace = self.namespaces[None]
        try:
            # Try to do a normal, global namespace lookup.
            return self._lookup_namespace(symbol, namespace)
        except Error as orig_exc:
            try:
                # The normal lookup can fail if all of the parts aren't
                # namespaces. This happens with OuterClass::Inner.
                namespace = self.namespaces[None]
                return self._lookup_namespace(symbol, namespace)
            except Error:
                raise orig_exc

Helper for lookup_symbol that only looks up global variables.

Args:
        symbol: Symbol


def get_clinvar_submission(store, institute_id, case_name, variant_id, submission_id):

    institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
    pinned = [store.variant(variant_id) or variant_id for variant_id in
                  case_obj.get('suspects', [])]
    variant_obj = store.variant(variant_id)
    clinvar_submission_objs = store.clinvars(submission_id=submission_id)
    return dict(
        today = str(date.today()),
        institute=institute_obj,
        case=case_obj,
        variant=variant_obj,
        pinned_vars=pinned,
        clinvars = clinvar_submission_objs
    )

Collects all variants from the clinvar submission collection with a specific submission_id

Args:
        store(scout.adapter.MongoAdapter)
        institute_id(str): Institute ID
        case_name(str): case ID
        variant_id(str): variant._id
        submission_id(str): clinvar submission id, i.e. SUB76578

Returns:
        A dictionary with all the data to display the clinvar_update.html template page


def add_answer(self, vote, rationale):

        self.raw_answers.append({
            VOTE_KEY: vote,
            RATIONALE_KEY: rationale,
        })

Add an answer

Args:
        vote (int): the option that student voted for
        rationale (str): the reason why the student vote for the option


def dict_from_items_with_values(*dictionaries, **items):

    dict_list = list(dictionaries)
    dict_list.append(items)
    result = {}
    for d in dict_list:
        for key, value in d.items():
            if value is not None:
                result[key] = value
    return result

Creates a dict with the inputted items; pruning any that are `None`.

Args:
        *dictionaries(dict): Dictionaries of items to be pruned and included.
        **items: Items to be pruned and included.

Returns:
        dict: A dictionary containing all of the items with a 'non-None' value.


def get_access_token(self, code):

        payload = {'redirect_uri': self.redirect_uri,
                   'code': code,
                   'grant_type': 'authorization_code'}

        headers = self._make_authorization_headers()

        response = requests.post(self.OAUTH_TOKEN_URL, data=payload,
            headers=headers, verify=LOGIN_VERIFY_SSL_CERT)
        if response.status_code is not 200:
            raise MercedesMeAuthError(response.reason)
        token_info = response.json()
        token_info = self._add_custom_values_to_token_info(token_info)
        self._save_token_info(token_info)
        return token_info

Gets the access token for the app given the code

    Parameters:
        - code - the response code


def ExpandGroups(path):

  precondition.AssertType(path, Text)

  chunks = []
  offset = 0

  for match in PATH_GROUP_REGEX.finditer(path):
    chunks.append([path[offset:match.start()]])
    chunks.append(match.group("alts").split(","))
    offset = match.end()

  chunks.append([path[offset:]])

  for prod in itertools.product(*chunks):
    yield "".join(prod)

Performs group expansion on a given path.

    For example, given path `foo/{bar,baz}/{quux,norf}` this method will yield
    `foo/bar/quux`, `foo/bar/norf`, `foo/baz/quux`, `foo/baz/norf`.

Args:
        path: A path to expand.

Yields:
        Paths that can be obtained from given path by expanding groups.


def ResultCollectionForFID(cls, flow_id):

    # TODO: Disallow/remove URNs after migration.
    if not isinstance(flow_id, rdfvalue.RDFURN):
      flow_id = rdfvalue.RDFURN(flow_id)

    return sequential_collection.GeneralIndexedCollection(
        flow_id.Add(RESULTS_SUFFIX))

Returns the ResultCollection for the flow with a given flow_id.

Args:
        flow_id: The id of the flow, a RDFURN of the form aff4:/flows/F:123456.

Returns:
        The collection containing the results for the flow identified by the id.


def _ParseComment(self, structure):

    if structure[1] == 'Date:':
      self._year, self._month, self._day_of_month, _, _, _ = structure.date_time
    elif structure[1] == 'Fields:':
      self._ParseFieldsMetadata(structure)

Parses a comment.

Args:
        structure (pyparsing.ParseResults): structure parsed from the log file.


def lazy(function, *args, **kwargs):

    NOT_EVALUATED = object()
    retval = [NOT_EVALUATED]

    def evaluate():
        if retval[0] is NOT_EVALUATED:
            retval[0] = function(*args, **kwargs)
        return retval[0]

    return evaluate

Produces a callable so that functions can be lazily evaluated in
    templates.

Args:
        function (callable): The function to call at evaluation time.

        args: Positional arguments, passed directly to ``function``.

        kwargs: Keyword arguments, passed directly to ``function``.

Returns:
        callable: A callable that will evaluate a call to ``function`` with
            the specified arguments.


def __init__(self, examples):

    self.config = {}
    self.set_examples(examples)
    self.set_model_type('classification')
    self.set_label_vocab([])

Constructs the WitConfigBuilder object.

Args:
        examples: A list of tf.Example or tf.SequenceExample proto objects.
        These are the examples that will be displayed in WIT. If not model to
        infer these examples with is specified through the methods on this class,
        then WIT will display the examples for exploration, but no model inference
        will be performed by the tool.


def init_logger(level, printout=True):

    root_logger = logging.getLogger("boussole")
    root_logger.setLevel(level)

    # Redirect outputs to the void space, mostly for usage within unittests
    if not printout:
        from io import StringIO
        dummystream = StringIO()
        handler = logging.StreamHandler(dummystream)
    # Standard output with colored messages
    else:
        handler = logging.StreamHandler()
        handler.setFormatter(
            colorlog.ColoredFormatter(
                '%(asctime)s - %(log_color)s%(message)s',
                datefmt="%H:%M:%S"
            )
        )

    root_logger.addHandler(handler)

    return root_logger

Initialize app logger to configure its level/handler/formatter/etc..

    Todo:
        * A mean to raise click.Abort or sys.exit when CRITICAL is used;

Args:
        level (str): Level name (``debug``, ``info``, etc..).

    Keyword Arguments:
        printout (bool): If False, logs will never be outputed.

Returns:
        logging.Logger: Application logger.


def call(self, inputs):

    del inputs  # unused
    with tf.compat.v1.name_scope(self._name):
      return tfd.MultivariateNormalDiag(self.loc, self.scale_diag)

Runs the model to generate multivariate normal distribution.

Args:
        inputs: Unused.

Returns:
        A MultivariateNormalDiag distribution with event shape
        [dimensions], batch shape [], and sample shape [sample_shape,
        dimensions].


def SetTimelineOwner(self, username):

    self._timeline_owner = username
    logger.info('Owner of the timeline: {0!s}'.format(self._timeline_owner))

Sets the username of the user that should own the timeline.

Args:
        username (str): username.


def RegisterHasher(cls, hasher_class):

    hasher_name = hasher_class.NAME.lower()
    if hasher_name in cls._hasher_classes:
      raise KeyError((
          'hasher class already set for name: {0:s}.').format(
              hasher_class.NAME))

    cls._hasher_classes[hasher_name] = hasher_class

Registers a hasher class.

    The hasher classes are identified based on their lower case name.

Args:
        hasher_class (type): class object of the hasher.

Raises:
        KeyError: if hasher class is already set for the corresponding name.


def SetFlushInterval(self, flush_interval):

    self._flush_interval = flush_interval
    logger.debug('Elasticsearch flush interval: {0:d}'.format(flush_interval))

Set the flush interval.

Args:
        flush_interval (int): number of events to buffer before doing a bulk
        insert.


def load_scout(adapter, config, ped=None, update=False):

    log.info("Check that the panels exists")
    if not check_panels(adapter, config.get('gene_panels', []),
                        config.get('default_gene_panels')):
        raise ConfigError("Some panel(s) does not exist in the database")
    case_obj = adapter.load_case(config, update=update)
    return case_obj

Load a new case from a Scout config.

Args:
        adapter(MongoAdapter)
        config(dict): loading info
        ped(Iterable(str)): Pedigree ingformation
        update(bool): If existing case should be updated


def zopen(filename, *args, **kwargs):

    if Path is not None and isinstance(filename, Path):
        filename = str(filename)

    name, ext = os.path.splitext(filename)
    ext = ext.upper()
    if ext == ".BZ2":
        if PY_VERSION[0] >= 3:
            return bz2.open(filename, *args, **kwargs)
        else:
            args = list(args)
            if len(args) > 0:
                args[0] = "".join([c for c in args[0] if c != "t"])
            if "mode" in kwargs:
                kwargs["mode"] = "".join([c for c in kwargs["mode"]
                                          if c != "t"])
            return bz2.BZ2File(filename, *args, **kwargs)
    elif ext in (".GZ", ".Z"):
        return gzip.open(filename, *args, **kwargs)
    else:
        return io.open(filename, *args, **kwargs)

This function wraps around the bz2, gzip and standard python's open
    function to deal intelligently with bzipped, gzipped or standard text
    files.

Args:
        filename (str/Path): filename or pathlib.Path.
        \*args: Standard args for python open(..). E.g., 'r' for read, 'w' for
            write.
        \*\*kwargs: Standard kwargs for python open(..).

Returns:
        File-like object. Supports with context.


def attach_socket(self, **kwargs):

        return self.client.api.attach_socket(self.id, **kwargs)

Like :py:meth:`attach`, but returns the underlying socket-like object
    for the HTTP request.

Args:
        params (dict): Dictionary of request parameters (e.g. ``stdout``,
            ``stderr``, ``stream``).
        ws (bool): Use websockets instead of raw HTTP.

Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.


def _compute_args(self, data=dict(), **kwargs):

        for name, remote_attribute in self._attributes.items():
            default_value = BambouConfig.get_default_attribute_value(self.__class__, name, remote_attribute.attribute_type)
            setattr(self, name, default_value)

        if len(data) > 0:
            self.from_dict(data)

        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)

Compute the arguments

    Try to import attributes from data.
    Otherwise compute kwargs arguments.

Args:
        data: a dict()
        kwargs: a list of arguments


def batch_insert(self, records, typecast=False):

        return self._batch_request(self.insert, records)

Calls :any:`insert` repetitively, following set API Rate Limit (5/sec)
    To change the rate limit use ``airtable.API_LIMIT = 0.2``
    (5 per second)

    >>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
    >>> airtable.batch_insert(records)

Args:
        records(``list``): Records to insert
        typecast(``boolean``): Automatic data conversion from string values.

Returns:
        records (``list``): list of added records


def apply(self, func, **kwargs):

        import dask

        # applies the func lazily
        delayed_call = self.delayed_call
        self.delayed_call = self.dask_obj
        return self.__class__(dask.delayed(func)(delayed_call, **kwargs))

Apply some callable function to the data in this partition.

    Note: It is up to the implementation how kwargs are handled. They are
        an important part of many implementations. As of right now, they
        are not serialized.

Args:
        func: The lambda to apply (may already be correctly formatted)

Returns:
        A new `BaseFramePartition` containing the object that has had `func`
        applied to it.


def _iterator(self, plugins, context):

        test = pyblish.logic.registered_test()

        for plug, instance in pyblish.logic.Iterator(plugins, context):
            if not plug.active:
                continue

            if instance is not None and instance.data.get("publish") is False:
                continue

            self.processing["nextOrder"] = plug.order

            if not self.is_running:
                raise StopIteration("Stopped")

            if test(**self.processing):
                raise StopIteration("Stopped due to %s" % test(
                    **self.processing))

            yield plug, instance

Yield next plug-in and instance to process.

Args:
        plugins (list): Plug-ins to process
        context (pyblish.api.Context): Context to process


def CaptureNamedVariable(self, name, value, depth, limits):

    if not hasattr(name, '__dict__'):
      name = str(name)
    else:  # TODO(vlif): call str(name) with immutability verifier here.
      name = str(id(name))
    self._total_size += len(name)

    v = (self.CheckDataVisiblity(value) or
         self.CaptureVariable(value, depth, limits))
    v['name'] = name
    return v

Appends name to the product of CaptureVariable.

Args:
        name: name of the variable.
        value: data to capture
        depth: nested depth of dictionaries and vectors so far.
        limits: Per-object limits for capturing variable data.

Returns:
        Formatted captured data as per Variable proto with name.


def install_requirements(self, path, index=None):

        cmd = 'install -r {0}'.format(path)
        if index:

            cmd = 'install --index-url {0} -r {1}'.format(index, path)

        self.pip(cmd)

Install packages from a requirements.txt file.

Args:
        path (str): The path to the requirements file.
        index (str): The URL for a pypi index to use.


def _get_register_specs(bit_labels):

    it = itertools.groupby(bit_labels, operator.itemgetter(0))
    for register_name, sub_it in it:
        yield register_name, max(ind[1] for ind in sub_it) + 1

Get the number and size of unique registers from bit_labels list.

Args:
        bit_labels (list): this list is of the form::

            [['reg1', 0], ['reg1', 1], ['reg2', 0]]

            which indicates a register named "reg1" of size 2
            and a register named "reg2" of size 1. This is the
            format of classic and quantum bit labels in qobj
            header.

Yields:
        tuple: iterator of register_name:size pairs.


def VerifyRow(self, parser_mediator, row):

    if len(row) < self.MIN_COLUMNS:
      return False

    # Check the date format!
    # If it doesn't parse, then this isn't a Trend Micro AV log.
    try:
      timestamp = self._ConvertToTimestamp(row['date'], row['time'])
    except (ValueError, TypeError):
      return False

    if timestamp is None:
      return False

    # Check that the action value is plausible.
    try:
      action = int(row['action'], 10)
    except (ValueError, TypeError):
      return False

    if action not in formatter.SCAN_RESULTS:
      return False
    return True

Verifies if a line of the file is in the expected format.

Args:
        parser_mediator (ParserMediator): mediates interactions between parsers
        and other components, such as storage and dfvfs.
        row (dict[str, str]): fields of a single row, as specified in COLUMNS.

Returns:
        bool: True if this is the correct parser, False otherwise.


def GetAPFSFileEntryByPathSpec(self, path_spec):

    # Opening a file by identifier is faster than opening a file by location.
    location = getattr(path_spec, 'location', None)
    identifier = getattr(path_spec, 'identifier', None)

    if identifier is not None:
      fsapfs_file_entry = self._fsapfs_volume.get_file_entry_by_identifier(
          identifier)
    elif location is not None:
      fsapfs_file_entry = self._fsapfs_volume.get_file_entry_by_path(location)
    else:
      raise errors.PathSpecError(
          'Path specification missing location and identifier.')

    return fsapfs_file_entry

Retrieves the APFS file entry for a path specification.

Args:
        path_spec (PathSpec): a path specification.

Returns:
        pyfsapfs.file_entry: file entry.

Raises:
        PathSpecError: if the path specification is missing location and
        identifier.


def register_hooked(self,
                        hooks,  # type: Union[Type[Hook], Sequence[Type[Hook]]]
                        func,  # type: Hooked
                        args_gen=None  # type: Optional[ArgsGen]
                        ):
        # type: (Type[Hook], Callable, Optional[Callable]) -> None

        if self.hooked is None:
            self.hooked = {}
        if args_gen is None:
            args_gen = getattr(func, "call_types", {}).keys
        if not isinstance(hooks, Sequence):
            hooks = [hooks]
        for hook_cls in hooks:
            self.hooked[hook_cls] = (func, args_gen)

Register func to be run when any of the hooks are run by parent

Args:
        hooks: A Hook class or list of Hook classes of interest
        func: The callable that should be run on that Hook
        args_gen: Optionally specify the argument names that should be
            passed to func. If not given then use func.call_types.keys


def to_string(cls, error_code):

        if error_code == cls.COMPARE_ERROR:
            return 'Error comparing flash content to programming data.'
        elif error_code == cls.PROGRAM_ERASE_ERROR:
            return 'Error during program/erase phase.'
        elif error_code == cls.VERIFICATION_ERROR:
            return 'Error verifying programmed data.'
        return super(JLinkFlashErrors, cls).to_string(error_code)

Returns the string message for the given ``error_code``.

Args:
        cls (JLinkFlashErrors): the ``JLinkFlashErrors`` 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 ParseOptions(self, options):

    # The extraction options are dependent on the data location.
    helpers_manager.ArgumentHelperManager.ParseOptions(
        options, self, names=['data_location'])

    self._ReadParserPresetsFromFile()

    # Check the list options first otherwise required options will raise.
    argument_helper_names = ['hashers', 'parsers', 'profiling']
    helpers_manager.ArgumentHelperManager.ParseOptions(
        options, self, names=argument_helper_names)

    self._ParseTimezoneOption(options)

    self.list_hashers = self._hasher_names_string == 'list'
    self.list_parsers_and_plugins = self._parser_filter_expression == 'list'
    self.list_profilers = self._profilers == 'list'

    self.show_info = getattr(options, 'show_info', False)
    self.show_troubleshooting = getattr(options, 'show_troubleshooting', False)

    if getattr(options, 'use_markdown', False):
      self._views_format_type = views.ViewsFactory.FORMAT_TYPE_MARKDOWN

    self.dependencies_check = getattr(options, 'dependencies_check', True)

    if (self.list_hashers or self.list_parsers_and_plugins or
        self.list_profilers or self.list_timezones or self.show_info or
        self.show_troubleshooting):
      return

    self._ParseInformationalOptions(options)

    argument_helper_names = [
        'artifact_definitions', 'artifact_filters', 'extraction',
        'filter_file', 'status_view', 'storage_file', 'storage_format',
        'text_prepend', 'yara_rules']
    helpers_manager.ArgumentHelperManager.ParseOptions(
        options, self, names=argument_helper_names)

    self._ParseLogFileOptions(options)

    self._ParseStorageMediaOptions(options)

    self._ParsePerformanceOptions(options)
    self._ParseProcessingOptions(options)

    if not self._storage_file_path:
      raise errors.BadConfigOption('Missing storage file option.')

    serializer_format = getattr(
        options, 'serializer_format', definitions.SERIALIZER_FORMAT_JSON)
    if serializer_format not in definitions.SERIALIZER_FORMATS:
      raise errors.BadConfigOption(
          'Unsupported storage serializer format: {0:s}.'.format(
              serializer_format))
    self._storage_serializer_format = serializer_format

    # TODO: where is this defined?
    self._operating_system = getattr(options, 'os', None)

    if self._operating_system:
      self._mount_path = getattr(options, 'filename', None)

    helpers_manager.ArgumentHelperManager.ParseOptions(
        options, self, names=['status_view'])

    self._enable_sigsegv_handler = getattr(options, 'sigsegv_handler', False)

    self._EnforceProcessMemoryLimit(self._process_memory_limit)

Parses the options.

Args:
        options (argparse.Namespace): command line arguments.

Raises:
        BadConfigOption: if the options are invalid.


def _request(self, resource, action, data=None, headers=None):

        url, httpmethod = res_to_url(resource, action)
        return self.ajax(url, httpmethod, data, headers)

Send request

Args:
        resource: resource
        action: action
        data: string or object which can be json.dumps
        headers: http headers


def __init__(self,
                 message: str,
                 status_code: int=None):

        super().__init__(message)
        if status_code is not None:
            self.status_code = status_code

初始化异常.

    Parameters:

        message (str): - 异常信息
        status_code (int): - 状态码


def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''):

    _, ext = os.path.splitext(filename)
    if ext != '.png':
        filename += '.png'

    gnuplot_cmds = \

    scr = _GnuplotScriptTemp(gnuplot_cmds)
    data = _GnuplotDataTemp(x, y)

    args_dict = {
        'filename': filename,
        'filename_data': data.name,
        'title': title,
        'x_label': x_label,
        'y_label': y_label
    }
    gnuplot(scr.name, args_dict)

Function to produce a general 2D plot.

Args:
        x (list): x points.
        y (list): y points.
        filename (str): Filename of the output image.
        title (str): Title of the plot.  Default is '' (no title).
        x_label (str): x-axis label.
        y_label (str): y-axis label.