def multiply(self, other):

        if not isinstance(other, Number):
            raise QiskitError("other is not a number")
        return SuperOp(other * self._data, self.input_dims(),
                       self.output_dims())

Return the QuantumChannel self + other.

Args:
        other (complex): a complex number.

Returns:
        SuperOp: the scalar multiplication other * self as a SuperOp object.

Raises:
        QiskitError: if other is not a valid scalar.


def env_problem(env_problem_name, **kwargs):

  ep_cls = Registries.env_problems[env_problem_name]
  ep = ep_cls()
  ep.initialize(**kwargs)
  return ep

Get and initialize the `EnvProblem` with the given name and batch size.

Args:
        env_problem_name: string name of the registered env problem.
        **kwargs: forwarded to env problem's initialize method.

Returns:
        an initialized EnvProblem with the given batch size.


def changes(self, **kwargs):

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

List the merge request changes.

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

Raises:
        GitlabAuthenticationError: If authentication is not correct
        GitlabListError: If the list could not be retrieved

Returns:
        RESTObjectList: List of changes


def encode(self, s):

    return [int(w) + self._num_reserved_ids for w in s.split()]

Transform a human-readable string into a sequence of int ids.

    The ids should be in the range [num_reserved_ids, vocab_size). Ids [0,
    num_reserved_ids) are reserved.

    EOS is not appended.

Args:
        s: human-readable string to be converted.

Returns:
        ids: list of integers


def _CompareStores(self, storage_reader, compare_storage_reader):

    storage_counters = self._CalculateStorageCounters(storage_reader)
    compare_storage_counters = self._CalculateStorageCounters(
        compare_storage_reader)

    # TODO: improve comparison, currently only total numbers are compared.

    return storage_counters == compare_storage_counters

Compares the contents of two stores.

Args:
        storage_reader (StorageReader): storage reader.
        compare_storage_reader (StorageReader): storage to compare against.

Returns:
        bool: True if the content of the stores is identical.


def add_element(self, element):

        if isinstance(element, BaseExpression):
            element.set_parent(self._working_fragment)
            self._working_fragment.elements.append(element)
            return self
        else:
            return self.add_operator(element)

Add an element of type ``Operator``, ``Constraint``, or
    ``Expression`` to the ``Expression``.

Args:
        element: ``Constraint``, ``Expression``, or ``Operator``.

Returns:
        Expression: ``self``

Raises:
        FiqlObjectException: Element is not a valid type.


def append_flags_into_file(self, filename):

    with open(filename, 'a') as out_file:
      out_file.write(self.flags_into_string())

Appends all flags assignments from this FlagInfo object to a file.

    Output will be in the format of a flagfile.

    NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile
    from https://github.com/gflags/gflags.

Args:
        filename: str, name of the file.


def do_ams_sto_put(endpoint, body, content_length):

    headers = {"Accept": json_acceptformat,
               "Accept-Charset" : charset,
               "x-ms-blob-type" : "BlockBlob",
               "x-ms-meta-m1": "v1",
               "x-ms-meta-m2": "v2",
               "x-ms-version" : "2015-02-21",
               "Content-Length" : str(content_length)}
    return requests.put(endpoint, data=body, headers=headers)

Do a PUT request to the Azure Storage API and return JSON.

Args:
        endpoint (str): Azure Media Services Initial Endpoint.
        body  (str): Azure Media Services Content Body.
        content_length (str): Content_length.

Returns:
        HTTP response. JSON body.


def convert_frame_change(self, shift, instruction):

        command_dict = {
            'name': 'fc',
            't0': shift+instruction.start_time,
            'ch': instruction.channels[0].name,
            'phase': instruction.command.phase
        }
        return self._qobj_model(**command_dict)

Return converted `FrameChangeInstruction`.

Args:
        shift(int): Offset time.
        instruction (FrameChangeInstruction): frame change instruction.

Returns:
        dict: Dictionary of required parameters.


def to_string(cls, error_code):

        if error_code == cls.ZONE_NOT_FOUND_ERROR:
            return 'Zone not found'
        return super(JLinkWriteErrors, cls).to_string(error_code)

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

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

Returns:
        An error string corresponding to the error code.

Raises:
        ValueError: if the error code is invalid.


def template(self, name):

        self.plain, self.html = self._find_tpls(name)
        if not self.plain:
            self.plain = self._find_tpl(name)
        try:
            self.send = self._sendtpl
            yield
        finally:
            self.plain, self.html = None, None
            self.send = self._send

Set an active template to use with our Postman.

    This changes the call signature of send.

Args:
    - `name`: str

    Return: None
    Exceptions: None


def __init__(self, session, proxy_class):

        assert isinstance(proxy_class, type)
        self.session = session
        self.proxy_class = proxy_class

Instantiate an API Authentication Proxy.

Args:
        auth (requests.Session): Authenticated requests Session.
        proxy_class (type): A class implementing the ``BaseApi``
        interface.


def TSKVolumeGetBytesPerSector(tsk_volume):

  # Note that because pytsk3.Volume_Info does not explicitly defines info
  # we need to check if the attribute exists and has a value other
  # than None. Default to 512 otherwise.
  if hasattr(tsk_volume, 'info') and tsk_volume.info is not None:
    block_size = getattr(tsk_volume.info, 'block_size', 512)
  else:
    block_size = 512

  return block_size

Retrieves the number of bytes per sector from a TSK volume object.

Args:
        tsk_volume (pytsk3.Volume_Info): TSK volume information.

Returns:
        int: number of bytes per sector or 512 by default.


def _publish_scan_response(self, client):

        devices = self._manager.scanned_devices

        converted_devs = []
        for uuid, info in devices.items():
            slug = self._build_device_slug(uuid)

            message = {}
            message['uuid'] = uuid
            if uuid in self._connections:
                message['user_connected'] = True
            elif 'user_connected' in info:
                message['user_connected'] = info['user_connected']
            else:
                message['user_connected'] = False

            message['connection_string'] = slug
            message['signal_strength'] = info['signal_strength']

            converted_devs.append({x: y for x, y in message.items()})
            message['type'] = 'notification'
            message['operation'] = 'advertisement'

            self.client.publish(self.topics.gateway_topic(slug, 'data/advertisement'), message)

        probe_message = {}
        probe_message['type'] = 'response'
        probe_message['client'] = client
        probe_message['success'] = True
        probe_message['devices'] = converted_devs

        self.client.publish(self.topics.status, probe_message)

Publish a scan response message

    The message contains all of the devices that are currently known
    to this agent.  Connection strings for direct connections are
    translated to what is appropriate for this agent.

Args:
        client (string): A unique id for the client that made this request


def get_local_variable_from_name(self, variable_name):

        return next((v for v in self.variables if v.name == variable_name), None)

Return a local variable from a name

Args:
        varible_name (str): name of the variable

Returns:
        LocalVariable


def __init__(self, resolver_context):

    super(CPIOFile, self).__init__(resolver_context)
    self._cpio_archive_file = None
    self._cpio_archive_file_entry = None
    self._current_offset = 0
    self._file_system = None
    self._size = 0

Initializes a file-like object.

Args:
        resolver_context (Context): resolver context.


def _adjust_penalty(self, observ, old_policy_params, length):

    old_policy = self._policy_type(**old_policy_params)
    with tf.name_scope('adjust_penalty'):
      network = self._network(observ, length)
      print_penalty = tf.Print(0, [self._penalty], 'current penalty: ')
      with tf.control_dependencies([print_penalty]):
        kl_change = tf.reduce_mean(self._mask(
            tf.contrib.distributions.kl_divergence(old_policy, network.policy),
            length))
        kl_change = tf.Print(kl_change, [kl_change], 'kl change: ')
        maybe_increase = tf.cond(
            kl_change > 1.3 * self._config.kl_target,
            # pylint: disable=g-long-lambda
            lambda: tf.Print(self._penalty.assign(
                self._penalty * 1.5), [0], 'increase penalty '),
            float)
        maybe_decrease = tf.cond(
            kl_change < 0.7 * self._config.kl_target,
            # pylint: disable=g-long-lambda
            lambda: tf.Print(self._penalty.assign(
                self._penalty / 1.5), [0], 'decrease penalty '),
            float)
      with tf.control_dependencies([maybe_increase, maybe_decrease]):
        return tf.summary.merge([
            tf.summary.scalar('kl_change', kl_change),
            tf.summary.scalar('penalty', self._penalty)])

Adjust the KL policy between the behavioral and current policy.

    Compute how much the policy actually changed during the multiple
    update steps. Adjust the penalty strength for the next training phase if we
    overshot or undershot the target divergence too much.

Args:
        observ: Sequences of observations.
        old_policy_params: Parameters of the behavioral policy.
        length: Batch of sequence lengths.

Returns:
        Summary tensor.


def get_by_provider_display_name(self, provider_display_name):

        san_managers = self._client.get_all()
        result = [x for x in san_managers if x['providerDisplayName'] == provider_display_name]
        return result[0] if result else None

Gets a SAN Manager by provider display name.

Args:
        provider_display_name: Name of the Provider Display Name

Returns:
        dict: SAN Manager.


def exec_function(ast, globals_map):

    locals_map = globals_map
    exec ast in globals_map, locals_map
    return locals_map

Execute a python code object in the given environment.

Args:
        globals_map: Dictionary to use as the globals context.

Returns:
        locals_map: Dictionary of locals from the environment after execution.


def post(self, url, params=None, data=None, files=None, **kwargs):

        return self.call_api(
            "POST",
            url,
            params=params,
            data=data,
            files=files,
            **kwargs
        )

Call the API with a POST request.

Args:
        url (str): Resource location relative to the base URL.
        params (dict or None): Query-string parameters.
        data (dict or None): Request body contents.
        files (dict or None: Files to be passed to the request.

Returns:
        An instance of ResultParser or ErrorParser.


def set_energy_upperbound(self, spins, offset=0):

        spin_energy = self.energy_upperbound(spins)
        self.assertions.add(GE(spin_energy, self.gap + offset))

Upper bound the energy of Theta with spins fixed to be greater than (gap + offset).

Args:
        spins (dict): Spin values for a subset of the variables in Theta.
        offset (float): A value that is added to the upper bound. Default value is 0.

Note:
        Add equality constraint to assertions.


def __init__(self, shape_id=None, lat=None, lon=None,seq=None, dist=None,
               field_dict=None):

    self._schedule = None
    if field_dict:
      if isinstance(field_dict, self.__class__):
        for k, v in field_dict.iteritems():
          self.__dict__[k] = v
      else:
        self.__dict__.update(field_dict)
    else:
      self.shape_id = shape_id
      self.shape_pt_lat = lat
      self.shape_pt_lon = lon
      self.shape_pt_sequence = seq
      self.shape_dist_traveled = dist

Initialize a new ShapePoint object.

Args:
        field_dict: A dictionary mapping attribute name to unicode string


def __init__(self, channel):

        self.ListUptimeCheckConfigs = channel.unary_unary(
            "/google.monitoring.v3.UptimeCheckService/ListUptimeCheckConfigs",
            request_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__service__pb2.ListUptimeCheckConfigsRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__service__pb2.ListUptimeCheckConfigsResponse.FromString,
        )
        self.GetUptimeCheckConfig = channel.unary_unary(
            "/google.monitoring.v3.UptimeCheckService/GetUptimeCheckConfig",
            request_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__service__pb2.GetUptimeCheckConfigRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__pb2.UptimeCheckConfig.FromString,
        )
        self.CreateUptimeCheckConfig = channel.unary_unary(
            "/google.monitoring.v3.UptimeCheckService/CreateUptimeCheckConfig",
            request_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__service__pb2.CreateUptimeCheckConfigRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__pb2.UptimeCheckConfig.FromString,
        )
        self.UpdateUptimeCheckConfig = channel.unary_unary(
            "/google.monitoring.v3.UptimeCheckService/UpdateUptimeCheckConfig",
            request_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__service__pb2.UpdateUptimeCheckConfigRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__pb2.UptimeCheckConfig.FromString,
        )
        self.DeleteUptimeCheckConfig = channel.unary_unary(
            "/google.monitoring.v3.UptimeCheckService/DeleteUptimeCheckConfig",
            request_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__service__pb2.DeleteUptimeCheckConfigRequest.SerializeToString,
            response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
        )
        self.ListUptimeCheckIps = channel.unary_unary(
            "/google.monitoring.v3.UptimeCheckService/ListUptimeCheckIps",
            request_serializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__service__pb2.ListUptimeCheckIpsRequest.SerializeToString,
            response_deserializer=google_dot_cloud_dot_monitoring__v3_dot_proto_dot_uptime__service__pb2.ListUptimeCheckIpsResponse.FromString,
        )

Constructor.

Args:
        channel: A grpc.Channel.


def _build(self, x, prev_state):

    x.get_shape().with_rank(2)
    self._batch_size = x.get_shape().as_list()[0]
    self._dtype = x.dtype

    x_zeros = tf.concat(
        [x, tf.zeros(
            shape=(self._batch_size, 1), dtype=self._dtype)], 1)
    x_ones = tf.concat(
        [x, tf.ones(
            shape=(self._batch_size, 1), dtype=self._dtype)], 1)
    # Weights for the halting signal
    halting_linear = basic.Linear(name="halting_linear", output_size=1)

    body = functools.partial(
        self._body, halting_linear=halting_linear, x_ones=x_ones)
    cumul_halting_init = tf.zeros(shape=(self._batch_size, 1),
                                  dtype=self._dtype)
    iteration_init = tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)
    core_output_size = [x.value for x in self._core.output_size]
    out_init = tf.zeros(shape=(self._batch_size,) + tuple(core_output_size),
                        dtype=self._dtype)
    cumul_state_init = _nested_zeros_like(prev_state)
    remainder_init = tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)
    (unused_final_x, final_out, unused_final_state, final_cumul_state,
     unused_final_halting, final_iteration, final_remainder) = tf.while_loop(
         self._cond, body, [x_zeros, out_init, prev_state, cumul_state_init,
                            cumul_halting_init, iteration_init, remainder_init])

    act_output = basic.Linear(
        name="act_output_linear", output_size=self._output_size)(final_out)

    return (act_output, (final_iteration, final_remainder)), final_cumul_state

Connects the core to the graph.

Args:
        x: Input `Tensor` of shape `(batch_size, input_size)`.
        prev_state: Previous state. This could be a `Tensor`, or a tuple of
        `Tensor`s.

Returns:
        The tuple `(output, state)` for this core.

Raises:
        ValueError: if the `Tensor` `x` does not have rank 2.


def get_course_details(self, course_id):

        try:
            return self.client.course(course_id).get()
        except (SlumberBaseException, ConnectionError, Timeout) as exc:
            LOGGER.exception(
                'Failed to retrieve course enrollment details for course [%s] due to: [%s]',
                course_id, str(exc)
            )
            return {}

Query the Enrollment API for the course details of the given course_id.

Args:
        course_id (str): The string value of the course's unique identifier

Returns:
        dict: A dictionary containing details about the course, in an enrollment context (allowed modes, etc.)


def create_explicit(bounds):

    safe_bounds = sorted(float(x) for x in bounds)
    if len(safe_bounds) != len(set(safe_bounds)):
        raise ValueError(u'Detected two elements of bounds that are the same')
    return sc_messages.Distribution(
        bucketCounts=[0] * (len(safe_bounds) + 1),
        explicitBuckets=sc_messages.ExplicitBuckets(bounds=safe_bounds))

Creates a new instance of distribution with explicit buckets.

    bounds is an iterable of ordered floats that define the explicit buckets

Args:
        bounds (iterable[float]): initializes the bounds

Returns:
        :class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`

Raises:
        ValueError: if the args are invalid for creating an instance


def GetMessages(self, formatter_mediator, event):

    regvalue = getattr(event, 'regvalue', {})
    # Loop over all the registry value names in the service key.
    for service_value_name in regvalue.keys():
      # A temporary variable so we can refer to this long name more easily.
      service_enums = human_readable_service_enums.SERVICE_ENUMS
      # Check if we need to can make the value more human readable.
      if service_value_name in service_enums.keys():
        service_enum = service_enums[service_value_name]
        # Find the human readable version of the name and fall back to the
        # raw value if it's not found.
        human_readable_value = service_enum.get(
            regvalue[service_value_name],
            regvalue[service_value_name])
        regvalue[service_value_name] = human_readable_value

    return super(WinRegistryServiceFormatter, self).GetMessages(
        formatter_mediator, event)

Determines the formatted message strings for an event object.

Args:
        formatter_mediator (FormatterMediator): mediates the interactions between
        formatters and other components, such as storage and Windows EventLog
        resources.
        event (EventObject): event.

Returns:
        tuple(str, str): formatted message string and short message string.

Raises:
        WrongFormatter: if the event object cannot be formatted by the formatter.


def _example_number_anywhere_for_type(num_type):

    for region_code in SUPPORTED_REGIONS:
        example_numobj = example_number_for_type(region_code, num_type)
        if example_numobj is not None:
            return example_numobj
    # If there wasn't an example number for a region, try the non-geographical entities.
    for country_calling_code in COUNTRY_CODES_FOR_NON_GEO_REGIONS:
        metadata = PhoneMetadata.metadata_for_nongeo_region(country_calling_code, None)
        desc = _number_desc_by_type(metadata, num_type)
        if desc is not None and desc.example_number is not None:
            try:
                return parse(_PLUS_SIGN + unicod(country_calling_code) + desc.example_number, UNKNOWN_REGION)
            except NumberParseException:  # pragma no cover
                pass

    # There are no example numbers of this type for any country in the library.
    return None

Gets a valid number for the specified number type (it may belong to any country).

Args:
    num_type -- The type of number that is needed.

    Returns a valid number for the specified type. Returns None when the
    metadata does not contain such information. This should only happen when
    no numbers of this type are allocated anywhere in the world anymore.


def set_cookies():

    cookies = dict(request.args.items())
    r = app.make_response(redirect(url_for("view_cookies")))
    for key, value in cookies.items():
        r.set_cookie(key=key, value=value, secure=secure_cookie())

    return r

Sets cookie(s) as provided by the query string and redirects to cookie list.
    ---
    tags:
        - Cookies
    parameters:
        - in: query
        name: freeform
        explode: true
        allowEmptyValue: true
        schema:
        type: object
        additionalProperties:
            type: string
        style: form
    produces:
        - text/plain
    responses:
        200:
        description: Redirect to cookie list


def _set_details(self, content):

        try:
            self.details = str(content)
        except UnicodeEncodeError:
            if sys.version_info < (3, 0):
                # If Py2 threw encode error, convert to unicode.
                self.details = unicode(content)
            else:
                # We should never hit this in Py3, if this happens, record
                # an encoded version of the content for users to handle.
                logging.error(
                    'Unable to decode "%s" in Py3, encoding in utf-8.',
                    content)
                self.details = content.encode('utf-8')

Sets the `details` field.

Args:
        content: the content to extract details from.


def _add_input_deps(self, executor, args, kwargs):

        # Return if the task is _*_stage_in
        if executor == 'data_manager':
            return args, kwargs

        inputs = kwargs.get('inputs', [])
        for idx, f in enumerate(inputs):
            if isinstance(f, File) and f.is_remote():
                inputs[idx] = self.data_manager.stage_in(f, executor)

        for kwarg, f in kwargs.items():
            if isinstance(f, File) and f.is_remote():
                kwargs[kwarg] = self.data_manager.stage_in(f, executor)

        newargs = list(args)
        for idx, f in enumerate(newargs):
            if isinstance(f, File) and f.is_remote():
                newargs[idx] = self.data_manager.stage_in(f, executor)

        return tuple(newargs), kwargs

Look for inputs of the app that are remote files. Submit stage_in
    apps for such files and replace the file objects in the inputs list with
    corresponding DataFuture objects.

Args:
        - executor (str) : executor where the app is going to be launched
        - args (List) : Positional args to app function
        - kwargs (Dict) : Kwargs to app function


def reduce_multiline(string):

    string = str(string)
    return " ".join([item.strip()
                     for item in string.split("\n")
                     if item.strip()])

reduces a multiline string to a single line of text.

Args:
        string: the text to reduce


def get_database_info(db_uri):

  if not db_uri:
    return None, None
  scheme = urlparse.urlparse(db_uri).scheme
  if scheme == 'sqlite':
    return sqlite3, create_sqlite_connection_provider(db_uri)
  else:
    raise ValueError('Only sqlite DB URIs are supported now: ' + db_uri)

Returns TBContext fields relating to SQL database.

Args:
        db_uri: A string URI expressing the DB file, e.g. "sqlite:~/tb.db".

Returns:
        A tuple with the db_module and db_connection_provider TBContext fields. If
        db_uri was empty, then (None, None) is returned.

Raises:
        ValueError: If db_uri scheme is not supported.


def define_lattice_from_file( self, filename, cell_lengths ):

        self.lattice = init_lattice.lattice_from_sites_file( filename, cell_lengths = cell_lengths )

Set up the simulation lattice from a file containing site data.
    Uses `init_lattice.lattice_from_sites_file`, which defines the site file spec.

Args:
    filename (Str): sites file filename.
    cell_lengths (List(x,y,z)): cell lengths for the simulation cell.

Returns:
    None


def bulkBatch(symbols, fields=None, range_='1m', last=10, token='', version=''):

    fields = fields or _BATCH_TYPES
    args = []
    empty_data = []
    list_orig = empty_data.__class__

    if not isinstance(symbols, list_orig):
        raise PyEXception('Symbols must be of type list')

    for i in range(0, len(symbols), 99):
        args.append((symbols[i:i+99], fields, range_, last, token, version))

    pool = ThreadPool(20)
    rets = pool.starmap(batch, args)
    pool.close()

    ret = {}

    for i, d in enumerate(rets):
        symbols_subset = args[i][0]
        if len(d) != len(symbols_subset):
            empty_data.extend(list_orig(set(symbols_subset) - set(d.keys())))
        ret.update(d)

    for k in empty_data:
        if k not in ret:
            if isinstance(fields, str):
                ret[k] = {}
            else:
                ret[k] = {x: {} for x in fields}
    return ret

Optimized batch to fetch as much as possible at once

    https://iexcloud.io/docs/api/#batch-requests

Args:
        symbols (list); List of tickers to request
        fields (list); List of fields to request
        range_ (string); Date range for chart
        last (int);
        token (string); Access token
        version (string); API version

Returns:
        dict: results in json


def __call__(self, fn):

        def output(app, *args, **kwargs):

            data = fn(app, *args, **kwargs)
            attr = getattr(app, self.attribute)
            if isinstance(data, list) and isinstance(attr, list):
                getattr(app, self.attribute).extend(data)
            elif isinstance(attr, list):
                getattr(app, self.attribute).append(data)
            else:
                setattr(app, self.attribute, data)
            return data

        return output

Implement __call__ function for decorator.

Args:
        fn (function): The decorated function.

Returns:
        function: The custom decorator function.


def format_error(status=None, title=None, detail=None, code=None):

    error = {}
    error.update({ 'title': title })

    if status is not None:
        error.update({ 'status': status })

    if detail is not None:
        error.update({ 'detail': detail })

    if code is not None:
        error.update({ 'code': code })

    return error

Formatting JSON API Error Object
    Constructing an error object based on JSON API standard
    ref: http://jsonapi.org/format/#error-objects

Args:
        status: Can be a http status codes
        title: A summary of error
        detail: A descriptive error message
        code: Application error codes (if any)

Returns:
        A dictionary contains of status, title, detail and code


def update(self, data):

        # If the instance was terminated, remove it
        if data.state['Name'] == 'terminated':
            self.delete(auto_commit=False)
            return True

        updated = self.set_property('launch_date', to_utc_date(data.launch_time).isoformat())
        updated |= self.set_property('state', data.state['Name'])
        updated |= self.set_property('instance_type', data.instance_type)
        updated |= self.set_property('public_ip', data.public_ip_address or None)
        updated |= self.set_property('public_dns', data.public_dns_name or None)

        tags = {x['Key']: x['Value'] for x in data.tags or {}}
        existing_tags = {x.key: x for x in self.tags}

        # Check for new tags
        for key, value in list(tags.items()):
            updated |= self.set_tag(key, value)

        # Check for updated or removed tags
        for key in list(existing_tags.keys()):
            if key not in tags:
                updated |= self.delete_tag(key)

        return updated

Updates the object information based on live data, if there were any changes made. Any changes will be
    automatically applied to the object, but will not be automatically persisted. You must manually call
    `db.session.add(instance)` on the object.

Args:
        data (:obj:): AWS API Resource object fetched from AWS API

Returns:
        True if there were any changes to the object, else false


def _CompareFields(field, other_field):

  field_attrs = _GetFieldAttributes(field)
  other_field_attrs = _GetFieldAttributes(other_field)
  if field_attrs != other_field_attrs:
    return False
  return field.__class__ == other_field.__class__

Checks if two ProtoRPC fields are "equal".

    Compares the arguments, rather than the id of the elements (which is
    the default __eq__ behavior) as well as the class of the fields.

Args:
        field: A ProtoRPC message field to be compared.
        other_field: A ProtoRPC message field to be compared.

Returns:
        Boolean indicating whether the fields are equal.


def __init__(self, details):

		# If details is not a dict instance
		if not isinstance(details, dict):
			raise ValueError('details')

		# If the hash config is not found
		if '__hash__' not in details:
			raise KeyError('__hash__')

		# If there's an optional flag somewhere in the mix
		if '__optional__' in details:
			bOptional = details['__optional__']
			del details['__optional__']
		else:
			bOptional = None

		# If the hash is simply set to True, make it a string with no
		#	requirements
		if details['__hash__'] is True:
			details['__hash__'] = {"__type__":"string"}

		# Store the key using the hash value
		self._key = Node(details['__hash__'])

		# Remove it from details
		del details['__hash__']

		# Store the child
		self._node = _child(details)

		# If we had an optional flag, add it for the parent constructor
		if bOptional:
			details['__optional__'] = bOptional

		# Call the parent constructor
		super(HashNode, self).__init__(details, 'HashNode')

Constructor

    Initialises the instance

Args:
    details {dict} -- Details describing the type of values allowed for
        the node

Raises:
    KeyError
    ValueError

Returns:
    HashNode


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 read_handler(Model, name=None, **kwds):

    async def action_handler(service, action_type, payload, props, **kwds):
        # if the payload represents a new instance of `model`
        if action_type == get_crud_action('read', name or Model):
            # the props of the message
            message_props = {}
            # if there was a correlation id in the request
            if 'correlation_id' in props:
                # make sure it ends up in the reply
                message_props['correlation_id'] = props['correlation_id']

            try:
                # resolve the query using the service schema
                resolved = service.schema.execute(payload)
                # create the string response
                response = json.dumps({
                    'data': {key:value for key,value in resolved.data.items()},
                    'errors': resolved.errors
                })

                # publish the success event
                await service.event_broker.send(
                    payload=response,
                    action_type=change_action_status(action_type, success_status()),
                    **message_props
                )

            # if something goes wrong
            except Exception as err:
                # publish the error as an event
                await service.event_broker.send(
                    payload=str(err),
                    action_type=change_action_status(action_type, error_status()),
                    **message_props
                )

    # return the handler
    return action_handler

This factory returns an action handler that responds to read requests
    by resolving the payload as a graphql query against the internal schema.

Args:
        Model (nautilus.BaseModel): The model to delete when the action
            received.

Returns:
        function(type, payload): The action handler for this model


def _CountClientStatisticByLabel(self, day_buckets, extract_statistic_fn):

    counts = collections.defaultdict(int)
    now = rdfvalue.RDFDatetime.Now()
    for info in self.IterateAllClientsFullInfo(batch_size=db.MAX_COUNT):
      if not info.metadata.ping:
        continue
      statistic_value = extract_statistic_fn(info)
      for client_label in info.GetLabelsNames(owner="GRR"):
        for day_bucket in day_buckets:
          time_boundary = now - rdfvalue.Duration.FromDays(day_bucket)
          if info.metadata.ping > time_boundary:
            # Count the client if it has been active in the last 'day_bucket'
            # days.
            counts[(statistic_value, client_label, day_bucket)] += 1
    return dict(counts)

Returns client-activity metrics for a particular statistic.

Args:
        day_buckets: A set of n-day-active buckets.
        extract_statistic_fn: A function that extracts the statistic's value from
        a ClientFullInfo object.


def _GetDayOfYear(self, year, month, day_of_month):

    if month not in range(1, 13):
      raise ValueError('Month value out of bounds.')

    days_per_month = self._GetDaysPerMonth(year, month)
    if day_of_month < 1 or day_of_month > days_per_month:
      raise ValueError('Day of month value out of bounds.')

    day_of_year = day_of_month
    for past_month in range(1, month):
      day_of_year += self._GetDaysPerMonth(year, past_month)

    return day_of_year

Retrieves the day of the year for a specific day of a month in a year.

Args:
        year (int): year e.g. 1970.
        month (int): month, where 1 represents January.
        day_of_month (int): day of the month, where 1 represents the first day.

Returns:
        int: day of year.

Raises:
        ValueError: if the month or day of month value is out of bounds.


def _set_unknown_flag(self, name, value):

    setter = self.__dict__['__set_unknown']
    if setter:
      try:
        setter(name, value)
        return value
      except (TypeError, ValueError):  # Flag value is not valid.
        raise _exceptions.IllegalFlagValueError(
            '"{1}" is not valid for --{0}' .format(name, value))
      except NameError:  # Flag name is not valid.
        pass
    raise _exceptions.UnrecognizedFlagError(name, value)

Returns value if setting flag |name| to |value| returned True.

Args:
        name: str, name of the flag to set.
        value: Value to set.

Returns:
        Flag value on successful call.

Raises:
        UnrecognizedFlagError
        IllegalFlagValueError


def update_thread(cls, session, conversation, thread):

        data = thread.to_api()
        data['reload'] = True
        return cls(
            '/conversations/%s/threads/%d.json' % (
                conversation.id, thread.id,
            ),
            data=data,
            request_type=RequestPaginator.PUT,
            singleton=True,
            session=session,
        )

Update a thread.

Args:
        session (requests.sessions.Session): Authenticated session.
        conversation (helpscout.models.Conversation): The conversation
            that the thread belongs to.
        thread (helpscout.models.Thread): The thread to be updated.

Returns:
        helpscout.models.Conversation: Conversation including freshly
            updated thread.


def bind(self, event_name, callback, first = False):

		if event_name not in self.handlers:
			self.handlers[event_name] = []

		if first:
			self.handlers[event_name].insert(0, callback)
		else:
			self.handlers[event_name].append(callback)

Bind a callback to an event

    Params:
    event_name (string):
        Name of the event to bind to
    callback (callable):
        Callback that will be called when the event is triggered
    first (boolean):
        If True, this callback is placed before all the other events already
        registered for this event, otherwise it is placed at the end.


def active_futures(ticker: str, dt) -> str:

    t_info = ticker.split()
    prefix, asset = ' '.join(t_info[:-1]), t_info[-1]
    info = const.market_info(f'{prefix[:-1]}1 {asset}')

    f1, f2 = f'{prefix[:-1]}1 {asset}', f'{prefix[:-1]}2 {asset}'
    fut_2 = fut_ticker(gen_ticker=f2, dt=dt, freq=info['freq'])
    fut_1 = fut_ticker(gen_ticker=f1, dt=dt, freq=info['freq'])

    fut_tk = bdp(tickers=[fut_1, fut_2], flds='Last_Tradeable_Dt', cache=True)

    if pd.Timestamp(dt).month < pd.Timestamp(fut_tk.last_tradeable_dt[0]).month: return fut_1

    d1 = bdib(ticker=f1, dt=dt)
    d2 = bdib(ticker=f2, dt=dt)

    return fut_1 if d1[f1].volume.sum() > d2[f2].volume.sum() else fut_2

Active futures contract

Args:
        ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc.
        dt: date

Returns:
        str: ticker name


def get_app_region_products(self, app_uri):

        apps, retInfo = self.list_apps()
        if apps is None:
            return None

        for app in apps:
            if (app.get('uri') == app_uri):
                return self.get_region_products(app.get('region'))

        return

获得指定应用所在区域的产品信息

Args:
        - app_uri: 应用的完整标识

Returns:
        返回产品信息列表，若失败则返回None


def make_config_get(conf_path):

    project_root = _get_project_root_from_conf_path(conf_path)
    config = load_config_in_dir(project_root)
    return partial(config_get, config)

Return a function to get configuration options for a specific project

Args:
        conf_path (path-like): path to project's conf file (i.e. foo.conf
            module)


def sendfrom(self, user_id, dest_address, amount, minconf=1):

        amount = Decimal(amount).quantize(self.quantum, rounding=ROUND_HALF_EVEN)
        txhash = self.rpc.call("sendfrom",
            user_id, dest_address, float(str(amount)), minconf
        )
        self.logger.debug("Send %s %s from %s to %s" % (str(amount), self.coin,
                                                        str(user_id), dest_address))
        self.logger.debug("Transaction hash: %s" % txhash)
        return txhash

Send coins from user's account.

Args:
        user_id (str): this user's unique identifier
        dest_address (str): address which is to receive coins
        amount (str or Decimal): amount to send (eight decimal points)
        minconf (int): ensure the account has a valid balance using this
                    many confirmations (default=1)

Returns:
        str: transaction ID


def equal(mol, query, largest_only=True, ignore_hydrogen=True):

    m = molutil.clone(mol)
    q = molutil.clone(query)
    if largest_only:
        m = molutil.largest_graph(m)
        q = molutil.largest_graph(q)
    if ignore_hydrogen:
        m = molutil.make_Hs_implicit(m)
        q = molutil.make_Hs_implicit(q)
    if molutil.mw(m) == molutil.mw(q):
        gm = GraphMatcher(q.graph, m.graph, node_match=atom_match)
        return gm.is_isomorphic()
    return False

if mol is exactly same structure as the query, return True

Args:
        mol: Compound
        query: Compound


def parse_rdf_payload(self, data, headers):

		# handle edge case for content-types not recognized by rdflib parser
		if headers['Content-Type'].startswith('text/plain'):
			logger.debug('text/plain Content-Type detected, using application/n-triples for parser')
			parse_format = 'application/n-triples'
		else:
			parse_format = headers['Content-Type']

		# clean parse format for rdf parser (see: https://www.w3.org/2008/01/rdf-media-types)
		if ';charset' in parse_format:
			parse_format = parse_format.split(';')[0]

		# parse graph
		graph = rdflib.Graph().parse(
			data=data.decode('utf-8'),
			format=parse_format)

		# return graph
		return graph

small function to parse RDF payloads from various repository endpoints

Args:
    data (response.data): data from requests response
    headers (response.headers): headers from requests response

Returns:
    (rdflib.Graph): parsed graph


def setMinimum(self, minimum):

        if not isinstance(minimum, int):
            raise TypeError("Argument is not of type int or long")
        self._minimum = minimum

setter to _minimum.

Args:
        minimum (int or long): new _minimum value.

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


def __init__(self, input_file_name, reference_histogram):

        self.start_time_sec = 0.0
        self.observed_start_time = False
        self.base_time_sec = 0.0
        self.observed_base_time = False
        self.input_file = open(input_file_name, "r")
        self.reference_histogram = reference_histogram

Constructs a new HistogramLogReader that produces intervals read
    from the specified file name.
    Params:
        input_file_name The name of the file to read from
        reference_histogram a histogram instance used as a reference to create
                            new instances for all subsequent decoded interval
                            histograms


def add_string_pairs_from_button_element(xib_file, results, button, special_ui_components_prefix):

    button_entry_comment = extract_element_internationalized_comment(button)
    if button_entry_comment is None:
        return

    for state in button.getElementsByTagName('state'):
        state_name = state.attributes['key'].value
        state_entry_comment = button_entry_comment + " - " + state_name + " state of button"
        if not add_string_pairs_from_attributed_ui_element(results, state, state_entry_comment):
            try:
                button_entry_key = state.attributes['title'].value
            except KeyError:
                try:
                    button_entry_key = state.getElementsByTagName('string')[0].firstChild.nodeValue
                except Exception:
                    continue

            results.append((button_entry_key, state_entry_comment))

    warn_if_element_not_of_class(button, 'Button', special_ui_components_prefix)

Adds strings pairs from a button xib element.

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


def _infer_mutants_handler(self, request):

    try:
      if request.method != 'GET':
        logger.error('%s requests are forbidden.', request.method)
        return http_util.Respond(request, {'error': 'invalid non-GET request'},
                                 'application/json', code=405)

      example_index = int(request.args.get('example_index', '0'))
      feature_name = request.args.get('feature_name')
      examples = (self.examples if example_index == -1
          else [self.examples[example_index]])

      (inference_addresses, model_names, model_versions,
          model_signatures) = self._parse_request_arguments(request)

      serving_bundles = []
      for model_num in xrange(len(inference_addresses)):
        serving_bundles.append(inference_utils.ServingBundle(
            inference_addresses[model_num],
            model_names[model_num],
            request.args.get('model_type'),
            model_versions[model_num],
            model_signatures[model_num],
            request.args.get('use_predict') == 'true',
            request.args.get('predict_input_tensor'),
            request.args.get('predict_output_tensor')))

      viz_params = inference_utils.VizParams(
          request.args.get('x_min'), request.args.get('x_max'),
          self.examples[0:NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS,
          request.args.get('feature_index_pattern'))
      json_mapping = inference_utils.mutant_charts_for_feature(
          examples, feature_name, serving_bundles, viz_params)
      return http_util.Respond(request, json_mapping, 'application/json')
    except common_utils.InvalidUserInputError as e:
      return http_util.Respond(request, {'error': e.message},
                               'application/json', code=400)

Returns JSON for the `vz-line-chart`s for a feature.

Args:
        request: A request that should contain 'feature_name', 'example_index',
        'inference_address', 'model_name', 'model_type', 'model_version', and
        'model_signature'.

Returns:
        A list of JSON objects, one for each chart.


def QA_fetch_strategy(message={}, db=DATABASE):

    collection = DATABASE.strategy
    return [res for res in collection.find(message, {"_id": 0})]

get the account

Args:
        query_mes {[type]} -- [description]

    Keyword Arguments:
        collection {[type]} -- [description] (default: {DATABASE})

Returns:
        [type] -- [description]


def show(self, objtype, objid):

        url = self._object_url(objtype, int(objid))
        return self._make_request(url, method="get")

Query for a specific resource by ID

Args:
        objtype (str): object type, e.g. 'device', 'interface'
        objid (int): object ID (DeviceID, etc.)

Returns:
        A dict with that object

Raises:
        requests.exceptions.HTTPError


def save_as(self, filename: str) -> None:

        lib.TCOD_image_save(self.image_c, filename.encode("utf-8"))

Save the Image to a 32-bit .bmp or .png file.

Args:
        filename (Text): File path to same this Image.


def design_stat_extremes(self, value="Extremes"):

        if value is not None:
            try:
                value = str(value)
            except ValueError:
                raise ValueError(
                    'value {} need to be of type str '
                    'for field `design_stat_extremes`'.format(value))
            if ',' in value:
                raise ValueError('value should not contain a comma '
                                 'for field `design_stat_extremes`')
            vals = set()
            vals.add("Extremes")
            if value not in vals:
                raise ValueError('value {} is not an accepted value for '
                                 'field `design_stat_extremes`'.format(value))

        self._design_stat_extremes = value

Corresponds to IDD Field `design_stat_extremes`

Args:
        value (str): value for IDD Field `design_stat_extremes`
            Accepted values are:
                - Extremes
            Default value: Extremes
            if `value` is None it will not be checked against the
            specification and is assumed to be a missing value

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


def _get_handled_methods(self, actions_map):

        methods = ('OPTIONS',)

        defined_actions = []
        for action_name in actions_map.keys():
            view_method = getattr(self, action_name, None)
            method_exists = view_method is not None
            method_defined = view_method != self.not_allowed_action
            if method_exists and method_defined:
                defined_actions.append(action_name)

        for action in defined_actions:
            methods += actions_map[action]

        return methods

Get names of HTTP methods that can be used at requested URI.

Args:
        :actions_map: Map of actions. Must have the same structure as
            self._item_actions and self._collection_actions


def raster_to_gtiff(tif, geotif, change_nodata=False, change_gdal_type=False):

        rst_file = RasterUtilClass.read_raster(tif)
        nodata = rst_file.noDataValue
        if change_nodata:
            if not MathClass.floatequal(rst_file.noDataValue, DEFAULT_NODATA):
                nodata = DEFAULT_NODATA
                rst_file.data[rst_file.data == rst_file.noDataValue] = DEFAULT_NODATA
        gdal_type = rst_file.dataType
        if change_gdal_type:
            gdal_type = GDT_Float32
        RasterUtilClass.write_gtiff_file(geotif, rst_file.nRows, rst_file.nCols, rst_file.data,
                                         rst_file.geotrans, rst_file.srs, nodata,
                                         gdal_type)

Converting Raster format to GeoTIFF.

Args:
        tif: source raster file path.
        geotif: output raster file path.
        change_nodata: change NoDataValue to -9999 or not.
        gdal_type (:obj:`pygeoc.raster.GDALDataType`): GDT_Float32 as default.
        change_gdal_type: If True, output the Float32 data type.


def k_value_orifice(pipe_id, orifice_id, orifice_l, q,
                    nu=con.WATER_NU):

    if orifice_id > pipe_id:
        raise ValueError('The orifice\'s inner diameter cannot be larger than'
                         'that of the entrance pipe.')

    re = pc.re_pipe(q, pipe_id, nu)  # Entrance pipe's Reynolds number.

    orifice_type = _get_orifice_type(orifice_l, orifice_id)

    if orifice_type == 'thin':
        return _k_value_thin_sharp_orifice(pipe_id, orifice_id, re)
    elif orifice_type == 'thick':
        return _k_value_thick_orifice(pipe_id, orifice_id, orifice_l, re)
    elif orifice_type == 'oversize':
        return k_value_reduction(pipe_id, orifice_id, q) \
               + k_value_expansion(orifice_id, pipe_id, q)

Calculates the minor loss coefficient of an orifice plate in a
    pipe.

    Parameters:
        pipe_id: Entrance pipe's inner diameter from which fluid flows.
        orifice_id: Orifice's inner diameter.
        orifice_l: Orifice's length from start to end.
        q: Fluid's q rate.

        nu: Fluid's dynamic viscosity of the fluid. Default: room
            temperature water (1 * 10**-6 * m**2/s)

Returns:
        k-value at the orifice.


def parsed_stack(self, value):

        if value == self._defaults['parsedStack'] and 'parsedStack' in self._values:
            del self._values['parsedStack']
        else:
            self._values['parsedStack'] = value

The parsed_stack property.

Args:
        value (list). the property value.


def decode_offset_commit_response(cls, data):

        ((correlation_id,), cur) = relative_unpack('>i', data, 0)
        ((num_topics,), cur) = relative_unpack('>i', data, cur)

        for _ in xrange(num_topics):
            (topic, cur) = read_short_string(data, cur)
            ((num_partitions,), cur) = relative_unpack('>i', data, cur)

            for _ in xrange(num_partitions):
                ((partition, error), cur) = relative_unpack('>ih', data, cur)
                yield OffsetCommitResponse(topic, partition, error)

Decode bytes to an OffsetCommitResponse

Args:
        data: bytes to decode


def regex_check(equation_str):

    match1 = re.match(
        r'^(([xy+\-*/()0-9. ]+|sin\(|cos\(|exp\(|log\()?)+$',
        equation_str
    )
    match2 = re.match(r'^.*([xy]) *([xy]).*$', equation_str)
    if match1 and not match2:
        return True
    raise BadInputError('Cannot parse entered equation')

A quick regular expression check to see that the input is sane

Args:
        equation_str (str): String of equation to be parsed by sympify
        function. Expected to be valid Python.

Raises:
        BadInputError: If input does not look safe to parse as an equation.


def replace_urls(status):

    text = status.text

    if not has_url(status):
        return text

    urls = [(e['indices'], e['expanded_url']) for e in status.entities['urls']]
    urls.sort(key=lambda x: x[0][0], reverse=True)

    for (start, end), url in urls:
        text = text[:start] + url + text[end:]

    return text

Replace shorturls in a status with expanded urls.

Args:
        status (tweepy.status): A tweepy status object

Returns:
        str


def save(self, wf_state):

        self.wf_state = wf_state
        self.wf_state['role_id'] = self.current.role_id
        self.set(self.wf_state)
        if self.wf_state['name'] not in settings.EPHEMERAL_WORKFLOWS:
            self.publish(job='_zops_sync_wf_cache',
                         token=self.db_key)

write wf state to DB through MQ >> Worker >> _zops_sync_wf_cache

Args:
        wf_state dict: wf state


def GetYearFromPosixTime(posix_time, timezone=pytz.UTC):

  datetime_object = datetime.datetime.fromtimestamp(posix_time, tz=timezone)
  return datetime_object.year

Gets the year from a POSIX timestamp

    The POSIX time is the number of seconds since 1970-01-01 00:00:00 UTC.

Args:
        posix_time: An integer containing the number of seconds since
                1970-01-01 00:00:00 UTC.
        timezone: Optional timezone of the POSIX timestamp.

Returns:
        The year of the POSIX timestamp.

Raises:
        ValueError: If the posix timestamp is out of the range of supported values.


def remove(self, layers):

        if not isinstance(layers, list):
            layers = [layers]
        for l in layers:
            if isinstance(l, string_types):
                if l not in self.layers:
                    raise ValueError("There's no image/layer named '%s' in "
                                     "the masking stack!" % l)
                self.stack.remove(l)
            else:
                l = self.stack.pop(l)
            del self.layers[l]

        self.set_mask()

Remove one or more layers from the stack of masking layers.

Args:
        layers: An int, string or list of strings and/or ints. Ints are
            interpreted as indices in the stack to remove; strings are
            interpreted as names of layers to remove. Negative ints will
            also work--i.e., remove(-1) will drop the last layer added.


def kill_raylet_monitor(self, check_alive=True):

        self._kill_process_type(
            ray_constants.PROCESS_TYPE_RAYLET_MONITOR, check_alive=check_alive)

Kill the raylet monitor.

Args:
        check_alive (bool): Raise an exception if the process was already
            dead.


def get_ieee_rotation(structure, refine_rotation=True):

        # Check conventional setting:
        sga = SpacegroupAnalyzer(structure)
        dataset = sga.get_symmetry_dataset()
        trans_mat = dataset['transformation_matrix']
        conv_latt = Lattice(np.transpose(np.dot(np.transpose(
            structure.lattice.matrix), np.linalg.inv(trans_mat))))
        xtal_sys = sga.get_crystal_system()

        vecs = conv_latt.matrix
        lengths = np.array(conv_latt.abc)
        angles = np.array(conv_latt.angles)
        rotation = np.zeros((3, 3))

        # IEEE rules: a,b,c || x1,x2,x3
        if xtal_sys == "cubic":
            rotation = [vecs[i] / lengths[i] for i in range(3)]

        # IEEE rules: a=b in length; c,a || x3, x1
        elif xtal_sys == "tetragonal":
            rotation = np.array([vec / mag for (mag, vec) in
                                 sorted(zip(lengths, vecs),
                                        key=lambda x: x[0])])
            if abs(lengths[2] - lengths[1]) < abs(lengths[1] - lengths[0]):
                rotation[0], rotation[2] = rotation[2], rotation[0].copy()
            rotation[1] = get_uvec(np.cross(rotation[2], rotation[0]))

        # IEEE rules: c<a<b; c,a || x3,x1
        elif xtal_sys == "orthorhombic":
            rotation = [vec / mag for (mag, vec) in sorted(zip(lengths, vecs))]
            rotation = np.roll(rotation, 2, axis=0)

        # IEEE rules: c,a || x3,x1, c is threefold axis
        # Note this also includes rhombohedral crystal systems
        elif xtal_sys in ("trigonal", "hexagonal"):
            # find threefold axis:
            tf_index = np.argmin(abs(angles - 120.))
            non_tf_mask = np.logical_not(angles == angles[tf_index])
            rotation[2] = get_uvec(vecs[tf_index])
            rotation[0] = get_uvec(vecs[non_tf_mask][0])
            rotation[1] = get_uvec(np.cross(rotation[2], rotation[0]))

        # IEEE rules: b,c || x2,x3; alpha=beta=90, c<a
        elif xtal_sys == "monoclinic":
            # Find unique axis
            u_index = np.argmax(abs(angles - 90.))
            n_umask = np.logical_not(angles == angles[u_index])
            rotation[1] = get_uvec(vecs[u_index])
            # Shorter of remaining lattice vectors for c axis
            c = [vec / mag for (mag, vec) in
                 sorted(zip(lengths[n_umask], vecs[n_umask]))][0]
            rotation[2] = np.array(c)
            rotation[0] = np.cross(rotation[1], rotation[2])

        # IEEE rules: c || x3, x2 normal to ac plane
        elif xtal_sys == "triclinic":
            rotation = [vec / mag for (mag, vec) in sorted(zip(lengths, vecs))]
            rotation[1] = get_uvec(np.cross(rotation[2], rotation[0]))
            rotation[0] = np.cross(rotation[1], rotation[2])

        rotation = SquareTensor(rotation)
        if refine_rotation:
            rotation = rotation.refine_rotation()

        return rotation

Given a structure associated with a tensor, determines
    the rotation matrix for IEEE conversion according to
    the 1987 IEEE standards.

Args:
        structure (Structure): a structure associated with the
            tensor to be converted to the IEEE standard
        refine_rotation (bool): whether to refine the rotation
            using SquareTensor.refine_rotation


def call(self, method, params, callback=None):

        cur_id = self._next_id()
        if callback:
            self._callbacks[cur_id] = callback
        self.send({'msg': 'method', 'id': cur_id, 'method': method, 'params': params})

Call a method on the server

Args:
    method - the remote server method
    params - an array of commands to send to the method

    Keyword Arguments:
    callback - a callback function containing the return data


def migrate_tasks_to_internal(self, kill_event):

        logger.info("[TASK_PULL_THREAD] Starting")
        task_counter = 0
        poller = zmq.Poller()
        poller.register(self.task_incoming, zmq.POLLIN)

        while not kill_event.is_set():
            try:
                msg = self.task_incoming.recv_pyobj()
            except zmq.Again:
                # We just timed out while attempting to receive
                logger.debug("[TASK_PULL_THREAD] {} tasks in internal queue".format(self.pending_task_queue.qsize()))
                continue

            if msg == 'STOP':
                kill_event.set()
                break
            else:
                self.pending_task_queue.put(msg)
                task_counter += 1
                logger.debug("[TASK_PULL_THREAD] Fetched task:{}".format(task_counter))

Pull tasks from the incoming tasks 0mq pipe onto the internal
    pending task queue

    Parameters:
    -----------
    kill_event : threading.Event
        Event to let the thread know when it is time to die.


def _parse_normalization(normalization):

        parsed_normalization = None

        if isinstance(normalization, dict):
            if len(normalization.keys()) == 1:
                items = list(normalization.items())[0]
                if len(items) == 2: # Two elements tuple
                    # Convert to string if no normalization options
                    if items[1] and isinstance(items[1], dict):
                        parsed_normalization = items
                    else:
                        parsed_normalization = items[0]
        elif isinstance(normalization, STR_TYPE):
            parsed_normalization = normalization

        return parsed_normalization

Parse a normalization item.

    Transform dicts into a tuple containing the normalization
    options. If a string is found, the actual value is used.

Args:
        normalization: Normalization to parse.

Returns:
        Tuple or string containing the parsed normalization.


def splitsDF(symbol, timeframe='ytd', token='', version=''):

    s = splits(symbol, timeframe, token, version)
    df = _splitsToDF(s)
    return df

Stock split history

    https://iexcloud.io/docs/api/#splits
    Updated at 9am UTC every day

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

Returns:
        DataFrame: result


def insert(self, **fields):

        if self.conflict_target or self.conflict_action:
            compiler = self._build_insert_compiler([fields])
            rows = compiler.execute_sql(return_id=True)

            pk_field_name = self.model._meta.pk.name
            return rows[0][pk_field_name]

        # no special action required, use the standard Django create(..)
        return super().create(**fields).pk

Creates a new record in the database.

    This allows specifying custom conflict behavior using .on_conflict().
    If no special behavior was specified, this uses the normal Django create(..)

Args:
        fields:
            The fields of the row to create.

Returns:
        The primary key of the record that was created.


def set_db_row(db, start, size, _bytearray):

    client.db_write(db, start, size, _bytearray)

Here we replace a piece of data in a db block with new data

Args:
        db (int): The db to use
        start(int): The start within the db
        size(int): The size of the data in bytes
        _butearray (enumerable): The data to put in the db


def stringify(self, use_bytes=False):

        def _str_value(value):
            if isinstance(value, (list, tuple)):
                value = (self.EOL + '\t').join(map(_str_value, value))
            elif callable(value):
                value = _str_value(value())
            return value

        s = self.EOL.join(("{key}: {value}".format(key=key,
                                                   value=_str_value(value))
                           for key, value in self._header_data.values()
                           if value is not None))
        return s + (self.EOL * 2)

Returns representation of headers as a valid HTTP header string. This
    is called by __str__.

Args:
        use_bytes (bool): Returns a bytes object instead of a str.


def _other_wrapper(self, name, writing):

        io_attr = getattr(self._io, name)

        def other_wrapper(*args, **kwargs):

            write_seek = self._io.tell()
            ret_value = io_attr(*args, **kwargs)
            if write_seek != self._io.tell():
                self._read_seek = self._io.tell()
                self._read_whence = 0
            if not writing or not IS_PY2:
                return ret_value

        return other_wrapper

Wrap a stream attribute in an other_wrapper.

Args:
        name: the name of the stream attribute to wrap.

Returns:
        other_wrapper which is described below.


def _RunOsLoginControl(self, params):

    try:
      return subprocess.call([constants.OSLOGIN_CONTROL_SCRIPT] + params)
    except OSError as e:
      if e.errno == errno.ENOENT:
        return None
      else:
        raise

Run the OS Login control script.

Args:
        params: list, the params to pass to the script

Returns:
        int, the return code from the call, or None if the script is not found.


def drop_vocab(self, vocab_name, **kwargs):

        vocab_dict = self.__get_vocab_dict__(vocab_name, **kwargs)
        return self.drop_file(vocab_dict['filename'], **kwargs)

Removes the vocab from the definiton triplestore

Args:
        vocab_name: the name or uri of the vocab to return


def get_dict_to_print(field_to_obs):

  def compressed_steps(steps):
    return {'num_steps': len(set(steps)),
            'min_step': min(steps),
            'max_step': max(steps),
            'last_step': steps[-1],
            'first_step': steps[0],
            'outoforder_steps': get_out_of_order(steps)}

  def full_steps(steps):
    return {'steps': steps, 'outoforder_steps': get_out_of_order(steps)}

  output = {}
  for field, observations in field_to_obs.items():
    if not observations:
      output[field] = None
      continue

    steps = [x['step'] for x in observations]
    if field in SHORT_FIELDS:
      output[field] = compressed_steps(steps)
    if field in LONG_FIELDS:
      output[field] = full_steps(steps)

  return output

Transform the field-to-obs mapping into a printable dictionary.

Args:
        field_to_obs: Dict that maps string field to `Observation` list.

Returns:
        A dict with the keys and values to print to console.


def delete_ldap_group_link(self, cn, provider=None, **kwargs):

        path = '/groups/%s/ldap_group_links' % self.get_id()
        if provider is not None:
            path += '/%s' % provider
        path += '/%s' % cn
        self.manager.gitlab.http_delete(path)

Delete an LDAP group link.

Args:
        cn (str): CN of the LDAP group
        provider (str): LDAP provider for the LDAP group
        **kwargs: Extra options to send to the server (e.g. sudo)

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


def _ReadFloatingPointDataTypeDefinition(
      self, definitions_registry, definition_values, definition_name,
      is_member=False):

    return self._ReadFixedSizeDataTypeDefinition(
        definitions_registry, definition_values,
        data_types.FloatingPointDefinition, definition_name,
        self._SUPPORTED_ATTRIBUTES_FIXED_SIZE_DATA_TYPE,
        is_member=is_member, supported_size_values=(4, 8))

Reads a floating-point data type definition.

Args:
        definitions_registry (DataTypeDefinitionsRegistry): data type definitions
        registry.
        definition_values (dict[str, object]): definition values.
        definition_name (str): name of the definition.
        is_member (Optional[bool]): True if the data type definition is a member
        data type definition.

Returns:
        FloatingPointDefinition: floating-point data type definition.


def start_local_nameserver(host=None, port=0, nic_name=None):

	if host is None:
		if nic_name is None:
			host = 'localhost'
		else:
			host = nic_name_to_host(nic_name)

	uri, ns, _ = Pyro4.naming.startNS(host=host, port=port)
	host, port = ns.locationStr.split(':')

	thread = threading.Thread(target=ns.requestLoop, name='Pyro4 nameserver started by HpBandSter')
	thread.daemon=True

	thread.start()
	return(host, int(port))

starts a Pyro4 nameserver in a daemon thread

    Parameters:
    -----------
    host: str
        the hostname to use for the nameserver
    port: int
        the port to be used. Default =0 means a random port
    nic_name: str
        name of the network interface to use

Returns:
    --------
    tuple (str, int):
        the host name and the used port


def write(path, pid, timestamp):

        with open(path, "w") as lockfile:
            print(pid, timestamp, file=lockfile)

Write the contents of a LockFile.

Args:
        path (str): Path to lockfile.
        pid (int): The integer process ID.
        timestamp (datetime): The time the lock was aquired.


def error_wrapper(fn, error_class):  # type: (Callable or None, Exception) -> ...

    def wrapper(*args, **kwargs):
        try:
            return fn(*args, **kwargs)
        except Exception as e:
            six.reraise(error_class, error_class(e), sys.exc_info()[2])

    return wrapper

Wraps function fn in a try catch block that re-raises error_class.

Args:
        fn (function): function to wrapped
        error_class (Exception): Error class to be re-raised

Returns:
        (object): fn wrapped in a try catch.


def _format_field_name(self, field_name) -> str:

        field = self._get_model_field(field_name)
        return self.qn(field.column)

Formats a field's name for usage in SQL.

Args:
        field_name:
            The field name to format.

Returns:
        The specified field name formatted for
        usage in SQL.


def associate_blocks(blocks, layout_pairs, start_peb_num):

    seq_blocks = []
    for layout_pair in layout_pairs:
        seq_blocks = sort.by_image_seq(blocks, blocks[layout_pair[0]].ec_hdr.image_seq)

        layout_pair.append(seq_blocks)

    return layout_pairs

Group block indexes with appropriate layout pairs

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

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


def run(self, args):

        jlink = self.create_jlink(args)
        if args.product:
            print('Product: %s' % jlink.product_name)

            manufacturer = 'SEGGER' if jlink.oem is None else jlink.oem
            print('Manufacturer: %s' % manufacturer)

            print('Hardware Version: %s' % jlink.hardware_version)
            print('Firmware: %s' % jlink.firmware_version)
            print('DLL Version: %s' % jlink.version)
            print('Features: %s' % ', '.join(jlink.features))
        elif args.jtag:
            status = jlink.hardware_status
            print('TCK Pin Status: %d' % status.tck)
            print('TDI Pin Status: %d' % status.tdi)
            print('TDO Pin Status: %d' % status.tdo)
            print('TMS Pin Status: %d' % status.tms)
            print('TRES Pin Status: %d' % status.tres)
            print('TRST Pin Status: %d' % status.trst)

Runs the information command.

Args:
        self (InfoCommand): the ``InfoCommand`` instance
        args (Namespace): the arguments passed on the command-line

Returns:
        ``None``


def l1_loss(tensor, weight=1.0, scope=None):

  with tf.name_scope(scope, 'L1Loss', [tensor]):
    weight = tf.convert_to_tensor(weight,
                                  dtype=tensor.dtype.base_dtype,
                                  name='loss_weight')
    loss = tf.multiply(weight, tf.reduce_sum(tf.abs(tensor)), name='value')
    tf.add_to_collection(LOSSES_COLLECTION, loss)
    return loss

Define a L1Loss, useful for regularize, i.e. lasso.

Args:
        tensor: tensor to regularize.
        weight: scale the loss by this factor.
        scope: Optional scope for name_scope.

Returns:
        the L1 loss op.


def __new__(cls, obj=None, prop=None, func=None):

        new = super(SinonBase, cls).__new__(cls)
        if func:
            new.__init__(obj, prop, func)
        else:
            new.__init__(obj, prop)
        cls._queue.append(new)
        return weakref.proxy(new)

Constructor of SinonBase
    It will new true base but return a proxy of weakref and store it in _queue

Args:
        obj: None / function / instance method / module / class
            Inspected target
        prop: None / string
            Inspected target when obj contains callable things
        func: function / instance method
            ONLY used by stub, it will replace original target

Returns:
        weakref


def __init__(self, callback):

        super(Interface, self).__init__(callback)
        self._mac_address_table = brocade_mac_address_table(
            callback=pynos.utilities.return_xml
        )

Interface init function.

Args:
        callback: Callback function that will be called for each action.

Returns:
        Interface Object

Raises:
        None


def podcasts_iter(self, *, device_id=None, page_size=250):

		if device_id is None:
			device_id = self.device_id

		start_token = None
		prev_items = None

		while True:
			response = self._call(
				mc_calls.PodcastSeries,
				device_id,
				max_results=page_size,
				start_token=start_token
			)
			items = response.body.get('data', {}).get('items', [])

			# Google does some weird shit.
			if items != prev_items:
				subscribed_podcasts = [
					item
					for item in items
					if item.get('userPreferences', {}).get('subscribed')
				]

				yield subscribed_podcasts

				prev_items = items
			else:
				break

			start_token = response.body.get('nextPageToken')
			if start_token is None:
				break

Get a paged iterator of subscribed podcast series.

    Parameters:
    device_id (str, Optional): A mobile device ID.
        Default: Use ``device_id`` of the :class:`MobileClient` instance.
    page_size (int, Optional): The maximum number of results per returned page.
        Max allowed is ``49995``.
        Default: ``250``

Yields:
    list: Podcast series dicts.


def PushTask(self, task):

    storage_file_size = getattr(task, 'storage_file_size', None)
    if not storage_file_size:
      raise ValueError('Task storage file size not set.')

    if task.file_entry_type == dfvfs_definitions.FILE_ENTRY_TYPE_DIRECTORY:
      weight = 1
    else:
      weight = storage_file_size

    task.merge_priority = weight

    heap_values = (weight, task)
    heapq.heappush(self._heap, heap_values)
    self._task_identifiers.add(task.identifier)

Pushes a task onto the heap.

Args:
        task (Task): task.

Raises:
        ValueError: if the size of the storage file is not set in the task.


def findall_operations_with_gate_type(
            self,
            gate_type: Type[T_DESIRED_GATE_TYPE]
    ) -> Iterable[Tuple[int,
                        ops.GateOperation,
                        T_DESIRED_GATE_TYPE]]:

        result = self.findall_operations(lambda operation: bool(
            ops.op_gate_of_type(operation, gate_type)))
        for index, op in result:
            gate_op = cast(ops.GateOperation, op)
            yield index, gate_op, cast(T_DESIRED_GATE_TYPE, gate_op.gate)

Find the locations of all gate operations of a given type.

Args:
        gate_type: The type of gate to find, e.g. XPowGate or
            MeasurementGate.

Returns:
        An iterator (index, operation, gate)'s for operations with the given
        gate type.


def __init__(self, outputdir, os_name, os_bits):

        if type(self) == Basedriver:
            raise Exception('Basedriver cannot be instantiated')
        self.outputdir = outputdir
        self.os_name = os_name
        self.os_bits = os_bits

Instantiate a new webdriver class

Args:
        outputdir:    The path to the directory to use.
        os_name:      Valid options: ['windows', 'linux', 'mac']
        os_bits:      Valid options: ['32', '64']


def _WriteRow(self, output_writer, values):

    maximum_row_width = self._MAXIMUM_WIDTH - self._column_width - 3

    # The format string of the first line of the column value.
    primary_format_string = '{{0:>{0:d}s}} : {{1:s}}\n'.format(
        self._column_width)

    # The format string of successive lines of the column value.
    secondary_format_string = '{{0:<{0:d}s}}{{1:s}}\n'.format(
        self._column_width + 3)

    if isinstance(values[1], py2to3.STRING_TYPES):
      value_string = values[1]
    else:
      value_string = '{0!s}'.format(values[1])

    if len(value_string) < maximum_row_width:
      output_writer.Write(primary_format_string.format(
          values[0], value_string))
      return

    # Split the column value in words.
    words = value_string.split()

    current = 0

    lines = []
    word_buffer = []
    for word in words:
      current += len(word) + 1
      if current >= maximum_row_width:
        current = len(word)
        lines.append(' '.join(word_buffer))
        word_buffer = [word]
      else:
        word_buffer.append(word)
    lines.append(' '.join(word_buffer))

    # Split the column value across multiple lines.
    output_writer.Write(
        primary_format_string.format(values[0], lines[0]))
    for line in lines[1:]:
      output_writer.Write(secondary_format_string.format('', line))

Writes a row of values aligned to the column width.

Args:
        output_writer (OutputWriter): output writer.
        values (list[object]): values.


def truncate(text, max_len=350, end='...'):

    if len(text) <= max_len:
        return text
    return text[:max_len].rsplit(' ', maxsplit=1)[0] + end

Truncate the supplied text for display.

Args:
        text (:py:class:`str`): The text to truncate.
        max_len (:py:class:`int`, optional): The maximum length of the
        text before truncation (defaults to 350 characters).
        end (:py:class:`str`, optional): The ending to use to show that
        the text was truncated (defaults to ``'...'``).

Returns:
        :py:class:`str`: The truncated text.


def get_class_members(self, cls_name, cls):

    for name, member in inspect.getmembers(cls):
      # Only show methods and properties presently.  In Python 3,
      # methods register as isfunction.
      is_method = inspect.ismethod(member) or inspect.isfunction(member)
      if not (is_method or isinstance(member, property)):
        continue
      if ((is_method and member.__name__ == "__init__")
          or self._should_include_member(name, member)):
        yield name, ("%s.%s" % (cls_name, name), member)

Returns the list of class members to document in `cls`.

    This function filters the class member to ONLY return those
    defined by the class.  It drops the inherited ones.

Args:
        cls_name: Qualified name of `cls`.
        cls: An inspect object of type 'class'.

Yields:
        name, member tuples.


def default(self, value):

        if isinstance(value, messages.Enum):
            return str(value)

        if six.PY3 and isinstance(value, bytes):
            return value.decode('utf8')

        if isinstance(value, messages.Message):
            result = {}
            for field in value.all_fields():
                item = value.get_assigned_value(field.name)
                if item not in (None, [], ()):
                    result[field.name] = (
                        self.__protojson_protocol.encode_field(field, item))
            # Handle unrecognized fields, so they're included when a message is
            # decoded then encoded.
            for unknown_key in value.all_unrecognized_fields():
                unrecognized_field, _ = value.get_unrecognized_field_info(
                    unknown_key)
                # Unknown fields are not encoded as they should have been
                # processed before we get to here.
                result[unknown_key] = unrecognized_field
            return result

        return super(MessageJSONEncoder, self).default(value)

Return dictionary instance from a message object.

Args:
    value: Value to get dictionary for.  If not encodable, will
        call superclasses default method.


def add_arguments(cls, parser):

        parser.add_argument(
            '-c', '--create-missing-tasks',
            action='store_true',
            dest='create_missing_tasks',
            help="[sync] create asana tasks for issues without tasks"
            )

        parser.add_argument(
            '-l', '--sync-labels',
            action='store_true',
            dest='sync_labels',
            help="[sync] sync labels and milestones for each issue"
            )

Add arguments to the parser for collection in app.args.

Args:
        parser:
            `argparse.ArgumentParser`. Parser.
            Arguments added here are server on
            self.args.


def _identify_eds_ing(first, second):

        A = set([first.L, first.R])
        A.update(first.D)

        B = set([second.L, second.R])
        B.update(second.D)

        depend_set = A & B
        left, right = sorted(list(A ^ B))

        return left, right, depend_set

Find nodes connecting adjacent edges.

Args:
        first(Edge): Edge object representing the first edge.
        second(Edge): Edge object representing the second edge.

Returns:
        tuple[int, int, set[int]]: The first two values represent left and right node
            indicies of the new edge. The third value is the new dependence set.


def optimize_boolean_expression_comparisons(ir_blocks):

    operator_inverses = {
        u'=': u'!=',
        u'!=': u'=',
    }

    def visitor_fn(expression):

        if not isinstance(expression, BinaryComposition):
            return expression

        left_is_binary_composition = isinstance(expression.left, BinaryComposition)
        right_is_binary_composition = isinstance(expression.right, BinaryComposition)

        if not left_is_binary_composition and not right_is_binary_composition:
            # Nothing to rewrite, return the expression as-is.
            return expression

        identity_literal = None  # The boolean literal for which we just use the inner expression.
        inverse_literal = None  # The boolean literal for which we negate the inner expression.
        if expression.operator == u'=':
            identity_literal = TrueLiteral
            inverse_literal = FalseLiteral
        elif expression.operator == u'!=':
            identity_literal = FalseLiteral
            inverse_literal = TrueLiteral
        else:
            return expression

        expression_to_rewrite = None
        if expression.left == identity_literal and right_is_binary_composition:
            return expression.right
        elif expression.right == identity_literal and left_is_binary_composition:
            return expression.left
        elif expression.left == inverse_literal and right_is_binary_composition:
            expression_to_rewrite = expression.right
        elif expression.right == inverse_literal and left_is_binary_composition:
            expression_to_rewrite = expression.left

        if expression_to_rewrite is None:
            # We couldn't find anything to rewrite, return the expression as-is.
            return expression
        elif expression_to_rewrite.operator not in operator_inverses:
            # We can't rewrite the inner expression since we don't know its inverse operator.
            return expression
        else:
            return BinaryComposition(
                operator_inverses[expression_to_rewrite.operator],
                expression_to_rewrite.left,
                expression_to_rewrite.right)

    new_ir_blocks = []
    for block in ir_blocks:
        new_block = block.visit_and_update_expressions(visitor_fn)
        new_ir_blocks.append(new_block)

    return new_ir_blocks

Optimize comparisons of a boolean binary comparison expression against a boolean literal.

    Rewriting example:
        BinaryComposition(
            '=',
            BinaryComposition('!=', something, NullLiteral)
            False)

    The above is rewritten into:
        BinaryComposition('=', something, NullLiteral)

Args:
        ir_blocks: list of basic block objects

Returns:
        a new list of basic block objects, with the optimization applied


def setup_data_stream(
            self,
            connection_factory: Callable[[tuple], Connection],
            data_stream_factory: Callable[[Connection], DataStream]=DataStream) -> \
            DataStream:

        yield from self._control_stream.write_command(Command('TYPE', 'I'))
        reply = yield from self._control_stream.read_reply()

        self.raise_if_not_match('Binary mode', ReplyCodes.command_okay, reply)

        address = yield from self.passive_mode()

        connection = yield from connection_factory(address)

        # TODO: unit test for following line for connections that have
        # the same port over time but within pool cleaning intervals
        connection.reset()

        yield from connection.connect()

        data_stream = data_stream_factory(connection)

        return data_stream

Create and setup a data stream.

    This function will set up passive and binary mode and handle
    connecting to the data connection.

Args:
        connection_factory: A coroutine callback that returns a connection
        data_stream_factory: A callback that returns a data stream

    Coroutine.

Returns:
        DataStream


def __init__(self, tag, ID, actual, expected):

        self.tag = tag
        self.ID = ID
        self.actual = actual
        self.expected = expected
        super(ConsistencyError, self).__init__("INCONSISTENCY in %s ID '%s': text results '%s' != concatenated '%s'" % (tag, ID, actual, expected))

Construct a new ConsistencyError.

Args:
        tag (string): Level of the inconsistent element
        ID (string): ``ID`` of the inconsistent element
        actual (string):
        expected (string):


def export_warnings(self, export_file):

        warn_filepath = op.dirname(export_file)
        warn_filename = op.splitext(op.basename(export_file))[0]
        self._add_entry(templates.EXPORT_WARNINGS
                                 .format(warnings_export_path=warn_filepath,
                                         warnings_export_file=warn_filename))

Append an export warnings entry to the journal.

    This instructs Revit to export warnings from the opened model.
    Currently Revit will stop journal execution if the model does not
    have any warnings and the export warnings UI button is disabled.

Args:
        export_file (str): full path of the ouput html file


def _send_json(self, method, path, data):

        headers = {'Content-type': 'application/json'}
        return self._make_request(method, path, data=data, headers=headers)

Make a application/json request.

Args:
        `method`: The method of the request (POST or PUT).
        `path`: The path to the resource.
        `data`: The JSON-encoded data.

Returns:
        The content of the response.

Raises:
        An exception depending on the HTTP status code of the response.


def ne(self, other, axis="columns", level=None):

        return self._binary_op("ne", other, axis=axis, level=level)

Checks element-wise that this is not equal to other.

Args:
        other: A DataFrame or Series or scalar to compare to.
        axis: The axis to perform the ne over.
        level: The Multilevel index level to apply ne over.

Returns:
        A new DataFrame filled with Booleans.


def compute_samples_displays(
            self,
            program: Union[circuits.Circuit, schedules.Schedule],
            param_resolver: 'study.ParamResolverOrSimilarType' = None,
    ) -> study.ComputeDisplaysResult:

        return self.compute_samples_displays_sweep(
            program,
            study.ParamResolver(param_resolver))[0]

Computes SamplesDisplays in the supplied Circuit or Schedule.

Args:
        program: The circuit or schedule to simulate.
        param_resolver: Parameters to run with the program.

Returns:
        ComputeDisplaysResult for the simulation.


def _ParseFileHeader(self, file_object):

    file_header_map = self._GetDataTypeMap(
        'chrome_cache_data_block_file_header')

    try:
      file_header, _ = self._ReadStructureFromFileObject(
          file_object, 0, file_header_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.ParseError(
          'Unable to parse data block file header with error: {0!s}'.format(
              exception))

    if file_header.signature != self._FILE_SIGNATURE:
      raise errors.ParseError('Unsupported data block file signature')

    format_version = '{0:d}.{1:d}'.format(
        file_header.major_version, file_header.minor_version)
    if format_version not in ('2.0', '2.1'):
      raise errors.ParseError(
          'Unsupported data block file format version: {0:s}'.format(
              format_version))

    if file_header.block_size not in (256, 1024, 4096):
      raise errors.ParseError(
          'Unsupported data block file block size: {0:d}'.format(
              file_header.block_size))

Parses the file header.

Args:
        file_object (dfvfs.FileIO): a file-like object to parse.

Raises:
        ParseError: if the file header cannot be read.


def put(self, url, params=None, data=None, files=None, **kwargs):

        return self.call_api(
            "PUT",
            url,
            params=params,
            data=data,
            files=files,
            **kwargs
        )

Call the API with a PUT request.

Args:
        url (str): Resource location relative to the base URL.
        params (dict or None): Query-string parameters.
        data (dict or None): Request body contents.
        files (dict or None: Files to be passed to the request.

Returns:
        An instance of ResultParser or ErrorParser.


def substitute(expr, var_map):

    try:
        if isinstance(expr, SympyBasic):
            sympy_var_map = {
                k: v for (k, v) in var_map.items()
                if isinstance(k, SympyBasic)}
            return expr.subs(sympy_var_map)
        else:
            return expr.substitute(var_map)
    except AttributeError:
        if expr in var_map:
            return var_map[expr]
        return expr

Substitute symbols or (sub-)expressions with the given replacements and
    re-evalute the result

Args:
        expr: The expression in which to perform the substitution
        var_map (dict): The substitution dictionary.


def ParseIfaddrs(ifaddrs):

  precondition.AssertOptionalType(ifaddrs, ctypes.POINTER(Ifaddrs))

  ifaces = {}

  for ifaddr in IterIfaddrs(ifaddrs):
    ifname = ctypes.string_at(ifaddr.ifa_name).decode("utf-8")
    iface = ifaces.setdefault(ifname, rdf_client_network.Interface())
    iface.ifname = ifname

    if not ifaddr.ifa_addr:
      continue

    sockaddr = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddr))
    iffamily = sockaddr.contents.sa_family
    if iffamily == AF_INET:
      sockaddrin = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrin))

      address = rdf_client_network.NetworkAddress()
      address.address_type = rdf_client_network.NetworkAddress.Family.INET
      address.packed_bytes = struct.pack("=L", sockaddrin.contents.sin_addr)
      iface.addresses.append(address)
    elif iffamily == AF_INET6:
      sockaddrin = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrin6))

      address = rdf_client_network.NetworkAddress()
      address.address_type = rdf_client_network.NetworkAddress.Family.INET6
      address.packed_bytes = bytes(list(sockaddrin.contents.sin6_addr))
      iface.addresses.append(address)
    elif iffamily == AF_LINK:
      sockaddrdl = ctypes.cast(ifaddr.ifa_addr, ctypes.POINTER(Sockaddrdl))

      nlen = sockaddrdl.contents.sdl_nlen
      alen = sockaddrdl.contents.sdl_alen
      iface.mac_address = bytes(sockaddrdl.contents.sdl_data[nlen:nlen + alen])
    else:
      raise ValueError("Unexpected socket address family: %s" % iffamily)

  return itervalues(ifaces)

Parses contents of the intrusive linked list of `ifaddrs`.

Args:
        ifaddrs: A pointer to the first node of `ifaddrs` linked list. Can be NULL.

Returns:
        An iterator over instances of `rdf_client_network.Interface`.


def parse(self, rrstr):
        # type: (bytes) -> None

        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('SL record already initialized!')

        (su_len, su_entry_version_unused, self.flags) = struct.unpack_from('=BBB', rrstr[:5], 2)

        # We assume that the caller has already checked the su_entry_version,
        # so we don't bother.

        cr_offset = 5
        data_len = su_len - 5
        while data_len > 0:
            (cr_flags, len_cp) = struct.unpack_from('=BB', rrstr[:cr_offset + 2], cr_offset)

            data_len -= 2
            cr_offset += 2

            self.symlink_components.append(self.Component(cr_flags, len_cp,
                                                          rrstr[cr_offset:cr_offset + len_cp]))

            # FIXME: if this is the last component in this SL record,
            # but the component continues on in the next SL record, we will
            # fail to record this bit.  We should fix that.

            cr_offset += len_cp
            data_len -= len_cp

        self._initialized = True

Parse a Rock Ridge Symbolic Link record out of a string.

    Parameters:
    rrstr - The string to parse the record out of.

Returns:
    Nothing.


def is_list_of_matching_dicts(list_of_dicts, expected_keys=None):

    if isinstance(list_of_dicts, list) and len(list_of_dicts) == 0:
        return False

    is_not_list_msg = .format(list_of_dicts)
    assert isinstance(list_of_dicts, list), is_not_list_msg

    not_all_dicts_msg = .format(list_of_dicts)
    assert all([isinstance(d, dict) for d in list_of_dicts]), not_all_dicts_msg

    # Si no se pasan expected_keys, se las toma del primer diccionario
    expected_keys = expected_keys or set(list_of_dicts[0].keys())

    elements = [set(d.keys()) == expected_keys for d in list_of_dicts]

    return all(elements)

Comprueba que una lista esté compuesta únicamente por diccionarios,
    que comparten exactamente las mismas claves.

Args:
        list_of_dicts (list): Lista de diccionarios a comparar.
        expected_keys (set): Conjunto de las claves que cada diccionario debe
            tener. Si no se incluye, se asume que son las claves del primer
            diccionario de la lista.

Returns:
        bool: True si todos los diccionarios comparten sus claves.


def _piecewise_learning_rate(step, boundaries, values):

  values = [1.0] + values
  boundaries = [float(x) for x in boundaries]
  return tf.train.piecewise_constant(
      step, boundaries, values, name="piecewise_lr")

Scale learning rate according to the given schedule.

    Multipliers are not cumulative.

Args:
        step: global step
        boundaries: List of steps to transition on.
        values: Multiplier to apply at each boundary transition.

Returns:
        Scaled value for the learning rate.


def remove_object_from_list(self, obj, list_element):

        list_element = self._handle_location(list_element)

        if isinstance(obj, JSSObject):
            results = [item for item in list_element.getchildren() if
                       item.findtext("id") == obj.id]
        elif isinstance(obj, (int, basestring)):
            results = [item for item in list_element.getchildren() if
                       item.findtext("id") == str(obj) or
                       item.findtext("name") == obj]

        if len(results) == 1:
            list_element.remove(results[0])
        elif len(results) > 1:
            raise ValueError("There is more than one matching object at that "
                             "path!")

Remove an object from a list element.

Args:
        obj: Accepts JSSObjects, id's, and names
        list_element: Accepts an Element or a string path to that
            element


def clean_video_data(_data):

    data = _data.copy()

    # TODO: fix this ugliness
    title = data.get('title')
    if title:
        data['title'] = clean_title(title)

    return data

Clean video data:
    -> cleans title
    -> ...

Args:
    _data (dict): Information about the video.

Returns:
    dict: Refined video data.


def bool_input(message):

    while True:
        suffix = ' (true or false): '
        inp = input(message + suffix)
        if inp.lower() == 'true':
            return True
        elif inp.lower() == 'false':
            return False
        else:
            print(colored('Must be either true or false, try again!', 'red'))

Ask a user for a boolean input

Args:
        message (str): Prompt for user

Returns:
        bool_in (boolean): Input boolean


def Reference(uri, meaning=None):

    attrib = {'uri': uri}
    if meaning is not None:
        attrib['meaning'] = meaning
    return objectify.Element('Reference', attrib)

Represents external information, typically original obs data and metadata.

Args:
        uri(str): Uniform resource identifier for external data, e.g. FITS file.
        meaning(str): The nature of the document referenced, e.g. what
            instrument and filter was used to create the data?


def GetValueLength(rd, pos):

  rd = bytearray(rd)
  key = rd[pos]
  if key == LONG_ITEM_ENCODING:
    # If the key is tagged as a long item (0xfe), then the format is
    # [key (1 byte)] [data len (1 byte)] [item tag (1 byte)] [data (n # bytes)].
    # Thus, the entire key record is 3 bytes long.
    if pos + 1 < len(rd):
      return (3, rd[pos + 1])
    else:
      raise errors.HidError('Malformed report descriptor')

  else:
    # If the key is tagged as a short item, then the item tag and data len are
    # packed into one byte.  The format is thus:
    # [tag (high 4 bits)] [type (2 bits)] [size code (2 bits)] [data (n bytes)].
    # The size code specifies 1,2, or 4 bytes (0x03 means 4 bytes).
    code = key & 0x03
    if code <= 0x02:
      return (1, code)
    elif code == 0x03:
      return (1, 4)

  raise errors.HidError('Cannot happen')

Get value length for a key in rd.

    For a key at position pos in the Report Descriptor rd, return the length
    of the associated value.  This supports both short and long format
    values.

Args:
        rd: Report Descriptor
        pos: The position of the key in rd.

Returns:
        (key_size, data_len) where key_size is the number of bytes occupied by
        the key and data_len is the length of the value associated by the key.


def __init__(self, resolver_context, file_object=None):

    if file_object:
      raise ValueError('File object value set.')

    super(EWFFile, self).__init__(resolver_context)
    self._file_objects = []

Initializes a file-like object.

Args:
        resolver_context (Context): resolver context.
        file_object (Optional[FileIO]): file-like object.

Raises:
        ValueError: when file_object is set.


def decode(obj, content_type):
    # type: (np.array or Iterable or int or float, str) -> np.array

    try:
        decoder = _decoders_map[content_type]
        return decoder(obj)
    except KeyError:
        raise _errors.UnsupportedFormatError(content_type)

Decode an object ton a one of the default content types to a numpy array.

Args:
        obj (object): to be decoded.
        content_type (str): content type to be used.

Returns:
        np.array: decoded object.


def resetThingStateForLogicalInterface(self, thingTypeId, thingId , logicalInterfaceId):

        req = ApiClient.thingStateUrl % (self.host, "", thingTypeId,thingId , logicalInterfaceId)
        body = {"operation" : "reset-state"}
        resp = requests.patch(req, auth=self.credentials, headers={"Content-Type":"application/json"}, data=json.dumps(body),
               verify=self.verify)
        if (resp.status_code == 200):
            self.logger.debug("Reset ThingState For LogicalInterface succeeded")
        else:
            raise ibmiotf.APIException(resp.status_code, " HTTP error on reset ThingState For LogicalInterface ", resp)
        return resp.json()

Perform an operation against the thing state for a logical interface
    Parameters:
        - thingTypeId (string)
        - thingId (string)
        - logicalInterfaceId (string)
    Throws APIException on failure.