def split_vert_on_nonmanifold_face(script, vert_displacement_ratio=0.0):
    filter_xml = ''.join(['  <filter name="Split Vertexes Incident on Non Manifold Faces">\n', '    <Param name="VertDispRatio" ', 'value="{}" '.format(vert_displacement_ratio), 'description="Vertex Displacement Ratio" ', 'type="RichFloat" ', '/>\n', '  </filter>\n'])
    util.write_filter(script, filter_xml)
    return None

Split non-manifold vertices until it becomes two-manifold.

Args:
script: the FilterScript object or script filename to write
the filter to.
vert_displacement_ratio (float): When a vertex is split it is moved
along the average vector going from its position to the centroid
of the FF connected faces sharing it.

Layer stack:
No impacts

MeshLab versions:
2016.12
1.3.4BETA


def nearest_neighbour_delta_E(self):
    delta_nn = ((self.final_site.nn_occupation() - self.initial_site.nn_occupation()) - 1)
    return (delta_nn * self.nearest_neighbour_energy)

Nearest-neighbour interaction contribution to the change in system energy if this jump were accepted.

Args:
None

Returns:
(Float): delta E (nearest-neighbour)


def parse_results(self, data):

        results = []
        if len(data["Records"]) < 1:
            return -1

        codes = data["Records"][0]["Results"]
        for code in codes.split(","):
            results.append(str(code))

        self.addr1 = data["Records"][0]["AddressLine1"]
        self.addr2 = data["Records"][0]["AddressLine2"]
        self.city = data["Records"][0]["City"]
        self.name = data["Records"][0]["NameFull"]
        self.phone = data["Records"][0]["PhoneNumber"]
        self.province = data["Records"][0]["State"]
        self.postal = data["Records"][0]["PostalCode"]
        self.recordID = data["Records"][0]["RecordID"]
        return results

parse_results

Parses the MelissaData response.

Args:
data (dict): Contains MelissaData response

Returns:
results, either contains a dict with corrected address info or -1 for an invalid address.


def peek(init, exposes, debug=False):

    def _peek(store, container, _stack=None):
        args = [ store.peek(objname, container, _stack=_stack) \
            for objname in exposes ]
        if debug:
            print(args)
        return init(*args)
    return _peek

Default deserializer factory.

Arguments:

init (callable): type constructor.

exposes (iterable): attributes to be peeked and passed to `init`.

Returns:

callable: deserializer (`peek` routine).


def __init__(self, default_environment: Optional[environments.Environment]=None, bundle_repeat: int=0, use_state_iterables: bool=False, provision_info: Optional['ExtendedProvisionInfo']=None, progress_request_frequency: Optional[float]=None, is_drain: bool=False) -> None:
    super().__init__()
    self._default_environment = default_environment or environments.EmbeddedPythonEnvironment.default()
    self._bundle_repeat = bundle_repeat
    self._num_workers = 1
    self._progress_frequency = progress_request_frequency
    self._profiler_factory: Optional[Callable[..., Profile]] = None
    self._use_state_iterables = use_state_iterables
    self._is_drain = is_drain
    self._provision_info = provision_info or ExtendedProvisionInfo(beam_provision_api_pb2.ProvisionInfo(retrieval_token='unused-retrieval-token'))

Creates a new Fn API Runner.

Args:
default_environment: the default environment to use for UserFns.
bundle_repeat: replay every bundle this many extra times, for profiling
and debugging
use_state_iterables: Intentionally split gbk iterables over state API
(for testing)
provision_info: provisioning info to make available to workers, or None
progress_request_frequency: The frequency (in seconds) that the runner
waits before requesting progress from the SDK.
is_drain: identify whether expand the sdf graph in the drain mode.


def scripthash_to_address(scripthash):
    sb = (bytearray([ADDRESS_VERSION]) + scripthash)
    c256 = bin_dbl_sha256(sb)[0:4]
    outb = (sb + bytearray(c256))
    return base58.b58encode(bytes(outb)).decode('utf-8')

Convert a script hash to a public address.

Args:
scripthash (bytes):

Returns:
str: base58 encoded string representing the wallet address.


def build_relative_position(query_size, key_size, bucket_size=-1, max_position=-1):
    q_ids = tf.range(query_size, dtype=tf.int32)
    k_ids = tf.range(key_size, dtype=tf.int32)
    rel_pos_ids = q_ids[:, None] - tf.tile(tf.expand_dims(k_ids, axis=0), [shape_list(q_ids)[0], 1])
    if bucket_size > 0 and max_position > 0:
        rel_pos_ids = make_log_bucket_position(rel_pos_ids, bucket_size, max_position)
    rel_pos_ids = rel_pos_ids[:query_size, :]
    rel_pos_ids = tf.expand_dims(rel_pos_ids, axis=0)
    return tf.cast(rel_pos_ids, tf.int64)

Build relative position according to the query and key

We assume the absolute position of query \(P_q\) is range from (0, query_size) and the absolute position of key
\(P_k\) is range from (0, key_size), The relative positions from query to key is \(R_{q \rightarrow k} = P_q -
P_k\)

Args:
query_size (int): the length of query
key_size (int): the length of key
bucket_size (int): the size of position bucket
max_position (int): the maximum allowed absolute position

Return:
`tf.Tensor`: A tensor with shape [1, query_size, key_size]


def virt_env(self):
    if (self._virt_env is None):
        self._virt_env = self._create_virt_env()
    return self._virt_env

Getter for this instance's virt env, creates it if needed

Returns:
lago.virt.VirtEnv: virt env instance used by this prefix


def observe(self, value):
    self._buffer.append(value)
    if (len(self._buffer) == _BUFFER_SIZE):
        self._flush()

Samples an observation's value.

Args:
value: A numeric value signifying the value to be sampled.


def get_subnets(target='ec2', purpose='internal', env='', region=''):
    account_az_dict = defaultdict(defaultdict)
    subnet_id_dict = defaultdict(defaultdict)
    subnet_url = '{0}/subnets/aws'.format(API_URL)
    subnet_response = requests.get(subnet_url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)
    if (not subnet_response.ok):
        raise SpinnakerTimeout(subnet_response.text)
    subnet_list = subnet_response.json()
    for subnet in subnet_list:
        LOG.debug('Subnet: %(account)s\t%(region)s\t%(target)s\t%(vpcId)s\t%(availabilityZone)s', subnet)
        if (subnet.get('target', '') == target):
            availability_zone = subnet['availabilityZone']
            account = subnet['account']
            subnet_region = subnet['region']
            subnet_id = subnet['id']
            try:
                if (availability_zone not in account_az_dict[account][subnet_region]):
                    account_az_dict[account][subnet_region].append(availability_zone)
            except KeyError:
                account_az_dict[account][subnet_region] = [availability_zone]
            if (subnet['purpose'] == purpose):
                try:
                    subnet_id_dict[account][subnet_region].append(subnet_id)
                except KeyError:
                    subnet_id_dict[account][subnet_region] = [subnet_id]
            LOG.debug('%s regions: %s', account, list(account_az_dict[account].keys()))
    if all([env, region]):
        try:
            region_dict = {region: account_az_dict[env][region]}
            region_dict['subnet_ids'] = {region: subnet_id_dict[env][region]}
            LOG.debug('Region dict: %s', region_dict)
            return region_dict
        except KeyError:
            raise SpinnakerSubnetError(env=env, region=region)
    LOG.debug('AZ dict:\n%s', pformat(dict(account_az_dict)))
    return account_az_dict

Get all availability zones for a given target.

Args:
target (str): Type of subnets to look up (ec2 or elb).
env (str): Environment to look up.
region (str): AWS Region to find Subnets for.

Returns:
az_dict: dictionary of  availbility zones, structured like
{ $region: [ $avaibilityzones ] }
or
{ $account: $region: [ $availabilityzone] }


def _preprocess(self, inputs: Sequence[torch.Tensor], freq: Sequence[int]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    input_ts, input_padding, inp_freq = ([], [], [])
    for i, ts in enumerate(inputs):
        input_len = ts.shape[0]
        padding = torch.zeros(input_len + self.horizon_len, dtype=ts.dtype, device=ts.device)
        if input_len < self.context_len:
            num_front_pad = self.context_len - input_len
            ts = torch.cat([torch.zeros(num_front_pad, dtype=ts.dtype, device=ts.device), ts], dim=0)
            padding = torch.cat([torch.ones(num_front_pad, dtype=ts.dtype, device=padding.device), padding], dim=0)
        elif input_len > self.context_len:
            ts = ts[-self.context_len:]
            padding = padding[-(self.context_len + self.horizon_len):]
        input_ts.append(ts)
        input_padding.append(padding)
        inp_freq.append(freq[i])
    return (torch.stack(input_ts, dim=0), torch.stack(input_padding, dim=0), torch.tensor(inp_freq, dtype=torch.int32).reshape(-1, 1))

Formats and pads raw inputs to feed into the model.

This function both pads each time series to match the context length, and
pads the inputs to meet the SPMD shape requirement.

Args:
inputs: A list of 1d Tensors. Each Tensor is the context time series of
a single forecast task.
freq: list of frequencies

Returns:
A tuple of:
- the padded input time series to meet the model required context.
- the padding indicator.
- the number of padded examples for SPMD so that each core has the same
number (a multiple of `batch_size`) of examples.


def dbmax10years(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 `dbmax10years`'.format(value))
    self._dbmax10years = value

Corresponds to IDD Field `dbmax10years`
10-year return period values for maximum extreme dry-bulb temperature

Args:
value (float): value for IDD Field `dbmax10years`
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 _locate_point(nodes, point):
    candidates = [(0.0, 1.0, nodes)]
    for _ in six.moves.xrange((_MAX_LOCATE_SUBDIVISIONS + 1)):
        next_candidates = []
        for (start, end, candidate) in candidates:
            if _helpers.contains_nd(candidate, point.ravel(order='F')):
                midpoint = (0.5 * (start + end))
                (left, right) = subdivide_nodes(candidate)
                next_candidates.extend(((start, midpoint, left), (midpoint, end, right)))
        candidates = next_candidates
    if (not candidates):
        return None
    params = [(start, end) for (start, end, _) in candidates]
    if (np.std(params) > _LOCATE_STD_CAP):
        raise ValueError('Parameters not close enough to one another', params)
    s_approx = np.mean(params)
    s_approx = newton_refine(nodes, point, s_approx)
    if (s_approx < 0.0):
        return 0.0
    elif (s_approx > 1.0):
        return 1.0
    else:
        return s_approx

r"""Locate a point on a curve.

Does so by recursively subdividing the curve and rejecting
sub-curves with bounding boxes that don't contain the point.
After the sub-curves are sufficiently small, uses Newton's
method to zoom in on the parameter value.

.. note::

This assumes, but does not check, that ``point`` is ``D x 1``,
where ``D`` is the dimension that ``curve`` is in.

.. note::

There is also a Fortran implementation of this function, which
will be used if it can be built.

Args:
nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve.
point (numpy.ndarray): The point to locate.

Returns:
Optional[float]: The parameter value (:math:`s`) corresponding
to ``point`` or :data:`None` if the point is not on the ``curve``.

Raises:
ValueError: If the standard deviation of the remaining start / end
parameters among the subdivided intervals exceeds a given
threshold (e.g. :math:`2^{-20}`).


def flatten_rules(self, declarations):
    rules = []
    for (protocole, paths) in declarations:
        if protocole:
            continue
        rules.extend([self.strip_quotes(v.strip()) for v in paths.split(',')])
    return list(filter(self.filter_rules, rules))

Flatten returned import rules from regex.

Because import rules can contains multiple items in the same rule
(called multiline import rule), the regex ``REGEX_IMPORT_RULE``
return a list of unquoted items for each rule.

Args:
declarations (list): A SCSS source.

Returns:
list: Given SCSS source with all comments removed.


def piece_to_id(input, model_file=None, model_proto=None, name=None):
    return _gen_sentencepiece_processor_op.sentencepiece_piece_to_id(input, model_file=model_file, model_proto=model_proto, name=name)

Converts piece into vocabulary id.

Args:
input: An arbitrary tensor of string.
model_file: The sentencepiece model file path.
model_proto: The sentencepiece model serialized proto.
Either `model_file` or `model_proto` must be set.
name: The name argument that is passed to the op function.
Returns:
A tensor of int32 with the same shape as input.


def pages(self):
    if (self._owner_id is None):
        it = ProfileIterator.from_username(self._username, self.session)
        self._owner_id = it.owner_id
        return it
    return ProfileIterator(self._owner_id, self.session, self.rhx)

Obtain an iterator over Instagram post pages.

Returns:
PageIterator: an iterator over the instagram post pages.

Raises:
ValueError: when the requested user does not exist.
RuntimeError: when the user is a private account
and there is no logged user (or the logged user
does not follow that account).


def createThread(parent, worker, deleteWorkerLater=False):
    thread = QtCore.QThread(parent)
    thread.started.connect(worker.doWork)
    worker.finished.connect(thread.quit)
    if deleteWorkerLater:
        thread.finished.connect(worker.deleteLater)
    worker.moveToThread(thread)
    worker.setParent(parent)
    return thread

Create a new thread for given worker.

Args:
parent (QObject): parent of thread and worker.
worker (ProgressWorker): worker to use in thread.
deleteWorkerLater (bool, optional): delete the worker if thread finishes.

Returns:
QThread


def _check_suffix(self, w_string, access_string, index):

        prefix_as = self._membership_query(access_string)
        full_as = self._membership_query(access_string + w_string[index:])

        prefix_w = self._membership_query(w_string[:index])
        full_w = self._membership_query(w_string)

        length = len(commonprefix([prefix_as, full_as]))
        as_suffix = full_as[length:]

        length = len(commonprefix([prefix_w, full_w]))
        w_suffix = full_w[length:]

        if as_suffix != w_suffix:
            logging.debug('Access string state incorrect')
            return True
        logging.debug('Access string state correct.')
        return False

Checks if access string suffix matches with the examined string suffix
Args:
w_string (str): The examined string to be consumed
access_string (str): The access string for the state
index (int): The index value for selecting the prefix of w
Returns:
bool: A boolean valuei indicating if matching was successful


def serialize_to_string(self, name, datas):
    value = datas.get('value', None)
    if (value is None):
        msg = "String reference '{}' lacks of required 'value' variable or is empty"
        raise SerializerError(msg.format(name))
    return value

Serialize given datas to a string.

Simply return the value from required variable``value``.

Arguments:
name (string): Name only used inside possible exception message.
datas (dict): Datas to serialize.

Returns:
string: Value.


def __le__(self, other):
    other = as_dimension(other)
    if self._value is None or other.value is None:
        return None
    else:
        return self._value <= other.value

Returns True if `self` is known to be less than or equal to `other`.

Dimensions are compared as follows:

```python
(tf.compat.v1.Dimension(m)    <= tf.compat.v1.Dimension(n))    == (m <= n)
(tf.compat.v1.Dimension(m)    <= tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) <= tf.compat.v1.Dimension(n))    == None
(tf.compat.v1.Dimension(None) <= tf.compat.v1.Dimension(None)) == None
```

Args:
other: Another Dimension.

Returns:
The value of `self.value <= other.value` if both are known, otherwise
None.


class GitProcessor(ProcessorMixin):
    attributes = ['image_processor', 'tokenizer']
    image_processor_class = 'AutoImageProcessor'
    tokenizer_class = 'AutoTokenizer'

    def __init__(self, image_processor, tokenizer):
        super().__init__(image_processor, tokenizer)
        self.current_processor = self.image_processor

    def __call__(self, images: Optional[ImageInput]=None, text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]]=None, audio=None, videos=None, **kwargs: Unpack[GitProcessorKwargs]) -> BatchFeature:

        if text is None and images is None:
            raise ValueError('You have to specify either text or images. Both cannot be none.')
        images, text = _validate_images_text_input_order(images, text)
        output_kwargs = self._merge_kwargs(GitProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs)
        data = {}
        if text is not None:
            text_features = self.tokenizer(text, **output_kwargs['text_kwargs'])
            data.update(text_features)
        if images is not None:
            image_features = self.image_processor(images, **output_kwargs['images_kwargs'])
            data.update(image_features)
        return BatchFeature(data=data, tensor_type=output_kwargs['common_kwargs'].get('return_tensors'))

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

        return self.tokenizer.batch_decode(*args, **kwargs)

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

        return self.tokenizer.decode(*args, **kwargs)

    @property
    def model_input_names(self):
        return ['input_ids', 'attention_mask', 'pixel_values']

Constructs a GIT processor which wraps a CLIP image processor and a BERT tokenizer into a single processor.

[`GitProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`BertTokenizerFast`]. See the
[`~GitProcessor.__call__`] and [`~GitProcessor.decode`] for more information.

Args:
image_processor ([`AutoImageProcessor`]):
The image processor is a required input.
tokenizer ([`AutoTokenizer`]):
The tokenizer is a required input.


def get_logger(name):

    logger = logging.getLogger(name)
    logger.addHandler(logging.NullHandler())
    return logger

Gets a logger

Arguments:
name - the name you wish to log as

Returns:
A logger!


def CacheObject(self, identifier, vfs_object):

    if identifier in self._values:
      raise KeyError('Object already cached for identifier: {0:s}'.format(
          identifier))

    if len(self._values) == self._maximum_number_of_cached_values:
      raise errors.CacheFullError('Maximum number of cached values reached.')

    self._values[identifier] = ObjectsCacheValue(vfs_object)

Caches a VFS object.

This method ignores the cache value reference count.

Args:
identifier (str): VFS object identifier.
vfs_object (object): VFS object to cache.

Raises:
CacheFullError: if he maximum number of cached values is reached.
KeyError: if the VFS object already is cached.


def get_or_create(session, model, **kwargs):
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return (instance, False)
    else:
        instance = model(**kwargs)
        if ('dataset' in kwargs):
            instance.update_sequence_id(session, kwargs['dataset'])
        session.add(instance)
        session.commit()
        return (instance, True)

Get or create sqlalchemy instance.

Args:
session (Sqlalchemy session):
model (sqlalchemy model):
kwargs (dict): kwargs to lookup or create instance.

Returns:
Tuple: first element is found or created instance, second is boolean - True if instance created,
False if instance found.


def nested_row_lengths(self, name=None):
    with ops.name_scope(name, 'RaggedNestedRowLengths', [self]):
        rt_nested_row_lengths = []
        rt = self
        while isinstance(rt, RaggedTensor):
            rt_nested_row_lengths.append(rt.row_lengths())
            rt = rt.values
        return tuple(rt_nested_row_lengths)

Returns a tuple containing the row_lengths for all ragged dimensions.

`rt.nested_row_lengths()` is a tuple containing the `row_lengths` tensors
for all ragged dimensions in `rt`, ordered from outermost to innermost.

Args:
name: A name prefix for the returned tensors (optional).

Returns:
A `tuple` of 1-D integer `Tensors`.  The length of the tuple is equal to
`self.ragged_rank`.


def converted_self(self):
    raise NotImplementedError

A copy of this Convertible to be modified during conversion.

Returns:
Implementations should return the copied instance, which in turn should
be contained in converted_enclosing_graph(). This instance is the one that
will be modified during conversion. Its main use will be in the
implementations of convert_variable_to_constant().


def monitored_timer(cell):

    def actual_decorator(func):

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            with MonitoredTimer(cell):
                return func(*args, **kwargs)
        return wrapper
    return actual_decorator

A function decorator for adding MonitoredTimer support.

Args:
cell: the cell associated with the time metric that will be inremented.
Returns:
A decorator that measure the function runtime and increment the specified
counter cell.


def convert(credentials):
    credentials_class = type(credentials)
    try:
        return _CLASS_CONVERSION_MAP[credentials_class](credentials)
    except KeyError as caught_exc:
        new_exc = ValueError(_CONVERT_ERROR_TMPL.format(credentials_class))
        six.raise_from(new_exc, caught_exc)

Convert oauth2client credentials to google-auth credentials.

This class converts:

- :class:`oauth2client.client.OAuth2Credentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.client.GoogleCredentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.service_account.ServiceAccountCredentials` to
:class:`google.oauth2.service_account.Credentials`.
- :class:`oauth2client.service_account._JWTAccessCredentials` to
:class:`google.oauth2.service_account.Credentials`.
- :class:`oauth2client.contrib.gce.AppAssertionCredentials` to
:class:`google.auth.compute_engine.Credentials`.
- :class:`oauth2client.contrib.appengine.AppAssertionCredentials` to
:class:`google.auth.app_engine.Credentials`.

Returns:
google.auth.credentials.Credentials: The converted credentials.

Raises:
ValueError: If the credentials could not be converted.


def clone(self, to_namespace, to_name):
    r = fapi.clone_workspace(self.namespace, self.name, to_namespace, to_name, self.api_url)
    fapi._check_response_code(r, 201)
    return Workspace(to_namespace, to_name, self.api_url)

Clone this workspace.

Args:
to_namespace (str): Target workspace namespace
to_name (str): Target workspace name


def issue(self, invoice_id, **kwargs):

        url = "{}/{}/issue".format(self.base_url, invoice_id)
        return self.post_url(url, {}, **kwargs)

Issues an invoice in draft state

Args:
invoice_id : Id for delete the invoice
Returns:
Its response is the invoice entity, similar to create/update API response. Its status now would be issued.


def _GetBetweenQEqualsAndAmpersand(self, url):

    _, _, url = url.partition('?')

    _, _, url = url.partition('q=')
    if not url:
      return ''

    url, _, _ = url.partition('&')
    return url

Retrieves the substring between the substrings 'q=' and '&'.

Args:
url (str): URL.

Returns:
str: search query, the value between 'q=' and '&'  or None if no query
was found.


def sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1):
    y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred)
    y_true = math_ops.cast(y_true, y_pred.dtype)
    return backend.sparse_categorical_crossentropy(y_true, y_pred, from_logits=from_logits, axis=axis)

Computes the sparse categorical crossentropy loss.

Standalone usage:

>>> y_true = [1, 2]
>>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
>>> loss = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred)
>>> assert loss.shape == (2,)
>>> loss.numpy()
array([0.0513, 2.303], dtype=float32)

Args:
y_true: Ground truth values.
y_pred: The predicted values.
from_logits: Whether `y_pred` is expected to be a logits tensor. By default,
we assume that `y_pred` encodes a probability distribution.
axis: Defaults to -1. The dimension along which the entropy is
computed.

Returns:
Sparse categorical crossentropy loss value.


def as_dict_summary(self, print_subelectrodes=True):

        chg_comp = self.fully_charged_entry.composition
        dischg_comp = self.fully_discharged_entry.composition

        ion = self.working_ion
        d = {"average_voltage": self.get_average_voltage(),
             "max_voltage": self.max_voltage,
             "min_voltage": self.min_voltage,
             "max_delta_volume": self.max_delta_volume,
             "max_voltage_step": self.max_voltage_step,
             "capacity_grav": self.get_capacity_grav(),
             "capacity_vol": self.get_capacity_vol(),
             "energy_grav": self.get_specific_energy(),
             "energy_vol": self.get_energy_density(),
             "working_ion": self._working_ion.symbol,
             "nsteps": self.num_steps,
             "framework": self._vpairs[0].framework.to_data_dict,
             "formula_charge": chg_comp.reduced_formula,
             "id_charge": self.fully_charged_entry.entry_id,
             "formula_discharge": dischg_comp.reduced_formula,
             "id_discharge": self.fully_discharged_entry.entry_id,
             "fracA_charge": chg_comp.get_atomic_fraction(ion),
             "fracA_discharge": dischg_comp.get_atomic_fraction(ion),
             "max_instability": self.get_max_instability(),
             "min_instability": self.get_min_instability(),
             "material_ids" : [itr_ent.entry_id for itr_ent in self._entries],
             "stable_material_ids" : [itr_ent.entry_id for itr_ent in self.get_stable_entries()],
             "unstable_material_ids": [itr_ent.entry_id for itr_ent in self.get_unstable_entries()],
             }

        if all(['decomposition_energy' in itr_ent.data for itr_ent in self._entries]):
            d.update({"stability_charge": self.fully_charged_entry.data['decomposition_energy'],
                 "stability_discharge": self.fully_discharged_entry.data['decomposition_energy'],
                 "stability_data":{itr_ent.entry_id: itr_ent.data['decomposition_energy'] for itr_ent in self._entries},
                 })

        if all(['muO2' in itr_ent.data for itr_ent in self._entries]):
            d.update({"muO2_data" : {itr_ent.entry_id: itr_ent.data['muO2'] for itr_ent in self._entries}})

        if print_subelectrodes:
            f_dict = lambda c: c.as_dict_summary(print_subelectrodes=False)
            d["adj_pairs"] = list(map(f_dict,
                                 self.get_sub_electrodes(adjacent_only=True)))
            d["all_pairs"] = list(map(f_dict,
                                 self.get_sub_electrodes(adjacent_only=False)))
        return d

Generate a summary dict.

Args:
print_subelectrodes: Also print data on all the possible
subelectrodes.

Returns:
A summary of this electrode"s properties in dict format.


def remove_results(vcs, signature):
    results_directory = _get_results_directory(vcs, signature)
    if (not os.path.exists(results_directory)):
        raise ResultsNotFoundError
    shutil.rmtree(results_directory)

Removed saved results for this signature

Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError


def get_creator_by_name(name):
    return {'docker(container)': Container.creator, 'shell': Bash.creator, 'docker(image)': Image.creator, 'python': Script.creator, 'packer': Packer.creator, 'ansible(simple)': Ansible.creator}[name]

Get creator function by name.

Args:
name (str): name of the creator function.

Returns:
function: creater function.


def get_links(self, **kw):
    links = [a for a in dir(self) if (isinstance(getattr(self, a), Model) and (not a.startswith('_model')))]
    return [{'field': l, 'mdl': getattr(self, l).__class__} for l in links]

Prepare links of form by mimicing pyoko's get_links method's result

Args:
**kw:

Returns: list of link dicts


def is_os(name, version_id=None):

    result = False
    os_release_infos = _fetch_os_release_infos()

    if name == os_release_infos.get('name', None):

        if version_id is None:
            result = True
        elif version_id == os_release_infos.get('version_id', None):
            result = True

    return result

Return True if OS name in /etc/lsb-release of host given by fabric param
`-H` is the same as given by argument, False else.

If arg version_id is not None only return True if it is the same as in
/etc/lsb-release, too.

Args:
name: 'Debian GNU/Linux', 'Ubuntu'
version_id(None or str): None,
'14.04', (Ubuntu)
'16.04', (Ubuntu)
'8', (Debian)


def __stripValue(self, value):

        if isinstance(value, str):
            if ( value[0] == '"' and value[-1] == '"' ) or ( value[0] == '[' and value[-1] == ']' ):
                return value[1:-1]
        return value

strip the special characters in the value

Args:
value: value string

Returns:
value string without special characters


def create_iam_resources(env='dev', app='', **_):
    session = boto3.session.Session(profile_name=env)
    client = session.client('iam')
    app_properties = get_properties(env='pipeline')
    generated = get_details(env=env, app=app)
    generated_iam = generated.iam()
    app_details = collections.namedtuple('AppDetails', generated_iam.keys())
    details = app_details(**generated_iam)
    LOG.debug('Application details: %s', details)
    deployment_type = app_properties['type']
    role_trust_template = get_template('infrastructure/iam/trust/{0}_role.json.j2'.format(deployment_type), formats=generated)
    resource_action(client, action='create_role', log_format='Created Role: %(RoleName)s', RoleName=details.role, AssumeRolePolicyDocument=role_trust_template)
    resource_action(client, action='create_instance_profile', log_format='Created Instance Profile: %(InstanceProfileName)s', InstanceProfileName=details.profile)
    attach_profile_to_role(client, role_name=details.role, profile_name=details.profile)
    iam_policy = construct_policy(app=app, group=details.group, env=env, pipeline_settings=app_properties)
    if iam_policy:
        resource_action(client, action='put_role_policy', log_format='Added IAM Policy: %(PolicyName)s', RoleName=details.role, PolicyName=details.policy, PolicyDocument=iam_policy)
    resource_action(client, action='create_user', log_format='Created User: %(UserName)s', UserName=details.user)
    resource_action(client, action='create_group', log_format='Created Group: %(GroupName)s', GroupName=details.group)
    resource_action(client, action='add_user_to_group', log_format='Added User to Group: %(UserName)s -> %(GroupName)s', GroupName=details.group, UserName=details.user)
    return True

Create the IAM Resources for the application.

Args:
env (str): Deployment environment/account, i.e. dev, stage, prod.
app (str): Spinnaker Application name.

Returns:
True upon successful completion.


def drop(self, items):

        self._manager.leaser.remove(items)
        self._manager.maybe_resume_consumer()

Remove the given messages from lease management.

Args:
items(Sequence[DropRequest]): The items to drop.


def get_default_description(arg: inspect.Parameter) -> str:
    if arg.annotation is inspect._empty:
        arg_type = '<fill_type>'
    elif hasattr(arg.annotation, '__name__'):
        arg_type = arg.annotation.__name__
    else:
        arg_type = str(arg.annotation)
    if arg.default is inspect._empty:
        return f'`{arg_type}`'
    elif arg.default is None:
        return f'`{arg_type}`, {OPTIONAL_KEYWORD}'
    else:
        str_default = stringify_default(arg.default)
        return f'`{arg_type}`, {OPTIONAL_KEYWORD}, defaults to {str_default}'

Builds a default description for a parameter that was not documented.

Args:
arg (`inspect.Parameter`): The argument in the signature to generate a description for.

Returns:
`str`: The description.


def _verify_ops(graph_def: graph_pb2.GraphDef, namespace_whitelist):
    if namespace_whitelist is None:
        return
    invalid_ops = []
    invalid_namespaces = set()
    all_operations = []
    all_operations.extend(meta_graph.ops_used_by_graph_def(graph_def))
    for op in all_operations:
        if '>' in op:
            namespace = op.split('>')[0]
            if namespace not in namespace_whitelist:
                invalid_ops.append(op)
                invalid_namespaces.add(namespace)
    if invalid_ops:
        raise ValueError(f"Attempted to save ops from non-whitelisted namespaces to SavedModel: {invalid_ops}.\nPlease verify that these ops should be saved, since they must be available when loading the SavedModel. If loading from Python, you must import the library defining these ops. From C++, link the custom ops to the serving binary. Once you've confirmed this, add the following namespaces to the `namespace_whitelist` argument in tf.saved_model.SaveOptions: {invalid_namespaces}.")

Verifies that all namespaced ops in the graph are whitelisted.

Args:
graph_def: the GraphDef to validate.
namespace_whitelist: a list of namespaces to allow. If `None`, all will be
allowed. If an op does not have a namespace, it will be allowed.

Raises:
ValueError: If the graph contains ops that violate the whitelist.


def get(self, uid: int) -> Optional[CachedMessage]:

        return self._cache.get(uid)

Return the given cached message.

Args:
uid: The message UID.


def parseConfig(cls, value):

		if 'enabled' in value:
			value['enabled'] = bool(value['enabled'])

		if 'exclude_paths' in value:
			value['exclude_paths'] = [n.strip() for n in ast.literal_eval(value['exclude_paths'])]

		return value

Parse the config values

Args:
value (dict): Dictionary which contains the checker config

Returns:
dict: The checker config with parsed values


def leave(self):
    try:
        self.client.api.leave_room(self.room_id)
        del self.client.rooms[self.room_id]
        return True
    except MatrixRequestError:
        return False

Leave the room.

Returns:
boolean: Leaving the room was successful.


def _getFieldStats(self):
    fieldStats = dict()
    fieldNames = self._inputSource.getFieldNames()
    for field in fieldNames:
        curStats = dict()
        curStats['min'] = self._inputSource.getFieldMin(field)
        curStats['max'] = self._inputSource.getFieldMax(field)
        fieldStats[field] = curStats
    return fieldStats

Method which returns a dictionary of field statistics received from the
input source.

Returns:

fieldStats: dict of dicts where the first level is the field name and
the second level is the statistic. ie. fieldStats['pounds']['min']


def get_np_doc_form():
    return _np_doc_form

Gets the form of the original numpy docstrings.

Returns:
See `set_np_doc_form` for the list of valid values.


def list_apps(site):

    ret = dict()
    ps_cmd = list()
    ps_cmd.append("Get-WebApplication -Site '{0}'".format(site))
    ps_cmd.append(r"| Select-Object applicationPool, path, PhysicalPath, preloadEnabled,")
    ps_cmd.append(r"@{ Name='name'; Expression={ $_.path.Split('/', 2)[-1] } },")
    ps_cmd.append(r"@{ Name='protocols'; Expression={ @( $_.enabledProtocols.Split(',')")
    ps_cmd.append(r"| Foreach-Object { $_.Trim() } ) } }")

    cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)

    try:
        items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
    except ValueError:
        raise CommandExecutionError('Unable to parse return data as Json.')

    for item in items:
        protocols = list()

        if isinstance(item['protocols'], dict):
            if 'value' in item['protocols']:
                protocols += item['protocols']['value']
        else:
            protocols.append(item['protocols'])

        ret[item['name']] = {'apppool': item['applicationPool'],
                             'path': item['path'],
                             'preload': item['preloadEnabled'],
                             'protocols': protocols,
                             'sourcepath': item['PhysicalPath']}

    if not ret:
        log.warning('No apps found in output: %s', cmd_ret)

    return ret

Get all configured IIS applications for the specified site.

Args:
site (str): The IIS site name.

Returns: A dictionary of the application names and properties.

CLI Example:

.. code-block:: bash

salt '*' win_iis.list_apps site


def get_total_mass(self):

        try:
            mass = self.loc[:, 'mass'].sum()
        except KeyError:
            mass_molecule = self.add_data('mass')
            mass = mass_molecule.loc[:, 'mass'].sum()
        return mass

Returns the total mass in g/mol.

Args:
None

Returns:
float:


def parse(self, utterance, context=None, N=1):
    start = time.time()
    context_trie = None
    if (context and isinstance(context, list)):
        context.sort(key=(lambda x: x.get('confidence')))
        context_trie = Trie()
        for entity in context:
            (entity_value, entity_type) = entity.get('data')[0]
            context_trie.insert(entity_value.lower(), data=(entity_value, entity_type), weight=entity.get('confidence'))
    tagged = self._tagger.tag(utterance.lower(), context_trie=context_trie)
    self.emit('tagged_entities', {'utterance': utterance, 'tags': list(tagged), 'time': (time.time() - start)})
    start = time.time()
    bke = BronKerboschExpander(self._tokenizer)

    def score_clique(clique):
        score = 0.0
        for tagged_entity in clique:
            ec = tagged_entity.get('entities', [{'confidence': 0.0}])[0].get('confidence')
            score += ((ec * len(tagged_entity.get('entities', [{'match': ''}])[0].get('match'))) / (len(utterance) + 1))
        return score
    parse_results = bke.expand(tagged, clique_scoring_func=score_clique)
    count = 0
    for result in parse_results:
        count += 1
        parse_confidence = 0.0
        for tag in result:
            sample_entity = tag['entities'][0]
            entity_confidence = ((sample_entity.get('confidence', 0.0) * float(len(sample_entity.get('match')))) / len(utterance))
            parse_confidence += entity_confidence
        (yield {'utterance': utterance, 'tags': result, 'time': (time.time() - start), 'confidence': parse_confidence})
        if (count >= N):
            break

Used to find tags within utterance with a given confidence

Args:
utterance(str): conversational piece given by the user
context(list): a list of entities
N(int): number of results
Returns: yield an object with the following fields
utterance(str): the value passed in
tags(list) : a list of tags found in utterance
time(time) : duration since call of function
confidence(float) : float indicating how confident of a match to the
utterance. This might be used to determan the most likely intent.


def set_query(self, value):

        if isinstance(value, basestring) or value is None:
            self._content['query'] = value
        elif hasattr(value, 'keys'):
            self._content['query'] = query.terms_from_dict(value)
        else:
            raise TypeError("Query must be a string or dict. Got: " + type(value) + " insted!")

Convert a dict form of query in a string of needed and store the query string.

Args:
value -- A query string or a dict with query xpaths as keys and text or
nested query dicts as values.


def locked_get(self):
    filters = {self.key_name: self.key_value}
    query = self.session.query(self.model_class).filter_by(**filters)
    entity = query.first()
    if entity:
        credential = getattr(entity, self.property_name)
        if (credential and hasattr(credential, 'set_store')):
            credential.set_store(self)
        return credential
    else:
        return None

Retrieve stored credential.

Returns:
A :class:`oauth2client.Credentials` instance or `None`.


def CheckFlowCanBeStartedOnClient(flow_name):

  flow_cls = flow.GRRFlow.GetPlugin(flow_name)

  if flow_cls.category:
    return True
  else:
    raise access_control.UnauthorizedAccess(
        "Flow %s can't be started on a client by non-suid users." % flow_name)

Checks if flow can be started on a particular client.

Only flows with a category can bestarted. Having a category means that the
flow will be accessible from the UI.

Args:
flow_name: Name of the flow to check access for.

Returns:
True if flow is externally accessible.
Raises:
access_control.UnauthorizedAccess: if flow is not externally accessible.


def RegisterPlugin(cls, plugin_class):

    name = getattr(
        plugin_class, 'ARTIFACT_DEFINITION_NAME', plugin_class.__name__)
    name = name.lower()
    if name in cls._plugins:
      raise KeyError(
          'Artifact plugin class already set for name: {0:s}.'.format(name))

    preprocess_plugin = plugin_class()

    cls._plugins[name] = preprocess_plugin

    if isinstance(
        preprocess_plugin, interface.FileSystemArtifactPreprocessorPlugin):
      cls._file_system_plugins[name] = preprocess_plugin

    elif isinstance(
        preprocess_plugin, interface.KnowledgeBasePreprocessorPlugin):
      cls._knowledge_base_plugins[name] = preprocess_plugin

    elif isinstance(
        preprocess_plugin,
        interface.WindowsRegistryKeyArtifactPreprocessorPlugin):
      cls._windows_registry_plugins[name] = preprocess_plugin

Registers an preprocess plugin class.

Args:
plugin_class (type): preprocess plugin class.

Raises:
KeyError: if plugin class is already set for the corresponding name.
TypeError: if the source type of the plugin class is not supported.


def angle(self, deg=False):
    if (self.dtype.str[1] != 'c'):
        warnings.warn('angle() is intended for complex-valued timeseries', RuntimeWarning, 1)
    da = distob.vectorize(np.angle)(self, deg)
    return _dts_from_da(da, self.tspan, self.labels)

Return the angle of a complex Timeseries

Args:
deg (bool, optional):
Return angle in degrees if True, radians if False (default).

Returns:
angle (Timeseries):
The counterclockwise angle from the positive real axis on
the complex plane, with dtype as numpy.float64.


def print_periodic_table(filter_function: callable = None):

        for row in range(1, 10):
            rowstr = []
            for group in range(1, 19):
                try:
                    el = Element.from_row_and_group(row, group)
                except ValueError:
                    el = None
                if el and ((not filter_function) or filter_function(el)):
                    rowstr.append("{:3s}".format(el.symbol))
                else:
                    rowstr.append("   ")
            print(" ".join(rowstr))

A pretty ASCII printer for the periodic table, based on some
filter_function.

Args:
filter_function: A filtering function taking an Element as input
and returning a boolean. For example, setting
filter_function = lambda el: el.X > 2 will print a periodic
table containing only elements with electronegativity > 2.


def List(self, request, global_params=None):
    config = self.GetMethodConfig('List')
    return self._RunMethod(config, request, global_params=global_params)

Lists snapshots.

Args:
request: (DataflowProjectsLocationsJobsSnapshotsListRequest) input message
global_params: (StandardQueryParameters, default: None) global arguments
Returns:
(ListSnapshotsResponse) The response message.


def __init__(self, data_parallelism, expert_parallelism, gates):

    self._gates = gates
    self._dp = data_parallelism
    self._ep = expert_parallelism
    assert len(gates) == self._dp.n
    self._dispatchers = self._dp(SparseDispatcher, self._ep.n, gates)

Create a DistributedSparseDispatcher.

Args:
data_parallelism: a Parallelism object.
expert_parallelism: a Parallelism object.
gates: a list of datashard_parallelism.n `Tensor`s of shapes
`[batch_size[d], num_experts]`.

Returns:
a DistributedSparseDispatcher


def find_nearest(a, value, index=False):

    i = np.abs(a - value).argmin()
    if index:
        return i
    else:
        return a[i]

Find the array value, or index of the array value, closest to some given
value.

Args:
a (ndarray)
value (float)
index (bool): whether to return the index instead of the array value.

Returns:
float. The array value (or index, as int) nearest the specified value.


def vocab_token_counts(text_filepattern, max_lines):
    ret = {}
    for (i, line) in enumerate(_read_filepattern(text_filepattern, max_lines=max_lines)):
        if (',' not in line):
            tf.logging.warning("Malformed vocab line
            continue
        (token, count) = line.rsplit(',', 1)
        ret[_native_to_unicode(token)] = int(count)
    return ret

Read a vocab file and return a dictionary of token counts.

Reads a two-column CSV file of tokens and their frequency in a dataset. The
tokens are presumed to be generated by encode() or the equivalent.

Args:
text_filepattern: A pattern matching one or more files.
max_lines: An integer; maximum total lines to read.

Returns:
a dictionary mapping token to count.


def _save_private_file(filename, json_contents):
    temp_filename = tempfile.mktemp()
    file_desc = os.open(temp_filename, (os.O_WRONLY | os.O_CREAT), 384)
    with os.fdopen(file_desc, 'w') as file_handle:
        json.dump(json_contents, file_handle, sort_keys=True, indent=2, separators=(',', ': '))
    shutil.move(temp_filename, filename)

Saves a file with read-write permissions on for the owner.

Args:
filename: String. Absolute path to file.
json_contents: JSON serializable object to be saved.


def summarize_tensors(tensor_dict, tag=None):

  if tag is None:
    tag = "tensors/"

  for t_name in list(tensor_dict):
    t = tensor_dict[t_name]
    tf.summary.histogram(tag + t_name, t)

Summarize the tensors.

Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.


def create_downloader_of_type(type_name):
    downloaders = available_downloaders()
    if (type_name not in downloaders.keys()):
        raise UnknownDownloaderException(('Unknown downloader: %s' % (type_name,)))
    return downloaders[type_name]()

Create an instance of the downloader with the given name.

Args:
type_name: The name of a downloader.

Returns:
An instance of the downloader with the given type.


def fetch_tuples(self, max_tuples=20, timeout=None):
    tuples = list()
    if (timeout is None):
        while (len(tuples) < max_tuples):
            fetcher = self._data_fetcher
            if (not fetcher):
                break
            tuples.append(fetcher.items.get())
        return tuples
    timeout = float(timeout)
    end = (time.time() + timeout)
    while (len(tuples) < max_tuples):
        qto = (end - time.time())
        if (qto <= 0):
            break
        try:
            fetcher = self._data_fetcher
            if (not fetcher):
                break
            tuples.append(fetcher.items.get(timeout=qto))
        except queue.Empty:
            break
    return tuples

Fetch a number of tuples from this view.

Fetching of data must have been started with
:py:meth:`start_data_fetch` before calling this method.

If ``timeout`` is ``None`` then the returned list will
contain ``max_tuples`` tuples. Otherwise if the timeout is reached
the list may contain less than ``max_tuples`` tuples.

Args:
max_tuples(int): Maximum number of tuples to fetch.
timeout(float): Maximum time to wait for ``max_tuples`` tuples.

Returns:
list: List of fetched tuples.
.. versionadded:: 1.12


def CheckForBadCharacters(filename, lines, error):
    for (linenum, line) in enumerate(lines):
        if (unicode_escape_decode('�') in line):
            error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).')
        if ('\x00' in line):
            error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')

Logs an error for each line containing bad characters.

Two kinds of bad characters:

1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't).  Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.

2. NUL bytes.  These are problematic for some tools.

Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.


def prose_wc(args):
    if (args.file is None):
        return 1
    if args.split_hyphens:
        INTERSTITIAL_PUNCTUATION.append(re.compile('-'))
    content = args.file.read().decode('utf-8')
    filename = args.file.name
    body = strip_frontmatter(content)
    parsed = markdown_to_text(body)
    result = wc(filename, body, parsed=parsed, is_jekyll=(body != content))
    if (args.update and (filename != '_stdin_') and (result['counts']['type'] == 'jekyll')):
        update_file(filename, result, content, args.indent)
    else:
        _mockable_print({'yaml': yaml.safe_dump(result, default_flow_style=False, indent=args.indent), 'json': json.dumps(result, indent=args.indent), 'default': default_dump(result)}[args.format])
    return 0

Processes data provided to print a count object, or update a file.

Args:
args: an ArgumentParser object returned by setup()


def _check_middleware_dependencies(concerned_object, required_middleware):
    declared_middleware = getattr(settings, 'MIDDLEWARE', None)
    if (declared_middleware is None):
        declared_middleware = settings.MIDDLEWARE_CLASSES
    matching_middleware = [mw for mw in declared_middleware if (mw in required_middleware)]
    if (required_middleware != matching_middleware):
        raise AssertionError('{} requires middleware order {} but matching middleware was {}'.format(concerned_object, required_middleware, matching_middleware))

Check required middleware dependencies exist and in the correct order.

Args:
concerned_object (object): The object for which the required
middleware is being checked. This is used for error messages only.
required_middleware (list of String): An ordered list representing the
required middleware to be checked.

Usage:
Add in __init__ method to a Middleware class to have its dependencies
checked on startup.

def __init__(self):
super(SomeMiddleware, self).__init__()
_check_middleware_dependencies(self, required_middleware=[
'edx_django_utils.cache.middleware.RequestCacheMiddleware',
])

Raises:
AssertionError if the provided dependencies don't appear in
MIDDLEWARE_CLASSES in the correct order.


def cardinal(self, to):

        return sum(1 for _ in filter(
            lambda d: not d.external and d.target in to, self.dependencies))

Return the number of dependencies of this module to the given node.

Args:
to (Package/Module): the target node.

Returns:
int: number of dependencies.


def vert_tab_pos(self, positions):

        if positions == 'clear':
            self.send(chr(27)+'B'+chr(0))
            return
        if positions.min < 1 or positions.max >255:
                raise RuntimeError('Invalid position parameter in function horzTabPos')
        sendstr = chr(27) + 'D'
        if len(positions)<=16:
            for position in positions:
                sendstr += chr(position)
            self.send(sendstr + chr(0))
        else:
            raise RuntimeError('Too many positions in function vertTabPos')

Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions.

Args:
positions -- Either a list of tab positions (between 1 and 255), or 'clear'.
Returns:
None
Raises:
RuntimeError: Invalid position parameter.
RuntimeError: Too many positions.


def update_or_create_all(cls, list_of_kwargs, keys=[]):
    objs = []
    for kwargs in list_of_kwargs:
        filter_kwargs = subdict(kwargs, keys)
        if (filter_kwargs == {}):
            obj = None
        else:
            obj = cls.first(**filter_kwargs)
        if (obj is not None):
            for (key, value) in kwargs.iteritems():
                if ((key not in keys) and (key not in cls._no_overwrite_)):
                    setattr(obj, key, value)
        else:
            obj = cls.new(**kwargs)
        objs.append(obj)
    try:
        return cls.add_all(objs)
    except:
        cls.session.rollback()
        raise

Batch method for updating a list of instances and
creating them if required

Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately

keys (list, optional): A list of keys to use for the
initial finding step. Matching is done only on these
attributes.

Examples:

>>> Customer.update_or_create_all([
... {'name': 'Vicky', 'email': 'vicky@x.com', 'age': 34},
... {'name': 'Ron', 'age': 40, 'email': 'ron@x.com',
... 'gender': 'Male'}], keys=['name', 'email'])


def _find_variables(graph_def: graph_pb2.GraphDef) -> Mapping[str, node_def_pb2.NodeDef]:
    variable_nodes = {}
    for var_node in filter(_is_variable, graph_def.node):
        shared_name = str(var_node.attr['shared_name'].s, encoding='utf-8')
        variable_nodes[shared_name] = var_node
    for func in graph_def.library.function:
        for var_node in filter(_is_variable, func.node_def):
            variable_nodes[shared_name] = var_node
    return variable_nodes

Finds all variables within `graph_def`.

This function makes sense for TF 1 graphs only, as it depends on
`shared_name`.

Args:
graph_def: `GraphDef` to find variables from.

Returns:
A mapping of `shared_name` -> `NodeDef` corresponding to a variable op.


def _head(self, client_kwargs):

        with _handle_azure_exception():

            if 'file_name' in client_kwargs:
                result = self.client.get_file_properties(**client_kwargs)

            elif 'directory_name' in client_kwargs:
                result = self.client.get_directory_properties(**client_kwargs)

            else:
                result = self.client.get_share_properties(**client_kwargs)

        return self._model_to_dict(result)

Returns object or bucket HTTP header.

Args:
client_kwargs (dict): Client arguments.

Returns:
dict: HTTP header.


def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):

        local_stream = BytearrayStream()

        if self._device_serial_number is not None:
            self._device_serial_number.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._password is not None:
            self._password.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._device_identifier is not None:
            self._device_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._network_identifier is not None:
            self._network_identifier.write(
                local_stream,
                kmip_version=kmip_version)
        if self._machine_identifier is not None:
            self._machine_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._media_identifier is not None:
            self._media_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )

        self.length = local_stream.length()
        super(DeviceCredential, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)

Write the data encoding the DeviceCredential struct to a stream.

Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 1.0.


def _construct(configdict, prefix, ua):
    if (not ua):
        raise UserAgentError("User_agent parameter missing. It can be your project's name for example.")
    preprefix = configdict.get('preprefix')
    if preprefix:
        user_agent = ('%s:' % preprefix)
    else:
        user_agent = ''
    if prefix:
        user_agent = ('%s%s-' % (user_agent, prefix))
    user_agent = ('%s%s' % (user_agent, ua))
    return user_agent

Construct user agent

Args:
configdict (str): Additional configuration for user agent
prefix (str): Text to put at start of user agent
ua (str): Custom user agent text

Returns:
str: Full user agent string


def round(cls, x: 'TensorFluent') -> 'TensorFluent':

        return cls._unary_op(x, tf.round, tf.float32)

Returns a TensorFluent for the round function.

Args:
x: The input fluent.

Returns:
A TensorFluent wrapping the round function.


def __init__(self,
               api,
               path,
               buffer_size=DEFAULT_BUFFER_SIZE,
               max_request_size=MAX_REQUEST_SIZE,
               offset=0):

    self._api = api
    self._path = path
    self.name = api_utils._unquote_filename(path)
    self.closed = False

    assert buffer_size <= max_request_size
    self._buffer_size = buffer_size
    self._max_request_size = max_request_size
    self._offset = offset

    self._buffer = _Buffer()
    self._etag = None

    get_future = self._get_segment(offset, self._buffer_size, check_response=False)

    status, headers, content = self._api.head_object(path)
    errors.check_status(status, [200], path, resp_headers=headers, body=content)
    self._file_size = long(common.get_stored_content_length(headers))
    self._check_etag(headers.get('etag'))

    self._buffer_future = None

    if self._file_size != 0:
      content, check_response_closure = get_future.get_result()
      check_response_closure()
      self._buffer.reset(content)
      self._request_next_buffer()

Constructor.

Args:
api: A StorageApi instance.
path: Quoted/escaped path to the object, e.g. /mybucket/myfile
buffer_size: buffer size. The ReadBuffer keeps
one buffer. But there may be a pending future that contains
a second buffer. This size must be less than max_request_size.
max_request_size: Max bytes to request in one urlfetch.
offset: Number of bytes to skip at the start of the file. If None, 0 is
used.


def dict_setdiff(dict_, negative_keys):
    keys = [key for key in six.iterkeys(dict_) if (key not in set(negative_keys))]
    subdict_ = dict_subset(dict_, keys)
    return subdict_

r"""
returns a copy of dict_ without keys in the negative_keys list

Args:
dict_ (dict):
negative_keys (list):


def _assert_same_base_type(items, expected_type=None):
  r
  original_expected_type = expected_type
  mismatch = False
  for item in items:
    if item is not None:
      item_type = base_dtype(item.dtype)
      if not expected_type:
        expected_type = item_type
      elif expected_type != item_type:
        mismatch = True
        break
  if mismatch:

    expected_type = original_expected_type
    original_item_str = None
    get_name = lambda x: x.name if hasattr(x, 'name') else str(x)
    for item in items:
      if item is not None:
        item_type = base_dtype(item.dtype)
        if not expected_type:
          expected_type = item_type
          original_item_str = get_name(item)
        elif expected_type != item_type:
          raise ValueError(
              '{}, type={}, must be of the same type ({}){}.'.format(
                  get_name(item),
                  item_type,
                  expected_type,
                  ((' as {}'.format(original_item_str))
                   if original_item_str else '')))
    return expected_type
  else:
    return expected_type

r"""Asserts all items are of the same base type.

Args:
items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`,
`Operation`, or `IndexedSlices`). Can include `None` elements, which
will be ignored.
expected_type: Expected type. If not specified, assert all items are
of the same base type.

Returns:
Validated type, or none if neither expected_type nor items provided.

Raises:
ValueError: If any types do not match.


def _perform_action(self, params, return_dict=True):

        action = self.get_data(
            "droplets/%s/actions/" % self.id,
            type=POST,
            params=params
        )
        if return_dict:
            return action
        else:
            action = action[u'action']
            return_action = Action(token=self.token)

            for attr in action.keys():
                setattr(return_action, attr, action[attr])
            return return_action

Perform a droplet action.

Args:
params (dict): parameters of the action

Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.

Returns dict or Action


def remove_pos_arg_placeholders(alias_command):

    split_command = shlex.split(alias_command)
    boundary_index = len(split_command)
    for i, subcommand in enumerate(split_command):
        if not re.match('^[a-z]', subcommand.lower()) or i > COLLISION_CHECK_LEVEL_DEPTH:
            boundary_index = i
            break

    return ' '.join(split_command[:boundary_index]).lower()

Remove positional argument placeholders from alias_command.

Args:
alias_command: The alias command to remove from.

Returns:
The alias command string without positional argument placeholder.


def ChiSquared(target_frequency):

    def inner(text):
        text = ''.join(text)
        return (- chi_squared(frequency_analyze(text), target_frequency))
    return inner

Score a text by comparing its frequency distribution against another.

Note:
It is easy to be penalised without knowing it when using this scorer.
English frequency ngrams are capital letters, meaning when using it
any text you score against must be all capitals for it to give correct results.
I am aware of the issue and will work on a fix.

Todo:
Maybe include paramter for ngram size. Havent had a use case for this yet.
Once there is evidence it is needed, I will add it.

Example:
>>> fitness = ChiSquared(english.unigrams)
>>> fitness("ABC")
-32.2

Args:
target_frequency (dict): symbol to frequency mapping of the distribution to compare with


def __init__(self, analyzer_class):

    super(HashTaggingAnalysisPlugin, self).__init__()
    self._analysis_queue_timeout = self.DEFAULT_QUEUE_TIMEOUT
    self._analyzer_started = False
    self._comment = 'Tag applied by {0:s} analysis plugin'.format(self.NAME)
    self._event_identifiers_by_pathspec = collections.defaultdict(list)
    self._hash_pathspecs = collections.defaultdict(list)
    self._requester_class = None
    self._time_of_last_status_log = time.time()
    self.hash_analysis_queue = Queue.Queue()
    self.hash_queue = Queue.Queue()

    self._analyzer = analyzer_class(self.hash_queue, self.hash_analysis_queue)

Initializes a hash tagging analysis plugin.

Args:
analyzer_class (type): a subclass of HashAnalyzer that will be
instantiated by the plugin.


def match(self, path):

        this = self.segments
        that = path.split('/')
        current_var = None
        bindings = {}
        segment_count = self.segment_count
        j = 0
        for i in range(0, len(this)):
            if j >= len(that):
                break
            if this[i].kind == _TERMINAL:
                if this[i].literal == '*':
                    bindings[current_var] = that[j]
                    j += 1
                elif this[i].literal == '**':
                    until = j + len(that) - segment_count + 1
                    segment_count += len(that) - segment_count
                    bindings[current_var] = '/'.join(that[j:until])
                    j = until
                elif this[i].literal != that[j]:
                    raise ValidationException(
                        'mismatched literal: \'%s\' != \'%s\'' % (
                            this[i].literal, that[j]))
                else:
                    j += 1
            elif this[i].kind == _BINDING:
                current_var = this[i].literal
        if j != len(that) or j != segment_count:
            raise ValidationException(
                'match error: could not render from the path template: {}'
                .format(path))
        return bindings

Matches a fully qualified path template string.

Args:
path (str): A fully qualified path template string.

Returns:
dict: Var names to matched binding values.

Raises:
ValidationException: If path can't be matched to the template.


def from_cif_file(cif_file, source='', comment=''):

        r = CifParser(cif_file)
        structure = r.get_structures()[0]
        return Header(structure, source, comment)

Static method to create Header object from cif_file

Args:
cif_file: cif_file path and name
source: User supplied identifier, i.e. for Materials Project this
would be the material ID number
comment: User comment that goes in header

Returns:
Header Object


def argmin(x, axis=None, keepdims=False):
    if any_symbolic_tensors((x,)):
        return Argmin(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.argmin(x, axis=axis, keepdims=keepdims)

Returns the indices of the minimum values along an axis.

Args:
x: Input tensor.
axis: By default, the index is into the flattened tensor, otherwise
along the specified axis.
keepdims: If this is set to `True`, the axes which are reduced are left
in the result as dimensions with size one. Defaults to `False`.

Returns:
Tensor of indices. It has the same shape as `x`, with the dimension
along `axis` removed.

Example:
>>> x = keras.ops.arange(6).reshape(2, 3) + 10
>>> x
array([[10, 11, 12],
[13, 14, 15]], dtype=int32)
>>> keras.ops.argmin(x)
array(0, dtype=int32)
>>> keras.ops.argmin(x, axis=0)
array([0, 0, 0], dtype=int32)
>>> keras.ops.argmin(x, axis=1)
array([0, 0], dtype=int32)


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

Get the user agent detail.

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

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


def inverse_removing(self, words_to_remove):

        mask = np.ones(self.as_np.shape[0], dtype='bool')
        mask[self.__get_idxs(words_to_remove)] = False
        if not self.bow:
            return ''.join([self.as_list[i] if mask[i]
                            else 'UNKWORDZ' for i in range(mask.shape[0])])
        return ''.join([self.as_list[v] for v in mask.nonzero()[0]])

Returns a string after removing the appropriate words.

If self.bow is false, replaces word with UNKWORDZ instead of removing
it.

Args:
words_to_remove: list of ids (ints) to remove

Returns:
original raw string with appropriate words removed.


def mod_replace(match, sphinx_modules):

    sphinx_modules.append(match.group("module"))
    return "`{}`_".format(match.group("value"))

Convert Sphinx ``:mod:`` to plain reST link.

Args:
match (_sre.SRE_Match): A match (from ``re``) to be used
in substitution.
sphinx_modules (list): List to be track the modules that have been
encountered.

Returns:
str: The ``match`` converted to a link.


def clean_title(title):
    date_pattern = re.compile('\\W*\\d{1,2}[/\\-.]\\d{1,2}[/\\-.](?=\\d*)(?:.{4}|.{2})\\W*')
    title = date_pattern.sub(' ', title)
    title = re.sub('\\s{2,}', ' ', title)
    title = title.strip()
    return title

Clean title -> remove dates, remove duplicated spaces and strip title.

Args:
title (str): Title.

Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.


def __call__(self, input_tensor: core.Tensor) -> Mapping[str, core.Tensor]:
    out = math_ops.matmul(input_tensor, self.filters)
    return {'output': out}

Performs a matrix multiplication.

Args:
input_tensor: Input tensor to matmul with the filter.

Returns:
A map of: output key -> output result.


def header(self, key, value):

        if type(key) is tuple:
            key, value = str(key[0]), key[1]

        headers = {key: value}
        self._headers.extend(headers)

Defines a new response header.
Alias to ``Response.header()``.

Arguments:
header (str): header name.
value (str): header value.

Returns:
self: ``pook.Response`` current instance.


def localopt(self, forcefield='mmff94', steps=500):

        pbmol = pb.Molecule(self._obmol)
        pbmol.localopt(forcefield=forcefield, steps=steps)
        self._obmol = pbmol.OBMol

A wrapper to pybel's localopt method to optimize a Molecule.

Args:
forcefield: Default is mmff94. Options are 'gaff', 'ghemical',
'mmff94', 'mmff94s', and 'uff'.
steps: Default is 500.


def _detect(self):
    results = []
    self.results = []
    self.visited_all_paths = {}
    for contract in self.slither.contracts:
        for function in contract.functions:
            if (function.is_implemented and (function.contract == contract)):
                if function.contains_assembly:
                    continue
                uninitialized_local_variables = [v for v in function.local_variables if ((not v.is_storage) and v.uninitialized)]
                function.entry_point.context[self.key] = uninitialized_local_variables
                self._detect_uninitialized(function, function.entry_point, [])
    all_results = list(set(self.results))
    for (function, uninitialized_local_variable) in all_results:
        var_name = uninitialized_local_variable.name
        info = '{} in {}.{} ({}) is a local variable never initialiazed\n'
        info = info.format(var_name, function.contract.name, function.name, uninitialized_local_variable.source_mapping_str)
        json = self.generate_json_result(info)
        self.add_variable_to_json(uninitialized_local_variable, json)
        self.add_function_to_json(function, json)
        results.append(json)
    return results

Detect uninitialized local variables

Recursively visit the calls
Returns:
dict: [contract name] = set(local variable uninitialized)


def test_correctness_2_factor_hull_white_consistency(self, valuation_method, error_tol):
    dtype = tf.float64
    expiries = np.array([1.0])
    fixed_leg_payment_times = np.array([1.25, 1.5, 1.75, 2.0])
    fixed_leg_daycount_fractions = 0.25 * np.ones_like(fixed_leg_payment_times)
    fixed_leg_coupon = 0.011 * np.ones_like(fixed_leg_payment_times)
    zero_rate_fn = lambda x: 0.01 * tf.ones_like(x, dtype=dtype)
    mu = 0.03
    vol1 = 0.02
    vol2 = 0.01
    eff_vol = np.sqrt(vol1 ** 2 + vol2 ** 2)
    hjm_price = tff.models.hjm.swaption_price(expiries=expiries, fixed_leg_payment_times=fixed_leg_payment_times, fixed_leg_daycount_fractions=fixed_leg_daycount_fractions, fixed_leg_coupon=fixed_leg_coupon, reference_rate_fn=zero_rate_fn, notional=100.0, num_hjm_factors=2, mean_reversion=[mu, mu], volatility=[vol1, vol2], num_samples=25000, valuation_method=valuation_method, time_step_finite_difference=0.05, num_grid_points_finite_difference=251, time_step=0.1, random_type=tff.math.random.RandomType.STATELESS_ANTITHETIC, seed=[1, 2], dtype=dtype)
    hjm_price = self.evaluate(hjm_price)
    hw_price = tff.models.hull_white.swaption_price(expiries=expiries, floating_leg_start_times=[0], floating_leg_end_times=[0], floating_leg_daycount_fractions=[0], fixed_leg_payment_times=fixed_leg_payment_times, fixed_leg_daycount_fractions=fixed_leg_daycount_fractions, fixed_leg_coupon=fixed_leg_coupon, reference_rate_fn=zero_rate_fn, notional=100.0, mean_reversion=[mu], volatility=[eff_vol], use_analytic_pricing=True, dtype=dtype)
    hw_price = self.evaluate(hw_price)
    self.assertNear(hjm_price, hw_price, error_tol)

Test that under certain conditions HJM matches analytic HW results.

Args:
valuation_method: The valuation method used.
error_tol: Test error tolerance.

For the two factor model, when both mean reversions are equivalent, then
the HJM model matches that of a HW one-factor model with the same mean
reversion, and effective volatility:
eff_vol = sqrt(vol1^2 + vol2^2 + 2 rho(vol1 * vol2)
where rho is the cross correlation between the two factors. In this
specific test, we assume rho = 0.0.


def get_program_by_title(self, program_title):

        all_programs = self._load_data(self.PROGRAMS_ENDPOINT, default=[])
        matching_programs = [program for program in all_programs if program.get('title') == program_title]
        if len(matching_programs) > 1:
            raise MultipleProgramMatchError(len(matching_programs))
        elif len(matching_programs) == 1:
            return matching_programs[0]
        else:
            return None

Return single program by name, or None if not found.

Arguments:
program_title(string): Program title as seen by students and in Course Catalog Admin

Returns:
dict: Program data provided by Course Catalog API


def log(self, level, msg, *args, **kwargs):

    if level >= logging.FATAL:

      extra = kwargs.setdefault('extra', {})
      extra[_ABSL_LOG_FATAL] = True
    super(ABSLLogger, self).log(level, msg, *args, **kwargs)

Logs a message at a cetain level substituting in the supplied arguments.

This method behaves differently in python and c++ modes.

Args:
level: int, the standard logging level at which to log the message.
msg: str, the text of the message to log.
*args: The arguments to substitute in the message.
**kwargs: The keyword arguments to substitute in the message.


def inverse(self, name: str='inverse') -> 'LinearOperator':
    if self.is_square is False:
        raise ValueError('Cannot take the Inverse: This operator represents a non square matrix.')
    if self.is_non_singular is False:
        raise ValueError('Cannot take the Inverse: This operator represents a singular matrix.')
    with self._name_scope(name):
        return self._linop_inverse()

Returns the Inverse of this `LinearOperator`.

Given `A` representing this `LinearOperator`, return a `LinearOperator`
representing `A^-1`.

Args:
name: A name scope to use for ops added by this method.

Returns:
`LinearOperator` representing inverse of this matrix.

Raises:
ValueError: When the `LinearOperator` is not hinted to be `non_singular`.


def experimental_from_jax(cls, serving_funcs, inputs):
    TFLiteConverterBase._set_original_model_type(conversion_metadata_fb.ModelType.JAX)
    return TFLiteJaxConverterV2(serving_funcs, inputs)

Creates a TFLiteConverter object from a Jax model with its inputs.

Args:
serving_funcs: An array of Jax functions with all the weights applied
already.
inputs: An array of Jax input placeholders tuples list, e.g.,
jnp.zeros(INPUT_SHAPE). Each tuple list should correspond with the
serving function.

Returns:
TFLiteConverter object.


def concat_video(video_list, out_file, vcodec=None, acodec=None, log_level='info', print_cmd=False, **kwargs):
    (_, tmp_filename) = tempfile.mkstemp(suffix='.txt', text=True)
    with open(tmp_filename, 'w') as f:
        for filename in video_list:
            f.write('file {}\n'.format(osp.abspath(filename)))
    options = {'log_level': log_level}
    if (vcodec is None):
        options['vcodec'] = 'copy'
    if (acodec is None):
        options['acodec'] = 'copy'
    convert_video(tmp_filename, out_file, print_cmd, pre_options='-f concat -safe 0', **options)
    os.remove(tmp_filename)

Concatenate multiple videos into a single one.

Args:
video_list (list): A list of video filenames
out_file (str): Output video filename
vcodec (None or str): Output video codec, None for unchanged
acodec (None or str): Output audio codec, None for unchanged
log_level (str): Logging level of ffmpeg.
print_cmd (bool): Whether to print the final ffmpeg command.


def _CheckPythonModuleVersion(
      self, module_name, module_object, version_property, minimum_version,
      maximum_version):

    module_version = None
    if not version_property.endswith('()'):
      module_version = getattr(module_object, version_property, None)
    else:
      version_method = getattr(
          module_object, version_property[:-2], None)
      if version_method:
        module_version = version_method()

    if not module_version:
      status_message = (
          'unable to determine version information for: {0:s}').format(
              module_name)
      return False, status_message

    module_version = '{0!s}'.format(module_version)

    module_version = self._VERSION_NUMBERS_REGEX.findall(module_version)[0]

    if module_version[-1] == '.':
      module_version = module_version[:-1]

    try:
      module_version_map = list(
          map(int, self._VERSION_SPLIT_REGEX.split(module_version)))
    except ValueError:
      status_message = 'unable to parse module version: {0:s} {1:s}'.format(
          module_name, module_version)
      return False, status_message

    if minimum_version:
      try:
        minimum_version_map = list(
            map(int, self._VERSION_SPLIT_REGEX.split(minimum_version)))
      except ValueError:
        status_message = 'unable to parse minimum version: {0:s} {1:s}'.format(
            module_name, minimum_version)
        return False, status_message

      if module_version_map < minimum_version_map:
        status_message = (
            '{0:s} version: {1!s} is too old, {2!s} or later required').format(
                module_name, module_version, minimum_version)
        return False, status_message

    if maximum_version:
      try:
        maximum_version_map = list(
            map(int, self._VERSION_SPLIT_REGEX.split(maximum_version)))
      except ValueError:
        status_message = 'unable to parse maximum version: {0:s} {1:s}'.format(
            module_name, maximum_version)
        return False, status_message

      if module_version_map > maximum_version_map:
        status_message = (
            '{0:s} version: {1!s} is too recent, {2!s} or earlier '
            'required').format(module_name, module_version, maximum_version)
        return False, status_message

    status_message = '{0:s} version: {1!s}'.format(module_name, module_version)
    return True, status_message

Checks the version of a Python module.

Args:
module_object (module): Python module.
module_name (str): name of the Python module.
version_property (str): version attribute or function.
minimum_version (str): minimum version.
maximum_version (str): maximum version.

Returns:
tuple: consists:

bool: True if the Python module is available and conforms to
the minimum required version, False otherwise.
str: status message.


def get_ast_dict(belstr, component_type: str=''):
    errors = []
    parsed = {}
    bels = list(belstr)
    (char_locs, errors) = parse_chars(bels, errors)
    (parsed, errors) = parse_functions(belstr, char_locs, parsed, errors)
    (parsed, errors) = parse_args(bels, char_locs, parsed, errors)
    (parsed, errors) = arg_types(parsed, errors)
    (parsed, errors) = parse_relations(belstr, char_locs, parsed, errors)
    (parsed, errors) = parse_nested(bels, char_locs, parsed, errors)
    errors = parsed_top_level_errors(parsed, errors)
    (ast, errors) = parsed_to_ast(parsed, errors, component_type=component_type)
    return (ast, errors)

Convert BEL string to AST dictionary

Args:
belstr: BEL string
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input


def query_orders(self, accounts, status='filled'):

        try:
            data = self.call("orders", {'client': accounts, 'status': status})

            if data is not None:
                orders = data.get('dataTable', False)

                order_headers = orders['columns']
                if ('成交状态' in order_headers
                        or '状态说明' in order_headers) and ('备注' in order_headers):
                    order_headers[order_headers.index('备注')] = '废弃'

                order_headers = [cn_en_compare[item] for item in order_headers]
                order_all = pd.DataFrame(
                    orders['rows'],
                    columns=order_headers
                ).assign(account_cookie=accounts)

                order_all.towards = order_all.towards.apply(
                    lambda x: trade_towards_cn_en[x]
                )
                if 'order_time' in order_headers:

                    order_all['status'] = order_all.status.apply(
                        lambda x: order_status_cn_en[x]
                    )
                    if 'order_date' not in order_headers:
                        order_all.order_time = order_all.order_time.apply(
                            lambda x: QA_util_get_order_datetime(
                                dt='{} {}'.format(datetime.date.today(),
                                                  x)
                            )
                        )
                    else:
                        order_all = order_all.assign(
                            order_time=order_all.order_date
                            .apply(QA_util_date_int2str) + ' ' +
                            order_all.order_time
                        )

                if 'trade_time' in order_headers:

                    order_all.trade_time = order_all.trade_time.apply(
                        lambda x: '{} {}'.format(datetime.date.today(),
                                                 x)
                    )

                if status is 'filled':
                    return order_all.loc[:,
                                         self.dealstatus_headers].set_index(
                                             ['account_cookie',
                                              'realorder_id']
                    ).sort_index()
                else:
                    return order_all.loc[:,
                                         self.orderstatus_headers].set_index(
                                             ['account_cookie',
                                              'realorder_id']
                    ).sort_index()
            else:
                print('response is None')
                return False
        except Exception as e:
            print(e)
            return False

查询订单

Arguments:
accounts {[type]} -- [description]

Keyword Arguments:
status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'})

Returns:
[type] -- [description]


def _copy_source(s, graph, op_map, handle_captures, inverse_captures, base_graph):
    if handle_captures and s in inverse_captures:
        copied_placeholder = graph.capture(inverse_captures[s], name=s.op.name)
    elif s.op.type == 'PlaceholderWithDefault' and _constant_inputs(s):
        default_value = s.op.inputs[0]
        unavailable_inputs, unavailable_control_inputs = _copy_non_source(op=default_value.op, graph=graph, op_map=op_map, base_graph=base_graph)
        if unavailable_inputs or unavailable_control_inputs:
            raise AssertionError('Could not copy source node {} because it has inputs.'.format(default_value))
        with ops.device(s.op.device):
            copied_placeholder = array_ops.placeholder_with_default(input=op_map[default_value], shape=s.shape, name=s.op.name)
    else:
        with ops.device(s.op.device):
            copied_placeholder = array_ops.placeholder(dtype=s.dtype, shape=s.shape, name=s.op.name)
    base_handle = resource_variable_ops.get_resource_handle_data(s)
    if base_handle.shape_and_type:
        resource_variable_ops._set_handle_shapes_and_types(copied_placeholder, base_handle, graph_mode=True)
    op_map[s] = copied_placeholder
    op_map[s.op] = copied_placeholder.op

Create a source in a graph based on a Tensor from a different graph.

This function creates a placeholder analog of `s` in a graph with the
following behavior:

1) If s is a captured Tensor or Variable and handle_captures is set to True,
simply capture it in the new graph as well.

2) If s is a PlaceholderWithDefault whose default is a constant, preserve
said default in the new graph.

3) When applicable, copy resource variable metadata from `s` to the newly
created placeholder.

Args:
s: The source of interest.
graph: The destination graph.
op_map: A dict mapping ops and tensors in the old graph to the new one.
handle_captures: A boolean indicating whether to re-capture s in the new
graph or simply create a vanilla placeholder.
inverse_captures: A dict mapping s back to the Tensor or Variable that it
captures.
base_graph: The graph being copied from.


def setExtension(self, ext):

        if ext[0] != ".":
            ext = "." + ext
        self._ext = utils.asString(ext)

Set a new file extension for the sequence.

Note:
A leading period will be added if none is provided.

Args:
ext (str): the new file extension


def center_label(self, input_length, order):

        location_in_the_box = '*'.center(input_length * 2 - 1).index('*') + 1
        top_limit = order * 2 + 2
        bot_limit = top_limit + 2
        if top_limit <= location_in_the_box < bot_limit:
            if location_in_the_box == top_limit:
                self.top_connect = self.label
            elif location_in_the_box == top_limit + 1:
                self.mid_content = self.label
            else:
                self.bot_connect = self.label

In multi-bit elements, the label is centered vertically.
Args:
input_length (int): Rhe amount of wires affected.
order (int): Which middle element is this one?


def patch_addPadding(self, patches):
    paddingLength = self.Patch_Margin
    nullPadding = ''
    for x in range(1, (paddingLength + 1)):
        nullPadding += chr(x)
    for patch in patches:
        patch.start1 += paddingLength
        patch.start2 += paddingLength
    patch = patches[0]
    diffs = patch.diffs
    if ((not diffs) or (diffs[0][0] != self.DIFF_EQUAL)):
        diffs.insert(0, (self.DIFF_EQUAL, nullPadding))
        patch.start1 -= paddingLength
        patch.start2 -= paddingLength
        patch.length1 += paddingLength
        patch.length2 += paddingLength
    elif (paddingLength > len(diffs[0][1])):
        extraLength = (paddingLength - len(diffs[0][1]))
        newText = (nullPadding[len(diffs[0][1]):] + diffs[0][1])
        diffs[0] = (diffs[0][0], newText)
        patch.start1 -= extraLength
        patch.start2 -= extraLength
        patch.length1 += extraLength
        patch.length2 += extraLength
    patch = patches[(- 1)]
    diffs = patch.diffs
    if ((not diffs) or (diffs[(- 1)][0] != self.DIFF_EQUAL)):
        diffs.append((self.DIFF_EQUAL, nullPadding))
        patch.length1 += paddingLength
        patch.length2 += paddingLength
    elif (paddingLength > len(diffs[(- 1)][1])):
        extraLength = (paddingLength - len(diffs[(- 1)][1]))
        newText = (diffs[(- 1)][1] + nullPadding[:extraLength])
        diffs[(- 1)] = (diffs[(- 1)][0], newText)
        patch.length1 += extraLength
        patch.length2 += extraLength
    return nullPadding

Add some padding on text start and end so that edges can match
something.  Intended to be called only from within patch_apply.

Args:
patches: Array of Patch objects.

Returns:
The padding string added to each side.


def download_report_hook(count, block_size, total_size):

  percent = int(count * block_size * 100 / total_size)
  print("\r%d%%" % percent + " completed", end="\r")

Report hook for download progress.

Args:
count: current block number
block_size: block size
total_size: total size


def get_counters(counter_list):
    if (not isinstance(counter_list, list)):
        raise CommandExecutionError('counter_list must be a list of tuples')
    try:
        query = win32pdh.OpenQuery()
        counters = build_counter_list(counter_list)
        for counter in counters:
            counter.add_to_query(query)
        win32pdh.CollectQueryData(query)
        time.sleep(1)
        win32pdh.CollectQueryData(query)
        ret = {}
        for counter in counters:
            try:
                ret.update({counter.path: counter.value()})
            except pywintypes.error as exc:
                if (exc.strerror == 'No data to return.'):
                    continue
                else:
                    raise
    finally:
        win32pdh.CloseQuery(query)
    return ret

Get the values for the passes list of counters

Args:
counter_list (list):
A list of counters to lookup

Returns:
dict: A dictionary of counters and their values


def get_apps_to_backup(self):
    app_db = appsdb.ApplicationsDatabase()
    apps_to_backup = (self._config.apps_to_sync or app_db.get_app_names())
    for app_name in self._config.apps_to_ignore:
        apps_to_backup.discard(app_name)
    return apps_to_backup

Get the list of applications that should be backed up by Mackup.

It's the list of allowed apps minus the list of ignored apps.

Returns:
(set) List of application names to back up


def split_into_batches(input_list, batch_size, batch_storage_dir, checkpoint=False):
    if (checkpoint and (not os.path.exists(batch_storage_dir))):
        os.mkdir(batch_storage_dir)
    batches = [{'index': batch_index, 'data': input_list[start_index:(start_index + batch_size)], 'input_filename': os.path.join(batch_storage_dir, 'batch-{:05d}-input.pickle'.format(batch_index)), 'result_filename': os.path.join(batch_storage_dir, 'batch-{:05d}-output.pickle'.format(batch_index))} for (batch_index, start_index) in enumerate(range(0, len(input_list), batch_size))]
    if checkpoint:
        for batch in batches:
            save(batch['data'], batch['input_filename'])
    return batches

Break the input data into smaller batches, optionally saving each one to disk.

Args:
input_list: An input object that has a list-like interface (indexing and slicing).
batch_size: The maximum number of input items in each batch.
batch_storage_dir: The directory to save the checkpoints to.
checkpoint: Whether to save each batch to a file.

Returns:
A list of batch objects with the following structure:
{'index', 'data', 'input_filename', 'result_filename'}


def structure_from_ncdata(ncdata, site_properties=None, cls=Structure):

    ncdata, closeit = as_ncreader(ncdata)

    lattice = ArrayWithUnit(ncdata.read_value("primitive_vectors"), "bohr").to("ang")

    red_coords = ncdata.read_value("reduced_atom_positions")
    natom = len(red_coords)

    znucl_type = ncdata.read_value("atomic_numbers")

    type_atom = ncdata.read_value("atom_species")

    species = natom * [None]
    for atom in range(natom):
        type_idx = type_atom[atom] - 1
        species[atom] = int(znucl_type[type_idx])

    d = {}
    if site_properties is not None:
        for prop in site_properties:
            d[property] = ncdata.read_value(prop)

    structure = cls(lattice, species, red_coords, site_properties=d)

    try:
        from abipy.core.structure import Structure as AbipyStructure
        structure.__class__ = AbipyStructure
    except ImportError:
        pass

    if closeit:
        ncdata.close()

    return structure

Reads and returns a pymatgen structure from a NetCDF file
containing crystallographic data in the ETSF-IO format.

Args:
ncdata: filename or NetcdfReader instance.
site_properties: Dictionary with site properties.
cls: The Structure class to instanciate.


def __init__(self, default: typing.Optional[str]=MISSING_VALUE, regex: typing.Optional[str]=None, is_noneable: bool=False, frozen: bool=False):
    self._regex = re.compile(regex) if regex else None
    super().__init__(str, default, is_noneable=is_noneable, frozen=frozen)

Constructor.

Args:
default: Default value for this value spec.
regex: Optional regular expression for acceptable value.
is_noneable: If True, None is acceptable.
frozen: If True, values other than the default value is not accceptable.


def _read(cls, filepath_or_buffer, **kwargs):

        try:
            args, _, _, defaults, _, _, _ = inspect.getfullargspec(cls.read_csv)
            defaults = dict(zip(args[2:], defaults))
            filtered_kwargs = {
                kw: kwargs[kw]
                for kw in kwargs
                if kw in defaults
                and not isinstance(kwargs[kw], type(defaults[kw]))
                or kwargs[kw] != defaults[kw]
            }

        except AttributeError:
            filtered_kwargs = kwargs

        if isinstance(filepath_or_buffer, str):
            if not file_exists(filepath_or_buffer):
                ErrorMessage.default_to_pandas("File path could not be resolved")
                return cls._read_csv_from_pandas(filepath_or_buffer, filtered_kwargs)
        elif not isinstance(filepath_or_buffer, py.path.local):
            read_from_pandas = True

            try:
                import pathlib

                if isinstance(filepath_or_buffer, pathlib.Path):
                    read_from_pandas = False
            except ImportError:
                pass
            if read_from_pandas:
                ErrorMessage.default_to_pandas("Reading from buffer.")
                return cls._read_csv_from_pandas(filepath_or_buffer, kwargs)
        if (
            _infer_compression(filepath_or_buffer, kwargs.get("compression"))
            is not None
        ):
            ErrorMessage.default_to_pandas("Compression detected.")
            return cls._read_csv_from_pandas(filepath_or_buffer, filtered_kwargs)

        chunksize = kwargs.get("chunksize")
        if chunksize is not None:
            ErrorMessage.default_to_pandas("Reading chunks from a file.")
            return cls._read_csv_from_pandas(filepath_or_buffer, filtered_kwargs)

        skiprows = kwargs.get("skiprows")
        if skiprows is not None and not isinstance(skiprows, int):
            ErrorMessage.default_to_pandas("skiprows parameter not optimized yet.")
            return cls._read_csv_from_pandas(filepath_or_buffer, kwargs)

        if kwargs.get("nrows") is not None:
            ErrorMessage.default_to_pandas("`read_csv` with `nrows`")
            return cls._read_csv_from_pandas(filepath_or_buffer, filtered_kwargs)
        else:
            return cls._read_csv_from_file_pandas_on_ray(
                filepath_or_buffer, filtered_kwargs
            )

Read csv file from local disk.
Args:
filepath_or_buffer:
The filepath of the csv file.
We only support local files for now.
kwargs: Keyword arguments in pandas.read_csv


def compression_type(self):
    best_compression = None
    for e in self.mardata.index.entries:
        self.fileobj.seek(e.offset)
        magic = self.fileobj.read(10)
        compression = guess_compression(magic)
        if (compression == 'xz'):
            best_compression = 'xz'
            break
        elif ((compression == 'bz2') and (best_compression is None)):
            best_compression = 'bz2'
    return best_compression

Return the latest compresion type used in this MAR.

Returns:
One of None, 'bz2', or 'xz'


def unpack(value):
    if not is_packed(value):
        return value
    variant = value._tf_extension_type_packed_variant
    spec = value._tf_extension_type_cached_type_spec
    spec = spec._tf_extension_type_with_packed(False)
    return composite_tensor_ops.composite_tensor_from_variant(variant, spec)

Returns a copy of `value` with individual fields stored in __dict__.

Args:
value: An `ExtensionType` object.

Returns:
An `ExtensionType` object.


def load_data_split(proc_data_dir):

    ds_train = Dataset.load(path.join(proc_data_dir, 'train.bin'))
    ds_val = Dataset.load(path.join(proc_data_dir, 'val.bin'))
    ds_test = Dataset.load(path.join(proc_data_dir, 'test.bin'))
    return ds_train, ds_val, ds_test

Loads a split dataset

Args:
proc_data_dir: Directory with the split and processed data

Returns:
(Training Data, Validation Data, Test Data)


def dagify_min_edge(g):

    while not nx.is_directed_acyclic_graph(g):
        cycle = next(nx.simple_cycles(g))
        scores = []
        edges = []
        for i, j in zip(cycle[:1], cycle[:1]):
            edges.append((i, j))
            scores.append(g[i][j]['weight'])

        i, j = edges[scores.index(min(scores))]
        gc = deepcopy(g)
        gc.remove_edge(i, j)
        gc.add_edge(j, i)

        if len(list(nx.simple_cycles(gc))) < len(list(nx.simple_cycles(g))):
            g.add_edge(j, i, weight=min(scores))
        g.remove_edge(i, j)
    return g

Input a graph and output a DAG.

The heuristic is to reverse the edge with the lowest score of the cycle
if possible, else remove it.

Args:
g (networkx.DiGraph): Graph to modify to output a DAG

Returns:
networkx.DiGraph: DAG made out of the input graph.


def _CreateFlagItem(flag, docstring_info, spec, required=False, flag_string=None, short_arg=False):
    max_str_length = LINE_LENGTH - SECTION_INDENTATION - SUBSECTION_INDENTATION
    description = _GetArgDescription(flag, docstring_info)
    if not flag_string:
        flag_name_upper = formatting.Underline(flag.upper())
        flag_string = f'--{flag}={flag_name_upper}'
    if required:
        flag_string += ' (required)'
    if short_arg:
        short_flag = flag[0]
        flag_string = f'-{short_flag}, {flag_string}'
    arg_type = _GetArgType(flag, spec)
    arg_default = _GetArgDefault(flag, spec)
    if arg_default == 'None':
        arg_type = f'Optional[{arg_type}]'
    arg_type = f'Type: {arg_type}' if arg_type else ''
    available_space = max_str_length - len(arg_type)
    arg_type = formatting.EllipsisTruncate(arg_type, available_space, max_str_length)
    arg_default = f'Default: {arg_default}' if arg_default else ''
    available_space = max_str_length - len(arg_default)
    arg_default = formatting.EllipsisTruncate(arg_default, available_space, max_str_length)
    description = '\n'.join((part for part in (arg_type, arg_default, description) if part))
    return _CreateItem(flag_string, description, indent=SUBSECTION_INDENTATION)

Returns a string describing a flag using docstring and FullArgSpec info.

Args:
flag: The name of the flag.
docstring_info: A docstrings.DocstringInfo namedtuple with information about
the containing function's docstring.
spec: An instance of fire.inspectutils.FullArgSpec, containing type and
default information about the arguments to a callable.
required: Whether the flag is required.
flag_string: If provided, use this string for the flag, rather than
constructing one from the flag name.
short_arg: Whether the flag has a short variation or not.
Returns:
A string to be used in constructing the help screen for the function.


def read(self, vals):

        i = 0
        if len(vals[i]) == 0:
            self.comments_2 = None
        else:
            self.comments_2 = vals[i]
        i += 1

Read values.

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


def __init__(self, order_dict, default_order=None):

        self.order_dict = order_dict.copy()
        self.default_order = default_order

Create a reorderer.

Args:
order_dict (dict of (str, `PackageOrder`): Orderers to apply to
each package family.
default_order (`PackageOrder`): Orderer to apply to any packages
not specified in `order_dict`.