def __init__(self, strategy, cluster_spec, task_type, task_id, session_config=None, rpc_layer='grpc', worker_barrier=None):
    self._strategy = strategy
    self._cluster_spec = cluster_spec
    self._task_type = task_type
    self._task_id = task_id
    self._session_config = session_config
    self._worker_barrier = worker_barrier
    self._rpc_layer = rpc_layer
    self._master_target = self._get_master_target()
    self._num_workers = _get_num_workers(cluster_spec)
    self._is_chief_node = self._is_chief()

Initialize the worker context object.

Args:
strategy: a `DistributionStrategy` object.
cluster_spec: a ClusterSpec object. It can be empty or None in the local
training case.
task_type: a string indicating the role of the corresponding task, such as
"worker" or "ps". It can be None if it is local training or in-graph
replicated training.
task_id: an integer indicating id of the corresponding task. It can be
None if it is local training or in-graph replicated training.
session_config: an optional `tf.compat.v1.ConfigProto` object.
rpc_layer: optional string specifying the RPC protocol for communication
with worker masters. If None or empty, hosts in the `cluster_spec` will
be used directly.
worker_barrier: optional, the barrier object for worker synchronization.


def _validate_none_or_type(t):

    def _validate(setting):

        if setting is not None and not isinstance(setting, t):
            raise ValueError('"{}" is not "{}"'.format(setting, t))
        return setting
    return _validate

Create a validator that checks if a setting is either None or a given type.

Args:
t: The type to assert.

Returns:
callable: A callable that will validate a setting for that type.


def assert_keys_have_values(self, caller, *keys):
    for key in keys:
        self.assert_key_has_value(key, caller)

Check that keys list are all in context and all have values.

Args:
*keys: Will check each of these keys in context
caller: string. Calling function name - just used for informational
messages

Raises:
KeyNotInContextError: Key doesn't exist
KeyInContextHasNoValueError: context[key] is None
AssertionError: if *keys is None


def ed25519_private_key_to_string(key):

    return base64.b64encode(key.private_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PrivateFormat.Raw,
        encryption_algorithm=serialization.NoEncryption()
    ), None).decode('utf-8')

Convert an ed25519 private key to a base64-encoded string.

Args:
key (Ed25519PrivateKey): the key to write to the file.

Returns:
str: the key representation as a str


def delete_plan(self, plan_code):
    return self.client._delete((self.url + 'plans/{}'.format(plan_code)), headers=self.get_headers())

Delete an entire subscription plan associated with the merchant.

Args:
plan_code: Plan’s identification code for the merchant.

Returns:


def list(self, **request_parameters):

        items = self._session.get_items(
            API_ENDPOINT,
            params=request_parameters
        )

        for item in items:
            yield self._object_factory(OBJECT_TYPE, item)

List all roles.

Args:
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).

Returns:
GeneratorContainer: A GeneratorContainer which, when iterated,
yields the roles returned by the Webex Teams query.

Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.


def mapTypeToSql(fld_type=FieldType.NoType, fld_len=0):

        if fld_type == FieldType.Float:
            return "FLOAT"
        elif fld_type == FieldType.String:
            return "VARCHAR(" + str(fld_len) + ")"
        elif fld_type == FieldType.Int:
            return "INT"
        elif fld_type == FieldType.Hex:
            return "VARCHAR(" + str(fld_len * 2) + ")"
        elif fld_type == FieldType.PowerFactor:
            return "VARCHAR(" + str(fld_len) + ")"
        else:
            ekm_log("Type " + str(type) + " not handled by mapTypeToSql, returned VARCHAR(255)")
            return "VARCHAR(255)"

Translate FieldType to portable SQL Type.  Override if needful.
Args:
fld_type (int): :class:`~ekmmeters.FieldType` in serial block.
fld_len (int): Binary length in serial block

Returns:
string: Portable SQL type and length where appropriate.


def _log_progress(self, bytes_downloaded):

    self._total_bytes_downloaded += bytes_downloaded
    now = time.time()
    if (self._interactive_mode() or
        now - self._last_progress_msg_print_time > 15):

      self._print_download_progress_msg(
          "Downloading %s: %s" % (self._url,
                                  tf_utils.bytes_to_readable_str(
                                      self._total_bytes_downloaded, True)))
      self._last_progress_msg_print_time = now

Logs progress information about ongoing module download.

Args:
bytes_downloaded: Number of bytes downloaded.


def Run(self, args, env):
    try:
        options, args = self.parser.parse_args(args)
    except SystemExit as e:
        return e.code
    conf = config.Config(env)
    if options.verbose:
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
    if options.debug:
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
    if options.config_file:
        conf.config_file = options.config_file
    self.log.info('using nss_cache library, version %s', nss_cache.__version__)
    self.log.debug('library path is %r', nss_cache.__file__)
    if not args:
        print('No command given')
        self.parser.print_help()
        return os.EX_USAGE
    if len(args) == 1 and args[0] == 'help':
        self.parser.print_help()
        return os.EX_OK
    self.log.debug('args: %r' % args)
    command_name = args.pop(0)
    self.log.debug('command: %r' % command_name)
    config.LoadConfig(conf)
    try:
        command_callable = getattr(command, command_name.capitalize())
    except AttributeError:
        self.log.warning('%s is not implemented', command_name)
        print('command %r is not implemented' % command_name)
        self.parser.print_help()
        return os.EX_SOFTWARE
    try:
        retval = command_callable().Run(conf=conf, args=args)
    except error.SourceUnavailable as e:
        self.log.error('Problem with configured data source: %s', e)
        return os.EX_TEMPFAIL
    return retval

Begin execution of nsscache.

This method loads our runtime configuration, instantiates the
appropriate Source and Cache objects, and invokes the
appropriate method based on the command given.

NOTE:  We avoid calling sys.exit() and instead return an int
to our caller, who will exit with that status.

Args:
args: list of command line arguments
env: dictionary of environment variables

Returns:
POSIX exit status


def idxmax(self, axis=0, skipna=True, *args, **kwargs):

        if not all(d != np.dtype("O") for d in self._get_dtypes()):
            raise TypeError("reduction operation 'argmax' not allowed for this dtype")
        axis = self._get_axis_number(axis)
        return self._reduce_dimension(
            self._query_compiler.idxmax(axis=axis, skipna=skipna)
        )

Get the index of the first occurrence of the max value of the axis.

Args:
axis (int): Identify the max over the rows (1) or columns (0).
skipna (bool): Whether or not to skip NA values.

Returns:
A Series with the index for each maximum value for the axis
specified.


def _json_clean(d):

    result = {}
    compkeys = {}
    for k, v in d.items():
        if not isinstance(k, tuple):
            result[k] = v
        else:

            key = "c.{}".format(id(k))
            result[key] = v
            compkeys[key] = k

    return (result, compkeys)

Cleans the specified python `dict` by converting any tuple keys to
strings so that they can be serialized by JSON.

Args:
d (dict): python dictionary to clean up.

Returns:
dict: cleaned-up dictionary.


def valid_content_type(self, content_type, accept):

        accept_tokens = accept.replace(' ', '').split(';')
        content_type_tokens = content_type.replace(' ', '').split(';')

        return (
            all(elem in content_type_tokens for elem in accept_tokens) and
            (content_type_tokens[0] == 'application/vnd.oasis.taxii+json' or
             content_type_tokens[0] == 'application/vnd.oasis.stix+json')
        )

Check that the server is returning a valid Content-Type

Args:
content_type (str): ``Content-Type:`` header value
accept (str): media type to include in the ``Accept:`` header.


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

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

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

Args:
[tokens]:

Returns: a string.


def get_commit_tree(profile, sha):
    data = commits.get_commit(profile, sha)
    tree = data.get('tree')
    sha = tree.get('sha')
    return sha

Get the SHA of a commit's tree.

Args:

profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.

sha
The SHA of a commit.

Returns:
The SHA of the commit's tree.


def enc(self, byts, asscd=None):

        iv = os.urandom(16)
        encryptor = AESGCM(self.ekey)
        byts = encryptor.encrypt(iv, byts, asscd)
        envl = {'iv': iv, 'data': byts, 'asscd': asscd}
        return s_msgpack.en(envl)

Encrypt the given bytes and return an envelope dict in msgpack form.

Args:
byts (bytes): The message to be encrypted.
asscd (bytes): Extra data that needs to be authenticated (but not encrypted).

Returns:
bytes: The encrypted message. This is a msgpacked dictionary
containing the IV, ciphertext, and associated data.


def Serialize(self, writer: BinaryWriter):

        super(ValidatorState, self).Serialize(writer)
        self.PublicKey.Serialize(writer)
        writer.WriteBool(self.Registered)
        writer.WriteFixed8(self.Votes)

Serialize full object.

Args:
writer (neo.IO.BinaryWriter):


def splitby(iterable: Iterable[_T], predicate: Callable[[_T], bool]) -> tuple[list[_T], list[_T]]:
    false_list = []
    true_list = []
    for v in iterable:
        if predicate(v):
            true_list.append(v)
        else:
            false_list.append(v)
    return (false_list, true_list)

Split the iterable into 2 lists (false, true), based on the predicate.

Example:

```python
small, big = epy.splitby([100, 4, 4, 1, 200], lambda x: x > 10)
assert small == [4, 4, 1]
assert big == [100, 200]
```

Args:
iterable: The iterable to split
predicate: Function applied to split

Returns:
False list, True list


def save(self, project):

        if 'id' in project and project['id'] is not None:

            self.logger.debug('Updating existing project: ' + json.dumps(project))
            url = '%(base_url)s/%(project_id)s' % {
                'base_url': self.base_url, 'project_id': project['id']
            }
            r = self.gbdx_connection.put(url, json=project)
            try:
                r.raise_for_status()
            except:
                print(r.text)
                raise

            return project['id']
        else:
            self.logger.debug('Creating new project: ' + json.dumps(project))

            url = self.base_url
            r = self.gbdx_connection.post(url, json=project)
            try:
                r.raise_for_status()
            except:
                print(r.text)
                raise
            project_json = r.json()

            return project_json['id']

Saves an AnswerFactory Project

Args:
project (dict): Dictionary specifying an AnswerFactory Project.

Returns:
AnswerFactory Project id


def add_map(self, counters_map):

    for counter_name in counters_map.counters:
      self.increment(counter_name, counters_map.counters[counter_name])

Add all counters from the map.

For each counter in the passed map, adds its value to the counter in this
map.

Args:
counters_map: CounterMap instance to add.


def execute(self, *args, **kwargs):
    self.walk(*args, **kwargs)
    failed_steps = [step for step in self.steps if (step.status == FAILED)]
    if failed_steps:
        raise PlanFailed(failed_steps)

Walks each step in the underlying graph, and raises an exception if
any of the steps fail.

Raises:
PlanFailed: Raised if any of the steps fail.


def function_completions(completion_text: str, bel_spec: BELSpec, function_list: list, bel_fmt: str, size: int) -> list:
    if isinstance(function_list, list):
        if (bel_fmt in ['short', 'medium']):
            function_list = [bel_spec['functions']['to_short'][fn] for fn in function_list]
        else:
            function_list = [bel_spec['functions']['to_long'][fn] for fn in function_list]
    elif (bel_fmt in ['short', 'medium']):
        function_list = bel_spec['functions']['primary']['list_short']
    else:
        function_list = bel_spec['functions']['primary']['list_long']
    matches = []
    for f in function_list:
        escaped_completion_text = completion_text.replace('(', '\\(').replace(')', '\\)')
        log.debug(f'Completion match: {escaped_completion_text}  F: {f}')
        if re.match(escaped_completion_text, f):
            matches.append(f)
    replace_list = []
    for match in matches:
        if completion_text:
            highlight = match.replace(completion_text, f'<em>{completion_text}</em>')
        else:
            highlight = completion_text
        replace_list.append({'replacement': match, 'label': f'{match}()', 'highlight': highlight, 'type': 'Function'})
    return replace_list[:size]

Filter BEL functions by prefix

Args:
prefix: completion string
bel_fmt: short, medium, long BEL formats
spec: BEL specification

Returns:
list: list of BEL functions that match prefix


def __init__(self, ordinals, years, months, days):
    self._ordinals = tf.convert_to_tensor(ordinals, dtype=tf.int32, name='dt_ordinals')
    self._years = tf.convert_to_tensor(years, dtype=tf.int32, name='dt_years')
    self._months = tf.convert_to_tensor(months, dtype=tf.int32, name='dt_months')
    self._days = tf.convert_to_tensor(days, dtype=tf.int32, name='dt_days')
    self._day_of_year = None

Initializer.

This initializer is primarily for internal use. More convenient construction
methods are available via 'dates_from_*' functions.

Args:
ordinals: Tensor of type int32. Each value is number of days since 1 Jan
0001. 1 Jan 0001 has `ordinal=1`. `years`, `months` and `days` must
represent the same dates as `ordinals`.
years: Tensor of type int32, of same shape as `ordinals`.
months: Tensor of type int32, of same shape as `ordinals`
days: Tensor of type int32, of same shape as `ordinals`.


def reverse_action(self, action):

    FUNCTIONS = actions.FUNCTIONS

    aif = self._agent_interface_format

    def func_call_ability(ability_id, cmd_type, *args):

      if ability_id not in actions.ABILITY_IDS:
        logging.warning("Unknown ability_id: %s. This is probably dance or "
                        "cheer, or some unknown new or map specific ability. "
                        "Treating it as a no-op.", ability_id)
        return FUNCTIONS.no_op()

      if aif.hide_specific_actions:
        general_id = next(iter(actions.ABILITY_IDS[ability_id])).general_id
        if general_id:
          ability_id = general_id

      for func in actions.ABILITY_IDS[ability_id]:
        if func.function_type is cmd_type:
          return FUNCTIONS[func.id](*args)
      raise ValueError("Unknown ability_id: %s, type: %s. Likely a bug." % (
          ability_id, cmd_type.__name__))

    if action.HasField("action_ui"):
      act_ui = action.action_ui
      if act_ui.HasField("multi_panel"):
        return FUNCTIONS.select_unit(act_ui.multi_panel.type - 1,
                                     act_ui.multi_panel.unit_index)
      if act_ui.HasField("control_group"):
        return FUNCTIONS.select_control_group(
            act_ui.control_group.action - 1,
            act_ui.control_group.control_group_index)
      if act_ui.HasField("select_idle_worker"):
        return FUNCTIONS.select_idle_worker(act_ui.select_idle_worker.type - 1)
      if act_ui.HasField("select_army"):
        return FUNCTIONS.select_army(act_ui.select_army.selection_add)
      if act_ui.HasField("select_warp_gates"):
        return FUNCTIONS.select_warp_gates(
            act_ui.select_warp_gates.selection_add)
      if act_ui.HasField("select_larva"):
        return FUNCTIONS.select_larva()
      if act_ui.HasField("cargo_panel"):
        return FUNCTIONS.unload(act_ui.cargo_panel.unit_index)
      if act_ui.HasField("production_panel"):
        return FUNCTIONS.build_queue(act_ui.production_panel.unit_index)
      if act_ui.HasField("toggle_autocast"):
        return func_call_ability(act_ui.toggle_autocast.ability_id,
                                 actions.autocast)

    if (action.HasField("action_feature_layer") or
        action.HasField("action_render")):
      act_sp = actions.spatial(action, aif.action_space)
      if act_sp.HasField("camera_move"):
        coord = point.Point.build(act_sp.camera_move.center_minimap)
        return FUNCTIONS.move_camera(coord)
      if act_sp.HasField("unit_selection_point"):
        select_point = act_sp.unit_selection_point
        coord = point.Point.build(select_point.selection_screen_coord)
        return FUNCTIONS.select_point(select_point.type - 1, coord)
      if act_sp.HasField("unit_selection_rect"):
        select_rect = act_sp.unit_selection_rect

        tl = point.Point.build(select_rect.selection_screen_coord[0].p0)
        br = point.Point.build(select_rect.selection_screen_coord[0].p1)
        return FUNCTIONS.select_rect(select_rect.selection_add, tl, br)
      if act_sp.HasField("unit_command"):
        cmd = act_sp.unit_command
        queue = int(cmd.queue_command)
        if cmd.HasField("target_screen_coord"):
          coord = point.Point.build(cmd.target_screen_coord)
          return func_call_ability(cmd.ability_id, actions.cmd_screen,
                                   queue, coord)
        elif cmd.HasField("target_minimap_coord"):
          coord = point.Point.build(cmd.target_minimap_coord)
          return func_call_ability(cmd.ability_id, actions.cmd_minimap,
                                   queue, coord)
        else:
          return func_call_ability(cmd.ability_id, actions.cmd_quick, queue)

    if action.HasField("action_raw") or action.HasField("action_render"):
      raise ValueError("Unknown action:\n%s" % action)

    return FUNCTIONS.no_op()

Transform an SC2-style action into an agent-style action.

This should be the inverse of `transform_action`.

Args:
action: a `sc_pb.Action` to be transformed.

Returns:
A corresponding `actions.FunctionCall`.

Raises:
ValueError: if it doesn't know how to transform this action.


def rtt_read(self, buffer_index, num_bytes):
    buf = (ctypes.c_ubyte * num_bytes)()
    bytes_read = self._dll.JLINK_RTTERMINAL_Read(buffer_index, buf, num_bytes)
    if (bytes_read < 0):
        raise errors.JLinkRTTException(bytes_read)
    return list(buf)[:bytes_read]

Reads data from the RTT buffer.

This method will read at most num_bytes bytes from the specified
RTT buffer. The data is automatically removed from the RTT buffer.
If there are not num_bytes bytes waiting in the RTT buffer, the
entire contents of the RTT buffer will be read.

Args:
self (JLink): the ``JLink`` instance
buffer_index (int): the index of the RTT buffer to read from
num_bytes (int): the maximum number of bytes to read

Returns:
A list of bytes read from RTT.

Raises:
JLinkRTTException if the underlying JLINK_RTTERMINAL_Read call fails.


def plot_cv(self, tmin, tmax, ntemp, ylim=None, **kwargs):

        temperatures = np.linspace(tmin, tmax, ntemp)

        if self.structure:
            ylabel = r"$C_v$ (J/K/mol)"
        else:
            ylabel = r"$C_v$ (J/K/mol-c)"

        fig = self._plot_thermo(self.dos.cv, temperatures, ylabel=ylabel, ylim=ylim, **kwargs)

        return fig

Plots the constant volume specific heat C_v in a temperature range.

Args:
tmin: minimum temperature
tmax: maximum temperature
ntemp: number of steps
ylim: tuple specifying the y-axis limits.
kwargs: kwargs passed to the matplotlib function 'plot'.
Returns:
matplotlib figure


def convert_instancenorm(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting instancenorm ...')
    if (names == 'short'):
        tf_name = ('IN' + random_string(6))
    elif (names == 'keep'):
        tf_name = w_name
    else:
        tf_name = (w_name + str(random.random()))
    assert (len(inputs) == 3)
    bias_name = '{0}.bias'.format(w_name)
    weights_name = '{0}.weight'.format(w_name)
    if ((inputs[(- 2)] + '_np') in layers):
        gamma = layers[(inputs[(- 2)] + '_np')]
    else:
        gamma = weights[weights_name].numpy()
    if ((inputs[(- 1)] + '_np') in layers):
        beta = layers[(inputs[(- 1)] + '_np')]
    else:
        beta = weights[bias_name].numpy()

    def target_layer(x, epsilon=params['epsilon'], gamma=gamma, beta=beta):
        layer = tf.contrib.layers.instance_norm(x, param_initializers={'beta': tf.constant_initializer(beta), 'gamma': tf.constant_initializer(gamma)}, epsilon=epsilon, data_format='NCHW', trainable=False)
        return layer
    lambda_layer = keras.layers.Lambda(target_layer, name=tf_name)
    layers[scope_name] = lambda_layer(layers[inputs[0]])

Convert instance normalization layer.

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


def Flash(self, partition, timeout_ms=0, info_cb=DEFAULT_MESSAGE_CALLBACK):

        return self._SimpleCommand(b'flash', arg=partition, info_cb=info_cb,
                                   timeout_ms=timeout_ms)

Flashes the last downloaded file to the given partition.

Args:
partition: Partition to overwrite with the new image.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_cb: See Download. Usually no messages.

Returns:
Response to a download request, normally nothing.


def find_all_template(im_source, im_search, threshold=0.5, maxcnt=0, rgb=False, bgremove=False):
    method = cv2.TM_CCOEFF_NORMED
    if rgb:
        s_bgr = cv2.split(im_search)
        i_bgr = cv2.split(im_source)
        weight = (0.3, 0.3, 0.4)
        resbgr = [0, 0, 0]
        for i in range(3):
            resbgr[i] = cv2.matchTemplate(i_bgr[i], s_bgr[i], method)
        res = (((resbgr[0] * weight[0]) + (resbgr[1] * weight[1])) + (resbgr[2] * weight[2]))
    else:
        s_gray = cv2.cvtColor(im_search, cv2.COLOR_BGR2GRAY)
        i_gray = cv2.cvtColor(im_source, cv2.COLOR_BGR2GRAY)
        if bgremove:
            s_gray = cv2.Canny(s_gray, 100, 200)
            i_gray = cv2.Canny(i_gray, 100, 200)
        res = cv2.matchTemplate(i_gray, s_gray, method)
    (w, h) = (im_search.shape[1], im_search.shape[0])
    result = []
    while True:
        (min_val, max_val, min_loc, max_loc) = cv2.minMaxLoc(res)
        if (method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]):
            top_left = min_loc
        else:
            top_left = max_loc
        if DEBUG:
            print(('templmatch_value(thresh:%.1f) = %.3f' % (threshold, max_val)))
        if (max_val < threshold):
            break
        middle_point = ((top_left[0] + (w / 2)), (top_left[1] + (h / 2)))
        result.append(dict(result=middle_point, rectangle=(top_left, (top_left[0], (top_left[1] + h)), ((top_left[0] + w), top_left[1]), ((top_left[0] + w), (top_left[1] + h))), confidence=max_val))
        if (maxcnt and (len(result) >= maxcnt)):
            break
        cv2.floodFill(res, None, max_loc, ((- 1000),), ((max_val - threshold) + 0.1), 1, flags=cv2.FLOODFILL_FIXED_RANGE)
    return result

Locate image position with cv2.templateFind

Use pixel match to find pictures.

Args:
im_source(string): 图像、素材
im_search(string): 需要查找的图片
threshold: 阈值，当相识度小于该阈值的时候，就忽略掉

Returns:
A tuple of found [(point, score), ...]

Raises:
IOError: when file read error


def merge_equivalent_compounds(model):

    def dicts_are_compatible(d1, d2):
        return all(key not in d1 or key not in d2 or d1[key] == d2[key]
                   for key in set(d1) | set(d2))

    compound_compartment = {}
    inelegible = set()
    for reaction in model.reactions:
        equation = reaction.equation
        if equation is None:
            continue

        for compound, _ in equation.compounds:
            compartment = compound.compartment
            if compartment is not None:
                compound_compartment[compound.name] = compartment
                if not compound.name.endswith('_{}'.format(compartment)):
                    inelegible.add(compound.name)

    compound_groups = {}
    for compound_id, compartment in iteritems(compound_compartment):
        if compound_id in inelegible:
            continue

        suffix = '_{}'.format(compound_compartment[compound_id])
        if compound_id.endswith(suffix):
            group_name = compound_id[:-len(suffix)]
            compound_groups.setdefault(group_name, set()).add(compound_id)

    compound_mapping = {}
    merged_compounds = {}
    for group, compound_set in iteritems(compound_groups):

        merged = []
        for compound_id in compound_set:
            props = dict(model.compounds[compound_id].properties)

            props.pop('id', None)
            props.pop('compartment', None)

            for merged_props, merged_set in merged:
                if dicts_are_compatible(props, merged_props):
                    merged_set.add(compound_id)
                    merged_props.update(props)
                    break
                else:
                    keys = set(key for key in set(props) | set(merged_props)
                               if key not in props or
                               key not in merged_props or
                               props[key] != merged_props[key])
                    logger.info(
                        'Unable to merge {} into {}, difference in'
                        ' keys: {}'.format(
                            compound_id, ', '.join(merged_set),
                            ', '.join(keys)))
            else:
                merged.append((props, {compound_id}))

        if len(merged) == 1:

            merged_props, merged_set = merged[0]

            for compound_id in merged_set:
                compound_mapping[compound_id] = group
            merged_compounds[group] = merged_props
        else:

            for merged_props, merged_set in merged:
                compartments = set(compound_compartment[c] for c in merged_set)
                merged_name = '{}_{}'.format(
                    group, '_'.join(sorted(compartments)))

                for compound_id in merged_set:
                    compound_mapping[compound_id] = merged_name
                merged_compounds[merged_name] = merged_props

    for reaction in model.reactions:
        equation = reaction.equation
        if equation is None:
            continue

        reaction.equation = equation.translated_compounds(
            lambda c: compound_mapping.get(c, c))

    new_compounds = []
    for compound in model.compounds:
        if compound.id not in compound_mapping:
            new_compounds.append(compound)
        else:
            group = compound_mapping[compound.id]
            if group not in merged_compounds:
                continue
            props = merged_compounds.pop(group)
            props['id'] = group
            new_compounds.append(DictCompoundEntry(
                props, filemark=compound.filemark))

    model.compounds.clear()
    model.compounds.update(new_compounds)

    new_exchange = OrderedDict()
    for compound, reaction_id, lower, upper in itervalues(model.exchange):
        new_compound = compound.translate(
            lambda name: compound_mapping.get(name, name))
        new_exchange[new_compound] = new_compound, reaction_id, lower, upper

    model.exchange.clear()
    model.exchange.update(new_exchange)

Merge equivalent compounds in various compartments.

Tries to detect and merge compound entries that represent the same
compound in different compartments. The entries are only merged if all
properties are equivalent. Compound entries must have an ID with a suffix
of an underscore followed by the compartment ID. This suffix will be
stripped and compounds with identical IDs are merged if the properties
are identical.

Args:
model: :class:`NativeModel`.


def most_specific_compatible_type(self, other: 'TypeSpec') -> 'TypeSpec':
    result = self.most_specific_common_supertype([other])
    if result is None:
        raise ValueError('No TypeSpec is compatible with both %s and %s' % (self, other))
    return result

Returns the most specific TypeSpec compatible with `self` and `other`.

Deprecated. Please use `most_specific_common_supertype` instead.
Do not override this function.

Args:
other: A `TypeSpec`.

Raises:
ValueError: If there is no TypeSpec that is compatible with both `self`
and `other`.


def add_column(self, column_name, column_values):
    if (isinstance(column_values, list) and isinstance(column_values[0], list)):
        raise ValueError('"column_values" must be a flat list, but we detected that its first entry is a list')
    if (isinstance(column_values, np.ndarray) and (column_values.ndim != 1)):
        raise ValueError(('"column_values" should be of rank 1, but is of rank %d' % column_values.ndim))
    if (len(column_values) != self.num_points):
        raise ValueError(('"column_values" should be of length %d, but is of length %d' % (self.num_points, len(column_values))))
    if (column_name in self.name_to_values):
        raise ValueError(('The column name "%s" is already used' % column_name))
    self.column_names.append(column_name)
    self.name_to_values[column_name] = column_values

Adds a named column of metadata values.

Args:
column_name: Name of the column.
column_values: 1D array/list/iterable holding the column values. Must be
of length `num_points`. The i-th value corresponds to the i-th point.

Raises:
ValueError: If `column_values` is not 1D array, or of length `num_points`,
or the `name` is already used.


def _Connect(self, banner=None, **kwargs):

        if not banner:
            banner = socket.gethostname().encode()

        conn_str = self.protocol_handler.Connect(self._handle, banner=banner, **kwargs)

        parts = conn_str.split(b'::')
        self._device_state = parts[0]

        self.build_props = str(parts[1].split(b';'))

        return True

Connect to the device.

Args:
banner: See protocol_handler.Connect.
**kwargs: See protocol_handler.Connect and adb_commands.ConnectDevice for kwargs.
Includes handle, rsa_keys, and auth_timeout_ms.
Returns:
An instance of this class if the device connected successfully.


def local_symbol_table(imports=None, symbols=()):
    return SymbolTable(table_type=LOCAL_TABLE_TYPE, symbols=symbols, imports=imports)

Constructs a local symbol table.

Args:
imports (Optional[SymbolTable]): Shared symbol tables to import.
symbols (Optional[Iterable[Unicode]]): Initial local symbols to add.

Returns:
SymbolTable: A mutable local symbol table with the seeded local symbols.


def read(self, vals):

        i = 0
        if len(vals[i]) == 0:
            self.number_of_records_per_hour = None
        else:
            self.number_of_records_per_hour = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.data_period_name_or_description = None
        else:
            self.data_period_name_or_description = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.data_period_start_day_of_week = None
        else:
            self.data_period_start_day_of_week = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.data_period_start_day = None
        else:
            self.data_period_start_day = vals[i]
        i += 1
        if len(vals[i]) == 0:
            self.data_period_end_day = None
        else:
            self.data_period_end_day = vals[i]
        i += 1

Read values.

Args:
vals (list): list of strings representing values


def get_referenced_object(prev_obj, obj, dot_separated_name, desired_type=None):
    from textx.scoping import Postponed
    assert (prev_obj or (not (type(obj) is list)))
    names = dot_separated_name.split('.')
    match = re.match('parent\\((\\w+)\\)', names[0])
    if match:
        next_obj = obj
        desired_parent_typename = match.group(1)
        next_obj = get_recursive_parent_with_typename(next_obj, desired_parent_typename)
        if next_obj:
            return get_referenced_object(None, next_obj, '.'.join(names[1:]), desired_type)
        else:
            return None
    elif (type(obj) is list):
        next_obj = None
        for res in obj:
            if (hasattr(res, 'name') and (res.name == names[0])):
                if ((desired_type is None) or textx_isinstance(res, desired_type)):
                    next_obj = res
                else:
                    raise TypeError('{} has type {} instead of {}.'.format(names[0], type(res).__name__, desired_type.__name__))
        if (not next_obj):
            if needs_to_be_resolved(prev_obj, names[0]):
                return Postponed()
            else:
                return None
    elif (type(obj) is Postponed):
        return Postponed()
    else:
        next_obj = getattr(obj, names[0])
    if (not next_obj):
        if needs_to_be_resolved(obj, names[0]):
            return Postponed()
        else:
            return None
    if (len(names) > 1):
        return get_referenced_object(obj, next_obj, '.'.join(names[1:]), desired_type)
    if ((type(next_obj) is list) and needs_to_be_resolved(obj, names[0])):
        return Postponed()
    return next_obj

get objects based on a path

Args:
prev_obj: the object containing obj (req. if obj is a list)
obj: the current object
dot_separated_name: the attribute name "a.b.c.d" starting from obj
Note: the attribute "parent(TYPE)" is a shortcut to jump to the
parent of type "TYPE" (exact match of type name).
desired_type: (optional)

Returns:
the object if found, None if not found or Postponed() if some postponed
refs are found on the path


def get_file_handle(file_path):
    LOG.debug('Check if file end is correct')
    if (not os.path.exists(file_path)):
        raise IOError('No such file:{0}'.format(file_path))
    if (not (os.path.splitext(file_path)[(- 1)] in VALID_ENDINGS)):
        raise IOError('Not a valid vcf file name: {}'.format(file_path))
    vcf_obj = VCF(file_path)
    return vcf_obj

Return cyvcf2 VCF object

Args:
file_path(str)

Returns:
vcf_obj(cyvcf2.VCF)


def _get_client_fqdn(self, client_info_contents):
    yamldict = yaml.safe_load(client_info_contents)
    fqdn = yamldict['system_info']['fqdn']
    client_id = yamldict['client_id'].split('/')[1]
    return (client_id, fqdn)

Extracts a GRR client's FQDN from its client_info.yaml file.

Args:
client_info_contents: The contents of the client_info.yaml file.

Returns:
A (str, str) tuple representing client ID and client FQDN.


def find_item(self, fq_name):
    names = fq_name.split(self._separator)
    current = self._yapconf_items
    for name in names:
        if isinstance(current, (YapconfDictItem, YapconfListItem)):
            current = current.children
        if (name not in current):
            return None
        current = current[name]
    return current

Find an item in the specification by fully qualified name.

Args:
fq_name (str): Fully-qualified name of the item.

Returns:
The item if it is in the specification. None otherwise


def get_configuration(self, uri):
    req_headers = {'Accept': 'application/vnd.onshape.v1+json', 'Content-Type': 'application/json'}
    return self._api.request('get', (((((((('/api/partstudios/d/' + uri['did']) + '/') + uri['wvm_type']) + '/') + uri['wvm']) + '/e/') + uri['eid']) + '/configuration'), headers=req_headers)

get the configuration of a PartStudio

Args:
- uri (dict): points to a particular element

Returns:
- requests.Response: Onshape response data


def get_run_start_intro(run_call_count, fetches, feed_dict, tensor_filters, is_callable_runner=False):
    fetch_lines = common.get_flattened_names(fetches)
    if not feed_dict:
        feed_dict_lines = [debugger_cli_common.RichLine('  (Empty)')]
    else:
        feed_dict_lines = []
        for feed_key in feed_dict:
            feed_key_name = common.get_graph_element_name(feed_key)
            feed_dict_line = debugger_cli_common.RichLine('  ')
            feed_dict_line += debugger_cli_common.RichLine(feed_key_name, debugger_cli_common.MenuItem(None, "pf '%s'" % feed_key_name))
            feed_dict_lines.append(feed_dict_line)
    feed_dict_lines = debugger_cli_common.rich_text_lines_from_rich_line_list(feed_dict_lines)
    out = debugger_cli_common.RichTextLines(_HORIZONTAL_BAR)
    if is_callable_runner:
        out.append('Running a runner returned by Session.make_callable()')
    else:
        out.append('Session.run() call
        out.append('')
        out.append('Fetch(es):')
        out.extend(debugger_cli_common.RichTextLines(['  ' + line for line in fetch_lines]))
        out.append('')
        out.append('Feed dict:')
        out.extend(feed_dict_lines)
    out.append(_HORIZONTAL_BAR)
    out.append('')
    out.append('Select one of the following commands to proceed ---->')
    out.extend(_recommend_command('run', 'Execute the run() call with debug tensor-watching', create_link=True))
    out.extend(_recommend_command('run -n', 'Execute the run() call without debug tensor-watching', create_link=True))
    out.extend(_recommend_command('run -t <T>', 'Execute run() calls (T - 1) times without debugging, then execute run() once more with debugging and drop back to the CLI'))
    out.extend(_recommend_command('run -f <filter_name>', 'Keep executing run() calls until a dumped tensor passes a given, registered filter (conditional breakpoint mode)'))
    more_lines = ['    Registered filter(s):']
    if tensor_filters:
        filter_names = []
        for filter_name in tensor_filters:
            filter_names.append(filter_name)
            command_menu_node = debugger_cli_common.MenuItem('', 'run -f %s' % filter_name)
            more_lines.append(RL('        * ') + RL(filter_name, command_menu_node))
    else:
        more_lines.append('        (None)')
    out.extend(debugger_cli_common.rich_text_lines_from_rich_line_list(more_lines))
    out.append('')
    out.append_rich_line(RL('For more details, see ') + RL('help.', debugger_cli_common.MenuItem('', 'help')) + '.')
    out.append('')
    menu = debugger_cli_common.Menu()
    menu.append(debugger_cli_common.MenuItem('run', 'run'))
    menu.append(debugger_cli_common.MenuItem('exit', 'exit'))
    out.annotations[debugger_cli_common.MAIN_MENU_KEY] = menu
    return out

Generate formatted intro for run-start UI.

Args:
run_call_count: (int) Run call counter.
fetches: Fetches of the `Session.run()` call. See doc of `Session.run()`
for more details.
feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()`
for more details.
tensor_filters: (dict) A dict from tensor-filter name to tensor-filter
callable.
is_callable_runner: (bool) whether a runner returned by
Session.make_callable is being run.

Returns:
(RichTextLines) Formatted intro message about the `Session.run()` call.


def run(coro, loop=None):

    loop = loop or asyncio.get_event_loop()
    return loop.run_until_complete(coro)

Convenient shortcut alias to ``loop.run_until_complete``.

Arguments:
coro (coroutine): coroutine object to schedule.
loop (asyncio.BaseEventLoop): optional event loop to use.
Defaults to: ``asyncio.get_event_loop()``.

Returns:
mixed: returned value by coroutine.

Usage::

async def mul_2(num):
return num * 2

paco.run(mul_2(4))
# => 8


def _FullUpdateFromFile(self, cache, source_map, force_write=False):
    return_val = 0
    for entry in source_map:
        if not entry.Verify():
            raise error.InvalidMap('Map is not valid. Aborting')
    if len(source_map) == 0 and (not force_write):
        raise error.EmptyMap('Source map empty during full update, aborting. Use --force-write to override.')
    return_val += cache.WriteMap(map_data=source_map, force_write=force_write)
    if return_val == 0:
        mtime = os.stat(cache.GetCacheFilename()).st_mtime
        self.log.debug('Cache filename %s has mtime %d', cache.GetCacheFilename(), mtime)
        self.WriteModifyTimestamp(mtime)
        self.WriteUpdateTimestamp()
    return return_val

Write a new map into the provided cache (overwrites).

Args:
cache: A nss_cache.caches.Cache object.
source_map: The map whose contents we're replacing the cache with, that is
used for verification.
force_write: A boolean flag forcing empty map updates when False,
defaults to False.

Returns:
0 if succesful, non-zero indicating number of failures otherwise.

Raises:
EmptyMap: Update is an empty map, not raised if force_write=True.
InvalidMap:


def load_config(self):
    logger.debug('loading config file: %s', self.config_file)
    if os.path.exists(self.config_file):
        with open(self.config_file) as file_handle:
            return json.load(file_handle)
    else:
        logger.error('configuration file is required for eventify')
    logger.error('unable to load configuration for service')
    raise EventifyConfigError(('Configuration is required! Missing: %s' % self.config_file))

Load configuration for the service

Args:
config_file: Configuration file path


def main(conf_file, overwrite, logger):

    uid = pwd.getpwnam(get_username()).pw_uid

    logger.info("Stopping the daemon.")
    sh.service(get_service_name(), "stop")

    logger.info("Creating config file.")
    create_config(
        cnf_file=conf_file,
        uid=uid,
        overwrite=overwrite
    )
    logger.info("Creating log file.")
    create_log(
        log_file=REQUIRED_SETTINGS["LogFile"],
        uid=uid
    )

    logger.info("Starting the daemon..")
    sh.service(get_service_name(), "start")

Create configuration and log file. Restart the daemon when configuration
is done.

Args:
conf_file (str): Path to the configuration file.
overwrite (bool): Overwrite the configuration file with `clean` config?


def set_features(self, partition=1):
    if (len(self.json) < (partition + 1)):
        raise ValueError('Not enough dates for the specified partition size: {0}.  Try a smaller partition.'.format(partition))
    data = []
    for offset in range((len(self.json) - partition)):
        json = self.json[offset:(offset + partition)]
        data.append(eval_features(json))
    return pd.DataFrame(data=data, dtype=np.float32)

Parses market data JSON for technical analysis indicators

Args:
partition: Int of how many dates to take into consideration
when evaluating technical analysis indicators.

Returns:
Pandas DataFrame instance with columns as numpy.float32 features.


def _enum_from_direction(direction):
    if isinstance(direction, int):
        return direction
    if (direction == Query.ASCENDING):
        return enums.StructuredQuery.Direction.ASCENDING
    elif (direction == Query.DESCENDING):
        return enums.StructuredQuery.Direction.DESCENDING
    else:
        msg = _BAD_DIR_STRING.format(direction, Query.ASCENDING, Query.DESCENDING)
        raise ValueError(msg)

Convert a string representation of a direction to an enum.

Args:
direction (str): A direction to order by. Must be one of
:attr:`~.firestore.Query.ASCENDING` or
:attr:`~.firestore.Query.DESCENDING`.

Returns:
int: The enum corresponding to ``direction``.

Raises:
ValueError: If ``direction`` is not a valid direction.


def init_grad(obj, allow_lazy_initializer=False):
    if (obj is None):
        return 0.0
    (initializer, supports_lazy_initializer) = grad_initializers[type(obj)]
    if supports_lazy_initializer:
        if isinstance(obj, ZeroGradient):
            if allow_lazy_initializer:
                return ZeroGradient(obj.like)
            else:
                return obj.instantiate()
        elif allow_lazy_initializer:
            return ZeroGradient(obj)
    else:
        assert (not isinstance(obj, ZeroGradient))
    return initializer(obj)

Initialize the gradient for an object.

Args:
obj: The object to initialize the gradient for, can be either a number,
array, tuple, list, or dictionary.
allow_lazy_initializer: Whether to allow using the ZeroGradient wrapper,
for efficiency.

Returns:
An object of the same type, shape, etc. but with all numeric values set to
zero. If the type is unknown, a zero is returned.


def classify_field(value):
    if (not (isinstance(value, six.string_types) and value)):
        return
    schema = load_schema('elements/inspire_field')
    inspire_categories = schema['properties']['term']['enum']
    for inspire_category in inspire_categories:
        if (value.upper() == inspire_category.upper()):
            return inspire_category
    category = normalize_arxiv_category(value)
    return ARXIV_TO_INSPIRE_CATEGORY_MAPPING.get(category, 'Other')

Normalize ``value`` to an Inspire category.

Args:
value(str): an Inspire category to properly case, or an arXiv category
to translate to the corresponding Inspire category.

Returns:
str: ``None`` if ``value`` is not a non-empty string,
otherwise the corresponding Inspire category.


def to_json_string(self) -> str:
    dictionary = self.to_dict()
    for key, value in dictionary.items():
        if isinstance(value, np.ndarray):
            dictionary[key] = value.tolist()
    _processor_class = dictionary.pop('_processor_class', None)
    if _processor_class is not None:
        dictionary['processor_class'] = _processor_class
    return json.dumps(dictionary, indent=2, sort_keys=True) + '\n'

Serializes this instance to a JSON string.

Returns:
`str`: String containing all the attributes that make up this feature_extractor instance in JSON format.


def extend_transformations(self, transformations, return_alternatives=False):
    for t in transformations:
        self.append_transformation(t, return_alternatives=return_alternatives)

Extends a sequence of transformations to the TransformedStructure.

Args:
transformations: Sequence of Transformations
return_alternatives: Whether to return alternative
TransformedStructures for one-to-many transformations.
return_alternatives can be a number, which stipulates the
total number of structures to return.


def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]
    if token_ids_1 is None:
        return len(cls + token_ids_0 + sep) * [0]
    return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
not make use of token type ids, therefore a list of zeros is returned.

Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.

Returns:
`List[int]`: List of zeros.


def bleu_score(logits, labels):
    predictions = tf.to_int32(tf.argmax(logits, axis=(- 1)))
    bleu = tf.py_func(compute_bleu, (labels, predictions), tf.float32)
    return (bleu, tf.constant(1.0))

Approximate BLEU score computation between labels and predictions.

An approximate BLEU scoring method since we do not glue word pieces or
decode the ids and tokenize the output. By default, we use ngram order of 4
and use brevity penalty. Also, this does not have beam search.

Args:
logits: Tensor of size [batch_size, length_logits, vocab_size]
labels: Tensor of size [batch-size, length_labels]

Returns:
bleu: int, approx bleu score


def associate_blocks(blocks, layout_pairs, start_peb_num):
    seq_blocks = []
    for layout_pair in layout_pairs:
        seq_blocks = sort.by_image_seq(blocks, blocks[layout_pair[0]].ec_hdr.image_seq)
        layout_pair.append(seq_blocks)
    return layout_pairs

Group block indexes with appropriate layout pairs

Arguments:
List:blocks        -- List of block objects
List:layout_pairs  -- List of grouped layout blocks
Int:start_peb_num  -- Number of the PEB to start from.

Returns:
List -- Layout block pairs grouped with associated block ranges.


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

        timeout = kwargs.pop('timeout', None)
        p = self.raw_cmd(*args, **kwargs)
        return p.communicate(timeout=timeout)[0].decode('utf-8').replace('\r\n', '\n')

Unix style output, already replace \r\n to \n

Args:
- timeout (float): timeout for a command exec


def Field(dagster_type, default_value=FIELD_NO_DEFAULT_PROVIDED, is_optional=INFER_OPTIONAL_COMPOSITE_FIELD, is_secret=False, description=None):
    config_type = resolve_to_config_type(dagster_type)
    if (not config_type):
        raise DagsterInvalidDefinitionError('Attempted to pass {value_repr} to a Field that expects a valid dagster type usable in config (e.g. Dict, NamedDict, Int, String et al).'.format(value_repr=repr(dagster_type)))
    return FieldImpl(config_type=resolve_to_config_type(dagster_type), default_value=default_value, is_optional=is_optional, is_secret=is_secret, description=description)

The schema for configuration data that describes the type, optionality, defaults, and description.

Args:
dagster_type (DagsterType):
A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})`
default_value (Any):
A default value to use that respects the schema provided via dagster_type
is_optional (bool): Whether the presence of this field is optional
despcription (str):


def make_decoder(num_topics, num_words):

  topics_words_logits = tf.compat.v1.get_variable(
      "topics_words_logits",
      shape=[num_topics, num_words],
      initializer=tf.compat.v1.glorot_normal_initializer())
  topics_words = tf.nn.softmax(topics_words_logits, axis=-1)

  def decoder(topics):
    word_probs = tf.matmul(topics, topics_words)

    return tfd.OneHotCategorical(probs=word_probs,
                                 name="bag_of_words")

  return decoder, topics_words

Create the decoder function.

Args:
num_topics: The number of topics.
num_words: The number of words.

Returns:
decoder: A `callable` mapping a `Tensor` of encodings to a
`tfd.Distribution` instance over words.


def pinch(self, direction='in', percent=0.6, duration=2.0, dead_zone=0.1):
    if (direction not in ('in', 'out')):
        raise ValueError('Argument `direction` should be one of "in" or "out". Got {}'.format(repr(direction)))
    if (dead_zone >= percent):
        raise ValueError('Argument `dead_zone` should not be greater than `percent`. dead_zoon={}, percent={}'.format(repr(dead_zone), repr(percent)))
    tracks = make_pinching(direction, [0.5, 0.5], [1, 1], percent, dead_zone, duration)
    speed = (((percent - dead_zone) / 2) / duration)
    ret = self.apply_motion_tracks(tracks, accuracy=(speed * 0.03))
    return ret

Squeezing or expanding 2 fingers on the entire screen.

Args:
direction (:py:obj:`str`): pinching direction, only "in" or "out". "in" for squeezing, "out" for expanding
percent (:py:obj:`float`): squeezing range from or expanding range to of the entire screen
duration (:py:obj:`float`): time interval in which the action is performed
dead_zone (:py:obj:`float`): pinching inner circle radius. should not be greater than ``percent``


def add_key_value(self, key, value):
    key = self._metadata_map.get(key, key)
    if (key in ['dateAdded', 'lastModified']):
        self._indicator_data[key] = self._utils.format_datetime(value, date_format='%Y-%m-%dT%H:%M:%SZ')
    elif (key == 'confidence'):
        self._indicator_data[key] = int(value)
    elif (key == 'rating'):
        self._indicator_data[key] = float(value)
    else:
        self._indicator_data[key] = value

Add custom field to Indicator object.

.. note:: The key must be the exact name required by the batch schema.

Example::

file_hash = tcex.batch.file('File', '1d878cdc391461e392678ba3fc9f6f32')
file_hash.add_key_value('size', '1024')

Args:
key (str): The field key to add to the JSON batch data.
value (str): The field value to add to the JSON batch data.


def deactivate(self, node_id):
    node = self.node_list[node_id]
    self.node_list[node_id] = node._replace(active=False)

Deactivate the node identified by node_id.

Deactivates the node corresponding to node_id, which means that
it can never be the output of a nearest_point query.

Note:
The node is not removed from the tree, its data is steel available.

Args:
node_id (int): The node identifier (given to the user after
its insertion).


def _to_numpy_type(dtype):
    if isinstance(dtype, dtypes.DType):
        return dtype.as_numpy_dtype
    return np.dtype(dtype)

Converts a native python or TF DType to numpy type.

Args:
dtype: Could be a python type, a numpy type or a TF DType.

Returns:
A NumPy `dtype`.


def default_value(fieldname, datatype):
    if (fieldname in tsdb_coded_attributes):
        return str(tsdb_coded_attributes[fieldname])
    else:
        return _default_datatype_values.get(datatype, '')

Return the default value for a column.

If the column name (e.g. *i-wf*) is defined to have an idiosyncratic
value, that value is returned. Otherwise the default value for the
column's datatype is returned.

Args:
fieldname: the column name (e.g. `i-wf`)
datatype: the datatype of the column (e.g. `:integer`)
Returns:
The default value for the column.

.. deprecated:: v0.7.0


def __init__(
      self, name, aliases=None, alignment_size=None, description=None,
      urls=None):

    super(PaddingDefinition, self).__init__(
        name, aliases=aliases, description=description, urls=urls)
    self.alignment_size = alignment_size

Initializes a padding data type definition.

Args:
name (str): name.
aliases (Optional[list[str]]): aliases.
alignment_size (Optional[int]): alignment size.
description (Optional[str]): description.
urls (Optional[list[str]]): URLs.


def url(self, endpoint=''):
    if (not endpoint.startswith('/')):
        endpoint = ('/' + endpoint)
    return (((self.protocol + ':

Get the base URL of the Remote.

Arguments:
None
Returns:
`str` base URL


def _send_message(self, method, endpoint, params=None, data=None):
    url = (self.url + endpoint)
    r = self.session.request(method, url, params=params, data=data, auth=self.auth, timeout=30)
    return r.json()

Send API request.

Args:
method (str): HTTP method (get, post, delete, etc.)
endpoint (str): Endpoint (to be added to base URL)
params (Optional[dict]): HTTP request parameters
data (Optional[str]): JSON-encoded string payload for POST

Returns:
dict/list: JSON response


def symmetric_difference(self, other):

        other = self._cast_to_frameset(other)
        if other is NotImplemented:
            return NotImplemented
        from_frozenset = self.items.symmetric_difference(other.items)
        return self.from_iterable(from_frozenset, sort=True)

Returns a new :class:`FrameSet` that contains all the elements in either
`self` or `other`, but not both.

Args:
other (:class:`FrameSet`):

Returns:
:class:`FrameSet`:


def export(self, composite=False):

        if composite:
            if rname_rfc6680 is None:
                raise NotImplementedError("Your GSSAPI implementation does "
                                          "not support RFC 6680 (the GSSAPI "
                                          "naming extensions)")

            return rname_rfc6680.export_name_composite(self)
        else:
            return rname.export_name(self)

Export this name as a token.

This method exports the name into a byte string which can then be
imported by using the `token` argument of the constructor.

Args:
composite (bool): whether or not use to a composite token --
:requires-ext:`rfc6680`

Returns:
bytes: the exported name in token form

Raises:
MechanismNameRequiredError
BadNameTypeError
BadNameError


def generate_pyi_ast(src: str, options: config.Options | None=None, loader: load_pytd.Loader | None=None) -> analyze.Analysis:
    options = options or config.Options.create()
    if options.use_rewrite:
        infer_types = rewrite_analyze.infer_types
    else:
        infer_types = analyze.infer_types
    with config.verbosity_from(options):
        ret = _call(infer_types, src, options, loader)
        mod = ret.ast
        mod.Visit(visitors.VerifyVisitor())
        mod = optimize.Optimize(mod, ret.ast_deps, lossy=False, use_abcs=False, max_union=7, remove_mutable=False)
        mod = pytd_utils.CanonicalOrdering(mod)
    ret.ast = mod
    return ret

Run the inferencer on a string of source code, producing output.

Args:
src: The source code.
options: config.Options object.
loader: A load_pytd.Loader instance.

Returns:
An analyze.Analysis object containing the inferencer results.

Raises:
CompileError: If we couldn't parse the input file.
UsageError: If the input filepath is invalid.


def register_from_fields(self, *args):

        names = []
        for field in args:
            widget = self.resolve_widget(field)
            self.register(widget.config_name)
            if widget.config_name not in names:
                names.append(widget.config_name)

        return names

Register config name from field widgets

Arguments:
*args: Fields that contains widget
:class:`djangocodemirror.widget.CodeMirrorWidget`.

Returns:
list: List of registered config names from fields.


def label_total_duration(self):
    durations = collections.defaultdict(float)
    for label in self:
        durations[label.value] += label.duration
    return durations

Return for each distinct label value the total duration of all occurrences.

Returns:
dict: A dictionary containing for every label-value (key)
the total duration in seconds (value).

Example:
>>> ll = LabelList(labels=[
>>>     Label('a', 3, 5),
>>>     Label('b', 5, 8),
>>>     Label('a', 8, 10),
>>>     Label('b', 10, 14),
>>>     Label('a', 15, 18.5)
>>> ])
>>> ll.label_total_duration()
{'a': 7.5 'b': 7.0}


def add_layer(self, layer, input_node_id):

        if isinstance(input_node_id, Iterable):
            layer.input = list(map(lambda x: self.node_list[x], input_node_id))
            output_node_id = self._add_node(Node(layer.output_shape))
            for node_id in input_node_id:
                self._add_edge(layer, node_id, output_node_id)

        else:
            layer.input = self.node_list[input_node_id]
            output_node_id = self._add_node(Node(layer.output_shape))
            self._add_edge(layer, input_node_id, output_node_id)

        layer.output = self.node_list[output_node_id]
        return output_node_id

Add a layer to the Graph.
Args:
layer: An instance of the subclasses of StubLayer in layers.py.
input_node_id: An integer. The ID of the input node of the layer.
Returns:
output_node_id: An integer. The ID of the output node of the layer.


def _item_to_document_ref(iterator, item):
    document_id = item.name.split(_helpers.DOCUMENT_PATH_DELIMITER)[(- 1)]
    return iterator.collection.document(document_id)

Convert Document resource to document ref.

Args:
iterator (google.api_core.page_iterator.GRPCIterator):
iterator response
item (dict): document resource


def FilterRange(self, start_time=None, stop_time=None):
    start_time = self._NormalizeTime(start_time)
    stop_time = self._NormalizeTime(stop_time)
    self.data = [p for p in self.data if (((start_time is None) or (p[1] >= start_time)) and ((stop_time is None) or (p[1] < stop_time)))]

Filter the series to lie between start_time and stop_time.

Removes all values of the series which are outside of some time range.

Args:
start_time: If set, timestamps before start_time will be dropped.
stop_time: If set, timestamps at or past stop_time will be dropped.


def __call__(self, product):

        reviewers = self.reviewers(product)
        Nq = len(reviewers)

        if Nq == 1:
            return 0.5

        else:

            var = np.var([self.review_score(r, product)
                          for r in reviewers], ddof=1)
            return np.log(Nq) / (var + 1)

Compute credibility of a given product.

Args:
product: An instance of :class:`bipartite.Product`.

Returns:
The credibility of the product. It is >= 0.5.


def _object_identifier(self):
    return '_generic_user_object'

String used to identify this object in a SavedModel.

THIS FIELD HAS BEEN DEPRECATED IN FAVOR OF THE NAME REGISTERED WITH
`register_serializable`.

Generally, the object identifier is constant across objects of the same
class, while the metadata field is used for instance-specific data.

Returns:
String object identifier.


def __format__(self, format_spec='dd'):

        text = super(Station.__base__, self).__format__(format_spec)

        if self.alt_id:
            return '%s (%s - %s)' % (self.name, self.alt_id, text)
        else:
            return '%s (%s)' % (self.name, text)

Extended pretty printing for location strings.

Args:
format_spec str: Coordinate formatting system to use

Returns:
Human readable string representation of ``Point`` object

Raises:
ValueError: Unknown value for ``format_spec``


def _check_stop_conditions(self, sensor_graph):
    for stop in self.stop_conditions:
        if stop.should_stop(self.tick_count, (self.tick_count - self._start_tick), sensor_graph):
            return True
    return False

Check if any of our stop conditions are met.

Args:
sensor_graph (SensorGraph): The sensor graph we are currently simulating

Returns:
bool: True if we should stop the simulation


def str_to_timedelta(value):
    m = re.match('^(?:(?:datetime\\.)?timedelta)?\\(?([^)]*)\\)?$', value)
    if (not m):
        raise ValueError('Invalid string for datetime.timedelta')
    args = [int(a.strip()) for a in m.group(1).split(',')]
    return datetime.timedelta(*args)

Convert a string to a datetime.timedelta value.

The following strings are accepted:

- 'datetime.timedelta(1, 5, 12345)'
- 'timedelta(1, 5, 12345)'
- '(1, 5, 12345)'
- '1, 5, 12345'
- '1'

if there are less then three parameters, the missing parameters are
assumed to be 0. Variations in the spacing of the parameters are allowed.

Raises:
ValueError for strings not matching the above criterion.


def check_placeholders(value):

  if isinstance(value, six.string_types):
    if TOKEN_REGEX.search(value):
      raise ValueError('{0:s} must be replaced in dictionary'.format(value))
  elif isinstance(value, list):
    return [check_placeholders(item) for item in value]
  elif isinstance(value, dict):
    return {key: check_placeholders(val) for key, val in value.items()}
  elif isinstance(value, tuple):
    return tuple(check_placeholders(val) for val in value)
  return value

Checks if any values in a given dictionary still contain @ parameters.

Args:
value: Dictionary, list, or string that will be recursively checked for
placeholders

Raises:
ValueError: There still exists a value with an @ parameter.

Returns:
Top-level caller: a modified dict with replaced tokens.
Recursive caller: a modified object with replaced tokens.


def primary(self, repl_id):

        repl = self[repl_id]
        primary = repl.primary()
        return repl.member_info(repl.host2id(primary))

find and return primary hostname
Args:
repl_id - replica set identity


def add(clss, func, deprecated_name):

    @Deprecator(func.__name__, deprecated_name)
    def _old_function(*args, **kwargs):
        return func(*args, **kwargs)
    setattr(clss, deprecated_name, _old_function)

Add the deprecated version of a member function to the given class.
Gives a deprecation warning on usage.

Args:
clss: the class where the deprecated function is to be added
func: the actual function that is called by the deprecated version
deprecated_name: the deprecated name of the function


def parse_mobly_cli_args(argv):
    parser = argparse.ArgumentParser(description='Mobly Test Executable.')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-c', '--config', type=str, metavar='<PATH>', help='Path to the test configuration file.')
    group.add_argument('-l', '--list_tests', action='store_true', help='Print the names of the tests defined in a script without executing them.')
    parser.add_argument('--tests', '--test_case', nargs='+', type=str, metavar='[test_a test_b re:test_(c|d)...]', help='A list of tests in the test class to execute. Each value can be a test name string or a `re:` prefixed string for full regex match of test names.')
    parser.add_argument('-tb', '--test_bed', nargs='+', type=str, metavar='[<TEST BED NAME1> <TEST BED NAME2> ...]', help='Specify which test beds to run tests on.')
    parser.add_argument('-v', '--verbose', action='store_true', help='Set console logger level to DEBUG')
    if not argv:
        argv = sys.argv[1:]
    return parser.parse_known_args(argv)[0]

Parses cli args that are consumed by Mobly.

This is the arg parsing logic for the default test_runner.main entry point.

Multiple arg parsers can be applied to the same set of cli input. So you
can use this logic in addition to any other args you want to parse. This
function ignores the args that don't apply to default `test_runner.main`.

Args:
argv: A list that is then parsed as cli args. If None, defaults to cli
input.

Returns:
Namespace containing the parsed args.


def _configure_from_module(self, item):

        package = None
        if item[0] == '.':
            package = self.import_name

        obj = importlib.import_module(item, package=package)

        self.config.from_object(obj)

        return self

Configure from a module by import path.

Effectively, you give this an absolute or relative import path, it will
import it, and then pass the resulting object to
``_configure_from_object``.

Args:
item (str):
A string pointing to a valid import path.

Returns:
fleaker.App:
Returns itself.


def for_default_graph(*args, **kwargs):

  graph = tf.get_default_graph()
  collection = graph.get_collection(_BOOKKEEPER)
  if collection:
    if args or kwargs:
      raise ValueError('Requesting construction of a BookKeeper that already '
                       'exists: %s %s' % (args, kwargs))
    return collection[0]
  else:
    books = BOOKKEEPER_FACTORY(*args, g=graph, **kwargs)
    graph.add_to_collection(_BOOKKEEPER, books)
    return books

Creates a bookkeeper for the default graph.

Args:
*args: Arguments to pass into Bookkeeper's constructor.
**kwargs: Arguments to pass into Bookkeeper's constructor.
Returns:
A new Bookkeeper.
Raises:
ValueError: If args or kwargs are provided and the Bookkeeper already
exists.


def is_prefix(cls, path):
    lagofile = paths.Paths(path).prefix_lagofile()
    return os.path.isfile(lagofile)

Check if a path is a valid prefix

Args:
path(str): path to be checked

Returns:
bool: True if the given path is a prefix


def SetKeyPathPrefix(self, key_path_prefix):

    self._key_path_prefix = key_path_prefix
    self._key_path_prefix_length = len(key_path_prefix)
    self._key_path_prefix_upper = key_path_prefix.upper()

Sets the Window Registry key path prefix.

Args:
key_path_prefix (str): Windows Registry key path prefix.


def __init__(self, latitude, longitude, altitude, name=None,
                 identity=None):

        super(Trigpoint, self).__init__(latitude, longitude)
        self.altitude = altitude
        self.name = name
        self.identity = identity

Initialise a new ``Trigpoint`` object.

Args:
latitude (float): Location's latitude
longitude (float): Location's longitude
altitude (float): Location's altitude
name (str): Name for location
identity (int): Database identifier, if known


def extract_build_info(exe_path, elf_section=ELF_SECTION):

    build_info = {}
    with mkdtemp() as tempd, pushd(tempd):
        proc = subprocess.Popen(
            [
                OBJCOPY,
                DUMP_SECTION,
                "{secn}={ofile}".format(secn=elf_section, ofile=BUILDINFO_FILE),
                exe_path,
            ],
            stderr=subprocess.PIPE,
        )
        proc.wait()
        errno = proc.returncode
        stderr = proc.stderr.read()
        if errno or len(stderr):
            LOGGER.warning('objcopy failed with errno %s.', errno)
            if len(stderr):
                LOGGER.warning('objcopy failed with following msg:\n%s', stderr)
            return build_info

        with open(BUILDINFO_FILE) as build_info_f:
            try:
                build_info = json.load(build_info_f, object_hook=byteify)
            except JSONDcdError as jsde:
                LOGGER.warning('benchmark executable build is not valid json:')
                LOGGER.warning(jsde.msg)
                LOGGER.warning('build info section content:')
                LOGGER.warning(jsde.doc)
    return build_info

Extracts the build information from a given executable.

The build information is expected to be in json format, which is parsed
and returned as a dictionary.
If no build information is found an empty dictionary is returned.

This assumes binutils 2.25 to work.

Args:
exe_path (str): The full path to the executable to be examined

Returns:
dict: A dictionary of the extracted information.


def IsOutOfLineMethodDefinition(clean_lines, linenum):

  for i in xrange(linenum, max(-1, linenum - 10), -1):
    if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
      return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
  return False

Check if current line contains an out-of-line method definition.

Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition.


def diff_commonOverlap(self, text1, text2):

    text1_length = len(text1)
    text2_length = len(text2)

    if text1_length == 0 or text2_length == 0:
      return 0

    if text1_length > text2_length:
      text1 = text1[-text2_length:]
    elif text1_length < text2_length:
      text2 = text2[:text1_length]
    text_length = min(text1_length, text2_length)

    if text1 == text2:
      return text_length

    best = 0
    length = 1
    while True:
      pattern = text1[-length:]
      found = text2.find(pattern)
      if found == -1:
        return best
      length += found
      if found == 0 or text1[-length:] == text2[:length]:
        best = length
        length += 1

Determine if the suffix of one string is the prefix of another.

Args:
text1 First string.
text2 Second string.

Returns:
The number of characters common to the end of the first
string and the start of the second string.


def tag(self, repository, tag=None, **kwargs):
    return self.client.api.tag(self.id, repository, tag=tag, **kwargs)

Tag this image into a repository. Similar to the ``docker tag``
command.

Args:
repository (str): The repository to set for the tag
tag (str): The tag name
force (bool): Force

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

Returns:
(bool): ``True`` if successful


def value_to_string(self, obj):
    value = self._get_val_from_obj(obj)
    return self.get_prep_value(value)

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

Used during model serialization.

Args:
obj: db.Model, model object

Returns:
string, the serialized field value


def load_feather(protein_feather, length_filter_pid=None, copynum_scale=False, copynum_df=None):

    protein_df = pd.read_feather(protein_feather).set_index('index')

    from ssbio.protein.sequence.properties.residues import _aa_property_dict_one, EXTENDED_AA_PROPERTY_DICT_ONE
    aggregators = {
        'aa_count_bulk'    : {'residues': EXTENDED_AA_PROPERTY_DICT_ONE['Bulky'],
                              'subseqs' : ['metal_2_5D', 'metal_3D']},
        'aa_count_carb'    : {'residues': EXTENDED_AA_PROPERTY_DICT_ONE['Carbonylation susceptible'],
                              'subseqs' : ['metal_2_5D', 'metal_3D', 'acc_2D', 'acc_3D', 'surface_3D']},
        'aa_count_chrg'    : {'residues': _aa_property_dict_one['Charged'],
                              'subseqs' : ['metal_2_5D', 'metal_3D', 'csa_2_5D', 'sites_2_5D', 'acc_2D', 'acc_3D',
                                           'surface_3D']},
        'aa_count_poschrg' : {'residues': _aa_property_dict_one['Basic'],
                              'subseqs' : ['metal_2_5D', 'metal_3D', 'acc_2D', 'acc_3D', 'surface_3D']},
        'aa_count_negchrg' : {'residues': _aa_property_dict_one['Acidic'],
                              'subseqs' : ['metal_2_5D', 'metal_3D', 'acc_2D', 'acc_3D', 'surface_3D']},
        'aa_count_tmstab'  : {'residues': EXTENDED_AA_PROPERTY_DICT_ONE['TM stabilizing'],
                              'subseqs' : ['tm_2D', 'tm_3D']},
        'aa_count_tmunstab': {'residues': EXTENDED_AA_PROPERTY_DICT_ONE['TM to Thr stabilizing'],
                              'subseqs' : ['tm_2D', 'tm_3D']},
        'aa_count_dis'     : {'residues': EXTENDED_AA_PROPERTY_DICT_ONE['Disorder promoting'],
                              'subseqs' : ['disorder_2D', 'ss_disorder_2D', 'disorder_3D', 'ss_disorder_3D',
                                           'dna_2_5D']},
        'aa_count_ord'     : {'residues': EXTENDED_AA_PROPERTY_DICT_ONE['Order promoting'],
                              'subseqs' : ['disorder_2D', 'ss_disorder_2D', 'disorder_3D', 'ss_disorder_3D',
                                           'dna_2_5D']}}

    for suffix, info in aggregators.items():
        agg_residues = info['residues']
        for prefix in info['subseqs']:
            to_add_idxes = []
            for agg_res in agg_residues:
                to_add_idx = prefix + '_aa_count_' + agg_res
                if to_add_idx in protein_df.index:
                    to_add_idxes.append(to_add_idx)
            subseq_agged_col = protein_df.loc[to_add_idxes, :].sum()
            protein_df.loc[prefix + '_' + suffix] = subseq_agged_col

    if length_filter_pid:
        keep_cols = protein_df.loc['aa_count_total'][protein_df.loc['aa_count_total'] > protein_df.at['aa_count_total', 'K12'] * length_filter_pid].index
        protein_df = protein_df[keep_cols]

    if copynum_scale:
        if not isinstance(copynum_df, pd.DataFrame):
            raise ValueError('Please supply copy numbers')
        protein_id = op.basename(protein_feather).split('_protein')[0]
        if protein_id in copynum_df.index:
            copynum = copynum_df.at[protein_id, 'copynum']
            if copynum > 0:
                protein_df = protein_df * copynum

    return protein_df

Load a feather of amino acid counts for a protein.

Args:
protein_feather (str): path to feather file
copynum_scale (bool): if counts should be multiplied by protein copy number
copynum_df (DataFrame): DataFrame of copy numbers

Returns:
DataFrame: of counts with some aggregated together


def num_inputs(self):
    num = 0
    for (walker, _) in self.inputs:
        if (not isinstance(walker, InvalidStreamWalker)):
            num += 1
    return num

Return the number of connected inputs.

Returns:
int: The number of connected inputs


def get_sparse_tensors(self, transformation_cache, state_manager):
    pass

Returns an IdWeightPair.

`IdWeightPair` is a pair of `SparseTensor`s which represents ids and
weights.

`IdWeightPair.id_tensor` is typically a `batch_size` x `num_buckets`
`SparseTensor` of `int64`. `IdWeightPair.weight_tensor` is either a
`SparseTensor` of `float` or `None` to indicate all weights should be
taken to be 1. If specified, `weight_tensor` must have exactly the same
shape and indices as `sp_ids`. Expected `SparseTensor` is same as parsing
output of a `VarLenFeature` which is a ragged matrix.

Args:
transformation_cache: A `FeatureTransformationCache` object to access
features.
state_manager: A `StateManager` to create / access resources such as
lookup tables.


def _parse_data_fields(self, fields, tag_id='tag', sub_id='code'):
    for field in fields:
        params = field.params
        if (tag_id not in params):
            continue
        field_repr = OrderedDict([[self.i1_name, params.get(self.i1_name, ' ')], [self.i2_name, params.get(self.i2_name, ' ')]])
        for subfield in field.find('subfield'):
            if (sub_id not in subfield.params):
                continue
            content = MARCSubrecord(val=subfield.getContent().strip(), i1=field_repr[self.i1_name], i2=field_repr[self.i2_name], other_subfields=field_repr)
            code = subfield.params[sub_id]
            if (code in field_repr):
                field_repr[code].append(content)
            else:
                field_repr[code] = [content]
        tag = params[tag_id]
        if (tag in self.datafields):
            self.datafields[tag].append(field_repr)
        else:
            self.datafields[tag] = [field_repr]

Parse data fields.

Args:
fields (list): of HTMLElements
tag_id (str): parameter name, which holds the information, about
field name this is normally "tag", but in case of
oai_marc "id"
sub_id (str): id of parameter, which holds informations about
subfield name this is normally "code" but in case of
oai_marc "label"


def unpack(self, buff, offset=0):

        try:
            begin = offset
            end = begin + self.length
            unpacked_data = struct.unpack(self._fmt, buff[begin:end])[0]
        except struct.error:
            raise Exception("%s: %s" % (offset, buff))

        self._value = unpacked_data.decode('ascii').rstrip('\0')

Unpack a binary message into this object's attributes.

Unpack the binary value *buff* and update this object attributes based
on the results.

Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking.

Raises:
Exception: If there is a struct unpacking error.


def tmybasename(usaf):

    url_file = open(env.SRC_PATH + '/tmy3.csv')
    for line in url_file.readlines():
        if line.find(usaf) is not -1:
            return line.rstrip().partition(',')[0]

Basename for USAF base.

Args:
usaf (str): USAF code

Returns:
(str)


def sg_arg():
    if (not tf.app.flags.FLAGS.__dict__['__parsed']):
        tf.app.flags.FLAGS._parse_flags()
    return tf.sg_opt(tf.app.flags.FLAGS.__dict__['__flags'])

r"""Gets current command line options

Returns:
tf.sg_opt instance that is updated with current commandd line options.


def join(basepath, *paths):
    filesystem = FileSystems.get_filesystem(basepath)
    return filesystem.join(basepath, *paths)

Join two or more pathname components for the filesystem

Args:
basepath: string path of the first component of the path
paths: path components to be added

Returns: full path after combining all the passed components


def depth_september_average_ground_temperature(self, value=None):

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

        self._depth_september_average_ground_temperature = value

Corresponds to IDD Field
`depth_september_average_ground_temperature`

Args:
value (float): value for IDD Field `depth_september_average_ground_temperature`
Unit: C
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 create_channel(target, credentials=None, scopes=None, ssl_credentials=None, **kwargs):
    if (credentials is None):
        (credentials, _) = google.auth.default(scopes=scopes)
    else:
        credentials = google.auth.credentials.with_scopes_if_required(credentials, scopes)
    request = google.auth.transport.requests.Request()
    metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin(credentials, request)
    google_auth_credentials = grpc.metadata_call_credentials(metadata_plugin)
    if (ssl_credentials is None):
        ssl_credentials = grpc.ssl_channel_credentials()
    composite_credentials = grpc.composite_channel_credentials(ssl_credentials, google_auth_credentials)
    if HAS_GRPC_GCP:
        return grpc_gcp.secure_channel(target, composite_credentials, **kwargs)
    else:
        return grpc.secure_channel(target, composite_credentials, **kwargs)

Create a secure channel with credentials.

Args:
target (str): The target service address in the format 'hostname:port'.
credentials (google.auth.credentials.Credentials): The credentials. If
not specified, then this function will attempt to ascertain the
credentials from the environment using :func:`google.auth.default`.
scopes (Sequence[str]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
credentials. This can be used to specify different certificates.
kwargs: Additional key-word args passed to
:func:`grpc_gcp.secure_channel` or :func:`grpc.secure_channel`.

Returns:
grpc.Channel: The created channel.


def extract_code(end_mark, current_str, str_array, line_num):
    if (end_mark not in current_str):
        reached_end = False
        line_num += 1
        while (reached_end is False):
            next_line = str_array[line_num]
            if (end_mark in next_line):
                reached_end = True
            else:
                line_num += 1
            current_str += next_line
    clean_str = current_str.split(end_mark)[0]
    return {'current_str': clean_str, 'line_num': line_num}

Extract a multi-line string from a string array, up to a specified end marker.

Args:
end_mark (str): The end mark string to match for.
current_str (str): The first line of the string array.
str_array (list): An array of strings (lines).
line_num (int): The current offset into the array.

Returns:
Extended string up to line with end marker.


def get_element_from_dict_by_path(d, path):
    path = path.split('.')
    for k in path:
        if k not in d:
            d[k] = {}
        d = d[k]
    return d

Get element from dictionary by path. If element is not present, recursively add empty dictionaries.

Args:
d (dict): the dictionary to get the element from
path (list): the path to the element which is delimited by "."


def _CheckStatusWorkerProcess(self, pid):
    self._RaiseIfNotRegistered(pid)
    process = self._processes_per_pid[pid]
    process_status = self._QueryProcessStatus(process)
    if (process_status is None):
        process_is_alive = False
    else:
        process_is_alive = True
    process_information = self._process_information_per_pid[pid]
    used_memory = (process_information.GetUsedMemory() or 0)
    if (self._worker_memory_limit and (used_memory > self._worker_memory_limit)):
        logger.warning('Process: {0:s} (PID: {1:d}) killed because it exceeded the memory limit: {2:d}.'.format(process.name, pid, self._worker_memory_limit))
        self._KillProcess(pid)
    if isinstance(process_status, dict):
        self._rpc_errors_per_pid[pid] = 0
        status_indicator = process_status.get('processing_status', None)
    else:
        rpc_errors = (self._rpc_errors_per_pid.get(pid, 0) + 1)
        self._rpc_errors_per_pid[pid] = rpc_errors
        if (rpc_errors > self._MAXIMUM_RPC_ERRORS):
            process_is_alive = False
        if process_is_alive:
            rpc_port = process.rpc_port.value
            logger.warning('Unable to retrieve process: {0:s} (PID: {1:d}) status via RPC socket: http:
            processing_status_string = 'RPC error'
            status_indicator = definitions.STATUS_INDICATOR_RUNNING
        else:
            processing_status_string = 'killed'
            status_indicator = definitions.STATUS_INDICATOR_KILLED
        process_status = {'processing_status': processing_status_string}
    self._UpdateProcessingStatus(pid, process_status, used_memory)
    for worker_status in self._processing_status.workers_status:
        if (worker_status.pid == pid):
            status_indicator = worker_status.status
            break
    if (status_indicator in definitions.ERROR_STATUS_INDICATORS):
        logger.error('Process {0:s} (PID: {1:d}) is not functioning correctly. Status code: {2!s}.'.format(process.name, pid, status_indicator))
        self._TerminateProcessByPid(pid)
        replacement_process = None
        for replacement_process_attempt in range(self._MAXIMUM_REPLACEMENT_RETRIES):
            logger.info('Attempt: {0:d} to start replacement worker process for {1:s}'.format((replacement_process_attempt + 1), process.name))
            replacement_process = self._StartWorkerProcess(process.name, self._storage_writer)
            if replacement_process:
                break
            time.sleep(self._REPLACEMENT_WORKER_RETRY_DELAY)
        if (not replacement_process):
            logger.error('Unable to create replacement worker process for: {0:s}'.format(process.name))

Checks the status of a worker process.

If a worker process is not responding the process is terminated and
a replacement process is started.

Args:
pid (int): process ID (PID) of a registered worker process.

Raises:
KeyError: if the process is not registered with the engine.


def _quadratic_sum_cost(self, state: _STATE) -> float:

        cost = 0.0
        total_len = float(len(self._c))
        seqs, _ = state
        for seq in seqs:
            cost += (len(seq) / total_len) ** 2
        return -cost

Cost function that sums squares of lengths of sequences.

Args:
state: Search state, not mutated.

Returns:
Cost which is minus the normalized quadratic sum of each linear
sequence section in the state. This promotes single, long linear
sequence solutions and converges to number -1. The solution with a
lowest cost consists of every node being a single sequence and is
always less than 0.


def _convert_to_dict(data):

    if isinstance(data, dict):
        return data

    if isinstance(data, list) or isinstance(data, tuple):
        if _all_correct_list(data):
            return dict(data)
        else:
            data = zip(data[::2], data[1::2])
            return dict(data)
    else:
        raise MetaParsingException(
            "Can't decode provided metadata - unknown structure."
        )

Convert `data` to dictionary.

Tries to get sense in multidimensional arrays.

Args:
data: List/dict/tuple of variable dimension.

Returns:
dict: If the data can be converted to dictionary.

Raises:
MetaParsingException: When the data are unconvertible to dict.


def convert_to_beam_types(args):
    if isinstance(args, dict):
        return {k: convert_to_beam_type(v) for k, v in args.items()}
    else:
        return [convert_to_beam_type(v) for v in args]

Convert the given list or dictionary of args to Beam types.

Args:
args: Either an iterable of types, or a dictionary where the values are
types.

Returns:
If given an iterable, a list of converted types. If given a dictionary,
a dictionary with the same keys, and values which have been converted.


def strip_cdata(text):

    if not is_cdata(text):
        return text

    xml = "<e>{0}</e>".format(text)
    node = etree.fromstring(xml)
    return node.text

Removes all CDATA blocks from `text` if it contains them.

Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.

Args:
A string containing one or more CDATA blocks.

Returns:
An XML unescaped string with CDATA block qualifiers removed.


def reset_internal_states(self, record=None):

        self._record = None
        self._count = 0
        self._record = record

Resets the internal state of the recorder.

Args:
record: records.TestResultRecord, the test record for a test.


def setPartationId(self, partationId):

        print '%s call setPartationId' % self.port
        print partationId

        cmd = WPANCTL_CMD + 'setprop Network:PartitionId %s' %(str(hex(partationId)).rstrip('L'))
        print cmd
        return self.__sendCommand(cmd)[0] != 'Fail'

set Thread Network Partition ID

Args:
partitionId: partition id to be set by leader

Returns:
True: successful to set the Partition ID
False: fail to set the Partition ID


def indicator(self, data):

        if self._name != 'Bulk' or self._name != 'Indicator':
            self._request_uri = '{}/{}'.format(
                self._api_uri, self.tcex.safe_indicator(data, 'ignore')
            )

Update the request URI to include the Indicator for specific indicator retrieval.

Args:
data (string): The indicator value


class BridgeTowerFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
    size_divisor: Optional[int]
    do_pad: Optional[bool]

Args:
size_divisor (`int`, *optional*, defaults to 32):
The size by which to make sure both the height and width can be divided. Only has an effect if `do_resize`
is set to `True`. Can be overridden by the `size_divisor` parameter in the `preprocess` method.
do_pad (`bool`, *optional*, defaults to `True`):
Whether to pad the image to the `(max_height, max_width)` of the images in the batch. Can be overridden by
the `do_pad` parameter in the `preprocess` method.


def reassign_label(cls, destination_cluster, label):

        conn = Qubole.agent(version=Cluster.api_version)
        data = {
                    "destination_cluster": destination_cluster,
                    "label": label
                }
        return conn.put(cls.rest_entity_path + "/reassign-label", data)

Reassign a label from one cluster to another.

Args:
`destination_cluster`: id/label of the cluster to move the label to

`label`: label to be moved from the source cluster


def _maybe_download_corpus(tmp_dir, vocab_type):

  filename = os.path.basename(PTB_URL)
  compressed_filepath = generator_utils.maybe_download(
      tmp_dir, filename, PTB_URL)
  ptb_files = []
  ptb_char_files = []

  with tarfile.open(compressed_filepath, "r:gz") as tgz:
    files = []

    for m in tgz.getmembers():
      if "ptb" in m.name and ".txt" in m.name:
        if "char" in m.name:
          ptb_char_files += [m.name]
        else:
          ptb_files += [m.name]
        files += [m]

    tgz.extractall(tmp_dir, members=files)

  if vocab_type == text_problems.VocabType.CHARACTER:
    return ptb_char_files
  else:
    return ptb_files

Download and unpack the corpus.

Args:
tmp_dir: directory containing dataset.
vocab_type: which vocabulary are we using.

Returns:
The list of names of files.


def bash_complete(self, path, cmd, *cmds):

        path = pathlib.Path(path)
        subcmds = list(self.subcmds.keys())
        with path.open('w') as bcf:

            print('_{}() {{'.format(cmd), file=bcf)
            print('COMPREPLY=()', file=bcf)
            print(r'local cur=${COMP_WORDS[COMP_CWORD]}', end='\n\n', file=bcf)
            optstr = ' '.join(self._bash_comp_command(None))
            print(r'local options="{}"'.format(optstr), end='\n\n', file=bcf)
            if subcmds:
                print('local commands="{}"'.format(' '.join(subcmds)),
                      file=bcf)
                print('declare -A suboptions', file=bcf)
            for sub in subcmds:
                optstr = ' '.join(self._bash_comp_command(sub))
                print('suboptions[{}]="{}"'.format(sub, optstr), file=bcf)
            condstr = 'if'
            for sub in subcmds:
                print(condstr, r'[[ "${COMP_LINE}" == *"', sub, '"* ]] ; then',
                      file=bcf)
                print(r'COMPREPLY=( `compgen -W "${suboptions[', sub,
                      r']}" -- ${cur}` )', sep='', file=bcf)
                condstr = 'elif'
            print(condstr, r'[[ ${cur} == -* ]] ; then', file=bcf)
            print(r'COMPREPLY=( `compgen -W "${options}" -- ${cur}`)',
                  file=bcf)
            if subcmds:
                print(r'else', file=bcf)
                print(r'COMPREPLY=( `compgen -W "${commands}" -- ${cur}`)',
                      file=bcf)
            print('fi', file=bcf)
            print('}', end='\n\n', file=bcf)
            print('complete -F _{0} {0}'.format(cmd), *cmds, file=bcf)

Write bash complete script.

Args:
path (path-like): desired path of the complete script.
cmd (str): command name that should be completed.
cmds (str): extra command names that should be completed.


def write(self, noautocmd=False):

        cmd = 'noautocmd write' if noautocmd else 'write'
        self._vim.command(cmd)

Writes the file of the current buffer.

Args:
noautocmd (bool): If true, write will skip autocommands.

Todo:
We should consider whether ``SourceFileInfo`` can replace most
usage of noautocmd. See #298


def get_texture(self, label: str) -> Union[(moderngl.Texture, moderngl.TextureArray, moderngl.Texture3D, moderngl.TextureCube)]:
    return self._project.get_texture(label)

Get a texture by its label

Args:
label (str): The Label for the texture

Returns:
The py:class:`moderngl.Texture` instance


def _einsum_matmul(cls, tensor, mat, indices, shift=0, right_mul=False):
    rank = tensor.ndim
    rank_mat = mat.ndim
    if ((rank_mat % 2) != 0):
        raise QiskitError('Contracted matrix must have an even number of indices.')
    indices_tensor = list(range(rank))
    for (j, index) in enumerate(indices):
        indices_tensor[(index + shift)] = (rank + j)
    mat_contract = list(reversed(range(rank, (rank + len(indices)))))
    mat_free = [(index + shift) for index in reversed(indices)]
    if right_mul:
        indices_mat = (mat_contract + mat_free)
    else:
        indices_mat = (mat_free + mat_contract)
    return np.einsum(tensor, indices_tensor, mat, indices_mat)

Perform a contraction using Numpy.einsum

Args:
tensor (np.array): a vector or matrix reshaped to a rank-N tensor.
mat (np.array): a matrix reshaped to a rank-2M tensor.
indices (list): tensor indices to contract with mat.
shift (int): shift for indicies of tensor to contract [Default: 0].
right_mul (bool): if True right multiply tensor by mat
(else left multiply) [Default: False].

Returns:
Numpy.ndarray: the matrix multiplied rank-N tensor.

Raises:
QiskitError: if mat is not an even rank tensor.


def serialize_to_display(self, doc_format="pretty-xml", *args, **kwargs):

        return (
            super(ResourceMap, self)
            .serialize(format=doc_format, encoding=None, *args, **kwargs)
            .decode("utf-8")
        )

Serialize ResourceMap to an XML doc that is pretty printed for display.

Args:
doc_format: str
One of: ``xml``, ``n3``, ``turtle``, ``nt``, ``pretty-xml``, ``trix``,
``trig`` and ``nquads``.

args and kwargs:
Optional arguments forwarded to rdflib.ConjunctiveGraph.serialize().

Returns:
str: Pretty printed Resource Map XML doc

Note:
Only the default, "xml", is automatically indexed by DataONE.


def update_default(self, new_default, respect_none=False):

        if new_default is not None:
            self.default = new_default
        elif new_default is None and respect_none:
            self.default = None

Update our current default with the new_default.

Args:
new_default: New default to set.
respect_none: Flag to determine if ``None`` is a valid value.


def identify(self, token):
    payload = {'op': 2, 'd': {'token': self.token, 'properties': {'$os': sys.platform, '$browser': 'legobot', '$device': 'legobot'}, 'compress': False, 'large_threshold': 250}}
    payload['d']['synced_guilds'] = []
    logger.info('Identifying with the following message:                     {}'.format(payload))
    self.ws.send(json.dumps(payload))
    return

Identifies to the websocket endpoint

Args:
token (string): Discord bot token


def list_asgs(access_token, subscription_id, resource_group):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', resource_group,
                        '/providers/Microsoft.Network/virtualNetworks/',
                        '?api-version=', NETWORK_API])
    return do_get(endpoint, access_token)

Get details about the application security groups for a resource group.

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

Returns:
HTTP response. ASG JSON body.


def build(self, variables):
    if self.built:
        return
    super().build(variables)
    self.momentums = []
    if self.momentum != 0:
        self.momentums = self.add_optimizer_variables(variables, 'momentum')

Initialize optimizer variables.

SGD optimizer has one variable `momentums`, only set if `self.momentum`
is not 0.

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