Assert that the contract holds as a precondition.

    :param contract: contract to be verified
    :param resolved_kwargs: resolved keyword arguments (including the default values)
    :return:
357754
def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None:
    
    # Check that all arguments to the condition function have been set.
    missing_args = [arg_name for arg_name in contract.condition_args if arg_name not in resolved_kwargs]
    if missing_args:
        raise TypeError(
            ("The argument(s) of the precondition have not been set: {}. "
             "Does the original function define them? Did you supply them in the call?").format(missing_args))

    condition_kwargs = {
        arg_name: value
        for arg_name, value in resolved_kwargs.items() if arg_name in contract.condition_arg_set
    }

    check = contract.condition(**condition_kwargs)

    if not check:
        if contract.error is not None and (inspect.ismethod(contract.error) or inspect.isfunction(contract.error)):
            assert contract.error_arg_set is not None, "Expected error_arg_set non-None if contract.error a function."
            assert contract.error_args is not None, "Expected error_args non-None if contract.error a function."

            error_kwargs = {
                arg_name: value
                for arg_name, value in resolved_kwargs.items() if arg_name in contract.error_arg_set
            }

            missing_args = [arg_name for arg_name in contract.error_args if arg_name not in resolved_kwargs]
            if missing_args:
                msg_parts = []  # type: List[str]
                if contract.location is not None:
                    msg_parts.append("{}:\n".format(contract.location))

                msg_parts.append(
                    ("The argument(s) of the precondition error have not been set: {}. "
                     "Does the original function define them? Did you supply them in the call?").format(missing_args))

                raise TypeError(''.join(msg_parts))

            raise contract.error(**error_kwargs)

        else:
            msg = icontract._represent.generate_message(contract=contract, condition_kwargs=condition_kwargs)
            if contract.error is None:
                raise ViolationError(msg)
            elif isinstance(contract.error, type):
                raise contract.error(msg)
280073
def cancelMktData(self, contract: Contract):
        
        ticker = self.ticker(contract)
        reqId = self.wrapper.endTicker(ticker, 'mktData')
        if reqId:
            self.client.cancelMktData(reqId)
        else:
            self._logger.error(
                'cancelMktData: ' f'No reqId found for contract {contract}')
239135
def make_validator!(contract)
      klass = contract.class
      key = if validator_strategies.key?(klass)
              klass
            else
              if contract.respond_to? :valid?
                :valid
              elsif klass == Class || klass == Module
                :class
              else
                :default
              end
            end

      validator_strategies[key].call(contract)
    end
217800
def _register_custom_contracts(contract_name, contract_exceptions):
    """"""
    # pylint: disable=W0602,W0603
    global _CUSTOM_CONTRACTS
    # Validate arguments and homogenize contract exceptions
    if not isinstance(contract_name, str):
        raise TypeError("Argument `contract_name` is of the wrong type")
    # A contract exception can be a string (only one exception, default
    # exception type) or a dictionary of exception definitions, if there is
    # more than one or if the type if different than the default
    if (
        (not isinstance(contract_exceptions, list))
        and (not isinstance(contract_exceptions, str))
        and (not isinstance(contract_exceptions, dict))
    ):
        raise TypeError("Argument `contract_exceptions` is of the wrong type")
    if isinstance(contract_exceptions, dict):
        contract_exceptions = [contract_exceptions]
    if isinstance(contract_exceptions, list) and any(
        [
            not isinstance(key, str)
            for item in contract_exceptions
            for key in item.keys()
        ]
    ):
        raise TypeError("Contract exception definition is of the wrong type")
    # Validate individual exception definitions
    if isinstance(contract_exceptions, list) and any(
        [
            not (
                (set(item.keys()) == set(["name", "msg"]))
                or (set(item.keys()) == set(["name", "msg", "type"]))
            )
            for item in contract_exceptions
        ]
    ):
        raise TypeError("Contract exception definition is of the wrong type")
    extype = type(ValueError)
    if isinstance(contract_exceptions, list) and any(
        [
            (not isinstance(item["name"], str))
            or (not isinstance(item["msg"], str))
            or (not isinstance(item.get("type", extype), extype))
            for item in contract_exceptions
        ]
    ):
        raise TypeError("Contract exception definition is of the wrong type")
    # Homogenize exception definitions
    if isinstance(contract_exceptions, list):
        homogenized_exdict = dict(
            (
                exdict["name"],
                {
                    "num": exnum,
                    "msg": exdict["msg"],
                    "type": exdict.get("type", RuntimeError),
                    "field": _get_replacement_token(exdict["msg"]),
                },
            )
            for exnum, exdict in enumerate(contract_exceptions)
        )
    else:
        homogenized_exdict = {
            "default": {
                "num": 0,
                "msg": contract_exceptions,
                "type": RuntimeError,
                "field": _get_replacement_token(contract_exceptions),
            }
        }
    # Verify exception names are unique
    if isinstance(contract_exceptions, list) and (
        len(homogenized_exdict) != len(contract_exceptions)
    ):
        raise ValueError("Contract exception names are not unique")
    # Verify that exception messages are unique
    msgs = [exvalue["msg"] for exvalue in homogenized_exdict.values()]
    if len(set(msgs)) != len(msgs):
        raise ValueError("Contract exception messages are not unique")
    # Verify that a custom contract is not being redefined
    if (contract_name in _CUSTOM_CONTRACTS) and (
        _CUSTOM_CONTRACTS[contract_name] != contract_exceptions
    ):
        raise RuntimeError(
            "Attempt to redefine custom contract `{0}`".format(contract_name)
        )
    # Verify that there are at most only two replacement fields, and one of
    # them should be argument_name
    fields = [
        exdict["field"]
        for exdict in homogenized_exdict.values()
        if exdict["field"] is not None
    ]
    if (len(fields) > 2) or (
        (len(fields) == 2)
        and (fields[0] != "argument_name")
        and (fields[1] != "argument_name")
    ):
        raise ValueError(
            "Multiple replacement fields to be substituted by argument value"
        )
    # Register new contract
    _CUSTOM_CONTRACTS[contract_name] = homogenized_exdict
    return contract_exceptions
1175041
def asserts(self, *args, **kwargs):
        
        result = self.match(*args, **kwargs)
        self.expect(result)
        return result
111847
def gather_verify_arguments(self):
        
        _ctx = self.service_context
        kwargs = {
            'client_id': _ctx.client_id, 'iss': _ctx.issuer,
            'keyjar': _ctx.keyjar, 'verify': True,
            'skew': _ctx.clock_skew
        }

        for attr, param in IDT2REG.items():
            try:
                kwargs[attr] = _ctx.registration_response[param]
            except KeyError:
                pass

        try:
            kwargs['allow_missing_kid'] = self.service_context.allow[
                'missing_kid']
        except KeyError:
            pass

        return kwargs
1110837
def add_query_kwargs(kwargs, visitor, constraints, index):
    
    (query_const, filter_const) = constraints.remove_index(index)
    kwargs["key_condition_expr"] = query_const.build(visitor)
    if filter_const:
        kwargs["filter"] = filter_const.build(visitor)
    if index.name != "TABLE":
        kwargs["index"] = index.name
719336
def verify(self, **kwargs):
        
        _spec = self.c_param
        try:
            _allowed = self.c_allowed_values
        except KeyError:
            _allowed = {}

        for (attribute, (typ, required, _, _, na)) in _spec.items():
            if attribute == "*":
                continue

            try:
                val = self._dict[attribute]
            except KeyError:
                if required:
                    raise MissingRequiredAttribute("%s" % attribute)
                continue
            else:
                if typ == bool:
                    pass
                elif not val:
                    if required:
                        raise MissingRequiredAttribute("%s" % attribute)
                    continue

            try:
                _allowed_val = _allowed[attribute]
            except KeyError:
                pass
            else:
                if not self._type_check(typ, _allowed_val, val, na):
                    raise NotAllowedValue(val)

        return True
503947
def bind(self, args, kwargs):
        
        spec = self._spec
        resolution = self.resolve(args, kwargs)
        params = dict(zip(spec.args, resolution.slots))
        if spec.varargs:
            params[spec.varargs] = resolution.varargs
        if spec.varkw:
            params[spec.varkw] = resolution.varkw
        if spec.kwonlyargs:
            params.update(resolution.kwonlyargs)
        return params
45920
def gather_verify_arguments(self):
        

        kwargs = {'client_id': self.service_context.client_id,
                  'iss': self.service_context.issuer,
                  'keyjar': self.service_context.keyjar,
                  'verify': True}
        return kwargs
428901
def validate_query(self, using=None, **kwargs):
        
        return self._get_connection(using).indices.validate_query(index=self._name, **kwargs)
508061
def infer_declared_from_conditions(conds, namespace=None):
    ''' 
    '''
    conflicts = []
    # If we can't resolve that standard namespace, then we'll look for
    # just bare "declared" caveats which will work OK for legacy
    # macaroons with no namespace.
    if namespace is None:
        namespace = Namespace()
    prefix = namespace.resolve(STD_NAMESPACE)
    if prefix is None:
        prefix = ''
    declared_cond = prefix + COND_DECLARED

    info = {}
    for cond in conds:
        try:
            name, rest = parse_caveat(cond)
        except ValueError:
            name, rest = '', ''
        if name != declared_cond:
            continue
        parts = rest.split(' ', 1)
        if len(parts) != 2:
            continue
        key, val = parts[0], parts[1]
        old_val = info.get(key)
        if old_val is not None and old_val != val:
            conflicts.append(key)
            continue
        info[key] = val
    for key in set(conflicts):
        del info[key]
    return info
966008
def _detect(self):
        
        results = []
        for c in self.contracts:
            for f in c.functions:
                if f.contract != c:
                    continue
                if f.view or f.pure:
                    if f.contains_assembly:
                        attr = 'view' if f.view else 'pure'
                        info = '{}.{} ({}) is declared {} but contains assembly code\n'
                        info = info.format(f.contract.name, f.name, f.source_mapping_str, attr)
                        json = self.generate_json_result(info)
                        self.add_function_to_json(f, json)
                        json['elements'].append({'type': 'info',
                                                 'contains_assembly' : True})
                        results.append(json)

                    variables_written = f.all_state_variables_written()
                    if variables_written:
                        attr = 'view' if f.view else 'pure'
                        info = '{}.{} ({}) is declared {} but changes state variables:\n'
                        info = info.format(f.contract.name, f.name, f.source_mapping_str, attr)
                        for variable_written in variables_written:
                            info += '\t- {}.{}\n'.format(variable_written.contract.name,
                                                         variable_written.name)


                        json = self.generate_json_result(info)
                        self.add_function_to_json(f, json)
                        self.add_variables_to_json(variables_written, json)
                        json['elements'].append({'type': 'info',
                                                  'contains_assembly' : False})
                        results.append(json)

        return results
1157501
public static int checkPostconditionI(
    final int value,
    final ContractIntConditionType condition)
    throws PostconditionViolationException
  {
    return checkPostconditionI(
      value, condition.predicate(), condition.describer());
  }
965412
def conditions(self):
        
        return operatorPrecedence(
            baseExpr=self.condition,
            opList=[(self.not_op, 1, opAssoc.RIGHT),
                    (self.logical_binary_op, 2, opAssoc.LEFT)],
            lpar=self.syntax.paren_left,
            rpar=self.syntax.paren_right)
830314
def accepts=(args)
      if args.last == Block # Transform into a ProcContract
        args.pop
        @block_contract = ProcContract.new
        @block_contract.accepts = ClauseMethods::ANYTHING
        @block_contract.returns = ClauseMethods::ANYTHING        
      elsif args.last.is_a?(ProcContract)
        @block_contract = args.pop
      end

      if args.find_all {|o| o.is_a? Array}.length > 1
        raise ContractError, "Cannot define more than one expected variable argument"
      end
      super(args)
    end
763515
def _format_preconditions(preconditions: List[List[icontract._Contract]], prefix: Optional[str] = None) -> List[str]:
    
    if not preconditions:
        return []

    result = []  # type: List[str]
    for i, group in enumerate(preconditions):
        if i == 0:
            if prefix is not None:
                result.append(":{} requires:".format(prefix))
            else:
                result.append(":requires:")
        else:
            if prefix is not None:
                result.append(":{} requires else:".format(prefix))
            else:
                result.append(":requires else:")

        for precondition in group:
            result.append("    * {}".format(_format_contract(contract=precondition)))

    return result