def bin(values, bins, labels=None):

    bins = np.asarray(bins)
    if labels is None:
        labels = (bins[:-1] + np.diff(bins)/2.)
    else:
        labels = np.asarray(labels)
    dtype = 'float' if labels.dtype.kind == 'f' else 'O'
    binned = np.full_like(values, (np.nan if dtype == 'f' else None), dtype=dtype)
    for lower, upper, label in zip(bins[:-1], bins[1:], labels):
        condition = (values > lower) & (values <= upper)
        binned[np.where(condition)[0]] = label
    return binned

Bins data into declared bins

Bins data into declared bins. By default each bin is labelled
with bin center values but an explicit list of bin labels may be
defined.

Args:
values: Array of values to be binned
bins: List or array containing the bin boundaries
labels: List of labels to assign to each bin
If the bins are length N the labels should be length N-1

Returns:
Array of binned values


def __init__(self, module, dropout, weights=['weight_hh_l0']):

        super().__init__()
        self.module,self.weights,self.dropout = module,weights,dropout
        self._setup()

Default constructor for the WeightDrop module

Args:
module (torch.nn.Module): A pytorch layer being wrapped
dropout (float): a dropout value to apply
weights (list(str)): the parameters of the wrapped **module**
which should be fractionally dropped.


def has_permission(self, perm):

        return self.user.superuser or self.auth.has_permission(perm)

Checks if current user (or role) has the given permission.

Args:
perm: Permmission code or object.
Depends on the :attr:`~zengine.auth.auth_backend.AuthBackend` implementation.

Returns:
Boolean.


def get_angle(self, i: int, j: int, k: int) -> float:
    v1 = (self[i].coords - self[j].coords)
    v2 = (self[k].coords - self[j].coords)
    return get_angle(v1, v2, units='degrees')

Returns angle specified by three sites.

Args:
i: Index of first site.
j: Index of second site.
k: Index of third site.

Returns:
Angle in degrees.


def __init__(self, data_type_definition):

    super(DataTypeMap, self).__init__()
    self._data_type_definition = data_type_definition

Initializes a data type map.

Args:
data_type_definition (DataTypeDefinition): data type definition.

Raises:
FormatError: if the data type map cannot be determined from the data
type definition.


def send_message_for_lane_change(sender, **kwargs):
    current = kwargs['current']
    owners = kwargs['possible_owners']
    if ('lane_change_invite' in current.task_data):
        msg_context = current.task_data.pop('lane_change_invite')
    else:
        msg_context = DEFAULT_LANE_CHANGE_INVITE_MSG
    wfi = WFCache(current).get_instance()
    TaskInvitation.objects.filter(instance=wfi, role=current.role, wf_name=wfi.wf.name).delete()
    today = datetime.today()
    for recipient in owners:
        inv = TaskInvitation(instance=wfi, role=recipient, wf_name=wfi.wf.name, progress=30, start_date=today, finish_date=(today + timedelta(15)))
        inv.title = (current.task_data.get('INVITATION_TITLE') or wfi.wf.title)
        inv.save()
        try:
            recipient.send_notification(title=msg_context['title'], message=('%s %s' % (wfi.wf.title, msg_context['body'])), typ=1, url='', sender=sender)
        except:
            pass

Sends a message to possible owners of the current workflows
next lane.

Args:
**kwargs: ``current`` and ``possible_owners`` are required.
sender (User): User object


def add_case(self, case, update=False):
    existing_case = self.case(case)
    if (existing_case and (not update)):
        raise CaseError('Case {} already exists'.format(case['case_id']))
    if existing_case:
        self.db.case.find_one_and_replace({'case_id': case['case_id']}, case)
    else:
        self.db.case.insert_one(case)
    return case

Add a case to the case collection

If the case exists and update is False raise error.

Args:
db (MongoClient): A connection to the mongodb
case (dict): A case dictionary
update(bool): If existing case should be updated

Returns:
mongo_case_id(ObjectId)


def as_list(self):
    if (self._dims is None):
        raise ValueError('as_list() is not defined on an unknown TensorShape.')
    return [dim.value for dim in self._dims]

Returns a list of integers or `None` for each dimension.

Returns:
A list of integers or `None` for each dimension.

Raises:
ValueError: If `self` is an unknown shape with an unknown rank.


def show_plot(plot, width=PREVIEW_WIDTH, height=PREVIEW_HEIGHT):

    return SVG(data=plot_to_svg(plot, width, height))

Preview a plot in a jupyter notebook.

Args:
plot (list): the plot to display (list of layers)
width (int): the width of the preview
height (int): the height of the preview

Returns:
An object that renders in Jupyter as the provided plot


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

Convert compartment entry to YAML dict.

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


def job_tasks(self, job_name):
    try:
        job = self._cluster_spec[job_name]
    except KeyError:
        raise ValueError('No such job in cluster: %r' % job_name)
    ret = [None for _ in range(max(job.keys()) + 1)]
    for i, task in job.items():
        ret[i] = task
    return ret

Returns a mapping from task ID to address in the given job.

NOTE: For backwards compatibility, this method returns a list. If
the given job was defined with a sparse set of task indices, the
length of this list may not reflect the number of tasks defined in
this job. Use the `tf.train.ClusterSpec.num_tasks` method
to find the number of tasks defined in a particular job.

Args:
job_name: The string name of a job in this cluster.

Returns:
A list of task addresses, where the index in the list
corresponds to the task index of each task. The list may contain
`None` if the job was defined with a sparse set of task indices.

Raises:
ValueError: If `job_name` does not name a job in this cluster.


def AFF4Path(self, client_urn):
    if (not self.HasField('pathtype')):
        raise ValueError("Can't determine AFF4 path without a valid pathtype.")
    first_component = self[0]
    dev = first_component.path
    if first_component.HasField('offset'):
        dev += ':{}'.format((first_component.offset
    if ((len(self) > 1) and (first_component.pathtype == PathSpec.PathType.OS) and (self[1].pathtype == PathSpec.PathType.TSK)):
        result = [self.AFF4_PREFIXES[PathSpec.PathType.TSK], dev]
        start = 1
    else:
        result = [self.AFF4_PREFIXES[first_component.pathtype]]
        start = 0
    for p in self[start]:
        component = p.path
        if p.HasField('offset'):
            component += ':{}'.format((p.offset
        if p.HasField('stream_name'):
            component += (':' + p.stream_name)
        result.append(component)
    return client_urn.Add('/'.join(result))

Returns the AFF4 URN this pathspec will be stored under.

Args:
client_urn: A ClientURN.

Returns:
A urn that corresponds to this pathspec.

Raises:
ValueError: If pathspec is not of the correct type.


def _determine_hpp_url(self, platform, action):

        base_uri = settings.BASE_HPP_URL.format(platform)
        service = action + '.shtml'
        result = '/'.join([base_uri, service])
        return result

This returns the Adyen HPP endpoint based on the provided platform,
and action.

Args:
platform (str): Adyen platform, ie 'live' or 'test'.
action (str):   the HPP action to perform.
possible actions: select, pay, skipDetails, directory


def isfunc(x):
    return any([(inspect.isfunction(x) and (not asyncio.iscoroutinefunction(x))), (inspect.ismethod(x) and (not asyncio.iscoroutinefunction(x)))])

Returns `True` if the given value is a function or method object.

Arguments:
x (mixed): value to check.

Returns:
bool


def bruteVersionStr(self, valu):
    try:
        (valu, info) = self.core.model.type('it:semver').norm(valu)
        subs = info.get('subs')
        return (valu, subs)
    except s_exc.BadTypeValu:
        subs = s_version.parseVersionParts(valu)
        if (subs is None):
            raise s_exc.BadTypeValu(valu=valu, name='bruteVersionStr', mesg='Unable to brute force version parts out of the string')
        if subs:
            valu = s_version.packVersion(subs.get('major'), subs.get('minor', 0), subs.get('patch', 0))
            return (valu, subs)

Brute force the version out of a string.

Args:
valu (str): String to attempt to get version information for.

Notes:
This first attempts to parse strings using the it:semver normalization
before attempting to extract version parts out of the string.

Returns:
int, dict: The system normalized version integer and a subs dictionary.


def download(url):

    filepath = get_file(fname='tmp.zip', origin=url, extract=True)
    base_dir = os.path.dirname(filepath)
    weights_file = os.path.join(base_dir, 'weights.h5')
    params_file = os.path.join(base_dir, 'params.json')
    preprocessor_file = os.path.join(base_dir, 'preprocessor.pickle')

    return weights_file, params_file, preprocessor_file

Download a trained weights, config and preprocessor.

Args:
url (str): target url.


def supports_default_grad(t):
    if t.dtype == dtypes.resource:
        handle_data = resource_variable_ops.get_eager_safe_handle_data(t)
        if handle_data is None or not handle_data.is_set or len(handle_data.shape_and_type) != 1:
            return False
    return True

Whether tensor `t` supports creating a default gradient.

This function assumes that `t` is of a trainable type.

Args:
t: Tensor

Returns:
Bool


def process_module(self, mod_info, mod_ast):
    module_name = mod_info.module_name
    module = Module(module_name, mod_info.filename, mod_ast)
    self._resolver.allow_singletons = False
    module.ast = self._resolver.resolve_builtin_types(module.ast)
    self._modules[module_name] = module
    try:
        self._resolver.allow_singletons = True
        module.ast = self._resolve_external_and_local_types(module.ast)
        module.ast = self._resolver.resolve_builtin_types(module.ast)
        self._resolver.allow_singletons = False
        module.ast = module.ast.Visit(visitors.AdjustTypeParameters())
        module_map = {'': module.ast, module_name: module.ast}
        module.ast.Visit(visitors.FillInLocalPointers(module_map))
    except:
        del self._modules[module_name]
        raise
    if module_name:
        self.add_module_prefixes(module_name)
    return module.ast

Create a module from a loaded ast and save it to the loader cache.

Args:
mod_info: The metadata of the module being imported.
mod_ast: The pytd.TypeDeclUnit representing the module.

Returns:
The ast (pytd.TypeDeclUnit) as represented in this loader.


def round_to_nearest(dt, n_round_sec=1.0):
    ts = (ts_from_dt(strip_timezone(dt)) + (n_round_sec / 2.0))
    res = dt_from_ts((ts - (ts % n_round_sec)))
    return res.replace(tzinfo=dt.tzinfo)

Round datetime up or down to nearest divisor.

Round datetime up or down to nearest number of seconds that divides evenly by
the divisor.

Any timezone is preserved but ignored in the rounding.

Args:
dt: datetime

n_round_sec : int or float
Divisor for rounding

Examples:
- ``n_round_sec`` = 0.1: nearest 10th of a second.
- ``n_round_sec`` = 1: nearest second.
- ``n_round_sec`` = 30: nearest half minute.


def simplify_exprs(exprs, result_type, stop_term, skip_term):
    expr_set = set()
    for e in exprs:
        if e is stop_term:
            return stop_term
        elif e is skip_term:
            continue
        elif isinstance(e, result_type):
            expr_set = expr_set.union(e.exprs)
        else:
            expr_set.add(e)
    if len(expr_set) > 1:
        return result_type(expr_set)
    elif expr_set:
        return expr_set.pop()
    else:
        return skip_term

Simplify a set of subexpressions for a conjunction or disjunction.

Args:
exprs: An iterable. The subexpressions.
result_type: _And or _Or. The type of result (unless it simplifies down to
something simpler).
stop_term: FALSE for _And, TRUE for _Or. If this term is encountered, it
will be immediately returned.
skip_term: TRUE for _And, FALSE for _Or. If this term is encountered, it
will be ignored.

Returns:
A BooleanTerm.


def add_bonds(self, neighbors, center, color=None, opacity=None, radius=0.1):
    points = vtk.vtkPoints()
    points.InsertPoint(0, center.x, center.y, center.z)
    n = len(neighbors)
    lines = vtk.vtkCellArray()
    for i in range(n):
        points.InsertPoint((i + 1), neighbors[i].coords)
        lines.InsertNextCell(2)
        lines.InsertCellPoint(0)
        lines.InsertCellPoint((i + 1))
    pd = vtk.vtkPolyData()
    pd.SetPoints(points)
    pd.SetLines(lines)
    tube = vtk.vtkTubeFilter()
    if (vtk.VTK_MAJOR_VERSION <= 5):
        tube.SetInputConnection(pd.GetProducerPort())
    else:
        tube.SetInputData(pd)
    tube.SetRadius(radius)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(tube.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    if (opacity is not None):
        actor.GetProperty().SetOpacity(opacity)
    if (color is not None):
        actor.GetProperty().SetColor(color)
    self.ren.AddActor(actor)

Adds bonds for a site.

Args:
neighbors: Neighbors of the site.
center: The site in the center for all bonds.
color: Color of the tubes representing the bonds
opacity: Opacity of the tubes representing the bonds
radius: Radius of tube s representing the bonds


def _indexOfEndTag(istack):

    if len(istack) <= 0:
        return 0

    if not istack[0].isOpeningTag():
        return 0

    cnt = 0
    opener = istack[0]
    for index, el in enumerate(istack[1:]):
        if el.isOpeningTag() and \
           el.getTagName().lower() == opener.getTagName().lower():
            cnt += 1

        elif el.isEndTagTo(opener):
            if cnt == 0:
                return index + 1

            cnt -= 1

    return 0

Go through `istack` and search endtag. Element at first index is considered
as opening tag.

Args:
istack (list): List of :class:`.HTMLElement` objects.

Returns:
int: Index of end tag or 0 if not found.


def ListFileEntries(self, base_path_specs, output_writer):
    for base_path_spec in base_path_specs:
        file_system = resolver.Resolver.OpenFileSystem(base_path_spec)
        file_entry = resolver.Resolver.OpenFileEntry(base_path_spec)
        if (file_entry is None):
            logging.warning('Unable to open base path specification:\n{0:s}'.format(base_path_spec.comparable))
            return
        self._ListFileEntry(file_system, file_entry, '', output_writer)

Lists file entries in the base path specification.

Args:
base_path_specs (list[dfvfs.PathSpec]): source path specification.
output_writer (StdoutWriter): output writer.


def _kl_gamma_gamma(g0, g1, name=None):
    with ops.name_scope(name, 'kl_gamma_gamma', values=[g0.concentration, g0.rate, g1.concentration, g1.rate]):
        return (g0.concentration - g1.concentration) * math_ops.digamma(g0.concentration) + math_ops.lgamma(g1.concentration) - math_ops.lgamma(g0.concentration) + g1.concentration * math_ops.log(g0.rate) - g1.concentration * math_ops.log(g1.rate) + g0.concentration * (g1.rate / g0.rate - 1.0)

Calculate the batched KL divergence KL(g0 || g1) with g0 and g1 Gamma.

Args:
g0: instance of a Gamma distribution object.
g1: instance of a Gamma distribution object.
name: (optional) Name to use for created operations.
Default is "kl_gamma_gamma".

Returns:
kl_gamma_gamma: `Tensor`. The batchwise KL(g0 || g1).


def long_description():
    cwd = os.path.abspath(os.path.dirname(__file__))
    readme_path = os.path.join(cwd, 'README.md')
    if (not os.path.exists(readme_path)):
        return pylink.__long_description__
    try:
        import pypandoc
        return pypandoc.convert(readme_path, 'rst')
    except (IOError, ImportError):
        pass
    return open(readme_path, 'r').read()

Reads and returns the contents of the README.

On failure, returns the project long description.

Returns:
The project's long description.


def elevation(self, value=0.0):

        if value is not None:
            try:
                value = float(value)
            except ValueError:
                raise ValueError('value {} need to be of type float '
                                 'for field `elevation`'.format(value))
            if value < -1000.0:
                raise ValueError('value need to be greater or equal -1000.0 '
                                 'for field `elevation`')
            if value >= 9999.9:
                raise ValueError('value need to be smaller 9999.9 '
                                 'for field `elevation`')

        self._elevation = value

Corresponds to IDD Field `elevation`

Args:
value (float): value for IDD Field `elevation`
Unit: m
Default value: 0.0
value >= -1000.0
value < 9999.9
if `value` is None it will not be checked against the
specification and is assumed to be a missing value

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


def _format_line(headers, fields):
    assert (len(fields) == len(headers)), (fields, headers)
    fields = [(('%2.4f' % field) if isinstance(field, float) else str(field)) for field in fields]
    return '  '.join((((' ' * max(0, (len(header) - len(field)))) + field) for (header, field) in zip(headers, fields)))

Format a line of a table.

Arguments:
headers: A list of strings that are used as the table headers.
fields: A list of the same length as `headers` where `fields[i]` is
the entry for `headers[i]` in this row. Elements can be of
arbitrary types. Pass `headers` to print the header row.

Returns:
A pretty string.


def __recognize_union(self, node: yaml.Node, expected_type: Type) -> RecResult:
    logger.debug('Recognizing as a union')
    recognized_types = []
    message = ''
    union_types = generic_type_args(expected_type)
    logger.debug('Union types {}'.format(union_types))
    for possible_type in union_types:
        (recognized_type, msg) = self.recognize(node, possible_type)
        if (len(recognized_type) == 0):
            message += msg
        recognized_types.extend(recognized_type)
    recognized_types = list(set(recognized_types))
    if ((bool in recognized_types) and (bool_union_fix in recognized_types)):
        recognized_types.remove(bool_union_fix)
    if (len(recognized_types) == 0):
        return (recognized_types, message)
    elif (len(recognized_types) > 1):
        message = '{}{}Could not determine which of the following types this is: {}'.format(node.start_mark, os.linesep, recognized_types)
        return (recognized_types, message)
    return (recognized_types, '')

Recognize a node that we expect to be one of a union of types.

Args:
node: The node to recognize.
expected_type: Union[...something...]

Returns:
The specific type that was recognized, multiple, or none.


def _postprocess_flat_outputs(outputs):
    if outputs is None:
        outputs = tuple()
    if not isinstance(outputs, collections_abc.Sequence):
        outputs = (outputs,)
    outputs += (control_flow_ops.no_op(),)
    try:
        outputs = [o if isinstance(o, ops.Operation) else ops.convert_to_tensor(o) for o in outputs]
    except Exception as e:
        raise ValueError('XLA computation function return values must all either be Operations or convertible to Tensors. Got error: "%s"' % str(e))
    output_operations = [o for o in outputs if isinstance(o, ops.Operation)]
    output_tensors = [o for o in outputs if not isinstance(o, ops.Operation)]
    if outputs != output_tensors + output_operations:
        raise ValueError('XLA computation function must return zero or more Tensor values followed by zero or more Operations.')
    new_output_tensors = []
    for t in output_tensors:
        with ops.device(t.device if t.device else ''):
            new_output_tensors.append(array_ops.identity(t))
    return (new_output_tensors, output_operations)

Validates flat outputs and adds back device assignments.

Args:
outputs: Output from `computation` inside `xla.compile`.

Returns:
Tensors and Operations extracted from outputs.


def _MaxPoolGrad(self, orig_input, orig_output, grad, window_rows, window_cols, row_stride, col_stride, padding, v2):
    pool_func = gen_nn_ops.max_pool_grad_v2 if v2 else gen_nn_ops.max_pool_grad
    if v2:
        return pool_func(orig_input, orig_output, grad, [1, window_rows, window_cols, 1], [1, row_stride, col_stride, 1], padding)
    else:
        padding, explicit_paddings = nn_ops.convert_padding(padding)
        return pool_func(orig_input, orig_output, grad, [1, window_rows, window_cols, 1], [1, row_stride, col_stride, 1], padding, explicit_paddings)

Max Pooling Gradient.

Args:
orig_input: A float Tensor. The original input tensor.
orig_output: A float Tensor. The original output tensor.
grad: A float Tensor.
The 4D (batch x rows x cols x depth) output backprop.
window_rows: integer. Kernel size along rows dimension.
window_cols: integer. Kernel size along cols dimension.
row_stride: integer. Stride along rows dimension
col_stride: integer. Stride along cols dimension
padding: PoolingOpDef.Padding.  Padding type.

Returns:
A Tensor.


def localize(dt, force_to_local=True):

  if not isinstance(dt, datetime_tz):
    if not dt.tzinfo:
      return datetime_tz(dt, tzinfo=localtz())
    dt = datetime_tz(dt)
  if force_to_local:
    return dt.astimezone(localtz())
  return dt

Localize a datetime to the local timezone.

If dt is naive, returns the same datetime with the local timezone, otherwise
uses astimezone to convert.

Args:
dt: datetime object.
force_to_local: Force all results to be in local time.

Returns:
A datetime_tz object.


def execute_tests(self):
    with open(self.notebook_path, 'r') as nb_f:
        nb = nbformat.read(nb_f, as_version=4)
    ExecutePreprocessor.timeout = self.timeout_secs
    ep = ExecutePreprocessor(allow_errors=True)
    exec_nb, _ = ep.preprocess(nb, {'metadata': {'path': self.dir + '/'}})
    test_count = 0
    error_count = 0
    errors = OrderedDict()
    code_cells = {}
    for cell in exec_nb['cells']:
        if cell['cell_type'] == 'code':
            code_cells[cell['execution_count']] = cell
    for cell_num in sorted(self.tests.keys()):
        if cell_num not in code_cells:
            test_count += 1
            error_count += 1
            errors[cell_num, '', ''] = 'Given cell does not exist.'
        else:
            cell = code_cells[cell_num]
            for test in self.tests[cell_num]:
                cls, setup = list(test.items())[0]
                test_count += 1
                try:
                    getattr(sys.modules['testlib'], cls)(setup).check(cell)
                except Exception as e:
                    error_count += 1
                    errors[cell_num, cls, setup] = str(e)
    return (test_count, error_count, errors)

Executes notebook and compares to test spec.

Returns:
# of tests, # of errors, error_dict
where error_dict maps (cell number, test class, expected output) to string


def lineitem_patch_v1(config, auth, patch, li):
    return API_DV360(config, auth).advertisers().lineItems().patch(advertiserId=li['advertiserId'], lineItemId=li['lineItemId'], updateMask=patch, body=li).execute()

Patches a DV360 Line Item

Args:
auth: StarThinker authentication scheme
patch: List of field names to patch
li: Line item with updates to push
Returns: Updated Line Item


def update_nsval(
        self, *, nsval: str = None, ns: str = None, val: str = None
    ) -> None:

        if not (ns and val) and nsval:
            (ns, val) = nsval.split(":", 1)
        elif not (ns and val) and not nsval:
            log.error("Did not update NSArg - no ns:val or nsval provided")

        self.namespace = ns
        self.value = val

Update Namespace and valueast.

Args:
nsval: e.g. HGNC:AKT1
ns: namespace
val: value of entity


def closure(self, rules):
    closure = set()
    todo = set(rules)
    while todo:
        rule = todo.pop()
        closure.add(rule)
        if rule.at_end:
            continue
        symbol = rule.rhs[rule.pos]
        for production in self.nonterminals[symbol]:
            for first in self.first(rule.rest):
                if (EPSILON in production.rhs):
                    new_rule = DottedRule(production, 1, first)
                else:
                    new_rule = DottedRule(production, 0, first)
                if (new_rule not in closure):
                    todo.add(new_rule)
    return frozenset(closure)

Fills out the entire closure based on some initial dotted rules.

Args:
rules - an iterable of DottedRules

Returns: frozenset of DottedRules


def gradient(poly):
    return differential(poly, chaospy.poly.collection.basis(1, 1, poly.dim))

Gradient of a polynomial.

Args:
poly (Poly) : polynomial to take gradient of.

Returns:
(Poly) : The resulting gradient.

Examples:
>>> q0, q1, q2 = chaospy.variable(3)
>>> poly = 2*q0 + q1*q2
>>> print(chaospy.gradient(poly))
[2, q2, q1]


def update_profiles(adapter):

    for case in adapter.cases():

        if case.get('profile_path'):

            profiles = get_profiles(adapter, case['profile_path'])
            profiled_individuals = deepcopy(case['individuals'])

            for individual in profiled_individuals:
                ind_id = individual['ind_id']
                try:
                    profile = profiles[ind_id]
                    individual['profile'] = profile

                except KeyError:
                    LOG.warning(f"sample IDs in vcf does not match for case {case['case_id']}")

            updated_case = deepcopy(case)

            updated_case['individuals'] = profiled_individuals

            adapter.add_case(updated_case, update=True)

For all cases having vcf_path, update the profile string for the samples

Args:
adapter (MongoAdapter): Adapter to mongodb


def plot_pie(self, key="wall_time", minfract=0.05, **kwargs):

        timers = self.timers()
        n = len(timers)

        import matplotlib.pyplot as plt
        from matplotlib.gridspec import GridSpec
        fig = plt.gcf()
        gspec = GridSpec(n, 1)
        for idx, timer in enumerate(timers):
            ax = plt.subplot(gspec[idx, 0])
            ax.set_title(str(timer))
            timer.pie(ax=ax, key=key, minfract=minfract, show=False)

        return fig

Plot pie charts of the different timers.

Args:
key: Keyword used to extract data from timers.
minfract: Don't show sections whose relative weight is less that minfract.

Returns:
`matplotlib` figure


def _raise_if_annotated(self, func):
    if (hasattr(func, ANNOTATED) and getattr(func, ANNOTATED)):
        msg = 'Functions decorated with {!r} should not be decorated with {!r}.\nPlease reverse the order of the decorators!'.format(self.__class__.__name__, Annotate.__name__)
        raise TypeError(msg)

Raise TypeError if a function is decorated with Annotate, as such
functions cause visual bugs when decorated with Animate.

Animate should be wrapped by Annotate instead.

Args:
func (function): Any callable.
Raises:
TypeError


def __init__(self, mol):

        if isinstance(mol, Molecule):
            if not mol.is_ordered:
                raise ValueError("OpenBabel Molecule only supports ordered "
                                 "molecules.")

            obmol = ob.OBMol()
            obmol.BeginModify()
            for site in mol:
                coords = [c for c in site.coords]
                atomno = site.specie.Z
                obatom = ob.OBAtom()
                obatom.thisown = 0
                obatom.SetAtomicNum(atomno)
                obatom.SetVector(*coords)
                obmol.AddAtom(obatom)
                del obatom
            obmol.ConnectTheDots()
            obmol.PerceiveBondOrders()
            obmol.SetTotalSpinMultiplicity(mol.spin_multiplicity)
            obmol.SetTotalCharge(mol.charge)
            obmol.Center()
            obmol.Kekulize()
            obmol.EndModify()
            self._obmol = obmol
        elif isinstance(mol, ob.OBMol):
            self._obmol = mol

Initializes with pymatgen Molecule or OpenBabel"s OBMol.

Args:
mol: pymatgen's Molecule or OpenBabel OBMol


def find_elements(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5):
    wait = WebDriverWait(driver, timeout, poll_frequency)
    return wait.until(EC.presence_of_all_elements_located((by, elem_path)))

Find and return all elements once located

find_elements locates all elements on the page, waiting
for up to timeout seconds. The elements, when located,
are returned. If not located, a TimeoutException is raised.

Args:
driver (selenium webdriver or element): A driver or element
elem_path (str): String used to located the element
by (selenium By): Selenium By reference
timeout (int): Selenium Wait timeout, in seconds
poll_frequency (float): Selenium Wait polling frequency, in seconds

Returns:
list of elements: Selenium element

Raises:
TimeoutException: Raised when target element isn't located


def verify_signature(amazon_cert: crypto.X509, signature: str, request_body: bytes) -> bool:
    signature = base64.b64decode(signature)
    try:
        crypto.verify(amazon_cert, signature, request_body, 'sha1')
        result = True
    except crypto.Error:
        result = False
    return result

Verifies Alexa request signature.

Args:
amazon_cert: Pycrypto X509 Amazon certificate.
signature: Base64 decoded Alexa request signature from Signature HTTP header.
request_body: full HTTPS request body
Returns:
result: True if verification was successful, False if not.


def get(self, name_or_uri):
    name_or_uri = quote(name_or_uri)
    return self._client.get(name_or_uri)

Get the role by its URI or Name.

Args:
name_or_uri:
Can be either the Name or the URI.

Returns:
dict: Role


def check_status(self, **kwargs):

        for work in self:
            work.check_status()

        if kwargs.pop("show", False):
            self.show_status(**kwargs)

Check the status of the works in self.

Args:
show: True to show the status of the flow.
kwargs: keyword arguments passed to show_status


def line_number_above():
    call_site_lineno = tf_inspect.stack()[1][2]
    if sys.version_info < (3, 8):
        return call_site_lineno - 1
    else:
        with open(__file__, 'rb') as f:
            source_text = f.read().decode('utf-8')
        source_tree = ast.parse(source_text)
        prev_node = _find_preceding_ast_node(source_tree, call_site_lineno)
        return prev_node.lineno

Get lineno of the AST node immediately above this function's call site.

It is assumed that there is no empty line(s) between the call site and the
preceding AST node.

Returns:
The lineno of the preceding AST node, at the same level of the AST.
If the preceding AST spans multiple lines:
- In Python 3.8+, the lineno of the first line is returned.
- In older Python versions, the lineno of the last line is returned.


def increment(self, counter_name, delta):

    current_value = self.counters.get(counter_name, 0)
    new_value = current_value + delta
    self.counters[counter_name] = new_value
    return new_value

Increment counter value.

Args:
counter_name: counter name as String.
delta: increment delta as Integer.

Returns:
new counter value.


def synthesize(self, duration, freqs_in_hz=[440.0]):
    freqs = np.array(freqs_in_hz)
    scaling = (1 / len(freqs))
    sr = int(self.samplerate)
    cps = (freqs / sr)
    ts = ((duration / Seconds(1)) * sr)
    ranges = np.array([np.arange(0, (ts * c), c) for c in cps])
    raw = (np.sin((ranges * (2 * np.pi))) * scaling).sum(axis=0)
    return AudioSamples(raw, self.samplerate)

Synthesize one or more sine waves

Args:
duration (numpy.timdelta64): The duration of the sound to be
synthesized
freqs_in_hz (list of float): Numbers representing the frequencies
in hz that should be synthesized


def _decontextualise_connection(self, connection):

        ctx = stack.top
        if ctx is not None and connection in ctx.ldap3_manager_connections:
            ctx.ldap3_manager_connections.remove(connection)

Remove a connection from the appcontext.

Args:
connection (ldap3.Connection): connection to remove from the
appcontext


def ajax(cls, url, param={}, method='get'):

        param = urllib.parse.urlencode(param)
        if method.lower() == 'get':
            req = urllib.request.Request(url + '?' + param)
        elif method.lower() == 'post':
            param = param.encode('utf-8')
            req = urllib.request.Request(url, data=param)
        else:
            raise Exception("invalid method '{}' (GET/POST)".format(method))
        rsp = urllib.request.urlopen(req)
        if rsp:
            rsp_json = rsp.read().decode('utf-8')
            rsp_dict = json.loads(rsp_json)
            return rsp_dict
        return None

Get info by ajax

Args:
url: string
Returns:
dict: json decoded into a dict


def _ParseMRUListExEntryValue(
      self, parser_mediator, registry_key, entry_index, entry_number,
      codepage='cp1252', **kwargs):

    value_string = ''

    value = registry_key.GetValueByName('{0:d}'.format(entry_number))
    if value is None:
      parser_mediator.ProduceExtractionWarning(
          'missing MRUListEx value: {0:d} in key: {1:s}.'.format(
              entry_number, registry_key.path))

    elif not value.DataIsBinaryData():
      logger.debug((
          '[{0:s}] Non-binary MRUListEx entry value: {1:d} in key: '
          '{2:s}.').format(self.NAME, entry_number, registry_key.path))

    elif value.data:
      utf16le_string_map = self._GetDataTypeMap('utf16le_string')

      context = dtfabric_data_maps.DataTypeMapContext()

      try:
        path = self._ReadStructureFromByteStream(
            value.data, 0, utf16le_string_map, context=context)
      except (ValueError, errors.ParseError) as exception:
        parser_mediator.ProduceExtractionWarning((
            'unable to parse MRUListEx entry value: {0:d} with error: '
            '{1!s}').format(entry_number, exception))
        return value_string

      path = path.rstrip('\x00')

      shell_item_data = value.data[context.byte_size:]

      if not shell_item_data:
        parser_mediator.ProduceExtractionWarning((
            'missing shell item in MRUListEx value: {0:d} in key: '
            '{1:s}.').format(entry_number, registry_key.path))
        value_string = 'Path: {0:s}'.format(path)

      else:
        shell_items_parser = shell_items.ShellItemsParser(registry_key.path)
        shell_items_parser.ParseByteStream(
            parser_mediator, shell_item_data, codepage=codepage)

        value_string = 'Path: {0:s}, Shell item: [{1:s}]'.format(
            path, shell_items_parser.CopyToPath())

    return value_string

Parses the MRUListEx entry value.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains
the MRUListEx value.
entry_index (int): MRUListEx entry index.
entry_number (int): entry number.
codepage (Optional[str]): extended ASCII string codepage.

Returns:
str: MRUList entry value.


def _parse_line(line):

    line, timestamp = line.rsplit(",", 1)
    line, command = line.rsplit(",", 1)
    path, username = line.rsplit(",", 1)

    return {
        "timestamp": timestamp.strip(),
        "command": command.strip(),
        "username": username.strip(),
        "path": path,
    }

Convert one line from the extended log to dict.

Args:
line (str): Line which will be converted.

Returns:
dict: dict with ``timestamp``, ``command``, ``username`` and ``path`` \
keys.

Note:
Typical line looks like this::

/home/ftp/xex/asd bsd.dat, xex, STOR, 1398351777

Filename may contain ``,`` character, so I am ``rsplitting`` the line
from the end to the beginning.


def get_geostationary_bounding_box(geos_area, nb_points=50):

    xmax, ymax = get_geostationary_angle_extent(geos_area)

    x = np.cos(np.linspace(-np.pi, 0, nb_points / 2)) * (xmax - 0.001)
    y = -np.sin(np.linspace(-np.pi, 0, nb_points / 2)) * (ymax - 0.001)

    ll_x, ll_y, ur_x, ur_y = (np.array(geos_area.area_extent) /
                              geos_area.proj_dict['h'])

    x = np.clip(np.concatenate([x, x[::-1]]), min(ll_x, ur_x), max(ll_x, ur_x))
    y = np.clip(np.concatenate([y, -y]), min(ll_y, ur_y), max(ll_y, ur_y))

    return _lonlat_from_geos_angle(x, y, geos_area)

Get the bbox in lon/lats of the valid pixels inside *geos_area*.

Args:
nb_points: Number of points on the polygon


def FromString(cls, desc):

        if language.stream is None:
            language.get_language()

        parse_exp = Optional(time_interval('time') - Literal(':').suppress()) - language.stream('stream') - Literal('=').suppress() - number('value')

        try:
            data = parse_exp.parseString(desc)
            time = 0
            if 'time' in data:
                time = data['time'][0]

            return SimulationStimulus(time, data['stream'][0], data['value'])
        except (ParseException, ParseSyntaxException):
            raise ArgumentError("Could not parse stimulus descriptor", descriptor=desc)

Create a new stimulus from a description string.

The string must have the format:

[time: ][system ]input X = Y
where X and Y are integers.  The time, if given must
be a time_interval, which is an integer followed by a
time unit such as second(s), minute(s), etc.

Args:
desc (str): A string description of the stimulus.

Returns:
SimulationStimulus: The parsed stimulus object.


def _write_input(self, input_dir='.'):
    with open(os.path.join(input_dir, self.input_file), 'wt', encoding='utf-8') as inp:
        for (k, v) in self.control_params.items():
            inp.write('{} {}\n'.format(k, self._format_param_val(v)))
        for (idx, mol) in enumerate(self.mols):
            filename = os.path.join(input_dir, '{}.{}'.format(idx, self.control_params['filetype'])).encode('ascii')
            if (self.control_params['filetype'] == 'pdb'):
                self.write_pdb(mol, filename, num=(idx + 1))
            else:
                a = BabelMolAdaptor(mol)
                pm = pb.Molecule(a.openbabel_mol)
                pm.write(self.control_params['filetype'], filename=filename, overwrite=True)
            inp.write('\n')
            inp.write('structure {}.{}\n'.format(os.path.join(input_dir, str(idx)), self.control_params['filetype']))
            for (k, v) in self.param_list[idx].items():
                inp.write('  {} {}\n'.format(k, self._format_param_val(v)))
            inp.write('end structure\n')

Write the packmol input file to the input directory.

Args:
input_dir (string): path to the input directory


async def get_all(self, direction: msg.StreamDirection=msg.StreamDirection.Forward, from_position: Optional[Union[(msg.Position, msg._PositionSentinel)]]=None, max_count: int=100, resolve_links: bool=True, require_master: bool=False, correlation_id: uuid.UUID=None):
    correlation_id = correlation_id
    cmd = convo.ReadAllEvents(msg.Position.for_direction(direction, from_position), max_count, resolve_links, require_master, direction=direction, credentials=self.credential)
    result = (await self.dispatcher.start_conversation(cmd))
    return (await result)

Read a range of events from the whole database.

Args:
direction (optional): Controls whether to read events forward or backward.
defaults to Forward.
from_position (optional): The position to read from.
defaults to the beginning of the stream when direction is forward
and the end of the stream if direction is backward.
max_count (optional): The maximum number of events to return.
resolve_links (optional): True if eventstore should
automatically resolve Link Events, otherwise False.
required_master (optional): True if this command must be
sent direct to the master node, otherwise False.
correlation_id (optional): A unique identifer for this command.

Examples:

Read 5 events

>>> async for event in conn.get_all(max_count=5):
>>>     print(event)

Read 10 most recent events in reverse order

>>> async for event in conn.get_all(
max_count=10,
direction=StreamDirection.Backward
):
>>>     print(event)


def diff(self, **kwargs):

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

Generate the commit diff.

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

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabGetError: If the diff could not be retrieved

Returns:
list: The changes done in this commit


def get_colorscale(cmap, levels=None, cmin=None, cmax=None):
    ncolors = (levels if isinstance(levels, int) else None)
    if isinstance(levels, list):
        ncolors = (len(levels) - 1)
        if (isinstance(cmap, list) and (len(cmap) != ncolors)):
            raise ValueError(('The number of colors in the colormap must match the intervals defined in the color_levels, expected %d colors found %d.' % (ncolors, len(cmap))))
    try:
        palette = process_cmap(cmap, ncolors)
    except Exception as e:
        colorscale = colors.PLOTLY_SCALES.get(cmap)
        if (colorscale is None):
            raise e
        return colorscale
    if isinstance(levels, int):
        colorscale = []
        scale = np.linspace(0, 1, (levels + 1))
        for i in range((levels + 1)):
            if (i == 0):
                colorscale.append((scale[0], palette[i]))
            elif (i == levels):
                colorscale.append((scale[(- 1)], palette[(- 1)]))
            else:
                colorscale.append((scale[i], palette[(i - 1)]))
                colorscale.append((scale[i], palette[i]))
        return colorscale
    elif isinstance(levels, list):
        (palette, (cmin, cmax)) = color_intervals(palette, levels, clip=(cmin, cmax))
    return colors.make_colorscale(palette)

Converts a cmap spec to a plotly colorscale

Args:
cmap: A recognized colormap by name or list of colors
levels: A list or integer declaring the color-levels
cmin: The lower bound of the color range
cmax: The upper bound of the color range

Returns:
A valid plotly colorscale


def _on_change(self, field_updates: Dict[utils.KeyPath, FieldUpdate]):

Event that is triggered when field values in the subtree are updated.

This event will be called
* On per-field basis when object is modified via attribute.
* In batch when multiple fields are modified via `rebind` method.

When a field in an object tree is updated, all ancestors' `_on_change` event
will be triggered in order, from the nearest one to furthest one.

Args:
field_updates: Updates made to the subtree. Key path is relative to
current object.


def setObsoletedBy(self, pid, obsoletedByPid, serialVersion, vendorSpecific=None):

        response = self.setObsoletedByResponse(
            pid, obsoletedByPid, serialVersion, vendorSpecific
        )
        return self._read_boolean_response(response)

See Also: setObsoletedByResponse()

Args:
pid:
obsoletedByPid:
serialVersion:
vendorSpecific:

Returns:


def add_value(self, value_type, value_min, value_max):

        if len(self._employers) > 0:
            self._logger.log(
                'warn',
                'Adding a value after employers have been created'
            )
        value = (value_type,  (value_min, value_max))
        self._value_ranges.append(value)
        self._limit = self._num_employers*len(self._value_ranges)
        self._logger.log(
            'debug',
            'Limit set to {}'.format(self._limit)
        )

Add a tunable value to the ABC (fitness function must be
configured to handle it)

Args:
value_type (string): type of the value, 'int' or 'float'
value_min (int or float): minimum bound for the value
value_max (int or float): maximum bound for the value

Returns:
None


def Verify(self, mempool):

        for descriptor in self.Descriptors:
            if not descriptor.Verify():
                return False

        return super(StateTransaction, self).Verify(mempool)

Verify the transaction.

Args:
mempool:

Returns:
bool: True if verified. False otherwise.


def stat_float_times(cls, newvalue=None):

        if newvalue is not None:
            cls._stat_float_times = bool(newvalue)
        return cls._stat_float_times

Determine whether a file's time stamps are reported as floats
or ints.

Calling without arguments returns the current value.
The value is shared by all instances of FakeOsModule.

Args:
newvalue: If `True`, mtime, ctime, atime are reported as floats.
Otherwise, they are returned as ints (rounding down).


def CollectFromKnowledgeBase(cls, knowledge_base):
    for preprocess_plugin in cls._knowledge_base_plugins.values():
        logger.debug('Running knowledge base preprocessor plugin: {0:s}'.format(preprocess_plugin.__class__.__name__))
        try:
            preprocess_plugin.Collect(knowledge_base)
        except errors.PreProcessFail as exception:
            logger.warning('Unable to collect knowledge base value with error: {0!s}'.format(exception))

Collects values from knowledge base values.

Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.


def find_iteration(
    url: Union[methods, str],
    itermode: Optional[str] = None,
    iterkey: Optional[str] = None,
) -> Tuple[str, str]:

    if isinstance(url, methods):
        if not itermode:
            itermode = url.value[1]
        if not iterkey:
            iterkey = url.value[2]

    if not iterkey or not itermode:
        raise ValueError("Iteration not supported for: {}".format(url))
    elif itermode not in ITERMODE:
        raise ValueError("Iteration not supported for: {}".format(itermode))

    return itermode, iterkey

Find iteration mode and iteration key for a given :class:`slack.methods`

Args:
url: :class:`slack.methods` or string url
itermode: Custom iteration mode
iterkey: Custom iteration key

Returns:
:py:class:`tuple` (itermode, iterkey)


def init_from_storage_write_to_datastore(self,
                                           batch_size=100,
                                           allowed_epsilon=None,
                                           skip_image_ids=None,
                                           max_num_images=None):

    if allowed_epsilon is None:
      allowed_epsilon = copy.copy(DEFAULT_EPSILON)

    self._dataset_batches = {}

    images = self._read_image_list(skip_image_ids)
    if max_num_images:
      images = images[:max_num_images]
    for batch_idx, batch_start in enumerate(range(0, len(images), batch_size)):
      batch = images[batch_start:batch_start+batch_size]
      batch_id = DATASET_BATCH_ID_PATTERN.format(batch_idx)
      batch_epsilon = allowed_epsilon[batch_idx % len(allowed_epsilon)]
      self.add_batch(batch_id, {'epsilon': batch_epsilon})
      for image_id, image_path in batch:
        self.add_image(batch_id, image_id,
                       {'dataset_image_id': os.path.basename(image_path)[:-4],
                        'image_path': image_path})

    self.write_to_datastore()

Initializes dataset batches from the list of images in the datastore.

Args:
batch_size: batch size
allowed_epsilon: list of allowed epsilon or None to use default
skip_image_ids: list of image ids to skip
max_num_images: maximum number of images to read


def orient_directed_graph(self, data, graph):

        warnings.warn("The algorithm is ran on the skeleton of the given graph.")
        return self.orient_undirected_graph(data, nx.Graph(graph))

Run the algorithm on a directed_graph.

Args:
data (pandas.DataFrame): DataFrame containing the data
graph (networkx.DiGraph): Skeleton of the graph to orient

Returns:
networkx.DiGraph: Solution on the given skeleton.

.. warning::
The algorithm is ran on the skeleton of the given graph.


def write_serializable_array(self, array):

        if array is None:
            self.write_byte(0)
        else:
            self.write_var_int(len(array))
            for item in array:
                item.Serialize(self)

Write an array of serializable objects to the stream.

Args:
array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin


def get_splitter_instance(split_type):

    if split_type is None:
        return NoneSplitter()
    elif split_type == 'Line':
        return LineSplitter()
    elif split_type == 'RecordIO':
        return RecordIOSplitter()
    else:
        raise ValueError('Invalid Split Type: %s' % split_type)

Return an Instance of :class:`sagemaker.local.data.Splitter` according to
the specified `split_type`.

Args:
split_type (str): either 'Line' or 'RecordIO'. Can be left as None to signal no data split
will happen.

Returns
:class:`sagemaker.local.data.Splitter`: an Instance of a Splitter


def GetArtifacts(self, os_name=None, name_list=None, source_type=None, exclude_dependents=False, provides=None, reload_datastore_artifacts=False):
    self._CheckDirty(reload_datastore_artifacts=reload_datastore_artifacts)
    results = set()
    for artifact in itervalues(self._artifacts):
        if (os_name and artifact.supported_os and (os_name not in artifact.supported_os)):
            continue
        if (name_list and (artifact.name not in name_list)):
            continue
        if source_type:
            source_types = [c.type for c in artifact.sources]
            if (source_type not in source_types):
                continue
        if (exclude_dependents and GetArtifactPathDependencies(artifact)):
            continue
        if (not provides):
            results.add(artifact)
        else:
            for provide_string in artifact.provides:
                if (provide_string in provides):
                    results.add(artifact)
                    break
    return results

Retrieve artifact classes with optional filtering.

All filters must match for the artifact to be returned.

Args:
os_name: string to match against supported_os
name_list: list of strings to match against artifact names
source_type: rdf_artifacts.ArtifactSource.SourceType to match against
source_type
exclude_dependents: if true only artifacts with no dependencies will be
returned
provides: return the artifacts that provide these dependencies
reload_datastore_artifacts: If true, the data store sources are queried
for new artifacts.

Returns:
set of artifacts matching filter criteria


def is_time_included(self, time):
    if (self._timestamps_data is None):
        self._calculate_timestamps()
    return (time.moy in self._timestamps_data)

Check if time is included in analysis period.

Return True if time is inside this analysis period,
otherwise return False

Args:
time: A DateTime to be tested

Returns:
A boolean. True if time is included in analysis period


def add_message(self, message_type):
    name = self.__normalized_name(message_type)
    if (name not in self.__schemas):
        self.__schemas[name] = None
        schema = self.__message_to_schema(message_type)
        self.__schemas[name] = schema
    return name

Add a new message.

Args:
message_type: protorpc.message.Message class to be parsed.

Returns:
string, The JSON Schema id.

Raises:
KeyError if the Schema id for this message_type would collide with the
Schema id of a different message_type that was already added.


def create_vpc_flow_logs(self, account, region, vpc_id, iam_role_arn):

        try:
            flow = self.session.client('ec2', region)
            flow.create_flow_logs(
                ResourceIds=[vpc_id],
                ResourceType='VPC',
                TrafficType='ALL',
                LogGroupName=vpc_id,
                DeliverLogsPermissionArn=iam_role_arn
            )
            fvpc = VPC.get(vpc_id)
            fvpc.set_property('vpc_flow_logs_status', 'ACTIVE')

            self.log.info('Enabled VPC Logging {}/{}/{}'.format(account, region, vpc_id))
            auditlog(
                event='vpc_flow_logs.create_vpc_flow',
                actor=self.ns,
                data={
                    'account': account.account_name,
                    'region': region,
                    'vpcId': vpc_id,
                    'arn': iam_role_arn
                }
            )
        except Exception:
            self.log.exception('Failed creating VPC Flow Logs for {}/{}/{}.'.format(
                account,
                region,
                vpc_id
            ))

Create a new VPC Flow log

Args:
account (:obj:`Account`): Account to create the flow in
region (`str`): Region to create the flow in
vpc_id (`str`): ID of the VPC to create the flow for
iam_role_arn (`str`): ARN of the IAM role used to post logs to the log group

Returns:
`None`


def _process_counter_example(self, mma, w_string):

        if len(w_string) == 1:
            self.observation_table.smi_vector.append(w_string)
            for exp in self.observation_table.em_vector:
                self._fill_table_entry(w_string, exp)

        diff = len(w_string)
        same = 0
        membership_answer = self._membership_query(w_string)
        while True:
            i = (same + diff) / 2
            access_string = self._run_in_hypothesis(mma, w_string, i)
            if membership_answer != self._membership_query(access_string + w_string[i:]):
                diff = i
            else:
                same = i
            if diff - same == 1:
                break

        access_string = self._run_in_hypothesis(mma, w_string, diff - 1)
        wrong_transition = access_string + w_string[diff - 1]
        if wrong_transition not in self.observation_table.smi_vector:

            self.observation_table.smi_vector.append(wrong_transition)
            for exp in self.observation_table.em_vector:
                self._fill_table_entry(wrong_transition, exp)
            return

        exp = w_string[diff:]
        self.observation_table.em_vector.append(exp)
        for row in self.observation_table.sm_vector + self.observation_table.smi_vector:
            self._fill_table_entry(row, exp)

Process a counterexample in the Rivest-Schapire way.
Args:
mma (DFA): The hypothesis automaton
w_string (str): The examined string to be consumed
Return:
None


def set_unrecognized_field(self, key, value, variant):

        if not isinstance(variant, Variant):
            raise TypeError('Variant type %s is not valid.' % variant)
        self.__unrecognized_fields[key] = value, variant

Set an unrecognized field, used when decoding a message.

Args:
key: The name or number used to refer to this unknown value.
value: The value of the field.
variant: Type information needed to interpret the value or re-encode
it.

Raises:
TypeError: If the variant is not an instance of messages.Variant.


def post(self, url, headers=None, params=None, **kwargs):
    if (len(kwargs) > 1):
        raise InvalidArgumentsError('Too many extra args ({} > 1)'.format(len(kwargs)))
    if kwargs:
        kwarg = next(iter(kwargs))
        if (kwarg not in ('json', 'data')):
            raise InvalidArgumentsError(('Invalid kwarg: ' + kwarg))
    resp = self.session.post(url, headers=headers, params=params, **kwargs)
    resp.raise_for_status()
    return _to_json(resp)

Send a JSON POST request with the given request headers, additional
URL query parameters, and the given JSON in the request body.  The
extra query parameters are merged with any which already exist in the
URL.  The 'json' and 'data' parameters may not both be given.

Args:
url (str): URL to retrieve
headers (dict): Any other headers to be added to the request.
params: dictionary or bytes to be sent in the query string for the
request. (optional)
json: json to send in the body of the Request.  This must be a
JSON-serializable object. (optional)
data: raw request body data.  May be a dictionary, list of tuples,
bytes, or file-like object to send in the body of the Request.
(optional)


def _get_key_counter(seed, alg):
    if alg == Algorithm.AUTO_SELECT.value:
        key, counter = gen_stateless_random_ops_v2.stateless_random_get_key_counter(seed)
    elif alg == Algorithm.PHILOX.value:
        key, counter = _philox_scramble_seed(seed)
    elif alg == Algorithm.THREEFRY.value:
        key = array_ops.reshape(_uint32s_to_uint64(math_ops.cast(seed, dtypes.uint32)), [1])
        counter = array_ops.zeros([1], dtypes.uint64)
    else:
        raise ValueError(unsupported_alg_error_msg(alg))
    return (key, counter)

Calculates the key and counter to pass to raw RNG ops.

This function calculates the key and counter that will be passed to
the raw RNG ops like `StatelessRandomUniformV2`. Depending on the
input `alg`, the key and counter may be scrambled or copied from
`seed`. If `alg` is `"auto_select"`, the key and counter will be
determined at runtime based on device type.

Args:
seed: An integer tensor of shape [2]. The seed to calculate the key and
counter from.
alg: The RNG algorithm. See `tf.random.stateless_uniform` for an
explanation.

Returns:
A pair (key, counter) suitable for V2 stateless RNG ops like
`StatelessRandomUniformV2`.


def export_kml_file(self):
    kml = create_elem('kml')
    kml.Document = create_elem('Document')
    for place in sorted(self.values(), key=(lambda x: x.name)):
        kml.Document.append(place.tokml())
    return etree.ElementTree(kml)

Generate KML element tree from ``Placemarks``.

Returns:
etree.ElementTree: KML element tree depicting ``Placemarks``


def reviews(self, **kwargs):

        path = self._get_id_path('reviews')

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

Get the reviews for a particular movie id.

Args:
page: (optional) Minimum value of 1.  Expected value is an integer.
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.

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


def render_template(cmd_derived_from_alias, pos_args_table):

    try:
        cmd_derived_from_alias = normalize_placeholders(cmd_derived_from_alias, inject_quotes=True)
        template = jinja.Template(cmd_derived_from_alias)

        rendered = shlex.split(template.render(pos_args_table))

        if '' in rendered:
            check_runtime_errors(cmd_derived_from_alias, pos_args_table)

        return rendered
    except Exception as exception:

        if isinstance(exception, CLIError):
            raise

        split_exception_message = str(exception).split()

        error_index = split_exception_message[-1]
        if error_index.isdigit():
            split_exception_message.insert(-1, 'index')
            error_msg = RENDER_TEMPLATE_ERROR.format(' '.join(split_exception_message), cmd_derived_from_alias)

            error_msg += '\n{}^'.format(' ' * (len(error_msg) - len(cmd_derived_from_alias) + int(error_index) - 1))
        else:
            exception_str = str(exception).replace('"{{', '}}').replace('}}"', '}}')
            error_msg = RENDER_TEMPLATE_ERROR.format(cmd_derived_from_alias, exception_str)

        raise CLIError(error_msg)

Render cmd_derived_from_alias as a Jinja template with pos_args_table as the arguments.

Args:
cmd_derived_from_alias: The string to be injected with positional arguemnts.
pos_args_table: The dictionary used to rendered.

Returns:
A processed string with positional arguments injected.


def load_template(path_or_buffer):

    from itertools import groupby
    from operator import itemgetter

    path_or_buffer = _stringify_path(path_or_buffer)

    if is_file_like(path_or_buffer):
        templates = json.load(path_or_buffer)
    else:
        with open(path_or_buffer, 'r') as f:
            templates = json.load(f)

    options = []

    grouper = itemgetter('page', 'extraction_method')

    for key, grp in groupby(sorted(templates, key=grouper), grouper):
        tmp_options = [_convert_template_option(e) for e in grp]

        if len(tmp_options) == 1:
            options.append(tmp_options[0])
            continue

        option = tmp_options[0]
        areas = [e.get('area') for e in tmp_options]
        option['area'] = areas
        option['multiple_tables'] = True
        options.append(option)

    return options

Build tabula-py option from template file

Args:
file_like_obj: File like object of Tabula app template

Returns:
`obj`:dict: tabula-py options


def set_json(self, reason='', new_page=False):

        compressed_json = json.dumps(self._compress_json(self.cached_json))

        if len(compressed_json) > self.max_page_size:
            raise OverflowError(
                'Usernotes page is too large (>{0} characters)'.
                format(self.max_page_size)
            )

        if new_page:
            self.subreddit.wiki.create(
                self.page_name,
                compressed_json,
                reason
            )

            self.subreddit.wiki[self.page_name].mod.update(False, permlevel=2)
        else:
            self.subreddit.wiki[self.page_name].edit(
                compressed_json,
                reason
            )

Send the JSON from the cache to the usernotes wiki page.

Arguments:
reason: the change reason that will be posted to the wiki changelog
(str)
Raises:
OverflowError if the new JSON data is greater than max_page_size


def AddForwardLoopCounter(self, outer_grad_state):
    n = constant_op.constant(0, name='f_count')
    if outer_grad_state is not None:
        outer_add_op = outer_grad_state.forward_index.op.inputs[0].op
        n.op._add_control_input(outer_add_op)
    self.Enter()
    self.AddName(n.name)
    enter_n = _Enter(n, self._name, is_constant=False, parallel_iterations=self._parallel_iterations, name='f_count')
    self.loop_enters.append(enter_n)
    merge_n = merge([enter_n, enter_n])[0]
    switch_n = switch(merge_n, self._pivot)
    index = math_ops.add(switch_n[1], 1)
    next_n = _NextIteration(index)
    merge_n.op._update_input(1, next_n)
    total_iterations = exit(switch_n[0], name='f_count')
    self.loop_exits.append(total_iterations)
    self.ExitResult([total_iterations])
    self.Exit()
    return (total_iterations, next_n)

Adds a loop that counts the number of iterations.

This is added to the forward loop at the time when we start to
create the loop for backprop gradient computation. Called in
the outer context of this forward context.

The pseudocode is:
`n = 0; while (_pivot) { n++; }`

Note that a control dependency is added to `n` to ensure the correct
execution order of stack push ops.

Args:
outer_grad_state: The outer grad state. None if not nested.

Returns:
The number of iterations taken by the forward loop and the loop index.


def AddStorageMediaImageOptions(self, argument_group):

    argument_group.add_argument(
        '--partitions', '--partition', dest='partitions', action='store',
        type=str, default=None, help=(
            'Define partitions to be processed. A range of '
            'partitions can be defined as: "3..5". Multiple partitions can '
            'be defined as: "1,3,5" (a list of comma separated values). '
            'Ranges and lists can also be combined as: "1,3..5". The first '
            'partition is 1. All partitions can be specified with: "all".'))

    argument_group.add_argument(
        '--volumes', '--volume', dest='volumes', action='store', type=str,
        default=None, help=(
            'Define volumes to be processed. A range of volumes can be defined '
            'as: "3..5". Multiple volumes can be defined as: "1,3,5" (a list '
            'of comma separated values). Ranges and lists can also be combined '
            'as: "1,3..5". The first volume is 1. All volumes can be specified '
            'with: "all".'))

Adds the storage media image options to the argument group.

Args:
argument_group (argparse._ArgumentGroup): argparse argument group.


def listSubjects(
        self, query, status=None, start=None, count=None, vendorSpecific=None
    ):

        response = self.listSubjectsResponse(
            query, status, start, count, vendorSpecific
        )
        return self._read_dataone_type_response(response, 'SubjectInfo')

See Also: listSubjectsResponse()

Args:
query:
status:
start:
count:
vendorSpecific:

Returns:


def add_keyword(self, keyword, schema=None, source=None):

        keyword_dict = self._sourced_dict(source, value=keyword)

        if schema is not None:
            keyword_dict['schema'] = schema

        self._append_to('keywords', keyword_dict)

Add a keyword.

Args:
keyword(str): keyword to add.
schema(str): schema to which the keyword belongs.
source(str): source for the keyword.


def validate(self, x: symbolic.Symbolic) -> None:
    if self._validator is not None:
        self._validator(x)

Validates an input's integrity.

This method will be called in :func:`pyglove.patch` when a chain of patchers
have been applied, as to validate the patched object in chain still
conforms to the patcher's plan.

Args:
x: The input after modification.


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

        super(EnrollmentTransaction, self).__init__(*args, **kwargs)
        self.Type = TransactionType.EnrollmentTransaction

Create an instance.

Args:
*args:
**kwargs:


def try_pick_piece_of_work(self, worker_id, submission_id=None):
    client = self._datastore_client
    unclaimed_work_ids = None
    if submission_id:
        unclaimed_work_ids = [k for (k, v) in iteritems(self.work) if (is_unclaimed(v) and (v['submission_id'] == submission_id))]
    if (not unclaimed_work_ids):
        unclaimed_work_ids = [k for (k, v) in iteritems(self.work) if is_unclaimed(v)]
    if unclaimed_work_ids:
        next_work_id = random.choice(unclaimed_work_ids)
    else:
        return None
    try:
        with client.transaction() as transaction:
            work_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id, KIND_WORK, next_work_id)
            work_entity = client.get(work_key, transaction=transaction)
            if (not is_unclaimed(work_entity)):
                return None
            work_entity['claimed_worker_id'] = worker_id
            work_entity['claimed_worker_start_time'] = get_integer_time()
            transaction.put(work_entity)
    except Exception:
        return None
    return next_work_id

Tries pick next unclaimed piece of work to do.

Attempt to claim work piece is done using Cloud Datastore transaction, so
only one worker can claim any work piece at a time.

Args:
worker_id: ID of current worker
submission_id: if not None then this method will try to pick
piece of work for this submission

Returns:
ID of the claimed work piece


def GetConsensusAddress(validators):
    vlen = len(validators)
    script = Contract.CreateMultiSigRedeemScript((vlen - int(((vlen - 1) / 3))), validators)
    return Crypto.ToScriptHash(script)

Get the script hash of the consensus node.

Args:
validators (list): of Ellipticcurve.ECPoint's

Returns:
UInt160:


def do_operation_update(self, info, an_op):
    self.update_op_func(self.metric_name, info, an_op)

Updates an operation using the assigned update_op_func

Args:
info: (:class:`endpoints_management.control.report_request.Info`): the
info instance to update
an_op: (:class:`endpoints_management.control.report_request.Info`):
the info instance to update

Return:
`True` if desc is supported, otherwise `False`


def goto(self, iroute: 'InstanceRoute') -> 'InstanceNode':
    inst = self
    for sel in iroute:
        inst = sel.goto_step(inst)
    return inst

Move the focus to an instance inside the receiver's value.

Args:
iroute: Instance route (relative to the receiver).

Returns:
The instance node corresponding to the target instance.

Raises:
InstanceValueError: If `iroute` is incompatible with the receiver's
value.
NonexistentInstance: If the instance node doesn't exist.
NonDataNode: If an instance route addresses a non-data node
(rpc/action/notification).


def log_cert_info(logger, msg_str, cert_obj):
    list(map(logger, (['{}:'.format(msg_str)] + ['  {}'.format(v) for v in ['Subject: {}'.format(_get_val_str(cert_obj, ['subject', 'value'], reverse=True)), 'Issuer: {}'.format(_get_val_str(cert_obj, ['issuer', 'value'], reverse=True)), 'Not Valid Before: {}'.format(cert_obj.not_valid_before.isoformat()), 'Not Valid After: {}'.format(cert_obj.not_valid_after.isoformat()), 'Subject Alt Names: {}'.format(_get_ext_val_str(cert_obj, 'SUBJECT_ALTERNATIVE_NAME', ['value', 'value'])), 'CRL Distribution Points: {}'.format(_get_ext_val_str(cert_obj, 'CRL_DISTRIBUTION_POINTS', ['value', 'full_name', 'value', 'value'])), 'Authority Access Location: {}'.format((extract_issuer_ca_cert_url(cert_obj) or '<not found>'))]])))

Dump basic certificate values to the log.

Args:
logger: Logger
Logger to which to write the certificate values.

msg_str: str
A message to write to the log before the certificate values.

cert_obj: cryptography.Certificate
Certificate containing values to log.

Returns:
None


def reflection(n1, n2):

    r = abs((n1-n2) / (n1+n2))**2
    return r

Calculate the power reflection at the interface
of two refractive index materials.

Args:
n1 (float): Refractive index of material 1.
n2 (float): Refractive index of material 2.

Returns:
float: The percentage of reflected power.


def update_mp_firware_version(self, timeout=-1):

        uri = "{}/mpFirmwareVersion".format(self.data["uri"])
        return self._helper.do_put(uri, None, timeout, None)

Updates the iLO firmware on a physical server to a minimum ILO firmware version required by OneView to
manage the server.

Args:
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.
Returns:
Resource


def get_class(schema_name):

    global _registry_loaded
    if not _registry_loaded:
        load_message_classes()

    try:
        return _schema_name_to_class[schema_name]
    except KeyError:
        _log.warning(
            'The schema "%s" is not in the schema registry! Either install '
            "the package with its schema definition or define a schema. "
            "Falling back to the default schema...",
            schema_name,
        )
        return Message

Retrieve the message class associated with the schema name.

If no match is found, the default schema is returned and a warning is logged.

Args:
schema_name (six.text_type): The name of the :class:`Message` sub-class;
this is typically the Python path.

Returns:
Message: A sub-class of :class:`Message` to create the message from.


def diagonalize_real_symmetric_matrix(matrix: np.ndarray, *, rtol: float=1e-05, atol: float=1e-08) -> np.ndarray:
    if (np.any((np.imag(matrix) != 0)) or (not predicates.is_hermitian(matrix))):
        raise ValueError('Input must be real and symmetric.')
    (_, result) = np.linalg.eigh(matrix)
    return result

Returns an orthogonal matrix that diagonalizes the given matrix.

Args:
matrix: A real symmetric matrix to diagonalize.
rtol: float = 1e-5,
atol: float = 1e-8

Returns:
An orthogonal matrix P such that P.T @ matrix @ P is diagonal.

Raises:
ValueError: Matrix isn't real symmetric.


def includes(self, lo_freq: float) -> bool:

        if self._lb <= lo_freq <= self._ub:
            return True
        return False

Whether `lo_freq` is within the `LoRange`.

Args:
lo_freq: LO frequency to be checked

Returns:
bool: True if lo_freq is included in this range, otherwise False


def split_leading_dim(tensor, inputs, n_dims=2):

  input_shape_static = inputs.get_shape()
  input_shape_list = input_shape_static.as_list()
  tensor_shape_static = tensor.get_shape()
  tensor_shape_list = tensor_shape_static.as_list()
  if (input_shape_static.is_fully_defined()
      and tensor_shape_static.is_fully_defined()):
    new_shape = input_shape_list[:n_dims] + tensor_shape_list[1:]
    return tf.reshape(tensor, new_shape)

  dims_after_first = tf.shape(tensor)[1:]
  split_sizes = tf.shape(inputs)[:n_dims]
  known_split_sizes = input_shape_list[:n_dims]
  known_dims_after_first = tensor_shape_list[1:]
  output_size = tf.concat([split_sizes, dims_after_first], 0)
  result = tf.reshape(tensor, output_size)
  result.set_shape(known_split_sizes + known_dims_after_first)
  return result

Split the first dimension of a tensor.

Args:
tensor: Tensor to have its first dimension split.
inputs: Original reference input to look the dimensions of.
n_dims: Number of dimensions to split.

Returns:
The input tensor, with its first dimension split.


def _get_events_list(object_key: str) -> List[str]:
    return DB.get_list(_keys.events_list(object_key))

Get list of event ids for the object with the specified key.

Args:
object_key (str): Key of an object in the database.


def get_worfklow_spec(self):
    if (self.current.workflow_name not in self.workflow_spec_cache):
        try:
            self.current.wf_object = BPMNWorkflow.objects.get(name=self.current.workflow_name)
        except ObjectDoesNotExist:
            self.current.wf_object = BPMNWorkflow.objects.get(name='not_found')
            self.current.task_data['non-existent-wf'] = self.current.workflow_name
            self.current.workflow_name = 'not_found'
        xml_content = self.current.wf_object.xml.body
        spec = ZopsSerializer().deserialize_workflow_spec(xml_content, self.current.workflow_name)
        spec.wf_id = self.current.wf_object.key
        self.workflow_spec_cache[self.current.workflow_name] = spec
    return self.workflow_spec_cache[self.current.workflow_name]

Generates and caches the workflow spec package from
BPMN diagrams that read from disk

Returns:
SpiffWorkflow Spec object.


def add_string_pairs_from_text_view_element(xib_file, results, text_view, special_ui_components_prefix):
    text_view_entry_comment = extract_element_internationalized_comment(text_view)
    if (text_view_entry_comment is None):
        return
    if (text_view.hasAttribute('usesAttributedText') and (text_view.attributes['usesAttributedText'].value == 'YES')):
        add_string_pairs_from_attributed_ui_element(results, text_view, text_view_entry_comment)
    else:
        try:
            text_view_entry_key = text_view.attributes['text'].value
            results.append((text_view_entry_key, (text_view_entry_comment + ' default text value')))
        except KeyError:
            pass
    warn_if_element_not_of_class(text_view, 'TextView', special_ui_components_prefix)

Adds string pairs from a textview element.

Args:
xib_file (str): Path to the xib file.
results (list): The list to add the results to.
text_view(element): The textview element from the xib, to extract the string pairs from.
special_ui_components_prefix(str): A custom prefix for internationalize component to allow (default is only JT)


def create_parser():
    parser = argparse_flags.ArgumentParser(description='saved_model_cli: Command-line interface for SavedModel', conflict_handler='resolve')
    parser.add_argument('-v', '--version', action='version', version='0.1.0')
    subparsers = parser.add_subparsers(title='commands', description='valid commands', help='additional help')
    add_show_subparser(subparsers)
    add_run_subparser(subparsers)
    add_scan_subparser(subparsers)
    add_convert_subparser(subparsers)
    add_aot_compile_cpu_subparser(subparsers)
    add_freeze_model_subparser(subparsers)
    return parser

Creates a parser that parse the command line arguments.

Returns:
A namespace parsed from command line arguments.


def _HasExpired(self, key):
    self.logger.debug('Processing key: %s.', key)
    try:
        (schema, json_str) = key.split(None, 3)[2:]
    except (ValueError, AttributeError):
        self.logger.debug('No schema identifier. Not expiring key.')
        return False
    if (schema != 'google-ssh'):
        self.logger.debug('Invalid schema %s. Not expiring key.', schema)
        return False
    try:
        json_obj = json.loads(json_str)
    except ValueError:
        self.logger.debug('Invalid JSON %s. Not expiring key.', json_str)
        return False
    if ('expireOn' not in json_obj):
        self.logger.debug('No expiration timestamp. Not expiring key.')
        return False
    expire_str = json_obj['expireOn']
    format_str = '%Y-%m-%dT%H:%M:%S+0000'
    try:
        expire_time = datetime.datetime.strptime(expire_str, format_str)
    except ValueError:
        self.logger.warning('Expiration timestamp "%s" not in format %s. Not expiring key.', expire_str, format_str)
        return False
    return (datetime.datetime.utcnow() > expire_time)

Check whether an SSH key has expired.

Uses Google-specific semantics of the OpenSSH public key format's comment
field to determine if an SSH key is past its expiration timestamp, and
therefore no longer to be trusted. This format is still subject to change.
Reliance on it in any way is at your own risk.

Args:
key: string, a single public key entry in OpenSSH public key file format.
This will be checked for Google-specific comment semantics, and if
present, those will be analysed.

Returns:
bool, True if the key has Google-specific comment semantics and has an
expiration timestamp in the past, or False otherwise.


def _parse_networks(service_list: dict) -> list:

        networks = []

        for n_values in service_list['networks'].values():
            for n_key, n_value in n_values.items():
                if 'name' in n_key:
                    networks.append(n_value)
        return networks

Parse network key.

Args:
service_list (dict): Service configurations

Returns:
list, List of networks


def _get_edge_sentences(
    G: AnalysisGraph, source: str, target: str
) -> List[str]:

    return chain.from_iterable(
        [
            [repr(e.text) for e in s.evidence]
            for s in G.edges[source, target]["InfluenceStatements"]
        ]
    )

Return the sentences that led to the construction of a specified edge.

Args:
G
source: The source of the edge.
target: The target of the edge.


def calc_transition_to_state(self, newstate):
    cached_val = JTAGStateMachine._lookup_cache.get((self.state, newstate))
    if cached_val:
        return cached_val
    if (newstate not in self.states):
        raise ValueError(('%s is not a valid state for this state machine' % newstate))
    path = self._find_shortest_path(self._statestr, newstate)
    if (not path):
        raise ValueError('No path to the requested state.')
    res = self._get_steps_from_nodes_path(path)
    res.reverse()
    JTAGStateMachine._lookup_cache[(self.state, newstate)] = res
    return res

Given a target state, generate the sequence of transitions that would move this state machine instance to that target state.

Args:
newstate: A str state name to calculate the path to.

Returns:
A bitarray containing the bits that would transition this
state machine to the target state. The bits read from right
to left. For efficiency, this retulting bitarray is cached.
Do not edit this bitarray, or it will cause undefined
behavior.


def gates_to_uncompute(self):
    q = QuantumRegister(self.num_qubits)
    circuit = QuantumCircuit(q, name='disentangler')
    remaining_param = self.params
    for i in range(self.num_qubits):
        (remaining_param, thetas, phis) = Initialize._rotations_to_disentangle(remaining_param)
        rz_mult = self._multiplex(RZGate, phis)
        ry_mult = self._multiplex(RYGate, thetas)
        circuit.append(rz_mult.to_instruction(), q[i:self.num_qubits])
        circuit.append(ry_mult.to_instruction(), q[i:self.num_qubits])
    return circuit

Call to create a circuit with gates that take the
desired vector to zero.

Returns:
QuantumCircuit: circuit to take self.params vector to |00..0>


def setSingleStep(self, singleStep):

        if not isinstance(singleStep, int):
            raise TypeError("Argument is not of type int")

        self._singleStep = abs(singleStep)
        return self._singleStep

setter to _singleStep. converts negativ values to positiv ones.

Args:
singleStep (int): new _singleStep value. converts negativ values to positiv ones.

Raises:
TypeError: If the given argument is not an integer.

Returns:
int or long: the absolute value of the given argument.


def put(self, block_id, priority, pb_type='offline'):
    if (pb_type not in ('offline', 'realtime')):
        raise ValueError('Invalid PB type.')
    with self._mutex:
        added_time = datetime.datetime.utcnow().isoformat()
        entry = (priority, (sys.maxsize - self._index), block_id, pb_type, added_time)
        self._index += 1
        if (self._block_map.get(block_id) is not None):
            raise KeyError('ERROR: Block id "{}" already exists in PC PB queue!'.format(block_id))
        self._block_map[block_id] = entry
        LOG.debug('Adding PB %s to queue', block_id)
        self._queue.append(entry)
        self._queue.sort()
        self._queue.reverse()

Add a Processing Block to the queue.

When a new entry it added, the queue is (re-)sorted by priority
followed by insertion order (older blocks with equal priority are
first).

Args:
block_id (str): Processing Block Identifier
priority (int): Processing Block scheduling priority
(higher values = higher priority)
pb_type (str): Processing Block type (offline, realtime)


def rental_report(self, address, zipcode, format_type="json"):

        query_params = {
            "format": format_type,
            "address": address,
            "zipcode": zipcode
        }

        return self._api_client.fetch_synchronous("property/rental_report", query_params)

Call the rental_report component

Rental Report only supports a single address.

Args:
- address
- zipcode

Kwargs:
- format_type - "json", "xlsx" or "all". Default is "json".


def get_user_info(self, token):
    url = self.get_user_info_url()
    try:
        headers = {'Authorization': 'Bearer {}'.format(token)}
        response = requests.get(url, headers=headers)
    except requests.RequestException:
        logger.exception('Failed to retrieve user info due to a request exception.')
        raise UserInfoRetrievalFailed
    if (response.status_code == 200):
        return self.process_user_info_response(response.json())
    else:
        msg = 'Failed to retrieve user info. Server [{server}] responded with status [{status}].'.format(server=url, status=response.status_code)
        raise UserInfoRetrievalFailed(msg)

Retrieves the user info from the OAuth provider.

Arguments:
token (str): OAuth2 access token.

Returns:
dict

Raises:
UserInfoRetrievalFailed: Retrieval of user info from the remote server failed.


def get_key_counter_alg(seed, alg):
    if alg is None:
        alg = Algorithm.AUTO_SELECT.value
    alg = convert_alg_to_int(alg)
    key, counter = _get_key_counter(seed, alg)
    return (key, counter, alg)

Calculates the key, counter and algorithm to pass to raw RNG ops.

This function calculates the key and counter, and determines the algorithm
that will be passed to the raw RNG ops like `StatelessRandomUniformV2`.
Depending on the input `alg`, the key and counter may be scrambled or copied
from `seed`. If `alg` is `"auto_select"`, the key and counter will be
determined at runtime based on device type.

Args:
seed: An integer tensor of shape [2]. The seed to calculate the key and
counter from.
alg: The RNG algorithm. See `tf.random.stateless_uniform` for an
explanation.

Returns:
A pair (key, counter, algorithm) suitable for V2 stateless RNG ops like
`StatelessRandomUniformV2`.


def console_set_char_foreground(con: tcod.console.Console, x: int, y: int, col: Tuple[(int, int, int)]) -> None:
    lib.TCOD_console_set_char_foreground(_console(con), x, y, col)

Change the foreground color of x,y to col.

Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.

.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.


def append(self, text, afterline=None):
    if afterline:
        self._vim.current.buffer.append(text, afterline)
    else:
        self._vim.current.buffer.append(text)

Append text to the current buffer.

Args:
text (str or Sequence[str]): One or many lines of text to append.
afterline (Optional[int]):
Line number to append after. If 0, text is prepended before the
first line; if ``None``, at end of the buffer.


def import_project(self, file, path, namespace=None, overwrite=False, override_params=None, **kwargs):
    files = {'file': ('file.tar.gz', file)}
    data = {'path': path, 'overwrite': overwrite}
    if override_params:
        for (k, v) in override_params.items():
            data[('override_params[%s]' % k)] = v
    if namespace:
        data['namespace'] = namespace
    return self.gitlab.http_post('/projects/import', post_data=data, files=files, **kwargs)

Import a project from an archive file.

Args:
file: Data or file object containing the project
path (str): Name and path for the new project
namespace (str): The ID or path of the namespace that the project
will be imported to
overwrite (bool): If True overwrite an existing project with the
same path
override_params (dict): Set the specific settings for the project
**kwargs: Extra options to send to the server (e.g. sudo)

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

Returns:
dict: A representation of the import status.


def create_from_json(cls, json_data):
    prop = Property()
    address_info = json_data['address_info']
    prop.address = address_info['address']
    prop.block_id = address_info['block_id']
    prop.zipcode = address_info['zipcode']
    prop.zipcode_plus4 = address_info['zipcode_plus4']
    prop.address_full = address_info['address_full']
    prop.city = address_info['city']
    prop.county_fips = address_info['county_fips']
    prop.geo_precision = address_info['geo_precision']
    prop.lat = address_info['lat']
    prop.lng = address_info['lng']
    prop.slug = address_info['slug']
    prop.state = address_info['state']
    prop.unit = address_info['unit']
    prop.meta = None
    if ('meta' in json_data):
        prop.meta = json_data['meta']
    prop.component_results = _create_component_results(json_data, 'address_info')
    return prop

Deserialize property json data into a Property object

Args:
json_data (dict): The json data for this property

Returns:
Property object


def object_upload(self, bucket, key, content, content_type):
    args = {'uploadType': 'media', 'name': key}
    headers = {'Content-Type': content_type}
    url = (Api._UPLOAD_ENDPOINT + (Api._OBJECT_PATH % (bucket, '')))
    return google.datalab.utils.Http.request(url, args=args, data=content, headers=headers, credentials=self._credentials, raw_response=True)

Writes text content to the object.

Args:
bucket: the name of the bucket containing the object.
key: the key of the object to be written.
content: the text content to be written.
content_type: the type of text content.
Raises:
Exception if the object could not be written to.


def set_aliases_and_defaults(self, aliases_config=None, default_properties=None):
    if (aliases_config is None):
        with open(os.path.join(os.path.dirname(__file__), 'aliases.json')) as f:
            d = json.load(f)
            self.aliases = d.get('aliases', {})
            self.default_criteria = d.get('defaults', {})
    else:
        self.aliases = aliases_config.get('aliases', {})
        self.default_criteria = aliases_config.get('defaults', {})
    if (default_properties is None):
        (self._default_props, self._default_prop_dict) = (None, None)
    else:
        (self._default_props, self._default_prop_dict) = self._parse_properties(default_properties)

Set the alias config and defaults to use. Typically used when
switching to a collection with a different schema.

Args:
aliases_config:
An alias dict to use. Defaults to None, which means the default
aliases defined in "aliases.json" is used. See constructor
for format.
default_properties:
List of property names (strings) to use by default, if no
properties are given to the 'properties' argument of
query().


def run(self, verbose=True):

        self.results.clear()

        for analysis_group in self.config.analysis_groups:
            if analysis_group.providers:
                for provider in analysis_group.providers:
                    logger.info('Run provider %s', provider.identifier)
                    provider.run()
                    for checker in analysis_group.checkers:
                        result = self._get_checker_result(
                            analysis_group, checker, provider)
                        self.results.append(result)
                        analysis_group.results.append(result)
                        if verbose:
                            result.print()
            else:
                for checker in analysis_group.checkers:
                    result = self._get_checker_result(
                        analysis_group, checker, nd='no-data-')
                    self.results.append(result)
                    analysis_group.results.append(result)
                    if verbose:
                        result.print()

Run the analysis.

Generate data from each provider, then check these data with every
checker, and store the analysis results.

Args:
verbose (bool): whether to immediately print the results or not.


def _get_transformers(self):
    transformer_dict = {}
    for table in self.metadata['tables']:
        table_name = table['name']
        for field in table['fields']:
            transformer_type = field.get('type')
            if transformer_type:
                col_name = field['name']
                transformer_dict[(table_name, col_name)] = transformer_type
    return transformer_dict

Load the contents of meta_file and extract information about the transformers.

Returns:
dict: tuple(str, str) -> Transformer.


def order(self, image_catalog_ids, batch_size=100, callback=None):

    def _order_single_batch(url_, ids, results_list):
        data = (json.dumps(ids) if (callback is None) else json.dumps({'acquisitionIds': ids, 'callback': callback}))
        r = self.gbdx_connection.post(url_, data=data)
        r.raise_for_status()
        order_id = r.json().get('order_id')
        if order_id:
            results_list.append(order_id)
    self.logger.debug('Place order')
    url = (('%s/order' if (callback is None) else '%s/ordercb') % self.base_url)
    batch_size = min(100, batch_size)
    if (not isinstance(image_catalog_ids, list)):
        image_catalog_ids = [image_catalog_ids]
    sanitized_ids = list(set((id for id in (_id.strip() for _id in image_catalog_ids) if id)))
    res = []
    acq_ids_by_batch = zip(*([iter(sanitized_ids)] * batch_size))
    for ids_batch in acq_ids_by_batch:
        _order_single_batch(url, ids_batch, res)
    remain_count = (len(sanitized_ids) % batch_size)
    if (remain_count > 0):
        _order_single_batch(url, sanitized_ids[(- remain_count):], res)
    if (len(res) == 1):
        return res[0]
    elif (len(res) > 1):
        return res

Orders images from GBDX.

Args:
image_catalog_ids (str or list): A single catalog id or a list of
catalog ids.
batch_size (int): The image_catalog_ids will be split into
batches of batch_size. The ordering API max
batch size is 100, if batch_size is greater
than 100 it will be truncated.
callback (str): A url to call when ordering is completed.

Returns:
order_ids (str or list): If one batch, returns a string. If more
than one batch, returns a list of order ids,
one for each batch.


def _apply_gradients_and_copy(self, opt, raw_grad_list, ps_var_grads):
    with tf.name_scope('apply_gradients'):
        var_update_ops = []
        for (vid, (g, v)) in enumerate(ps_var_grads):
            apply_gradient_op = opt.apply_gradients([(g, v)])
            barrier = self._add_sync_queues_and_barrier('param_update_barrier_{}'.format(vid), [apply_gradient_op])
            with tf.control_dependencies([barrier]), tf.device(self.cpu_device):
                updated_value = v.read_value()
                for towerid in range(self.nr_gpu):
                    var_update_ops.append(raw_grad_list[towerid][vid][1].assign(updated_value))
        return var_update_ops

Apply averaged gradients to ps vars, and then copy the updated
variables back to each tower.

Args:
raw_grad_list: Ngpu x Nvar x 2 gradient list from all towers
ps_var_grads: Nvar x 2 (grad, ps_var)

Returns:
list of copy ops


def call(self, inputs, training=None, mask=None):
    return self._run_internal_graph(inputs, training=training, mask=mask)

Calls the model on new inputs.

In this case `call` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).

Args:
inputs: A tensor or list of tensors.
training: Boolean or boolean scalar tensor, indicating whether to run
the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be
either a tensor or None (no mask).

Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.


def checkUser(self, user):
    return (not self.conn('POST', '{0}/GetCredentialType.srf'.format(SkypeConnection.API_MSACC), json={'username': user}).json().get('IfExistsResult'))

Query a username or email address to see if a corresponding Microsoft account exists.

Args:
user (str): username or email address of an account

Returns:
bool: whether the account exists


def get_videos_for_course(course_id, sort_field=None, sort_dir=SortDirection.asc, pagination_conf=None):
    return _get_videos_for_filter({'courses__course_id': six.text_type(course_id), 'courses__is_hidden': False}, sort_field, sort_dir, pagination_conf)

Returns an iterator of videos for the given course id.

Args:
course_id (String)
sort_field (VideoSortField)
sort_dir (SortDirection)

Returns:
A generator expression that contains the videos found, sorted by the
given field and direction, with ties broken by edx_video_id to ensure a
total order.


def get(cls):
    if cls.is_twoconspect:
        return (cls.subconspect_el.value or None)
    input_value = cls.input_el.value.strip()
    if (not input_value):
        return None
    mdt = conspectus.mdt_by_name.get(input_value)
    if (not mdt):
        alert(('Invalid sub-conspect `%s`!' % input_value))
        return None
    return mdt

Get code selected by user.

Returns:
str: Code or None in case that user didn't selected anything yet.


def lookup_descriptor(self, definition_name):

        try:
            return self.__descriptors[definition_name]
        except KeyError:
            pass

        if self.__descriptor_loader:
            definition = self.__descriptor_loader(definition_name)
            self.__descriptors[definition_name] = definition
            return definition
        else:
            raise messages.DefinitionNotFoundError(
                'Could not find definition for %s' % definition_name)

Lookup descriptor by name.

Get descriptor from library by name.  If descriptor is not found will
attempt to find via descriptor loader if provided.

Args:
definition_name: Definition name to find.

Returns:
Descriptor that describes definition name.

Raises:
DefinitionNotFoundError if not descriptor exists for definition name.


def get(account):

        account = Account.get(account)
        if not account:
            return None

        acct_type = AccountType.get(account.account_type_id).account_type
        account_class = get_plugin_by_name(PLUGIN_NAMESPACES['accounts'], acct_type)

        return account_class(account)

Returns the class object identified by `account_id`

Args:
account (`int`, `str`): Unique ID of the account to load from database

Returns:
`Account` object if found, else None


def Sleep(self, seconds):
    time.sleep((seconds - int(seconds)))
    for _ in range(int(seconds)):
        time.sleep(1)
        if (self.GetMemoryUsage() > self.memory_quota):
            raise MemoryError('Exceeded memory allowance.')
        if (not self.running):
            break

Sleep a given time in 1 second intervals.

When a machine is suspended during a time.sleep(n) call for more
than n seconds, sometimes the sleep is interrupted and all threads
wake up at the same time. This leads to race conditions between
the threads issuing the heartbeat and the one checking for it. By
sleeping in small intervals, we make sure that even if one sleep
call is interrupted, we do not check for the heartbeat too early.

Args:
seconds: Number of seconds to sleep.

Raises:
MemoryError: if the process exceeds memory quota.