language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | numpy__numpy | numpy/distutils/tests/test_exec_command.py | {
"start": 1316,
"end": 3357
} | class ____:
"""Context manager to emulate os.name != 'posix' """
def __init__(self, osname='non-posix'):
self._new_name = osname
def __enter__(self):
self._old_name = os.name
os.name = self._new_name
def __exit__(self, exc_type, exc_value, traceback):
os.name = self._old_name
def test_exec_command_stdout():
# Regression test for gh-2999 and gh-2915.
# There are several packages (nose, scipy.weave.inline, Sage inline
# Fortran) that replace stdout, in which case it doesn't have a fileno
# method. This is tested here, with a do-nothing command that fails if the
# presence of fileno() is assumed in exec_command.
# The code has a special case for posix systems, so if we are on posix test
# both that the special case works and that the generic code works.
# Test posix version:
with redirect_stdout(StringIO()):
with redirect_stderr(TemporaryFile()):
with pytest.warns(DeprecationWarning):
exec_command.exec_command("cd '.'")
if os.name == 'posix':
# Test general (non-posix) version:
with emulate_nonposix():
with redirect_stdout(StringIO()):
with redirect_stderr(TemporaryFile()):
with pytest.warns(DeprecationWarning):
exec_command.exec_command("cd '.'")
def test_exec_command_stderr():
# Test posix version:
with redirect_stdout(TemporaryFile(mode='w+')):
with redirect_stderr(StringIO()):
with pytest.warns(DeprecationWarning):
exec_command.exec_command("cd '.'")
if os.name == 'posix':
# Test general (non-posix) version:
with emulate_nonposix():
with redirect_stdout(TemporaryFile()):
with redirect_stderr(StringIO()):
with pytest.warns(DeprecationWarning):
exec_command.exec_command("cd '.'")
@pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
| emulate_nonposix |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol1.py | {
"start": 790,
"end": 877
} | class ____(Protocol[T]):
def m1(self, p0: T) -> None:
pass
attr: T
| Proto |
python | readthedocs__readthedocs.org | readthedocs/api/mixins.py | {
"start": 369,
"end": 1901
} | class ____:
"""
Add cache tags for project and version to the response of this view.
The view inheriting this mixin should implement the
`self._get_project` and `self._get_version` methods.
If `self._get_version` returns `None`,
only the project level tags are added.
You can add an extra per-project tag by overriding the `project_cache_tag` attribute.
"""
project_cache_tag = None
def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
cache_tags = self._get_cache_tags()
if cache_tags:
add_cache_tags(response, cache_tags)
return response
def _get_cache_tags(self):
"""
Get cache tags for this view.
.. warning::
This method is run at the end of the request,
so any exceptions like 404 should be caught.
"""
try:
project = self._get_project()
version = self._get_version()
except Exception:
log.warning(
"Error while retrieving project or version for this view.",
exc_info=True,
)
return []
tags = []
if project:
tags.append(project.slug)
if project and version:
tags.append(get_cache_tag(project.slug, version.slug))
if project and self.project_cache_tag:
tags.append(get_cache_tag(project.slug, self.project_cache_tag))
return tags
| CDNCacheTagsMixin |
python | google__pytype | pytype/constant_folding.py | {
"start": 4495,
"end": 7086
} | class ____:
"""A simple opcode stack."""
def __init__(self):
self.stack = []
self.consts = {}
def __iter__(self):
return self.stack.__iter__()
def push(self, val):
self.stack.append(val)
def pop(self):
return self.stack.pop()
def _preserve_constant(self, c):
if c and (
not isinstance(c.op, opcodes.LOAD_CONST)
or isinstance(c.op, opcodes.BUILD_STRING)
):
self.consts[id(c.op)] = c
def clear(self):
# Preserve any constants in the stack before clearing it.
for c in self.stack:
self._preserve_constant(c)
self.stack = []
def _pop_args(self, n):
"""Try to get n args off the stack for a BUILD call."""
if len(self.stack) < n:
# We have started a new block in the middle of constructing a literal
# (e.g. due to an inline function call). Clear the stack, since the
# literal is not constant.
self.clear()
return None
elif n and any(x is None for x in self.stack[-n:]):
# We have something other than constants in the arg list. Pop all the args
# for this op off the stack, preserving constants.
for _ in range(n):
self._preserve_constant(self.pop())
return None
else:
return [self.pop() for _ in range(n)]
def fold_args(self, n, op):
"""Collect the arguments to a build call."""
ret = _CollectionBuilder()
args = self._pop_args(n)
if args is None:
self.push(None)
return None
for elt in args:
ret.add(elt)
elt.op.folded = op
return ret.build()
def fold_map_args(self, n, op):
"""Collect the arguments to a BUILD_MAP call."""
ret = _MapBuilder()
args = self._pop_args(2 * n)
if args is None:
self.push(None)
return None
for i in range(0, 2 * n, 2):
v_elt, k_elt = args[i], args[i + 1]
ret.add(k_elt, v_elt)
k_elt.op.folded = op
v_elt.op.folded = op
return ret.build()
def build_str(self, n, op):
ret = self.fold_args(n, op)
if ret:
self.push(_Constant(('prim', str), '', None, op))
else:
self.push(None)
return ret
def build(self, python_type, op):
"""Build a folded type."""
collection = self.fold_args(op.arg, op)
if collection:
typename = python_type.__name__
typ = (typename, collection.types)
try:
value = python_type(collection.values)
except TypeError as e:
raise ConstantError(f'TypeError: {e.args[0]}', op) from e
elements = collection.elements
self.push(_Constant(typ, value, elements, op))
| _Stack |
python | pytorch__pytorch | torch/_inductor/compile_fx_ext.py | {
"start": 2414,
"end": 3544
} | class ____(contextlib.ExitStack):
"""
Helper for _VirtualizedSerializer.patch()
"""
def __init__(self, virtualized: _VirtualizedSerializer) -> None:
super().__init__()
self.virtualized = virtualized
@override
def __enter__(self) -> Self:
super().__enter__()
for set_name in dir(V):
if not set_name.startswith("set_"):
continue
name = set_name[4:]
name = name.removesuffix("_handler")
set_handler = getattr(V, set_name)
if hasattr(self.virtualized, name):
value = getattr(self.virtualized, name)
else:
# poison any values that we don't serialize so that any
# unset accesses are caught.
value = torch._inductor.virtualized._PoisonedVirtual
self.enter_context(set_handler(value))
return self
def _is_fallback_handler(op: object) -> bool:
try:
return op._is_fallback_handler # type: ignore[attr-defined]
except AttributeError:
return False
| _VirtualizedSerializerContextManager |
python | pypa__warehouse | warehouse/subscriptions/models.py | {
"start": 4225,
"end": 5174
} | class ____(db.Model):
__tablename__ = "stripe_subscription_prices"
__repr__ = make_repr("price_id", "unit_amount", "recurring")
price_id: Mapped[str | None] # generated by Payment Service Provider
currency: Mapped[str] # https://stripe.com/docs/currencies
subscription_product_id: Mapped[UUID] = mapped_column(
PG_UUID,
ForeignKey(
"stripe_subscription_products.id", onupdate="CASCADE", ondelete="CASCADE"
),
)
unit_amount: Mapped[int] # positive integer in cents
is_active: Mapped[bool_true]
recurring: Mapped[enum.Enum] = mapped_column(
Enum(
StripeSubscriptionPriceInterval,
values_callable=lambda x: [e.value for e in x],
),
)
tax_behavior: Mapped[str | None] # TODO: Enum? inclusive, exclusive, unspecified
subscription_product: Mapped["StripeSubscriptionProduct"] = relationship(lazy=False)
| StripeSubscriptionPrice |
python | getsentry__sentry | src/sentry/users/services/usersocialauth/model.py | {
"start": 407,
"end": 722
} | class ____(RpcModel):
id: int
user_id: int
provider: str
uid: str
extra_data: dict[str, Any]
def get_backend(self) -> type[BaseAuth] | None:
return get_backend(instance=self)
@property
def tokens(self) -> dict[str, Any]:
return tokens(instance=self)
| RpcUserSocialAuth |
python | apache__airflow | providers/apache/kafka/src/airflow/providers/apache/kafka/operators/consume.py | {
"start": 1249,
"end": 9825
} | class ____(BaseOperator):
"""
An operator that consumes from Kafka a topic(s) and processing the messages.
The operator creates a Kafka consumer that reads a batch of messages from the cluster and processes them
using the user supplied callable function. The consumer will continue to read in batches until it reaches
the end of the log or reads a maximum number of messages is reached.
:param kafka_config_id: The connection object to use, defaults to "kafka_default"
:param topics: A list of topics or regex patterns the consumer should subscribe to.
:param apply_function: The function that should be applied to fetched one at a time.
name of dag file executing the function and the function name delimited by a `.`
:param apply_function_batch: The function that should be applied to a batch of messages fetched. Can not
be used with `apply_function`. Intended for transactional workloads where an expensive task might
be called before or after operations on the messages are taken.
:param apply_function_args: Additional arguments that should be applied to the callable, defaults to None
:param apply_function_kwargs: Additional key word arguments that should be applied to the callable
defaults to None
:param commit_cadence: When consumers should commit offsets ("never", "end_of_batch","end_of_operator"),
defaults to "end_of_operator";
if end_of_operator, the commit() is called based on the max_messages arg. Commits are made after the
operator has processed the apply_function method for the maximum messages in the operator.
if end_of_batch, the commit() is called based on the max_batch_size arg. Commits are made after each
batch has processed by the apply_function method for all messages in the batch.
if never, close() is called without calling the commit() method.
:param max_messages: The maximum total number of messages an operator should read from Kafka,
defaults to None implying read to the end of the topic.
:param max_batch_size: The maximum number of messages a consumer should read when polling,
defaults to 1000
:param poll_timeout: How long the Kafka consumer should wait before determining no more messages are
available, defaults to 60
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:ConsumeFromTopicOperator`
"""
BLUE = "#ffefeb"
ui_color = BLUE
template_fields = (
"topics",
"apply_function_args",
"apply_function_kwargs",
"kafka_config_id",
)
def __init__(
self,
topics: str | Sequence[str],
kafka_config_id: str = "kafka_default",
apply_function: Callable[..., Any] | str | None = None,
apply_function_batch: Callable[..., Any] | str | None = None,
apply_function_args: Sequence[Any] | None = None,
apply_function_kwargs: dict[Any, Any] | None = None,
commit_cadence: str = "end_of_operator",
max_messages: int | None = None,
max_batch_size: int = 1000,
poll_timeout: float = 60,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self.topics = topics
self.apply_function = apply_function
self.apply_function_batch = apply_function_batch
self.apply_function_args = apply_function_args or ()
self.apply_function_kwargs = apply_function_kwargs or {}
self.kafka_config_id = kafka_config_id
self.commit_cadence = commit_cadence
self.max_messages = max_messages
self.max_batch_size = max_batch_size
self.poll_timeout = poll_timeout
self.read_to_end = self.max_messages is None
self._validate_commit_cadence_on_construct()
if self.max_messages is not None and self.max_batch_size > self.max_messages:
self.log.warning(
"max_batch_size (%s) > max_messages (%s). Setting max_messages to %s ",
self.max_batch_size,
self.max_messages,
self.max_batch_size,
)
self.max_messages = self.max_batch_size
if apply_function and apply_function_batch:
raise AirflowException(
"One of apply_function or apply_function_batch must be supplied, not both."
)
@cached_property
def hook(self):
"""Return the KafkaConsumerHook instance."""
return KafkaConsumerHook(topics=self.topics, kafka_config_id=self.kafka_config_id)
def execute(self, context) -> Any:
self._validate_commit_cadence_before_execute()
consumer = self.hook.get_consumer()
if isinstance(self.apply_function, str):
self.apply_function = import_string(self.apply_function)
if isinstance(self.apply_function_batch, str):
self.apply_function_batch = import_string(self.apply_function_batch)
if self.apply_function is not None and not callable(self.apply_function):
raise TypeError(f"apply_function is not a callable, got {type(self.apply_function)} instead.")
if self.apply_function:
apply_callable = partial(
self.apply_function,
*self.apply_function_args,
**self.apply_function_kwargs,
)
if self.apply_function_batch is not None and not callable(self.apply_function_batch):
raise TypeError(
f"apply_function_batch is not a callable, got {type(self.apply_function_batch)} instead."
)
if self.apply_function_batch:
apply_callable = partial(
self.apply_function_batch,
*self.apply_function_args,
**self.apply_function_kwargs,
)
messages_left = self.max_messages or True
while self.read_to_end or (
messages_left > 0
): # bool(True > 0) == True in the case where self.max_messages isn't set by the user
if not isinstance(messages_left, bool):
batch_size = self.max_batch_size if messages_left > self.max_batch_size else messages_left
else:
batch_size = self.max_batch_size
msgs = consumer.consume(num_messages=batch_size, timeout=self.poll_timeout)
if not self.read_to_end:
messages_left -= len(msgs)
if not msgs: # No messages + messages_left is being used.
self.log.info("Reached end of log. Exiting.")
break
if self.apply_function:
for m in msgs:
apply_callable(m)
if self.apply_function_batch:
apply_callable(msgs)
if self.commit_cadence == "end_of_batch":
self.log.info("committing offset at %s", self.commit_cadence)
consumer.commit()
if self.commit_cadence != "never":
self.log.info("committing offset at %s", self.commit_cadence)
consumer.commit()
consumer.close()
return
def _validate_commit_cadence_on_construct(self):
"""Validate the commit_cadence parameter when the operator is constructed."""
if self.commit_cadence and self.commit_cadence not in VALID_COMMIT_CADENCE:
raise AirflowException(
f"commit_cadence must be one of {VALID_COMMIT_CADENCE}. Got {self.commit_cadence}"
)
def _validate_commit_cadence_before_execute(self):
"""Validate the commit_cadence parameter before executing the operator."""
kafka_config = self.hook.get_connection(self.kafka_config_id).extra_dejson
# Same as kafka's behavior, default to "true" if not set
enable_auto_commit = str(kafka_config.get("enable.auto.commit", "true")).lower()
if self.commit_cadence and enable_auto_commit != "false":
self.log.warning(
"To respect commit_cadence='%s', "
"'enable.auto.commit' should be set to 'false' in the Kafka connection configuration. "
"Currently, 'enable.auto.commit' is not explicitly set, so it defaults to 'true', which causes "
"the consumer to auto-commit offsets every 5 seconds. "
"See: https://kafka.apache.org/documentation/#consumerconfigs_enable.auto.commit for more information",
self.commit_cadence,
)
| ConsumeFromTopicOperator |
python | Textualize__textual | docs/examples/app/question01.py | {
"start": 87,
"end": 502
} | class ____(App[str]):
def compose(self) -> ComposeResult:
yield Label("Do you love Textual?")
yield Button("Yes", id="yes", variant="primary")
yield Button("No", id="no", variant="error")
def on_button_pressed(self, event: Button.Pressed) -> None:
self.exit(event.button.id)
if __name__ == "__main__":
app = QuestionApp()
reply = app.run()
print(reply)
| QuestionApp |
python | encode__django-rest-framework | tests/test_viewsets.py | {
"start": 890,
"end": 1082
} | class ____(models.Model):
pass
def decorate(fn):
@wraps(fn)
def wrapper(self, request, *args, **kwargs):
return fn(self, request, *args, **kwargs)
return wrapper
| Action |
python | great-expectations__great_expectations | great_expectations/self_check/sqlalchemy_connection_manager.py | {
"start": 1295,
"end": 2008
} | class ____:
def __init__(self, sa, connection_string) -> None:
self.lock = threading.Lock()
self.sa = sa
self.connection_string = connection_string
self._is_valid = None
def is_valid(self):
with self.lock:
if self._is_valid is None:
try:
engine = self.sa.create_engine(self.connection_string)
conn = engine.connect()
conn.close()
self._is_valid = True
except (ImportError, self.sa.exc.SQLAlchemyError) as e:
print(f"{e!s}")
self._is_valid = False
return self._is_valid
| LockingConnectionCheck |
python | modin-project__modin | modin/core/execution/unidist/implementations/pandas_on_unidist/dataframe/dataframe.py | {
"start": 1070,
"end": 2413
} | class ____(PandasDataframe):
"""
The class implements the interface in ``PandasDataframe`` using unidist.
Parameters
----------
partitions : np.ndarray
A 2D NumPy array of partitions.
index : sequence
The index for the dataframe. Converted to a ``pandas.Index``.
columns : sequence
The columns object for the dataframe. Converted to a ``pandas.Index``.
row_lengths : list, optional
The length of each partition in the rows. The "height" of
each of the block partitions. Is computed if not provided.
column_widths : list, optional
The width of each partition in the columns. The "width" of
each of the block partitions. Is computed if not provided.
dtypes : pandas.Series, optional
The data types for the dataframe columns.
pandas_backend : {"pyarrow", None}, optional
Backend used by pandas. None - means default NumPy backend.
"""
_partition_mgr_cls = PandasOnUnidistDataframePartitionManager
def support_materialization_in_worker_process(self) -> bool:
# more details why this is not `True` in https://github.com/modin-project/modin/pull/6673
return False
@property
@_inherit_docstrings(PandasDataframe.engine)
def engine(self) -> str:
return "Unidist"
| PandasOnUnidistDataframe |
python | pydata__xarray | xarray/backends/file_manager.py | {
"start": 12554,
"end": 16239
} | class ____(FileManager[T_File]):
"""File manager that supports pickling by reopening a file object.
Use PickleableFileManager for wrapping file-like objects that do not natively
support pickling (e.g., netCDF4.Dataset and h5netcdf.File) in cases where a
global cache is not desirable (e.g., for netCDF files opened from bytes in
memory, or from existing file objects).
"""
def __init__(
self,
opener: Callable[..., T_File],
*args: Any,
mode: Any = _OMIT_MODE,
kwargs: Mapping[str, Any] | None = None,
):
kwargs = {} if kwargs is None else dict(kwargs)
self._opener = opener
self._args = args
self._mode = "a" if mode == "w" else mode
self._kwargs = kwargs
# Note: No need for locking with PickleableFileManager, because all
# opening of files happens in the constructor.
if mode != _OMIT_MODE:
kwargs = kwargs | {"mode": mode}
self._file: T_File | None = opener(*args, **kwargs)
@property
def _closed(self) -> bool:
# If opener() raised an error in the constructor, _file may not be set
return getattr(self, "_file", None) is None
def _get_unclosed_file(self) -> T_File:
if self._closed:
raise RuntimeError("file is closed")
file = self._file
assert file is not None
return file
def acquire(self, needs_lock: bool = True) -> T_File:
del needs_lock # unused
return self._get_unclosed_file()
@contextmanager
def acquire_context(self, needs_lock: bool = True) -> Iterator[T_File]:
del needs_lock # unused
yield self._get_unclosed_file()
def close(self, needs_lock: bool = True) -> None:
del needs_lock # unused
if not self._closed:
file = self._get_unclosed_file()
file.close()
self._file = None
# Remove all references to opener arguments, so they can be garbage
# collected.
self._args = ()
self._mode = _OMIT_MODE
self._kwargs = {}
def __del__(self) -> None:
if not self._closed:
self.close()
if OPTIONS["warn_for_unclosed_files"]:
warnings.warn(
f"deallocating {self}, but file is not already closed. "
"This may indicate a bug.",
RuntimeWarning,
stacklevel=2,
)
def __getstate__(self):
# file is intentionally omitted: we want to open it again
opener = _get_none if self._closed else self._opener
return (opener, self._args, self._mode, self._kwargs)
def __setstate__(self, state) -> None:
opener, args, mode, kwargs = state
self.__init__(opener, *args, mode=mode, kwargs=kwargs) # type: ignore[misc]
def __repr__(self) -> str:
if self._closed:
return f"<closed {type(self).__name__}>"
args_string = ", ".join(map(repr, self._args))
if self._mode is not _OMIT_MODE:
args_string += f", mode={self._mode!r}"
kwargs = (
self._kwargs | {"memory": utils.ReprObject("...")}
if "memory" in self._kwargs
else self._kwargs
)
return f"{type(self).__name__}({self._opener!r}, {args_string}, {kwargs=})"
@atexit.register
def _remove_del_methods():
# We don't need to close unclosed files at program exit, and may not be able
# to, because Python is cleaning up imports / globals.
del CachingFileManager.__del__
del PickleableFileManager.__del__
| PickleableFileManager |
python | streamlit__streamlit | lib/tests/streamlit/elements/lib/options_selector_utils_test.py | {
"start": 3231,
"end": 5682
} | class ____(unittest.TestCase):
@parameterized.expand(
[
(np.array([1, 2, 3, 4, 5]), 5, 4),
# This one will have 0.15000000000000002 because of floating point precision
(np.arange(0.0, 0.25, 0.05), 0.15, 3),
([0, 1, 2, 3], 3, 3),
([0.1, 0.2, 0.3], 0.2, 1),
([0.1, 0.2, None], None, 2),
([0.1, 0.2, float("inf")], float("inf"), 2),
(["He", "ello w", "orld"], "He", 0),
(list(np.arange(0.0, 0.25, 0.05)), 0.15, 3),
]
)
def test_successful_index_(self, input, find_value, expected_index):
actual_index = index_(input, find_value)
assert actual_index == expected_index
@parameterized.expand(
[
(np.array([1, 2, 3, 4, 5]), 6),
(np.arange(0.0, 0.25, 0.05), 0.1500002),
([0, 1, 2, 3], 3.00001),
([0.1, 0.2, 0.3], 0.3000004),
([0.1, 0.2, 0.3], None),
(["He", "ello w", "orld"], "world"),
(list(np.arange(0.0, 0.25, 0.05)), 0.150002),
]
)
def test_unsuccessful_index_(self, input_options, find_value):
with pytest.raises(ValueError, match=f"{find_value} is not in iterable"):
index_(input_options, find_value)
def test_index_list(self):
assert index_([1, 2, 3, 4], 1) == 0
assert index_([1, 2, 3, 4], 4) == 3
def test_index_list_fails(self):
with pytest.raises(ValueError, match="5 is not in iterable"):
index_([1, 2, 3, 4], 5)
def test_index_tuple(self):
assert index_((1, 2, 3, 4), 1) == 0
assert index_((1, 2, 3, 4), 4) == 3
def test_index_tuple_fails(self):
with pytest.raises(ValueError, match="5 is not in iterable"):
index_((1, 2, 3, 4), 5)
def test_index_numpy_array(self):
assert index_(np.array([1, 2, 3, 4]), 1) == 0
assert index_(np.array([1, 2, 3, 4]), 4) == 3
def test_index_numpy_array_fails(self):
with pytest.raises(ValueError, match="5 is not in iterable"):
index_(np.array([1, 2, 3, 4]), 5)
def test_index_pandas_series(self):
assert index_(pd.Series([1, 2, 3, 4]), 1) == 0
assert index_(pd.Series([1, 2, 3, 4]), 4) == 3
def test_index_pandas_series_fails(self):
with pytest.raises(ValueError, match="5 is not in iterable"):
index_(pd.Series([1, 2, 3, 4]), 5)
| TestIndexMethod |
python | python__mypy | mypy/stubutil.py | {
"start": 11718,
"end": 12083
} | class ____:
def __init__(
self,
name: str,
self_var: str,
docstring: str | None = None,
cls: type | None = None,
parent: ClassInfo | None = None,
) -> None:
self.name = name
self.self_var = self_var
self.docstring = docstring
self.cls = cls
self.parent = parent
| ClassInfo |
python | lazyprogrammer__machine_learning_examples | rnn_class/mlp_parity.py | {
"start": 491,
"end": 903
} | class ____(object):
def __init__(self, M1, M2, an_id):
self.id = an_id
self.M1 = M1
self.M2 = M2
W = init_weight(M1, M2)
b = np.zeros(M2)
self.W = theano.shared(W, 'W_%s' % self.id)
self.b = theano.shared(b, 'b_%s' % self.id)
self.params = [self.W, self.b]
def forward(self, X):
return T.nnet.relu(X.dot(self.W) + self.b)
| HiddenLayer |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard_python3/bundled-services/blobstore/django/main.py | {
"start": 1644,
"end": 3546
} | class ____(blobstore.BlobstoreDownloadHandler):
def get(self, environ, photo_key):
if not blobstore.get(photo_key):
return HttpResponse("Photo key not found", status=404)
else:
response = HttpResponse(headers=self.send_blob(environ, photo_key))
# Prevent Django from setting a default content-type.
# GAE sets it to a guessed type if the header is not set.
response["Content-Type"] = None
return response
# [END gae_blobstore_handler_django]
def upload_form(request):
"""Create the HTML form to upload a file."""
upload_url = blobstore.create_upload_url("/upload_photo")
response = f"""
<html><body>
<form action="{upload_url}" method="POST" enctype="multipart/form-data">
Upload File: <input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body></html>"""
return HttpResponse(response)
def view_photo(request, key):
"""View photo given a key."""
return ViewPhotoHandler().get(request.environ, key)
def upload_photo(request):
"""Upload handler called by blobstore when a blob is uploaded in the test."""
return PhotoUploadHandler().post(request.environ)
# [START gae_blobstore_handler_django]
urlpatterns = (
path("", upload_form, name="upload_form"),
path("view_photo/<key>", view_photo, name="view_photo"),
path("upload_photo", upload_photo, name="upload_photo"),
)
# [END gae_blobstore_handler_django]
settings.configure(
DEBUG=True,
SECRET_KEY="thisisthesecretkey",
ROOT_URLCONF=__name__,
MIDDLEWARE_CLASSES=(
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
),
ALLOWED_HOSTS=["*"],
)
app = wrap_wsgi_app(get_wsgi_application())
| ViewPhotoHandler |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 94362,
"end": 94845
} | class ____(sgqlc.types.Enum):
"""Possible roles a user may have in relation to an organization.
Enumeration Choices:
* `DIRECT_MEMBER`: A user who is a direct member of the
organization.
* `OWNER`: A user with full administrative access to the
organization.
* `UNAFFILIATED`: A user who is unaffiliated with the
organization.
"""
__schema__ = github_schema
__choices__ = ("DIRECT_MEMBER", "OWNER", "UNAFFILIATED")
| RoleInOrganization |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 28391,
"end": 28513
} | class ____(BaseModel):
dag_id: str
run_id: str
type: Literal["GetDagRunState"] = "GetDagRunState"
| GetDagRunState |
python | GoogleCloudPlatform__python-docs-samples | datastore/cloud-client/snippets_test.py | {
"start": 784,
"end": 1365
} | class ____(datastore.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.entities_to_delete = []
self.keys_to_delete = []
def cleanup(self):
batch = self.batch()
batch.begin()
self.delete_multi(
list({x.key for x in self.entities_to_delete if x})
+ list(set(self.keys_to_delete))
)
batch.commit(retry=retry_policy)
@pytest.fixture
def client():
client = CleanupClient(PROJECT)
yield client
client.cleanup()
@pytest.mark.flaky
| CleanupClient |
python | neetcode-gh__leetcode | python/1888-minimum-number-of-flips-to-make-the-binary-string-alternating.py | {
"start": 0,
"end": 753
} | class ____:
def minFlips(self, s: str) -> int:
n = len(s)
s = s + s
alt1, alt2 = "", ""
for i in range(len(s)):
alt1 += "0" if i % 2 == 0 else "1"
alt2 += "1" if i % 2 == 0 else "0"
res = float('inf')
diff1, diff2 = 0, 0
l = 0
for r in range(len(s)):
if s[r] != alt1[r]:
diff1 += 1
if s[r] != alt2[r]:
diff2 += 1
if (r - l + 1) > n:
if s[l] != alt1[l]:
diff1 -= 1
if s[l] != alt2[l]:
diff2 -= 1
l += 1
if (r - l + 1) == n:
res = min(res, diff1, diff2)
return res
| Solution |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 8290,
"end": 8357
} | class ____(HTTPClientError):
status_code = 408
| HTTPRequestTimeout |
python | walkccc__LeetCode | solutions/974. Subarray Sums Divisible by K/974.py | {
"start": 0,
"end": 273
} | class ____:
def subarraysDivByK(self, nums: list[int], k: int) -> int:
ans = 0
prefix = 0
count = [0] * k
count[0] = 1
for num in nums:
prefix = (prefix + num % k + k) % k
ans += count[prefix]
count[prefix] += 1
return ans
| Solution |
python | ZoranPandovski__al-go-rithms | data_structures/Tree/decisionTree/python/Decision_Tree.py | {
"start": 239,
"end": 4810
} | class ____:
def __init__(self, depth = 5, min_leaf_size = 5):
self.depth = depth
self.decision_boundary = 0
self.left = None
self.right = None
self.min_leaf_size = min_leaf_size
self.prediction = None
def mean_squared_error(self, labels, prediction):
"""
mean_squared_error:
@param labels: a one dimensional numpy array
@param prediction: a floating point value
return value: mean_squared_error calculates the error if prediction is used to estimate the labels
"""
if labels.ndim != 1:
print("Error: Input labels must be one dimensional")
return np.mean((labels - prediction) ** 2)
def train(self, X, y):
"""
train:
@param X: a one dimensional numpy array
@param y: a one dimensional numpy array.
The contents of y are the labels for the corresponding X values
train does not have a return value
"""
"""
this section is to check that the inputs conform to our dimensionality constraints
"""
if X.ndim != 1:
print("Error: Input data set must be one dimensional")
return
if len(X) != len(y):
print("Error: X and y have different lengths")
return
if y.ndim != 1:
print("Error: Data set labels must be one dimensional")
return
if len(X) < 2 * self.min_leaf_size:
self.prediction = np.mean(y)
return
if self.depth == 1:
self.prediction = np.mean(y)
return
best_split = 0
min_error = self.mean_squared_error(X,np.mean(y)) * 2
"""
loop over all possible splits for the decision tree. find the best split.
if no split exists that is less than 2 * error for the entire array
then the data set is not split and the average for the entire array is used as the predictor
"""
for i in range(len(X)):
if len(X[:i]) < self.min_leaf_size:
continue
elif len(X[i:]) < self.min_leaf_size:
continue
else:
error_left = self.mean_squared_error(X[:i], np.mean(y[:i]))
error_right = self.mean_squared_error(X[i:], np.mean(y[i:]))
error = error_left + error_right
if error < min_error:
best_split = i
min_error = error
if best_split != 0:
left_X = X[:best_split]
left_y = y[:best_split]
right_X = X[best_split:]
right_y = y[best_split:]
self.decision_boundary = X[best_split]
self.left = Decision_Tree(depth = self.depth - 1, min_leaf_size = self.min_leaf_size)
self.right = Decision_Tree(depth = self.depth - 1, min_leaf_size = self.min_leaf_size)
self.left.train(left_X, left_y)
self.right.train(right_X, right_y)
else:
self.prediction = np.mean(y)
return
def predict(self, x):
"""
predict:
@param x: a floating point value to predict the label of
the prediction function works by recursively calling the predict function
of the appropriate subtrees based on the tree's decision boundary
"""
if self.prediction is not None:
return self.prediction
elif self.left or self.right is not None:
if x >= self.decision_boundary:
return self.right.predict(x)
else:
return self.left.predict(x)
else:
print("Error: Decision tree not yet trained")
return None
def main():
"""
In this demonstration we're generating a sample data set from the sin function in numpy.
We then train a decision tree on the data set and use the decision tree to predict the
label of 10 different test values. Then the mean squared error over this test is displayed.
"""
X = np.arange(-1., 1., 0.005)
y = np.sin(X)
tree = Decision_Tree(depth = 10, min_leaf_size = 10)
tree.train(X,y)
test_cases = (np.random.rand(10) * 2) - 1
predictions = np.array([tree.predict(x) for x in test_cases])
avg_error = np.mean((predictions - test_cases) ** 2)
print("Test values: " + str(test_cases))
print("Predictions: " + str(predictions))
print("Average error: " + str(avg_error))
if __name__ == '__main__':
main() | Decision_Tree |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 108852,
"end": 108977
} | class ____(_pkg_config_info):
section = 'xft'
append_config_exe = 'xft'
version_macro_name = 'XFT_VERSION'
| xft_info |
python | great-expectations__great_expectations | tests/datasource/fluent/conftest.py | {
"start": 5181,
"end": 9832
} | class ____(ExecutionEngine):
def __init__(self, *args, **kwargs):
pass
@override
def get_batch_data_and_markers(self, batch_spec) -> tuple[BatchData, BatchMarkers]: # type: ignore[override] # FIXME CoP
return BatchData(self), BatchMarkers(ge_load_time=None)
@pytest.fixture
def inject_engine_lookup_double(
monkeypatch: MonkeyPatch,
) -> Generator[Type[ExecutionEngineDouble], None, None]:
"""
Inject an execution engine test double into the _SourcesFactory.engine_lookup
so that all Datasources use the execution engine double.
Dynamically create a new subclass so that runtime type validation does not fail.
"""
original_engine_override: dict[Type[Datasource], Type[ExecutionEngine]] = {}
for key in DataSourceManager.type_lookup:
if issubclass(type(key), Datasource):
original_engine_override[key] = key.execution_engine_override
try:
for source in original_engine_override:
source.execution_engine_override = ExecutionEngineDouble
yield ExecutionEngineDouble
finally:
for source, engine in original_engine_override.items():
source.execution_engine_override = engine
@pytest.fixture
def sqlite_database_path() -> pathlib.Path:
relative_path = pathlib.Path(
"..",
"..",
"test_sets",
"taxi_yellow_tripdata_samples",
"sqlite",
"yellow_tripdata.db",
)
return pathlib.Path(__file__).parent.joinpath(relative_path).resolve(strict=True)
@pytest.fixture
def seed_ds_env_vars(
monkeypatch: pytest.MonkeyPatch, sqlite_database_path: pathlib.Path
) -> tuple[tuple[str, str], ...]:
"""Seed a collection of ENV variables for use in testing config substitution."""
config_sub_dict = {
"MY_CONN_STR": f"sqlite:///{sqlite_database_path}",
"MY_URL": "http://example.com",
"MY_FILE": __file__,
}
for name, value in config_sub_dict.items():
monkeypatch.setenv(name, value)
CNF_TEST_LOGGER.info(f"Setting ENV - {name} = '{value}'")
# return as tuple of tuples so that the return value is immutable and therefore cacheable
return tuple((k, v) for k, v in config_sub_dict.items())
@pytest.fixture
def cloud_api_fake_db(cloud_api_fake) -> FakeDBTypedDict:
from tests.datasource.fluent._fake_cloud_api import _CLOUD_API_FAKE_DB
return _CLOUD_API_FAKE_DB
@pytest.fixture
def file_dc_config_dir_init(tmp_path: pathlib.Path) -> pathlib.Path:
"""
Initialize an regular/old-style FileDataContext project config directory.
Removed on teardown.
"""
gx_yml = tmp_path / FileDataContext.GX_DIR / FileDataContext.GX_YML
assert gx_yml.exists() is False
gx.get_context(mode="file", project_root_dir=tmp_path)
assert gx_yml.exists()
tmp_gx_dir = gx_yml.parent.absolute()
CNF_TEST_LOGGER.info(f"tmp_gx_dir -> {tmp_gx_dir}")
return tmp_gx_dir
@pytest.fixture
def empty_file_context(file_dc_config_dir_init) -> FileDataContext:
context = gx.get_context(context_root_dir=file_dc_config_dir_init, cloud_mode=False)
return context
@pytest.fixture(
params=[
pytest.param("empty_cloud_context_fluent", marks=pytest.mark.cloud),
pytest.param("empty_file_context", marks=pytest.mark.filesystem),
],
ids=["cloud", "file"],
)
def empty_contexts(
request: FixtureRequest,
cloud_storage_get_client_doubles,
) -> FileDataContext | CloudDataContext:
context_fixture: FileDataContext | CloudDataContext = request.getfixturevalue(request.param)
return context_fixture
@pytest.fixture(scope="session")
def fluent_gx_config_yml() -> pathlib.Path:
assert PG_CONFIG_YAML_FILE.exists()
return PG_CONFIG_YAML_FILE
@pytest.fixture(scope="session")
def fluent_gx_config_yml_str(fluent_gx_config_yml: pathlib.Path) -> str:
return fluent_gx_config_yml.read_text()
@pytest.fixture()
def aws_region_name() -> str:
return "us-east-1"
@pytest.fixture(scope="function")
def aws_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
"""Monkeypatch ENV AWS Credentials for moto."""
monkeypatch.setenv("AWS_ACCESS_KEY_ID", "testing")
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "testing")
monkeypatch.setenv("AWS_SECURITY_TOKEN", "testing")
monkeypatch.setenv("AWS_SESSION_TOKEN", "testing")
monkeypatch.setenv("AWS_DEFAULT_REGION", "testing")
@pytest.fixture
def s3_mock(aws_credentials, aws_region_name: str) -> Generator[BotoBaseClient, None, None]:
with mock_s3():
client = aws.boto3.client("s3", region_name=aws_region_name)
yield client
| ExecutionEngineDouble |
python | fastapi__sqlmodel | docs_src/tutorial/many_to_many/tutorial003_py310.py | {
"start": 85,
"end": 456
} | class ____(SQLModel, table=True):
team_id: int | None = Field(default=None, foreign_key="team.id", primary_key=True)
hero_id: int | None = Field(default=None, foreign_key="hero.id", primary_key=True)
is_training: bool = False
team: "Team" = Relationship(back_populates="hero_links")
hero: "Hero" = Relationship(back_populates="team_links")
| HeroTeamLink |
python | sqlalchemy__sqlalchemy | test/orm/test_versioning.py | {
"start": 4581,
"end": 17653
} | class ____(fixtures.MappedTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"version_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("version_id", Integer, nullable=False),
Column("value", String(40), nullable=False),
test_needs_acid=True,
)
@classmethod
def setup_classes(cls):
class Foo(cls.Basic):
pass
def _fixture(self):
Foo, version_table = self.classes.Foo, self.tables.version_table
self.mapper_registry.map_imperatively(
Foo, version_table, version_id_col=version_table.c.version_id
)
s1 = fixture_session()
return s1
@engines.close_open_connections
def test_notsane_warning(self):
Foo = self.classes.Foo
save = testing.db.dialect.supports_sane_rowcount
testing.db.dialect.supports_sane_rowcount = False
try:
s1 = self._fixture()
f1 = Foo(value="f1")
f2 = Foo(value="f2")
s1.add_all((f1, f2))
s1.commit()
f1.value = "f1rev2"
assert_warns(sa.exc.SAWarning, s1.commit)
finally:
testing.db.dialect.supports_sane_rowcount = save
@provision.allow_stale_updates
def test_basic(self):
Foo = self.classes.Foo
s1 = self._fixture()
f1 = Foo(value="f1")
f2 = Foo(value="f2")
s1.add_all((f1, f2))
s1.commit()
f1.value = "f1rev2"
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
s2 = fixture_session()
f1_s = s2.get(Foo, f1.id)
f1_s.value = "f1rev3"
with conditional_sane_rowcount_warnings(update=True):
s2.commit()
f1.value = "f1rev3mine"
# Only dialects with a sane rowcount can detect the
# StaleDataError
if testing.db.dialect.supports_sane_rowcount:
assert_raises_message(
sa.orm.exc.StaleDataError,
r"UPDATE statement on table 'version_table' expected "
r"to update 1 row\(s\); 0 were matched.",
s1.commit,
),
s1.rollback()
else:
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
# new in 0.5 ! don't need to close the session
f1 = s1.get(Foo, f1.id)
f2 = s1.get(Foo, f2.id)
f1_s.value = "f1rev4"
with conditional_sane_rowcount_warnings(update=True):
s2.commit()
s1.delete(f1)
s1.delete(f2)
if testing.db.dialect.supports_sane_multi_rowcount:
assert_raises_message(
sa.orm.exc.StaleDataError,
r"DELETE statement on table 'version_table' expected "
r"to delete 2 row\(s\); 1 were matched.",
s1.commit,
)
else:
with conditional_sane_rowcount_warnings(delete=True):
s1.commit()
def test_multiple_updates(self):
Foo = self.classes.Foo
s1 = self._fixture()
f1 = Foo(value="f1")
f2 = Foo(value="f2")
s1.add_all((f1, f2))
s1.commit()
f1.value = "f1rev2"
f2.value = "f2rev2"
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
eq_(
s1.query(Foo.id, Foo.value, Foo.version_id).order_by(Foo.id).all(),
[(f1.id, "f1rev2", 2), (f2.id, "f2rev2", 2)],
)
def test_bulk_insert(self):
Foo = self.classes.Foo
s1 = self._fixture()
s1.bulk_insert_mappings(
Foo, [{"id": 1, "value": "f1"}, {"id": 2, "value": "f2"}]
)
eq_(
s1.query(Foo.id, Foo.value, Foo.version_id).order_by(Foo.id).all(),
[(1, "f1", 1), (2, "f2", 1)],
)
def test_bulk_update(self):
Foo = self.classes.Foo
s1 = self._fixture()
f1 = Foo(value="f1")
f2 = Foo(value="f2")
s1.add_all((f1, f2))
s1.commit()
with conditional_sane_rowcount_warnings(update=True):
s1.bulk_update_mappings(
Foo,
[
{"id": f1.id, "value": "f1rev2", "version_id": 1},
{"id": f2.id, "value": "f2rev2", "version_id": 1},
],
)
s1.commit()
eq_(
s1.query(Foo.id, Foo.value, Foo.version_id).order_by(Foo.id).all(),
[(f1.id, "f1rev2", 2), (f2.id, "f2rev2", 2)],
)
def test_bump_version(self):
"""test that version number can be bumped.
Ensures that the UPDATE or DELETE is against the
last committed version of version_id_col, not the modified
state.
"""
Foo = self.classes.Foo
s1 = self._fixture()
f1 = Foo(value="f1")
s1.add(f1)
s1.commit()
eq_(f1.version_id, 1)
f1.version_id = 2
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
eq_(f1.version_id, 2)
# skip an id, test that history
# is honored
f1.version_id = 4
f1.value = "something new"
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
eq_(f1.version_id, 4)
f1.version_id = 5
s1.delete(f1)
with conditional_sane_rowcount_warnings(delete=True):
s1.commit()
eq_(s1.query(Foo).count(), 0)
@provision.allow_stale_updates
@engines.close_open_connections
def test_versioncheck(self):
"""query.with_lockmode performs a 'version check' on an already loaded
instance"""
Foo = self.classes.Foo
s1 = self._fixture()
f1s1 = Foo(value="f1 value")
s1.add(f1s1)
s1.commit()
s2 = fixture_session()
f1s2 = s2.get(Foo, f1s1.id)
f1s2.value = "f1 new value"
with conditional_sane_rowcount_warnings(update=True):
s2.commit()
# load, version is wrong
assert_raises_message(
sa.orm.exc.StaleDataError,
r"Instance .* has version id '\d+' which does not "
r"match database-loaded version id '\d+'",
s1.get,
Foo,
f1s1.id,
with_for_update=dict(read=True),
)
# reload it - this expires the old version first
s1.refresh(f1s1, with_for_update={"read": True})
# now assert version OK
s1.get(Foo, f1s1.id, with_for_update=dict(read=True))
# assert brand new load is OK too
s1.close()
s1.get(Foo, f1s1.id, with_for_update=dict(read=True))
def test_versioncheck_not_versioned(self):
"""ensure the versioncheck logic skips if there isn't a
version_id_col actually configured"""
Foo = self.classes.Foo
version_table = self.tables.version_table
self.mapper_registry.map_imperatively(Foo, version_table)
s1 = fixture_session()
f1s1 = Foo(value="f1 value", version_id=1)
s1.add(f1s1)
s1.commit()
s1.query(Foo).with_for_update(read=True).where(Foo.id == f1s1.id).one()
@engines.close_open_connections
@testing.requires.update_nowait
def test_versioncheck_for_update(self):
"""query.with_lockmode performs a 'version check' on an already loaded
instance"""
Foo = self.classes.Foo
s1 = self._fixture()
f1s1 = Foo(value="f1 value")
s1.add(f1s1)
s1.commit()
s2 = fixture_session()
f1s2 = s2.get(Foo, f1s1.id)
# not sure if I like this API
s2.refresh(f1s2, with_for_update=True)
f1s2.value = "f1 new value"
assert_raises(
exc.DBAPIError, s1.refresh, f1s1, with_for_update={"nowait": True}
)
s1.rollback()
with conditional_sane_rowcount_warnings(update=True):
s2.commit()
s1.refresh(f1s1, with_for_update={"nowait": True})
assert f1s1.version_id == f1s2.version_id
def test_update_multi_missing_broken_multi_rowcount(self):
@util.memoized_property
def rowcount(self):
if len(self.context.compiled_parameters) > 1:
return -1
else:
return self.context.rowcount
with (
patch.object(
config.db.dialect, "supports_sane_multi_rowcount", False
),
patch("sqlalchemy.engine.cursor.CursorResult.rowcount", rowcount),
):
Foo = self.classes.Foo
s1 = self._fixture()
f1s1 = Foo(value="f1 value")
s1.add(f1s1)
s1.commit()
f1s1.value = "f2 value"
with conditional_sane_rowcount_warnings(update=True):
s1.flush()
eq_(f1s1.version_id, 2)
def test_update_delete_no_plain_rowcount(self):
with (
patch.object(config.db.dialect, "supports_sane_rowcount", False),
patch.object(
config.db.dialect, "supports_sane_multi_rowcount", False
),
):
Foo = self.classes.Foo
s1 = self._fixture()
f1s1 = Foo(value="f1 value")
s1.add(f1s1)
s1.commit()
f1s1.value = "f2 value"
with expect_warnings(
"Dialect .* does not support updated rowcount - "
"versioning cannot be verified."
):
s1.flush()
eq_(f1s1.version_id, 2)
s1.delete(f1s1)
with expect_warnings(
"Dialect .* does not support deleted rowcount - "
"versioning cannot be verified."
):
s1.flush()
@engines.close_open_connections
def test_noversioncheck(self):
"""test query.with_lockmode works when the mapper has no version id
col"""
Foo, version_table = self.classes.Foo, self.tables.version_table
s1 = fixture_session()
self.mapper_registry.map_imperatively(Foo, version_table)
f1s1 = Foo(value="foo", version_id=0)
s1.add(f1s1)
s1.commit()
s2 = fixture_session()
f1s2 = (
s2.query(Foo)
.with_for_update(read=True)
.where(Foo.id == f1s1.id)
.one()
)
assert f1s2.id == f1s1.id
assert f1s2.value == f1s1.value
def test_merge_no_version(self):
Foo = self.classes.Foo
s1 = self._fixture()
f1 = Foo(value="f1")
s1.add(f1)
s1.commit()
f1.value = "f2"
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
f2 = Foo(id=f1.id, value="f3")
f3 = s1.merge(f2)
assert f3 is f1
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
eq_(f3.version_id, 3)
def test_merge_correct_version(self):
Foo = self.classes.Foo
s1 = self._fixture()
f1 = Foo(value="f1")
s1.add(f1)
s1.commit()
f1.value = "f2"
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
f2 = Foo(id=f1.id, value="f3", version_id=2)
f3 = s1.merge(f2)
assert f3 is f1
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
eq_(f3.version_id, 3)
def test_merge_incorrect_version(self):
Foo = self.classes.Foo
s1 = self._fixture()
f1 = Foo(value="f1")
s1.add(f1)
s1.commit()
f1.value = "f2"
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
f2 = Foo(id=f1.id, value="f3", version_id=1)
assert_raises_message(
orm_exc.StaleDataError,
"Version id '1' on merged state "
"<Foo at .*?> does not match existing version '2'. "
"Leave the version attribute unset when "
"merging to update the most recent version.",
s1.merge,
f2,
)
def test_merge_incorrect_version_not_in_session(self):
Foo = self.classes.Foo
s1 = self._fixture()
f1 = Foo(value="f1")
s1.add(f1)
s1.commit()
f1.value = "f2"
with conditional_sane_rowcount_warnings(update=True):
s1.commit()
f2 = Foo(id=f1.id, value="f3", version_id=1)
s1.close()
assert_raises_message(
orm_exc.StaleDataError,
"Version id '1' on merged state "
"<Foo at .*?> does not match existing version '2'. "
"Leave the version attribute unset when "
"merging to update the most recent version.",
s1.merge,
f2,
)
| VersioningTest |
python | facelessuser__pymdown-extensions | pymdownx/magiclink.py | {
"start": 32469,
"end": 33177
} | class ____(InlineProcessor):
"""Convert emails to clickable email links."""
ANCESTOR_EXCLUDES = ('a',)
def email_encode(self, code):
"""Return entity definition by code, or the code if not defined."""
return f"{md_util.AMP_SUBSTITUTE}#{code:d};"
def handleMatch(self, m, data):
"""Handle email link patterns."""
el = etree.Element("a")
email = self.unescape(m.group('mail'))
href = f"mailto:{email}"
el.text = md_util.AtomicString(''.join([self.email_encode(ord(c)) for c in email]))
el.set("href", ''.join([md_util.AMP_SUBSTITUTE + f'#{ord(c):d};' for c in href]))
return el, m.start(0), m.end(0)
| MagiclinkMailPattern |
python | wandb__wandb | wandb/sdk/artifacts/_generated/create_registry_members.py | {
"start": 272,
"end": 376
} | class ____(GQLResult):
success: bool
CreateRegistryMembers.model_rebuild()
| CreateRegistryMembersResult |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 37378,
"end": 37618
} | class ____(ChainedSource):
def name(self) -> str:
return f"___as_tensor({self.base.name()})"
def guard_source(self) -> GuardSource:
return self.base.guard_source()
@dataclasses.dataclass(frozen=True)
| FloatTensorSource |
python | neetcode-gh__leetcode | python/0153-find-minimum-in-rotated-sorted-array.py | {
"start": 0,
"end": 540
} | class ____:
def findMin(self, nums: List[int]) -> int:
start , end = 0, len(nums) - 1
curr_min = float("inf")
while start < end :
mid = start + (end - start ) // 2
curr_min = min(curr_min,nums[mid])
# right has the min
if nums[mid] > nums[end]:
start = mid + 1
# left has the min
else:
end = mid - 1
return min(curr_min,nums[start])
| Solution |
python | scikit-learn__scikit-learn | sklearn/metrics/tests/test_score_objects.py | {
"start": 5023,
"end": 5163
} | class ____(BaseEstimator):
"""Dummy estimator to test scoring validators"""
def fit(self, X, y):
return self
| EstimatorWithFit |
python | pytorch__pytorch | test/test_mps.py | {
"start": 413790,
"end": 428415
} | class ____(TestCaseMPS):
def _compare_tensors(self, y, ref):
denom = torch.maximum(ref.abs(), torch.tensor([1e-6], device=ref.device, dtype=ref.dtype))
err = ((y - ref).abs() / denom).mean().item()
self.assertLess(err, 0.01)
def _test_sdpa_no_mask(
self,
is_causal: bool,
dtype: torch.dtype,
L: int = 1,
S: int = 72,
NH: int = 32,
HS: int = 128,
requires_grad: bool = False
):
torch.manual_seed(1729)
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
q = torch.randn([1, NH, L, HS], dtype=dtype, device="mps", requires_grad=requires_grad)
k = torch.randn([1, NH, S, HS], dtype=q.dtype, device="mps")
v = torch.randn([1, NH, S, HS], dtype=q.dtype, device="mps")
q_cpu = q.cpu().detach().cpu().requires_grad_(requires_grad)
k_cpu = k.cpu()
v_cpu = v.cpu()
y = F.scaled_dot_product_attention(q, k, v, dropout_p=0.0, is_causal=is_causal)
y_ref = F.scaled_dot_product_attention(q_cpu, k_cpu, v_cpu, dropout_p=0.0, is_causal=is_causal)
self._compare_tensors(y.cpu(), y_ref)
if requires_grad and torch.is_grad_enabled():
y.sum().backward()
y_ref.sum().backward()
self._compare_tensors(q.grad.cpu(), q_cpu.grad)
def test_sdpa_no_mask_no_causal_fp32(self):
self._test_sdpa_no_mask(False, torch.float32)
def test_sdpa_no_mask_no_causal_fp16(self):
self._test_sdpa_no_mask(False, torch.float16)
def test_sdpa_no_mask_causal_fp32(self):
self._test_sdpa_no_mask(True, torch.float32)
def test_sdpa_no_mask_causal_fp16(self):
self._test_sdpa_no_mask(True, torch.float16)
def test_sdpa_no_mask_causal_fp16_L7(self):
self._test_sdpa_no_mask(True, torch.float16, 7)
def test_sdpa_no_mask_causal_fp16_L7_S17(self):
self._test_sdpa_no_mask(True, torch.float16, 7, 17)
def test_sdpa_no_mask_causal_fp16_L7_S17_NH23_HS121(self):
self._test_sdpa_no_mask(True, torch.float16, 7, 17, 23, 121)
def test_sdpa_no_mask_no_causal_fp32_grad(self):
self._test_sdpa_no_mask(False, torch.float32, requires_grad=True)
with torch.no_grad():
self._test_sdpa_no_mask(False, torch.float32, requires_grad=True)
def _test_sdpa_mask(self, dtype: torch.dtype, L: int = 1, S: int = 72, NH: int = 32, HS: int = 128):
torch.manual_seed(1729)
causal_mask = torch.tril(torch.ones(S, S, dtype=torch.bool, device='mps'))
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
i = 42 if S > 42 else S // 2
q = torch.randn([1, NH, L, HS], dtype=dtype, device="mps")
k = torch.randn([1, NH, S, HS], dtype=q.dtype, device="mps")
v = torch.randn([1, NH, S, HS], dtype=q.dtype, device="mps")
input_pos = torch.tensor([i], dtype=torch.int32, device='mps')
mask = causal_mask[None, None, input_pos]
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
y_ref = F.scaled_dot_product_attention(q.cpu(), k.cpu(), v.cpu(), attn_mask=mask.cpu(), dropout_p=0.0, is_causal=False)
self._compare_tensors(y.cpu(), y_ref)
def test_sdpa_mask_fp32(self):
self._test_sdpa_mask(torch.float32)
# Test twice to catch https://github.com/pytorch/pytorch/issues/148194
self._test_sdpa_mask(torch.float32)
def test_sdpa_mask_fp16(self):
self._test_sdpa_mask(torch.float16)
def test_sdpa_mask_fp16_L6(self):
self._test_sdpa_mask(torch.float16, 6)
def test_sdpa_mask_fp16_L6_S17_NH23_HS121(self):
self._test_sdpa_mask(torch.float16, 7, 17, 23, 121)
# Regression test from: https://github.com/pytorch/pytorch/issues/156707
@parametrize("dtype", [torch.float16, torch.float32])
def test_sdpa_full_mask(self, dtype):
q = torch.randn(1, 1, 2, 4, dtype=dtype)
k = torch.randn(1, 1, 2, 4, dtype=dtype)
v = torch.randn(1, 1, 2, 4, dtype=dtype)
mask = torch.tensor([[[[False, False], [True, True]]]], dtype=torch.bool)
out_cpu = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
out_mps = F.scaled_dot_product_attention(q.to('mps'), k.to('mps'), v.to('mps'), attn_mask=mask.to('mps'))
self._compare_tensors(out_mps.cpu(), out_cpu)
@parametrize("dtype", [torch.float16, torch.float32])
def test_sdpa_3d_input(self, dtype):
head_num, seq_len, embed_dim = 16, 16, 80
q = torch.randn(head_num, seq_len, embed_dim, dtype=dtype)
k = torch.randn(head_num, seq_len, embed_dim, dtype=dtype)
v = torch.randn(head_num, seq_len, embed_dim, dtype=dtype)
attention_mask = torch.ones(1, seq_len, seq_len, dtype=dtype)
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
y = F.scaled_dot_product_attention(
q.to("mps"),
k.to("mps"),
v.to("mps"),
attention_mask.to("mps"),
dropout_p=0.0
)
y_ref = F.scaled_dot_product_attention(
q.to("cpu"),
k.to("cpu"),
v.to("cpu"),
attention_mask.to("cpu"),
dropout_p=0.0
)
self._compare_tensors(y.cpu(), y_ref)
@parametrize("dtype", [torch.float16, torch.float32])
def test_sdpa_no_mask_5d(
self,
dtype: torch.dtype,
B: int = 2,
extra: int = 3,
NH: int = 4,
L: int = 10,
HS: int = 16,
requires_grad: bool = False
):
torch.manual_seed(1729)
q = torch.randn(B, extra, NH, L, HS, dtype=dtype, device="mps", requires_grad=requires_grad)
k = torch.randn(B, extra, NH, L, HS, dtype=dtype, device="mps")
v = torch.randn(B, extra, NH, L, HS, dtype=dtype, device="mps")
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
y = F.scaled_dot_product_attention(q, k, v, dropout_p=0.0, is_causal=False)
y_ref = F.scaled_dot_product_attention(q.cpu(), k.cpu(), v.cpu(), dropout_p=0.0, is_causal=False)
self._compare_tensors(y.cpu(), y_ref)
if requires_grad and torch.is_grad_enabled():
y.sum().backward()
y_ref.sum().backward()
self._compare_tensors(q.grad.cpu(), q.cpu().grad)
@parametrize('dtype', [torch.float16, torch.float32])
def test_sdpa_mask_5d(
self,
dtype: torch.dtype,
B: int = 2,
extra: int = 3,
NH: int = 4,
L: int = 10,
HS: int = 16
):
torch.manual_seed(1729)
q = torch.randn(B, extra, NH, L, HS, dtype=dtype, device="mps")
k = torch.randn(B, extra, NH, L, HS, dtype=dtype, device="mps")
v = torch.randn(B, extra, NH, L, HS, dtype=dtype, device="mps")
mask = torch.tril(torch.ones(L, L, dtype=torch.bool, device="mps")).unsqueeze(0).unsqueeze(0)
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
y_ref = F.scaled_dot_product_attention(q.cpu(), k.cpu(), v.cpu(), attn_mask=mask.cpu(), dropout_p=0.0, is_causal=False)
self._compare_tensors(y.cpu(), y_ref)
@parametrize("dtype", [torch.float16, torch.float32])
@parametrize("is_causal", [True, False])
def test_sdpa_enable_gqa(self, dtype, is_causal):
q_heads = 32
key_heads = 16
L = 7
S = 17
HS = 23
q = torch.randn([2, q_heads, L, HS], dtype=dtype, device="mps")
k = torch.randn([2, key_heads, S, HS], dtype=dtype, device="mps")
v = torch.randn([2, key_heads, S, HS], dtype=dtype, device="mps")
y_ref = F.scaled_dot_product_attention(
q.cpu(), k.cpu(), v.cpu(), dropout_p=0.0, is_causal=is_causal, enable_gqa=True,
)
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
y = F.scaled_dot_product_attention(
q, k, v, dropout_p=0.0, is_causal=is_causal, enable_gqa=True,
)
self._compare_tensors(y.cpu(), y_ref)
@serialTest()
def test_sdpa_fp32_no_memory_leak(self):
def get_mps_memory_usage():
return (torch.mps.current_allocated_memory() / (1024 * 1024),
torch.mps.driver_allocated_memory() / (1024 * 1024))
batch_size, seq_len, num_heads, head_dim = 4, 128, 8, 64
query = torch.randn(batch_size, num_heads, seq_len, head_dim, device="mps", dtype=torch.float32)
key = torch.randn(batch_size, num_heads, seq_len, head_dim, device="mps", dtype=torch.float32)
value = torch.randn(batch_size, num_heads, seq_len, head_dim, device="mps", dtype=torch.float32)
memory_footprints = []
for _ in range(100):
output = F.scaled_dot_product_attention(query, key, value)
# synchronize to wait for the GPU computation to return
torch.mps.synchronize()
current_mem, driver_mem = get_mps_memory_usage()
memory_footprints.append((current_mem, driver_mem))
# 1 kB different maximum allowed value
torch.testing.assert_close(memory_footprints[-1], memory_footprints[0], atol=1e-3, rtol=1e-3)
def generate_qkv(self, batch: int, NH: int, q_len: int, s_len: int, head_dim: int, layout: str, dtype: torch.dtype):
if layout == "contiguous":
q = torch.randn(batch, NH, q_len, head_dim, dtype=dtype, device="mps")
k = torch.randn(batch, NH, s_len, head_dim, dtype=dtype, device="mps")
elif layout == "mT":
# Transpose head dimension and length
q = torch.randn(batch, NH, head_dim, q_len, dtype=dtype, device="mps").mT
k = torch.randn(batch, NH, head_dim, s_len, dtype=dtype, device="mps").mT
elif layout == "transpose_seq_head":
# Transpose length and number of heads
q = torch.randn(batch, q_len, NH, head_dim, dtype=dtype, device="mps").transpose(1, 2)
k = torch.randn(batch, s_len, NH, head_dim, dtype=dtype, device="mps").transpose(1, 2)
elif layout == "permute":
# Permute head dimension and length
q = torch.randn(batch, head_dim, NH, q_len, dtype=dtype, device="mps").permute(0, 2, 3, 1)
k = torch.randn(batch, head_dim, NH, s_len, dtype=dtype, device="mps").permute(0, 2, 3, 1)
else:
raise ValueError(f"Unknown layout: {layout}")
v = torch.randn(batch, NH, s_len, head_dim, dtype=dtype, device="mps")
return q, k, v
def run_fast_attention_test(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
with_mask: bool,
dropout_p: float = 0.0,
is_causal: bool = False,
):
q_len = q.shape[2]
s_len = k.shape[2]
if with_mask:
attn_mask = torch.zeros(q.shape[0], q.shape[1], q_len, s_len,
dtype=torch.bool, device=q.device)
attn_mask[..., s_len // 2:] = True
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
y = F.scaled_dot_product_attention(
q, k, v,
attn_mask=attn_mask,
dropout_p=dropout_p,
is_causal=is_causal,
)
y_ref = F.scaled_dot_product_attention(
q.cpu(),
k.cpu(),
v.cpu(),
attn_mask=attn_mask.cpu(),
dropout_p=dropout_p,
is_causal=is_causal,
)
else:
with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.MATH]):
y = F.scaled_dot_product_attention(
q, k, v,
dropout_p=dropout_p,
is_causal=is_causal,
)
y_ref = F.scaled_dot_product_attention(
q.cpu(),
k.cpu(),
v.cpu(),
dropout_p=dropout_p,
is_causal=is_causal,
)
self._compare_tensors(y.cpu(), y_ref)
@parametrize("dtype", [torch.float16, torch.float32])
@parametrize("layout", ["contiguous", "mT", "transpose_seq_head", "permute"])
@parametrize("head_dim", [64, 96, 128]) # 64, 96, 128 are for the fast kernel
@parametrize("with_mask", [True, False])
def test_fast_vector_attention(self, dtype: torch.dtype, layout: str, head_dim: int, with_mask: bool):
torch.manual_seed(1729)
batch = 1
NH = 2
q_len = 4 # <8 so that vector fast is eligible
s_len = 16 # smaller than 1024 so that we use the one–pass variant
q, k, v = self.generate_qkv(batch, NH, q_len, s_len, head_dim, layout, dtype)
self.run_fast_attention_test(q, k, v, with_mask)
@parametrize("dtype", [torch.float32]) # float16 underflows sometimes, which leads to flaky tests
@parametrize("layout", ["contiguous", "mT", "transpose_seq_head", "permute"])
@parametrize("with_mask", [True, False])
def test_fast_vector_attention_2pass(self, dtype: torch.dtype, layout: str, with_mask: bool):
torch.manual_seed(1729)
batch = 1
NH = 32
q_len = 8
s_len = 1024 # large enough to trigger the two–pass path
head_dim = 64 # supported head dimension for vector attention
q, k, v = self.generate_qkv(batch, NH, q_len, s_len, head_dim, layout, dtype)
self.run_fast_attention_test(q, k, v, with_mask)
@unittest.skip("Full attention fast kernel not implemented yet")
@parametrize("dtype", [torch.float16, torch.float32])
@parametrize("layout", ["contiguous", "mT"])
@parametrize("head_dim", [64, 80, 128]) # 64, 80, 128 are for the fast kernel
@parametrize("with_mask", [True, False])
def test_fast_full_attention(self, dtype: torch.dtype, layout: str, head_dim: int, with_mask: bool):
torch.manual_seed(1729)
batch = 1
NH = 2
q_len = 32 # threshold to trigger full fast attention path
s_len = 16
q, k, v = self.generate_qkv(batch, NH, q_len, s_len, head_dim, layout, dtype)
self.run_fast_attention_test(q, k, v, with_mask)
| TestSDPA |
python | run-llama__llama_index | llama-index-core/tests/prompts/test_mixin.py | {
"start": 653,
"end": 2153
} | class ____(PromptMixin):
def __init__(self) -> None:
self.mock_object_2 = MockObject2()
self._prompt_dict_1 = {
"summary": PromptTemplate("{summary}"),
"foo": PromptTemplate("{foo} {bar}"),
}
def _get_prompts(self) -> PromptDictType:
return self._prompt_dict_1
def _get_prompt_modules(self) -> PromptMixinType:
return {"mock_object_2": self.mock_object_2}
def _update_prompts(self, prompts: PromptDictType) -> None:
if "summary" in prompts:
self._prompt_dict_1["summary"] = prompts["summary"]
if "foo" in prompts:
self._prompt_dict_1["foo"] = prompts["foo"]
def test_prompt_mixin() -> None:
mock_obj1 = MockObject1()
prompts = mock_obj1.get_prompts()
assert prompts == {
"summary": PromptTemplate("{summary}"),
"foo": PromptTemplate("{foo} {bar}"),
"mock_object_2:abc": PromptTemplate("{abc} {def}"),
}
assert mock_obj1.mock_object_2.get_prompts() == {
"abc": PromptTemplate("{abc} {def}"),
}
# update prompts
mock_obj1.update_prompts(
{
"summary": PromptTemplate("{summary} testing"),
"mock_object_2:abc": PromptTemplate("{abc} {def} ghi"),
}
)
assert mock_obj1.get_prompts() == {
"summary": PromptTemplate("{summary} testing"),
"foo": PromptTemplate("{foo} {bar}"),
"mock_object_2:abc": PromptTemplate("{abc} {def} ghi"),
}
| MockObject1 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 685638,
"end": 686190
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("upvote_count", "viewer_can_upvote", "viewer_has_upvoted")
upvote_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="upvoteCount"
)
viewer_can_upvote = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="viewerCanUpvote"
)
viewer_has_upvoted = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="viewerHasUpvoted"
)
| Votable |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/back_populates/tutorial003_py310.py | {
"start": 257,
"end": 493
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
hero_id: int = Field(foreign_key="hero.id")
hero: "Hero" = Relationship(back_populates="powers")
| Power |
python | geekcomputers__Python | binary_search_tree.py | {
"start": 0,
"end": 313
} | class ____:
"""Class for node of a tree"""
def __init__(self, info):
"""Initialising a node"""
self.info = info
self.left = None
self.right = None
# self.level = None
def __str__(self):
return str(self.info)
def __del__(self):
del self
| Node |
python | google__python-fire | fire/docstrings.py | {
"start": 2664,
"end": 2765
} | class ____(ArgInfo):
pass
KwargInfo.__new__.__defaults__ = (None,) * len(KwargInfo._fields)
| KwargInfo |
python | aio-libs__aiohttp | tests/test_flowcontrol_streams.py | {
"start": 493,
"end": 5267
} | class ____:
async def test_read(self, stream: streams.StreamReader) -> None:
stream.feed_data(b"da")
res = await stream.read(1)
assert res == b"d"
assert not stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_read_resume_paused(self, stream: streams.StreamReader) -> None:
stream.feed_data(b"test")
stream._protocol._reading_paused = True
res = await stream.read(1)
assert res == b"t"
assert stream._protocol.pause_reading.called # type: ignore[attr-defined]
async def test_readline(self, stream: streams.StreamReader) -> None:
stream.feed_data(b"d\n")
res = await stream.readline()
assert res == b"d\n"
assert not stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_readline_resume_paused(self, stream: streams.StreamReader) -> None:
stream._protocol._reading_paused = True
stream.feed_data(b"d\n")
res = await stream.readline()
assert res == b"d\n"
assert stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_readany(self, stream: streams.StreamReader) -> None:
stream.feed_data(b"data")
res = await stream.readany()
assert res == b"data"
assert not stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_readany_resume_paused(self, stream: streams.StreamReader) -> None:
stream._protocol._reading_paused = True
stream.feed_data(b"data")
res = await stream.readany()
assert res == b"data"
assert stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_readchunk(self, stream: streams.StreamReader) -> None:
stream.feed_data(b"data")
res, end_of_http_chunk = await stream.readchunk()
assert res == b"data"
assert not end_of_http_chunk
assert not stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_readchunk_resume_paused(self, stream: streams.StreamReader) -> None:
stream._protocol._reading_paused = True
stream.feed_data(b"data")
res, end_of_http_chunk = await stream.readchunk()
assert res == b"data"
assert not end_of_http_chunk
assert stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_readexactly(self, stream: streams.StreamReader) -> None:
stream.feed_data(b"data")
res = await stream.readexactly(3)
assert res == b"dat"
assert not stream._protocol.resume_reading.called # type: ignore[attr-defined]
async def test_feed_data(self, stream: streams.StreamReader) -> None:
stream._protocol._reading_paused = False
stream.feed_data(b"datadata")
assert stream._protocol.pause_reading.called # type: ignore[attr-defined]
async def test_read_nowait(self, stream: streams.StreamReader) -> None:
stream._protocol._reading_paused = True
stream.feed_data(b"data1")
stream.feed_data(b"data2")
stream.feed_data(b"data3")
res = await stream.read(5)
assert res == b"data1"
assert stream._protocol.resume_reading.call_count == 0 # type: ignore[attr-defined]
res = stream.read_nowait(5)
assert res == b"data2"
assert stream._protocol.resume_reading.call_count == 0 # type: ignore[attr-defined]
res = stream.read_nowait(5)
assert res == b"data3"
assert stream._protocol.resume_reading.call_count == 1 # type: ignore[attr-defined]
stream._protocol._reading_paused = False
res = stream.read_nowait(5)
assert res == b""
assert stream._protocol.resume_reading.call_count == 1 # type: ignore[attr-defined]
async def test_resumed_on_eof(self, stream: streams.StreamReader) -> None:
stream.feed_data(b"data")
assert stream._protocol.pause_reading.call_count == 1 # type: ignore[attr-defined]
assert stream._protocol.resume_reading.call_count == 0 # type: ignore[attr-defined]
stream._protocol._reading_paused = True
stream.feed_eof()
assert stream._protocol.resume_reading.call_count == 1 # type: ignore[attr-defined]
async def test_stream_reader_eof_when_full() -> None:
loop = asyncio.get_event_loop()
protocol = BaseProtocol(loop=loop)
protocol.transport = asyncio.Transport()
stream = streams.StreamReader(protocol, 1024, loop=loop)
data_len = stream._high_water + 1
stream.feed_data(b"0" * data_len)
assert protocol._reading_paused
stream.feed_eof()
assert not protocol._reading_paused
| TestFlowControlStreamReader |
python | kamyu104__LeetCode-Solutions | Python/unique-substrings-with-equal-digit-frequency.py | {
"start": 69,
"end": 652
} | class ____(object):
def equalDigitFrequency(self, s):
"""
:type s: str
:rtype: int
"""
MOD = 10**9+7
D = 27
lookup = set()
for i in xrange(len(s)):
cnt = collections.Counter()
h = max_cnt = 0
for j in xrange(i, len(s)):
d = ord(s[j])-ord('0')+1
h = (h*D+d)%MOD
cnt[d] += 1
max_cnt = max(max_cnt, cnt[d])
if len(cnt)*max_cnt == j-i+1:
lookup.add(h)
return len(lookup)
| Solution |
python | getsentry__sentry | src/sentry/integrations/bitbucket_server/integration.py | {
"start": 6336,
"end": 7963
} | class ____:
"""
Start the OAuth dance by creating a request token
and redirecting the user to approve it.
"""
@method_decorator(csrf_exempt)
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
with IntegrationPipelineViewEvent(
IntegrationPipelineViewType.OAUTH_LOGIN,
IntegrationDomain.SOURCE_CODE_MANAGEMENT,
BitbucketServerIntegrationProvider.key,
).capture() as lifecycle:
if "oauth_token" in request.GET:
return pipeline.next_step()
config = pipeline.fetch_state("installation_data")
assert config is not None
client = BitbucketServerSetupClient(
config.get("url"),
config.get("consumer_key"),
config.get("private_key"),
config.get("verify_ssl"),
)
try:
request_token = client.get_request_token()
except ApiError as error:
lifecycle.record_failure(str(error), extra={"url": config.get("url")})
return pipeline.error(f"Could not fetch a request token from Bitbucket. {error}")
pipeline.bind_state("request_token", request_token)
if not request_token.get("oauth_token"):
lifecycle.record_failure("missing oauth_token", extra={"url": config.get("url")})
return pipeline.error("Missing oauth_token")
authorize_url = client.get_authorize_url(request_token)
return HttpResponseRedirect(authorize_url)
| OAuthLoginView |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/callbacks/fake_callback_handler.py | {
"start": 2965,
"end": 6215
} | class ____(BaseCallbackHandler, BaseFakeCallbackHandlerMixin):
"""Fake callback handler for testing."""
@property
def ignore_llm(self) -> bool:
"""Whether to ignore LLM callbacks."""
return self.ignore_llm_
@property
def ignore_chain(self) -> bool:
"""Whether to ignore chain callbacks."""
return self.ignore_chain_
@property
def ignore_agent(self) -> bool:
"""Whether to ignore agent callbacks."""
return self.ignore_agent_
@property
def ignore_retriever(self) -> bool:
"""Whether to ignore retriever callbacks."""
return self.ignore_retriever_
@override
def on_llm_start(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_llm_start_common()
@override
def on_llm_new_token(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_llm_new_token_common()
@override
def on_llm_end(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_llm_end_common()
@override
def on_llm_error(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_llm_error_common()
@override
def on_retry(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_retry_common()
@override
def on_chain_start(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_chain_start_common()
@override
def on_chain_end(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_chain_end_common()
@override
def on_chain_error(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_chain_error_common()
@override
def on_tool_start(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_tool_start_common()
@override
def on_tool_end(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_tool_end_common()
@override
def on_tool_error(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_tool_error_common()
@override
def on_agent_action(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_agent_action_common()
@override
def on_agent_finish(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_agent_finish_common()
@override
def on_text(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_text_common()
@override
def on_retriever_start(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_retriever_start_common()
@override
def on_retriever_end(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_retriever_end_common()
@override
def on_retriever_error(
self,
*args: Any,
**kwargs: Any,
) -> Any:
self.on_retriever_error_common()
def __deepcopy__(self, memo: dict) -> "FakeCallbackHandler": # type: ignore[override]
return self
| FakeCallbackHandler |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py | {
"start": 62413,
"end": 62644
} | class ____(Qwen3MoeDecoderLayer):
def __init__(self, config, layer_idx):
super().__init__(config, layer_idx)
self.self_attn = Qwen3OmniMoeThinkerTextAttention(config, layer_idx)
| Qwen3OmniMoeThinkerTextDecoderLayer |
python | walkccc__LeetCode | solutions/59. Spiral Matrix II/59.py | {
"start": 0,
"end": 557
} | class ____:
def generateMatrix(self, n: int) -> list[list[int]]:
ans = [[0] * n for _ in range(n)]
count = 1
for mn in range(n // 2):
mx = n - mn - 1
for i in range(mn, mx):
ans[mn][i] = count
count += 1
for i in range(mn, mx):
ans[i][mx] = count
count += 1
for i in range(mx, mn, -1):
ans[mx][i] = count
count += 1
for i in range(mx, mn, -1):
ans[i][mn] = count
count += 1
if n % 2 == 1:
ans[n // 2][n // 2] = count
return ans
| Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/pytest/test_parametrized_db_keys.py | {
"start": 1275,
"end": 1674
} | class ____:
# Regression test for https://github.com/HypothesisWorks/hypothesis/issues/3733
@given(x=st.text())
@pytest.mark.parametrize("i", range(2))
def test_method(self, x, i):
pass
@settings(suppress_health_check=[HealthCheck.function_scoped_fixture])
@given(x=st.text())
def test_method_fixture(self, x, fixt):
pass
| TestNoDifferingExecutorsHealthCheck |
python | Netflix__metaflow | metaflow/includefile.py | {
"start": 8702,
"end": 15325
} | class ____(Parameter):
"""
Includes a local file as a parameter for the flow.
`IncludeFile` behaves like `Parameter` except that it reads its value from a file instead of
the command line. The user provides a path to a file on the command line. The file contents
are saved as a read-only artifact which is available in all steps of the flow.
Parameters
----------
name : str
User-visible parameter name.
default : Union[str, Callable[ParameterContext, str]]
Default path to a local file. A function
implies that the parameter corresponds to a *deploy-time parameter*.
is_text : bool, optional, default None
Convert the file contents to a string using the provided `encoding`.
If False, the artifact is stored in `bytes`. A value of None is equivalent to
True.
encoding : str, optional, default None
Use this encoding to decode the file contexts if `is_text=True`. A value of None
is equivalent to "utf-8".
required : bool, optional, default None
Require that the user specified a value for the parameter.
`required=True` implies that the `default` is not used. A value of None is
equivalent to False
help : str, optional
Help text to show in `run --help`.
show_default : bool, default True
If True, show the default value in the help text. A value of None is equivalent
to True.
parser : Union[str, Callable[[str], Any]], optional, default None
If a callable, it is a function that can parse the file contents
into any desired format. If a string, the string should refer to
a function (like "my_parser_package.my_parser.my_parser_function") which should
be able to parse the file contents. If the name starts with a ".", it is assumed
to be relative to "metaflow".
"""
def __init__(
self,
name: str,
required: Optional[bool] = None,
is_text: Optional[bool] = None,
encoding: Optional[str] = None,
help: Optional[str] = None,
parser: Optional[Union[str, Callable[[str], Any]]] = None,
**kwargs: Dict[str, str]
):
self._includefile_overrides = {}
if is_text is not None:
self._includefile_overrides["is_text"] = is_text
if encoding is not None:
self._includefile_overrides["encoding"] = encoding
self._parser = parser
# NOTA: Right now, there is an issue where these can't be overridden by config
# in all circumstances. Ignoring for now.
super(IncludeFile, self).__init__(
name,
required=required,
help=help,
type=FilePathClass(
self._includefile_overrides.get("is_text", True),
self._includefile_overrides.get("encoding", "utf-8"),
),
**kwargs,
)
def init(self, ignore_errors=False):
super(IncludeFile, self).init(ignore_errors)
# This will use the values set explicitly in the args if present, else will
# use and remove from kwargs else will use True/utf-8
is_text = self._includefile_overrides.get(
"is_text", self.kwargs.pop("is_text", True)
)
encoding = self._includefile_overrides.get(
"encoding", self.kwargs.pop("encoding", "utf-8")
)
# If a default is specified, it needs to be uploaded when the flow is deployed
# (for example when doing a `step-functions create`) so we make the default
# be a DeployTimeField. This means that it will be evaluated in two cases:
# - by deploy_time_eval for `step-functions create` and related.
# - by Click when evaluating the parameter.
#
# In the first case, we will need to fully upload the file whereas in the
# second case, we can just return the string as the FilePath.convert method
# will take care of evaluating things.
v = self.kwargs.get("default")
if v is not None:
# If the default is a callable, we have two DeployTimeField:
# - the callable nature of the default will require us to "call" the default
# (so that is the outer DeployTimeField)
# - IncludeFile defaults are always DeployTimeFields (since they need to be
# uploaded)
#
# Therefore, if the default value is itself a callable, we will have
# a DeployTimeField (upload the file) wrapping another DeployTimeField
# (call the default)
if callable(v) and not isinstance(v, DeployTimeField):
# If default is a callable, make it a DeployTimeField (the inner one)
v = DeployTimeField(self.name, str, "default", v, return_str=True)
self.kwargs["default"] = DeployTimeField(
self.name,
str,
"default",
IncludeFile._eval_default(is_text, encoding, v),
print_representation=v,
)
def load_parameter(self, v):
if v is None:
return v
# Get the raw content from the file
content = v.decode(self.name, var_type="Parameter")
# If a parser is specified, use it to parse the content
if self._parser is not None:
try:
return ConfigInput._call_parser(self._parser, content, True)
except Exception as e:
raise MetaflowException(
"Failed to parse content in parameter '%s' using parser: %s"
% (self.name, str(e))
) from e
return content
@staticmethod
def _eval_default(is_text, encoding, default_path):
# NOTE: If changing name of this function, check comments that refer to it to
# update it.
def do_eval(ctx, deploy_time):
if isinstance(default_path, DeployTimeField):
d = default_path(deploy_time=deploy_time)
else:
d = default_path
if deploy_time:
fp = FilePathClass(is_text, encoding)
val = fp.convert(d, None, ctx)
if isinstance(val, DelayedEvaluationParameter):
val = val()
# At this point this is an IncludedFile, but we need to make it
# into a string so that it can be properly saved.
return json.dumps(val.descriptor)
else:
return d
return do_eval
| IncludeFile |
python | fastai__fastai | fastai/callback/schedule.py | {
"start": 7825,
"end": 14455
} | class ____(ParamScheduler):
"Training with exponentially growing learning rate"
def __init__(self, start_lr=1e-7, end_lr=10, num_it=100, stop_div=True):
if num_it < 6: num_it = 6
self.scheds = {'lr': [SchedExp(s, e) for (s,e) in zip(start_lr,end_lr)
] if is_listy(start_lr) else SchedExp(start_lr, end_lr)}
self.num_it,self.stop_div = num_it,stop_div
def before_fit(self):
super().before_fit()
path = self.path/self.model_dir
path.mkdir(parents=True, exist_ok=True)
self.tmp_d = tempfile.TemporaryDirectory(dir=path)
self.tmp_p = Path(self.tmp_d.name).stem
self.learn.save(f'{self.tmp_p}/_tmp')
self.best_loss = float('inf')
def before_batch(self): self._update_val(self.train_iter/self.num_it)
def after_batch(self):
super().after_batch()
if self.smooth_loss < self.best_loss: self.best_loss = self.smooth_loss
if self.smooth_loss > 4*self.best_loss and self.stop_div: raise CancelFitException()
if self.train_iter >= self.num_it: raise CancelFitException()
def before_validate(self): raise CancelValidException()
def after_fit(self):
self.learn.opt.zero_grad() # Needed before detaching the optimizer for future fits
tmp_f = self.path/self.model_dir/self.tmp_p/'_tmp.pth'
if tmp_f.exists():
self.learn.load(f'{self.tmp_p}/_tmp', with_opt=True)
self.tmp_d.cleanup()
_docs = {"before_fit": "Initialize container for hyper-parameters and save the model",
"before_batch": "Set the proper hyper-parameters in the optimizer",
"after_batch": "Record hyper-parameters of this batch and potentially stop training",
"after_fit": "Save the hyper-parameters in the recorder if there is one and load the original model",
"before_validate": "Skip the validation part of training"}
# %% ../../nbs/14_callback.schedule.ipynb 78
def valley(lrs:list, losses:list, num_it:int):
"Suggests a learning rate from the longest valley and returns its index"
n = len(losses)
max_start, max_end = 0,0
# find the longest valley
lds = [1]*n
for i in range(1,n):
for j in range(0,i):
if (losses[i] < losses[j]) and (lds[i] < lds[j] + 1):
lds[i] = lds[j] + 1
if lds[max_end] < lds[i]:
max_end = i
max_start = max_end - lds[max_end]
sections = (max_end - max_start) / 3
idx = max_start + int(sections) + int(sections/2)
return float(lrs[idx]), (float(lrs[idx]), losses[idx])
# %% ../../nbs/14_callback.schedule.ipynb 81
def slide(lrs:list, losses:list, num_it:int, lr_diff:int=15, thresh:float=.005, adjust_value:float=1.):
"Suggests a learning rate following an interval slide rule and returns its index"
losses = to_np(losses)
loss_grad = np.gradient(losses)
r_idx = -1
l_idx = r_idx - lr_diff
local_min_lr = lrs[l_idx]
while (l_idx >= -len(losses)) and (abs(loss_grad[r_idx] - loss_grad[l_idx]) > thresh):
local_min_lr = lrs[l_idx]
r_idx -= 1
l_idx -= 1
suggestion = float(local_min_lr) * adjust_value
idx = np.interp(np.log10(suggestion), np.log10(lrs), losses)
return suggestion, (suggestion, idx)
# %% ../../nbs/14_callback.schedule.ipynb 84
def minimum(lrs:list, losses:list, num_it:int):
"Suggests a learning rate one-tenth the minumum before divergance and returns its index"
lr_min = lrs[losses.argmin()].item()
loss_idx = losses[min(range(len(lrs)), key=lambda i: abs(lrs[i]-lr_min))]
return lr_min/10, (lr_min, loss_idx)
# %% ../../nbs/14_callback.schedule.ipynb 86
def steep(lrs:list, losses:list, num_it:int) -> (float, tuple):
"Suggests a learning rate when the slope is the steepest and returns its index"
grads = (losses[1:]-losses[:-1]) / (lrs[1:].log()-lrs[:-1].log())
lr_steep = lrs[grads.argmin()].item()
loss_idx = losses[min(range(len(lrs)), key=lambda i: abs(lrs[i]-lr_steep))]
return lr_steep, (lr_steep, loss_idx)
# %% ../../nbs/14_callback.schedule.ipynb 88
@patch
def plot_lr_find(self:Recorder, skip_end=5, return_fig=True, suggestions=None, nms=None, **kwargs):
"Plot the result of an LR Finder test (won't work if you didn't do `learn.lr_find()` before)"
lrs = self.lrs if skip_end==0 else self.lrs [:-skip_end]
losses = self.losses if skip_end==0 else self.losses[:-skip_end]
fig, ax = plt.subplots(1,1)
ax.plot(lrs, losses)
ax.set_ylabel("Loss")
ax.set_xlabel("Learning Rate")
ax.set_xscale('log')
if suggestions:
colors = plt.rcParams['axes.prop_cycle'].by_key()['color'][1:]
for (val, idx), nm, color in zip(suggestions, nms, colors):
ax.plot(val, idx, 'o', label=nm, c=color)
ax.legend(loc='best')
if return_fig: fig
# %% ../../nbs/14_callback.schedule.ipynb 89
mk_class("SuggestionMethod", **{o.__name__.capitalize():o for o in [valley,slide,minimum,steep]},
doc="All possible suggestion methods as convience attributes to get tab-completion and typo-proofing")
# %% ../../nbs/14_callback.schedule.ipynb 90
@patch
def lr_find(self:Learner, start_lr=1e-7, end_lr=10, num_it=100, stop_div=True, show_plot=True, suggest_funcs=(SuggestionMethod.Valley)):
"Launch a mock training to find a good learning rate and return suggestions based on `suggest_funcs` as a named tuple"
n_epoch = num_it//len(self.dls.train) + 1
cb=LRFinder(start_lr=start_lr, end_lr=end_lr, num_it=num_it, stop_div=stop_div)
with self.no_logging(): self.fit(n_epoch, cbs=cb)
if suggest_funcs is not None:
lrs, losses = tensor(self.recorder.lrs[num_it//10:-5]), tensor(self.recorder.losses[num_it//10:-5])
nan_idxs = torch.nonzero(torch.isnan(losses.view(-1)))
if len(nan_idxs) > 0:
drop_idx = min(nan_idxs)
lrs = lrs[:drop_idx]
losses = losses[:drop_idx]
_suggestions, nms = [], []
for func in tuplify(suggest_funcs):
nms.append(func.__name__ if not isinstance(func, partial) else func.func.__name__) # deal with partials
_suggestions.append(func(lrs, losses, num_it))
SuggestedLRs = collections.namedtuple('SuggestedLRs', nms)
lrs, pnts = [], []
for lr, pnt in _suggestions:
lrs.append(lr)
pnts.append(pnt)
if show_plot: self.recorder.plot_lr_find(suggestions=pnts, nms=nms)
return SuggestedLRs(*lrs)
elif show_plot: self.recorder.plot_lr_find()
| LRFinder |
python | numpy__numpy | numpy/lib/tests/test_nanfunctions.py | {
"start": 13130,
"end": 15726
} | class ____:
nanfuncs = {
np.nanmin: np.min,
np.nanmax: np.max,
np.nanargmin: np.argmin,
np.nanargmax: np.argmax,
np.nansum: np.sum,
np.nanprod: np.prod,
np.nancumsum: np.cumsum,
np.nancumprod: np.cumprod,
np.nanmean: np.mean,
np.nanmedian: np.median,
np.nanvar: np.var,
np.nanstd: np.std,
}
nanfunc_ids = [i.__name__ for i in nanfuncs]
@pytest.mark.parametrize("nanfunc,func", nanfuncs.items(), ids=nanfunc_ids)
@np.errstate(over="ignore")
def test_nanfunc(self, mat, dtype, nanfunc, func):
mat = mat.astype(dtype)
tgt = func(mat)
out = nanfunc(mat)
assert_almost_equal(out, tgt)
if dtype == "O":
assert type(out) is type(tgt)
else:
assert out.dtype == tgt.dtype
@pytest.mark.parametrize(
"nanfunc,func",
[(np.nanquantile, np.quantile), (np.nanpercentile, np.percentile)],
ids=["nanquantile", "nanpercentile"],
)
def test_nanfunc_q(self, mat, dtype, nanfunc, func):
mat = mat.astype(dtype)
if mat.dtype.kind == "c":
assert_raises(TypeError, func, mat, q=1)
assert_raises(TypeError, nanfunc, mat, q=1)
else:
tgt = func(mat, q=1)
out = nanfunc(mat, q=1)
assert_almost_equal(out, tgt)
if dtype == "O":
assert type(out) is type(tgt)
else:
assert out.dtype == tgt.dtype
@pytest.mark.parametrize(
"nanfunc,func",
[(np.nanvar, np.var), (np.nanstd, np.std)],
ids=["nanvar", "nanstd"],
)
def test_nanfunc_ddof(self, mat, dtype, nanfunc, func):
mat = mat.astype(dtype)
tgt = func(mat, ddof=0.5)
out = nanfunc(mat, ddof=0.5)
assert_almost_equal(out, tgt)
if dtype == "O":
assert type(out) is type(tgt)
else:
assert out.dtype == tgt.dtype
@pytest.mark.parametrize(
"nanfunc", [np.nanvar, np.nanstd]
)
def test_nanfunc_correction(self, mat, dtype, nanfunc):
mat = mat.astype(dtype)
assert_almost_equal(
nanfunc(mat, correction=0.5), nanfunc(mat, ddof=0.5)
)
err_msg = "ddof and correction can't be provided simultaneously."
with assert_raises_regex(ValueError, err_msg):
nanfunc(mat, ddof=0.5, correction=0.5)
with assert_raises_regex(ValueError, err_msg):
nanfunc(mat, ddof=1, correction=0)
| TestNanFunctions_NumberTypes |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride3.py | {
"start": 910,
"end": 961
} | class ____(D1, D2): ...
_T_E = TypeVar("_T_E")
| DSub |
python | gevent__gevent | src/greentest/3.10/test_wsgiref.py | {
"start": 19941,
"end": 20144
} | class ____(ErrorHandler):
"""Simple handler subclass for testing BaseHandler, w/error passthru"""
def handle_error(self):
raise # for testing, we want to see what's happening
| TestHandler |
python | django__django | tests/postgres_tests/models.py | {
"start": 2406,
"end": 2546
} | class ____(PostgreSQLModel):
field = HStoreField(blank=True, null=True)
array_field = ArrayField(HStoreField(), null=True)
| HStoreModel |
python | pytorch__pytorch | torch/_inductor/utils.py | {
"start": 113017,
"end": 114455
} | class ____:
type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND
override_return_dtype: Optional[torch.dtype]
op_dtype_propagation_rules: dict[str, OpDtypeRule] = {}
def register_op_dtype_propagation_rules(
name: str,
type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND,
override_return_dtype: Optional[torch.dtype],
) -> None:
op_dtype_propagation_rules[name] = OpDtypeRule(
type_promotion_kind, override_return_dtype
)
op_requires_libdevice_fp64: OrderedSet[str] = OrderedSet()
def register_op_requires_libdevice_fp64(name: str) -> None:
op_requires_libdevice_fp64.add(name)
def get_current_backend(device_type: Optional[str] = None) -> str:
from torch._inductor.virtualized import V
if not device_type:
device_type = V.graph.get_current_device_or_throw().type
if device_type == "cpu":
return config.cpu_backend
elif device_type == "mps":
return "mps"
elif device_type == "xpu":
return config.xpu_backend
else:
return config.cuda_backend
def upcast_compute_type(dtype: torch.dtype) -> torch.dtype:
"""Maybe upcast [b]float16 to float32"""
if (
dtype in (torch.float16, torch.bfloat16)
and config.triton.codegen_upcast_to_fp32
and get_current_backend() == "triton"
):
return torch.float32
return dtype
KeyType = TypeVar("KeyType")
ValType = TypeVar("ValType")
| OpDtypeRule |
python | pypa__pip | src/pip/_internal/distributions/installed.py | {
"start": 275,
"end": 929
} | class ____(AbstractDistribution):
"""Represents an installed package.
This does not need any preparation as the required information has already
been computed.
"""
@property
def build_tracker_id(self) -> str | None:
return None
def get_metadata_distribution(self) -> BaseDistribution:
assert self.req.satisfied_by is not None, "not actually installed"
return self.req.satisfied_by
def prepare_distribution_metadata(
self,
build_env_installer: BuildEnvironmentInstaller,
build_isolation: bool,
check_build_deps: bool,
) -> None:
pass
| InstalledDistribution |
python | ray-project__ray | python/ray/_private/runtime_env/plugin_schema_manager.py | {
"start": 258,
"end": 3504
} | class ____:
"""This manager is used to load plugin json schemas."""
default_schema_path = os.path.join(
os.path.dirname(__file__), "../../runtime_env/schemas"
)
schemas = {}
loaded = False
@classmethod
def _load_schemas(cls, schema_paths: List[str]):
for schema_path in schema_paths:
try:
with open(schema_path) as f:
schema = json.load(f)
except json.decoder.JSONDecodeError:
logger.error("Invalid runtime env schema %s, skip it.", schema_path)
continue
except OSError:
logger.error("Cannot open runtime env schema %s, skip it.", schema_path)
continue
if "title" not in schema:
logger.error(
"No valid title in runtime env schema %s, skip it.", schema_path
)
continue
if schema["title"] in cls.schemas:
logger.error(
"The 'title' of runtime env schema %s conflicts with %s, skip it.",
schema_path,
cls.schemas[schema["title"]],
)
continue
cls.schemas[schema["title"]] = schema
@classmethod
def _load_default_schemas(cls):
schema_json_files = list()
for root, _, files in os.walk(cls.default_schema_path):
for f in files:
if f.endswith(RAY_RUNTIME_ENV_PLUGIN_SCHEMA_SUFFIX):
schema_json_files.append(os.path.join(root, f))
logger.debug(
f"Loading the default runtime env schemas: {schema_json_files}."
)
cls._load_schemas(schema_json_files)
@classmethod
def _load_schemas_from_env_var(cls):
# The format of env var:
# "/path/to/env_1_schema.json,/path/to/env_2_schema.json,/path/to/schemas_dir/"
schema_paths = os.environ.get(RAY_RUNTIME_ENV_PLUGIN_SCHEMAS_ENV_VAR)
if schema_paths:
schema_json_files = list()
for path in schema_paths.split(","):
if path.endswith(RAY_RUNTIME_ENV_PLUGIN_SCHEMA_SUFFIX):
schema_json_files.append(path)
elif os.path.isdir(path):
for root, _, files in os.walk(path):
for f in files:
if f.endswith(RAY_RUNTIME_ENV_PLUGIN_SCHEMA_SUFFIX):
schema_json_files.append(os.path.join(root, f))
logger.info(
f"Loading the runtime env schemas from env var: {schema_json_files}."
)
cls._load_schemas(schema_json_files)
@classmethod
def validate(cls, name, instance):
if not cls.loaded:
# Load the schemas lazily.
cls._load_default_schemas()
cls._load_schemas_from_env_var()
cls.loaded = True
# if no schema matches, skip the validation.
if name in cls.schemas:
jsonschema.validate(instance=instance, schema=cls.schemas[name])
@classmethod
def clear(cls):
cls.schemas.clear()
cls.loaded = False
| RuntimeEnvPluginSchemaManager |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 59851,
"end": 60054
} | class ____(themeable):
"""
Length of ticks in the legend
Parameters
----------
theme_element : float
A good value should be in the range `[0, 0.5]`.
"""
| legend_ticks_length |
python | geekcomputers__Python | BlackJack_game/blackjack_simulate.py | {
"start": 11646,
"end": 19598
} | class ____:
def __init__(self, username):
self.deck = Deck()
self.dealer = Dealer("Bob")
self.player = Player(username.title(), 1000)
self.recorder = Recorder()
self.go_on = True
self.first_hand = True
self.choice = None
self.winner = None
self.bust = False
self.res = None
def play(self):
while self.player.chips:
self.initial_game()
self.in_bet()
self.deal_card()
while self.go_on:
self.choice = self.menu()
# self.player.speak()
self.chips_manage()
try:
self.card_manage()
except ValueError as res:
self.bust = True
self.go_on = False
self.res = res
if not self.bust:
self.is_surrender()
self.winner = self.get_winner()
self.res = "Winner is " + self.winner
os.system("clear")
self.calculate_chips()
self.result_exhibit()
self.dealer.unveiling()
self.player.unveiling()
self.recorder.record(
self.winner,
self.player.chips.amount,
self.player.point,
self.dealer.point,
)
self.recorder.draw_diagram()
ending = "\n\tSorry I lost all chips!\n\tTime to say goodbye."
self.player.speak(ending)
print("\n" + "-" * 20 + " End Game " + "-" * 20)
def initial_game(self):
self.go_on = True
self.first_hand = True
self.choice = None
self.winner = None
self.bust = False
self.deck.rebuilt()
self.deck.shuffle()
self.player.chips.reset_chip()
self.player.drop_card()
self.player.refresh_prompt()
self.dealer.drop_card()
print("\n" + "-" * 20 + " Start Game " + "-" * 20)
def in_bet(self):
in_bet = "\n\tI want to bet: "
not_invalid = True
self.player.speak(in_bet, end_char="")
while not_invalid:
try:
self.player.chips.bet_amount = input()
except ValueError as e:
print(e)
self.player.speak(in_bet, end_char="")
continue
except KeyboardInterrupt:
print("")
self.recorder.draw_diagram()
quit()
else:
self.player.refresh_prompt()
# self.player.speak()
not_invalid = False
def deal_card(self):
# dealer
self.dealer.obtain_card(self.deck, face=False)
self.dealer.obtain_card(self.deck)
# player
self.player.obtain_card(self.deck)
self.player.obtain_card(self.deck)
self.dealer.showing()
self.player.showing()
def menu(self):
pattern = "HS"
if self.first_hand:
pattern += "U"
if self.dealer.hand[1].rank == 1 and self.player.chips.current_amount():
pattern += "I"
self.dealer.ask_insurance()
if self.player.is_point(">", 10) and self.player.chips.can_double():
pattern += "D"
self.first_hand = False
choices = self.player.select_choice(pattern)
select = self.get_select(len(choices), general_err="Select above number.")
return choices[select]
@staticmethod
def get_select(select_max, prompt=">> ", general_err=""):
while True:
try:
value = input(prompt)
select = int(value)
if select > select_max:
raise ValueError
except ValueError:
print(general_err)
continue
except KeyboardInterrupt:
print("")
quit()
else:
return select
def chips_manage(self):
if self.choice == "Insurance":
err = "The amount should under " + str(self.player.chips.current_amount())
pay_ins = self.get_select(
self.player.chips.current_amount(),
prompt="Insurance amount >> ",
general_err=err,
)
self.player.chips.insurance = pay_ins
if self.choice == "Double-down":
try:
self.player.chips.double_bet()
except ValueError as e:
print(e)
self.player.refresh_prompt()
if self.choice in ("Insurance", "Double-down", "Surrender"):
self.go_on = False
def card_manage(self):
if self.choice in ("Hit", "Double-down"):
self.player.obtain_card(self.deck)
if self.player.is_point(">", BLACK_JACK):
raise ValueError("Player BUST")
else:
self.dealer.strategy_trigger(self.deck)
if self.dealer.is_point(">", BLACK_JACK):
raise ValueError("Dealer BUST")
elif self.choice != "Surrender":
if not self.player.chips.is_insurance:
self.dealer.strategy_trigger(self.deck)
if self.dealer.is_point(">", BLACK_JACK):
raise ValueError("Dealer BUST")
self.dealer.showing()
self.player.showing()
if self.choice in ("Double-down", "Stand"):
self.go_on = False
def is_surrender(self):
if self.choice == "Surrender":
self.player.speak("Sorry, I surrender....\n")
def get_winner(self):
if self.bust:
return "Dealer" if self.player.is_point(">", BLACK_JACK) else "Player"
if self.choice == "Surrender":
return "Dealer"
elif self.choice == "Insurance":
if self.player.is_point("==", BLACK_JACK):
return "Dealer"
return "Player"
if self.choice in ("Double-down", "Stand"):
self.player.calculate_point()
self.dealer.calculate_point()
if self.player.point > self.dealer.point:
return "Player"
return "Dealer"
return "Both"
def calculate_chips(self):
if self.choice == "Surrender":
if self.player.chips.bet_amount == 1:
if self.player.chips.current_amount() == 0:
self.player.chips.amount = 0
else:
surrender_amount = self.player.chips.bet_amount // 2
self.player.chips.amount -= surrender_amount
elif self.choice in ("Double-down", "Stand", "Insurance", "Hit"):
if self.winner == "Player":
self.player.chips.amount += (
self.player.chips.bet_amount + self.player.chips.insurance * 2
)
elif self.winner == "Dealer":
self.player.chips.amount -= (
self.player.chips.bet_amount + self.player.chips.insurance
)
def result_exhibit(self):
def get_color():
if "BUST" in content:
return COLOR.get("RED" if "Player" in content else "GREEN")
if self.winner == "Player":
return COLOR.get("GREEN")
elif self.winner == "Dealer":
return COLOR.get("RED")
else:
return COLOR.get("YELLOW")
end = COLOR.get("END")
content = str(self.res)
color = get_color()
winner_fmt = color + "\n\t>> {content} <<\n" + end
print(winner_fmt.format(content=content))
def main():
try:
user_name = input("What is your name: ")
except KeyboardInterrupt:
print("")
else:
black_jack = BlackJack(username=user_name)
black_jack.play()
if __name__ == "__main__":
main()
| BlackJack |
python | plotly__plotly.py | plotly/graph_objs/layout/slider/_font.py | {
"start": 235,
"end": 9878
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.slider"
_path_str = "layout.slider.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets the font of the slider step labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.slider.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.layout.slider.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.slider.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | PrefectHQ__prefect | tests/blocks/test_notifications.py | {
"start": 29608,
"end": 35033
} | class ____:
URL_PARAMS = {
# default notify format
"format": "html",
# default overflow mode
"overflow": "upstream",
}
async def test_notify_async(self):
with patch("apprise.Apprise", autospec=True) as AppriseMock:
apprise_instance_mock = AppriseMock.return_value
apprise_instance_mock.async_notify = AsyncMock()
sg_block = SendgridEmail(
api_key="test-api-key",
sender_email="test@gmail.com",
to_emails=["test1@gmail.com", "test2@gmail.com"],
)
await sg_block.notify("test")
# Apprise is called once during initialization
AppriseMock.assert_called_once()
# check if the Apprise().add function is called with correct url
url = f"sendgrid://{sg_block.api_key.get_secret_value()}:{sg_block.sender_email}/"
url += "/".join(
[urllib.parse.quote(email, safe="") for email in sg_block.to_emails]
)
url += "?"
url += urllib.parse.urlencode(TestSendgridEmail.URL_PARAMS)
# add() should be called twice: once in constructor, once in notify update
assert apprise_instance_mock.add.call_count == 2
for call in apprise_instance_mock.add.call_args_list:
assert call.kwargs["servers"] == url
# clear() should be called once during notify to update emails
apprise_instance_mock.clear.assert_called_once()
apprise_instance_mock.async_notify.assert_awaited_once_with(
body="test", title="", notify_type=PREFECT_NOTIFY_TYPE_DEFAULT
)
def test_notify_sync(self):
with patch("apprise.Apprise", autospec=True) as AppriseMock:
apprise_instance_mock = AppriseMock.return_value
apprise_instance_mock.async_notify = AsyncMock()
sg_block = SendgridEmail(
api_key="test-api-key",
sender_email="test@gmail.com",
to_emails=["test1@gmail.com", "test2@gmail.com"],
)
@flow
def test_flow():
sg_block.notify("test")
test_flow()
# check if the Apprise().add function is called with correct url
url = f"sendgrid://{sg_block.api_key.get_secret_value()}:{sg_block.sender_email}/"
url += "/".join(
[urllib.parse.quote(email, safe="") for email in sg_block.to_emails]
)
url += "?"
url += urllib.parse.urlencode(TestSendgridEmail.URL_PARAMS)
# Apprise is called once during initialization
AppriseMock.assert_called_once()
# add() should be called twice: once in constructor, once in notify update
assert apprise_instance_mock.add.call_count == 2
for call in apprise_instance_mock.add.call_args_list:
assert call.kwargs["servers"] == url
# clear() should be called once during notify to update emails
apprise_instance_mock.clear.assert_called_once()
apprise_instance_mock.async_notify.assert_called_once_with(
body="test", title="", notify_type=PREFECT_NOTIFY_TYPE_DEFAULT
)
def test_is_picklable(self):
block = SendgridEmail(
api_key="test-api-key",
sender_email="test@gmail.com",
to_emails=["test1@gmail.com", "test2@gmail.com"],
)
pickled = cloudpickle.dumps(block)
unpickled = cloudpickle.loads(pickled)
assert isinstance(unpickled, SendgridEmail)
def test_notify_uses_updated_to_emails(self):
"""Test that notify() uses programmatically updated to_emails."""
with patch("apprise.Apprise", autospec=True) as AppriseMock:
apprise_instance_mock = AppriseMock.return_value
apprise_instance_mock.async_notify = AsyncMock()
# Create block with empty recipients
sg_block = SendgridEmail(
api_key="test-api-key",
sender_email="test@gmail.com",
to_emails=[],
)
# Update recipients programmatically
sg_block.to_emails = ["updated@gmail.com"]
# Call notify - should use updated recipients
sg_block.notify("test")
# Verify that add() was called twice: once in constructor (empty), once in notify (updated)
add_calls = apprise_instance_mock.add.call_args_list
assert len(add_calls) == 2
# The second call should have the updated email in the URL
updated_url = add_calls[1].kwargs["servers"]
assert "updated%40gmail.com" in updated_url
# The first call should have empty targets (since to_emails was [])
initial_url = add_calls[0].kwargs["servers"]
# With empty to_emails, the URL should still be valid but have no targets in path
assert initial_url.startswith("sendgrid://")
assert "updated%40gmail.com" not in initial_url
# Apprise should be called once during initialization only
AppriseMock.assert_called_once()
# clear() should be called once to update the email list
apprise_instance_mock.clear.assert_called_once()
| TestSendgridEmail |
python | realpython__materials | rp-portfolio/projects/admin.py | {
"start": 71,
"end": 163
} | class ____(admin.ModelAdmin):
pass
admin.site.register(Project, ProjectAdmin)
| ProjectAdmin |
python | allegroai__clearml | clearml/binding/frameworks/tensorflow_bind.py | {
"start": 43173,
"end": 52806
} | class ____(object):
_current_task = None
__original_getattribute = None
__original_getattributeX = None
__patched = False
_original_add_event = None
_original_add_eventT = None
_original_add_eventX = None
defaults_dict = dict(
report_freq=1,
image_report_freq=1,
histogram_update_freq_multiplier=5,
histogram_granularity=50,
)
@staticmethod
def trains_object(
self,
) -> Union[EventTrainsWriter, Dict[str, Any], None]:
if isinstance(self.event_writer, ProxyEventsWriter):
# noinspection PyProtectedMember
trains_writer = [e for e in self.event_writer._events if isinstance(e, EventTrainsWriter)]
return trains_writer[0] if trains_writer else None
elif isinstance(self.event_writer, EventTrainsWriter):
return self.event_writer
if not self.__dict__.get("_trains_defaults"):
self.__dict__["_trains_defaults"] = {}
return self.__dict__["_trains_defaults"]
@staticmethod
def update_current_task(task: Any, **kwargs: Any) -> None:
PatchSummaryToEventTransformer.defaults_dict.update(kwargs)
PatchSummaryToEventTransformer._current_task = task
if not task:
return
if not PatchSummaryToEventTransformer.__patched:
PatchSummaryToEventTransformer.__patched = True
# make sure we patched the SummaryToEventTransformer
PatchSummaryToEventTransformer._patch_summary_to_event_transformer()
PostImportHookPatching.add_on_import(
"tensorflow",
PatchSummaryToEventTransformer._patch_summary_to_event_transformer,
)
PostImportHookPatching.add_on_import(
"torch",
PatchSummaryToEventTransformer._patch_summary_to_event_transformer,
)
PostImportHookPatching.add_on_import(
"tensorboardX",
PatchSummaryToEventTransformer._patch_summary_to_event_transformer,
)
@staticmethod
def _patch_summary_to_event_transformer() -> None:
if "tensorflow" in sys.modules:
try:
from tensorflow.python.summary.writer.writer import (
SummaryToEventTransformer,
) # noqa
# only patch once
if PatchSummaryToEventTransformer.__original_getattribute is None:
PatchSummaryToEventTransformer.__original_getattribute = SummaryToEventTransformer.__getattribute__
SummaryToEventTransformer.__getattribute__ = PatchSummaryToEventTransformer._patched_getattribute
setattr(
SummaryToEventTransformer,
"clearml",
property(PatchSummaryToEventTransformer.trains_object),
)
except Exception as ex:
LoggerRoot.get_base_logger(TensorflowBinding).debug(str(ex))
if "torch" in sys.modules:
try:
# only patch once
if PatchSummaryToEventTransformer._original_add_eventT is None:
# noinspection PyUnresolvedReferences
from torch.utils.tensorboard.writer import (
FileWriter as FileWriterT,
) # noqa
PatchSummaryToEventTransformer._original_add_eventT = FileWriterT.add_event
FileWriterT.add_event = PatchSummaryToEventTransformer._patched_add_eventT
setattr(FileWriterT, "clearml", None)
except ImportError:
# this is a new version of TensorflowX
pass
except Exception as ex:
LoggerRoot.get_base_logger(TensorflowBinding).debug(str(ex))
if "tensorboardX" in sys.modules:
try:
# only patch once
if PatchSummaryToEventTransformer.__original_getattributeX is None:
# noinspection PyUnresolvedReferences
from tensorboardX.writer import (
SummaryToEventTransformer as SummaryToEventTransformerX,
) # noqa
PatchSummaryToEventTransformer.__original_getattributeX = (
SummaryToEventTransformerX.__getattribute__
)
SummaryToEventTransformerX.__getattribute__ = PatchSummaryToEventTransformer._patched_getattributeX
setattr(
SummaryToEventTransformerX,
"clearml",
property(PatchSummaryToEventTransformer.trains_object),
)
except ImportError:
# this is a new version of TensorflowX
pass
except Exception as ex:
LoggerRoot.get_base_logger(TensorflowBinding).debug(str(ex))
if PatchSummaryToEventTransformer.__original_getattributeX is None:
try:
# only patch once
if PatchSummaryToEventTransformer._original_add_eventX is None:
from tensorboardX.writer import (
FileWriter as FileWriterX,
) # noqa
PatchSummaryToEventTransformer._original_add_eventX = FileWriterX.add_event
FileWriterX.add_event = PatchSummaryToEventTransformer._patched_add_eventX
setattr(FileWriterX, "clearml", None)
except ImportError:
# this is a new version of TensorflowX
pass
except Exception as ex:
LoggerRoot.get_base_logger(TensorflowBinding).debug(str(ex))
@staticmethod
def _patched_add_eventT(self, *args: Any, **kwargs: Any) -> None:
if not hasattr(self, "clearml") or not PatchSummaryToEventTransformer._current_task:
return PatchSummaryToEventTransformer._original_add_eventT(self, *args, **kwargs)
if not self.clearml: # noqa
# noinspection PyBroadException
try:
logdir = self.get_logdir()
except Exception:
logdir = None
self.clearml = EventTrainsWriter(
PatchSummaryToEventTransformer._current_task.get_logger(),
logdir=logdir,
**PatchSummaryToEventTransformer.defaults_dict
)
# noinspection PyBroadException
try:
self.clearml.add_event(*args, **kwargs)
except Exception:
pass
return PatchSummaryToEventTransformer._original_add_eventT(self, *args, **kwargs)
@staticmethod
def _patched_add_eventX(self, *args: Any, **kwargs: Any) -> Any:
if not hasattr(self, "clearml") or not PatchSummaryToEventTransformer._current_task:
return PatchSummaryToEventTransformer._original_add_eventX(self, *args, **kwargs)
if not self.clearml:
# noinspection PyBroadException
try:
logdir = self.get_logdir()
except Exception:
logdir = None
self.clearml = EventTrainsWriter(
PatchSummaryToEventTransformer._current_task.get_logger(),
logdir=logdir,
**PatchSummaryToEventTransformer.defaults_dict
)
# noinspection PyBroadException
try:
self.clearml.add_event(*args, **kwargs)
except Exception:
pass
return PatchSummaryToEventTransformer._original_add_eventX(self, *args, **kwargs)
@staticmethod
def _patched_getattribute(self, attr: str) -> Any:
get_base = PatchSummaryToEventTransformer.__original_getattribute
return PatchSummaryToEventTransformer._patched_getattribute_(self, attr, get_base)
@staticmethod
def _patched_getattributeX(self, attr: str) -> Any:
get_base = PatchSummaryToEventTransformer.__original_getattributeX
return PatchSummaryToEventTransformer._patched_getattribute_(self, attr, get_base)
@staticmethod
def _patched_getattribute_(self, attr: str, get_base: Callable[[Any, str], Any]) -> Any:
# no main task, zero chance we have an ClearML event logger
if PatchSummaryToEventTransformer._current_task is None:
return get_base(self, attr)
# check if we already have an ClearML event logger
__dict__ = get_base(self, "__dict__")
if "event_writer" not in __dict__ or isinstance(
__dict__["event_writer"], (ProxyEventsWriter, EventTrainsWriter)
):
return get_base(self, attr)
# patch the events writer field, and add a double Event Logger (ClearML and original)
base_eventwriter = __dict__["event_writer"]
# noinspection PyBroadException
try:
logdir = base_eventwriter.get_logdir()
except Exception:
logdir = None
defaults_dict = __dict__.get("_trains_defaults") or PatchSummaryToEventTransformer.defaults_dict
trains_event = EventTrainsWriter(
PatchSummaryToEventTransformer._current_task.get_logger(), logdir=logdir, **defaults_dict
)
# order is important, the return value of ProxyEventsWriter is the last object in the list
__dict__["event_writer"] = ProxyEventsWriter([trains_event, base_eventwriter])
return get_base(self, attr)
| PatchSummaryToEventTransformer |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 11336,
"end": 11562
} | class ____(Where):
"""Not contains comparison for document content"""
key: str
content: str
def to_dict(self) -> Dict[str, Any]:
return {self.key: {"$not_contains": self.content}}
@dataclass
| NotContains |
python | getsentry__sentry | src/sentry/api/endpoints/organization_sdk_deprecations.py | {
"start": 877,
"end": 992
} | class ____(TypedDict):
projectId: str
minimumVersion: str
sdkName: str
sdkVersion: str
| SDKDeprecation |
python | h5py__h5py | h5py/_hl/group.py | {
"start": 29812,
"end": 30297
} | class ____:
"""
Represents a symbolic ("soft") link in an HDF5 file. The path
may be absolute or relative. No checking is performed to ensure
that the target actually exists.
"""
@property
def path(self):
""" Soft link value. Not guaranteed to be a valid path. """
return self._path
def __init__(self, path):
self._path = str(path)
def __repr__(self):
return '<SoftLink to "%s">' % self.path
| SoftLink |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/model_service.py | {
"start": 4762,
"end": 8297
} | class ____(GoogleCloudBaseOperator):
"""
Retrieves a Model.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param model_id: Required. The ID of the Model resource to be retrieved.
Could be in format `projects/{project}/locations/{location}/models/{model_id}@{version_id}` or
`projects/{project}/locations/{location}/models/{model_id}@{version_alias}` if model has
several versions.
:param retry: Designation of what errors, if any, should be retried.
:param timeout: The timeout for this request.
:param metadata: Strings which should be sent along with the request as metadata.
:param gcp_conn_id: The connection ID to use connecting to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields = ("region", "model_id", "project_id", "impersonation_chain")
operator_extra_links = (VertexAIModelLink(),)
def __init__(
self,
*,
region: str,
project_id: str,
model_id: str,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.region = region
self.project_id = project_id
self.model_id = model_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
@property
def extra_links_params(self) -> dict[str, Any]:
return {
"region": self.region,
"project_id": self.project_id,
}
def execute(self, context: Context):
hook = ModelServiceHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
self.model_id = self.model_id.rpartition("@")[0] if "@" in self.model_id else self.model_id
try:
self.log.info("Retrieving model: %s", self.model_id)
model = hook.get_model(
project_id=self.project_id,
region=self.region,
model_id=self.model_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
self.log.info("Model found. Model ID: %s", self.model_id)
context["ti"].xcom_push(key="model_id", value=self.model_id)
VertexAIModelLink.persist(context=context, model_id=self.model_id)
return Model.to_dict(model)
except NotFound:
self.log.info("The Model ID %s does not exist.", self.model_id)
| GetModelOperator |
python | jazzband__django-simple-history | simple_history/registry_tests/tests.py | {
"start": 2648,
"end": 3038
} | class ____(unittest.TestCase):
def test_accessor_default(self):
register(UserAccessorDefault)
self.assertFalse(hasattr(User, "historicaluseraccessordefault_set"))
def test_accessor_override(self):
register(UserAccessorOverride, user_related_name="my_history_model_accessor")
self.assertTrue(hasattr(User, "my_history_model_accessor"))
| TestUserAccessor |
python | ethereum__web3.py | web3/eth/eth.py | {
"start": 1710,
"end": 20433
} | class ____(BaseEth):
# mypy types
w3: "Web3"
_default_contract_factory: type[Contract | ContractCaller] = Contract
# eth_accounts
_accounts: Method[Callable[[], tuple[ChecksumAddress]]] = Method(
RPC.eth_accounts,
is_property=True,
)
@property
def accounts(self) -> tuple[ChecksumAddress]:
return self._accounts()
# eth_blobBaseFee
_eth_blobBaseFee: Method[Callable[[], Wei]] = Method(
RPC.eth_blobBaseFee,
is_property=True,
)
@property
def blob_base_fee(self) -> Wei:
return self._eth_blobBaseFee()
# eth_blockNumber
get_block_number: Method[Callable[[], BlockNumber]] = Method(
RPC.eth_blockNumber,
is_property=True,
)
@property
def block_number(self) -> BlockNumber:
return self.get_block_number()
# eth_chainId
_chain_id: Method[Callable[[], int]] = Method(
RPC.eth_chainId,
is_property=True,
)
@property
def chain_id(self) -> int:
return self._chain_id()
# eth_gasPrice
_gas_price: Method[Callable[[], Wei]] = Method(
RPC.eth_gasPrice,
is_property=True,
)
@property
def gas_price(self) -> Wei:
return self._gas_price()
# eth_maxPriorityFeePerGas
_max_priority_fee: Method[Callable[[], Wei]] = Method(
RPC.eth_maxPriorityFeePerGas,
is_property=True,
)
@property
def max_priority_fee(self) -> Wei:
"""
Try to use eth_maxPriorityFeePerGas but, since this is not part
of the spec and is only supported by some clients, fall back to
an eth_feeHistory calculation with min and max caps.
"""
try:
return self._max_priority_fee()
except Web3RPCError:
warnings.warn(
"There was an issue with the method eth_maxPriorityFeePerGas. "
"Calculating using eth_feeHistory.",
stacklevel=2,
)
return fee_history_priority_fee(self)
# eth_syncing
_syncing: Method[Callable[[], SyncStatus | bool]] = Method(
RPC.eth_syncing,
is_property=True,
)
@property
def syncing(self) -> SyncStatus | bool:
return self._syncing()
# eth_feeHistory
_fee_history: Method[
Callable[[int, BlockParams | BlockNumber, list[float] | None], FeeHistory]
] = Method(RPC.eth_feeHistory, mungers=[default_root_munger])
def fee_history(
self,
block_count: int,
newest_block: BlockParams | BlockNumber,
reward_percentiles: list[float] | None = None,
) -> FeeHistory:
reward_percentiles = reward_percentiles or []
return self._fee_history(block_count, newest_block, reward_percentiles)
# eth_call
_call: Method[
Callable[
[TxParams, BlockIdentifier | None, StateOverride | None],
HexBytes,
]
] = Method(RPC.eth_call, mungers=[BaseEth.call_munger])
def call(
self,
transaction: TxParams,
block_identifier: BlockIdentifier | None = None,
state_override: StateOverride | None = None,
ccip_read_enabled: bool | None = None,
) -> HexBytes:
ccip_read_enabled_on_provider = self.w3.provider.global_ccip_read_enabled
if (
# default conditions:
ccip_read_enabled_on_provider
and ccip_read_enabled is not False
# explicit call flag overrides provider flag,
# enabling ccip read for specific calls:
or not ccip_read_enabled_on_provider
and ccip_read_enabled is True
):
return self._durin_call(transaction, block_identifier, state_override)
return self._call(transaction, block_identifier, state_override)
def _durin_call(
self,
transaction: TxParams,
block_identifier: BlockIdentifier | None = None,
state_override: StateOverride | None = None,
) -> HexBytes:
max_redirects = self.w3.provider.ccip_read_max_redirects
if not max_redirects or max_redirects < 4:
raise Web3ValueError(
"ccip_read_max_redirects property on provider must be at least 4."
)
for _ in range(max_redirects):
try:
return self._call(transaction, block_identifier, state_override)
except OffchainLookup as offchain_lookup:
durin_calldata = handle_offchain_lookup(
offchain_lookup.payload,
transaction,
)
transaction["data"] = durin_calldata
raise TooManyRequests("Too many CCIP read redirects")
# eth_simulateV1
_simulateV1: Method[
Callable[[SimulateV1Payload, BlockIdentifier], Sequence[SimulateV1Result]]
] = Method(RPC.eth_simulateV1)
def simulate_v1(
self,
payload: SimulateV1Payload,
block_identifier: BlockIdentifier,
) -> Sequence[SimulateV1Result]:
return self._simulateV1(payload, block_identifier)
# eth_createAccessList
_create_access_list: Method[
Callable[
[TxParams, BlockIdentifier | None],
CreateAccessListResponse,
]
] = Method(RPC.eth_createAccessList, mungers=[BaseEth.create_access_list_munger])
def create_access_list(
self,
transaction: TxParams,
block_identifier: BlockIdentifier | None = None,
) -> CreateAccessListResponse:
return self._create_access_list(transaction, block_identifier)
# eth_estimateGas
_estimate_gas: Method[
Callable[[TxParams, BlockIdentifier | None, StateOverride | None], int]
] = Method(RPC.eth_estimateGas, mungers=[BaseEth.estimate_gas_munger])
def estimate_gas(
self,
transaction: TxParams,
block_identifier: BlockIdentifier | None = None,
state_override: StateOverride | None = None,
) -> int:
return self._estimate_gas(transaction, block_identifier, state_override)
# eth_getTransactionByHash
_get_transaction: Method[Callable[[_Hash32], TxData]] = Method(
RPC.eth_getTransactionByHash, mungers=[default_root_munger]
)
def get_transaction(self, transaction_hash: _Hash32) -> TxData:
return self._get_transaction(transaction_hash)
# eth_getRawTransactionByHash
_get_raw_transaction: Method[Callable[[_Hash32], HexBytes]] = Method(
RPC.eth_getRawTransactionByHash, mungers=[default_root_munger]
)
def get_raw_transaction(self, transaction_hash: _Hash32) -> HexBytes:
return self._get_raw_transaction(transaction_hash)
# eth_getTransactionByBlockNumberAndIndex
# eth_getTransactionByBlockHashAndIndex
get_transaction_by_block: Method[Callable[[BlockIdentifier, int], TxData]] = Method(
method_choice_depends_on_args=select_method_for_block_identifier(
if_predefined=RPC.eth_getTransactionByBlockNumberAndIndex,
if_hash=RPC.eth_getTransactionByBlockHashAndIndex,
if_number=RPC.eth_getTransactionByBlockNumberAndIndex,
),
mungers=[default_root_munger],
)
# eth_getRawTransactionByBlockHashAndIndex
# eth_getRawTransactionByBlockNumberAndIndex
_get_raw_transaction_by_block: Method[
Callable[[BlockIdentifier, int], HexBytes]
] = Method(
method_choice_depends_on_args=select_method_for_block_identifier(
if_predefined=RPC.eth_getRawTransactionByBlockNumberAndIndex,
if_hash=RPC.eth_getRawTransactionByBlockHashAndIndex,
if_number=RPC.eth_getRawTransactionByBlockNumberAndIndex,
),
mungers=[default_root_munger],
)
def get_raw_transaction_by_block(
self, block_identifier: BlockIdentifier, index: int
) -> HexBytes:
return self._get_raw_transaction_by_block(block_identifier, index)
# eth_getBlockTransactionCountByHash
# eth_getBlockTransactionCountByNumber
get_block_transaction_count: Method[Callable[[BlockIdentifier], int]] = Method(
method_choice_depends_on_args=select_method_for_block_identifier(
if_predefined=RPC.eth_getBlockTransactionCountByNumber,
if_hash=RPC.eth_getBlockTransactionCountByHash,
if_number=RPC.eth_getBlockTransactionCountByNumber,
),
mungers=[default_root_munger],
)
# eth_sendTransaction
_send_transaction: Method[Callable[[TxParams], HexBytes]] = Method(
RPC.eth_sendTransaction, mungers=[BaseEth.send_transaction_munger]
)
def send_transaction(self, transaction: TxParams) -> HexBytes:
return self._send_transaction(transaction)
# eth_sendRawTransaction
_send_raw_transaction: Method[Callable[[HexStr | bytes], HexBytes]] = Method(
RPC.eth_sendRawTransaction,
mungers=[default_root_munger],
)
def send_raw_transaction(self, transaction: HexStr | bytes) -> HexBytes:
return self._send_raw_transaction(transaction)
# eth_getBlockByHash
# eth_getBlockByNumber
_get_block: Method[Callable[[BlockIdentifier, bool], BlockData]] = Method(
method_choice_depends_on_args=select_method_for_block_identifier(
if_predefined=RPC.eth_getBlockByNumber,
if_hash=RPC.eth_getBlockByHash,
if_number=RPC.eth_getBlockByNumber,
),
mungers=[BaseEth.get_block_munger],
)
def get_block(
self, block_identifier: BlockIdentifier, full_transactions: bool = False
) -> BlockData:
return self._get_block(block_identifier, full_transactions)
# eth_getBlockReceipts
_get_block_receipts: Method[Callable[[BlockIdentifier], BlockReceipts]] = Method(
RPC.eth_getBlockReceipts,
mungers=[default_root_munger],
)
def get_block_receipts(self, block_identifier: BlockIdentifier) -> BlockReceipts:
return self._get_block_receipts(block_identifier)
# eth_getBalance
_get_balance: Method[
Callable[[Address | ChecksumAddress | ENS, BlockIdentifier | None], Wei]
] = Method(
RPC.eth_getBalance,
mungers=[BaseEth.block_id_munger],
)
def get_balance(
self,
account: Address | ChecksumAddress | ENS,
block_identifier: BlockIdentifier | None = None,
) -> Wei:
return self._get_balance(account, block_identifier)
# eth_getCode
_get_code: Method[
Callable[[Address | ChecksumAddress | ENS, BlockIdentifier | None], HexBytes]
] = Method(RPC.eth_getCode, mungers=[BaseEth.block_id_munger])
def get_code(
self,
account: Address | ChecksumAddress | ENS,
block_identifier: BlockIdentifier | None = None,
) -> HexBytes:
return self._get_code(account, block_identifier)
# eth_getLogs
_get_logs: Method[Callable[[FilterParams], list[LogReceipt]]] = Method(
RPC.eth_getLogs, mungers=[default_root_munger]
)
def get_logs(
self,
filter_params: FilterParams,
) -> list[LogReceipt]:
return self._get_logs(filter_params)
# eth_getTransactionCount
_get_transaction_count: Method[
Callable[[Address | ChecksumAddress | ENS, BlockIdentifier | None], Nonce]
] = Method(
RPC.eth_getTransactionCount,
mungers=[BaseEth.block_id_munger],
)
def get_transaction_count(
self,
account: Address | ChecksumAddress | ENS,
block_identifier: BlockIdentifier | None = None,
) -> Nonce:
return self._get_transaction_count(account, block_identifier)
# eth_getTransactionReceipt
_transaction_receipt: Method[Callable[[_Hash32], TxReceipt]] = Method(
RPC.eth_getTransactionReceipt, mungers=[default_root_munger]
)
def get_transaction_receipt(self, transaction_hash: _Hash32) -> TxReceipt:
return self._transaction_receipt(transaction_hash)
def wait_for_transaction_receipt(
self, transaction_hash: _Hash32, timeout: float = 120, poll_latency: float = 0.1
) -> TxReceipt:
try:
with Timeout(timeout) as _timeout:
while True:
try:
tx_receipt = self._transaction_receipt(transaction_hash)
except (TransactionNotFound, TransactionIndexingInProgress):
tx_receipt = None
if tx_receipt is not None:
break
_timeout.sleep(poll_latency)
return tx_receipt
except Timeout:
raise TimeExhausted(
f"Transaction {HexBytes(transaction_hash) !r} is not in the chain "
f"after {timeout} seconds"
)
# eth_getStorageAt
_get_storage_at: Method[
Callable[
[Address | ChecksumAddress | ENS, int, BlockIdentifier | None],
HexBytes,
]
] = Method(
RPC.eth_getStorageAt,
mungers=[BaseEth.get_storage_at_munger],
)
def get_storage_at(
self,
account: Address | ChecksumAddress | ENS,
position: int,
block_identifier: BlockIdentifier | None = None,
) -> HexBytes:
return self._get_storage_at(account, position, block_identifier)
# eth_getProof
def get_proof_munger(
self,
account: Address | ChecksumAddress | ENS,
positions: Sequence[int],
block_identifier: BlockIdentifier | None = None,
) -> tuple[Address | ChecksumAddress | ENS, Sequence[int], BlockIdentifier | None]:
if block_identifier is None:
block_identifier = self.default_block
return (account, positions, block_identifier)
get_proof: Method[
Callable[
[
tuple[
Address | ChecksumAddress | ENS,
Sequence[int],
BlockIdentifier | None,
]
],
MerkleProof,
]
] = Method(
RPC.eth_getProof,
mungers=[get_proof_munger],
)
# eth_getUncleCountByBlockHash
# eth_getUncleCountByBlockNumber
_get_uncle_count: Method[Callable[[BlockIdentifier], int]] = Method(
method_choice_depends_on_args=select_method_for_block_identifier(
if_predefined=RPC.eth_getUncleCountByBlockNumber,
if_hash=RPC.eth_getUncleCountByBlockHash,
if_number=RPC.eth_getUncleCountByBlockNumber,
),
mungers=[default_root_munger],
)
get_uncle_count = DeprecatedMethod(
_get_uncle_count,
old_name="_get_uncle_count",
new_name="get_uncle_count",
msg="All get_uncle* methods have been deprecated",
)
# eth_getUncleByBlockHashAndIndex
# eth_getUncleByBlockNumberAndIndex
_get_uncle_by_block: Method[Callable[[BlockIdentifier, int], Uncle]] = Method(
method_choice_depends_on_args=select_method_for_block_identifier(
if_predefined=RPC.eth_getUncleByBlockNumberAndIndex,
if_hash=RPC.eth_getUncleByBlockHashAndIndex,
if_number=RPC.eth_getUncleByBlockNumberAndIndex,
),
mungers=[default_root_munger],
)
get_uncle_by_block = DeprecatedMethod(
_get_uncle_by_block,
old_name="_get_uncle_by_block",
new_name="get_uncle_by_block",
msg="All get_uncle* methods have been deprecated",
)
def replace_transaction(
self, transaction_hash: _Hash32, new_transaction: TxParams
) -> HexBytes:
current_transaction = get_required_transaction(self.w3, transaction_hash)
return replace_transaction(self.w3, current_transaction, new_transaction)
def modify_transaction(
self, transaction_hash: _Hash32, **transaction_params: Unpack[TxParams]
) -> HexBytes:
assert_valid_transaction_params(cast(TxParams, transaction_params))
current_transaction = get_required_transaction(self.w3, transaction_hash)
current_transaction_params = extract_valid_transaction_params(
current_transaction
)
new_transaction = merge(current_transaction_params, transaction_params)
return replace_transaction(self.w3, current_transaction, new_transaction)
# eth_sign
sign: Method[Callable[..., HexStr]] = Method(
RPC.eth_sign, mungers=[BaseEth.sign_munger]
)
# eth_signTransaction
sign_transaction: Method[Callable[[TxParams], SignedTx]] = Method(
RPC.eth_signTransaction,
mungers=[default_root_munger],
)
# eth_signTypedData
sign_typed_data: Method[
Callable[[Address | ChecksumAddress | ENS, dict[str, Any]], HexStr]
] = Method(
RPC.eth_signTypedData,
mungers=[default_root_munger],
)
# eth_newFilter, eth_newBlockFilter, eth_newPendingTransactionFilter
filter: Method[Callable[[str | FilterParams | HexStr | None], Filter]] = Method(
method_choice_depends_on_args=select_filter_method(
if_new_block_filter=RPC.eth_newBlockFilter,
if_new_pending_transaction_filter=RPC.eth_newPendingTransactionFilter,
if_new_filter=RPC.eth_newFilter,
),
mungers=[BaseEth.filter_munger],
)
# eth_getFilterChanges, eth_getFilterLogs, eth_uninstallFilter
get_filter_changes: Method[Callable[[HexStr], list[LogReceipt]]] = Method(
RPC.eth_getFilterChanges, mungers=[default_root_munger]
)
get_filter_logs: Method[Callable[[HexStr], list[LogReceipt]]] = Method(
RPC.eth_getFilterLogs, mungers=[default_root_munger]
)
uninstall_filter: Method[Callable[[HexStr], bool]] = Method(
RPC.eth_uninstallFilter,
mungers=[default_root_munger],
)
@overload
def contract(self, address: None = None, **kwargs: Any) -> type[Contract]:
...
@overload
def contract(
self, address: Address | ChecksumAddress | ENS, **kwargs: Any
) -> Contract:
...
def contract(
self,
address: Address | ChecksumAddress | ENS | None = None,
**kwargs: Any,
) -> type[Contract] | Contract:
ContractFactoryClass = kwargs.pop(
"ContractFactoryClass", self._default_contract_factory
)
ContractFactory = ContractFactoryClass.factory(self.w3, **kwargs)
if address:
return ContractFactory(address)
else:
return ContractFactory
def set_contract_factory(
self,
contract_factory: type[Contract | ContractCaller],
) -> None:
self._default_contract_factory = contract_factory
| Eth |
python | walkccc__LeetCode | solutions/419. Battleships in a Board/419.py | {
"start": 0,
"end": 367
} | class ____:
def countBattleships(self, board: list[list[str]]) -> int:
ans = 0
for i, row in enumerate(board):
for j, cell in enumerate(row):
if cell == '.':
continue
if i > 0 and board[i - 1][j] == 'X':
continue
if j > 0 and board[i][j - 1] == 'X':
continue
ans += 1
return ans
| Solution |
python | getsentry__sentry-python | tests/integrations/wsgi/test_wsgi.py | {
"start": 334,
"end": 501
} | class ____:
def __init__(self, iterable):
self.iterable = iterable
def __call__(self, environ, start_response):
return self.iterable
| IterableApp |
python | numpy__numpy | numpy/_core/tests/test_overrides.py | {
"start": 18382,
"end": 27777
} | class ____:
def _create_MyArray(self):
class MyArray:
def __init__(self, function=None):
self.function = function
def __array_function__(self, func, types, args, kwargs):
assert func is getattr(np, func.__name__)
try:
my_func = getattr(self, func.__name__)
except AttributeError:
return NotImplemented
return my_func(*args, **kwargs)
return MyArray
def _create_MyNoArrayFunctionArray(self):
class MyNoArrayFunctionArray:
def __init__(self, function=None):
self.function = function
return MyNoArrayFunctionArray
def _create_MySubclass(self):
class MySubclass(np.ndarray):
def __array_function__(self, func, types, args, kwargs):
result = super().__array_function__(func, types, args, kwargs)
return result.view(self.__class__)
return MySubclass
def add_method(self, name, arr_class, enable_value_error=False):
def _definition(*args, **kwargs):
# Check that `like=` isn't propagated downstream
assert 'like' not in kwargs
if enable_value_error and 'value_error' in kwargs:
raise ValueError
return arr_class(getattr(arr_class, name))
setattr(arr_class, name, _definition)
def func_args(*args, **kwargs):
return args, kwargs
def test_array_like_not_implemented(self):
MyArray = self._create_MyArray()
self.add_method('array', MyArray)
ref = MyArray.array()
with assert_raises_regex(TypeError, 'no implementation found'):
array_like = np.asarray(1, like=ref)
_array_tests = [
('array', *func_args((1,))),
('asarray', *func_args((1,))),
('asanyarray', *func_args((1,))),
('ascontiguousarray', *func_args((2, 3))),
('asfortranarray', *func_args((2, 3))),
('require', *func_args((np.arange(6).reshape(2, 3),),
requirements=['A', 'F'])),
('empty', *func_args((1,))),
('full', *func_args((1,), 2)),
('ones', *func_args((1,))),
('zeros', *func_args((1,))),
('arange', *func_args(3)),
('frombuffer', *func_args(b'\x00' * 8, dtype=int)),
('fromiter', *func_args(range(3), dtype=int)),
('fromstring', *func_args('1,2', dtype=int, sep=',')),
('loadtxt', *func_args(lambda: StringIO('0 1\n2 3'))),
('genfromtxt', *func_args(lambda: StringIO('1,2.1'),
dtype=[('int', 'i8'), ('float', 'f8')],
delimiter=',')),
]
def test_nep35_functions_as_array_functions(self,):
all_array_functions = get_overridable_numpy_array_functions()
like_array_functions_subset = {
getattr(np, func_name) for func_name, *_ in self.__class__._array_tests
}
assert like_array_functions_subset.issubset(all_array_functions)
nep35_python_functions = {
np.eye, np.fromfunction, np.full, np.genfromtxt,
np.identity, np.loadtxt, np.ones, np.require, np.tri,
}
assert nep35_python_functions.issubset(all_array_functions)
nep35_C_functions = {
np.arange, np.array, np.asanyarray, np.asarray,
np.ascontiguousarray, np.asfortranarray, np.empty,
np.frombuffer, np.fromfile, np.fromiter, np.fromstring,
np.zeros,
}
assert nep35_C_functions.issubset(all_array_functions)
@pytest.mark.parametrize('function, args, kwargs', _array_tests)
@pytest.mark.parametrize('numpy_ref', [True, False])
def test_array_like(self, function, args, kwargs, numpy_ref):
MyArray = self._create_MyArray()
self.add_method('array', MyArray)
self.add_method(function, MyArray)
np_func = getattr(np, function)
my_func = getattr(MyArray, function)
if numpy_ref is True:
ref = np.array(1)
else:
ref = MyArray.array()
like_args = tuple(a() if callable(a) else a for a in args)
array_like = np_func(*like_args, **kwargs, like=ref)
if numpy_ref is True:
assert type(array_like) is np.ndarray
np_args = tuple(a() if callable(a) else a for a in args)
np_arr = np_func(*np_args, **kwargs)
# Special-case np.empty to ensure values match
if function == "empty":
np_arr.fill(1)
array_like.fill(1)
assert_equal(array_like, np_arr)
else:
assert type(array_like) is MyArray
assert array_like.function is my_func
@pytest.mark.parametrize('function, args, kwargs', _array_tests)
@pytest.mark.parametrize('ref', [1, [1], "MyNoArrayFunctionArray"])
def test_no_array_function_like(self, function, args, kwargs, ref):
MyNoArrayFunctionArray = self._create_MyNoArrayFunctionArray()
self.add_method('array', MyNoArrayFunctionArray)
self.add_method(function, MyNoArrayFunctionArray)
np_func = getattr(np, function)
# Instantiate ref if it's the MyNoArrayFunctionArray class
if ref == "MyNoArrayFunctionArray":
ref = MyNoArrayFunctionArray.array()
like_args = tuple(a() if callable(a) else a for a in args)
with assert_raises_regex(TypeError,
'The `like` argument must be an array-like that implements'):
np_func(*like_args, **kwargs, like=ref)
@pytest.mark.parametrize('function, args, kwargs', _array_tests)
def test_subclass(self, function, args, kwargs):
MySubclass = self._create_MySubclass()
ref = np.array(1).view(MySubclass)
np_func = getattr(np, function)
like_args = tuple(a() if callable(a) else a for a in args)
array_like = np_func(*like_args, **kwargs, like=ref)
assert type(array_like) is MySubclass
if np_func is np.empty:
return
np_args = tuple(a() if callable(a) else a for a in args)
np_arr = np_func(*np_args, **kwargs)
assert_equal(array_like.view(np.ndarray), np_arr)
@pytest.mark.parametrize('numpy_ref', [True, False])
def test_array_like_fromfile(self, numpy_ref):
MyArray = self._create_MyArray()
self.add_method('array', MyArray)
self.add_method("fromfile", MyArray)
if numpy_ref is True:
ref = np.array(1)
else:
ref = MyArray.array()
data = np.random.random(5)
with tempfile.TemporaryDirectory() as tmpdir:
fname = os.path.join(tmpdir, "testfile")
data.tofile(fname)
array_like = np.fromfile(fname, like=ref)
if numpy_ref is True:
assert type(array_like) is np.ndarray
np_res = np.fromfile(fname, like=ref)
assert_equal(np_res, data)
assert_equal(array_like, np_res)
else:
assert type(array_like) is MyArray
assert array_like.function is MyArray.fromfile
def test_exception_handling(self):
MyArray = self._create_MyArray()
self.add_method('array', MyArray, enable_value_error=True)
ref = MyArray.array()
with assert_raises(TypeError):
# Raises the error about `value_error` being invalid first
np.array(1, value_error=True, like=ref)
@pytest.mark.parametrize('function, args, kwargs', _array_tests)
def test_like_as_none(self, function, args, kwargs):
MyArray = self._create_MyArray()
self.add_method('array', MyArray)
self.add_method(function, MyArray)
np_func = getattr(np, function)
like_args = tuple(a() if callable(a) else a for a in args)
# required for loadtxt and genfromtxt to init w/o error.
like_args_exp = tuple(a() if callable(a) else a for a in args)
array_like = np_func(*like_args, **kwargs, like=None)
expected = np_func(*like_args_exp, **kwargs)
# Special-case np.empty to ensure values match
if function == "empty":
array_like.fill(1)
expected.fill(1)
assert_equal(array_like, expected)
def test_function_like():
# We provide a `__get__` implementation, make sure it works
assert type(np.mean) is np._core._multiarray_umath._ArrayFunctionDispatcher
class MyClass:
def __array__(self, dtype=None, copy=None):
# valid argument to mean:
return np.arange(3)
func1 = staticmethod(np.mean)
func2 = np.mean
func3 = classmethod(np.mean)
m = MyClass()
assert m.func1([10]) == 10
assert m.func2() == 1 # mean of the arange
with pytest.raises(TypeError, match="unsupported operand type"):
# Tries to operate on the class
m.func3()
# Manual binding also works (the above may shortcut):
bound = np.mean.__get__(m, MyClass)
assert bound() == 1
bound = np.mean.__get__(None, MyClass) # unbound actually
assert bound([10]) == 10
bound = np.mean.__get__(MyClass) # classmethod
with pytest.raises(TypeError, match="unsupported operand type"):
bound()
| TestArrayLike |
python | streamlit__streamlit | lib/tests/streamlit/elements/lib/column_types_test.py | {
"start": 1147,
"end": 19849
} | class ____(unittest.TestCase):
def test_generic_column(self):
"""Test Column creation."""
assert remove_none_values(Column()) == {}, (
"Should not have any properties defined."
)
assert remove_none_values(
Column(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
}, "Should have all the properties defined."
def test_number_column(self):
"""Test NumberColumn creation."""
assert remove_none_values(NumberColumn()) == {
"type_config": {"type": "number"}
}, "Should only have the type defined and nothing else."
assert remove_none_values(
NumberColumn(
"Col1",
width=100,
help="Help text",
disabled=False,
required=True,
pinned=True,
default=50,
min_value=0,
max_value=100,
step=1,
format="%.2f",
)
) == {
"label": "Col1",
"width": 100,
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": 50,
"type_config": {
"type": "number",
"format": "%.2f",
"max_value": 100,
"min_value": 0,
"step": 1,
},
}, "Should have all the properties defined."
def test_text_column(self):
"""Test TextColumn creation."""
assert remove_none_values(TextColumn()) == {"type_config": {"type": "text"}}, (
"Should only have the type defined and nothing else."
)
assert remove_none_values(
TextColumn(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
default="default",
max_chars=10,
validate="^[a-zA-Z]+$",
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": "default",
"type_config": {"type": "text", "max_chars": 10, "validate": "^[a-zA-Z]+$"},
}, "Should have all the properties defined."
def test_checkbox_column(self):
"""Test CheckboxColumn creation."""
assert remove_none_values(CheckboxColumn()) == {
"type_config": {"type": "checkbox"}
}, "Should only have the type defined and nothing else."
assert remove_none_values(
CheckboxColumn(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
default=True,
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": True,
"type_config": {"type": "checkbox"},
}, "Should have all the properties defined."
def test_selectbox_column(self):
"""Test SelectboxColumn creation."""
assert remove_none_values(SelectboxColumn()) == {
"type_config": {"type": "selectbox"}
}, "Should only have the type defined and nothing else."
assert remove_none_values(
SelectboxColumn(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
default="a",
options=["a", "b", "c"],
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": "a",
"type_config": {"type": "selectbox", "options": ["a", "b", "c"]},
}, "Should have all the properties defined."
def test_selectbox_column_with_format_func(self):
"""Test SelectboxColumn creation with format_func applied to options."""
assert remove_none_values(
SelectboxColumn(options=["a", "b"], format_func=str.upper)
) == {
"type_config": {
"type": "selectbox",
"options": [
{"value": "a", "label": "A"},
{"value": "b", "label": "B"},
],
}
}, "Options should be transformed into value/label pairs via format_func."
def test_datetime_column(self):
"""Test DatetimeColumn creation."""
assert remove_none_values(DatetimeColumn()) == {
"type_config": {"type": "datetime"}
}, "Should only have the type defined and nothing else."
assert remove_none_values(
DatetimeColumn(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
default=datetime.datetime(2021, 1, 1),
min_value=datetime.datetime(2020, 1, 1),
max_value=datetime.datetime(2022, 1, 2),
step=datetime.timedelta(milliseconds=100),
format="yyyy-MM-dd",
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": "2021-01-01T00:00:00",
"type_config": {
"type": "datetime",
"format": "yyyy-MM-dd",
"max_value": "2022-01-02T00:00:00",
"min_value": "2020-01-01T00:00:00",
"step": 0.1,
},
}, "Should have all the properties defined."
def test_time_column(self):
"""Test TimeColumn creation."""
assert remove_none_values(TimeColumn()) == {"type_config": {"type": "time"}}, (
"Should only have the type defined and nothing else."
)
assert remove_none_values(
TimeColumn(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
default=datetime.time(12, 0),
min_value=datetime.time(0, 0),
max_value=datetime.time(23, 59),
step=datetime.timedelta(milliseconds=100),
format="HH:mm",
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": "12:00:00",
"type_config": {
"type": "time",
"format": "HH:mm",
"max_value": "23:59:00",
"min_value": "00:00:00",
"step": 0.1,
},
}, "Should have all the properties defined."
def test_date_column(self):
"""Test DateColumn creation."""
assert remove_none_values(DateColumn()) == {"type_config": {"type": "date"}}, (
"Should only have the type defined and nothing else."
)
assert remove_none_values(
DateColumn(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
default=datetime.date(2021, 1, 1),
min_value=datetime.date(2020, 1, 1),
max_value=datetime.date(2022, 1, 2),
step=1,
format="yyyy-MM-dd",
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": "2021-01-01",
"type_config": {
"type": "date",
"format": "yyyy-MM-dd",
"min_value": "2020-01-01",
"max_value": "2022-01-02",
"step": 1,
},
}, "Should have all the properties defined."
def test_progress_column(self):
"""Test ProgressColumn creation."""
assert remove_none_values(ProgressColumn()) == {
"type_config": {"type": "progress"}
}, "Should only have the type defined and nothing else."
assert remove_none_values(
ProgressColumn(
"Col1",
width="small",
help="Help text",
pinned=True,
min_value=0,
max_value=100,
format="%.1f%%",
color="red",
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"pinned": True,
"type_config": {
"type": "progress",
"format": "%.1f%%",
"min_value": 0,
"max_value": 100,
"color": "red",
},
}, "Should have all the properties defined."
def test_line_chart_column(self):
"""Test LineChartColumn creation."""
assert remove_none_values(LineChartColumn()) == {
"type_config": {"type": "line_chart"}
}, "Should only have the type defined and nothing else."
assert remove_none_values(
LineChartColumn(
"Col1", width="small", help="Help text", pinned=True, y_min=0, y_max=100
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"pinned": True,
"type_config": {"type": "line_chart", "y_min": 0, "y_max": 100},
}, "Should have all the properties defined."
def test_bar_chart_column(self):
"""Test BarChartColumn creation."""
assert remove_none_values(BarChartColumn()) == {
"type_config": {"type": "bar_chart"}
}, "Should only have the type defined and nothing else."
assert remove_none_values(
BarChartColumn(
"Col1", width="small", help="Help text", pinned=True, y_min=0, y_max=100
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"pinned": True,
"type_config": {"type": "bar_chart", "y_min": 0, "y_max": 100},
}, "Should have all the properties defined."
def test_link_column(self):
"""Test LinkColumn creation."""
assert remove_none_values(LinkColumn()) == {"type_config": {"type": "link"}}, (
"Should only have the type defined and nothing else."
)
assert remove_none_values(
LinkColumn(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
default="https://streamlit.io/",
max_chars=100,
validate="^[a-zA-Z]+$",
display_text="streamlit",
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": "https://streamlit.io/",
"type_config": {
"type": "link",
"max_chars": 100,
"validate": "^[a-zA-Z]+$",
"display_text": "streamlit",
},
}, "Should have all the properties defined."
def test_list_column(self):
"""Test ListColumn creation."""
assert remove_none_values(ListColumn()) == {"type_config": {"type": "list"}}, (
"Should only have the type defined and nothing else."
)
assert remove_none_values(
ListColumn(
"Col1",
width="small",
help="Help text",
pinned=True,
disabled=False,
required=True,
default=["a", "b", "c"],
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"pinned": True,
"disabled": False,
"required": True,
"default": ["a", "b", "c"],
"type_config": {"type": "list"},
}, "Should have all the properties defined."
def test_image_column(self):
"""Test ImageColumn creation."""
assert remove_none_values(ImageColumn()) == {
"type_config": {"type": "image"}
}, "Should only have the type defined and nothing else."
assert remove_none_values(
ImageColumn("Col1", width="small", help="Help text", pinned=True)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"pinned": True,
"type_config": {"type": "image"},
}, "Should have all the properties defined."
def test_json_column(self):
"""Test JsonColumn creation."""
assert remove_none_values(JsonColumn()) == {"type_config": {"type": "json"}}, (
"Should only have the type defined and nothing else."
)
assert remove_none_values(
JsonColumn("Col1", width="small", help="Help text", pinned=True)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"pinned": True,
"type_config": {"type": "json"},
}, "Should have all the properties defined."
def test_multiselect_column(self):
"""Test MultiselectColumn creation (basic)."""
assert remove_none_values(MultiselectColumn()) == {
"type_config": {"type": "multiselect"}
}, "Should only have the type defined and nothing else."
def test_multiselect_column_full(self):
"""Test MultiselectColumn creation with common properties and simple options."""
assert remove_none_values(
MultiselectColumn(
"Col1",
width="small",
help="Help text",
disabled=False,
required=True,
pinned=True,
default=["a", "b"],
options=["a", "b", "c"],
accept_new_options=True,
)
) == {
"label": "Col1",
"width": "small",
"help": "Help text",
"disabled": False,
"required": True,
"pinned": True,
"default": ["a", "b"],
"type_config": {
"type": "multiselect",
"options": [
{"value": "a"},
{"value": "b"},
{"value": "c"},
],
"accept_new_options": True,
},
}, "Should have all the properties defined."
def test_multiselect_column_with_format_and_single_color(self):
"""Test MultiselectColumn options transformed via format_func and colored uniformly."""
assert remove_none_values(
MultiselectColumn(
options=["exploration", "visualization", "llm"],
color="orange",
format_func=lambda x: x.capitalize(),
)
) == {
"type_config": {
"type": "multiselect",
"options": [
{"value": "exploration", "label": "Exploration", "color": "orange"},
{
"value": "visualization",
"label": "Visualization",
"color": "orange",
},
{"value": "llm", "label": "Llm", "color": "orange"},
],
}
}, "Options should include formatted labels and a single repeated color."
def test_multiselect_column_with_color_iterable(self):
"""Test MultiselectColumn color cycling when an iterable of colors is provided."""
assert remove_none_values(
MultiselectColumn(
options=["a", "b", "c", "d"],
color=["red", "blue"],
)
) == {
"type_config": {
"type": "multiselect",
"options": [
{"value": "a", "color": "red"},
{"value": "b", "color": "blue"},
{"value": "c", "color": "red"},
{"value": "d", "color": "blue"},
],
}
}, "Colors should cycle through the provided iterable."
@pytest.mark.parametrize(
"color",
[
# Supported named colors
"auto",
"auto-inverse",
"red",
"blue",
"green",
"yellow",
"violet",
"orange",
"gray",
"grey",
"primary",
# CSS-like colors accepted by is_css_color_like
"#fff",
"#ffff",
"#ffffff",
"#ffffffff",
"rgb(255, 0, 0)",
"rgba(0, 0, 0, 0.5)",
],
)
def test__validate_chart_color_valid(color: str) -> None:
"""Validate that supported names and CSS-like colors do not raise."""
_validate_chart_color(color)
@pytest.mark.parametrize(
"color",
[
"purple",
"hsl(0,0%,0%)",
"#12",
"#12345",
"#1234567",
"auto-invers",
"",
" ",
"not-a-color",
":material/open_in_new:",
],
)
def test__validate_chart_color_invalid(color: str) -> None:
"""Validate that unsupported names and non CSS-like strings raise StreamlitValueError."""
with pytest.raises(StreamlitValueError):
_validate_chart_color(color)
| ColumnTypesTest |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 14636,
"end": 14774
} | class ____(AnsiblePluginError):
"""A collection is not supported by this version of Ansible."""
| AnsibleCollectionUnsupportedVersionError |
python | astropy__astropy | astropy/modeling/tests/test_input.py | {
"start": 1735,
"end": 8242
} | class ____:
"""Test various input options to fitting routines."""
def setup_class(self):
self.x1 = np.arange(10)
self.y, self.x = np.mgrid[:10, :10]
def test_linear_fitter_1set(self):
"""1 set 1D x, 1pset"""
expected = np.array([0, 1, 1, 1])
p1 = models.Polynomial1D(3)
p1.parameters = [0, 1, 1, 1]
y1 = p1(self.x1)
pfit = fitting.LinearLSQFitter()
model = pfit(p1, self.x1, y1)
assert_allclose(model.parameters, expected, atol=10 ** (-7))
def test_linear_fitter_Nset(self):
"""1 set 1D x, 2 sets 1D y, 2 param_sets"""
expected = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
p1 = models.Polynomial1D(3, n_models=2)
p1.parameters = [0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0]
params = {}
for i in range(4):
params[p1.param_names[i]] = [i, i]
p1 = models.Polynomial1D(3, model_set_axis=0, **params)
y1 = p1(self.x1, model_set_axis=False)
pfit = fitting.LinearLSQFitter()
model = pfit(p1, self.x1, y1)
assert_allclose(model.param_sets, expected, atol=10 ** (-7))
def test_linear_fitter_1dcheb(self):
"""1 pset, 1 set 1D x, 1 set 1D y, Chebyshev 1D polynomial"""
expected = np.array(
[
[
2817.2499999999995,
4226.6249999999991,
1680.7500000000009,
273.37499999999926,
]
]
).T
ch1 = models.Chebyshev1D(3)
ch1.parameters = [0, 1, 2, 3]
y1 = ch1(self.x1)
pfit = fitting.LinearLSQFitter()
model = pfit(ch1, self.x1, y1)
assert_allclose(model.param_sets, expected, atol=10 ** (-2))
def test_linear_fitter_1dlegend(self):
"""
1 pset, 1 set 1D x, 1 set 1D y, Legendre 1D polynomial
"""
expected = np.array(
[
[
1925.5000000000011,
3444.7500000000005,
1883.2500000000014,
364.4999999999996,
]
]
).T
leg1 = models.Legendre1D(3)
leg1.parameters = [1, 2, 3, 4]
y1 = leg1(self.x1)
pfit = fitting.LinearLSQFitter()
model = pfit(leg1, self.x1, y1)
assert_allclose(model.param_sets, expected, atol=10 ** (-12))
def test_linear_fitter_1set2d(self):
p2 = models.Polynomial2D(2)
p2.parameters = [0, 1, 2, 3, 4, 5]
expected = [0, 1, 2, 3, 4, 5]
z = p2(self.x, self.y)
pfit = fitting.LinearLSQFitter()
model = pfit(p2, self.x, self.y, z)
assert_allclose(model.parameters, expected, atol=10 ** (-12))
assert_allclose(model(self.x, self.y), z, atol=10 ** (-12))
def test_wrong_numpset(self):
"""
A ValueError is raised if a 1 data set (1d x, 1d y) is fit
with a model with multiple parameter sets.
"""
MESSAGE = (
r"Number of data sets .* is expected to equal the number of parameter sets"
)
with pytest.raises(ValueError, match=MESSAGE):
p1 = models.Polynomial1D(5)
y1 = p1(self.x1)
p1 = models.Polynomial1D(5, n_models=2)
pfit = fitting.LinearLSQFitter()
pfit(p1, self.x1, y1)
def test_wrong_pset(self):
"""A case of 1 set of x and multiple sets of y and parameters."""
expected = np.array(
[
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[1, 5],
]
)
p1 = models.Polynomial1D(5, n_models=2)
params = {}
for i in range(6):
params[p1.param_names[i]] = [1, i]
p1 = models.Polynomial1D(5, model_set_axis=0, **params)
y1 = p1(self.x1, model_set_axis=False)
pfit = fitting.LinearLSQFitter()
model = pfit(p1, self.x1, y1)
assert_allclose(model.param_sets, expected, atol=10 ** (-7))
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
@pytest.mark.parametrize("fitter", fitters_bounds)
def test_nonlinear_lsqt_1set_1d(self, fitter):
"""1 set 1D x, 1 set 1D y, 1 pset NonLinearFitter"""
fitter = fitter()
g1 = models.Gaussian1D(10, mean=3, stddev=0.2)
y1 = g1(self.x1)
model = fitter(g1, self.x1, y1)
assert_allclose(model.parameters, [10, 3, 0.2])
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
@pytest.mark.parametrize("fitter", fitters_bounds)
def test_nonlinear_lsqt_Nset_1d(self, fitter):
"""1 set 1D x, 1 set 1D y, 2 param_sets, NonLinearFitter"""
fitter = fitter()
MESSAGE = r"Non-linear fitters can only fit one data set at a time"
with pytest.raises(ValueError, match=MESSAGE):
g1 = models.Gaussian1D(
[10.2, 10], mean=[3, 3.2], stddev=[0.23, 0.2], n_models=2
)
y1 = g1(self.x1, model_set_axis=False)
_ = fitter(g1, self.x1, y1)
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
@pytest.mark.parametrize("fitter", fitters_bounds)
def test_nonlinear_lsqt_1set_2d(self, fitter):
"""1 set 2d x, 1set 2D y, 1 pset, NonLinearFitter"""
fitter = fitter()
g2 = models.Gaussian2D(
10, x_mean=3, y_mean=4, x_stddev=0.3, y_stddev=0.2, theta=0
)
z = g2(self.x, self.y)
model = fitter(g2, self.x, self.y, z)
assert_allclose(model.parameters, [10, 3, 4, 0.3, 0.2, 0])
@pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
@pytest.mark.parametrize("fitter", fitters_bounds)
def test_nonlinear_lsqt_Nset_2d(self, fitter):
"""1 set 2d x, 1set 2D y, 2 param_sets, NonLinearFitter"""
fitter = fitter()
MESSAGE = (
r"Input argument .* does not have the correct dimensions in .* for a model"
r" set with .*"
)
with pytest.raises(ValueError, match=MESSAGE):
g2 = models.Gaussian2D(
[10, 10],
[3, 3],
[4, 4],
x_stddev=[0.3, 0.3],
y_stddev=[0.2, 0.2],
theta=[0, 0],
n_models=2,
)
z = g2(self.x.ravel(), self.y.ravel())
_ = fitter(g2, self.x, self.y, z)
| TestFitting |
python | wepe__MachineLearning | DeepLearning Tutorials/cnn_LeNet/convolutional_mlp_commentate.py | {
"start": 5124,
"end": 16688
} | class ____(object):
def __init__(self, input, n_in, n_out):
#W大小是n_in行n_out列,b为n_out维向量。即:每个输出对应W的一列以及b的一个元素。
self.W = theano.shared(
value=numpy.zeros(
(n_in, n_out),
dtype=theano.config.floatX
),
name='W',
borrow=True
)
self.b = theano.shared(
value=numpy.zeros(
(n_out,),
dtype=theano.config.floatX
),
name='b',
borrow=True
)
#input是(n_example,n_in),W是(n_in,n_out),点乘得到(n_example,n_out),加上偏置b,
#再作为T.nnet.softmax的输入,得到p_y_given_x
#故p_y_given_x每一行代表每一个样本被估计为各类别的概率
#PS:b是n_out维向量,与(n_example,n_out)矩阵相加,内部其实是先复制n_example个b,
#然后(n_example,n_out)矩阵的每一行都加b
self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b)
#argmax返回最大值下标,因为本例数据集是MNIST,下标刚好就是类别。axis=1表示按行操作。
self.y_pred = T.argmax(self.p_y_given_x, axis=1)
#params,LogisticRegression的参数
self.params = [self.W, self.b]
def negative_log_likelihood(self, y):
return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y])
def errors(self, y):
if y.ndim != self.y_pred.ndim:
raise TypeError(
'y should have the same shape as self.y_pred',
('y', y.type, 'y_pred', self.y_pred.type)
)
if y.dtype.startswith('int'):
return T.mean(T.neq(self.y_pred, y))
else:
raise NotImplementedError()
"""
加载MNIST数据集load_data()
"""
def load_data(dataset):
# dataset是数据集的路径,程序首先检测该路径下有没有MNIST数据集,没有的话就下载MNIST数据集
#这一部分就不解释了,与softmax回归算法无关。
data_dir, data_file = os.path.split(dataset)
if data_dir == "" and not os.path.isfile(dataset):
# Check if dataset is in the data directory.
new_path = os.path.join(
os.path.split(__file__)[0],
"..",
"data",
dataset
)
if os.path.isfile(new_path) or data_file == 'mnist.pkl.gz':
dataset = new_path
if (not os.path.isfile(dataset)) and data_file == 'mnist.pkl.gz':
import urllib
origin = (
'http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz'
)
print 'Downloading data from %s' % origin
urllib.urlretrieve(origin, dataset)
print '... loading data'
#以上是检测并下载数据集mnist.pkl.gz,不是本文重点。下面才是load_data的开始
#从"mnist.pkl.gz"里加载train_set, valid_set, test_set,它们都是包括label的
#主要用到python里的gzip.open()函数,以及 cPickle.load()。
#‘rb’表示以二进制可读的方式打开文件
f = gzip.open(dataset, 'rb')
train_set, valid_set, test_set = cPickle.load(f)
f.close()
#将数据设置成shared variables,主要时为了GPU加速,只有shared variables才能存到GPU memory中
#GPU里数据类型只能是float。而data_y是类别,所以最后又转换为int返回
def shared_dataset(data_xy, borrow=True):
data_x, data_y = data_xy
shared_x = theano.shared(numpy.asarray(data_x,
dtype=theano.config.floatX),
borrow=borrow)
shared_y = theano.shared(numpy.asarray(data_y,
dtype=theano.config.floatX),
borrow=borrow)
return shared_x, T.cast(shared_y, 'int32')
test_set_x, test_set_y = shared_dataset(test_set)
valid_set_x, valid_set_y = shared_dataset(valid_set)
train_set_x, train_set_y = shared_dataset(train_set)
rval = [(train_set_x, train_set_y), (valid_set_x, valid_set_y),
(test_set_x, test_set_y)]
return rval
"""
实现LeNet5
LeNet5有两个卷积层,第一个卷积层有20个卷积核,第二个卷积层有50个卷积核
"""
def evaluate_lenet5(learning_rate=0.1, n_epochs=200,
dataset='mnist.pkl.gz',
nkerns=[20, 50], batch_size=500):
"""
learning_rate:学习速率,随机梯度前的系数。
n_epochs训练步数,每一步都会遍历所有batch,即所有样本
batch_size,这里设置为500,即每遍历完500个样本,才计算梯度并更新参数
nkerns=[20, 50],每一个LeNetConvPoolLayer卷积核的个数,第一个LeNetConvPoolLayer有
20个卷积核,第二个有50个
"""
rng = numpy.random.RandomState(23455)
#加载数据
datasets = load_data(dataset)
train_set_x, train_set_y = datasets[0]
valid_set_x, valid_set_y = datasets[1]
test_set_x, test_set_y = datasets[2]
# 计算batch的个数
n_train_batches = train_set_x.get_value(borrow=True).shape[0]
n_valid_batches = valid_set_x.get_value(borrow=True).shape[0]
n_test_batches = test_set_x.get_value(borrow=True).shape[0]
n_train_batches /= batch_size
n_valid_batches /= batch_size
n_test_batches /= batch_size
#定义几个变量,index表示batch下标,x表示输入的训练数据,y对应其标签
index = T.lscalar()
x = T.matrix('x')
y = T.ivector('y')
######################
# BUILD ACTUAL MODEL #
######################
print '... building the model'
#我们加载进来的batch大小的数据是(batch_size, 28 * 28),但是LeNetConvPoolLayer的输入是四维的,所以要reshape
layer0_input = x.reshape((batch_size, 1, 28, 28))
# layer0即第一个LeNetConvPoolLayer层
#输入的单张图片(28,28),经过conv得到(28-5+1 , 28-5+1) = (24, 24),
#经过maxpooling得到(24/2, 24/2) = (12, 12)
#因为每个batch有batch_size张图,第一个LeNetConvPoolLayer层有nkerns[0]个卷积核,
#故layer0输出为(batch_size, nkerns[0], 12, 12)
layer0 = LeNetConvPoolLayer(
rng,
input=layer0_input,
image_shape=(batch_size, 1, 28, 28),
filter_shape=(nkerns[0], 1, 5, 5),
poolsize=(2, 2)
)
#layer1即第二个LeNetConvPoolLayer层
#输入是layer0的输出,每张特征图为(12,12),经过conv得到(12-5+1, 12-5+1) = (8, 8),
#经过maxpooling得到(8/2, 8/2) = (4, 4)
#因为每个batch有batch_size张图(特征图),第二个LeNetConvPoolLayer层有nkerns[1]个卷积核
#,故layer1输出为(batch_size, nkerns[1], 4, 4)
layer1 = LeNetConvPoolLayer(
rng,
input=layer0.output,
image_shape=(batch_size, nkerns[0], 12, 12),#输入nkerns[0]张特征图,即layer0输出nkerns[0]张特征图
filter_shape=(nkerns[1], nkerns[0], 5, 5),
poolsize=(2, 2)
)
#前面定义好了两个LeNetConvPoolLayer(layer0和layer1),layer1后面接layer2,这是一个全连接层,相当于MLP里面的隐含层
#故可以用MLP中定义的HiddenLayer来初始化layer2,layer2的输入是二维的(batch_size, num_pixels) ,
#故要将上层中同一张图经不同卷积核卷积出来的特征图合并为一维向量,
#也就是将layer1的输出(batch_size, nkerns[1], 4, 4)flatten为(batch_size, nkerns[1]*4*4)=(500,800),作为layer2的输入。
#(500,800)表示有500个样本,每一行代表一个样本。layer2的输出大小是(batch_size,n_out)=(500,500)
layer2_input = layer1.output.flatten(2)
layer2 = HiddenLayer(
rng,
input=layer2_input,
n_in=nkerns[1] * 4 * 4,
n_out=500,
activation=T.tanh
)
#最后一层layer3是分类层,用的是逻辑回归中定义的LogisticRegression,
#layer3的输入是layer2的输出(500,500),layer3的输出就是(batch_size,n_out)=(500,10)
layer3 = LogisticRegression(input=layer2.output, n_in=500, n_out=10)
#代价函数NLL
cost = layer3.negative_log_likelihood(y)
# test_model计算测试误差,x、y根据给定的index具体化,然后调用layer3,
#layer3又会逐层地调用layer2、layer1、layer0,故test_model其实就是整个CNN结构,
#test_model的输入是x、y,输出是layer3.errors(y)的输出,即误差。
test_model = theano.function(
[index],
layer3.errors(y),
givens={
x: test_set_x[index * batch_size: (index + 1) * batch_size],
y: test_set_y[index * batch_size: (index + 1) * batch_size]
}
)
#validate_model,验证模型,分析同上。
validate_model = theano.function(
[index],
layer3.errors(y),
givens={
x: valid_set_x[index * batch_size: (index + 1) * batch_size],
y: valid_set_y[index * batch_size: (index + 1) * batch_size]
}
)
#下面是train_model,涉及到优化算法即SGD,需要计算梯度、更新参数
#参数集
params = layer3.params + layer2.params + layer1.params + layer0.params
#对各个参数的梯度
grads = T.grad(cost, params)
#因为参数太多,在updates规则里面一个一个具体地写出来是很麻烦的,所以下面用了一个for..in..,自动生成规则对(param_i, param_i - learning_rate * grad_i)
updates = [
(param_i, param_i - learning_rate * grad_i)
for param_i, grad_i in zip(params, grads)
]
#train_model,代码分析同test_model。train_model里比test_model、validation_model多出updates规则
train_model = theano.function(
[index],
cost,
updates=updates,
givens={
x: train_set_x[index * batch_size: (index + 1) * batch_size],
y: train_set_y[index * batch_size: (index + 1) * batch_size]
}
)
###############
# 开始训练 #
###############
print '... training'
patience = 10000
patience_increase = 2
improvement_threshold = 0.995
validation_frequency = min(n_train_batches, patience / 2)
#这样设置validation_frequency可以保证每一次epoch都会在验证集上测试。
best_validation_loss = numpy.inf #最好的验证集上的loss,最好即最小
best_iter = 0 #最好的迭代次数,以batch为单位。比如best_iter=10000,说明在训练完第10000个batch时,达到best_validation_loss
test_score = 0.
start_time = time.clock()
epoch = 0
done_looping = False
#下面就是训练过程了,while循环控制的时步数epoch,一个epoch会遍历所有的batch,即所有的图片。
#for循环是遍历一个个batch,一次一个batch地训练。for循环体里会用train_model(minibatch_index)去训练模型,
#train_model里面的updatas会更新各个参数。
#for循环里面会累加训练过的batch数iter,当iter是validation_frequency倍数时则会在验证集上测试,
#如果验证集的损失this_validation_loss小于之前最佳的损失best_validation_loss,
#则更新best_validation_loss和best_iter,同时在testset上测试。
#如果验证集的损失this_validation_loss小于best_validation_loss*improvement_threshold时则更新patience。
#当达到最大步数n_epoch时,或者patience<iter时,结束训练
while (epoch < n_epochs) and (not done_looping):
epoch = epoch + 1
for minibatch_index in xrange(n_train_batches):
iter = (epoch - 1) * n_train_batches + minibatch_index
if iter % 100 == 0:
print 'training @ iter = ', iter
cost_ij = train_model(minibatch_index)
#cost_ij 没什么用,后面都没有用到,只是为了调用train_model,而train_model有返回值
if (iter + 1) % validation_frequency == 0:
# compute zero-one loss on validation set
validation_losses = [validate_model(i) for i
in xrange(n_valid_batches)]
this_validation_loss = numpy.mean(validation_losses)
print('epoch %i, minibatch %i/%i, validation error %f %%' %
(epoch, minibatch_index + 1, n_train_batches,
this_validation_loss * 100.))
if this_validation_loss < best_validation_loss:
if this_validation_loss < best_validation_loss * \
improvement_threshold:
patience = max(patience, iter * patience_increase)
best_validation_loss = this_validation_loss
best_iter = iter
test_losses = [
test_model(i)
for i in xrange(n_test_batches)
]
test_score = numpy.mean(test_losses)
print((' epoch %i, minibatch %i/%i, test error of '
'best model %f %%') %
(epoch, minibatch_index + 1, n_train_batches,
test_score * 100.))
if patience <= iter:
done_looping = True
break
end_time = time.clock()
print('Optimization complete.')
print('Best validation score of %f %% obtained at iteration %i, '
'with test performance %f %%' %
(best_validation_loss * 100., best_iter + 1, test_score * 100.))
print >> sys.stderr, ('The code for file ' +
os.path.split(__file__)[1] +
' ran for %.2fm' % ((end_time - start_time) / 60.))
if __name__ == '__main__':
evaluate_lenet5()
def experiment(state, channel):
evaluate_lenet5(state.learning_rate, dataset=state.dataset)
| LogisticRegression |
python | pypa__pip | src/pip/_vendor/packaging/_parser.py | {
"start": 691,
"end": 771
} | class ____(Node):
def serialize(self) -> str:
return f'"{self}"'
| Value |
python | plotly__plotly.py | plotly/graph_objs/volume/_hoverlabel.py | {
"start": 233,
"end": 11234
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume"
_path_str = "volume.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc",
"showarrow",
}
@property
def align(self):
"""
Sets the horizontal alignment of the text content within hover
label box. Has an effect only if the hover label text spans
more two or more lines
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'right', 'auto']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["align"]
@align.setter
def align(self, val):
self["align"] = val
@property
def alignsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `align`.
The 'alignsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["alignsrc"]
@alignsrc.setter
def alignsrc(self, val):
self["alignsrc"] = val
@property
def bgcolor(self):
"""
Sets the background color of the hover labels for this trace
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def bgcolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `bgcolor`.
The 'bgcolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bgcolorsrc"]
@bgcolorsrc.setter
def bgcolorsrc(self, val):
self["bgcolorsrc"] = val
@property
def bordercolor(self):
"""
Sets the border color of the hover labels for this trace.
The 'bordercolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["bordercolor"]
@bordercolor.setter
def bordercolor(self, val):
self["bordercolor"] = val
@property
def bordercolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
The 'bordercolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bordercolorsrc"]
@bordercolorsrc.setter
def bordercolorsrc(self, val):
self["bordercolorsrc"] = val
@property
def font(self):
"""
Sets the font used in hover labels.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.volume.hoverlabel.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.volume.hoverlabel.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def namelength(self):
"""
Sets the default length (in number of characters) of the trace
name in the hover labels for all traces. -1 shows the whole
name regardless of length. 0-3 shows the first 0-3 characters,
and an integer >3 will show the whole name if it is less than
that many characters, but if it is longer, will truncate to
`namelength - 3` characters and add an ellipsis.
The 'namelength' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [-1, 9223372036854775807]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["namelength"]
@namelength.setter
def namelength(self, val):
self["namelength"] = val
@property
def namelengthsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`namelength`.
The 'namelengthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["namelengthsrc"]
@namelengthsrc.setter
def namelengthsrc(self, val):
self["namelengthsrc"] = val
@property
def showarrow(self):
"""
Sets whether or not to show the hover label arrow/triangle
pointing to the data point.
The 'showarrow' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showarrow"]
@showarrow.setter
def showarrow(self, val):
self["showarrow"] = val
@property
def _prop_descriptions(self):
return """\
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
`bgcolor`.
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
`namelength`.
showarrow
Sets whether or not to show the hover label
arrow/triangle pointing to the data point.
"""
def __init__(
self,
arg=None,
align=None,
alignsrc=None,
bgcolor=None,
bgcolorsrc=None,
bordercolor=None,
bordercolorsrc=None,
font=None,
namelength=None,
namelengthsrc=None,
showarrow=None,
**kwargs,
):
"""
Construct a new Hoverlabel object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.volume.Hoverlabel`
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
`bgcolor`.
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
`namelength`.
showarrow
Sets whether or not to show the hover label
arrow/triangle pointing to the data point.
Returns
-------
Hoverlabel
"""
super().__init__("hoverlabel")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.volume.Hoverlabel
constructor must be a dict or
an instance of :class:`plotly.graph_objs.volume.Hoverlabel`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("align", arg, align)
self._set_property("alignsrc", arg, alignsrc)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("bgcolorsrc", arg, bgcolorsrc)
self._set_property("bordercolor", arg, bordercolor)
self._set_property("bordercolorsrc", arg, bordercolorsrc)
self._set_property("font", arg, font)
self._set_property("namelength", arg, namelength)
self._set_property("namelengthsrc", arg, namelengthsrc)
self._set_property("showarrow", arg, showarrow)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Hoverlabel |
python | tensorflow__tensorflow | tensorflow/python/debug/wrappers/hooks.py | {
"start": 1120,
"end": 5948
} | class ____(session_run_hook.SessionRunHook):
"""Command-line-interface debugger hook.
Can be used as a hook for `tf.compat.v1.train.MonitoredSession`.
"""
def __init__(self,
ui_type="readline",
dump_root=None,
thread_name_filter=None,
config_file_path=None):
"""Create a local debugger command-line interface (CLI) hook.
Args:
ui_type: (`str`) requested user-interface type. Currently supported:
(readline).
dump_root: (`str`) optional path to the dump root directory. Must be a
directory that does not exist or an empty directory. If the directory
does not exist, it will be created by the debugger core during debug
`run()` calls and removed afterwards.
thread_name_filter: Regular-expression white list for threads on which the
wrapper session will be active. See doc of `BaseDebugWrapperSession` for
more details.
config_file_path: Optional override to the default configuration file
path, which is at `${HOME}/.tfdbg_config`.
"""
self._ui_type = ui_type
self._dump_root = dump_root
self._thread_name_filter = thread_name_filter
self._session_wrapper = None
self._pending_tensor_filters = {}
self._config_file_path = config_file_path
def add_tensor_filter(self, filter_name, tensor_filter):
"""Add a tensor filter.
See doc of `LocalCLIDebugWrapperSession.add_tensor_filter()` for details.
Override default behavior to accommodate the possibility of this method
being
called prior to the initialization of the underlying
`LocalCLIDebugWrapperSession` object.
Args:
filter_name: See doc of `LocalCLIDebugWrapperSession.add_tensor_filter()`
for details.
tensor_filter: See doc of
`LocalCLIDebugWrapperSession.add_tensor_filter()` for details.
"""
if self._session_wrapper:
self._session_wrapper.add_tensor_filter(filter_name, tensor_filter)
else:
self._pending_tensor_filters[filter_name] = tensor_filter
def begin(self):
pass
def before_run(self, run_context):
if not self._session_wrapper:
self._session_wrapper = local_cli_wrapper.LocalCLIDebugWrapperSession(
run_context.session,
ui_type=self._ui_type,
dump_root=self._dump_root,
thread_name_filter=self._thread_name_filter,
config_file_path=self._config_file_path)
# Actually register tensor filters registered prior to the construction
# of the underlying LocalCLIDebugWrapperSession object.
for filter_name in self._pending_tensor_filters:
self._session_wrapper.add_tensor_filter(
filter_name, self._pending_tensor_filters[filter_name])
# Increment run call counter.
self._session_wrapper.increment_run_call_count()
# Adapt run_context to an instance of OnRunStartRequest for invoking
# superclass on_run_start().
on_run_start_request = framework.OnRunStartRequest(
run_context.original_args.fetches, run_context.original_args.feed_dict,
None, None, self._session_wrapper.run_call_count)
on_run_start_response = self._session_wrapper.on_run_start(
on_run_start_request)
self._performed_action = on_run_start_response.action
run_args = session_run_hook.SessionRunArgs(
None, feed_dict=None, options=config_pb2.RunOptions())
if self._performed_action == framework.OnRunStartAction.DEBUG_RUN:
# pylint: disable=protected-access
self._session_wrapper._decorate_run_options_for_debug(
run_args.options,
on_run_start_response.debug_urls,
debug_ops=on_run_start_response.debug_ops,
node_name_regex_allowlist=(
on_run_start_response.node_name_regex_allowlist),
op_type_regex_allowlist=(
on_run_start_response.op_type_regex_allowlist),
tensor_dtype_regex_allowlist=(
on_run_start_response.tensor_dtype_regex_allowlist),
tolerate_debug_op_creation_failures=(
on_run_start_response.tolerate_debug_op_creation_failures))
# pylint: enable=protected-access
elif self._performed_action == framework.OnRunStartAction.PROFILE_RUN:
# pylint: disable=protected-access
self._session_wrapper._decorate_run_options_for_profile(run_args.options)
# pylint: enable=protected-access
return run_args
def after_run(self, run_context, run_values):
# Adapt run_context and run_values to OnRunEndRequest and invoke superclass
# on_run_end()
on_run_end_request = framework.OnRunEndRequest(self._performed_action,
run_values.run_metadata)
self._session_wrapper.on_run_end(on_run_end_request)
| LocalCLIDebugHook |
python | sympy__sympy | sympy/assumptions/predicates/order.py | {
"start": 5314,
"end": 6646
} | class ____(Predicate):
r"""
Positive real number predicate.
Explanation
===========
``Q.positive(x)`` is true iff ``x`` is real and `x > 0`, that is if ``x``
is in the interval `(0, \infty)`. In particular, infinity is not
positive.
A few important facts about positive numbers:
- Note that ``Q.nonpositive`` and ``~Q.positive`` are *not* the same
thing. ``~Q.positive(x)`` simply means that ``x`` is not positive,
whereas ``Q.nonpositive(x)`` means that ``x`` is real and not
positive, i.e., ``Q.nonpositive(x)`` is logically equivalent to
`Q.negative(x) | Q.zero(x)``. So for example, ``~Q.positive(I)`` is
true, whereas ``Q.nonpositive(I)`` is false.
- See the documentation of ``Q.real`` for more information about
related facts.
Examples
========
>>> from sympy import Q, ask, symbols, I
>>> x = symbols('x')
>>> ask(Q.positive(x), Q.real(x) & ~Q.negative(x) & ~Q.zero(x))
True
>>> ask(Q.positive(1))
True
>>> ask(Q.nonpositive(I))
False
>>> ask(~Q.positive(I))
True
"""
name = 'positive'
handler = Dispatcher(
"PositiveHandler",
doc=("Handler for key 'positive'. Test that an expression is strictly"
" greater than zero.")
)
| PositivePredicate |
python | modin-project__modin | modin/core/dataframe/base/interchange/dataframe_protocol/dataframe.py | {
"start": 2227,
"end": 4456
} | class ____(ABC):
"""
Data in the buffer is guaranteed to be contiguous in memory.
Note that there is no dtype attribute present, a buffer can be thought of
as simply a block of memory. However, if the column that the buffer is
attached to has a dtype that's supported by DLPack and ``__dlpack__`` is
implemented, then that dtype information will be contained in the return
value from ``__dlpack__``.
This distinction is useful to support both (a) data exchange via DLPack on a
buffer and (b) dtypes like variable-length strings which do not have a
fixed number of bytes per element.
"""
@property
@abstractmethod
def bufsize(self) -> int:
"""
Buffer size in bytes.
Returns
-------
int
"""
pass
@property
@abstractmethod
def ptr(self) -> int:
"""
Pointer to start of the buffer as an integer.
Returns
-------
int
"""
pass
@abstractmethod
def __dlpack__(self) -> Any:
"""
Produce DLPack capsule (see array API standard).
DLPack not implemented in NumPy yet, so leave it out here.
Raises
------
``TypeError`` if the buffer contains unsupported dtypes.
``NotImplementedError`` if DLPack support is not implemented.
Notes
-----
Useful to have to connect to array libraries. Support optional because
it's not completely trivial to implement for a Python-only library.
"""
pass
@abstractmethod
def __dlpack_device__(self) -> Tuple[DlpackDeviceType, Optional[int]]:
"""
Device type and device ID for where the data in the buffer resides.
Uses device type codes matching DLPack. Enum members are:
- CPU = 1
- CUDA = 2
- CPU_PINNED = 3
- OPENCL = 4
- VULKAN = 7
- METAL = 8
- VPI = 9
- ROCM = 10
Returns
-------
tuple
Device type and device ID.
Notes
-----
Must be implemented even if ``__dlpack__`` is not.
"""
pass
| ProtocolBuffer |
python | matplotlib__matplotlib | lib/matplotlib/tri/_triinterpolate.py | {
"start": 11481,
"end": 24071
} | class ____(TriInterpolator):
r"""
Cubic interpolator on a triangular grid.
In one-dimension - on a segment - a cubic interpolating function is
defined by the values of the function and its derivative at both ends.
This is almost the same in 2D inside a triangle, except that the values
of the function and its 2 derivatives have to be defined at each triangle
node.
The CubicTriInterpolator takes the value of the function at each node -
provided by the user - and internally computes the value of the
derivatives, resulting in a smooth interpolation.
(As a special feature, the user can also impose the value of the
derivatives at each node, but this is not supposed to be the common
usage.)
Parameters
----------
triangulation : `~matplotlib.tri.Triangulation`
The triangulation to interpolate over.
z : (npoints,) array-like
Array of values, defined at grid points, to interpolate between.
kind : {'min_E', 'geom', 'user'}, optional
Choice of the smoothing algorithm, in order to compute
the interpolant derivatives (defaults to 'min_E'):
- if 'min_E': (default) The derivatives at each node is computed
to minimize a bending energy.
- if 'geom': The derivatives at each node is computed as a
weighted average of relevant triangle normals. To be used for
speed optimization (large grids).
- if 'user': The user provides the argument *dz*, no computation
is hence needed.
trifinder : `~matplotlib.tri.TriFinder`, optional
If not specified, the Triangulation's default TriFinder will
be used by calling `.Triangulation.get_trifinder`.
dz : tuple of array-likes (dzdx, dzdy), optional
Used only if *kind* ='user'. In this case *dz* must be provided as
(dzdx, dzdy) where dzdx, dzdy are arrays of the same shape as *z* and
are the interpolant first derivatives at the *triangulation* points.
Methods
-------
`__call__` (x, y) : Returns interpolated values at (x, y) points.
`gradient` (x, y) : Returns interpolated derivatives at (x, y) points.
Notes
-----
This note is a bit technical and details how the cubic interpolation is
computed.
The interpolation is based on a Clough-Tocher subdivision scheme of
the *triangulation* mesh (to make it clearer, each triangle of the
grid will be divided in 3 child-triangles, and on each child triangle
the interpolated function is a cubic polynomial of the 2 coordinates).
This technique originates from FEM (Finite Element Method) analysis;
the element used is a reduced Hsieh-Clough-Tocher (HCT)
element. Its shape functions are described in [1]_.
The assembled function is guaranteed to be C1-smooth, i.e. it is
continuous and its first derivatives are also continuous (this
is easy to show inside the triangles but is also true when crossing the
edges).
In the default case (*kind* ='min_E'), the interpolant minimizes a
curvature energy on the functional space generated by the HCT element
shape functions - with imposed values but arbitrary derivatives at each
node. The minimized functional is the integral of the so-called total
curvature (implementation based on an algorithm from [2]_ - PCG sparse
solver):
.. math::
E(z) = \frac{1}{2} \int_{\Omega} \left(
\left( \frac{\partial^2{z}}{\partial{x}^2} \right)^2 +
\left( \frac{\partial^2{z}}{\partial{y}^2} \right)^2 +
2\left( \frac{\partial^2{z}}{\partial{y}\partial{x}} \right)^2
\right) dx\,dy
If the case *kind* ='geom' is chosen by the user, a simple geometric
approximation is used (weighted average of the triangle normal
vectors), which could improve speed on very large grids.
References
----------
.. [1] Michel Bernadou, Kamal Hassan, "Basis functions for general
Hsieh-Clough-Tocher triangles, complete or reduced.",
International Journal for Numerical Methods in Engineering,
17(5):784 - 789. 2.01.
.. [2] C.T. Kelley, "Iterative Methods for Optimization".
"""
def __init__(self, triangulation, z, kind='min_E', trifinder=None,
dz=None):
super().__init__(triangulation, z, trifinder)
# Loads the underlying c++ _triangulation.
# (During loading, reordering of triangulation._triangles may occur so
# that all final triangles are now anti-clockwise)
self._triangulation.get_cpp_triangulation()
# To build the stiffness matrix and avoid zero-energy spurious modes
# we will only store internally the valid (unmasked) triangles and
# the necessary (used) points coordinates.
# 2 renumbering tables need to be computed and stored:
# - a triangle renum table in order to translate the result from a
# TriFinder instance into the internal stored triangle number.
# - a node renum table to overwrite the self._z values into the new
# (used) node numbering.
tri_analyzer = TriAnalyzer(self._triangulation)
(compressed_triangles, compressed_x, compressed_y, tri_renum,
node_renum) = tri_analyzer._get_compressed_triangulation()
self._triangles = compressed_triangles
self._tri_renum = tri_renum
# Taking into account the node renumbering in self._z:
valid_node = (node_renum != -1)
self._z[node_renum[valid_node]] = self._z[valid_node]
# Computing scale factors
self._unit_x = np.ptp(compressed_x)
self._unit_y = np.ptp(compressed_y)
self._pts = np.column_stack([compressed_x / self._unit_x,
compressed_y / self._unit_y])
# Computing triangle points
self._tris_pts = self._pts[self._triangles]
# Computing eccentricities
self._eccs = self._compute_tri_eccentricities(self._tris_pts)
# Computing dof estimations for HCT triangle shape function
_api.check_in_list(['user', 'geom', 'min_E'], kind=kind)
self._dof = self._compute_dof(kind, dz=dz)
# Loading HCT element
self._ReferenceElement = _ReducedHCT_Element()
def __call__(self, x, y):
return self._interpolate_multikeys(x, y, tri_index=None,
return_keys=('z',))[0]
__call__.__doc__ = TriInterpolator._docstring__call__
def gradient(self, x, y):
return self._interpolate_multikeys(x, y, tri_index=None,
return_keys=('dzdx', 'dzdy'))
gradient.__doc__ = TriInterpolator._docstringgradient
def _interpolate_single_key(self, return_key, tri_index, x, y):
_api.check_in_list(['z', 'dzdx', 'dzdy'], return_key=return_key)
tris_pts = self._tris_pts[tri_index]
alpha = self._get_alpha_vec(x, y, tris_pts)
ecc = self._eccs[tri_index]
dof = np.expand_dims(self._dof[tri_index], axis=1)
if return_key == 'z':
return self._ReferenceElement.get_function_values(
alpha, ecc, dof)
else: # 'dzdx', 'dzdy'
J = self._get_jacobian(tris_pts)
dzdx = self._ReferenceElement.get_function_derivatives(
alpha, J, ecc, dof)
if return_key == 'dzdx':
return dzdx[:, 0, 0]
else:
return dzdx[:, 1, 0]
def _compute_dof(self, kind, dz=None):
"""
Compute and return nodal dofs according to kind.
Parameters
----------
kind : {'min_E', 'geom', 'user'}
Choice of the _DOF_estimator subclass to estimate the gradient.
dz : tuple of array-likes (dzdx, dzdy), optional
Used only if *kind*=user; in this case passed to the
:class:`_DOF_estimator_user`.
Returns
-------
array-like, shape (npts, 2)
Estimation of the gradient at triangulation nodes (stored as
degree of freedoms of reduced-HCT triangle elements).
"""
if kind == 'user':
if dz is None:
raise ValueError("For a CubicTriInterpolator with "
"*kind*='user', a valid *dz* "
"argument is expected.")
TE = _DOF_estimator_user(self, dz=dz)
elif kind == 'geom':
TE = _DOF_estimator_geom(self)
else: # 'min_E', checked in __init__
TE = _DOF_estimator_min_E(self)
return TE.compute_dof_from_df()
@staticmethod
def _get_alpha_vec(x, y, tris_pts):
"""
Fast (vectorized) function to compute barycentric coordinates alpha.
Parameters
----------
x, y : array-like of dim 1 (shape (nx,))
Coordinates of the points whose points barycentric coordinates are
requested.
tris_pts : array like of dim 3 (shape: (nx, 3, 2))
Coordinates of the containing triangles apexes.
Returns
-------
array of dim 2 (shape (nx, 3))
Barycentric coordinates of the points inside the containing
triangles.
"""
ndim = tris_pts.ndim-2
a = tris_pts[:, 1, :] - tris_pts[:, 0, :]
b = tris_pts[:, 2, :] - tris_pts[:, 0, :]
abT = np.stack([a, b], axis=-1)
ab = _transpose_vectorized(abT)
OM = np.stack([x, y], axis=1) - tris_pts[:, 0, :]
metric = ab @ abT
# Here we try to deal with the colinear cases.
# metric_inv is in this case set to the Moore-Penrose pseudo-inverse
# meaning that we will still return a set of valid barycentric
# coordinates.
metric_inv = _pseudo_inv22sym_vectorized(metric)
Covar = ab @ _transpose_vectorized(np.expand_dims(OM, ndim))
ksi = metric_inv @ Covar
alpha = _to_matrix_vectorized([
[1-ksi[:, 0, 0]-ksi[:, 1, 0]], [ksi[:, 0, 0]], [ksi[:, 1, 0]]])
return alpha
@staticmethod
def _get_jacobian(tris_pts):
"""
Fast (vectorized) function to compute triangle jacobian matrix.
Parameters
----------
tris_pts : array like of dim 3 (shape: (nx, 3, 2))
Coordinates of the containing triangles apexes.
Returns
-------
array of dim 3 (shape (nx, 2, 2))
Barycentric coordinates of the points inside the containing
triangles.
J[itri, :, :] is the jacobian matrix at apex 0 of the triangle
itri, so that the following (matrix) relationship holds:
[dz/dksi] = [J] x [dz/dx]
with x: global coordinates
ksi: element parametric coordinates in triangle first apex
local basis.
"""
a = np.array(tris_pts[:, 1, :] - tris_pts[:, 0, :])
b = np.array(tris_pts[:, 2, :] - tris_pts[:, 0, :])
J = _to_matrix_vectorized([[a[:, 0], a[:, 1]],
[b[:, 0], b[:, 1]]])
return J
@staticmethod
def _compute_tri_eccentricities(tris_pts):
"""
Compute triangle eccentricities.
Parameters
----------
tris_pts : array like of dim 3 (shape: (nx, 3, 2))
Coordinates of the triangles apexes.
Returns
-------
array like of dim 2 (shape: (nx, 3))
The so-called eccentricity parameters [1] needed for HCT triangular
element.
"""
a = np.expand_dims(tris_pts[:, 2, :] - tris_pts[:, 1, :], axis=2)
b = np.expand_dims(tris_pts[:, 0, :] - tris_pts[:, 2, :], axis=2)
c = np.expand_dims(tris_pts[:, 1, :] - tris_pts[:, 0, :], axis=2)
# Do not use np.squeeze, this is dangerous if only one triangle
# in the triangulation...
dot_a = (_transpose_vectorized(a) @ a)[:, 0, 0]
dot_b = (_transpose_vectorized(b) @ b)[:, 0, 0]
dot_c = (_transpose_vectorized(c) @ c)[:, 0, 0]
# Note that this line will raise a warning for dot_a, dot_b or dot_c
# zeros, but we choose not to support triangles with duplicate points.
return _to_matrix_vectorized([[(dot_c-dot_b) / dot_a],
[(dot_a-dot_c) / dot_b],
[(dot_b-dot_a) / dot_c]])
# FEM element used for interpolation and for solving minimisation
# problem (Reduced HCT element)
| CubicTriInterpolator |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/test_annotated_types.py | {
"start": 4094,
"end": 5164
} | class ____:
__is_annotated_types_grouped_metadata__ = True
def __init__(self, *args) -> None:
self._args = args
def __iter__(self):
return iter(self._args)
def __repr__(self) -> str:
return f"GroupedStuff({', '.join(map(repr, self._args))})"
def test_flattens_grouped_metadata():
grp = GroupedStuff(GroupedStuff(GroupedStuff(at.Len(min_length=1, max_length=5))))
constraints = list(_get_constraints(grp))
assert constraints == [at.MinLen(1), at.MaxLen(5)]
try:
# we can drop this ugly code when Python 3.10 reaches EOL
from typing import NotRequired, TypedDict
except ImportError:
pass
else:
class TypedDictWithAnnotations(TypedDict):
x: Annotated[int, at.Ge(0)]
y: Annotated[NotRequired[int], at.Ge(0)]
z: NotRequired[Annotated[int, at.Ge(0)]]
@given(st.from_type(TypedDictWithAnnotations))
def test_typeddict_with_annotated_constraints(value):
assert value["x"] >= 0
assert value.get("y", 0) >= 0
assert value.get("z", 0) >= 0
| GroupedStuff |
python | spack__spack | lib/spack/spack/modules/common.py | {
"start": 37509,
"end": 37685
} | class ____(AttributeError, ModulesError):
"""Raised if the attribute ``default_template`` has not been specified
in the derived classes.
"""
| DefaultTemplateNotDefined |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_select_dtypes.py | {
"start": 534,
"end": 954
} | class ____(ExtensionArray):
def __init__(self, data, dtype) -> None:
self.data = data
self._dtype = dtype
def __array__(self, dtype=None, copy=None):
return self.data
@property
def dtype(self):
return self._dtype
def __len__(self) -> int:
return len(self.data)
def __getitem__(self, item):
pass
def copy(self):
return self
| DummyArray |
python | huggingface__transformers | tests/models/mamba2/test_modeling_mamba2.py | {
"start": 14426,
"end": 20473
} | class ____(unittest.TestCase):
def setUp(self):
self.model_id = "mistralai/Mamba-Codestral-7B-v0.1"
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id, from_slow=True, legacy=False)
self.prompt = ("[INST]Write a hello world program in C++.",)
@require_read_token
@slow
@require_torch
def test_simple_generate(self):
"""
Simple generate test to avoid regressions.
Note: state-spaces (cuda) implementation and pure torch implementation
have irreconciliable differences as of now, which will cause this test to fail
in an environment with state-spaces installed.
"""
tokenizer = self.tokenizer
tokenizer.pad_token_id = tokenizer.eos_token_id
model = Mamba2ForCausalLM.from_pretrained(self.model_id, dtype=torch.bfloat16)
model.to(torch_device)
input_ids = tokenizer("[INST]Write a hello world program in C++.[/INST]", return_tensors="pt")["input_ids"].to(
torch_device
)
out = model.generate(input_ids, do_sample=False, use_cache=True, max_new_tokens=30)
output_sentence = tokenizer.decode(out[0])
ground_truth_sentences = Expectations(
{
("xpu", 3): """<s>[INST]Write a hello world program in C++.[/INST] Sure, here is a simple "Hello, World!" program written in C++:\n\n```cpp\n#include <iostream>\n""",
("cuda", 7): """<s>[INST]Write a hello world program in C++.[/INST] Sure, here is a simple "Hello, World!" program in C++:\n\n```cpp\n#include <iostream>\n\n""",
}
) # fmt: skip
ground_truth_sentence = ground_truth_sentences.get_expectation()
self.assertEqual(output_sentence, ground_truth_sentence)
@require_read_token
@slow
@require_torch_accelerator
def test_batched_equivalence_with_cache(self):
"""
Verifies that batched generation matches individual generation.
Important because of the specific caching mechanism + statefulness of mamba model.
Depending on precision and devices, differences can be observed from generation to generation.
"""
tokenizer = self.tokenizer
prompt = [
"[INST]Write C#.[/INST]",
"[INST]Write a hello world in C++.[/INST]",
"[INST] Write a simple Fibonacci number computation function in Rust that does memoization, with comments, in safe Rust.[/INST]",
]
model = Mamba2ForCausalLM.from_pretrained(self.model_id, dtype=torch.bfloat16).to(torch_device)
tokenizer.pad_token_id = tokenizer.eos_token_id
# batched generation
tokenized_prompts = tokenizer(prompt, return_tensors="pt", padding="longest").to(torch_device)
batched_gen = model.generate(**tokenized_prompts, max_new_tokens=30, use_cache=True)
batched_output = tokenizer.batch_decode(batched_gen, skip_special_tokens=True)
# individual generation
for index_gen, individual_prompt in enumerate(prompt):
inputs = tokenizer(individual_prompt, return_tensors="pt", padding="longest").to(torch_device)
individual_gen = model.generate(**inputs, max_new_tokens=30, use_cache=True)
individual_output = tokenizer.batch_decode(individual_gen, skip_special_tokens=True)[0]
self.assertEqual(individual_output[:100], batched_output[index_gen][:100])
@require_read_token
@slow
@require_torch_accelerator
def test_batched_equivalence_without_cache(self):
"""
Verifies that batched generation matches individual generation without cache.
Important because of the specific caching mechanism + statefulness of mamba model.
Depending on precision and devices, differences can be observed from generation to generation.
"""
tokenizer = self.tokenizer
prompt = [
"[INST]Write C#.[/INST]",
"[INST]Write a hello world in C++.[/INST]",
"[INST] Write a simple Fibonacci number computation function in Rust that does memoization, with comments, in safe Rust.[/INST]",
]
model = Mamba2ForCausalLM.from_pretrained(self.model_id, dtype=torch.bfloat16).to(torch_device)
tokenizer.pad_token_id = tokenizer.eos_token_id
# batched generation
tokenized_prompts = tokenizer(prompt, return_tensors="pt", padding="longest").to(torch_device)
batched_gen = model.generate(**tokenized_prompts, max_new_tokens=30, use_cache=True)
batched_output = tokenizer.batch_decode(batched_gen, skip_special_tokens=True)
# individual generation
for index_gen, individual_prompt in enumerate(prompt):
inputs = tokenizer(individual_prompt, return_tensors="pt", padding="longest").to(torch_device)
individual_gen = model.generate(**inputs, max_new_tokens=30, use_cache=True)
individual_output = tokenizer.batch_decode(individual_gen, skip_special_tokens=True)[0]
self.assertEqual(individual_output[:100], batched_output[index_gen][:100])
@slow
@require_torch_accelerator
def test_mamba2_mixer_train_vs_eval_equivalence(self):
# Based on https://github.com/sustcsonglin/flash-linear-attention/issues/63
# Credit to zhixuan-lin
B, T, D = 4, 512, 768
dtype = torch.bfloat16
config = Mamba2Config(num_heads=24, head_dim=64, hidden_size=768, expand=2, n_groups=1)
torch.manual_seed(42)
with torch.autocast(device_type=torch_device, dtype=dtype):
with torch.no_grad():
mixer = Mamba2Mixer(config, layer_idx=0).to(torch_device)
hidden_states = torch.rand(size=(B, T, D), dtype=dtype, device=torch_device)
mixer.train()
out_train = mixer(hidden_states)
mixer.eval()
out_eval = mixer(hidden_states)
torch.testing.assert_close(out_train, out_eval, rtol=1e-3, atol=1e-3)
| Mamba2IntegrationTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/cwise_ops_unary_test.py | {
"start": 2396,
"end": 27843
} | class ____(test.TestCase):
def _compareCpu(self, x, np_func, tf_func, grad_rtol=None, grad_atol=None):
if grad_rtol is None:
grad_rtol = _default_tolerance(x.dtype)
if grad_atol is None:
grad_atol = _default_tolerance(x.dtype)
np_ans = np_func(x)
with self.cached_session(use_gpu=False):
inx = ops.convert_to_tensor(x)
y = tf_func(inx)
tf_cpu = self.evaluate(y)
self.assertShapeEqual(np_ans, y)
if x.dtype == np.float16:
self.assertAllClose(np_ans, tf_cpu, rtol=1e-3, atol=1e-3)
elif x.dtype == dtypes_lib.bfloat16.as_numpy_dtype:
self.assertAllClose(np_ans, tf_cpu, rtol=1e-2, atol=1e-2)
else:
self.assertAllClose(np_ans, tf_cpu)
if x.dtype in (np.complex64, np.complex128) and tf_func == math_ops.sign:
return # Return early
if tf_func == math_ops.round:
return # Return early
if x.dtype in (np.float16, dtypes_lib.bfloat16.as_numpy_dtype):
s = list(np.shape(x))
jacob_t, _ = gradient_checker.compute_gradient(
inx, s, y, s, x_init_value=x)
xf = x.astype(np.float64)
inxf = ops.convert_to_tensor(xf)
yf = tf_func(inxf)
_, jacob_n = gradient_checker.compute_gradient(
inxf, s, yf, s, x_init_value=xf, delta=1e-2)
jacob_n = jacob_n.astype(x.dtype)
self.assertAllClose(jacob_t, jacob_n, rtol=grad_rtol, atol=grad_atol)
elif x.dtype in (np.float32, np.complex64):
s = list(np.shape(x))
jacob_t, jacob_n = gradient_checker.compute_gradient(
inx, s, y, s, x_init_value=x, delta=1e-3)
self.assertAllClose(jacob_t, jacob_n, rtol=grad_rtol, atol=grad_atol)
elif x.dtype in (np.float64, np.complex128):
s = list(np.shape(x))
jacob_t, jacob_n = gradient_checker.compute_gradient(
inx, s, y, s, x_init_value=x, delta=1e-5)
self.assertAllClose(jacob_t, jacob_n, rtol=grad_rtol, atol=grad_atol)
def _check(self, result_tensor, result_np, input_sp_t, tol):
self.assertTrue(isinstance(result_tensor, sparse_tensor.SparseTensor))
self.assertTrue(isinstance(input_sp_t, sparse_tensor.SparseTensor))
self.assertAllEqual(input_sp_t.indices, result_tensor.indices)
self.assertAllEqual(input_sp_t.dense_shape, result_tensor.dense_shape)
if tol is None:
self.assertAllClose(result_np, result_tensor.values)
else:
self.assertAllClose(result_np, result_tensor.values, rtol=tol, atol=tol)
def _compareSparseCpu(self, x, np_func, tf_func, tol):
x_sp, x_sp_vals = _sparsify(x)
res_np = np_func(x_sp_vals)
with test_util.force_cpu():
self._check(tf_func(x_sp), res_np, x_sp, tol)
def _compareGpu(self, x, np_func, tf_func):
np_ans = np_func(x)
with test_util.use_gpu():
result = tf_func(ops.convert_to_tensor(x))
tf_gpu = self.evaluate(result)
# Slightly increase the tolerance for float64 computations. This is
# desired for specifically lgamma but shouldn't be of concern for other
# functions.
self.assertAllCloseAccordingToType(np_ans, tf_gpu, atol=2e-6)
# TODO(zhifengc/ke): make gradient checker work on GPU.
def _compareSparseGpu(self, x, np_func, tf_func, tol):
x_sp, x_sp_vals = _sparsify(x)
res_np = np_func(x_sp_vals)
with test_util.use_gpu():
self._check(tf_func(x_sp), res_np, x_sp, tol)
def _compareBoth(self, x, np_func, tf_func, grad_tol=None):
self._compareCpu(x, np_func, tf_func, grad_rtol=grad_tol,
grad_atol=grad_tol)
self._compareGpu(x, np_func, tf_func)
def _compareBothSparse(self, x, np_func, tf_func, tol=None):
self._compareSparseCpu(x, np_func, tf_func, tol)
self._compareSparseGpu(x, np_func, tf_func, tol)
def _inv(self, x):
return 1.0 / x
def _rsqrt(self, x):
return self._inv(np.sqrt(x))
def _sigmoid(self, x):
return 1.0 / (1.0 + np.exp(-x))
def _log_sigmoid(self, x):
return np.log(self._sigmoid(x))
def _replace_domain_error_with_inf(self, fn):
def func(x):
try:
return fn(x)
except ValueError as e:
if "domain error" in str(e):
return np.inf * np.ones_like(x)
else:
raise e
return func
@test_util.run_deprecated_v1
def testFloatBasic(self):
x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float32)
w = x - x.min() + 1.02 # all greater than 1
y = (x + .5).astype(np.float32) # no zero
z = (x + 15.5).astype(np.float32) # all positive
k = np.arange(-0.90, 0.90, 0.25).astype(np.float32) # between -1 and 1
self._compareBoth(x, np.abs, math_ops.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, self._inv, math_ops.reciprocal)
self._compareBoth(x, np.square, math_ops.square)
self._compareBoth(z, np.sqrt, math_ops.sqrt)
self._compareBoth(z, self._rsqrt, math_ops.rsqrt)
self._compareBoth(x, np.exp, math_ops.exp)
self._compareBoth(x, np.expm1, math_ops.expm1)
self._compareBoth(z, np.log, math_ops.log)
self._compareBoth(z, np.log1p, math_ops.log1p)
self._compareBoth(x, np.sinh, math_ops.sinh)
self._compareBoth(x, np.cosh, math_ops.cosh)
self._compareBoth(x, np.tanh, math_ops.tanh)
self._compareBoth(x, np.arcsinh, math_ops.asinh)
self._compareBoth(w, np.arccosh, math_ops.acosh)
self._compareBoth(k, np.arctanh, math_ops.atanh)
self._compareBoth(x, self._sigmoid, math_ops.sigmoid)
self._compareBoth(x, self._log_sigmoid, math_ops.log_sigmoid)
self._compareBoth(y, np.sign, math_ops.sign)
self._compareBoth(x, np.sin, math_ops.sin)
self._compareBoth(x, np.cos, math_ops.cos)
self._compareBoth(k, np.arcsin, math_ops.asin)
self._compareBoth(k, np.arccos, math_ops.acos)
self._compareBoth(x, np.arctan, math_ops.atan)
self._compareBoth(x, np.tan, math_ops.tan)
self._compareBoth(
y, np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
math_ops.lgamma)
self._compareBoth(x, np.vectorize(math.erf), math_ops.erf)
self._compareBoth(x, np.vectorize(math.erfc), math_ops.erfc)
try:
from scipy import special # pylint: disable=g-import-not-at-top
self._compareBoth(x, special.i0e, special_math_ops.bessel_i0e)
self._compareBoth(x, special.i1e, special_math_ops.bessel_i1e)
except ImportError as e:
tf_logging.warn("Cannot test special functions: %s" % str(e))
self._compareBothSparse(x, np.abs, math_ops.abs)
self._compareBothSparse(x, np.negative, math_ops.negative)
self._compareBothSparse(x, np.square, math_ops.square)
self._compareBothSparse(z, np.sqrt, math_ops.sqrt, tol=1e-3)
self._compareBothSparse(x, np.tanh, math_ops.tanh)
self._compareBothSparse(y, np.sign, math_ops.sign)
self._compareBothSparse(x, np.vectorize(math.erf), math_ops.erf)
@test_util.run_deprecated_v1
def testFloatTanhEdge(self):
x = np.arange(40, 40 + 6).reshape(6).astype(np.float32)
self._compareBoth(x, np.tanh, math_ops.tanh)
x = np.arange(-40, -40 + 6).reshape(6).astype(np.float32)
self._compareBoth(x, np.tanh, math_ops.tanh)
@test_util.run_deprecated_v1
def testFloatEmpty(self):
x = np.empty((2, 0, 5), dtype=np.float32)
self._compareBoth(x, np.abs, math_ops.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(x, self._inv, math_ops.reciprocal)
self._compareBoth(x, np.square, math_ops.square)
self._compareBoth(x, np.sqrt, math_ops.sqrt)
self._compareBoth(x, self._rsqrt, math_ops.rsqrt)
self._compareBoth(x, np.exp, math_ops.exp)
self._compareBoth(x, np.expm1, math_ops.expm1)
self._compareBoth(x, np.log, math_ops.log)
self._compareBoth(x, np.log1p, math_ops.log1p)
self._compareBoth(x, np.sinh, math_ops.sinh)
self._compareBoth(x, np.arcsinh, math_ops.asinh)
self._compareBoth(x, np.cosh, math_ops.cosh)
self._compareBoth(x, np.arccosh, math_ops.acosh)
self._compareBoth(x, np.tanh, math_ops.tanh)
self._compareBoth(x, np.arctanh, math_ops.atanh)
self._compareBoth(x, self._sigmoid, math_ops.sigmoid)
self._compareBoth(x, np.sign, math_ops.sign)
self._compareBoth(x, np.sin, math_ops.sin)
self._compareBoth(x, np.cos, math_ops.cos)
# Can't use vectorize below, so just use some arbitrary function
self._compareBoth(x, np.sign, math_ops.lgamma)
self._compareBoth(x, np.sign, math_ops.erf)
self._compareBoth(x, np.sign, math_ops.erfc)
self._compareBoth(x, np.tan, math_ops.tan)
self._compareBoth(x, np.arcsin, math_ops.asin)
self._compareBoth(x, np.arccos, math_ops.acos)
self._compareBoth(x, np.arctan, math_ops.atan)
try:
from scipy import special # pylint: disable=g-import-not-at-top
self._compareBoth(x, special.i0e, special_math_ops.bessel_i0e)
self._compareBoth(x, special.i1e, special_math_ops.bessel_i1e)
except ImportError as e:
tf_logging.warn("Cannot test special functions: %s" % str(e))
self._compareBothSparse(x, np.abs, math_ops.abs)
self._compareBothSparse(x, np.negative, math_ops.negative)
self._compareBothSparse(x, np.square, math_ops.square)
self._compareBothSparse(x, np.sqrt, math_ops.sqrt, tol=1e-3)
self._compareBothSparse(x, np.tanh, math_ops.tanh)
self._compareBothSparse(x, np.sign, math_ops.sign)
self._compareBothSparse(x, np.sign, math_ops.erf)
@test_util.run_deprecated_v1
def testDoubleBasic(self):
x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float64)
w = x - x.min() + 1.02 # all greater than 1
y = (x + .5).astype(np.float64) # no zero
z = (x + 15.5).astype(np.float64) # all positive
k = np.arange(-0.90, 0.90,
0.35).reshape(1, 3, 2).astype(np.float64) # between -1 and 1
self._compareBoth(x, np.abs, math_ops.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, self._inv, math_ops.reciprocal)
self._compareBoth(x, np.square, math_ops.square)
self._compareBoth(z, np.sqrt, math_ops.sqrt)
self._compareBoth(z, self._rsqrt, math_ops.rsqrt)
self._compareBoth(x, np.exp, math_ops.exp)
self._compareBoth(x, np.expm1, math_ops.expm1)
self._compareBoth(z, np.log, math_ops.log)
self._compareBoth(z, np.log1p, math_ops.log1p)
self._compareBoth(x, np.sinh, math_ops.sinh)
self._compareBoth(x, np.cosh, math_ops.cosh)
self._compareBoth(x, np.tanh, math_ops.tanh)
self._compareBoth(x, np.arcsinh, math_ops.asinh)
self._compareBoth(w, np.arccosh, math_ops.acosh)
self._compareBoth(k, np.arctanh, math_ops.atanh)
self._compareBoth(x, self._sigmoid, math_ops.sigmoid)
self._compareBoth(y, np.sign, math_ops.sign)
self._compareBoth(x, np.sin, math_ops.sin)
self._compareBoth(x, np.cos, math_ops.cos)
self._compareBoth(
y, np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
math_ops.lgamma)
self._compareBoth(x, np.vectorize(math.erf), math_ops.erf)
self._compareBoth(x, np.vectorize(math.erfc), math_ops.erfc)
self._compareBoth(x, np.arctan, math_ops.atan)
self._compareBoth(k, np.arcsin, math_ops.asin)
self._compareBoth(k, np.arccos, math_ops.acos)
self._compareBoth(k, np.tan, math_ops.tan)
try:
from scipy import special # pylint: disable=g-import-not-at-top
self._compareBoth(x, special.i0e, special_math_ops.bessel_i0e)
self._compareBoth(x, special.i1e, special_math_ops.bessel_i1e)
except ImportError as e:
tf_logging.warn("Cannot test special functions: %s" % str(e))
self._compareBothSparse(x, np.abs, math_ops.abs)
self._compareBothSparse(x, np.negative, math_ops.negative)
self._compareBothSparse(x, np.square, math_ops.square)
self._compareBothSparse(z, np.sqrt, math_ops.sqrt, tol=1e-3)
self._compareBothSparse(x, np.tanh, math_ops.tanh)
self._compareBothSparse(y, np.sign, math_ops.sign)
self._compareBothSparse(x, np.vectorize(math.erf), math_ops.erf)
@test_util.run_deprecated_v1
def testHalfBasic(self):
x = np.arange(-3, 3).reshape(1, 3, 2).astype(np.float16)
w = x - x.min() + 1.1 # all greater than 1
y = (x + .5).astype(np.float16) # no zero
z = (x + 15.5).astype(np.float16) # all positive
k = np.arange(-0.90, 0.90, 0.05).astype(np.float16) # between -1 and 1
self._compareBoth(x, np.abs, math_ops.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, self._inv, math_ops.reciprocal)
self._compareBoth(x, np.square, math_ops.square)
self._compareBoth(z, np.sqrt, math_ops.sqrt)
self._compareBoth(z, self._rsqrt, math_ops.rsqrt)
self._compareBoth(x, np.exp, math_ops.exp)
self._compareBoth(x, np.expm1, math_ops.expm1)
self._compareBoth(z, np.log, math_ops.log)
self._compareBoth(z, np.log1p, math_ops.log1p)
self._compareBoth(x, np.sinh, math_ops.sinh)
self._compareBoth(x, np.cosh, math_ops.cosh)
self._compareBoth(x, np.tanh, math_ops.tanh)
self._compareBoth(x, self._sigmoid, math_ops.sigmoid)
self._compareBoth(y, np.sign, math_ops.sign)
self._compareBoth(x, np.sin, math_ops.sin)
self._compareBoth(x, np.cos, math_ops.cos)
self._compareBoth(x, np.tan, math_ops.tan)
self._compareBoth(k, np.arcsin, math_ops.asin)
self._compareBoth(k, np.arccos, math_ops.acos)
self._compareBoth(x, np.arctan, math_ops.atan)
self._compareBoth(x, np.arcsinh, math_ops.asinh)
# The derivative of acosh close to 1 is very large, and needs a high
# tolerance for small precision.
self._compareBoth(w, np.arccosh, math_ops.acosh, grad_tol=1e-3)
self._compareBoth(k, np.arctanh, math_ops.atanh)
self._compareBoth(
y, np.vectorize(self._replace_domain_error_with_inf(math.lgamma)),
math_ops.lgamma)
self._compareBoth(x, np.vectorize(math.erf), math_ops.erf)
self._compareBoth(x, np.vectorize(math.erfc), math_ops.erfc)
self._compareBothSparse(x, np.abs, math_ops.abs)
self._compareBothSparse(x, np.negative, math_ops.negative)
self._compareBothSparse(x, np.square, math_ops.square)
self._compareBothSparse(z, np.sqrt, math_ops.sqrt, tol=1e-3)
self._compareBothSparse(x, np.tanh, math_ops.tanh)
self._compareBothSparse(y, np.sign, math_ops.sign)
self._compareBothSparse(x, np.vectorize(math.erf), math_ops.erf, tol=1e-3)
@test_util.run_deprecated_v1
def testBFloat16Basic(self):
def compute_f32(np_func):
"""Decorator to compute Numpy function with float32 math."""
def f(x):
y = np_func(x.astype(np.float32))
return y.astype(x.dtype)
return f
bfloat16 = dtypes_lib.bfloat16.as_numpy_dtype
x = np.arange(-6, 6,
2).reshape(1, 3, 2).astype(bfloat16)
w = x - x.min() + 1.1 # all greater than 1
y = (x + .5).astype(bfloat16) # no zero
z = (x + 15.5).astype(bfloat16) # all positive
k = np.arange(-0.90, 0.90, 0.05).astype(bfloat16) # between -1 and 1
self._compareBoth(x, np.abs, math_ops.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, compute_f32(self._inv), math_ops.reciprocal)
self._compareCpu(x, np.round, math_ops.round)
self._compareCpu(x, np.exp, math_ops.exp)
self._compareCpu(x, np.expm1, math_ops.expm1)
self._compareCpu(z, compute_f32(np.log), math_ops.log)
self._compareCpu(z, compute_f32(np.log1p), math_ops.log1p)
self._compareBoth(y, np.sign, math_ops.sign)
self._compareCpu(z, self._rsqrt, math_ops.rsqrt)
self._compareCpu(x, np.square, math_ops.square)
self._compareBoth(x, compute_f32(np.sin), math_ops.sin)
self._compareBoth(x, compute_f32(np.cos), math_ops.cos)
self._compareBoth(x, compute_f32(np.tan), math_ops.tan)
self._compareBoth(x, compute_f32(np.sinh), math_ops.sinh)
self._compareBoth(x, compute_f32(np.cosh), math_ops.cosh)
self._compareBoth(x, compute_f32(np.tanh), math_ops.tanh)
self._compareBoth(k, compute_f32(np.arcsin), math_ops.asin)
self._compareBoth(k, compute_f32(np.arccos), math_ops.acos)
self._compareBoth(x, compute_f32(np.arctan), math_ops.atan)
self._compareBoth(x, compute_f32(np.arcsinh), math_ops.asinh)
self._compareBoth(w, compute_f32(np.arccosh), math_ops.acosh)
self._compareBoth(k, compute_f32(np.arctanh), math_ops.atanh,
grad_tol=1e-2)
self._compareBoth(x, compute_f32(np.vectorize(math.erf)), math_ops.erf)
self._compareBoth(x, compute_f32(np.vectorize(math.erfc)), math_ops.erfc)
self._compareBoth(x, compute_f32(np.square), math_ops.square)
def testInt8Basic(self):
x = np.arange(-6, 6, 2).reshape(1, 3, 2).astype(np.int8)
self._compareCpu(x, np.abs, math_ops.abs)
self._compareCpu(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(x, np.sign, math_ops.sign)
def testUInt8Basic(self):
x = np.arange(6).reshape(1, 3, 2).astype(np.uint8)
self._compareBoth(x, np.square, math_ops.square)
def testInt16Basic(self):
x = np.arange(-6, 6, 2).reshape(1, 3, 2).astype(np.int16)
self._compareCpu(x, np.abs, math_ops.abs)
self._compareCpu(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(x, np.sign, math_ops.sign)
def testUInt16Basic(self):
x = np.arange(6).reshape(1, 3, 2).astype(np.uint16)
self._compareBoth(x, np.square, math_ops.square)
def testInt32Basic(self):
x = np.arange(-6, 6, 2).reshape(1, 3, 2).astype(np.int32)
self._compareCpu(x, np.abs, math_ops.abs)
self._compareCpu(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(x, np.square, math_ops.square)
self._compareCpu(x, np.sign, math_ops.sign)
self._compareBothSparse(x, np.abs, math_ops.abs)
self._compareBothSparse(x, np.negative, math_ops.negative)
self._compareBothSparse(x, np.square, math_ops.square)
self._compareBothSparse(x, np.sign, math_ops.sign)
def testUInt32Basic(self):
x = np.arange(6).reshape(1, 3, 2).astype(np.uint32)
self._compareBoth(x, np.square, math_ops.square)
def testInt64Basic(self):
x = np.arange(-6 << 40, 6 << 40, 2 << 40).reshape(1, 3, 2).astype(np.int64)
self._compareCpu(x, np.abs, math_ops.abs)
self._compareCpu(x, np.abs, _ABS)
self._compareCpu(x, np.negative, math_ops.negative)
self._compareCpu(x, np.negative, _NEG)
self._compareCpu(x, np.sign, math_ops.sign)
self._compareBothSparse(x, np.abs, math_ops.abs)
self._compareBothSparse(x, np.negative, math_ops.negative)
self._compareBothSparse(x, np.sign, math_ops.sign)
def testInt64Square(self):
x = np.arange(-6 << 20, 6 << 20, 2 << 20).reshape(1, 3, 2).astype(np.int64)
self._compareCpu(x, np.square, math_ops.square)
self._compareBothSparse(x, np.square, math_ops.square)
def testUInt64Basic(self):
x = np.arange(6).reshape(1, 3, 2).astype(np.uint64)
self._compareBoth(x, np.square, math_ops.square)
@test_util.run_deprecated_v1
def testComplex64Basic(self):
x = (1 + 1j) * np.arange(-3, 3).reshape(1, 3, 2).astype(np.complex64)
y = x + (0.5 + 0.5j) # no zeros
self._compareBoth(x, np.abs, math_ops.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, self._inv, math_ops.reciprocal)
self._compareCpu(x, np.square, math_ops.square)
self._compareCpu(y, np.sqrt, math_ops.sqrt)
self._compareCpu(y, self._rsqrt, math_ops.rsqrt)
self._compareBoth(x, np.exp, math_ops.exp)
self._compareCpu(x, np.expm1, math_ops.expm1)
self._compareCpu(y, np.log, math_ops.log)
self._compareCpu(y, np.log1p, math_ops.log1p)
self._compareCpu(x, np.sinh, math_ops.sinh)
self._compareCpu(x, np.cosh, math_ops.cosh)
self._compareCpu(x, np.tanh, math_ops.tanh)
self._compareCpu(x, np.arcsin, math_ops.asin)
self._compareCpu(x, np.arctan, math_ops.atan)
# Complex64 versions of asinh() and acosh() in libstdc++ only have 6 digits
# of precision.
# Small gradient values + low precision --> High relative error
self._compareCpu(y, np.arcsinh, math_ops.asinh, grad_rtol=1e-2)
self._compareCpu(y, np.arccosh, math_ops.acosh, grad_rtol=1e-2)
self._compareCpu(y, np.arctanh, math_ops.atanh)
self._compareCpu(x, self._sigmoid, math_ops.sigmoid)
self._compareCpu(x, np.sin, math_ops.sin)
self._compareCpu(x, np.cos, math_ops.cos)
self._compareBothSparse(x, np.abs, math_ops.abs)
self._compareBothSparse(x, np.negative, math_ops.negative)
self._compareBothSparse(x, np.square, math_ops.square)
self._compareBothSparse(x, np.sqrt, math_ops.sqrt, 1e-3)
self._compareBothSparse(x, np.tanh, math_ops.tanh)
# Numpy uses an incorrect definition of sign; use the right one instead.
def complex_sign(x):
return x / np.abs(x)
self._compareBoth(y, complex_sign, math_ops.sign)
self._compareBothSparse(y, complex_sign, math_ops.sign)
@test_util.run_deprecated_v1
def testComplex128Basic(self):
x = (1 + 1j) * np.arange(-3, 3).reshape(1, 3, 2).astype(np.complex128)
y = x + (0.5 + 0.5j) # no zeros
self._compareBoth(x, np.abs, math_ops.abs)
self._compareBoth(x, np.abs, _ABS)
self._compareBoth(x, np.negative, math_ops.negative)
self._compareBoth(x, np.negative, _NEG)
self._compareBoth(y, self._inv, math_ops.reciprocal)
self._compareCpu(x, np.square, math_ops.square)
self._compareCpu(y, np.sqrt, math_ops.sqrt)
self._compareCpu(y, self._rsqrt, math_ops.rsqrt)
self._compareBoth(x, np.exp, math_ops.exp)
self._compareCpu(x, np.expm1, math_ops.expm1)
self._compareCpu(y, np.log, math_ops.log)
self._compareCpu(y, np.log1p, math_ops.log1p)
self._compareCpu(x, np.sinh, math_ops.sinh)
self._compareCpu(x, np.cosh, math_ops.cosh)
self._compareCpu(x, np.tanh, math_ops.tanh)
self._compareCpu(y, np.arcsinh, math_ops.asinh)
self._compareCpu(y, np.arccosh, math_ops.acosh)
self._compareCpu(y, np.arctanh, math_ops.atanh)
self._compareCpu(x, self._sigmoid, math_ops.sigmoid)
self._compareCpu(x, np.sin, math_ops.sin)
self._compareCpu(x, np.cos, math_ops.cos)
self._compareCpu(x, np.arcsin, math_ops.asin)
self._compareCpu(x, np.arctan, math_ops.atan)
self._compareBothSparse(x, np.abs, math_ops.abs)
self._compareBothSparse(x, np.negative, math_ops.negative)
self._compareBothSparse(x, np.square, math_ops.square)
self._compareBothSparse(x, np.sqrt, math_ops.sqrt, 1e-3)
self._compareBothSparse(x, np.tanh, math_ops.tanh)
# Numpy uses an incorrect definition of sign; use the right one instead.
def complex_sign(x):
return x / np.abs(x)
self._compareBoth(y, complex_sign, math_ops.sign)
self._compareBothSparse(y, complex_sign, math_ops.sign)
@test_util.run_deprecated_v1
def testGradGrad(self):
np.random.seed(7)
shape = (5,)
dtype_tols = [(np.float32, 5e-4), (np.float64, 1e-6), (np.complex64, 5e-4),
(np.complex128, 1e-6)]
op_range = [
(gen_math_ops.reciprocal_grad, [-2, 2]),
(gen_math_ops.rsqrt_grad, [0.1, 3]),
(gen_math_ops.sigmoid_grad, [-2, 2]),
(gen_math_ops.sqrt_grad, [0.1, 3]),
(gen_math_ops.tanh_grad, [-2, 2]),
]
def rand(dtype, real_range):
x = np.random.uniform(
real_range[0], real_range[1], size=shape[0]).astype(dtype)
if dtype in (np.complex64, np.complex128):
x += 1j * np.random.uniform(-2, 2, size=shape[0]).astype(dtype)
return x
for op, real_range in op_range:
with self.cached_session():
for dtype, tol in dtype_tols:
x = constant_op.constant(rand(dtype, real_range))
y = constant_op.constant(rand(dtype, real_range))
z = op(x, y)
grads = gradient_checker.compute_gradient(
[x, y], [shape, shape],
z,
shape,
x_init_value=[rand(dtype, real_range),
rand(dtype, real_range)])
if isinstance(grads, tuple):
grads = [grads]
for analytical, numerical in grads:
self.assertAllClose(analytical, numerical, rtol=tol, atol=tol)
@test_util.run_in_graph_and_eager_modes
def testComplexAbsGradGrad(self):
def f(x):
real = math_ops.cos(x)
imag = ops.convert_to_tensor(1.)
return math_ops.abs(math_ops.complex(real, imag))
def g(x):
with backprop.GradientTape() as t:
t.watch(x)
y = f(x)
return t.gradient(y, x)
err = gradient_checker_v2.max_error(
*gradient_checker_v2.compute_gradient(g, [ops.convert_to_tensor(2.0)]))
self.assertLess(err, 1e-3)
if __name__ == "__main__":
test.main()
| UnaryOpTest |
python | python-markdown__markdown | markdown/extensions/footnotes.py | {
"start": 16601,
"end": 17429
} | class ____(Treeprocessor):
""" Build and append footnote div to end of document. """
def __init__(self, footnotes: FootnoteExtension):
self.footnotes = footnotes
def run(self, root: etree.Element) -> None:
footnotesDiv = self.footnotes.makeFootnotesDiv(root)
if footnotesDiv is not None:
result = self.footnotes.findFootnotesPlaceholder(root)
if result:
child, parent, isText = result
ind = list(parent).index(child)
if isText:
parent.remove(child)
parent.insert(ind, footnotesDiv)
else:
parent.insert(ind + 1, footnotesDiv)
child.tail = None
else:
root.append(footnotesDiv)
| FootnoteTreeprocessor |
python | openai__openai-python | src/openai/types/chat/chat_completion.py | {
"start": 1572,
"end": 3488
} | class ____(BaseModel):
id: str
"""A unique identifier for the chat completion."""
choices: List[Choice]
"""A list of chat completion choices.
Can be more than one if `n` is greater than 1.
"""
created: int
"""The Unix timestamp (in seconds) of when the chat completion was created."""
model: str
"""The model used for the chat completion."""
object: Literal["chat.completion"]
"""The object type, which is always `chat.completion`."""
service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] = None
"""Specifies the processing type used for serving the request.
- If set to 'auto', then the request will be processed with the service tier
configured in the Project settings. Unless otherwise configured, the Project
will use 'default'.
- If set to 'default', then the request will be processed with the standard
pricing and performance for the selected model.
- If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or
'[priority](https://openai.com/api-priority-processing/)', then the request
will be processed with the corresponding service tier.
- When not set, the default behavior is 'auto'.
When the `service_tier` parameter is set, the response body will include the
`service_tier` value based on the processing mode actually used to serve the
request. This response value may be different from the value set in the
parameter.
"""
system_fingerprint: Optional[str] = None
"""This fingerprint represents the backend configuration that the model runs with.
Can be used in conjunction with the `seed` request parameter to understand when
backend changes have been made that might impact determinism.
"""
usage: Optional[CompletionUsage] = None
"""Usage statistics for the completion request."""
| ChatCompletion |
python | donnemartin__interactive-coding-challenges | online_judges/mult_other_numbers/test_mult_other_numbers.py | {
"start": 18,
"end": 673
} | class ____(unittest.TestCase):
def test_mult_other_numbers(self):
solution = Solution()
self.assertRaises(TypeError, solution.mult_other_numbers, None)
self.assertEqual(solution.mult_other_numbers([0]), [])
self.assertEqual(solution.mult_other_numbers([0, 1]), [1, 0])
self.assertEqual(solution.mult_other_numbers([0, 1, 2]), [2, 0, 0])
self.assertEqual(solution.mult_other_numbers([1, 2, 3, 4]), [24, 12, 8, 6])
print('Success: test_mult_other_numbers')
def main():
test = TestMultOtherNumbers()
test.test_mult_other_numbers()
if __name__ == '__main__':
main()
| TestMultOtherNumbers |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 59137,
"end": 66361
} | class ____(Collection):
_attr = "shapes"
_kw = kw.shape
_wrap = Shape
@atexit.register
def cleanup():
"""
Since AppleScript cannot access Excel while a Macro is running, we have to run the
Python call in a background process which makes the call return immediately: we
rely on the StatusBar to give the user feedback.
This function is triggered when the interpreter exits and runs the CleanUp Macro in
VBA to show any errors and to reset the StatusBar.
"""
if is_excel_running():
# Prevents Excel from reopening
# if it has been closed manually or never been opened
for app in Apps():
try:
app.xl.run_VB_macro("CleanUp")
except (CommandError, AttributeError, aem.aemsend.EventError):
# Excel files initiated from Python don't have the xlwings VBA module
pass
def posix_to_hfs_path(posix_path):
"""
Turns a posix path (/Path/file.ext) into an HFS path (Macintosh HD:Path:file.ext)
"""
dir_name, file_name = os.path.split(posix_path)
dir_name_hfs = mactypes.Alias(dir_name).hfspath
return dir_name_hfs + ":" + file_name
def hfs_to_posix_path(hfs_path):
"""
Turns an HFS path (Macintosh HD:Path:file.ext) into a posix path (/Path/file.ext)
"""
url = mactypes.convertpathtourl(hfs_path, 1) # kCFURLHFSPathStyle = 1
return mactypes.converturltopath(url, 0) # kCFURLPOSIXPathStyle = 0
def is_excel_running():
for proc in psutil.process_iter():
try:
if proc.name() == "Microsoft Excel":
return True
except psutil.NoSuchProcess:
pass
return False
# --- constants ---
chart_types_k2s = {
kw.ThreeD_area: "3d_area",
kw.ThreeD_area_stacked: "3d_area_stacked",
kw.ThreeD_area_stacked_100: "3d_area_stacked_100",
kw.ThreeD_bar_clustered: "3d_bar_clustered",
kw.ThreeD_bar_stacked: "3d_bar_stacked",
kw.ThreeD_bar_stacked_100: "3d_bar_stacked_100",
kw.ThreeD_column: "3d_column",
kw.ThreeD_column_clustered: "3d_column_clustered",
kw.ThreeD_column_stacked: "3d_column_stacked",
kw.ThreeD_column_stacked_100: "3d_column_stacked_100",
kw.ThreeD_line: "3d_line",
kw.ThreeD_pie: "3d_pie",
kw.ThreeD_pie_exploded: "3d_pie_exploded",
kw.area_chart: "area",
kw.area_stacked: "area_stacked",
kw.area_stacked_100: "area_stacked_100",
kw.bar_clustered: "bar_clustered",
kw.bar_of_pie: "bar_of_pie",
kw.bar_stacked: "bar_stacked",
kw.bar_stacked_100: "bar_stacked_100",
kw.bubble: "bubble",
kw.bubble_ThreeD_effect: "bubble_3d_effect",
kw.column_clustered: "column_clustered",
kw.column_stacked: "column_stacked",
kw.column_stacked_100: "column_stacked_100",
kw.combination_chart: "combination",
kw.cone_bar_clustered: "cone_bar_clustered",
kw.cone_bar_stacked: "cone_bar_stacked",
kw.cone_bar_stacked_100: "cone_bar_stacked_100",
kw.cone_col: "cone_col",
kw.cone_column_clustered: "cone_col_clustered",
kw.cone_column_stacked: "cone_col_stacked",
kw.cone_column_stacked_100: "cone_col_stacked_100",
kw.cylinder_bar_clustered: "cylinder_bar_clustered",
kw.cylinder_bar_stacked: "cylinder_bar_stacked",
kw.cylinder_bar_stacked_100: "cylinder_bar_stacked_100",
kw.cylinder_column: "cylinder_col",
kw.cylinder_column_clustered: "cylinder_col_clustered",
kw.cylinder_column_stacked: "cylinder_col_stacked",
kw.cylinder_column_stacked_100: "cylinder_col_stacked_100",
kw.doughnut: "doughnut",
kw.doughnut_exploded: "doughnut_exploded",
kw.line_chart: "line",
kw.line_markers: "line_markers",
kw.line_markers_stacked: "line_markers_stacked",
kw.line_markers_stacked_100: "line_markers_stacked_100",
kw.line_stacked: "line_stacked",
kw.line_stacked_100: "line_stacked_100",
kw.pie_chart: "pie",
kw.pie_exploded: "pie_exploded",
kw.pie_of_pie: "pie_of_pie",
kw.pyramid_bar_clustered: "pyramid_bar_clustered",
kw.pyramid_bar_stacked: "pyramid_bar_stacked",
kw.pyramid_bar_stacked_100: "pyramid_bar_stacked_100",
kw.pyramid_column: "pyramid_col",
kw.pyramid_column_clustered: "pyramid_col_clustered",
kw.pyramid_column_stacked: "pyramid_col_stacked",
kw.pyramid_column_stacked_100: "pyramid_col_stacked_100",
kw.radar: "radar",
kw.radar_filled: "radar_filled",
kw.radar_markers: "radar_markers",
kw.stock_HLC: "stock_hlc",
kw.stock_OHLC: "stock_ohlc",
kw.stock_VHLC: "stock_vhlc",
kw.stock_VOHLC: "stock_vohlc",
kw.surface: "surface",
kw.surface_top_view: "surface_top_view",
kw.surface_top_view_wireframe: "surface_top_view_wireframe",
kw.surface_wireframe: "surface_wireframe",
kw.xy_scatter_lines: "xy_scatter_lines",
kw.xy_scatter_lines_no_markers: "xy_scatter_lines_no_markers",
kw.xy_scatter_smooth: "xy_scatter_smooth",
kw.xy_scatter_smooth_no_markers: "xy_scatter_smooth_no_markers",
kw.xyscatter: "xy_scatter",
}
chart_types_s2k = {v: k for k, v in chart_types_k2s.items()}
directions_s2k = {
"d": kw.toward_the_bottom,
"down": kw.toward_the_bottom,
"l": kw.toward_the_left,
"left": kw.toward_the_left,
"r": kw.toward_the_right,
"right": kw.toward_the_right,
"u": kw.toward_the_top,
"up": kw.toward_the_top,
}
directions_k2s = {
kw.toward_the_bottom: "down",
kw.toward_the_left: "left",
kw.toward_the_right: "right",
kw.toward_the_top: "up",
}
calculation_k2s = {
kw.calculation_automatic: "automatic",
kw.calculation_manual: "manual",
kw.calculation_semiautomatic: "semiautomatic",
}
calculation_s2k = {v: k for k, v in calculation_k2s.items()}
shape_types_k2s = {
kw.shape_type_3d_model: "3d_model",
kw.shape_type_auto: "auto_shape",
kw.shape_type_callout: "callout",
kw.shape_type_canvas: "canvas",
kw.shape_type_chart: "chart",
kw.shape_type_comment: "comment",
kw.shape_type_content_application: "content_app",
kw.shape_type_diagram: "diagram",
kw.shape_type_free_form: "free_form",
kw.shape_type_graphic: "graphic",
kw.shape_type_group: "group",
kw.shape_type_embedded_OLE_control: "embedded_ole_object",
kw.shape_type_form_control: "form_control",
kw.shape_type_line: "line",
kw.shape_type_linked_3d_model: "linked_3d_model",
kw.shape_type_linked_graphic: "linked_graphic",
kw.shape_type_linked_OLE_object: "linked_ole_object",
kw.shape_type_linked_picture: "linked_picture",
kw.shape_type_OLE_control: "ole_control_object",
kw.shape_type_picture: "picture",
kw.shape_type_place_holder: "placeholder",
kw.shape_type_web_video: "web_video",
kw.shape_type_media: "media",
kw.shape_type_text_box: "text_box",
kw.shape_type_table: "table",
kw.shape_type_ink: "ink",
kw.shape_type_ink_comment: "ink_comment",
kw.shape_type_unset: "unset",
kw.shape_type_slicer: "slicer",
}
scaling = {
"scale_from_top_left": kw.scale_from_top_left,
"scale_from_bottom_right": kw.scale_from_bottom_right,
"scale_from_middle": kw.scale_from_middle,
}
shape_types_s2k = {v: k for k, v in shape_types_k2s.items()}
| Shapes |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_workflows.py | {
"start": 5572,
"end": 6535
} | class ____:
@mock.patch(BASE_PATH.format("WorkflowsHook"))
def test_execute(
self,
mock_hook,
):
op = WorkflowsDeleteWorkflowOperator(
task_id="test_task",
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
op.execute({})
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_hook.return_value.delete_workflow.assert_called_once_with(
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
| TestWorkflowsDeleteWorkflowOperator |
python | kamyu104__LeetCode-Solutions | Python/greatest-english-letter-in-upper-and-lower-case.py | {
"start": 450,
"end": 756
} | class ____(object):
def greatestLetter(self, s):
"""
:type s: str
:rtype: str
"""
lookup = set(s)
return next((C for c, C in itertools.izip(reversed(string.ascii_lowercase), reversed(string.ascii_uppercase)) if c in lookup and C in lookup), "")
| Solution2 |
python | sympy__sympy | sympy/geometry/line.py | {
"start": 53808,
"end": 56585
} | class ____(LinearEntity):
"""A base class for all linear entities (line, ray and segment)
in a 2-dimensional Euclidean space.
Attributes
==========
p1
p2
coefficients
slope
points
Notes
=====
This is an abstract class and is not meant to be instantiated.
See Also
========
sympy.geometry.entity.GeometryEntity
"""
@property
def bounds(self):
"""Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
rectangle for the geometric figure.
"""
verts = self.points
xs = [p.x for p in verts]
ys = [p.y for p in verts]
return (min(xs), min(ys), max(xs), max(ys))
def perpendicular_line(self, p):
"""Create a new Line perpendicular to this linear entity which passes
through the point `p`.
Parameters
==========
p : Point
Returns
=======
line : Line
See Also
========
sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment
Examples
========
>>> from sympy import Point, Line
>>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2)
>>> L = Line(p1, p2)
>>> P = L.perpendicular_line(p3); P
Line2D(Point2D(-2, 2), Point2D(-5, 4))
>>> L.is_perpendicular(P)
True
In 2D, the first point of the perpendicular line is the
point through which was required to pass; the second
point is arbitrarily chosen. To get a line that explicitly
uses a point in the line, create a line from the perpendicular
segment from the line to the point:
>>> Line(L.perpendicular_segment(p3))
Line2D(Point2D(-2, 2), Point2D(4/13, 6/13))
"""
p = Point(p, dim=self.ambient_dimension)
# any two lines in R^2 intersect, so blindly making
# a line through p in an orthogonal direction will work
# and is faster than finding the projection point as in 3D
return Line(p, p + self.direction.orthogonal_direction)
@property
def slope(self):
"""The slope of this linear entity, or infinity if vertical.
Returns
=======
slope : number or SymPy expression
See Also
========
coefficients
Examples
========
>>> from sympy import Point, Line
>>> p1, p2 = Point(0, 0), Point(3, 5)
>>> l1 = Line(p1, p2)
>>> l1.slope
5/3
>>> p3 = Point(0, 4)
>>> l2 = Line(p1, p3)
>>> l2.slope
oo
"""
d1, d2 = (self.p1 - self.p2).args
if d1 == 0:
return S.Infinity
return simplify(d2/d1)
| LinearEntity2D |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py | {
"start": 1476,
"end": 2840
} | class ____(GenericFakeChatModel):
tool_style: Literal["openai", "anthropic"] = "openai"
def bind_tools(
self,
tools: typing.Sequence[Union[dict[str, Any], type[BaseModel], typing.Callable, BaseTool]],
**kwargs: Any,
) -> Runnable[LanguageModelInput, BaseMessage]:
if len(tools) == 0:
msg = "Must provide at least one tool"
raise ValueError(msg)
tool_dicts = []
for tool in tools:
if isinstance(tool, dict):
tool_dicts.append(tool)
continue
if not isinstance(tool, BaseTool):
msg = "Only BaseTool and dict is supported by FakeToolCallingModel.bind_tools"
raise TypeError(msg)
# NOTE: this is a simplified tool spec for testing purposes only
if self.tool_style == "openai":
tool_dicts.append(
{
"type": "function",
"function": {
"name": tool.name,
},
}
)
elif self.tool_style == "anthropic":
tool_dicts.append(
{
"name": tool.name,
}
)
return self.bind(tools=tool_dicts)
| FakeModel |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 7588,
"end": 8690
} | class ____(Boolean):
"""
Base class of :py:class:`~.BooleanTrue` and :py:class:`~.BooleanFalse`.
"""
is_Boolean = True
is_Atom = True
_op_priority = 11 # higher than Expr
def simplify(self, *a, **kw):
return self
def expand(self, *a, **kw):
return self
@property
def canonical(self):
return self
def _noop(self, other=None):
raise TypeError('BooleanAtom not allowed in this context.')
__add__ = _noop
__radd__ = _noop
__sub__ = _noop
__rsub__ = _noop
__mul__ = _noop
__rmul__ = _noop
__pow__ = _noop
__rpow__ = _noop
__truediv__ = _noop
__rtruediv__ = _noop
__mod__ = _noop
__rmod__ = _noop
_eval_power = _noop
def __lt__(self, other):
raise TypeError(filldedent('''
A Boolean argument can only be used in
Eq and Ne; all other relationals expect
real expressions.
'''))
__le__ = __lt__
__gt__ = __lt__
__ge__ = __lt__
# \\\
def _eval_simplify(self, **kwargs):
return self
| BooleanAtom |
python | getsentry__sentry | src/sentry/web/frontend/oauth_token.py | {
"start": 1652,
"end": 14711
} | class ____(View):
# Token responses must not be cached per RFC 6749 §5.1/§5.2. We apply
# never_cache at dispatch so every response from this endpoint is marked
# appropriately without repeating headers across handlers.
@csrf_exempt
@method_decorator(never_cache)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
# Note: the reason parameter is for internal use only
def error(self, request: HttpRequest, name, reason=None, status=400):
client_id = request.POST.get("client_id")
logger.error(
"oauth.token-error",
extra={
"error_name": name,
"status": status,
"client_id": client_id,
"reason": reason,
},
)
resp = HttpResponse(
json.dumps({"error": name}), content_type="application/json", status=status
)
# RFC 6749 §5.2 invalid_client requires WWW-Authenticate header
if name == "invalid_client":
resp["WWW-Authenticate"] = 'Basic realm="oauth"'
return resp
def post(self, request: Request) -> HttpResponse:
"""OAuth 2.0 token endpoint (RFC 6749 §3.2).
Purpose
- Exchanges an authorization code for tokens, or uses a refresh token to
obtain a new access token.
Supported grant types
- `authorization_code` (RFC 6749 §4.1): requires `code` and, if bound,
a matching `redirect_uri` (§4.1.3). If `openid` scope was granted and
signing is configured, an `id_token` (OIDC Core 1.0) is included.
- `refresh_token` (RFC 6749 §6): requires `refresh_token`. Supplying `scope`
is not supported here and returns `invalid_request`.
Client authentication
- Either Authorization header (Basic) or form fields `client_id`/`client_secret`
(RFC 6749 §2.3.1). Only one method may be used per request.
Request format
- Requests are `application/x-www-form-urlencoded` as defined in RFC 6749 §3.2.
Responses
- Success (RFC 6749 §5.1): 200 JSON with `access_token`, `refresh_token`,
`expires_in`/`expires_at`, `token_type` (Bearer), `scope`, `user`, and
optionally `id_token` and `organization_id`.
- Errors (RFC 6749 §5.2): 400 JSON for `invalid_request`, `invalid_grant`,
`unsupported_grant_type`; 401 JSON for `invalid_client` (with
`WWW-Authenticate: Basic realm="oauth"`).
"""
grant_type = request.POST.get("grant_type")
# Determine client credentials from header or body (mutually exclusive).
(client_id, client_secret), cred_error = self._extract_basic_auth_credentials(request)
if cred_error is not None:
return cred_error
metrics.incr(
"oauth_token.post.start",
sample_rate=1.0,
tags={
"client_id_exists": bool(client_id),
"client_secret_exists": bool(client_secret),
},
)
if not client_id or not client_secret:
return self.error(
request=request,
name="invalid_client",
reason="missing client credentials",
status=401,
)
if not grant_type:
return self.error(request=request, name="invalid_request", reason="missing grant_type")
if grant_type not in [GrantTypes.AUTHORIZATION, GrantTypes.REFRESH]:
return self.error(request=request, name="unsupported_grant_type")
try:
application = ApiApplication.objects.get(
client_id=client_id, client_secret=client_secret, status=ApiApplicationStatus.active
)
except ApiApplication.DoesNotExist:
metrics.incr(
"oauth_token.post.invalid",
sample_rate=1.0,
)
logger.warning("Invalid client_id / secret pair", extra={"client_id": client_id})
return self.error(
request=request,
name="invalid_client",
reason="invalid client_id or client_secret",
status=401,
)
# Defense-in-depth: verify the application's client_id matches the request.
# This should always be true given the query above, but protects against
# potential logic bugs or database inconsistencies.
if application.client_id != client_id:
logger.error(
"Application client_id mismatch",
extra={
"requested_client_id": client_id,
"application_client_id": application.client_id,
"application_id": application.id,
},
)
return self.error(
request=request,
name="invalid_client",
reason="client_id mismatch",
status=401,
)
if grant_type == GrantTypes.AUTHORIZATION:
token_data = self.get_access_tokens(request=request, application=application)
else:
token_data = self.get_refresh_token(request=request, application=application)
if "error" in token_data:
return self.error(
request=request,
name=token_data["error"],
reason=token_data["reason"] if "reason" in token_data else None,
)
return self.process_token_details(
token=token_data["token"],
id_token=token_data["id_token"] if "id_token" in token_data else None,
)
def _extract_basic_auth_credentials(
self, request: Request
) -> tuple[tuple[str | None, str | None], HttpResponse | None]:
"""
Extract client credentials from the request.
Supported mechanisms (mutually exclusive):
- HTTP Authorization header with the Basic scheme
(RFC 6749 §2.3.1; Basic syntax per RFC 7617: base64(client_id:client_secret)).
- Form body fields: `client_id` and `client_secret` (RFC 6749 §2.3.1).
Returns ((client_id, client_secret), error_response).
- If both mechanisms are present, returns `invalid_request` (client MUST NOT
use more than one authentication method; RFC 6749 §2.3).
- If the Basic header is malformed, returns `invalid_client` with 401
(error semantics per RFC 6749 §5.2; Basic auth per §2.3.1).
- If neither mechanism is present, returns (None, None), None and the
caller enforces `invalid_client` as appropriate (RFC 6749 §5.2).
Note: This helper enforces a conservative upper bound on Basic header
payload size for robustness; this limit is an implementation detail and
not dictated by the RFCs.
"""
# Check for Basic auth header first
auth_header = request.META.get("HTTP_AUTHORIZATION", "")
has_auth_header = isinstance(auth_header, str) and bool(auth_header)
body_client_id = request.POST.get("client_id")
body_client_secret = request.POST.get("client_secret")
has_body_credentials = bool(body_client_id) or bool(body_client_secret)
# If both mechanisms are present, this is an invalid request per spec.
if has_auth_header:
scheme, _, param = auth_header.partition(" ")
if scheme and scheme.lower() == "basic" and param:
if has_body_credentials:
logger.info(
"oauth.basic-and-body-credentials",
extra={
"client_id": body_client_id,
"reason": "conflict",
},
)
return (None, None), self.error(
request=request,
name="invalid_request",
reason="credential conflict",
)
# Enforce a reasonable upper bound on the Base64 payload to
# avoid excessive memory use on decode.
b64 = param.strip()
if len(b64) > MAX_BASIC_AUTH_B64_LEN:
logger.warning("Invalid Basic auth header: too long", extra={"client_id": None})
return (None, None), self.error(
request=request,
name="invalid_client",
reason="invalid basic auth (too long)",
status=401,
)
try:
decoded = base64.b64decode(b64.encode("ascii"), validate=True).decode("utf-8")
# format: client_id:client_secret (client_secret may be empty)
if ":" not in decoded:
raise ValueError("missing colon in basic credentials")
client_id, client_secret = decoded.split(":", 1)
return (client_id, client_secret), None
except Exception:
logger.warning("Invalid Basic auth header", extra={"client_id": None})
return (None, None), self.error(
request=request,
name="invalid_client",
reason="invalid basic auth",
status=401,
)
# No usable Basic header; fall back to body credentials if provided.
if has_body_credentials:
return (body_client_id, body_client_secret), None
# Neither header nor body provided credentials.
return (None, None), None
def get_access_tokens(self, request: Request, application: ApiApplication) -> dict:
code = request.POST.get("code")
try:
grant = ApiGrant.objects.get(
application=application, application__status=ApiApplicationStatus.active, code=code
)
except ApiGrant.DoesNotExist:
return {"error": "invalid_grant", "reason": "invalid grant"}
if grant.is_expired():
return {"error": "invalid_grant", "reason": "grant expired"}
# Enforce redirect_uri binding (RFC 6749 §4.1.3)
redirect_uri = request.POST.get("redirect_uri")
if grant.redirect_uri and grant.redirect_uri != redirect_uri:
return {"error": "invalid_grant", "reason": "invalid redirect URI"}
try:
token_data = {"token": ApiToken.from_grant(grant=grant)}
except UnableToAcquireLock:
# TODO(mdtro): we should return a 409 status code here
return {"error": "invalid_grant", "reason": "invalid grant"}
if grant.has_scope("openid") and options.get("codecov.signing_secret"):
open_id_token = OpenIDToken(
application.client_id,
grant.user_id,
options.get("codecov.signing_secret"),
nonce=request.POST.get("nonce"),
)
token_data["id_token"] = open_id_token.get_signed_id_token(grant=grant)
return token_data
def get_refresh_token(self, request: Request, application: ApiApplication) -> dict:
refresh_token_code = request.POST.get("refresh_token")
scope = request.POST.get("scope")
if not refresh_token_code:
return {"error": "invalid_request"}
# TODO(dcramer): support scope
if scope:
return {"error": "invalid_request"}
try:
refresh_token = ApiToken.objects.get(
application=application, refresh_token=refresh_token_code
)
except ApiToken.DoesNotExist:
return {"error": "invalid_grant", "reason": "invalid request"}
refresh_token.refresh()
return {"token": refresh_token}
def process_token_details(
self, token: ApiToken, id_token: OpenIDToken | None = None
) -> HttpResponse:
token_information: _TokenInformation = {
"access_token": token.token,
"refresh_token": token.refresh_token,
"expires_in": (
int((token.expires_at - timezone.now()).total_seconds())
if token.expires_at
else None
),
"expires_at": token.expires_at,
"token_type": "Bearer",
"scope": " ".join(token.get_scopes()),
"user": {
"id": str(token.user.id),
# we might need these to become scope based
"name": token.user.name,
"email": token.user.email,
},
}
if id_token:
token_information["id_token"] = id_token
if token.scoping_organization_id:
token_information["organization_id"] = str(token.scoping_organization_id)
return HttpResponse(
json.dumps(token_information),
content_type="application/json",
)
| OAuthTokenView |
python | huggingface__transformers | src/transformers/models/resnet/modeling_resnet.py | {
"start": 1999,
"end": 2907
} | class ____(nn.Module):
"""
ResNet Embeddings (stem) composed of a single aggressive convolution.
"""
def __init__(self, config: ResNetConfig):
super().__init__()
self.embedder = ResNetConvLayer(
config.num_channels, config.embedding_size, kernel_size=7, stride=2, activation=config.hidden_act
)
self.pooler = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.num_channels = config.num_channels
def forward(self, pixel_values: Tensor) -> Tensor:
num_channels = pixel_values.shape[1]
if num_channels != self.num_channels:
raise ValueError(
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
)
embedding = self.embedder(pixel_values)
embedding = self.pooler(embedding)
return embedding
| ResNetEmbeddings |
python | numpy__numpy | numpy/_core/tests/test_ufunc.py | {
"start": 1002,
"end": 2011
} | class ____:
def test_kwarg_exact(self):
assert_raises(TypeError, np.add, 1, 2, castingx='safe')
assert_raises(TypeError, np.add, 1, 2, dtypex=int)
assert_raises(TypeError, np.add, 1, 2, extobjx=[4096])
assert_raises(TypeError, np.add, 1, 2, outx=None)
assert_raises(TypeError, np.add, 1, 2, sigx='ii->i')
assert_raises(TypeError, np.add, 1, 2, signaturex='ii->i')
assert_raises(TypeError, np.add, 1, 2, subokx=False)
assert_raises(TypeError, np.add, 1, 2, wherex=[True])
def test_sig_signature(self):
assert_raises(TypeError, np.add, 1, 2, sig='ii->i',
signature='ii->i')
def test_sig_dtype(self):
assert_raises(TypeError, np.add, 1, 2, sig='ii->i',
dtype=int)
assert_raises(TypeError, np.add, 1, 2, signature='ii->i',
dtype=int)
def test_extobj_removed(self):
assert_raises(TypeError, np.add, 1, 2, extobj=[4096])
| TestUfuncKwargs |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/io_ops/save_restore_ops_test.py | {
"start": 1271,
"end": 2191
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.parameters(_TEST_DTYPES)
@test_util.run_in_graph_and_eager_modes
def testRelativePath(self, dtype):
os.chdir(self.get_temp_dir())
self.evaluate(
io_ops.save_v2(
"ckpt", ["x"], [""], [constant_op.constant(2, dtype=dtype)]
)
)
self.assertAllEqual(
[2], self.evaluate(io_ops.restore_v2("ckpt", ["x"], [""], [dtype]))
)
@parameterized.parameters(_TEST_DTYPES)
def testWithSliceInput(self, dtype):
os.chdir(self.get_temp_dir())
self.evaluate(
io_ops.save_v2(
"ckpt",
["x"],
[""],
[constant_op.constant([[1, 2, 3], [2, 3, 4]], dtype=dtype)],
)
)
self.assertAllEqual(
[[2], [3]],
self.evaluate(io_ops.restore_v2("ckpt", ["x"], ["2 3 -:1,1"], [dtype]))[
0
],
)
| SaveRestoreTest |
python | walkccc__LeetCode | solutions/1805. Number of Different Integers in a String/1805-2.py | {
"start": 0,
"end": 124
} | class ____:
def numDifferentIntegers(self, word: str) -> int:
return len(set(map(int, re.findall(r'\d+', word))))
| Solution |
python | spack__spack | lib/spack/spack/test/oci/mock_registry.py | {
"start": 9903,
"end": 10520
} | class ____(urllib.request.BaseHandler):
"""Glue between urllib and DummyServer, routing requests to
the correct mock server for a given domain."""
def __init__(self) -> None:
self.servers: Dict[str, DummyServer] = {}
def add_server(self, domain: str, api: DummyServer):
self.servers[domain] = api
return self
def https_open(self, req: Request):
domain = urllib.parse.urlparse(req.full_url).netloc
if domain not in self.servers:
return MockHTTPResponse(404, "Not found")
return self.servers[domain].handle(req)
| DummyServerUrllibHandler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.