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 | pytorch__pytorch | torch/jit/annotations.py | {
"start": 1508,
"end": 18003
} | class ____:
env = {
"torch": Module("torch", {"Tensor": torch.Tensor}),
"Tensor": torch.Tensor,
"typing": Module("typing", {"Tuple": Tuple}),
"Tuple": Tuple,
"List": List,
"Dict": Dict,
"Optional": Optional,
"Union": Union,
"Future": Future,
"Await": _Await,
}
def __init__(self, rcb) -> None:
self.rcb = rcb
if torch.distributed.rpc.is_available():
# pyrefly: ignore [unsupported-operation]
self.env["RRef"] = RRef
def __getitem__(self, name):
if name in self.env:
return self.env[name]
if self.rcb is not None:
return self.rcb(name)
return getattr(builtins, name, None)
def get_signature(fn, rcb, loc, is_method):
if isinstance(fn, OpOverloadPacket):
signature = try_real_annotations(fn.op, loc)
else:
signature = try_real_annotations(fn, loc)
if signature is not None and is_method:
# If this is a method, then the signature will include a type for
# `self`, but type comments do not contain a `self`. So strip it
# away here so everything is consistent (`inspect.ismethod` does
# not work here since `fn` is unbound at this point)
param_types, return_type = signature
param_types = param_types[1:]
signature = (param_types, return_type)
if signature is None:
type_line, source = None, None
try:
source = dedent("".join(get_source_lines_and_file(fn)[0]))
type_line = get_type_line(source)
except TypeError:
pass
# This might happen both because we failed to get the source of fn, or
# because it didn't have any annotations.
if type_line is not None:
signature = parse_type_line(type_line, rcb, loc)
return signature
def is_function_or_method(the_callable):
# A stricter version of `inspect.isroutine` that does not pass for built-in
# functions
return inspect.isfunction(the_callable) or inspect.ismethod(the_callable)
def is_vararg(the_callable):
if not is_function_or_method(the_callable) and callable(the_callable): # noqa: B004
# If `the_callable` is a class, de-sugar the call so we can still get
# the signature
the_callable = the_callable.__call__
if is_function_or_method(the_callable):
return inspect.getfullargspec(the_callable).varargs is not None
else:
return False
def get_param_names(fn, n_args):
if isinstance(fn, OpOverloadPacket):
fn = fn.op
if (
not is_function_or_method(fn)
and callable(fn)
and is_function_or_method(fn.__call__)
): # noqa: B004
# De-sugar calls to classes
fn = fn.__call__
if is_function_or_method(fn):
if is_ignored_fn(fn):
fn = inspect.unwrap(fn)
return inspect.getfullargspec(fn).args
else:
# The `fn` was not a method or function (maybe a class with a __call__
# method, so use a default param name list)
return [str(i) for i in range(n_args)]
def check_fn(fn, loc) -> None:
# Make sure the function definition is not a class instantiation
try:
source = dedent("".join(get_source_lines_and_file(fn)[0]))
except (OSError, TypeError):
return
if source is None:
return
py_ast = ast.parse(source)
if len(py_ast.body) == 1 and isinstance(py_ast.body[0], ast.ClassDef):
raise torch.jit.frontend.FrontendError(
loc,
f"Cannot instantiate class '{py_ast.body[0].name}' in a script function",
)
if len(py_ast.body) != 1 or not isinstance(py_ast.body[0], ast.FunctionDef):
raise torch.jit.frontend.FrontendError(
loc, "Expected a single top-level function"
)
def _eval_no_call(stmt, glob, loc):
"""Evaluate statement as long as it does not contain any method/function calls."""
bytecode = compile(stmt, "", mode="eval")
for insn in dis.get_instructions(bytecode):
if "CALL" in insn.opname:
raise RuntimeError(
f"Type annotation should not contain calls, but '{stmt}' does"
)
return eval(bytecode, glob, loc) # type: ignore[arg-type] # noqa: P204
def parse_type_line(type_line, rcb, loc):
"""Parse a type annotation specified as a comment.
Example inputs:
# type: (Tensor, torch.Tensor) -> Tuple[Tensor]
# type: (Tensor, Tuple[Tensor, Tensor]) -> Tensor
"""
arg_ann_str, ret_ann_str = split_type_line(type_line)
try:
arg_ann = _eval_no_call(arg_ann_str, {}, EvalEnv(rcb))
except (NameError, SyntaxError) as e:
raise RuntimeError(
"Failed to parse the argument list of a type annotation"
) from e
if not isinstance(arg_ann, tuple):
arg_ann = (arg_ann,)
try:
ret_ann = _eval_no_call(ret_ann_str, {}, EvalEnv(rcb))
except (NameError, SyntaxError) as e:
raise RuntimeError(
"Failed to parse the return type of a type annotation"
) from e
arg_types = [ann_to_type(ann, loc) for ann in arg_ann]
return arg_types, ann_to_type(ret_ann, loc)
def get_type_line(source):
"""Try to find the line containing a comment with the type annotation."""
type_comment = "# type:"
lines = source.split("\n")
lines = list(enumerate(lines))
type_lines = list(filter(lambda line: type_comment in line[1], lines))
# `type: ignore` comments may be needed in JIT'ed functions for mypy, due
# to the hack in torch/_VF.py.
# An ignore type comment can be of following format:
# 1) type: ignore
# 2) type: ignore[rule-code]
# This ignore statement must be at the end of the line
# adding an extra backslash before the space, to avoid triggering
# one of the checks in .github/workflows/lint.yml
type_pattern = re.compile("# type:\\ ignore(\\[[a-zA-Z-]+\\])?$")
type_lines = list(filter(lambda line: not type_pattern.search(line[1]), type_lines))
if len(type_lines) == 0:
# Catch common typo patterns like extra spaces, typo in 'ignore', etc.
wrong_type_pattern = re.compile("#[\t ]*type[\t ]*(?!: ignore(\\[.*\\])?$):")
wrong_type_lines = list(
filter(lambda line: wrong_type_pattern.search(line[1]), lines)
)
if len(wrong_type_lines) > 0:
raise RuntimeError(
"The annotation prefix in line "
+ str(wrong_type_lines[0][0])
+ " is probably invalid.\nIt must be '# type:'"
+ "\nSee PEP 484 (https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code)" # noqa: B950
+ "\nfor examples"
)
return None
elif len(type_lines) == 1:
# Only 1 type line, quit now
return type_lines[0][1].strip()
# Parse split up argument types according to PEP 484
# https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
return_line = None
parameter_type_lines = []
for line_num, line in type_lines:
if "# type: (...) -> " in line:
return_line = (line_num, line)
break
elif type_comment in line:
parameter_type_lines.append(line)
if return_line is None:
raise RuntimeError(
"Return type line '# type: (...) -> ...' not found on multiline "
"type annotation\nfor type lines:\n"
+ "\n".join([line[1] for line in type_lines])
+ "\n(See PEP 484 https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code)"
)
def get_parameter_type(line):
item_type = line[line.find(type_comment) + len(type_comment) :]
return item_type.strip()
types = map(get_parameter_type, parameter_type_lines)
parameter_types = ", ".join(types)
return return_line[1].replace("...", parameter_types)
def split_type_line(type_line):
"""Split the comment with the type annotation into parts for argument and return types.
For example, for an input of:
# type: (Tensor, torch.Tensor) -> Tuple[Tensor, Tensor]
This function will return:
("(Tensor, torch.Tensor)", "Tuple[Tensor, Tensor]")
"""
start_offset = len("# type:")
try:
arrow_pos = type_line.index("->")
except ValueError:
raise RuntimeError(
"Syntax error in type annotation (couldn't find `->`)"
) from None
return type_line[start_offset:arrow_pos].strip(), type_line[arrow_pos + 2 :].strip()
def try_real_annotations(fn, loc):
"""Try to use the Py3.5+ annotation syntax to get the type."""
try:
# Note: anything annotated as `Optional[T]` will automatically
# be returned as `Union[T, None]` per
# https://github.com/python/cpython/blob/main/Lib/typing.py#L732
sig = inspect.signature(fn)
except ValueError:
return None
all_annots = [sig.return_annotation] + [
p.annotation for p in sig.parameters.values()
]
if all(ann is sig.empty for ann in all_annots):
return None
arg_types = [ann_to_type(p.annotation, loc) for p in sig.parameters.values()]
return_type = ann_to_type(sig.return_annotation, loc)
return arg_types, return_type
# Finds common type for enum values belonging to an Enum class. If not all
# values have the same type, AnyType is returned.
def get_enum_value_type(e: type[enum.Enum], loc):
enum_values: List[enum.Enum] = list(e)
if not enum_values:
raise ValueError(f"No enum values defined for: '{e.__class__}'")
types = {type(v.value) for v in enum_values}
ir_types = [try_ann_to_type(t, loc) for t in types]
# If Enum values are of different types, an exception will be raised here.
# Even though Python supports this case, we chose to not implement it to
# avoid overcomplicate logic here for a rare use case. Please report a
# feature request if you find it necessary.
res = torch._C.unify_type_list(ir_types)
if not res:
return AnyType.get()
return res
def is_tensor(ann) -> bool:
if issubclass(ann, torch.Tensor):
return True
if issubclass(
ann,
(
torch.LongTensor,
torch.DoubleTensor,
torch.FloatTensor,
torch.IntTensor,
torch.ShortTensor,
torch.HalfTensor,
torch.CharTensor,
torch.ByteTensor,
torch.BoolTensor,
),
):
warnings.warn(
"TorchScript will treat type annotations of Tensor "
"dtype-specific subtypes as if they are normal Tensors. "
"dtype constraints are not enforced in compilation either.",
stacklevel=2,
)
return True
return False
def _fake_rcb(inp) -> None:
return None
def try_ann_to_type(ann, loc, rcb=None):
ann_args = typing.get_args(ann) # always returns a tuple!
if ann is inspect.Signature.empty:
return TensorType.getInferred()
if ann is None:
return NoneType.get()
if inspect.isclass(ann) and is_tensor(ann):
return TensorType.get()
if is_tuple(ann):
# Special case for the empty Tuple type annotation `Tuple[()]`
if len(ann_args) == 1 and ann_args[0] == ():
return TupleType([])
return TupleType([try_ann_to_type(a, loc) for a in ann_args])
if is_list(ann):
elem_type = try_ann_to_type(ann_args[0], loc)
if elem_type:
return ListType(elem_type)
if is_dict(ann):
key = try_ann_to_type(ann_args[0], loc)
value = try_ann_to_type(ann_args[1], loc)
# Raise error if key or value is None
if key is None:
raise ValueError(
f"Unknown type annotation: '{ann_args[0]}' at {loc.highlight()}"
)
if value is None:
raise ValueError(
f"Unknown type annotation: '{ann_args[1]}' at {loc.highlight()}"
)
return DictType(key, value)
if is_optional(ann):
if issubclass(ann_args[1], type(None)):
contained = ann_args[0]
else:
contained = ann_args[1]
valid_type = try_ann_to_type(contained, loc)
msg = "Unsupported annotation {} could not be resolved because {} could not be resolved. At\n{}"
assert valid_type, msg.format(repr(ann), repr(contained), repr(loc))
return OptionalType(valid_type)
if is_union(ann):
# TODO: this is hack to recognize NumberType
if set(ann_args) == {int, float, complex}:
return NumberType.get()
inner: List = []
# We need these extra checks because both `None` and invalid
# values will return `None`
# TODO: Determine if the other cases need to be fixed as well
for a in typing.get_args(ann):
if a is None:
inner.append(NoneType.get())
maybe_type = try_ann_to_type(a, loc)
msg = "Unsupported annotation {} could not be resolved because {} could not be resolved. At\n{}"
assert maybe_type, msg.format(repr(ann), repr(maybe_type), repr(loc))
inner.append(maybe_type)
return UnionType(inner) # type: ignore[arg-type]
if torch.distributed.rpc.is_available() and is_rref(ann):
return RRefType(try_ann_to_type(ann_args[0], loc))
if is_future(ann):
return FutureType(try_ann_to_type(ann_args[0], loc))
if is_await(ann):
elementType = try_ann_to_type(ann_args[0], loc) if ann_args else AnyType.get()
return AwaitType(elementType)
if ann is float:
return FloatType.get()
if ann is complex:
return ComplexType.get()
if ann is int or ann is torch.SymInt:
return IntType.get()
if ann is str:
return StringType.get()
if ann is bool:
return BoolType.get()
if ann is Any:
return AnyType.get()
if ann is type(None):
return NoneType.get()
if inspect.isclass(ann) and hasattr(ann, "__torch_script_interface__"):
return InterfaceType(ann.__torch_script_interface__)
if ann is torch.device:
return DeviceObjType.get()
if ann is torch.Generator:
return _GeneratorType.get()
if ann is torch.Stream:
return StreamObjType.get()
if ann is torch.dtype:
return IntType.get() # dtype not yet bound in as its own type
if ann is torch.qscheme:
return IntType.get() # qscheme not yet bound in as its own type
if inspect.isclass(ann) and issubclass(ann, enum.Enum):
if _get_script_class(ann) is None:
scripted_class = torch.jit._script._recursive_compile_class(ann, loc)
name = scripted_class.qualified_name()
else:
name = _qualified_name(ann)
return EnumType(name, get_enum_value_type(ann, loc), list(ann))
if inspect.isclass(ann):
maybe_script_class = _get_script_class(ann)
if maybe_script_class is not None:
return maybe_script_class
if torch._jit_internal.can_compile_class(ann):
return torch.jit._script._recursive_compile_class(ann, loc)
# Maybe resolve a NamedTuple to a Tuple Type
if rcb is None:
rcb = _fake_rcb
return torch._C._resolve_type_from_object(ann, loc, rcb)
def ann_to_type(ann, loc, rcb=None):
the_type = try_ann_to_type(ann, loc, rcb)
if the_type is not None:
return the_type
raise ValueError(f"Unknown type annotation: '{ann}' at {loc.highlight()}")
__all__ = [
"Any",
"List",
"BroadcastingList1",
"BroadcastingList2",
"BroadcastingList3",
"Tuple",
"is_tuple",
"is_list",
"Dict",
"is_dict",
"is_optional",
"is_union",
"TensorType",
"TupleType",
"FloatType",
"ComplexType",
"IntType",
"ListType",
"StringType",
"DictType",
"AnyType",
"Module",
# TODO: Consider not exporting these during wildcard import (reserve
# that for the types; for idiomatic typing code.)
"get_signature",
"check_fn",
"get_param_names",
"parse_type_line",
"get_type_line",
"split_type_line",
"try_real_annotations",
"try_ann_to_type",
"ann_to_type",
]
| EvalEnv |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/scalarstring.py | {
"start": 2399,
"end": 2624
} | class ____(ScalarString):
__slots__ = ()
style = '"'
def __new__(cls, value, anchor=None):
# type: (Text, Any) -> Any
return ScalarString.__new__(cls, value, anchor=anchor)
| DoubleQuotedScalarString |
python | rapidsai__cudf | python/cudf/cudf/core/mixins/notiterable.py | {
"start": 141,
"end": 575
} | class ____:
def __iter__(self) -> None:
"""
Iteration is unsupported.
See :ref:`iteration <pandas-comparison/iteration>` for more
information.
"""
raise TypeError(
f"{self.__class__.__name__} object is not iterable. "
f"Consider using `.to_arrow()`, `.to_pandas()` or `.values_host` "
f"if you wish to iterate over the values."
)
| NotIterable |
python | sqlalchemy__sqlalchemy | test/ext/test_horizontal_shard.py | {
"start": 31497,
"end": 36456
} | class ____(fixtures.DeclarativeMappedTest):
def _init_dbs(self):
self.db1 = db1 = testing_engine(
"sqlite:///shard1_%s.db" % provision.FOLLOWER_IDENT
)
self.db2 = db2 = testing_engine(
"sqlite:///shard2_%s.db" % provision.FOLLOWER_IDENT
)
for db in (db1, db2):
self.tables_test_metadata.create_all(db)
self.dbs = [db1, db2]
return self.dbs
def teardown_test(self):
for db in self.dbs:
db.connect().invalidate()
testing_reaper.checkin_all()
for i in range(1, 3):
os.remove("shard%d_%s.db" % (i, provision.FOLLOWER_IDENT))
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class Book(Base):
__tablename__ = "book"
id = Column(Integer, primary_key=True)
title = Column(String(50), nullable=False)
pages = relationship("Page", backref="book")
class Page(Base):
__tablename__ = "page"
id = Column(Integer, primary_key=True)
book_id = Column(ForeignKey("book.id"))
title = Column(String(50))
def _fixture(self, lazy_load_book=False, lazy_load_pages=False):
Book, Page = self.classes("Book", "Page")
def shard_for_book(book):
if book.title == "title 1":
return "test"
elif book.title == "title 2":
return "test2"
else:
assert False
def identity_chooser(
mapper,
primary_key,
*,
lazy_loaded_from,
execution_options,
bind_arguments,
**kw,
):
assert lazy_loaded_from
if isinstance(lazy_loaded_from.obj(), Book):
token = shard_for_book(lazy_loaded_from.obj())
assert lazy_loaded_from.identity_token == token
return [lazy_loaded_from.identity_token]
def execute_chooser(orm_context):
if (
orm_context.statement.column_descriptions[0]["type"] is Book
and lazy_load_book
):
assert isinstance(orm_context.lazy_loaded_from.obj(), Page)
elif (
orm_context.statement.column_descriptions[0]["type"] is Page
and lazy_load_pages
):
assert isinstance(orm_context.lazy_loaded_from.obj(), Book)
if orm_context.lazy_loaded_from is None:
return ["test", "test2"]
else:
return [orm_context.lazy_loaded_from.identity_token]
def shard_chooser(mapper, instance, **kw):
if isinstance(instance, Page):
return shard_for_book(instance.book)
else:
return shard_for_book(instance)
db1, db2 = self._init_dbs()
session = ShardedSession(
shards={"test": db1, "test2": db2},
shard_chooser=shard_chooser,
identity_chooser=identity_chooser,
execute_chooser=execute_chooser,
)
return session
def test_lazy_load_from_identity_map(self):
session = self._fixture()
Book, Page = self.classes("Book", "Page")
book = Book(title="title 1")
book.pages.append(Page())
session.add(book)
session.flush()
page = session.query(Page).first()
session.expire(page, ["book"])
with self.assert_statement_count_multi_db(self.dbs, [0, 0]):
# doesn't emit SQL
eq_(page.book, book)
def test_lazy_load_from_db(self):
session = self._fixture(lazy_load_book=True)
Book, Page = self.classes("Book", "Page")
book1 = Book(title="title 1")
book1.pages.append(Page(title="book 1 page 1"))
session.add(book1)
session.flush()
book1_id = inspect(book1).identity_key
session.expunge(book1)
book1_page = session.query(Page).first()
session.expire(book1_page, ["book"])
with self.assert_statement_count_multi_db(self.dbs, [1, 0]):
# emits one query
eq_(inspect(book1_page.book).identity_key, book1_id)
def test_lazy_load_no_baked_conflict(self):
session = self._fixture(lazy_load_pages=True)
Book, Page = self.classes("Book", "Page")
book1 = Book(title="title 1")
book1.pages.append(Page(title="book 1 page 1"))
book2 = Book(title="title 2")
book2.pages.append(Page(title="book 2 page 1"))
session.add(book1)
session.add(book2)
session.flush()
session.expire(book1, ["pages"])
session.expire(book2, ["pages"])
eq_(book1.pages[0].title, "book 1 page 1")
# second lazy load uses correct state
eq_(book2.pages[0].title, "book 2 page 1")
| LazyLoadIdentityKeyTest |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/key_value_parsers.py | {
"start": 872,
"end": 1776
} | class ____(KeyValueParser):
"""Composite argument parser for origin key/value pairs."""
def get_parsers(self, state: ParserState) -> dict[str, Parser]:
"""Return a dictionary of key names and value parsers."""
versions = CONTROLLER_PYTHON_VERSIONS
return dict(
python=PythonParser(versions=versions, allow_venv=True, allow_default=True),
)
def document(self, state: DocumentationState) -> t.Optional[str]:
"""Generate and return documentation for this parser."""
python_parser = PythonParser(versions=CONTROLLER_PYTHON_VERSIONS, allow_venv=True, allow_default=True)
section_name = 'origin options'
state.sections[f'controller {section_name} (comma separated):'] = '\n'.join([
f' python={python_parser.document(state)}',
])
return f'{{{section_name}}} # default'
| OriginKeyValueParser |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 20819,
"end": 22912
} | class ____(GlobalValue):
"""
A global variable.
"""
def __init__(self, module, typ, name, addrspace=0):
assert isinstance(typ, types.Type)
super(GlobalVariable, self).__init__(module, typ.as_pointer(addrspace),
name=name)
self.value_type = typ
self.initializer = None
self.unnamed_addr = False
self.global_constant = False
self.addrspace = addrspace
self.align = None
self.parent.add_global(self)
def descr(self, buf):
if self.global_constant:
kind = 'constant'
else:
kind = 'global'
if not self.linkage:
# Default to external linkage
linkage = 'external' if self.initializer is None else ''
else:
linkage = self.linkage
if linkage:
buf.append(linkage + " ")
if self.storage_class:
buf.append(self.storage_class + " ")
if self.unnamed_addr:
buf.append("unnamed_addr ")
if self.addrspace != 0:
buf.append('addrspace({0:d}) '.format(self.addrspace))
buf.append("{kind} {type}" .format(kind=kind, type=self.value_type))
if self.initializer is not None:
if self.initializer.type != self.value_type:
raise TypeError("got initializer of type %s "
"for global value type %s"
% (self.initializer.type, self.value_type))
buf.append(" " + self.initializer.get_reference())
elif linkage not in ('external', 'extern_weak'):
# emit 'undef' for non-external linkage GV
buf.append(" " + self.value_type(Undefined).get_reference())
if self.section:
buf.append(", section \"%s\"" % (self.section,))
if self.align is not None:
buf.append(", align %d" % (self.align,))
if self.metadata:
buf.append(self._stringify_metadata(leading_comma=True))
buf.append("\n")
| GlobalVariable |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 521928,
"end": 522397
} | class ____(NumBinopNode):
# '@' operator.
def is_py_operation_types(self, type1, type2):
return True
def infer_builtin_types_operation(self, type1, type2):
# We really don't know anything about this operation.
return None
def generate_evaluation_code(self, code):
code.globalstate.use_utility_code(UtilityCode.load_cached("MatrixMultiply", "ObjectHandling.c"))
super().generate_evaluation_code(code)
| MatMultNode |
python | ray-project__ray | python/ray/data/tests/test_numpy_support.py | {
"start": 310,
"end": 14752
} | class ____:
def __eq__(self, other):
return isinstance(other, UserObj)
def do_map_batches(data):
ds = ray.data.range(1)
ds = ds.map_batches(lambda x: {"output": data})
return ds.take_batch()["output"]
def assert_structure_equals(a, b):
assert type(a) is type(b), (type(a), type(b))
assert type(a[0]) == type(b[0]), (type(a[0]), type(b[0])) # noqa: E721
assert a.dtype == b.dtype
assert a.shape == b.shape
for i in range(len(a)):
assert np.array_equal(a[i], b[i]), (i, a[i], b[i])
def test_list_of_scalars(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [1, 2, 3]
output = do_map_batches(data)
assert_structure_equals(output, np.array([1, 2, 3], dtype=np.int64))
def test_list_of_numpy_scalars(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [np.int64(1), np.int64(2), np.int64(3)]
output = do_map_batches(data)
assert_structure_equals(output, np.array([1, 2, 3], dtype=np.int64))
def test_list_of_objects(ray_start_regular_shared, restore_data_context):
# NOTE: Fallback is enabled by default, this is purely for notational purposes
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = True
data = [1, 2, 3, UserObj()]
output = do_map_batches(data)
assert_structure_equals(output, np.array([1, 2, 3, UserObj()]))
# Define datetime values with different precisions
DATETIME_DAY_PRECISION = datetime(year=2024, month=1, day=1)
DATETIME_HOUR_PRECISION = datetime(year=2024, month=1, day=1, hour=1)
DATETIME_MIN_PRECISION = datetime(year=2024, month=1, day=1, minute=1)
DATETIME_SEC_PRECISION = datetime(year=2024, month=1, day=1, second=1)
DATETIME_MILLISEC_PRECISION = datetime(year=2024, month=1, day=1, microsecond=1000)
DATETIME_MICROSEC_PRECISION = datetime(year=2024, month=1, day=1, microsecond=1)
# Define pandas values for different precisions
PANDAS_DAY_PRECISION = pd.Timestamp(year=2024, month=1, day=1)
PANDAS_HOUR_PRECISION = pd.Timestamp(year=2024, month=1, day=1, hour=1)
PANDAS_MIN_PRECISION = pd.Timestamp(year=2024, month=1, day=1, minute=1)
PANDAS_SEC_PRECISION = pd.Timestamp(year=2024, month=1, day=1, second=1)
PANDAS_MILLISEC_PRECISION = pd.Timestamp(year=2024, month=1, day=1, microsecond=1000)
PANDAS_MICROSEC_PRECISION = pd.Timestamp(year=2024, month=1, day=1, microsecond=1)
PANDAS_NANOSEC_PRECISION = pd.Timestamp(
year=2024, month=1, day=1, hour=1, minute=1, second=1
) + pd.Timedelta(nanoseconds=1)
# Define numpy.datetime64 values for comparison
DATETIME64_DAY_PRECISION = np.datetime64("2024-01-01")
DATETIME64_HOUR_PRECISION = np.datetime64("2024-01-01T01:00", "s")
DATETIME64_MIN_PRECISION = np.datetime64("2024-01-01T00:01", "s")
DATETIME64_SEC_PRECISION = np.datetime64("2024-01-01T00:00:01")
DATETIME64_MILLISEC_PRECISION = np.datetime64("2024-01-01T00:00:00.001")
DATETIME64_MICROSEC_PRECISION = np.datetime64("2024-01-01T00:00:00.000001")
DATETIME64_NANOSEC_PRECISION = np.datetime64("2024-01-01T01:01:01.000000001", "ns")
# Parametrized test to validate datetime values and expected numpy.datetime64 results
@pytest.mark.parametrize(
"data,expected_output",
[
(
[DATETIME_DAY_PRECISION],
np.array([DATETIME64_DAY_PRECISION], dtype="datetime64[s]"),
),
([DATETIME_HOUR_PRECISION], np.array([DATETIME64_HOUR_PRECISION])),
([DATETIME_MIN_PRECISION], np.array([DATETIME64_MIN_PRECISION])),
([DATETIME_SEC_PRECISION], np.array([DATETIME64_SEC_PRECISION])),
([DATETIME_MILLISEC_PRECISION], np.array([DATETIME64_MILLISEC_PRECISION])),
([DATETIME_MICROSEC_PRECISION], np.array([DATETIME64_MICROSEC_PRECISION])),
(
[DATETIME_MICROSEC_PRECISION, DATETIME_MILLISEC_PRECISION],
np.array(
[DATETIME64_MICROSEC_PRECISION, DATETIME64_MILLISEC_PRECISION],
dtype="datetime64[us]",
),
),
(
[DATETIME_SEC_PRECISION, DATETIME_MILLISEC_PRECISION],
np.array(
[DATETIME64_SEC_PRECISION, DATETIME64_MILLISEC_PRECISION],
dtype="datetime64[ms]",
),
),
(
[DATETIME_DAY_PRECISION, DATETIME_SEC_PRECISION],
np.array(
[DATETIME64_DAY_PRECISION, DATETIME64_SEC_PRECISION],
dtype="datetime64[s]",
),
),
(
[PANDAS_DAY_PRECISION],
np.array([DATETIME64_DAY_PRECISION], dtype="datetime64[s]"),
),
([PANDAS_HOUR_PRECISION], np.array([DATETIME64_HOUR_PRECISION])),
([PANDAS_MIN_PRECISION], np.array([DATETIME64_MIN_PRECISION])),
([PANDAS_SEC_PRECISION], np.array([DATETIME64_SEC_PRECISION])),
([PANDAS_MILLISEC_PRECISION], np.array([DATETIME64_MILLISEC_PRECISION])),
([PANDAS_MICROSEC_PRECISION], np.array([DATETIME64_MICROSEC_PRECISION])),
([PANDAS_NANOSEC_PRECISION], np.array([DATETIME64_NANOSEC_PRECISION])),
(
[PANDAS_NANOSEC_PRECISION, PANDAS_MICROSEC_PRECISION],
np.array(
[DATETIME64_NANOSEC_PRECISION, DATETIME64_MICROSEC_PRECISION],
dtype="datetime64[ns]",
),
),
(
[PANDAS_MICROSEC_PRECISION, PANDAS_MILLISEC_PRECISION],
np.array(
[DATETIME64_MICROSEC_PRECISION, DATETIME64_MILLISEC_PRECISION],
dtype="datetime64[us]",
),
),
(
[PANDAS_SEC_PRECISION, PANDAS_MILLISEC_PRECISION],
np.array(
[DATETIME64_SEC_PRECISION, DATETIME64_MILLISEC_PRECISION],
dtype="datetime64[ms]",
),
),
(
[PANDAS_DAY_PRECISION, PANDAS_SEC_PRECISION],
np.array(
[DATETIME64_DAY_PRECISION, DATETIME64_SEC_PRECISION],
dtype="datetime64[s]",
),
),
],
)
def test_list_of_datetimes(
data, expected_output, ray_start_regular_shared, restore_data_context
):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
output = do_map_batches(data)
assert_structure_equals(output, expected_output)
def test_array_like(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = torch.Tensor([1, 2, 3])
output = do_map_batches(data)
assert_structure_equals(output, np.array([1.0, 2.0, 3.0], dtype=np.float32))
def test_list_of_arrays(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [np.array([1, 2, 3]), np.array([4, 5, 6])]
output = do_map_batches(data)
assert_structure_equals(output, np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int64))
def test_list_of_array_like(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [torch.Tensor([1, 2, 3]), torch.Tensor([4, 5, 6])]
output = do_map_batches(data)
assert_structure_equals(output, np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))
def test_ragged_tensors_map_batches(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [torch.Tensor([1, 2, 3]), torch.Tensor([1, 2])]
output = do_map_batches(data)
assert_structure_equals(
output, create_ragged_ndarray([np.array([1, 2, 3]), np.array([1, 2])])
)
data = [torch.zeros((3, 5, 10)), torch.zeros((3, 8, 8))]
output = do_map_batches(data)
assert_structure_equals(
output, create_ragged_ndarray([np.zeros((3, 5, 10)), np.zeros((3, 8, 8))])
)
def test_scalar_nested_arrays(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [[[1]], [[2]]]
output = do_map_batches(data)
assert_structure_equals(
output,
create_ragged_ndarray(
[np.array([1], dtype=np.object_), np.array([2], dtype=np.object_)]
),
)
def test_scalar_lists_not_converted(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [[1, 2], [1, 2]]
output = do_map_batches(data)
assert_structure_equals(
output, create_ragged_ndarray([np.array([1, 2]), np.array([1, 2])])
)
data = [[1, 2, 3], [1, 2]]
output = do_map_batches(data)
assert_structure_equals(
output, create_ragged_ndarray([np.array([1, 2, 3]), np.array([1, 2])])
)
def test_scalar_numpy(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = np.int64(1)
ds = ray.data.range(2, override_num_blocks=1)
ds = ds.map(lambda x: {"output": data})
output = ds.take_batch()["output"]
assert_structure_equals(output, np.array([1, 1], dtype=np.int64))
def test_scalar_arrays(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = np.array([1, 2, 3])
ds = ray.data.range(2, override_num_blocks=1)
ds = ds.map(lambda x: {"output": data})
output = ds.take_batch()["output"]
assert_structure_equals(output, np.array([[1, 2, 3], [1, 2, 3]], dtype=np.int64))
def test_bytes(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
"""Tests that bytes are converted to object dtype instead of zero-terminated."""
data = b"\x1a\n\x00\n\x1a"
ds = ray.data.range(1, override_num_blocks=1)
ds = ds.map(lambda x: {"output": data})
output = ds.take_batch()["output"]
assert_structure_equals(output, np.array([b"\x1a\n\x00\n\x1a"], dtype=object))
def test_uniform_tensors(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = torch.Tensor([1, 2, 3])
ds = ray.data.range(2, override_num_blocks=1)
ds = ds.map(lambda x: {"output": data})
output = ds.take_batch()["output"]
assert_structure_equals(output, np.array([[1, 2, 3], [1, 2, 3]], dtype=np.float32))
def test_scalar_ragged_arrays(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [np.array([1, 2, 3]), np.array([1, 2])]
ds = ray.data.range(2, override_num_blocks=1)
ds = ds.map(lambda x: {"output": data[x["id"]]})
output = ds.take_batch()["output"]
assert_structure_equals(
output, np.array([np.array([1, 2, 3]), np.array([1, 2])], dtype=object)
)
def test_ragged_tensors(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [torch.Tensor([1, 2, 3]), torch.Tensor([1, 2])]
ds = ray.data.range(2, override_num_blocks=1)
ds = ds.map(lambda x: {"output": data[x["id"]]})
output = ds.take_batch()["output"]
assert_structure_equals(
output, np.array([np.array([1, 2, 3]), np.array([1, 2])], dtype=object)
)
data = [torch.zeros((3, 5, 10)), torch.zeros((3, 8, 8))]
ds = ray.data.range(2, override_num_blocks=1)
ds = ds.map(lambda x: {"output": data[x["id"]]})
output = ds.take_batch()["output"]
assert_structure_equals(
output, create_ragged_ndarray([np.zeros((3, 5, 10)), np.zeros((3, 8, 8))])
)
def test_nested_ragged_arrays(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [
{"a": [[1], [2, 3]]},
{"a": [[4, 5], [6]]},
]
def f(row):
return data[row["id"]]
output = ray.data.range(2).map(f).take_all()
assert output == data
# https://github.com/ray-project/ray/issues/35340
def test_complex_ragged_arrays(ray_start_regular_shared, restore_data_context):
# Disable (automatic) fallback to `ArrowPythonObjectType` extension type
DataContext.get_current().enable_fallback_to_arrow_object_ext_type = False
data = [[{"a": 1}, {"a": 2}, {"a": 3}], [{"b": 1}]]
output = do_map_batches(data)
# Assert resulting objects are coerced to appropriate shape, following
# table's schema
assert_structure_equals(
output,
create_ragged_ndarray(
[
np.array(
[{"a": 1, "b": None}, {"a": 2, "b": None}, {"a": 3, "b": None}]
),
np.array([{"a": None, "b": 1}]),
]
),
)
data = ["hi", 1, None, [[[[]]]], {"a": [[{"b": 2, "c": UserObj()}]]}, UserObj()]
output = do_map_batches(data)
assert_structure_equals(output, create_ragged_ndarray(data))
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-v", __file__]))
| UserObj |
python | walkccc__LeetCode | solutions/1948. Delete Duplicate Folders in System/1948.py | {
"start": 0,
"end": 109
} | class ____:
def __init__(self):
self.children: dict[str, TrieNode] = {}
self.deleted = False
| TrieNode |
python | has2k1__plotnine | plotnine/scales/scale_manual.py | {
"start": 4142,
"end": 4553
} | class ____(_scale_manual):
"""
Custom discrete size scale
"""
_aesthetics = ["size"]
values: InitVar[Sequence[Any] | dict[Any, Any]]
"""
Sizes that make up the palette. The values will be matched
with the `limits` of the scale or the `breaks` if provided.
If it is a dict then it should map data values to sizes.
"""
# American to British spelling
@alias
| scale_size_manual |
python | coleifer__peewee | tests/regressions.py | {
"start": 47108,
"end": 48623
} | class ____(ModelTestCase):
requires = [LK]
def assertNames(self, expr, expected):
query = LK.select().where(expr).order_by(LK.id)
self.assertEqual([lk.key for lk in query], expected)
def test_like_escape(self):
names = ('foo', 'foo%', 'foo%bar', 'foo_bar', 'fooxba', 'fooba')
LK.insert_many([(n,) for n in names]).execute()
cases = (
(LK.key.contains('bar'), ['foo%bar', 'foo_bar']),
(LK.key.contains('%'), ['foo%', 'foo%bar']),
(LK.key.contains('_'), ['foo_bar']),
(LK.key.contains('o%b'), ['foo%bar']),
(LK.key.startswith('foo%'), ['foo%', 'foo%bar']),
(LK.key.startswith('foo_'), ['foo_bar']),
(LK.key.startswith('bar'), []),
(LK.key.endswith('ba'), ['fooxba', 'fooba']),
(LK.key.endswith('_bar'), ['foo_bar']),
(LK.key.endswith('fo'), []),
)
for expr, expected in cases:
self.assertNames(expr, expected)
def test_like_escape_backslash(self):
names = ('foo_bar\\baz', 'bar\\', 'fbar\\baz', 'foo_bar')
LK.insert_many([(n,) for n in names]).execute()
cases = (
(LK.key.contains('\\'), ['foo_bar\\baz', 'bar\\', 'fbar\\baz']),
(LK.key.contains('_bar\\'), ['foo_bar\\baz']),
(LK.key.contains('bar\\'), ['foo_bar\\baz', 'bar\\', 'fbar\\baz']),
)
for expr, expected in cases:
self.assertNames(expr, expected)
| TestLikeEscape |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_aux/test_migrate_database_job.py | {
"start": 16276,
"end": 19068
} | class ____:
"""Tests migrate database job service account."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"migrateDatabaseJob": {
"labels": {"test_label": "test_label_value"},
},
},
show_only=["templates/jobs/migrate-database-job-serviceaccount.yaml"],
)
assert "test_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["test_label"] == "test_label_value"
def test_should_merge_common_labels_and_component_specific_labels(self):
docs = render_chart(
values={
"labels": {"test_common_label": "test_common_label_value"},
"migrateDatabaseJob": {
"labels": {"test_specific_label": "test_specific_label_value"},
},
},
show_only=["templates/jobs/migrate-database-job-serviceaccount.yaml"],
)
assert "test_common_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["test_common_label"] == "test_common_label_value"
assert "test_specific_label" in jmespath.search("metadata.labels", docs[0])
assert (
jmespath.search("metadata.labels", docs[0])["test_specific_label"] == "test_specific_label_value"
)
def test_default_automount_service_account_token(self):
docs = render_chart(
values={
"migrateDatabaseJob": {
"serviceAccount": {"create": True},
},
},
show_only=["templates/jobs/migrate-database-job-serviceaccount.yaml"],
)
assert jmespath.search("automountServiceAccountToken", docs[0]) is True
def test_overridden_automount_service_account_token(self):
docs = render_chart(
values={
"migrateDatabaseJob": {
"serviceAccount": {"create": True, "automountServiceAccountToken": False},
},
},
show_only=["templates/jobs/migrate-database-job-serviceaccount.yaml"],
)
assert jmespath.search("automountServiceAccountToken", docs[0]) is False
def test_should_add_component_specific_env(self):
env = {"name": "test_env_key", "value": "test_env_value"}
docs = render_chart(
values={
"migrateDatabaseJob": {
"env": [env],
},
},
show_only=["templates/jobs/migrate-database-job.yaml"],
)
assert env in jmespath.search("spec.template.spec.containers[0].env", docs[0])
| TestMigrateDatabaseJobServiceAccount |
python | huggingface__transformers | src/transformers/models/mlcd/modular_mlcd.py | {
"start": 5817,
"end": 7317
} | class ____(VisionRotaryEmbedding):
def forward(self, num_patches_height: int, num_patches_width: int) -> torch.Tensor:
"""
Calculate the Rotary Position Embedding (RoPE) for MLCDVisionModel based on the grid size.
Args:
num_patches_height (int): Number of patches in the height dimension.
num_patches_width (int): Number of patches in the width dimension.
Returns:
torch.Tensor: Rotary positional embeddings for the given grid size.
"""
# Generate position IDs for height and width dimensions
hpos_ids = (
torch.arange(num_patches_height, device=self.inv_freq.device).unsqueeze(1).expand(-1, num_patches_width)
)
wpos_ids = (
torch.arange(num_patches_width, device=self.inv_freq.device).unsqueeze(0).expand(num_patches_height, -1)
)
# Flatten and stack the position IDs
pos_ids = torch.stack([hpos_ids.flatten(), wpos_ids.flatten()], dim=-1)
# Generate the full rotary positional embeddings for the maximum grid size
max_grid_size = max(num_patches_height, num_patches_width)
seq = torch.arange(max_grid_size, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
rotary_pos_emb_full = torch.outer(seq, self.inv_freq)
# Select and flatten the embeddings based on the position IDs
rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
return rotary_pos_emb
| MLCDRotaryEmbedding |
python | tornadoweb__tornado | tornado/platform/asyncio.py | {
"start": 2397,
"end": 10207
} | class ____(IOLoop):
def initialize( # type: ignore
self, asyncio_loop: asyncio.AbstractEventLoop, **kwargs: Any
) -> None:
# asyncio_loop is always the real underlying IOLoop. This is used in
# ioloop.py to maintain the asyncio-to-ioloop mappings.
self.asyncio_loop = asyncio_loop
# selector_loop is an event loop that implements the add_reader family of
# methods. Usually the same as asyncio_loop but differs on platforms such
# as windows where the default event loop does not implement these methods.
self.selector_loop = asyncio_loop
if hasattr(asyncio, "ProactorEventLoop") and isinstance(
asyncio_loop, asyncio.ProactorEventLoop
):
# Ignore this line for mypy because the abstract method checker
# doesn't understand dynamic proxies.
self.selector_loop = AddThreadSelectorEventLoop(asyncio_loop) # type: ignore
# Maps fd to (fileobj, handler function) pair (as in IOLoop.add_handler)
self.handlers: Dict[int, Tuple[Union[int, _Selectable], Callable]] = {}
# Set of fds listening for reads/writes
self.readers: Set[int] = set()
self.writers: Set[int] = set()
self.closing = False
# If an asyncio loop was closed through an asyncio interface
# instead of IOLoop.close(), we'd never hear about it and may
# have left a dangling reference in our map. In case an
# application (or, more likely, a test suite) creates and
# destroys a lot of event loops in this way, check here to
# ensure that we don't have a lot of dead loops building up in
# the map.
#
# TODO(bdarnell): consider making self.asyncio_loop a weakref
# for AsyncIOMainLoop and make _ioloop_for_asyncio a
# WeakKeyDictionary.
for loop in IOLoop._ioloop_for_asyncio.copy():
if loop.is_closed():
try:
del IOLoop._ioloop_for_asyncio[loop]
except KeyError:
pass
# Make sure we don't already have an IOLoop for this asyncio loop
existing_loop = IOLoop._ioloop_for_asyncio.setdefault(asyncio_loop, self)
if existing_loop is not self:
raise RuntimeError(
f"IOLoop {existing_loop} already associated with asyncio loop {asyncio_loop}"
)
super().initialize(**kwargs)
def close(self, all_fds: bool = False) -> None:
self.closing = True
for fd in list(self.handlers):
fileobj, handler_func = self.handlers[fd]
self.remove_handler(fd)
if all_fds:
self.close_fd(fileobj)
# Remove the mapping before closing the asyncio loop. If this
# happened in the other order, we could race against another
# initialize() call which would see the closed asyncio loop,
# assume it was closed from the asyncio side, and do this
# cleanup for us, leading to a KeyError.
del IOLoop._ioloop_for_asyncio[self.asyncio_loop]
if self.selector_loop is not self.asyncio_loop:
self.selector_loop.close()
self.asyncio_loop.close()
def add_handler(
self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
) -> None:
fd, fileobj = self.split_fd(fd)
if fd in self.handlers:
raise ValueError("fd %s added twice" % fd)
self.handlers[fd] = (fileobj, handler)
if events & IOLoop.READ:
self.selector_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
self.readers.add(fd)
if events & IOLoop.WRITE:
self.selector_loop.add_writer(fd, self._handle_events, fd, IOLoop.WRITE)
self.writers.add(fd)
def update_handler(self, fd: Union[int, _Selectable], events: int) -> None:
fd, fileobj = self.split_fd(fd)
if events & IOLoop.READ:
if fd not in self.readers:
self.selector_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
self.readers.add(fd)
else:
if fd in self.readers:
self.selector_loop.remove_reader(fd)
self.readers.remove(fd)
if events & IOLoop.WRITE:
if fd not in self.writers:
self.selector_loop.add_writer(fd, self._handle_events, fd, IOLoop.WRITE)
self.writers.add(fd)
else:
if fd in self.writers:
self.selector_loop.remove_writer(fd)
self.writers.remove(fd)
def remove_handler(self, fd: Union[int, _Selectable]) -> None:
fd, fileobj = self.split_fd(fd)
if fd not in self.handlers:
return
if fd in self.readers:
self.selector_loop.remove_reader(fd)
self.readers.remove(fd)
if fd in self.writers:
self.selector_loop.remove_writer(fd)
self.writers.remove(fd)
del self.handlers[fd]
def _handle_events(self, fd: int, events: int) -> None:
fileobj, handler_func = self.handlers[fd]
handler_func(fileobj, events)
def start(self) -> None:
self.asyncio_loop.run_forever()
def stop(self) -> None:
self.asyncio_loop.stop()
def call_at(
self, when: float, callback: Callable, *args: Any, **kwargs: Any
) -> object:
# asyncio.call_at supports *args but not **kwargs, so bind them here.
# We do not synchronize self.time and asyncio_loop.time, so
# convert from absolute to relative.
return self.asyncio_loop.call_later(
max(0, when - self.time()),
self._run_callback,
functools.partial(callback, *args, **kwargs),
)
def remove_timeout(self, timeout: object) -> None:
timeout.cancel() # type: ignore
def add_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:
try:
if asyncio.get_running_loop() is self.asyncio_loop:
call_soon = self.asyncio_loop.call_soon
else:
call_soon = self.asyncio_loop.call_soon_threadsafe
except RuntimeError:
call_soon = self.asyncio_loop.call_soon_threadsafe
try:
call_soon(self._run_callback, functools.partial(callback, *args, **kwargs))
except RuntimeError:
# "Event loop is closed". Swallow the exception for
# consistency with PollIOLoop (and logical consistency
# with the fact that we can't guarantee that an
# add_callback that completes without error will
# eventually execute).
pass
except AttributeError:
# ProactorEventLoop may raise this instead of RuntimeError
# if call_soon_threadsafe races with a call to close().
# Swallow it too for consistency.
pass
def add_callback_from_signal(
self, callback: Callable, *args: Any, **kwargs: Any
) -> None:
warnings.warn("add_callback_from_signal is deprecated", DeprecationWarning)
try:
self.asyncio_loop.call_soon_threadsafe(
self._run_callback, functools.partial(callback, *args, **kwargs)
)
except RuntimeError:
pass
def run_in_executor(
self,
executor: Optional[concurrent.futures.Executor],
func: Callable[..., _T],
*args: Any,
) -> "asyncio.Future[_T]":
return self.asyncio_loop.run_in_executor(executor, func, *args)
def set_default_executor(self, executor: concurrent.futures.Executor) -> None:
return self.asyncio_loop.set_default_executor(executor)
| BaseAsyncIOLoop |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/nonlocal_without_binding.py | {
"start": 395,
"end": 453
} | class ____:
def method(self):
nonlocal __class__
| A |
python | huggingface__transformers | src/transformers/models/bart/modeling_bart.py | {
"start": 63711,
"end": 70348
} | class ____(BartPreTrainedModel):
def __init__(self, config):
super().__init__(config)
config.num_labels = 2
self.num_labels = config.num_labels
self.model = BartModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
def tie_weights(self, missing_keys: Optional[set[str]] = None, recompute_mapping: bool = True):
"""We need to overload here to handle the wrong key saved in some main checkpoints."""
if self.config.tie_word_embeddings:
# Some model checkpoints like "facebook/bart-large-cnn"'s embedding weight is in decoder.embed_tokens,
# need check here, see issue #36247
if missing_keys is not None:
if "model.shared.weight" in missing_keys and "model.decoder.embed_tokens.weight" not in missing_keys:
self.model.encoder.embed_tokens.weight = self.model.decoder.embed_tokens.weight
self.model.shared.weight = self.model.decoder.embed_tokens.weight
missing_keys.discard("model.encoder.embed_token.weight")
missing_keys.discard("model.shared.weight")
# needs to be done after, otherwise it raises an Error because the correct weights are not present
super().tie_weights(missing_keys=missing_keys, recompute_mapping=recompute_mapping)
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
encoder_outputs: Optional[list[torch.FloatTensor]] = None,
start_positions: Optional[torch.LongTensor] = None,
end_positions: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
) -> Union[tuple, Seq2SeqQuestionAnsweringModelOutput]:
r"""
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are decoder input IDs?](../glossary#decoder-input-ids)
Bart uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
For translation and summarization training, `decoder_input_ids` should be provided. If no
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
for denoising pre-training following the paper.
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
be used by default.
If you want to change padding behavior, you should read [`modeling_bart._prepare_decoder_attention_mask`]
and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
information on the default strategy.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if start_positions is not None and end_positions is not None:
use_cache = False
outputs = self.model(
input_ids,
attention_mask=attention_mask,
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
encoder_outputs=encoder_outputs,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (
start_logits,
end_logits,
) + outputs[1:]
return ((total_loss,) + output) if total_loss is not None else output
return Seq2SeqQuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
past_key_values=outputs.past_key_values,
decoder_hidden_states=outputs.decoder_hidden_states,
decoder_attentions=outputs.decoder_attentions,
cross_attentions=outputs.cross_attentions,
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
encoder_hidden_states=outputs.encoder_hidden_states,
encoder_attentions=outputs.encoder_attentions,
)
| BartForQuestionAnswering |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 8443,
"end": 10447
} | class ____(django_test.TestCase):
"""Tests class Meta:
model = 'app.Model' pattern."""
def test_loading(self):
class ExampleFactory(factory.django.DjangoModelFactory):
class Meta:
model = 'djapp.StandardModel'
self.assertEqual(models.StandardModel, ExampleFactory._meta.get_model_class())
def test_building(self):
class ExampleFactory(factory.django.DjangoModelFactory):
class Meta:
model = 'djapp.StandardModel'
e = ExampleFactory.build()
self.assertEqual(models.StandardModel, e.__class__)
def test_inherited_loading(self):
"""Proper loading of a model within 'child' factories.
See https://github.com/FactoryBoy/factory_boy/issues/109.
"""
class ExampleFactory(factory.django.DjangoModelFactory):
class Meta:
model = 'djapp.StandardModel'
class Example2Factory(ExampleFactory):
pass
e = Example2Factory.build()
self.assertEqual(models.StandardModel, e.__class__)
def test_inherited_loading_and_sequence(self):
"""Proper loading of a model within 'child' factories.
See https://github.com/FactoryBoy/factory_boy/issues/109.
"""
class ExampleFactory(factory.django.DjangoModelFactory):
class Meta:
model = 'djapp.StandardModel'
foo = factory.Sequence(lambda n: n)
class Example2Factory(ExampleFactory):
class Meta:
model = 'djapp.StandardSon'
e1 = ExampleFactory.build()
e2 = Example2Factory.build()
e3 = ExampleFactory.build()
self.assertEqual(models.StandardModel, e1.__class__)
self.assertEqual(models.StandardSon, e2.__class__)
self.assertEqual(models.StandardModel, e3.__class__)
self.assertEqual(0, e1.foo)
self.assertEqual(1, e2.foo)
self.assertEqual(2, e3.foo)
| DjangoModelLoadingTestCase |
python | doocs__leetcode | solution/3000-3099/3016.Minimum Number of Pushes to Type Word II/Solution.py | {
"start": 0,
"end": 229
} | class ____:
def minimumPushes(self, word: str) -> int:
cnt = Counter(word)
ans = 0
for i, x in enumerate(sorted(cnt.values(), reverse=True)):
ans += (i // 8 + 1) * x
return ans
| Solution |
python | plotly__plotly.py | plotly/graph_objs/cone/colorbar/title/_font.py | {
"start": 233,
"end": 9898
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "cone.colorbar.title"
_path_str = "cone.colorbar.title.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 this color bar's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.cone.colorbar.title.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.cone.colorbar.title.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.cone.colorbar.title.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 | hynek__structlog | src/structlog/dev.py | {
"start": 13418,
"end": 35448
} | class ____:
r"""
Render ``event_dict`` nicely aligned, possibly in colors, and ordered.
If ``event_dict`` contains a true-ish ``exc_info`` key, it will be rendered
*after* the log line. If Rich_ or better-exceptions_ are present, in colors
and with extra context.
Tip:
Since `ConsoleRenderer` is mainly a development helper, it is less
strict about immutability than the rest of *structlog* for better
ergonomics. Notably, the currently active instance can be obtained by
calling `ConsoleRenderer.get_active()` and it offers properties to
configure its behavior after instantiation.
Args:
columns:
A list of `Column` objects defining both the order and format of
the key-value pairs in the output. If passed, most other arguments
become meaningless.
**Must** contain a column with ``key=''`` that defines the default
formatter.
.. seealso:: `columns-config`
pad_event_to:
Pad the event to this many characters. Ignored if *columns* are
passed.
colors:
Use colors for a nicer output. `True` by default. On Windows only
if Colorama_ is installed. Ignored if *columns* are passed.
force_colors:
Force colors even for non-tty destinations. Use this option if your
logs are stored in a file that is meant to be streamed to the
console. Only meaningful on Windows. Ignored if *columns* are
passed.
repr_native_str:
When `True`, `repr` is also applied to ``str``\ s. The ``event``
key is *never* `repr` -ed. Ignored if *columns* are passed.
level_styles:
When present, use these styles for colors. This must be a dict from
level names (strings) to terminal sequences (for example, Colorama)
styles. The default can be obtained by calling
`ConsoleRenderer.get_default_level_styles`. Ignored when *columns*
are passed.
exception_formatter:
A callable to render ``exc_infos``. If Rich_ or better-exceptions_
are installed, they are used for pretty-printing by default (rich_
taking precedence). You can also manually set it to
`plain_traceback`, `better_traceback`, an instance of
`RichTracebackFormatter` like `rich_traceback`, or implement your
own.
sort_keys:
Whether to sort keys when formatting. `True` by default. Ignored if
*columns* are passed.
event_key:
The key to look for the main log message. Needed when you rename it
e.g. using `structlog.processors.EventRenamer`. Ignored if
*columns* are passed.
timestamp_key:
The key to look for timestamp of the log message. Needed when you
rename it e.g. using `structlog.processors.EventRenamer`. Ignored
if *columns* are passed.
pad_level:
Whether to pad log level with blanks to the longest amongst all
level label.
Requires the Colorama_ package if *colors* is `True` **on Windows**.
Raises:
ValueError: If there's not exactly one default column formatter.
.. _Colorama: https://pypi.org/project/colorama/
.. _better-exceptions: https://pypi.org/project/better-exceptions/
.. _Rich: https://pypi.org/project/rich/
.. versionadded:: 16.0.0
.. versionadded:: 16.1.0 *colors*
.. versionadded:: 17.1.0 *repr_native_str*
.. versionadded:: 18.1.0 *force_colors*
.. versionadded:: 18.1.0 *level_styles*
.. versionchanged:: 19.2.0
Colorama now initializes lazily to avoid unwanted initializations as
``ConsoleRenderer`` is used by default.
.. versionchanged:: 19.2.0 Can be pickled now.
.. versionchanged:: 20.1.0
Colorama does not initialize lazily on Windows anymore because it breaks
rendering.
.. versionchanged:: 21.1.0
It is additionally possible to set the logger name using the
``logger_name`` key in the ``event_dict``.
.. versionadded:: 21.2.0 *exception_formatter*
.. versionchanged:: 21.2.0
`ConsoleRenderer` now handles the ``exc_info`` event dict key itself. Do
**not** use the `structlog.processors.format_exc_info` processor
together with `ConsoleRenderer` anymore! It will keep working, but you
can't have customize exception formatting and a warning will be raised
if you ask for it.
.. versionchanged:: 21.2.0
The colors keyword now defaults to True on non-Windows systems, and
either True or False in Windows depending on whether Colorama is
installed.
.. versionadded:: 21.3.0 *sort_keys*
.. versionadded:: 22.1.0 *event_key*
.. versionadded:: 23.2.0 *timestamp_key*
.. versionadded:: 23.3.0 *columns*
.. versionadded:: 24.2.0 *pad_level*
"""
_default_column_formatter: ColumnFormatter
def __init__(
self,
pad_event_to: int = _EVENT_WIDTH,
colors: bool = _has_colors,
force_colors: bool = False,
repr_native_str: bool = False,
level_styles: dict[str, str] | None = None,
exception_formatter: ExceptionRenderer = default_exception_formatter,
sort_keys: bool = True,
event_key: str = "event",
timestamp_key: str = "timestamp",
columns: list[Column] | None = None,
pad_level: bool = True,
pad_event: int | None = None,
):
if pad_event is not None:
if pad_event_to != _EVENT_WIDTH:
raise ValueError(
"Cannot set both `pad_event` and `pad_event_to`."
)
warnings.warn(
"The `pad_event` argument is deprecated. Use `pad_event_to` instead.",
DeprecationWarning,
stacklevel=2,
)
pad_event_to = pad_event
# Store all settings in case the user later switches from columns to
# defaults.
self.exception_formatter = exception_formatter
self._sort_keys = sort_keys
self._repr_native_str = repr_native_str
self._styles = self.get_default_column_styles(colors, force_colors)
self._colors = colors
self._force_colors = force_colors
self._level_styles = (
self.get_default_level_styles(colors)
if level_styles is None
else level_styles
)
self._pad_event_to = pad_event_to
self._timestamp_key = timestamp_key
self._event_key = event_key
self._pad_level = pad_level
if columns is None:
self._configure_columns()
return
self.columns = columns
to_warn = []
def add_meaningless_arg(arg: str) -> None:
to_warn.append(
f"The `{arg}` argument is ignored when passing `columns`.",
)
if pad_event_to != _EVENT_WIDTH:
add_meaningless_arg("pad_event_to")
if colors != _has_colors:
add_meaningless_arg("colors")
if force_colors is not False:
add_meaningless_arg("force_colors")
if repr_native_str is not False:
add_meaningless_arg("repr_native_str")
if level_styles is not None:
add_meaningless_arg("level_styles")
if event_key != "event":
add_meaningless_arg("event_key")
if timestamp_key != "timestamp":
add_meaningless_arg("timestamp_key")
for w in to_warn:
warnings.warn(w, stacklevel=2)
@classmethod
def get_active(cls) -> ConsoleRenderer:
"""
If *structlog* is configured to use `ConsoleRenderer`, it's returned.
It does not have to be the last processor.
Raises:
NoConsoleRendererConfiguredError:
If no ConsoleRenderer is found in the current configuration.
MultipleConsoleRenderersConfiguredError:
If more than one is found in the current configuration. This is
almost certainly a bug.
.. versionadded:: 25.5.0
"""
from ._config import get_config
cr = None
for p in get_config()["processors"]:
if isinstance(p, ConsoleRenderer):
if cr is not None:
raise MultipleConsoleRenderersConfiguredError
cr = p
if cr is None:
raise NoConsoleRendererConfiguredError
return cr
@classmethod
def get_default_column_styles(
cls, colors: bool, force_colors: bool = False
) -> ColumnStyles:
"""
Configure and return the appropriate styles class for console output.
This method handles the setup of colorful or plain styles, including
proper colorama initialization on Windows systems when colors are
enabled.
Args:
colors: Whether to use colorful output styles.
force_colors:
Force colorful output even in non-interactive environments.
Only relevant on Windows with colorama.
Returns:
The configured styles.
Raises:
SystemError:
On Windows when colors=True but colorama is not installed.
.. versionadded:: 25.5.0
"""
if not colors:
return _plain_styles
_init_terminal(cls.__name__, force_colors)
return _colorful_styles
@staticmethod
def get_default_level_styles(colors: bool = True) -> dict[str, str]:
"""
Get the default styles for log levels
This is intended to be used with `ConsoleRenderer`'s ``level_styles``
parameter. For example, if you are adding custom levels in your
home-grown :func:`~structlog.stdlib.add_log_level` you could do::
my_styles = ConsoleRenderer.get_default_level_styles()
my_styles["EVERYTHING_IS_ON_FIRE"] = my_styles["critical"]
renderer = ConsoleRenderer(level_styles=my_styles)
Args:
colors:
Whether to use colorful styles. This must match the *colors*
parameter to `ConsoleRenderer`. Default: `True`.
"""
styles: ColumnStyles
styles = _colorful_styles if colors else _plain_styles
return {
"critical": styles.level_critical,
"exception": styles.level_exception,
"error": styles.level_error,
"warn": styles.level_warn,
"warning": styles.level_warn,
"info": styles.level_info,
"debug": styles.level_debug,
"notset": styles.level_notset,
}
def _configure_columns(self) -> None:
"""
Re-configure self._columns and self._default_column_formatter
according to our current settings.
Overwrite existing columns settings, regardless of whether they were
explicitly passed by the user or derived by us.
"""
level_to_color = self._level_styles.copy()
for key in level_to_color:
level_to_color[key] += self._styles.bright
self._longest_level = len(
max(level_to_color.keys(), key=lambda e: len(e))
)
self._default_column_formatter = KeyValueColumnFormatter(
self._styles.kv_key,
self._styles.kv_value,
self._styles.reset,
value_repr=self._repr,
width=0,
)
logger_name_formatter = KeyValueColumnFormatter(
key_style=None,
value_style=self._styles.bright + self._styles.logger_name,
reset_style=self._styles.reset,
value_repr=str,
prefix="[",
postfix="]",
)
level_width = 0 if not self._pad_level else None
self._columns = [
Column(
self._timestamp_key,
KeyValueColumnFormatter(
key_style=None,
value_style=self._styles.timestamp,
reset_style=self._styles.reset,
value_repr=str,
),
),
Column(
"level",
LogLevelColumnFormatter(
level_to_color,
reset_style=self._styles.reset,
width=level_width,
),
),
Column(
self._event_key,
KeyValueColumnFormatter(
key_style=None,
value_style=self._styles.bright,
reset_style=self._styles.reset,
value_repr=str,
width=self._pad_event_to,
),
),
Column("logger", logger_name_formatter),
Column("logger_name", logger_name_formatter),
]
def _repr(self, val: Any) -> str:
"""
Determine representation of *val* depending on its type &
self._repr_native_str.
"""
if self._repr_native_str is True:
return repr(val)
if isinstance(val, str):
if set(val) & {" ", "\t", "=", "\r", "\n", '"', "'"}:
return repr(val)
return val
return repr(val)
def __call__(
self, logger: WrappedLogger, name: str, event_dict: EventDict
) -> str:
stack = event_dict.pop("stack", None)
exc = event_dict.pop("exception", None)
exc_info = event_dict.pop("exc_info", None)
kvs = [
col.formatter(col.key, val)
for col in self.columns
if (val := event_dict.pop(col.key, _NOTHING)) is not _NOTHING
] + [
self._default_column_formatter(key, event_dict[key])
for key in (sorted(event_dict) if self._sort_keys else event_dict)
]
sio = StringIO()
sio.write((" ".join(kv for kv in kvs if kv)).rstrip(" "))
if stack is not None:
sio.write("\n" + stack)
if exc_info or exc is not None:
sio.write("\n\n" + "=" * 79 + "\n")
exc_info = _figure_out_exc_info(exc_info)
if exc_info:
self._exception_formatter(sio, exc_info)
elif exc is not None:
if self._exception_formatter is not plain_traceback:
warnings.warn(
"Remove `format_exc_info` from your processor chain "
"if you want pretty exceptions.",
stacklevel=2,
)
sio.write("\n" + exc)
return sio.getvalue()
@property
def exception_formatter(self) -> ExceptionRenderer:
"""
The exception formatter used by this console renderer.
.. versionadded:: 25.5.0
"""
return self._exception_formatter
@exception_formatter.setter
def exception_formatter(self, value: ExceptionRenderer) -> None:
"""
.. versionadded:: 25.5.0
"""
self._exception_formatter = value
@property
def sort_keys(self) -> bool:
"""
Whether to sort keys when formatting.
.. versionadded:: 25.5.0
"""
return self._sort_keys
@sort_keys.setter
def sort_keys(self, value: bool) -> None:
"""
.. versionadded:: 25.5.0
"""
# _sort_keys is a format-time setting, so we can just set it directly.
self._sort_keys = value
@property
def columns(self) -> list[Column]:
"""
The columns configuration for this console renderer.
Warning:
Just like with passing *columns* argument, many of the other
arguments you may have passed are ignored.
Args:
value:
A list of `Column` objects defining both the order and format
of the key-value pairs in the output.
**Must** contain a column with ``key=''`` that defines the
default formatter.
Raises:
ValueError: If there's not exactly one default column formatter.
.. versionadded:: 25.5.0
"""
return [Column("", self._default_column_formatter), *self._columns]
@columns.setter
def columns(self, value: list[Column]) -> None:
"""
.. versionadded:: 25.5.0
"""
defaults = [col for col in value if col.key == ""]
if not defaults:
raise ValueError(
"Must pass a default column formatter (a column with `key=''`)."
)
if len(defaults) > 1:
raise ValueError("Only one default column formatter allowed.")
self._default_column_formatter = defaults[0].formatter
self._columns = [col for col in value if col.key]
@property
def colors(self) -> bool:
"""
Whether to use colorful output styles.
Setting this will update the renderer's styles immediately and reset
level styles to the defaults according to the new color setting -- even
if the color value is the same.
.. versionadded:: 25.5.0
"""
return self._colors
@colors.setter
def colors(self, value: bool) -> None:
"""
.. versionadded:: 25.5.0
"""
self._colors = value
self._styles = self.get_default_column_styles(
value, self._force_colors
)
self._level_styles = self.get_default_level_styles(value)
self._configure_columns()
@property
def force_colors(self) -> bool:
"""
Force colorful output even in non-interactive environments.
Setting this will update the renderer's styles immediately and reset
level styles to the defaults according to the current color setting --
even if the value is the same.
.. versionadded:: 25.5.0
"""
return self._force_colors
@force_colors.setter
def force_colors(self, value: bool) -> None:
"""
.. versionadded:: 25.5.0
"""
self._force_colors = value
self._styles = self.get_default_column_styles(self._colors, value)
self._level_styles = self.get_default_level_styles(self._colors)
self._configure_columns()
@property
def level_styles(self) -> dict[str, str]:
"""
The level styles mapping for this console renderer.
Setting this property will reset to defaults if set to None, otherwise
it applies the provided mapping. In all cases, columns are rebuilt to
reflect the change.
.. versionadded:: 25.5.0
"""
return self._level_styles
@level_styles.setter
def level_styles(self, value: dict[str, str] | None) -> None:
"""
.. versionadded:: 25.5.0
"""
self._level_styles = (
self.get_default_level_styles(self._colors)
if value is None
else value
)
self._configure_columns()
@property
def pad_level(self) -> bool:
"""
Whether to pad log level with blanks to the longest amongst all
level labels.
Setting this will rebuild columns to reflect the change.
.. versionadded:: 25.5.0
"""
return self._pad_level
@pad_level.setter
def pad_level(self, value: bool) -> None:
"""
.. versionadded:: 25.5.0
"""
self._pad_level = value
self._configure_columns()
@property
def pad_event_to(self) -> int:
"""
The number of characters to pad the event to.
Setting this will rebuild columns to reflect the change.
.. versionadded:: 25.5.0
"""
return self._pad_event_to
@pad_event_to.setter
def pad_event_to(self, value: int) -> None:
"""
.. versionadded:: 25.5.0
"""
self._pad_event_to = value
self._configure_columns()
@property
def event_key(self) -> str:
"""
The key to look for the main log message.
Setting this will rebuild columns to reflect the change.
.. versionadded:: 25.5.0
"""
return self._event_key
@event_key.setter
def event_key(self, value: str) -> None:
"""
.. versionadded:: 25.5.0
"""
self._event_key = value
self._configure_columns()
@property
def timestamp_key(self) -> str:
"""
The key to look for the timestamp of the log message.
Setting this will rebuild columns to reflect the change.
.. versionadded:: 25.5.0
"""
return self._timestamp_key
@timestamp_key.setter
def timestamp_key(self, value: str) -> None:
"""
.. versionadded:: 25.5.0
"""
self._timestamp_key = value
self._configure_columns()
@property
def repr_native_str(self) -> bool:
"""
Whether native strings are passed through repr() in non-event values.
.. versionadded:: 25.5.0
"""
return self._repr_native_str
@repr_native_str.setter
def repr_native_str(self, value: bool) -> None:
"""
.. versionadded:: 25.5.0
"""
self._repr_native_str = value
_SENTINEL = object()
def set_exc_info(
logger: WrappedLogger, method_name: str, event_dict: EventDict
) -> EventDict:
"""
Set ``event_dict["exc_info"] = True`` if *method_name* is ``"exception"``.
Do nothing if the name is different or ``exc_info`` is already set.
.. versionadded:: 19.2.0
"""
if (
method_name != "exception"
or event_dict.get("exc_info", _SENTINEL) is not _SENTINEL
):
return event_dict
event_dict["exc_info"] = True
return event_dict
| ConsoleRenderer |
python | kamyu104__LeetCode-Solutions | Python/maximum-building-height.py | {
"start": 33,
"end": 828
} | class ____(object):
def maxBuilding(self, n, restrictions):
"""
:type n: int
:type restrictions: List[List[int]]
:rtype: int
"""
restrictions.extend([[1, 0], [n, n-1]])
restrictions.sort()
for i in reversed(xrange(len(restrictions)-1)):
restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1]+(restrictions[i+1][0]-restrictions[i][0]))
result = 0
for i in xrange(1, len(restrictions)):
restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1]+(restrictions[i][0]-restrictions[i-1][0]))
left, h1 = restrictions[i-1]
right, h2 = restrictions[i]
result = max(result, max(h1, h2)+((right-left)-abs(h1-h2))//2)
return result
| Solution |
python | mlflow__mlflow | mlflow/server/graphql/autogenerated_graphql_schema.py | {
"start": 768,
"end": 888
} | class ____(graphene.Enum):
PENDING_REGISTRATION = 1
FAILED_REGISTRATION = 2
READY = 3
| MlflowModelVersionStatus |
python | doocs__leetcode | solution/2400-2499/2421.Number of Good Paths/Solution.py | {
"start": 0,
"end": 839
} | class ____:
def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
n = len(vals)
p = list(range(n))
size = defaultdict(Counter)
for i, v in enumerate(vals):
size[i][v] = 1
ans = n
for v, a in sorted(zip(vals, range(n))):
for b in g[a]:
if vals[b] > v:
continue
pa, pb = find(a), find(b)
if pa != pb:
ans += size[pa][v] * size[pb][v]
p[pa] = pb
size[pb][v] += size[pa][v]
return ans
| Solution |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 207538,
"end": 207655
} | class ____(AsyncDefNode):
gen_type_name = 'IterableCoroutine'
is_iterable_coroutine = True
| IterableAsyncDefNode |
python | huggingface__transformers | src/transformers/generation/stopping_criteria.py | {
"start": 27636,
"end": 28874
} | class ____(list):
@add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
is_done = torch.full((input_ids.shape[0],), False, device=input_ids.device, dtype=torch.bool)
for criteria in self:
is_done = is_done | criteria(input_ids, scores, **kwargs)
return is_done
@property
def max_length(self) -> int | None:
for stopping_criterium in self:
if isinstance(stopping_criterium, MaxLengthCriteria):
return stopping_criterium.max_length
return None
def validate_stopping_criteria(stopping_criteria: StoppingCriteriaList, max_length: int) -> StoppingCriteriaList:
stopping_max_length = stopping_criteria.max_length
new_stopping_criteria = deepcopy(stopping_criteria)
if stopping_max_length is not None and stopping_max_length != max_length:
warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter", UserWarning)
elif stopping_max_length is None:
new_stopping_criteria.append(MaxLengthCriteria(max_length=max_length))
return new_stopping_criteria
| StoppingCriteriaList |
python | apache__airflow | airflow-core/src/airflow/providers_manager.py | {
"start": 3111,
"end": 6106
} | class ____(MutableMapping):
"""
Lazy-loaded cached dictionary.
Dictionary, which in case you set callable, executes the passed callable with `key` attribute
at first use - and returns and caches the result.
"""
__slots__ = ["_resolved", "_raw_dict"]
def __init__(self, *args, **kw):
self._resolved = set()
self._raw_dict = dict(*args, **kw)
def __setitem__(self, key, value):
self._raw_dict.__setitem__(key, value)
def __getitem__(self, key):
value = self._raw_dict.__getitem__(key)
if key not in self._resolved and callable(value):
# exchange callable with result of calling it -- but only once! allow resolver to return a
# callable itself
value = value()
self._resolved.add(key)
self._raw_dict.__setitem__(key, value)
return value
def __delitem__(self, key):
with contextlib.suppress(KeyError):
self._resolved.remove(key)
self._raw_dict.__delitem__(key)
def __iter__(self):
return iter(self._raw_dict)
def __len__(self):
return len(self._raw_dict)
def __contains__(self, key):
return key in self._raw_dict
def clear(self):
self._resolved.clear()
self._raw_dict.clear()
def _read_schema_from_resources_or_local_file(filename: str) -> dict:
try:
with resource_files("airflow").joinpath(filename).open("rb") as f:
schema = json.load(f)
except (TypeError, FileNotFoundError):
import pathlib
with (pathlib.Path(__file__).parent / filename).open("rb") as f:
schema = json.load(f)
return schema
def _create_provider_info_schema_validator():
"""Create JSON schema validator from the provider_info.schema.json."""
import jsonschema
schema = _read_schema_from_resources_or_local_file("provider_info.schema.json")
cls = jsonschema.validators.validator_for(schema)
validator = cls(schema)
return validator
def _create_customized_form_field_behaviours_schema_validator():
"""Create JSON schema validator from the customized_form_field_behaviours.schema.json."""
import jsonschema
schema = _read_schema_from_resources_or_local_file("customized_form_field_behaviours.schema.json")
cls = jsonschema.validators.validator_for(schema)
validator = cls(schema)
return validator
def _check_builtin_provider_prefix(provider_package: str, class_name: str) -> bool:
if provider_package.startswith("apache-airflow"):
provider_path = provider_package[len("apache-") :].replace("-", ".")
if not class_name.startswith(provider_path):
log.warning(
"Coherence check failed when importing '%s' from '%s' package. It should start with '%s'",
class_name,
provider_package,
provider_path,
)
return False
return True
@dataclass
| LazyDictWithCache |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/helpers/cli.py | {
"start": 999,
"end": 2958
} | class ____:
quiet: bool = True
help_message: Optional[str] = None
def log_command_results(
ctx: click.Context, command_results: List[CommandResult], logger: Logger, options: LogOptions = LogOptions()
) -> None:
"""
Log the output of the subcommands run by `run_all_subcommands`.
"""
if not options.quiet:
details_template = Template(DETAILS_TEMPLATE_STR)
details_message = details_template.render(command_results=command_results)
logger.info(details_message)
summary_template = Template(SUMMARY_TEMPLATE_STR)
summary_message = summary_template.render(command_results=command_results)
logger.info(summary_message)
if options.help_message:
logger.info(options.help_message)
async def invoke_commands_concurrently(ctx: click.Context, commands: List[click.Command]) -> List[Any]:
"""
Run click commands concurrently and return a list of their return values.
"""
soon_command_executions_results = []
async with asyncer.create_task_group() as command_task_group:
for command in commands:
soon_command_execution_result = command_task_group.soonify(command.invoke)(ctx)
soon_command_executions_results.append(soon_command_execution_result)
return [r.value for r in soon_command_executions_results]
async def invoke_commands_sequentially(ctx: click.Context, commands: List[click.Command]) -> List[Any]:
"""
Run click commands sequentially and return a list of their return values.
"""
command_executions_results = []
for command in commands:
command_executions_results.append(await command.invoke(ctx))
return command_executions_results
def get_all_sibling_commands(ctx: click.Context) -> List[click.Command]:
"""
Get all sibling commands of the current command.
"""
return [c for c in ctx.parent.command.commands.values() if c.name != ctx.command.name] # type: ignore
| LogOptions |
python | cython__cython | docs/examples/userguide/language_basics/optional_subclassing.py | {
"start": 96,
"end": 191
} | class ____(A):
@cython.cfunc
def foo(self, x=None):
print("B", x)
@cython.cclass
| B |
python | huggingface__transformers | tests/models/speecht5/test_modeling_speecht5.py | {
"start": 52523,
"end": 56969
} | class ____:
def __init__(
self,
parent,
batch_size=13,
encoder_seq_length=1024, # speech is longer
decoder_seq_length=1024,
is_training=False,
hidden_size=24,
num_hidden_layers=2,
num_attention_heads=2,
intermediate_size=4,
conv_dim=(32, 32, 32),
conv_stride=(4, 4, 4),
conv_kernel=(8, 8, 8),
conv_bias=False,
num_conv_pos_embeddings=16,
num_conv_pos_embedding_groups=2,
vocab_size=81,
num_mel_bins=20,
reduction_factor=2,
speech_decoder_postnet_layers=2,
speech_decoder_postnet_units=32,
speech_decoder_prenet_units=32,
):
self.parent = parent
self.batch_size = batch_size
self.encoder_seq_length = encoder_seq_length
self.decoder_seq_length = decoder_seq_length
self.is_training = is_training
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.conv_dim = conv_dim
self.conv_stride = conv_stride
self.conv_kernel = conv_kernel
self.conv_bias = conv_bias
self.num_conv_pos_embeddings = num_conv_pos_embeddings
self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
self.vocab_size = vocab_size
self.num_mel_bins = num_mel_bins
self.reduction_factor = reduction_factor
self.speech_decoder_postnet_layers = speech_decoder_postnet_layers
self.speech_decoder_postnet_units = speech_decoder_postnet_units
self.speech_decoder_prenet_units = speech_decoder_prenet_units
def prepare_config_and_inputs(self):
input_values = floats_tensor([self.batch_size, self.encoder_seq_length], scale=1.0)
attention_mask = random_attention_mask([self.batch_size, self.encoder_seq_length])
decoder_input_values = floats_tensor([self.batch_size, self.decoder_seq_length, self.num_mel_bins], scale=1.0)
decoder_attention_mask = random_attention_mask([self.batch_size, self.decoder_seq_length])
config = self.get_config()
inputs_dict = prepare_inputs_dict(
config,
input_values=input_values,
decoder_input_values=decoder_input_values,
attention_mask=attention_mask,
decoder_attention_mask=decoder_attention_mask,
)
return config, inputs_dict
def prepare_config_and_inputs_for_common(self):
config, inputs_dict = self.prepare_config_and_inputs()
return config, inputs_dict
def get_config(self):
return SpeechT5Config(
hidden_size=self.hidden_size,
encoder_layers=self.num_hidden_layers,
decoder_layers=self.num_hidden_layers,
encoder_attention_heads=self.num_attention_heads,
decoder_attention_heads=self.num_attention_heads,
encoder_ffn_dim=self.intermediate_size,
decoder_ffn_dim=self.intermediate_size,
conv_dim=self.conv_dim,
conv_stride=self.conv_stride,
conv_kernel=self.conv_kernel,
conv_bias=self.conv_bias,
num_conv_pos_embeddings=self.num_conv_pos_embeddings,
num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups,
vocab_size=self.vocab_size,
num_mel_bins=self.num_mel_bins,
reduction_factor=self.reduction_factor,
speech_decoder_postnet_layers=self.speech_decoder_postnet_layers,
speech_decoder_postnet_units=self.speech_decoder_postnet_units,
speech_decoder_prenet_units=self.speech_decoder_prenet_units,
)
def create_and_check_model_forward(self, config, inputs_dict):
model = SpeechT5ForSpeechToSpeech(config=config).to(torch_device).eval()
input_values = inputs_dict["input_values"]
attention_mask = inputs_dict["attention_mask"]
decoder_input_values = inputs_dict["decoder_input_values"]
result = model(input_values, attention_mask=attention_mask, decoder_input_values=decoder_input_values)
self.parent.assertEqual(
result.spectrogram.shape,
(self.batch_size, self.decoder_seq_length * self.reduction_factor, self.num_mel_bins),
)
@require_torch
| SpeechT5ForSpeechToSpeechTester |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_bad_repr.py | {
"start": 465,
"end": 1278
} | class ____:
def __init__(self, value):
self.value = value
def __repr__(self):
return self.value
Frosty = BadRepr("☃")
def test_just_frosty():
assert repr(st.just(Frosty)) == "just(☃)"
def test_sampling_snowmen():
assert repr(st.sampled_from((Frosty, "hi"))) == "sampled_from((☃, 'hi'))"
def varargs(*args, **kwargs):
pass
@given(
st.sampled_from(
[
"✐",
"✑",
"✒",
"✓",
"✔",
"✕",
"✖",
"✗",
"✘",
"✙",
"✚",
"✛",
"✜",
"✝",
"✞",
"✟",
"✠",
"✡",
"✢",
"✣",
]
)
)
def test_sampled_from_bad_repr(c):
pass
| BadRepr |
python | scikit-image__scikit-image | benchmarks/benchmark_morphology.py | {
"start": 2296,
"end": 4994
} | class ____:
param_names = ["shape", "footprint", "radius", "decomposition"]
params = [
((512, 512),),
("square", "diamond", "octagon", "disk", "ellipse", "star"),
(1, 3, 5, 15, 25, 40),
(None, "sequence", "separable", "crosses"),
]
def setup(self, shape, footprint, radius, decomposition):
rng = np.random.default_rng(123)
# Make an image that is mostly True, with random isolated False areas
# (so it will not become fully False for any of the footprints).
self.image = rng.standard_normal(shape) < 3.5
fp_func = getattr(morphology, footprint)
allow_sequence = ("rectangle", "square", "diamond", "octagon", "disk")
allow_separable = ("rectangle", "square")
allow_crosses = ("disk", "ellipse")
allow_decomp = tuple(
set(allow_sequence) | set(allow_separable) | set(allow_crosses)
)
footprint_kwargs = {}
if decomposition == "sequence" and footprint not in allow_sequence:
raise NotImplementedError("decomposition unimplemented")
elif decomposition == "separable" and footprint not in allow_separable:
raise NotImplementedError("separable decomposition unavailable")
elif decomposition == "crosses" and footprint not in allow_crosses:
raise NotImplementedError("separable decomposition unavailable")
if footprint in allow_decomp:
footprint_kwargs["decomposition"] = decomposition
if footprint in ["rectangle", "square"]:
size = 2 * radius + 1
self.footprint = fp_func(size, **footprint_kwargs)
elif footprint in ["diamond", "disk"]:
self.footprint = fp_func(radius, **footprint_kwargs)
elif footprint == "star":
# set a so bounding box size is approximately 2*radius + 1
# size will be 2*a + 1 + 2*floor(a / 2)
a = max((2 * radius) // 3, 1)
self.footprint = fp_func(a, **footprint_kwargs)
elif footprint == "octagon":
# overall size is m + 2 * n
# so choose m = n so that overall size is ~ 2*radius + 1
m = n = max((2 * radius) // 3, 1)
self.footprint = fp_func(m, n, **footprint_kwargs)
elif footprint == "ellipse":
if radius > 1:
# make somewhat elliptical
self.footprint = fp_func(radius - 1, radius + 1, **footprint_kwargs)
else:
self.footprint = fp_func(radius, radius, **footprint_kwargs)
def time_erosion(self, shape, footprint, radius, *args):
morphology.erosion(self.image, self.footprint)
| GrayMorphology2D |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py | {
"start": 2295,
"end": 2647
} | class ____(TypedDict):
"""Response when a human rejects the action."""
type: Literal["reject"]
"""The type of response when a human rejects the action."""
message: NotRequired[str]
"""The message sent to the model explaining why the action was rejected."""
Decision = ApproveDecision | EditDecision | RejectDecision
| RejectDecision |
python | django__django | tests/messages_tests/test_fallback.py | {
"start": 410,
"end": 6868
} | class ____(BaseTests, SimpleTestCase):
storage_class = FallbackStorage
def get_request(self):
self.session = {}
request = super().get_request()
request.session = self.session
return request
def get_cookie_storage(self, storage):
return storage.storages[-2]
def get_session_storage(self, storage):
return storage.storages[-1]
def stored_cookie_messages_count(self, storage, response):
return stored_cookie_messages_count(self.get_cookie_storage(storage), response)
def stored_session_messages_count(self, storage, response):
return stored_session_messages_count(self.get_session_storage(storage))
def stored_messages_count(self, storage, response):
"""
Return the storage totals from both cookie and session backends.
"""
return self.stored_cookie_messages_count(
storage, response
) + self.stored_session_messages_count(storage, response)
def test_get(self):
request = self.get_request()
storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage)
# Set initial cookie data.
example_messages = [str(i) for i in range(5)]
set_cookie_data(cookie_storage, example_messages)
# Overwrite the _get method of the fallback storage to prove it is not
# used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._get = None
self.assertEqual(list(storage), example_messages)
def test_get_empty(self):
request = self.get_request()
storage = self.storage_class(request)
# Overwrite the _get method of the fallback storage to prove it is not
# used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._get = None
self.assertEqual(list(storage), [])
def test_get_fallback(self):
request = self.get_request()
storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage)
session_storage = self.get_session_storage(storage)
# Set initial cookie and session data.
example_messages = [str(i) for i in range(5)]
set_cookie_data(
cookie_storage, example_messages[:4] + [CookieStorage.not_finished]
)
set_session_data(session_storage, example_messages[4:])
self.assertEqual(list(storage), example_messages)
def test_get_fallback_only(self):
request = self.get_request()
storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage)
session_storage = self.get_session_storage(storage)
# Set initial cookie and session data.
example_messages = [str(i) for i in range(5)]
set_cookie_data(cookie_storage, [CookieStorage.not_finished], encode_empty=True)
set_session_data(session_storage, example_messages)
self.assertEqual(list(storage), example_messages)
def test_flush_used_backends(self):
request = self.get_request()
storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage)
session_storage = self.get_session_storage(storage)
# Set initial cookie and session data.
set_cookie_data(cookie_storage, ["cookie", CookieStorage.not_finished])
set_session_data(session_storage, ["session"])
# When updating, previously used but no longer needed backends are
# flushed.
response = self.get_response()
list(storage)
storage.update(response)
session_storing = self.stored_session_messages_count(storage, response)
self.assertEqual(session_storing, 0)
def test_no_fallback(self):
"""
(1) A short number of messages whose data size doesn't exceed what is
allowed in a cookie will all be stored in the CookieBackend.
(2) If the CookieBackend can store all messages, the SessionBackend
won't be written to at all.
"""
storage = self.get_storage()
response = self.get_response()
# Overwrite the _store method of the fallback storage to prove it isn't
# used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._store = None
for i in range(5):
storage.add(constants.INFO, str(i) * 100)
storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 5)
session_storing = self.stored_session_messages_count(storage, response)
self.assertEqual(session_storing, 0)
def test_session_fallback(self):
"""
If the data exceeds what is allowed in a cookie, messages which did
not fit are stored in the SessionBackend.
"""
storage = self.get_storage()
response = self.get_response()
# see comment in CookieTests.test_cookie_max_length()
msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37)
# Generate the same (tested) content every time that does not get run
# through zlib compression.
random.seed(42)
for i in range(5):
storage.add(constants.INFO, get_random_string(msg_size))
storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 4)
session_storing = self.stored_session_messages_count(storage, response)
self.assertEqual(session_storing, 1)
def test_session_fallback_only(self):
"""
Large messages, none of which fit in a cookie, are stored in the
SessionBackend (and nothing is stored in the CookieBackend).
"""
storage = self.get_storage()
response = self.get_response()
# Generate the same (tested) content every time that does not get run
# through zlib compression.
random.seed(42)
storage.add(constants.INFO, get_random_string(5000))
storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 0)
session_storing = self.stored_session_messages_count(storage, response)
self.assertEqual(session_storing, 1)
| FallbackTests |
python | falconry__falcon | falcon/testing/helpers.py | {
"start": 14218,
"end": 58300
} | class ____:
"""Simulates a WebSocket client for testing a Falcon ASGI app.
This class provides a way to test WebSocket endpoints in a Falcon ASGI app
without having to interact with an actual ASGI server. While it is certainly
important to test against a real server, a number of functional tests can be
satisfied more efficiently and transparently with a simulated connection.
Note:
The ASGIWebSocketSimulator class is not designed to be instantiated
directly; rather it should be obtained via
:meth:`~falcon.testing.ASGIConductor.simulate_ws`.
"""
_DEFAULT_WAIT_READY_TIMEOUT = 5
def __init__(self) -> None:
self.__msgpack = None
self._state = _WebSocketState.CONNECT
self._disconnect_emitted = False
self._close_code: int | None = None
self._close_reason: str | None = None
self._accepted_subprotocol: str | None = None
self._accepted_headers: list[tuple[bytes, bytes]] | None = None
self._collected_server_events: deque[AsgiEvent] = deque()
self._collected_client_events: deque[AsgiEvent] = deque()
self._event_handshake_complete = asyncio.Event()
@property
def ready(self) -> bool:
"""``True`` if the WebSocket connection has been accepted and the client is
still connected, ``False`` otherwise.
""" # noqa: D205
return self._state == _WebSocketState.ACCEPTED
@property
def closed(self) -> bool:
"""``True`` if the WebSocket connection has been denied or closed by the app,
or the client has disconnected.
""" # noqa: D205
return self._state in {_WebSocketState.DENIED, _WebSocketState.CLOSED}
@property
def close_code(self) -> int | None:
"""The WebSocket close code provided by the app if the connection is closed.
Returns ``None`` if the connection is still open.
"""
return self._close_code
@property
def close_reason(self) -> str | None:
"""The WebSocket close reason provided by the app if the connection is closed.
Returns ``None`` if the connection is still open.
"""
return self._close_reason
@property
def subprotocol(self) -> str | None:
"""The subprotocol the app wishes to accept, or ``None`` if not specified."""
return self._accepted_subprotocol
@property
def headers(self) -> list[tuple[bytes, bytes]] | None:
"""An iterable of ``[name, value]`` two-item tuples, where *name* is the
header name, and *value* is the header value for each header returned by
the app when it accepted the WebSocket connection.
This property resolves to ``None`` if the connection has not been accepted.
""" # noqa: D205
return self._accepted_headers
async def wait_ready(self, timeout: int | None = None) -> None:
"""Wait until the connection has been accepted or denied.
This coroutine can be awaited in order to pause execution until the
app has accepted or denied the connection. In the latter case, an
error will be raised to the caller.
Keyword Args:
timeout (int): Number of seconds to wait before giving up and
raising an error (default: ``5``).
"""
timeout = timeout or self._DEFAULT_WAIT_READY_TIMEOUT
try:
await asyncio.wait_for(self._event_handshake_complete.wait(), timeout)
except asyncio.TimeoutError:
msg = (
f'Timed out after waiting {timeout} seconds for the WebSocket '
f'handshake to complete. Check the on_websocket responder and '
f'any middleware for any conditions that may be stalling the '
f'request flow.'
)
raise asyncio.TimeoutError(msg)
self._require_accepted()
# NOTE(kgriffs): This is a coroutine just in case we need it to be
# in a future code revision. It also makes it more consistent
# with the other methods.
async def close(self, code: int | None = None, reason: str | None = None) -> None:
"""Close the simulated connection.
Keyword Args:
code (int): The WebSocket close code to send to the application
per the WebSocket spec (default: ``1000``).
reason (str): The WebSocket close reason to send to the application
per the WebSocket spec (default: empty string).
"""
# NOTE(kgriffs): Give our collector a chance in case the
# server is trying to close at the same time (e.g., there was an
# unhandled error and the server wants to disconnect with an error
# code.) We await a few times to let the server app settle across
# multiple of its own await's.
for __ in range(3):
await asyncio.sleep(0)
if self.closed:
return
assert self._close_code is None
if code is None:
code = WSCloseCode.NORMAL
if reason is None:
reason = ''
self._state = _WebSocketState.CLOSED
self._close_code = code
self._close_reason = reason
async def send_text(self, payload: str) -> None:
"""Send a message to the app with a Unicode string payload.
Arguments:
payload (str): The string to send.
"""
# NOTE(kgriffs): We have to check ourselves because some ASGI
# servers are not very strict which can lead to hard-to-debug
# errors.
if not isinstance(payload, str):
raise TypeError('payload must be a string')
# NOTE(kgriffs): From the client's perspective, it was a send,
# but the server will be expecting websocket.receive
await self._send(text=payload)
async def send_data(self, payload: bytes | bytearray | memoryview) -> None:
"""Send a message to the app with a binary data payload.
Arguments:
payload (Union[bytes, bytearray, memoryview]): The binary data to send.
"""
# NOTE(kgriffs): We have to check ourselves because some ASGI
# servers are not very strict which can lead to hard-to-debug
# errors.
if not isinstance(payload, (bytes, bytearray, memoryview)):
raise TypeError('payload must be a byte string')
# NOTE(kgriffs): From the client's perspective, it was a send,
# but the server will be expecting websocket.receive
await self._send(data=bytes(payload))
async def send_json(self, media: object) -> None:
"""Send a message to the app with a JSON-encoded payload.
Arguments:
media: A JSON-encodable object to send as a TEXT (0x01) payload.
"""
text = json.dumps(media)
await self.send_text(text)
async def send_msgpack(self, media: object) -> None:
"""Send a message to the app with a MessagePack-encoded payload.
Arguments:
media: A MessagePack-encodable object to send as a BINARY (0x02) payload.
"""
data = self._msgpack.packb(media, use_bin_type=True)
await self.send_data(data)
async def receive_text(self) -> str:
"""Receive a message from the app with a Unicode string payload.
Awaiting this coroutine will block until a message is available or
the WebSocket is disconnected.
"""
event = await self._receive()
# PERF(kgriffs): When we normally expect the key to be
# present, this pattern is faster than get()
try:
text = event['text']
except KeyError:
text = None
# NOTE(kgriffs): Even if the key is present, it may be None
if text is None:
raise falcon_errors.PayloadTypeError(
'Expected TEXT payload but got BINARY instead'
)
return text
async def receive_data(self) -> bytes:
"""Receive a message from the app with a binary data payload.
Awaiting this coroutine will block until a message is available or
the WebSocket is disconnected.
"""
event = await self._receive()
# PERF(kgriffs): When we normally expect the key to be
# present, EAFP is faster than get()
try:
data = event['bytes']
except KeyError:
data = None
# NOTE(kgriffs): Even if the key is present, it may be None
if data is None:
raise falcon_errors.PayloadTypeError(
'Expected BINARY payload but got TEXT instead'
)
return data
async def receive_json(self) -> Any:
"""Receive a message from the app with a JSON-encoded TEXT payload.
Awaiting this coroutine will block until a message is available or
the WebSocket is disconnected.
"""
text = await self.receive_text()
return json.loads(text)
async def receive_msgpack(self) -> Any:
"""Receive a message from the app with a MessagePack-encoded BINARY payload.
Awaiting this coroutine will block until a message is available or
the WebSocket is disconnected.
"""
data = await self.receive_data()
return self._msgpack.unpackb(data, use_list=True, raw=False)
@property
def _msgpack(self) -> Any:
# NOTE(kgriffs): A property is used in lieu of referencing
# the msgpack module directly, in order to bubble up the
# import error in an obvious way, when the package has
# not been installed.
if not self.__msgpack:
import msgpack
self.__msgpack = msgpack
return self.__msgpack
def _require_accepted(self) -> None:
if self._state == _WebSocketState.ACCEPTED:
return
if self._state in {_WebSocketState.CONNECT, _WebSocketState.HANDSHAKE}:
raise falcon_errors.OperationNotAllowed(
'WebSocket connection has not yet been accepted'
)
elif self._state == _WebSocketState.CLOSED:
raise falcon_errors.WebSocketDisconnected(self._close_code)
assert self._state == _WebSocketState.DENIED
if self._close_code == WSCloseCode.PATH_NOT_FOUND:
raise falcon_errors.WebSocketPathNotFound(WSCloseCode.PATH_NOT_FOUND)
if self._close_code == WSCloseCode.SERVER_ERROR:
raise falcon_errors.WebSocketServerError(WSCloseCode.SERVER_ERROR)
if self._close_code == WSCloseCode.HANDLER_NOT_FOUND:
raise falcon_errors.WebSocketHandlerNotFound(WSCloseCode.HANDLER_NOT_FOUND)
raise falcon_errors.WebSocketDisconnected(self._close_code)
# NOTE(kgriffs): This is a coroutine just in case we need it to be
# in a future code revision. It also makes it more consistent
# with the other methods.
async def _send(self, data: bytes | None = None, text: str | None = None) -> None:
self._require_accepted()
# NOTE(kgriffs): From the client's perspective, it was a send,
# but the server will be expecting websocket.receive
event: dict[str, Any] = {'type': EventType.WS_RECEIVE}
if data is not None:
event['bytes'] = data
if text is not None:
event['text'] = text
self._collected_client_events.append(event)
# NOTE(kgriffs): If something is waiting to read this data on the
# other side, give it a chance to progress (because we like to party
# like it's 1992.)
await asyncio.sleep(0)
async def _receive(self) -> AsgiEvent:
while not self._collected_server_events:
self._require_accepted()
await asyncio.sleep(0)
self._require_accepted()
return self._collected_server_events.popleft()
async def _emit(self) -> AsgiEvent:
if self._state == _WebSocketState.CONNECT:
self._state = _WebSocketState.HANDSHAKE
return {'type': EventType.WS_CONNECT}
if self._state == _WebSocketState.HANDSHAKE:
# NOTE(kgriffs): We need to wait for the handshake to
# complete, before proceeding.
await self._event_handshake_complete.wait()
while not self._collected_client_events:
await asyncio.sleep(0)
if self.closed:
return self._create_checked_disconnect()
return self._collected_client_events.popleft()
async def _collect(self, event: AsgiEvent) -> None:
assert event
if self._state == _WebSocketState.CONNECT:
raise falcon_errors.OperationNotAllowed(
'An ASGI application must receive the first websocket.connect '
'event before attempting to send any events.'
)
event_type = event['type']
if self._state == _WebSocketState.HANDSHAKE:
if event_type == EventType.WS_ACCEPT:
self._state = _WebSocketState.ACCEPTED
self._accepted_subprotocol = event.get('subprotocol')
self._accepted_headers = event.get('headers')
self._event_handshake_complete.set()
# NOTE(kgriffs): Yield to other pending tasks that may be
# waiting on the completion of the handshake. This ensures
# that the simulated client connection can enter its context
# before the app logic continues and potentially closes the
# connection from that side.
await asyncio.sleep(0)
elif event_type == EventType.WS_CLOSE:
self._state = _WebSocketState.DENIED
desired_code = event.get('code', WSCloseCode.NORMAL)
reason = event.get('reason', '')
if desired_code == WSCloseCode.SERVER_ERROR or (
3000 <= desired_code < 4000
):
# NOTE(kgriffs): Pass this code through since it is a
# special code we have set in the framework to trigger
# different raised error types or to pass through a
# raised HTTPError status code.
self._close_code = desired_code
self._close_reason = reason
else:
# NOTE(kgriffs): Force the close code to this since it is
# similar to what happens with a real web server (the HTTP
# connection is closed with a 403 and there is no websocket
# close code).
self._close_code = WSCloseCode.FORBIDDEN
self._close_reason = code_to_http_status(
WSCloseCode.FORBIDDEN - 3000
)
self._event_handshake_complete.set()
else:
raise falcon_errors.OperationNotAllowed(
'An ASGI application must send either websocket.accept or '
'websocket.close before sending any other event types (got '
'{0})'.format(event_type)
)
elif self._state == _WebSocketState.ACCEPTED:
if event_type == EventType.WS_CLOSE:
self._state = _WebSocketState.CLOSED
self._close_code = event.get('code', WSCloseCode.NORMAL)
self._close_reason = event.get('reason', '')
else:
assert event_type == EventType.WS_SEND
self._collected_server_events.append(event)
else:
assert self.closed
# NOTE(vytas): Tweaked in Falcon 4.0: we now simulate ASGI
# WebSocket protocol 2.4+, raising an instance of OSError upon
# send if the client has already disconnected.
raise falcon_errors.WebSocketDisconnected(self._close_code)
# NOTE(kgriffs): Give whatever is waiting on the handshake or a
# collected data/text event a chance to progress.
await asyncio.sleep(0)
def _create_checked_disconnect(self) -> AsgiEvent:
if self._disconnect_emitted:
raise falcon_errors.OperationNotAllowed(
'The websocket.disconnect event has already been emitted, '
'and so the app should not attempt to receive any more '
'events, since ASGI servers will likely block indefinitely '
'rather than re-emitting websocket.disconnect events.'
)
self._disconnect_emitted = True
response = {'type': EventType.WS_DISCONNECT, 'code': self._close_code}
if self._close_reason:
response['reason'] = self._close_reason
return response
# get_encoding_from_headers() is Copyright 2016 Kenneth Reitz, and is
# used here under the terms of the Apache License, Version 2.0.
def get_encoding_from_headers(headers: Mapping[str, str]) -> str | None:
"""Return encoding from given HTTP Header Dict.
Args:
headers(dict): Dictionary from which to extract encoding. Header
names must either be lowercase or the dict must support
case-insensitive lookups.
"""
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = parse_header(content_type)
if 'charset' in params:
return params['charset'].strip('\'"')
# NOTE(kgriffs): Added checks for text/event-stream and application/json
if content_type in ('text/event-stream', 'application/json'):
return 'UTF-8'
if 'text' in content_type:
return 'ISO-8859-1'
return None
def get_unused_port() -> int:
"""Get an unused localhost port for use by a test server.
Warning:
It is possible for a third party to bind to the returned port
before the caller is able to do so. The caller will need to
retry with a different port in that case.
Warning:
This method has only be tested on POSIX systems and may not
work elsewhere.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 0))
return s.getsockname()[1]
def rand_string(min: int, max: int) -> str:
"""Return a randomly-generated string, of a random length.
Args:
min (int): Minimum string length to return, inclusive
max (int): Maximum string length to return, inclusive
"""
int_gen = random.randint
string_length = int_gen(min, max)
return ''.join([chr(int_gen(ord(' '), ord('~'))) for __ in range(string_length)])
def create_scope(
path: str = '/',
query_string: str = '',
method: str = 'GET',
headers: HeaderArg | None = None,
host: str = DEFAULT_HOST,
scheme: str | None = None,
port: int | None = None,
http_version: str = '1.1',
remote_addr: str | None = None,
root_path: str | None = None,
content_length: int | None = None,
include_server: bool = True,
cookies: CookieArg | None = None,
) -> dict[str, Any]:
"""Create a mock ASGI scope ``dict`` for simulating HTTP requests.
Keyword Args:
path (str): The path for the request (default ``'/'``)
query_string (str): The query string to simulate, without a
leading ``'?'`` (default ``''``). The query string is passed as-is
(it will not be percent-encoded).
method (str): The HTTP method to use (default ``'GET'``)
headers (dict): Headers as a dict-like (Mapping) object, or an
iterable yielding a series of two-member (*name*, *value*)
iterables. Each pair of strings provides the name and value
for an HTTP header. If desired, multiple header values may be
combined into a single (*name*, *value*) pair by joining the values
with a comma when the header in question supports the list
format (see also RFC 7230 and RFC 7231). When the
request will include a body, the Content-Length header should be
included in this list. Header names are not case-sensitive.
Note:
If a User-Agent header is not provided, it will default to::
f'falcon-client/{falcon.__version__}'
host(str): Hostname for the request (default ``'falconframework.org'``).
This also determines the value of the Host header in the
request.
scheme (str): URL scheme, either ``'http'`` or ``'https'``
(default ``'http'``)
port (int): The TCP port to simulate. Defaults to
the standard port used by the given scheme (i.e., 80 for ``'http'``
and 443 for ``'https'``). A string may also be passed, as long as
it can be parsed as an int.
http_version (str): The HTTP version to simulate. Must be either
``'2'``, ``'2.0'``, ``'1.1'``, ``'1.0'``, or ``'1'``
(default ``'1.1'``). If set to ``'1.0'``, the Host header will not
be added to the scope.
remote_addr (str): Remote address for the request to use for
the 'client' field in the connection scope (default None)
root_path (str): The root path this application is mounted at; same as
SCRIPT_NAME in WSGI (default ``''``).
content_length (int): The expected content length of the request
body (default ``None``). If specified, this value will be
used to set the Content-Length header in the request.
include_server (bool): Set to ``False`` to not set the 'server' key
in the scope ``dict`` (default ``True``).
cookies (dict): Cookies as a dict-like (Mapping) object, or an
iterable yielding a series of two-member (*name*, *value*)
iterables. Each pair of items provides the name and value
for the 'Set-Cookie' header.
.. versionadded:: 4.1
The raw (i.e., not URL-decoded) version of the provided `path` is now
preserved in the returned scope as the ``raw_path`` byte string.
According to the ASGI specification, ``raw_path`` **does not include**
any query string.
"""
http_version = _fixup_http_version(http_version)
raw_path, _, _ = path.partition('?')
path = uri.decode(path, unquote_plus=False)
# NOTE(kgriffs): Handles both None and ''
query_string_bytes = query_string.encode() if query_string else b''
if query_string_bytes and query_string_bytes.startswith(b'?'):
raise ValueError("query_string should not start with '?'")
scope: dict[str, Any] = {
'type': ScopeType.HTTP,
'asgi': {
'version': '3.0',
'spec_version': '2.1',
},
'http_version': http_version,
'method': method.upper(),
'path': path,
'raw_path': raw_path.encode(),
'query_string': query_string_bytes,
}
# NOTE(kgriffs): Explicitly test against None so that the caller
# is able to simulate setting app to an empty string if they
# need to cover that branch in their code.
if root_path is not None:
# NOTE(kgriffs): Judging by the algorithm given in PEP-3333 for
# reconstructing the URL, SCRIPT_NAME is expected to contain a
# preceding slash character. Since ASGI states that this value is
# the same as WSGI's SCRIPT_NAME, we will follow suit here.
if root_path and not root_path.startswith('/'):
scope['root_path'] = '/' + root_path
else:
scope['root_path'] = root_path
if scheme:
if scheme not in {'http', 'https', 'ws', 'wss'}:
raise ValueError("scheme must be either 'http', 'https', 'ws', or 'wss'")
scope['scheme'] = scheme
if port is None:
if (scheme or 'http') in {'http', 'ws'}:
port = 80
else:
port = 443
else:
port = int(port)
if remote_addr:
# NOTE(kgriffs): Choose from the standard IANA dynamic range
remote_port = random.randint(49152, 65535)
# NOTE(kgriffs): Expose as an iterable to ensure the framework/app
# isn't hard-coded to only work with a list or tuple.
scope['client'] = iter([remote_addr, remote_port])
if include_server:
scope['server'] = iter([host, port])
# NOTE(myusko): Clients discard Set-Cookie header
# in the response to the OPTIONS method.
if method == 'OPTIONS' and cookies is not None:
cookies = None
_add_headers_to_scope(
scope, headers, content_length, host, port, scheme, http_version, cookies
)
return scope
def create_scope_ws(
path: str = '/',
query_string: str = '',
headers: HeaderArg | None = None,
host: str = DEFAULT_HOST,
scheme: str | None = None,
port: int | None = None,
http_version: str = '1.1',
remote_addr: str | None = None,
root_path: str | None = None,
include_server: bool = True,
subprotocols: str | None = None,
spec_version: str = '2.1',
) -> dict[str, Any]:
"""Create a mock ASGI scope ``dict`` for simulating WebSocket requests.
Keyword Args:
path (str): The path for the request (default ``'/'``)
query_string (str): The query string to simulate, without a
leading ``'?'`` (default ``''``). The query string is passed as-is
(it will not be percent-encoded).
headers (dict): Headers as a dict-like (Mapping) object, or an
iterable yielding a series of two-member (*name*, *value*)
iterables. Each pair of strings provides the name and value
for an HTTP header. If desired, multiple header values may be
combined into a single (*name*, *value*) pair by joining the values
with a comma when the header in question supports the list
format (see also RFC 7230 and RFC 7231). When the
request will include a body, the Content-Length header should be
included in this list. Header names are not case-sensitive.
Note:
If a User-Agent header is not provided, it will default to::
f'falcon-client/{falcon.__version__}'
host(str): Hostname for the request (default ``'falconframework.org'``).
This also determines the value of the Host header in the
request.
scheme (str): URL scheme, either ``'ws'`` or ``'wss'``
(default ``'ws'``)
port (int): The TCP port to simulate. Defaults to
the standard port used by the given scheme (i.e., 80 for ``'ws'``
and 443 for ``'wss'``). A string may also be passed, as long as
it can be parsed as an int.
http_version (str): The HTTP version to simulate. Must be either
``'2'``, ``'2.0'``, or ``'1.1'`` (default ``'1.1'``).
remote_addr (str): Remote address for the request to use for
the 'client' field in the connection scope (default None)
root_path (str): The root path this application is mounted at; same as
SCRIPT_NAME in WSGI (default ``''``).
include_server (bool): Set to ``False`` to not set the 'server' key
in the scope ``dict`` (default ``True``).
spec_version (str): The ASGI spec version to emulate (default ``'2.1'``).
subprotocols (Iterable[str]): Subprotocols the client wishes to
advertise to the server (default ``[]``).
"""
scope = create_scope(
path=path,
query_string=query_string,
headers=headers,
host=host,
scheme=(scheme or 'ws'),
port=port,
http_version=http_version,
remote_addr=remote_addr,
root_path=root_path,
include_server=include_server,
)
scope['type'] = ScopeType.WS
scope['asgi']['spec_version'] = spec_version
del scope['method']
# NOTE(kgriffiths): Explicit check against None affords simulating a request
# with a scope that does not contain the optional 'subprotocols' key.
if subprotocols is not None:
scope['subprotocols'] = subprotocols
return scope
def create_environ(
path: str = '/',
query_string: str = '',
http_version: str = '1.1',
scheme: str = 'http',
host: str = DEFAULT_HOST,
port: int | None = None,
headers: HeaderArg | None = None,
app: str | None = None,
body: str | bytes = b'',
method: str = 'GET',
wsgierrors: TextIO | None = None,
file_wrapper: Callable[..., Any] | None = None,
remote_addr: str | None = None,
root_path: str | None = None,
cookies: CookieArg | None = None,
) -> dict[str, Any]:
"""Create a mock PEP-3333 environ ``dict`` for simulating WSGI requests.
Keyword Args:
path (str): The path for the request (default ``'/'``)
query_string (str): The query string to simulate, without a
leading ``'?'`` (default ``''``). The query string is passed as-is
(it will not be percent-encoded).
http_version (str): The HTTP version to simulate. Must be either
``'2'``, ``'2.0'``, ``'1.1'``, ``'1.0'``, or ``'1'``
(default ``'1.1'``). If set to ``'1.0'``, the Host header will not
be added to the scope.
scheme (str): URL scheme, either ``'http'`` or ``'https'``
(default ``'http'``)
host(str): Hostname for the request (default ``'falconframework.org'``)
port (int): The TCP port to simulate. Defaults to
the standard port used by the given scheme (i.e., 80 for ``'http'``
and 443 for ``'https'``). A string may also be passed, as long as
it can be parsed as an int.
headers (dict): Headers as a dict-like (Mapping) object, or an
iterable yielding a series of two-member (*name*, *value*)
iterables. Each pair of strings provides the name and value
for an HTTP header. If desired, multiple header values may be
combined into a single (*name*, *value*) pair by joining the values
with a comma when the header in question supports the list
format (see also RFC 7230 and RFC 7231). Header names are not
case-sensitive.
Note:
If a User-Agent header is not provided, it will default to::
f'falcon-client/{falcon.__version__}'
root_path (str): Value for the ``SCRIPT_NAME`` environ variable, described in
PEP-3333: 'The initial portion of the request URL's "path" that
corresponds to the application object, so that the application
knows its virtual "location". This may be an empty string, if the
application corresponds to the "root" of the server.' (default ``''``)
app (str): Deprecated alias for `root_path`. If both kwargs are passed,
`root_path` takes precedence.
body (str): The body of the request (default ``''``). The value will be
encoded as UTF-8 in the WSGI environ. Alternatively, a byte string
may be passed, in which case it will be used as-is.
method (str): The HTTP method to use (default ``'GET'``)
wsgierrors (io): The stream to use as *wsgierrors*
(default ``sys.stderr``)
file_wrapper: Callable that returns an iterable, to be used as
the value for *wsgi.file_wrapper* in the environ.
remote_addr (str): Remote address for the request to use as the
``'REMOTE_ADDR'`` environ variable (default ``None``)
cookies (dict): Cookies as a dict-like (Mapping) object, or an
iterable yielding a series of two-member (*name*, *value*)
iterables. Each pair of items provides the name and value
for the Set-Cookie header.
"""
http_version = _fixup_http_version(http_version)
if query_string and query_string.startswith('?'):
raise ValueError("query_string should not start with '?'")
body_bytes = io.BytesIO(body.encode() if isinstance(body, str) else body)
# NOTE(kgriffs): wsgiref, gunicorn, and uWSGI all unescape
# the paths before setting PATH_INFO but preserve raw original
raw_path = path
path = uri.decode(path, unquote_plus=False)
# NOTE(kgriffs): The decoded path may contain UTF-8 characters.
# But according to the WSGI spec, no strings can contain chars
# outside ISO-8859-1. Therefore, to reconcile the URI
# encoding standard that allows UTF-8 with the WSGI spec
# that does not, WSGI servers tunnel the string via
# ISO-8859-1. falcon.testing.create_environ() mimics this
# behavior, e.g.:
#
# tunnelled_path = path.encode('utf-8').decode('iso-8859-1')
#
# falcon.Request does the following to reverse the process:
#
# path = tunnelled_path.encode('iso-8859-1').decode('utf-8', 'replace')
#
path = path.encode().decode('iso-8859-1')
scheme = scheme.lower()
if port is None:
port_str = '80' if scheme == 'http' else '443'
else:
# NOTE(kgriffs): Running it through int() first ensures that if
# a string was passed, it is a valid integer.
port_str = str(int(port))
root_path = root_path or app or ''
# NOTE(kgriffs): Judging by the algorithm given in PEP-3333 for
# reconstructing the URL, SCRIPT_NAME is expected to contain a
# preceding slash character.
if root_path and not root_path.startswith('/'):
root_path = '/' + root_path
env: dict[str, Any] = {
'SERVER_PROTOCOL': 'HTTP/' + http_version,
'SERVER_SOFTWARE': 'gunicorn/0.17.0',
'SCRIPT_NAME': (root_path or ''),
'REQUEST_METHOD': method,
'PATH_INFO': path,
'QUERY_STRING': query_string,
'REMOTE_PORT': '65133',
'RAW_URI': raw_path,
'SERVER_NAME': host,
'SERVER_PORT': port_str,
'wsgi.version': (1, 0),
'wsgi.url_scheme': scheme,
'wsgi.input': body_bytes,
'wsgi.errors': wsgierrors or sys.stderr,
'wsgi.multithread': False,
'wsgi.multiprocess': True,
'wsgi.run_once': False,
}
# NOTE(kgriffs): It has been observed that WSGI servers do not always
# set the REMOTE_ADDR variable, so we don't always set it either, to
# ensure the framework/app handles that case correctly.
if remote_addr:
env['REMOTE_ADDR'] = remote_addr
if file_wrapper is not None:
env['wsgi.file_wrapper'] = file_wrapper
if http_version != '1.0':
host_header = host
if scheme == 'https':
if port_str != '443':
host_header += ':' + port_str
else:
if port_str != '80':
host_header += ':' + port_str
env['HTTP_HOST'] = host_header
content_length = body_bytes.seek(0, 2)
body_bytes.seek(0)
if content_length != 0:
env['CONTENT_LENGTH'] = str(content_length)
# NOTE(myusko): Clients discard Set-Cookie header
# in the response to the OPTIONS method.
if cookies is not None and method != 'OPTIONS':
env['HTTP_COOKIE'] = _make_cookie_values(cookies)
_add_headers_to_environ(env, headers)
return env
def create_req(
options: falcon.request.RequestOptions | None = None, **kwargs: Any
) -> falcon.Request:
"""Create and return a new Request instance.
This function can be used to conveniently create a WSGI environ
and use it to instantiate a :class:`falcon.Request` object in one go.
The arguments for this function are identical to those
of :meth:`falcon.testing.create_environ`, except an additional
`options` keyword argument may be set to an instance of
:class:`falcon.RequestOptions` to configure certain
aspects of request parsing in lieu of the defaults.
"""
env = create_environ(**kwargs)
return falcon.request.Request(env, options=options)
def create_asgi_req(
body: bytes | None = None,
req_type: type[falcon.asgi.Request] | None = None,
options: falcon.request.RequestOptions | None = None,
**kwargs: Any,
) -> falcon.asgi.Request:
"""Create and return a new ASGI Request instance.
This function can be used to conveniently create an ASGI scope
and use it to instantiate a :class:`falcon.asgi.Request` object
in one go.
The arguments for this function are identical to those
of :meth:`falcon.testing.create_scope`, with the addition of
`body`, `req_type`, and `options` arguments as documented below.
Keyword Arguments:
body (bytes): The body data to use for the request (default b''). If
the value is a :class:`str`, it will be UTF-8 encoded to
a byte string.
req_type (object): A subclass of :class:`falcon.asgi.Request`
to instantiate. If not specified, the standard
:class:`falcon.asgi.Request` class will simply be used.
options (falcon.RequestOptions): An instance of
:class:`falcon.RequestOptions` that should be used to determine
certain aspects of request parsing in lieu of the defaults.
"""
scope = create_scope(**kwargs)
body = body or b''
disconnect_at = time.time() + 300
req_event_emitter = ASGIRequestEventEmitter(body, disconnect_at=disconnect_at)
req_type = req_type or falcon.asgi.Request
return req_type(scope, req_event_emitter, options=options)
# NOTE(TudorGR): Deprecated in Falcon 4.3.
# TODO(TudorGR): Remove in Falcon 5.0.
@falcon.util.deprecated(
'This context manager is deprecated and will be removed in Falcon 5.0. '
'Please use contextlib.redirect_stdout and contextlib.redirect_stderr instead.'
)
@contextlib.contextmanager
def redirected(
stdout: TextIO = sys.stdout, stderr: TextIO = sys.stderr
) -> Iterator[None]:
"""Redirect stdout or stderr temporarily.
For instance, this helper can be used to capture output from Falcon
reources under tests::
import io
import falcon
import falcon.testing
class MediaPrinter:
def on_post(self, req, resp):
print(req.get_media())
client = falcon.testing.TestClient(falcon.App())
client.app.add_route('/print', MediaPrinter())
output = io.StringIO()
with falcon.testing.redirected(stdout=output):
client.simulate_post('/print', json={'message': 'Hello'})
assert output.getvalue() == "{'message': 'Hello'}\\n"
Tip:
The popular `pytest <https://docs.pytest.org/>`__ also captures
and suppresses output from successful tests by default.
.. deprecated:: 4.3
Use the stlib's :func:`contextlib.redirect_stdout` and
:func:`contextlib.redirect_stderr` instead.
"""
old_stdout, old_stderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = stdout, stderr
try:
yield
finally:
sys.stderr, sys.stdout = old_stderr, old_stdout
def closed_wsgi_iterable(iterable: Iterable[bytes]) -> Iterable[bytes]:
"""Wrap an iterable to ensure its ``close()`` method is called.
Wraps the given `iterable` in an iterator utilizing a ``for`` loop as
illustrated in
`the PEP-3333 server/gateway side example
<https://www.python.org/dev/peps/pep-3333/#the-server-gateway-side>`_.
Finally, if the iterable has a ``close()`` method, it is called upon
exception or exhausting iteration.
Furthermore, the first bytestring yielded from iteration, if any, is
prefetched before returning the wrapped iterator in order to ensure the
WSGI ``start_response`` function is called even if the WSGI application is
a generator.
Args:
iterable (iterable): An iterable that yields zero or more
bytestrings, per PEP-3333
Returns:
iterator: An iterator yielding the same bytestrings as `iterable`
"""
def wrapper() -> Iterator[bytes]:
try:
yield from iterable
finally:
if hasattr(iterable, 'close'):
iterable.close()
wrapped = wrapper()
head: tuple[bytes, ...]
try:
head = (next(wrapped),)
except StopIteration:
head = ()
return itertools.chain(head, wrapped)
# ---------------------------------------------------------------------
# Private
# ---------------------------------------------------------------------
def _add_headers_to_environ(env: dict[str, Any], headers: HeaderArg | None) -> None:
if headers:
try:
items = headers.items() # type: ignore[union-attr]
except AttributeError:
items = headers
for name, value in items:
name_wsgi = name.upper().replace('-', '_')
if name_wsgi not in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
name_wsgi = 'HTTP_' + name_wsgi
if value is None:
value = ''
else:
value = value.strip()
if name_wsgi not in env or name.lower() in SINGLETON_HEADERS:
env[name_wsgi] = value
else:
env[name_wsgi] += ',' + value
env.setdefault('HTTP_USER_AGENT', DEFAULT_UA)
def _add_headers_to_scope(
scope: dict[str, Any],
headers: HeaderArg | None,
content_length: int | None,
host: str,
port: int,
scheme: str | None,
http_version: str,
cookies: CookieArg | None,
) -> None:
found_ua = False
prepared_headers: list[Iterable[bytes]] = []
if headers:
try:
items = headers.items() # type: ignore[union-attr]
except AttributeError:
items = headers
for name, value in items:
n = name.lower().encode('latin1')
found_ua = found_ua or (n == b'user-agent')
# NOTE(kgriffs): Value is stripped if not empty, otherwise defaults
# to b'' to be consistent with _add_headers_to_environ().
v = b'' if value is None else value.strip().encode('latin1')
# NOTE(kgriffs): Expose as an iterable to ensure the framework/app
# isn't hard-coded to only work with a list or tuple.
prepared_headers.append(iter([n, v]))
if not found_ua:
prepared_headers.append([b'user-agent', DEFAULT_UA.encode()])
if content_length is not None:
value = str(content_length).encode()
prepared_headers.append((b'content-length', value))
if http_version != '1.0':
host_header = host
if scheme == 'https':
if port != 443:
host_header += ':' + str(port)
else:
if port != 80:
host_header += ':' + str(port)
prepared_headers.append([b'host', host_header.encode()])
if cookies is not None:
prepared_headers.append([b'cookie', _make_cookie_values(cookies).encode()])
# NOTE(kgriffs): Make it an iterator to ensure the app is not expecting
# a specific type (ASGI only specified that it is an iterable).
scope['headers'] = iter(prepared_headers)
def _fixup_http_version(http_version: str) -> str:
if http_version not in ('2', '2.0', '1.1', '1.0', '1'):
raise ValueError('Invalid http_version specified: ' + http_version)
# NOTE(kgrifs): Normalize so that they conform to the standard
# protocol names with prefixed with "HTTP/"
if http_version == '2.0':
http_version = '2'
elif http_version == '1':
http_version = '1.0'
return http_version
def _make_cookie_values(cookies: CookieArg) -> str:
return '; '.join(
[
'{}={}'.format(key, cookie.value if hasattr(cookie, 'value') else cookie)
for key, cookie in cookies.items()
]
)
| ASGIWebSocketSimulator |
python | google__jax | jax/_src/pallas/core.py | {
"start": 10556,
"end": 13044
} | class ____:
"""Allows to specify a bounded slice of a dimension.
Specifically, the index_map need to return a `pl.Slice/pl.ds` for this
dimension. The start and size may be dynamic, as long as the size <=
block_size.
"""
block_size: int
def __repr__(self):
return f"BoundedSlice({self.block_size})"
BlockDim: TypeAlias = Element | Squeezed | Blocked | BoundedSlice
def default_index_map(ndim: int) -> Callable:
return lambda *args: (0,) * ndim
def _canonicalize_block_dim(dim: BlockDim | int | None) -> BlockDim:
match dim:
case None:
return squeezed
case int():
return Blocked(int(dim))
case Squeezed() | Blocked() | Element() | BoundedSlice():
return dim
case _:
# Handle case where the dim is a symbolic dimension so we assume it is
# Blocked.
if jax_core.is_symbolic_dim(dim):
return Blocked(dim)
try:
return Blocked(int(dim))
except Exception as e:
raise ValueError(
f"Unsupported block dimension type: {type(dim)}. Allowed types:"
" `pl.Squeezed`, `pl.Blocked`, `pl.Element`, `int`, `None`."
) from e
def _canonicalize_block_shape(block_shape: Sequence[BlockDim | int | None]
) -> tuple[BlockDim, ...]:
return tuple(_canonicalize_block_dim(dim) for dim in block_shape)
def _get_block_dim_size(dim: BlockDim) -> int:
match dim:
case Squeezed():
return 1
case Blocked(block_size):
return block_size
case Element():
return dim.block_size
case BoundedSlice(block_size):
return block_size
case _:
raise ValueError(f"Unsupported block shape type: {type(dim)}")
def get_block_size(dim: BlockDim | int | None) -> int:
match dim:
case int():
return dim
case Squeezed() | None:
return 1
case (
Blocked(block_size) | Element(block_size, _) | BoundedSlice(block_size)
):
return block_size
case _:
raise ValueError(f"Unsupported block shape type: {type(dim)}")
def _get_block_shape(block_shape: tuple[BlockDim, ...]) -> tuple[int, ...]:
return tuple(_get_block_dim_size(dim) for dim in block_shape)
def _get_ref_block_shape(block_shape: tuple[BlockDim, ...]) -> tuple[int, ...]:
# Special handling for squeezed here (don't include Squeezed dims in the Ref
# shape).
return tuple(
_get_block_dim_size(dim)
for dim in block_shape
if not isinstance(dim, Squeezed)
)
| BoundedSlice |
python | PyCQA__pylint | pylint/pyreverse/main.py | {
"start": 9855,
"end": 11732
} | class ____(_ArgumentsManager, _ArgumentsProvider):
options = OPTIONS
name = "pyreverse"
def __init__(self, args: Sequence[str]) -> None:
# Immediately exit if user asks for version
if "--version" in args:
print("pyreverse is included in pylint:")
print(constants.full_version)
sys.exit(0)
_ArgumentsManager.__init__(self, prog="pyreverse", description=__doc__)
_ArgumentsProvider.__init__(self, self)
# Parse options
insert_default_options()
self.args = self._parse_command_line_configuration(args)
if self.config.output_format not in DIRECTLY_SUPPORTED_FORMATS:
check_graphviz_availability()
print(
f"Format {self.config.output_format} is not supported natively."
" Pyreverse will try to generate it using Graphviz..."
)
check_if_graphviz_supports_format(self.config.output_format)
def run(self) -> int:
"""Checking arguments and run project."""
if not self.args:
print(self.help())
return 1
extra_packages_paths = list(
{discover_package_path(arg, self.config.source_roots) for arg in self.args}
)
with augmented_sys_path(extra_packages_paths):
project = project_from_files(
self.args,
project_name=self.config.project,
black_list=self.config.ignore_list,
verbose=self.config.verbose,
)
linker = Linker(project, tag=True)
handler = DiadefsHandler(self.config, self.args)
diadefs = handler.get_diadefs(project, linker)
writer.DiagramWriter(self.config).write(diadefs)
return 0
if __name__ == "__main__":
arguments = sys.argv[1:]
Run(arguments).run()
| Run |
python | tiangolo__fastapi | docs_src/response_model/tutorial006_py310.py | {
"start": 78,
"end": 816
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float = 10.5
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz",
"description": "There goes my baz",
"price": 50.2,
"tax": 10.5,
},
}
@app.get(
"/items/{item_id}/name",
response_model=Item,
response_model_include=["name", "description"],
)
async def read_item_name(item_id: str):
return items[item_id]
@app.get("/items/{item_id}/public", response_model=Item, response_model_exclude=["tax"])
async def read_item_public_data(item_id: str):
return items[item_id]
| Item |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type_test.py | {
"start": 5901,
"end": 6075
} | class ____(extension_type.ExtensionType):
x: tensor.Tensor = 5
y: tensor.Tensor = ['a', 'b', 'c']
@test_util.run_all_in_graph_and_eager_modes
| ExtensionTypeWithTensorDefault |
python | huggingface__transformers | tests/models/bit/test_modeling_bit.py | {
"start": 9358,
"end": 10331
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return BitImageProcessor.from_pretrained("google/bit-50") if is_vision_available() else None
@slow
def test_inference_image_classification_head(self):
model = BitForImageClassification.from_pretrained("google/bit-50").to(torch_device)
image_processor = self.default_image_processor
image = prepare_img()
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
# verify the logits
expected_shape = torch.Size((1, 1000))
self.assertEqual(outputs.logits.shape, expected_shape)
expected_slice = torch.tensor([[-0.6526, -0.5263, -1.4398]]).to(torch_device)
torch.testing.assert_close(outputs.logits[0, :3], expected_slice, rtol=1e-4, atol=1e-4)
@require_torch
| BitModelIntegrationTest |
python | tox-dev__tox | src/tox/config/types.py | {
"start": 220,
"end": 295
} | class ____(ValueError):
"""circular chain in config"""
| CircularChainError |
python | spyder-ide__spyder | spyder/widgets/tabs.py | {
"start": 15197,
"end": 22798
} | class ____(QTabWidget):
"""TabWidget with context menu and corner widgets"""
sig_close_tab = Signal(int)
def __init__(self, parent, actions=None, menu=None,
corner_widgets=None, menu_use_tooltips=False):
QTabWidget.__init__(self, parent)
self.setTabBar(TabBar(self, parent))
# Needed to prevent eliding tabs text on MacOS
# See spyder-ide/spyder#18817
self.setElideMode(Qt.ElideNone)
self.tabBar().setObjectName('pane-tabbar')
self.corner_widgets = {}
self.menu_use_tooltips = menu_use_tooltips
if menu is None:
self.menu = SpyderMenu(self)
if actions:
add_actions(self.menu, actions)
else:
self.menu = menu
self.setStyleSheet(str(PANES_TABBAR_STYLESHEET))
# Corner widgets
if corner_widgets is None:
corner_widgets = {}
corner_widgets.setdefault(Qt.TopLeftCorner, [])
corner_widgets.setdefault(Qt.TopRightCorner, [])
self.browse_button = create_toolbutton(
self, icon=ima.icon('browse_tab'), tip=_("Browse tabs"))
self.browse_button.setStyleSheet(str(PANES_TABBAR_STYLESHEET))
self.browse_tabs_menu = SpyderMenu(self)
self.browse_button.setMenu(self.browse_tabs_menu)
self.browse_button.setPopupMode(QToolButton.InstantPopup)
self.browse_tabs_menu.aboutToShow.connect(self.update_browse_tabs_menu)
corner_widgets[Qt.TopLeftCorner] += [self.browse_button]
self.set_corner_widgets(corner_widgets)
def update_browse_tabs_menu(self):
"""Update browse tabs menu"""
self.browse_tabs_menu.clear()
names = []
dirnames = []
for index in range(self.count()):
if self.menu_use_tooltips:
text = str(self.tabToolTip(index))
else:
text = str(self.tabText(index))
names.append(text)
if osp.isfile(text):
# Testing if tab names are filenames
dirnames.append(osp.dirname(text))
offset = None
# If tab names are all filenames, removing common path:
if len(names) == len(dirnames):
common = get_common_path(dirnames)
if common is None:
offset = None
else:
offset = len(common)+1
if offset <= 3:
# Common path is not a path but a drive letter...
offset = None
for index, text in enumerate(names):
tab_action = create_action(self, text[offset:],
icon=self.tabIcon(index),
toggled=lambda state, index=index:
self.setCurrentIndex(index),
tip=self.tabToolTip(index))
tab_action.setChecked(index == self.currentIndex())
self.browse_tabs_menu.addAction(tab_action)
def set_corner_widgets(self, corner_widgets):
"""
Set tabs corner widgets
corner_widgets: dictionary of (corner, widgets)
corner: Qt.TopLeftCorner or Qt.TopRightCorner
widgets: list of widgets (may contains integers to add spacings)
"""
assert isinstance(corner_widgets, dict)
assert all(key in (Qt.TopLeftCorner, Qt.TopRightCorner)
for key in corner_widgets)
self.corner_widgets.update(corner_widgets)
for corner, widgets in list(self.corner_widgets.items()):
cwidget = QWidget()
cwidget.hide()
# This removes some white dots in our tabs (not all but most).
# See spyder-ide/spyder#15081
cwidget.setObjectName('corner-widget')
cwidget.setStyleSheet(
"QWidget#corner-widget {border-radius: '0px'}")
prev_widget = self.cornerWidget(corner)
if prev_widget:
prev_widget.close()
self.setCornerWidget(cwidget, corner)
clayout = QHBoxLayout()
clayout.setContentsMargins(0, 0, 0, 0)
for widget in widgets:
if isinstance(widget, int):
clayout.addSpacing(widget)
else:
clayout.addWidget(widget)
cwidget.setLayout(clayout)
cwidget.show()
def add_corner_widgets(self, widgets, corner=Qt.TopRightCorner):
self.set_corner_widgets({corner:
self.corner_widgets.get(corner, [])+widgets})
def get_offset_pos(self, event):
"""
Add offset to position event to capture the mouse cursor
inside a tab.
"""
# This is necessary because event.pos() is the position in this
# widget, not in the tabBar. see spyder-ide/spyder#12617
tb = self.tabBar()
point = tb.mapFromGlobal(event.globalPos())
return tb.tabAt(point)
def contextMenuEvent(self, event):
"""Override Qt method"""
index = self.get_offset_pos(event)
self.setCurrentIndex(index)
if self.menu:
self.menu.popup(event.globalPos())
def mousePressEvent(self, event):
"""Override Qt method"""
if event.button() == Qt.MidButton:
index = self.get_offset_pos(event)
if index >= 0:
self.sig_close_tab.emit(index)
event.accept()
return
QTabWidget.mousePressEvent(self, event)
def keyPressEvent(self, event):
"""Override Qt method"""
ctrl = event.modifiers() & Qt.ControlModifier
key = event.key()
handled = False
if ctrl and self.count() > 0:
index = self.currentIndex()
if key == Qt.Key_PageUp or key == Qt.Key_8:
if index > 0:
self.setCurrentIndex(index - 1)
else:
self.setCurrentIndex(self.count() - 1)
handled = True
elif key == Qt.Key_PageDown or key == Qt.Key_9:
if index < self.count() - 1:
self.setCurrentIndex(index + 1)
else:
self.setCurrentIndex(0)
handled = True
if not handled:
QTabWidget.keyPressEvent(self, event)
def tab_navigate(self, delta=1):
"""Ctrl+Tab"""
if delta > 0 and self.currentIndex() == self.count()-1:
index = delta-1
elif delta < 0 and self.currentIndex() == 0:
index = self.count()+delta
else:
index = self.currentIndex()+delta
self.setCurrentIndex(index)
def set_close_function(self, func):
"""Setting Tabs close function
None -> tabs are not closable"""
state = func is not None
if state:
self.sig_close_tab.connect(func)
try:
# Assuming Qt >= 4.5
QTabWidget.setTabsClosable(self, state)
self.tabCloseRequested.connect(func)
except AttributeError:
# Workaround for Qt < 4.5
close_button = create_toolbutton(self, triggered=func,
icon=ima.icon('fileclose'),
tip=_("Close current tab"))
self.setCornerWidget(close_button if state else None)
def refresh_style(self):
"""Refresh the widget style."""
self.tabBar().refresh_style()
| BaseTabs |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_retrieve_event_param.py | {
"start": 234,
"end": 579
} | class ____(TypedDict, total=False):
item_id: Required[str]
"""The ID of the item to retrieve."""
type: Required[Literal["conversation.item.retrieve"]]
"""The event type, must be `conversation.item.retrieve`."""
event_id: str
"""Optional client-generated ID used to identify this event."""
| ConversationItemRetrieveEventParam |
python | readthedocs__readthedocs.org | readthedocs/proxito/views/serve.py | {
"start": 15662,
"end": 25720
} | class ____(CDNCacheControlMixin, ServeRedirectMixin, ServeDocsMixin, View):
"""
Proxito handler for 404 pages.
This view is called by an internal nginx redirect when there is a 404.
"""
def get(self, request, proxito_path):
"""
Handler for 404 pages on subdomains.
This does a couple of things:
* Handles directory indexing for URLs that don't end in a slash
* Check for user redirects
* Record the broken link for analytics
* Handles custom 404 serving
For 404's, first search for a 404 page in the current version, then continues
with the default version and finally, if none of them are found, the Read
the Docs default page (Maze Found) is rendered by Django and served.
"""
structlog.contextvars.bind_contextvars(proxito_path=proxito_path)
log.debug("Executing 404 handler.")
unresolved_domain = request.unresolved_domain
# We force all storage calls to use the external versions storage,
# since we are serving an external version.
# The version that results from the unresolve_path() call already is
# validated to use the correct manager, this is here to add defense in
# depth against serving the wrong version.
if unresolved_domain.is_from_external_domain:
self.version_type = EXTERNAL
project = None
version = None
# If we weren't able to resolve a filename,
# then the path is the filename.
filename = proxito_path
lang_slug = None
version_slug = None
# Try to map the current path to a project/version/filename.
# If that fails, we fill the variables with the information we have
# available in the exceptions.
contextualized_404_class = ContextualizedHttp404
try:
unresolved = unresolver.unresolve_path(
unresolved_domain=unresolved_domain,
path=proxito_path,
append_indexhtml=False,
)
# Inject the UnresolvedURL into the HttpRequest so we can access from the middleware.
# We could resolve it again from the middleware, but we would duplicating DB queries.
request.unresolved_url = unresolved
project = unresolved.project
version = unresolved.version
filename = unresolved.filename
lang_slug = project.language
version_slug = version.slug
contextualized_404_class = ProjectFilenameHttp404
except VersionNotFoundError as exc:
project = exc.project
lang_slug = project.language
version_slug = exc.version_slug
filename = exc.filename
contextualized_404_class = ProjectVersionHttp404
except TranslationNotFoundError as exc:
project = exc.project
lang_slug = exc.language
version_slug = exc.version_slug
filename = exc.filename
contextualized_404_class = ProjectTranslationHttp404
except TranslationWithoutVersionError as exc:
project = exc.project
lang_slug = exc.language
# TODO: Use a contextualized 404
except InvalidExternalVersionError as exc:
project = exc.project
# TODO: Use a contextualized 404
except InvalidPathForVersionedProjectError as exc:
project = exc.project
filename = exc.path
# TODO: Use a contextualized 404
structlog.contextvars.bind_contextvars(
project_slug=project.slug,
version_slug=version_slug,
)
# TODO: find a better way to pass this to the middleware.
request.path_project_slug = project.slug
request.path_version_slug = version_slug
# If we were able to resolve to a valid version, it means that the
# current file doesn't exist. So we check if we can redirect to its
# index file if it exists before doing anything else.
# If the version isn't marked as built, we don't check for index files,
# since the version doesn't have any files.
# This is /en/latest/foo -> /en/latest/foo/index.html.
if version and version.built:
response = self._get_index_file_redirect(
request=request,
project=project,
version=version,
filename=filename,
full_path=proxito_path,
)
if response:
return response
# Check and perform redirects on 404 handler for non-external domains only.
# NOTE: This redirect check must be done after trying files like
# ``index.html`` to emulate the behavior we had when
# serving directly from NGINX without passing through Python.
if not unresolved_domain.is_from_external_domain:
try:
redirect_response = self.get_redirect_response(
request=request,
project=project,
language=lang_slug,
version_slug=version_slug,
filename=filename,
path=proxito_path,
)
if redirect_response:
return redirect_response
except InfiniteRedirectException:
# ``get_redirect_response`` raises this when it's redirecting back to itself.
# We can safely ignore it here because it's logged in ``canonical_redirect``,
# and we don't want to issue infinite redirects.
pass
response = self._get_custom_404_page(
request=request,
project=project,
version=version,
)
if response:
return response
# Don't use the custom 404 page, use our general contextualized 404 response
# Several additional context variables can be added if the templates
# or other error handling is developed (version, language, filename).
raise contextualized_404_class(
project=project,
path_not_found=proxito_path,
)
def _get_custom_404_page(self, request, project, version=None):
"""
Try to serve a custom 404 page from this project.
If a version is given, try to serve the 404 page from that version first,
if it doesn't exist, try to serve the 404 page from the default version.
We check for a 404.html or 404/index.html file.
We don't check for a custom 404 page in versions that aren't marked as built,
since they don't have any files.
If a 404 page is found, we return a response with the content of that file,
`None` otherwise.
"""
versions_404 = [version] if version and version.built else []
if not version or version.slug != project.default_version:
default_version = project.versions.filter(slug=project.default_version).first()
if default_version and default_version.built:
versions_404.append(default_version)
if not versions_404:
return None
tryfiles = ["404.html", "404/index.html"]
available_404_files = list(
HTMLFile.objects.filter(version__in=versions_404, path__in=tryfiles).values_list(
"version__slug", "path"
)
)
if not available_404_files:
return None
for version_404 in versions_404:
if not self.allowed_user(request, version_404):
continue
for tryfile in tryfiles:
if (version_404.slug, tryfile) not in available_404_files:
continue
storage_root_path = project.get_storage_path(
type_="html",
version_slug=version_404.slug,
include_file=False,
version_type=self.version_type,
)
storage_filename_path = build_media_storage.join(storage_root_path, tryfile)
log.debug(
"Serving custom 404.html page.",
version_slug_404=version_404.slug,
storage_filename_path=storage_filename_path,
)
try:
content = build_media_storage.open(storage_filename_path).read()
return HttpResponse(content, status=404)
except FileNotFoundError:
log.warning(
"File not found in storage. File out of sync with DB.",
file=storage_filename_path,
)
return None
return None
def _get_index_file_redirect(self, request, project, version, filename, full_path):
"""
Check if a file is a directory and redirect to its index file.
For example:
- /en/latest/foo -> /en/latest/foo/index.html
"""
# If the path ends with `/`, we already tried to serve
# the `/index.html` file.
if full_path.endswith("/"):
return None
tryfile = (filename.rstrip("/") + "/index.html").lstrip("/")
if not HTMLFile.objects.filter(version=version, path=tryfile).exists():
return None
log.info("Redirecting to index file.", tryfile=tryfile)
# Use urlparse so that we maintain GET args in our redirect
parts = urlparse(full_path)
new_path = parts.path.rstrip("/") + "/"
# `full_path` doesn't include query params.`
query = urlparse(request.get_full_path()).query
redirect_url = parts._replace(
path=new_path,
query=query,
).geturl()
# TODO: decide if we need to check for infinite redirect here
# (from URL == to URL)
return HttpResponseRedirect(redirect_url)
| ServeError404Base |
python | celery__celery | t/unit/tasks/test_tasks.py | {
"start": 814,
"end": 997
} | class ____(Task):
abstract = True
applied = 0
def run(self, x, y):
return x * y
def apply_async(self, *args, **kwargs):
self.applied += 1
| MockApplyTask |
python | has2k1__plotnine | plotnine/scales/scale_shape.py | {
"start": 1045,
"end": 1512
} | class ____(scale_discrete):
"""
Scale for shapes
"""
_aesthetics = ["shape"]
unfilled: InitVar[bool] = False
"""
If `True`, then all shapes will have no interiors
that can be a filled.
"""
def __post_init__(self, unfilled):
from mizani.palettes import manual_pal
super().__post_init__()
_shapes = unfilled_shapes if unfilled else shapes
self.palette = manual_pal(_shapes)
@dataclass
| scale_shape |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 7008,
"end": 7823
} | class ____(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5]):
def __init__(self, function: Callable[[T0, T1, T2, T3, T4, T5], R]) -> None:
pass
def remote(
self,
__arg0: "Union[T0, ObjectRef[T0]]",
__arg1: "Union[T1, ObjectRef[T1]]",
__arg2: "Union[T2, ObjectRef[T2]]",
__arg3: "Union[T3, ObjectRef[T3]]",
__arg4: "Union[T4, ObjectRef[T4]]",
__arg5: "Union[T5, ObjectRef[T5]]",
) -> "ObjectRef[R]":
...
def bind(
self,
__arg0: "Union[T0, DAGNode[T0]]",
__arg1: "Union[T1, DAGNode[T1]]",
__arg2: "Union[T2, DAGNode[T2]]",
__arg3: "Union[T3, DAGNode[T3]]",
__arg4: "Union[T4, DAGNode[T4]]",
__arg5: "Union[T5, DAGNode[T5]]",
) -> "DAGNode[R]":
...
| RemoteFunction5 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py | {
"start": 827,
"end": 1756
} | class ____(PGDialect_psycopg2):
driver = "psycopg2cffi"
supports_unicode_statements = True
supports_statement_cache = True
# psycopg2cffi's first release is 2.5.0, but reports
# __version__ as 2.4.4. Subsequent releases seem to have
# fixed this.
FEATURE_VERSION_MAP = dict(
native_json=(2, 4, 4),
native_jsonb=(2, 7, 1),
sane_multi_rowcount=(2, 4, 4),
array_oid=(2, 4, 4),
hstore_adapter=(2, 4, 4),
)
@classmethod
def import_dbapi(cls):
return __import__("psycopg2cffi")
@util.memoized_property
def _psycopg2_extensions(cls):
root = __import__("psycopg2cffi", fromlist=["extensions"])
return root.extensions
@util.memoized_property
def _psycopg2_extras(cls):
root = __import__("psycopg2cffi", fromlist=["extras"])
return root.extras
dialect = PGDialect_psycopg2cffi
| PGDialect_psycopg2cffi |
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 3209,
"end": 3379
} | class ____(_SimpleAutomotiveTestMixin):
"""Test el_GR automotive provider methods"""
license_plate_pattern = re.compile(r"^(?P<prefix>[A-Z]{2,3}) \d{4}$")
| TestElGr |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-cart/source_cart/source.py | {
"start": 1286,
"end": 3116
} | class ____(AbstractHeaderAuthenticator):
def __init__(self, user_name, user_secret, site_id):
self.auth_method = AuthMethod.CENTRAL_API_ROUTER
self.user_name = user_name
self.user_secret = user_secret
self.site_id = site_id
def get_auth_header(self) -> Mapping[str, Any]:
"""
This method is not implemented here because for the Central API Router
needs to build the header for each request based
on path + parameters (next token, pagination, page size)
To solve this the logic was moved to `request_headers` in CartStream class.
"""
return {}
def url_base(self) -> str:
return "https://public.americommerce.com/api/v1/"
def extra_params(self, stream, params):
return self.generate_auth_signature(stream, params)
def generate_auth_signature(self, stream, params) -> Mapping[str, Any]:
"""
How to build signature:
1. build a string concatenated with:
request method (uppercase) & request path and query & provisioning user name
example: GET&/api/v1/customers&myUser
2. Generate HMACSHA256 hash using this string as the input, and the provisioning user secret as the key
3. Base64 this hash to be used as the final value in the header
"""
path_with_params = f"/api/v1/{stream.path()}?{urllib.parse.urlencode(params)}"
msg = codecs.encode(f"GET&{path_with_params}&{self.user_name}")
key = codecs.encode(self.user_secret)
dig = hmac.new(key=key, msg=msg, digestmod=hashlib.sha256).digest()
auth_signature = base64.b64encode(dig).decode()
return {"X-AC-PUB-Site-ID": self.site_id, "X-AC-PUB-User": self.user_name, "X-AC-PUB-Auth-Signature": auth_signature}
| CentralAPIHeaderAuthenticator |
python | great-expectations__great_expectations | great_expectations/checkpoint/actions.py | {
"start": 9831,
"end": 10452
} | class ____(ValidationAction):
def _build_data_docs(
self,
site_names: list[str] | None = None,
resource_identifiers: list | None = None,
) -> dict:
return project_manager.build_data_docs(
site_names=site_names, resource_identifiers=resource_identifiers
)
def _get_docs_sites_urls(
self,
site_names: list[str] | None = None,
resource_identifier: Any | None = None,
):
return project_manager.get_docs_sites_urls(
site_names=site_names, resource_identifier=resource_identifier
)
@public_api
| DataDocsAction |
python | huggingface__transformers | tests/models/gemma3n/test_modeling_gemma3n.py | {
"start": 9594,
"end": 12394
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = Gemma3nTextModel
causal_lm_class = Gemma3nForCausalLM
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=False,
use_labels=True,
vocab_size=99,
vocab_size_per_layer_input=99,
hidden_size=16,
hidden_size_per_layer_input=16,
num_hidden_layers=4, # override to correctly test sharing cache pattern
num_kv_shared_layers=2, # important to override
layer_types=[
"full_attention",
"sliding_attention",
"full_attention",
"sliding_attention",
], # similarly we want to test sharing on both types
num_attention_heads=2,
num_key_value_heads=2,
altup_num_inputs=2,
intermediate_size=21,
hidden_activation="gelu_pytorch_tanh",
max_position_embeddings=512,
type_vocab_size=16,
type_sequence_label_size=2,
initializer_range=0.02,
num_labels=3,
num_choices=4,
pad_token_id=0,
bos_token_id=1,
eos_token_id=2,
is_decoder=False,
):
self._verify_and_infer_model_attributes()
self.parent = parent
self.batch_size = batch_size
self.seq_length = seq_length
self.is_training = is_training
self.use_input_mask = use_input_mask
self.use_token_type_ids = use_token_type_ids
self.use_labels = use_labels
self.vocab_size = vocab_size
self.vocab_size_per_layer_input = vocab_size_per_layer_input
self.hidden_size = hidden_size
self.hidden_size_per_layer_input = hidden_size_per_layer_input
self.num_hidden_layers = num_hidden_layers
self.num_kv_shared_layers = num_kv_shared_layers
self.layer_types = layer_types
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.altup_num_inputs = altup_num_inputs
self.intermediate_size = intermediate_size
self.hidden_activation = hidden_activation
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.type_sequence_label_size = type_sequence_label_size
self.initializer_range = initializer_range
self.num_labels = num_labels
self.num_choices = num_choices
self.pad_token_id = pad_token_id
self.bos_token_id = bos_token_id
self.eos_token_id = eos_token_id
self.head_dim = self.hidden_size // self.num_attention_heads
self.is_decoder = is_decoder
@require_torch
| Gemma3nTextModelTester |
python | sqlalchemy__sqlalchemy | examples/versioned_rows/versioned_rows_w_versionid.py | {
"start": 2717,
"end": 3263
} | class ____(Versioned, Base):
__tablename__ = "example"
data = Column(String)
Base.metadata.create_all(engine)
session = Session()
e1 = Example(id=1, data="e1")
session.add(e1)
session.commit()
e1.data = "e2"
session.commit()
assert session.query(
Example.id,
Example.version_id,
Example.is_current_version,
Example.calc_is_current_version,
Example.data,
).order_by(Example.id, Example.version_id).all() == (
[(1, 1, False, False, "e1"), (1, 2, True, True, "e2")]
)
# example 2, versioning with a parent
| Example |
python | pytorch__pytorch | torch/_inductor/codegen/triton.py | {
"start": 70815,
"end": 71006
} | class ____:
config: dict[str, int]
def __getitem__(self, item):
return self.config[item]
def __contains__(self, item):
return item in self.config
| FixedTritonConfig |
python | django__django | tests/gis_tests/test_geoforms.py | {
"start": 18299,
"end": 21048
} | class ____(SimpleTestCase):
def test_get_context_attrs(self):
# The Widget.get_context() attrs argument overrides self.attrs.
widget = BaseGeometryWidget(attrs={"geom_type": "POINT"})
context = widget.get_context("point", None, attrs={"geom_type": "POINT2"})
self.assertEqual(context["widget"]["attrs"]["geom_type"], "POINT2")
# Widget.get_context() returns expected name for geom_type.
widget = BaseGeometryWidget(attrs={"geom_type": "POLYGON"})
context = widget.get_context("polygon", None, None)
self.assertEqual(context["widget"]["attrs"]["geom_name"], "Polygon")
# Widget.get_context() returns 'Geometry' instead of 'Unknown'.
widget = BaseGeometryWidget(attrs={"geom_type": "GEOMETRY"})
context = widget.get_context("geometry", None, None)
self.assertEqual(context["widget"]["attrs"]["geom_name"], "Geometry")
def test_subwidgets(self):
widget = forms.BaseGeometryWidget()
self.assertEqual(
list(widget.subwidgets("name", "value")),
[
{
"is_hidden": False,
"attrs": {
"base_layer": None,
"display_raw": False,
"map_srid": 4326,
"geom_name": "Geometry",
"geom_type": "GEOMETRY",
},
"name": "name",
"template_name": "",
"value": "value",
"required": False,
}
],
)
def test_custom_serialization_widget(self):
class CustomGeometryWidget(forms.BaseGeometryWidget):
template_name = "gis/openlayers.html"
deserialize_called = 0
def serialize(self, value):
return value.json if value else ""
def deserialize(self, value):
self.deserialize_called += 1
return GEOSGeometry(value)
class PointForm(forms.Form):
p = forms.PointField(widget=CustomGeometryWidget)
point = GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)")
form = PointForm(data={"p": point})
self.assertIn(escape(point.json), form.as_p())
CustomGeometryWidget.called = 0
widget = form.fields["p"].widget
# Force deserialize use due to a string value
self.assertIn(escape(point.json), widget.render("p", point.json))
self.assertEqual(widget.deserialize_called, 1)
form = PointForm(data={"p": point.json})
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data["p"].srid, 4326)
| GeometryWidgetTests |
python | getsentry__sentry | src/sentry/hybridcloud/models/apitokenreplica.py | {
"start": 419,
"end": 2240
} | class ____(Model, HasApiScopes):
__relocation_scope__ = RelocationScope.Excluded
application_id = HybridCloudForeignKey("sentry.ApiApplication", null=True, on_delete="CASCADE")
organization = FlexibleForeignKey("sentry.Organization", null=True, on_delete=models.SET_NULL)
application_is_active = models.BooleanField(default=False)
user_id = HybridCloudForeignKey("sentry.User", on_delete="CASCADE")
apitoken_id = HybridCloudForeignKey("sentry.ApiToken", null=False, on_delete="CASCADE")
hashed_token = models.CharField(max_length=128, null=True)
token = models.CharField(max_length=71)
expires_at = models.DateTimeField(null=True)
allowed_origins = models.TextField(blank=True, null=True)
date_added = models.DateTimeField(default=timezone.now)
scoping_organization_id = HybridCloudForeignKey(
"sentry.Organization", null=True, on_delete="CASCADE"
)
class Meta:
app_label = "hybridcloud"
db_table = "hybridcloud_apitokenreplica"
indexes = (
models.Index(fields=["token"]),
models.Index(fields=["hashed_token"]),
)
__repr__ = sane_repr("user_id", "token", "application_id")
def __str__(self) -> str:
return f"replica_token_id={self.id}, token_id={force_str(self.apitoken_id)}"
@property
def entity_id(self) -> int:
return self.apitoken_id
def is_expired(self) -> bool:
if not self.expires_at:
return False
return timezone.now() >= self.expires_at
def get_allowed_origins(self) -> list[str]:
if not self.allowed_origins:
return []
return [origin for origin in self.allowed_origins.split()]
def get_audit_log_data(self) -> dict[str, Any]:
return {"scopes": self.get_scopes()}
| ApiTokenReplica |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 46840,
"end": 51136
} | class ____(BlipPreTrainedModel):
config: BlipConfig
def __init__(self, config: BlipConfig):
super().__init__(config)
self.vision_model = BlipVisionModel(config.vision_config)
self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
# vision projection layer
self.vision_proj = nn.Linear(config.vision_config.hidden_size, config.image_text_hidden_size)
# text projection layer
self.text_proj = nn.Linear(config.text_config.hidden_size, config.image_text_hidden_size)
# image text matching head
self.itm_head = nn.Linear(config.text_config.hidden_size, 2)
self.decoder_pad_token_id = (
config.text_config.pad_token_id
if not hasattr(config, "decoder_pad_token_id")
else config.decoder_pad_token_id
)
self.decoder_start_token_id = (
config.text_config.bos_token_id
if not hasattr(config, "decoder_start_token_id")
else config.decoder_start_token_id
)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.text_encoder.get_input_embeddings()
def set_input_embeddings(self, value):
self.text_encoder.set_input_embeddings(value)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: torch.LongTensor,
pixel_values: torch.FloatTensor,
use_itm_head: Optional[bool] = True,
attention_mask: Optional[torch.LongTensor] = None,
interpolate_pos_encoding: bool = False,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, BlipTextVisionModelOutput]:
r"""
use_itm_head (`bool`, *optional*, defaults to `True`):
Whether or not to use the image-text matching head.
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipForImageTextRetrieval
>>> model = BlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = "an image of a cat"
>>> inputs = processor(images=image, text=text, return_tensors="pt")
>>> outputs = model(**inputs)
```
"""
vision_outputs = self.vision_model(
pixel_values=pixel_values,
interpolate_pos_encoding=interpolate_pos_encoding,
**kwargs,
)
image_embeds = vision_outputs.last_hidden_state
image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
if use_itm_head:
question_embeds = self.text_encoder(
input_ids=input_ids,
attention_mask=attention_mask,
encoder_hidden_states=image_embeds,
encoder_attention_mask=image_atts,
**kwargs,
)
question_embeds = question_embeds.last_hidden_state
output = self.itm_head(question_embeds[:, 0, :])
else:
question_embeds = self.text_encoder(
input_ids=input_ids,
attention_mask=attention_mask,
**kwargs,
)
question_embeds = question_embeds.last_hidden_state
image_feat = normalize(self.vision_proj(image_embeds[:, 0, :]), dim=-1)
text_feat = normalize(self.text_proj(question_embeds[:, 0, :]), dim=-1)
output = image_feat @ text_feat.t()
return BlipImageTextMatchingModelOutput(
itm_score=output,
last_hidden_state=vision_outputs.last_hidden_state,
hidden_states=vision_outputs.hidden_states,
attentions=vision_outputs.attentions,
question_embeds=question_embeds,
)
__all__ = [
"BlipModel",
"BlipPreTrainedModel",
"BlipForConditionalGeneration",
"BlipForQuestionAnswering",
"BlipVisionModel",
"BlipTextModel",
"BlipForImageTextRetrieval",
]
| BlipForImageTextRetrieval |
python | jd__tenacity | tests/test_asyncio.py | {
"start": 1620,
"end": 4547
} | class ____(unittest.TestCase):
@asynctest
async def test_retry(self):
thing = NoIOErrorAfterCount(5)
await _retryable_coroutine(thing)
assert thing.counter == thing.count
@asynctest
async def test_iscoroutinefunction(self):
assert asyncio.iscoroutinefunction(_retryable_coroutine)
assert inspect.iscoroutinefunction(_retryable_coroutine)
@asynctest
async def test_retry_using_async_retying(self):
thing = NoIOErrorAfterCount(5)
retrying = AsyncRetrying()
await retrying(_async_function, thing)
assert thing.counter == thing.count
@asynctest
async def test_stop_after_attempt(self):
thing = NoIOErrorAfterCount(2)
try:
await _retryable_coroutine_with_2_attempts(thing)
except RetryError:
assert thing.counter == 2
def test_repr(self):
repr(tasyncio.AsyncRetrying())
def test_retry_attributes(self):
assert hasattr(_retryable_coroutine, "retry")
assert hasattr(_retryable_coroutine, "retry_with")
def test_retry_preserves_argument_defaults(self):
async def function_with_defaults(a=1):
return a
async def function_with_kwdefaults(*, a=1):
return a
retrying = AsyncRetrying(
wait=tenacity.wait_fixed(0.01), stop=tenacity.stop_after_attempt(3)
)
wrapped_defaults_function = retrying.wraps(function_with_defaults)
wrapped_kwdefaults_function = retrying.wraps(function_with_kwdefaults)
self.assertEqual(
function_with_defaults.__defaults__, wrapped_defaults_function.__defaults__
)
self.assertEqual(
function_with_kwdefaults.__kwdefaults__,
wrapped_kwdefaults_function.__kwdefaults__,
)
@asynctest
async def test_attempt_number_is_correct_for_interleaved_coroutines(self):
attempts = []
def after(retry_state):
attempts.append((retry_state.args[0], retry_state.attempt_number))
thing1 = NoIOErrorAfterCount(3)
thing2 = NoIOErrorAfterCount(3)
await asyncio.gather(
_retryable_coroutine.retry_with(after=after)(thing1), # type: ignore[attr-defined]
_retryable_coroutine.retry_with(after=after)(thing2), # type: ignore[attr-defined]
)
# There's no waiting on retry, only a wait in the coroutine, so the
# executions should be interleaved.
even_thing_attempts = attempts[::2]
things, attempt_nos1 = zip(*even_thing_attempts)
assert len(set(things)) == 1
assert list(attempt_nos1) == [1, 2, 3]
odd_thing_attempts = attempts[1::2]
things, attempt_nos2 = zip(*odd_thing_attempts)
assert len(set(things)) == 1
assert list(attempt_nos2) == [1, 2, 3]
@unittest.skipIf(not have_trio, "trio not installed")
| TestAsyncio |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-fauna/unit_tests/test_util.py | {
"start": 938,
"end": 1139
} | class ____:
def __init__(
self,
page_size=64,
deletions=DeletionsConfig.ignore(),
):
self.page_size = page_size
self.deletions = deletions
| CollectionConfig |
python | sqlalchemy__sqlalchemy | test/orm/test_session_state_change.py | {
"start": 208,
"end": 296
} | class ____(state_changes._StateChangeState):
a = 1
b = 2
c = 3
| StateTestChange |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 10300,
"end": 10543
} | class ____[T](list):
def __new__(cls: type[Generic1]) -> Generic1: ...
def __enter__(self: Generic1) -> Generic1: ...
### Correctness of typevar-likes are not verified.
T = TypeVar('T')
P = ParamSpec()
Ts = TypeVarTuple('foo')
| Generic1 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/subset/all.py | {
"start": 554,
"end": 4766
} | class ____(PartitionsSubset):
"""This is an in-memory (i.e. not serializable) convenience class that represents all partitions
of a given PartitionsDefinition, allowing set operations to be taken without having to load
all partition keys immediately.
"""
def __init__(self, partitions_def: PartitionsDefinition, context: PartitionLoadingContext):
self.partitions_def = partitions_def
check.invariant(
context.dynamic_partitions_store is not None,
"Cannot create an AllPartitionsSubset if a dynamic_partitions_store is "
"not available in the current PartitionLoadingContext.",
)
self._partition_loading_context = context
@property
def is_empty(self) -> bool:
return False
@use_partition_loading_context
def get_partition_keys(self, current_time: Optional[datetime] = None) -> Sequence[str]:
check.param_invariant(current_time is None, "current_time")
return self.partitions_def.get_partition_keys()
def get_partition_keys_not_in_subset(
self, partitions_def: PartitionsDefinition
) -> Iterable[str]:
return []
@use_partition_loading_context
def get_partition_key_ranges(
self, partitions_def: PartitionsDefinition
) -> Sequence[PartitionKeyRange]:
first_key = partitions_def.get_first_partition_key()
last_key = partitions_def.get_last_partition_key()
if first_key and last_key:
return [PartitionKeyRange(first_key, last_key)]
return []
def with_partition_keys(self, partition_keys: Iterable[str]) -> "AllPartitionsSubset":
return self
def __eq__(self, other: object) -> bool:
return (
isinstance(other, AllPartitionsSubset) and other.partitions_def == self.partitions_def
)
def __and__(self, other: "PartitionsSubset") -> "PartitionsSubset":
return other
@use_partition_loading_context
def __sub__(self, other: "PartitionsSubset") -> "PartitionsSubset":
from dagster._core.definitions.partitions.definition import TimeWindowPartitionsDefinition
from dagster._core.definitions.partitions.subset import TimeWindowPartitionsSubset
if self == other:
return self.partitions_def.empty_subset()
elif isinstance(other, TimeWindowPartitionsSubset) and isinstance(
self.partitions_def, TimeWindowPartitionsDefinition
):
return TimeWindowPartitionsSubset.from_all_partitions_subset(self) - other
return self.partitions_def.empty_subset().with_partition_keys(
set(self.get_partition_keys()).difference(set(other.get_partition_keys()))
)
def __or__(self, other: "PartitionsSubset") -> "PartitionsSubset":
return self
@use_partition_loading_context
def __len__(self) -> int:
return len(self.get_partition_keys())
@use_partition_loading_context
def __contains__(self, value) -> bool:
return self.partitions_def.has_partition_key(partition_key=value)
def __repr__(self) -> str:
return f"AllPartitionsSubset(partitions_def={self.partitions_def})"
@classmethod
def can_deserialize(
cls,
partitions_def: PartitionsDefinition,
serialized: str,
serialized_partitions_def_unique_id: Optional[str],
serialized_partitions_def_class_name: Optional[str],
) -> bool:
return False
def serialize(self) -> str:
raise NotImplementedError()
@classmethod
def from_serialized(
cls, partitions_def: PartitionsDefinition, serialized: str
) -> "PartitionsSubset":
raise NotImplementedError()
def empty_subset(self) -> PartitionsSubset:
return self.partitions_def.empty_subset()
@classmethod
def create_empty_subset(
cls, partitions_def: Optional[PartitionsDefinition] = None
) -> PartitionsSubset:
return check.not_none(partitions_def).empty_subset()
@use_partition_loading_context
def to_serializable_subset(self) -> PartitionsSubset:
return self.partitions_def.subset_with_all_partitions().to_serializable_subset()
| AllPartitionsSubset |
python | scrapy__scrapy | tests/test_utils_defer.py | {
"start": 2241,
"end": 2948
} | class ____:
def test_iter_errback_good(self):
def itergood() -> Generator[int, None, None]:
yield from range(10)
errors = []
out = list(iter_errback(itergood(), errors.append))
assert out == list(range(10))
assert not errors
def test_iter_errback_bad(self):
def iterbad() -> Generator[int, None, None]:
for x in range(10):
if x == 5:
1 / 0
yield x
errors = []
out = list(iter_errback(iterbad(), errors.append))
assert out == [0, 1, 2, 3, 4]
assert len(errors) == 1
assert isinstance(errors[0].value, ZeroDivisionError)
| TestIterErrback |
python | neetcode-gh__leetcode | python/0131-palindrome-partitioning.py | {
"start": 0,
"end": 593
} | class ____:
def partition(self, s: str) -> List[List[str]]:
res, part = [], []
def dfs(i):
if i >= len(s):
res.append(part.copy())
return
for j in range(i, len(s)):
if self.isPali(s, i, j):
part.append(s[i : j + 1])
dfs(j + 1)
part.pop()
dfs(0)
return res
def isPali(self, s, l, r):
while l < r:
if s[l] != s[r]:
return False
l, r = l + 1, r - 1
return True
| Solution |
python | getsentry__sentry | src/sentry/models/authprovider.py | {
"start": 1326,
"end": 9641
} | class ____(ReplicatedControlModel):
__relocation_scope__ = RelocationScope.Global
category = OutboxCategory.AUTH_PROVIDER_UPDATE
organization_id = HybridCloudForeignKey("sentry.Organization", on_delete="cascade", unique=True)
provider = models.CharField(max_length=128)
config = models.JSONField(default=dict)
date_added = models.DateTimeField(default=timezone.now)
sync_time = BoundedPositiveIntegerField(null=True)
last_sync = models.DateTimeField(null=True)
default_role = BoundedPositiveIntegerField(default=50)
default_global_access = models.BooleanField(default=True)
def handle_async_replication(self, region_name: str, shard_identifier: int) -> None:
from sentry.auth.services.auth.serial import serialize_auth_provider
from sentry.hybridcloud.services.replica.service import region_replica_service
serialized = serialize_auth_provider(self)
region_replica_service.upsert_replicated_auth_provider(
auth_provider=serialized, region_name=region_name
)
@classmethod
def handle_async_deletion(
cls,
identifier: int,
region_name: str,
shard_identifier: int,
payload: Mapping[str, Any] | None,
) -> None:
from sentry.hybridcloud.services.replica.service import region_replica_service
region_replica_service.delete_replicated_auth_provider(
auth_provider_id=identifier, region_name=region_name
)
class flags(TypedClassBitField):
# WARNING: Only add flags to the bottom of this list
# bitfield flags are dependent on their order and inserting/removing
# flags from the middle of the list will cause bits to shift corrupting
# existing data.
# Grant access to members who have not linked SSO accounts.
allow_unlinked: bool
# Enable SCIM for member and team provisioning and syncing.
scim_enabled: bool
bitfield_default = 0
class Meta:
app_label = "sentry"
db_table = "sentry_authprovider"
__repr__ = sane_repr("organization_id", "provider")
def __str__(self) -> str:
return self.provider
def get_provider(self):
from sentry.auth import manager
return manager.get(self.provider, **self.config)
@property
def provider_name(self) -> str:
return self.get_provider().name
def get_scim_token(self):
return get_scim_token(self.flags.scim_enabled, self.organization_id, self.provider)
def enable_scim(self, user):
from sentry.sentry_apps.logic import SentryAppCreator
from sentry.sentry_apps.models.sentry_app_installation import SentryAppInstallation
from sentry.sentry_apps.models.sentry_app_installation_for_provider import (
SentryAppInstallationForProvider,
)
if (
not self.get_provider().can_use_scim(self.organization_id, user)
or self.flags.scim_enabled is True
):
logger.warning(
"SCIM already enabled",
extra={"organization_id": self.organization_id},
)
return
# check if we have a scim app already
if SentryAppInstallationForProvider.objects.filter(
organization_id=self.organization_id, provider="okta_scim"
).exists():
logger.warning(
"SCIM installation already exists",
extra={"organization_id": self.organization_id},
)
return
sentry_app = SentryAppCreator(
name="SCIM Internal Integration",
author="Auto-generated by Sentry",
organization_id=self.organization_id,
overview=SCIM_INTERNAL_INTEGRATION_OVERVIEW,
is_internal=True,
verify_install=False,
scopes=[
"member:read",
"member:write",
"member:admin",
"team:write",
"team:admin",
],
).run(user=user)
sentry_app_installation = SentryAppInstallation.objects.get(sentry_app=sentry_app)
SentryAppInstallationForProvider.objects.create(
sentry_app_installation=sentry_app_installation,
organization_id=self.organization_id,
provider=f"{self.provider}_scim",
)
self.flags.scim_enabled = True
def outboxes_for_reset_idp_flags(self) -> list[ControlOutbox]:
return [
ControlOutbox(
shard_scope=OutboxScope.ORGANIZATION_SCOPE,
shard_identifier=self.organization_id,
category=OutboxCategory.RESET_IDP_FLAGS,
object_identifier=self.organization_id,
region_name=region_name,
)
for region_name in find_regions_for_orgs([self.organization_id])
]
def disable_scim(self):
from sentry.sentry_apps.models.sentry_app_installation_for_provider import (
SentryAppInstallationForProvider,
)
if self.flags.scim_enabled:
# Only one SCIM installation allowed per organization. So we can reset the idp flags for the orgs
# We run this update before the app is uninstalled to avoid ending up in a situation where there are
# members locked out because we failed to drop the IDP flag
for outbox in self.outboxes_for_reset_idp_flags():
outbox.save()
try:
# Provider : Installation links aren't guaranteed to be around all the time.
# Customers can remove the SCIM sentry app before the auth provider
install = SentryAppInstallationForProvider.objects.get(
organization_id=self.organization_id, provider=f"{self.provider}_scim"
)
sentry_app = install.sentry_app_installation.sentry_app
assert (
sentry_app.is_internal
), "scim sentry apps should always be internal, thus deleting them without triggering InstallationNotifier is correct."
sentry_app.update(status=SentryAppStatus.DELETION_IN_PROGRESS)
ScheduledDeletion.schedule(sentry_app, days=0)
except SentryAppInstallationForProvider.DoesNotExist:
pass
self.flags.scim_enabled = False
def get_audit_log_data(self):
provider = self.provider
# NOTE(isabella): for both standard fly SSO and fly-non-partner SSO, we should record the
# provider as "fly" in the audit log entry data; the only difference between the two is
# that the latter can be disabled by customers
if "fly" in self.provider:
provider = "fly"
return {"provider": provider, "config": self.config}
def outboxes_for_mark_invalid_sso(self, user_id: int) -> list[ControlOutbox]:
return [
ControlOutbox(
shard_scope=OutboxScope.ORGANIZATION_SCOPE,
shard_identifier=self.organization_id,
category=OutboxCategory.MARK_INVALID_SSO,
object_identifier=user_id,
region_name=region_name,
)
for region_name in find_regions_for_orgs([self.organization_id])
]
@classmethod
def sanitize_relocation_json(
cls, json: Any, sanitizer: Sanitizer, model_name: NormalizedModelName | None = None
) -> None:
model_name = get_model_name(cls) if model_name is None else model_name
super().sanitize_relocation_json(json, sanitizer, model_name)
sanitizer.set_json(json, SanitizableField(model_name, "config"), {})
sanitizer.set_string(json, SanitizableField(model_name, "provider"))
def get_scim_token(scim_enabled: bool, organization_id: int, provider: str) -> str | None:
from sentry.sentry_apps.services.app import app_service
if scim_enabled:
return app_service.get_installation_token(
organization_id=organization_id, provider=f"{provider}_scim"
)
else:
logger.warning(
"SCIM disabled but tried to access token",
extra={"organization_id": organization_id},
)
return None
| AuthProvider |
python | getsentry__sentry | src/sentry/api/serializers/models/userrollback.py | {
"start": 78,
"end": 177
} | class ____(TypedDict):
id: int
name: str
slug: str
| RollbackOrganizationSerializerResponse |
python | pdm-project__pdm | src/pdm/installers/manager.py | {
"start": 417,
"end": 3079
} | class ____:
"""The manager that performs the installation and uninstallation actions."""
# The packages below are needed to load paths and thus should not be cached.
NO_CACHE_PACKAGES = ("editables",)
def __init__(
self, environment: BaseEnvironment, *, use_install_cache: bool = False, rename_pth: bool = False
) -> None:
self.environment = environment
self.use_install_cache = use_install_cache
self.rename_pth = rename_pth
def install(self, candidate: Candidate) -> Distribution:
"""Install a candidate into the environment, return the distribution"""
prepared = candidate.prepare(self.environment)
dist_info = install_wheel(
prepared.build(),
self.environment,
direct_url=prepared.direct_url(),
install_links=self.use_install_cache and not candidate.req.editable,
rename_pth=self.rename_pth,
requested=candidate.requested,
)
return Distribution.at(dist_info)
def get_paths_to_remove(self, dist: Distribution) -> BaseRemovePaths:
"""Get the path collection to be removed from the disk"""
return StashedRemovePaths.from_dist(dist, environment=self.environment)
def uninstall(self, dist: Distribution) -> None:
"""Perform the uninstallation for a given distribution"""
remove_path = self.get_paths_to_remove(dist)
dist_name = dist.metadata.get("Name")
termui.logger.info("Removing distribution %s", dist_name)
try:
remove_path.remove()
remove_path.commit()
except OSError as e:
termui.logger.warning("Error occurred during uninstallation, roll back the changes now.")
remove_path.rollback()
raise UninstallError(e) from e
def overwrite(self, dist: Distribution, candidate: Candidate) -> None:
"""An in-place update to overwrite the distribution with a new candidate"""
paths_to_remove = self.get_paths_to_remove(dist)
termui.logger.info("Overwriting distribution %s", dist.metadata.get("Name"))
installed = self.install(candidate)
installed_paths = self.get_paths_to_remove(installed)
# Remove the paths that are in the new distribution
paths_to_remove.difference_update(installed_paths)
try:
paths_to_remove.remove()
paths_to_remove.commit()
except OSError as e:
termui.logger.warning("Error occurred during overwriting, roll back the changes now.")
paths_to_remove.rollback()
raise UninstallError(e) from e
| InstallManager |
python | MongoEngine__mongoengine | tests/test_connection.py | {
"start": 864,
"end": 25843
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
disconnect_all()
@classmethod
def tearDownClass(cls):
disconnect_all()
def tearDown(self):
mongoengine.connection._connection_settings = {}
mongoengine.connection._connections = {}
mongoengine.connection._dbs = {}
def test_connect(self):
"""Ensure that the connect() method works properly."""
connect("mongoenginetest")
conn = get_connection()
assert isinstance(conn, pymongo.MongoClient)
db = get_db()
assert isinstance(db, pymongo.database.Database)
assert db.name == "mongoenginetest"
connect("mongoenginetest2", alias="testdb")
conn = get_connection("testdb")
assert isinstance(conn, pymongo.MongoClient)
connect(
"mongoenginetest2", alias="testdb3", mongo_client_class=pymongo.MongoClient
)
conn = get_connection("testdb")
assert isinstance(conn, pymongo.MongoClient)
def test_connect_disconnect_works_properly(self):
class History1(Document):
name = StringField()
meta = {"db_alias": "db1"}
class History2(Document):
name = StringField()
meta = {"db_alias": "db2"}
connect("db1", alias="db1")
connect("db2", alias="db2")
History1.drop_collection()
History2.drop_collection()
h = History1(name="default").save()
h1 = History2(name="db1").save()
assert list(History1.objects().as_pymongo()) == [
{"_id": h.id, "name": "default"}
]
assert list(History2.objects().as_pymongo()) == [{"_id": h1.id, "name": "db1"}]
disconnect("db1")
disconnect("db2")
with pytest.raises(ConnectionFailure):
list(History1.objects().as_pymongo())
with pytest.raises(ConnectionFailure):
list(History2.objects().as_pymongo())
connect("db1", alias="db1")
connect("db2", alias="db2")
assert list(History1.objects().as_pymongo()) == [
{"_id": h.id, "name": "default"}
]
assert list(History2.objects().as_pymongo()) == [{"_id": h1.id, "name": "db1"}]
def test_connect_different_documents_to_different_database(self):
class History(Document):
name = StringField()
class History1(Document):
name = StringField()
meta = {"db_alias": "db1"}
class History2(Document):
name = StringField()
meta = {"db_alias": "db2"}
connect()
connect("db1", alias="db1")
connect("db2", alias="db2")
History.drop_collection()
History1.drop_collection()
History2.drop_collection()
h = History(name="default").save()
h1 = History1(name="db1").save()
h2 = History2(name="db2").save()
assert History._collection.database.name == DEFAULT_DATABASE_NAME
assert History1._collection.database.name == "db1"
assert History2._collection.database.name == "db2"
assert list(History.objects().as_pymongo()) == [
{"_id": h.id, "name": "default"}
]
assert list(History1.objects().as_pymongo()) == [{"_id": h1.id, "name": "db1"}]
assert list(History2.objects().as_pymongo()) == [{"_id": h2.id, "name": "db2"}]
def test_connect_fails_if_connect_2_times_with_default_alias(self):
connect("mongoenginetest")
with pytest.raises(ConnectionFailure) as exc_info:
connect("mongoenginetest2")
assert (
"A different connection with alias `default` was already registered. Use disconnect() first"
== str(exc_info.value)
)
def test_connect_fails_if_connect_2_times_with_custom_alias(self):
connect("mongoenginetest", alias="alias1")
with pytest.raises(ConnectionFailure) as exc_info:
connect("mongoenginetest2", alias="alias1")
assert (
"A different connection with alias `alias1` was already registered. Use disconnect() first"
== str(exc_info.value)
)
def test_connect_fails_if_similar_connection_settings_arent_defined_the_same_way(
self,
):
"""Intended to keep the detecton function simple but robust"""
db_name = "mongoenginetest"
db_alias = "alias1"
connect(db=db_name, alias=db_alias, host="localhost", port=27017)
with pytest.raises(ConnectionFailure):
connect(host="mongodb://localhost:27017/%s" % db_name, alias=db_alias)
def test___get_connection_settings(self):
funky_host = "mongodb://root:12345678@1.1.1.1:27017,2.2.2.2:27017,3.3.3.3:27017/db_api?replicaSet=s0&readPreference=secondary&uuidRepresentation=javaLegacy&readPreferenceTags=region:us-west-2,usage:api"
settings = _get_connection_settings(host=funky_host)
if PYMONGO_VERSION < (4,):
read_pref = Secondary(
tag_sets=[{"region": "us-west-2", "usage": "api"}],
max_staleness=-1,
)
else:
read_pref = Secondary(
tag_sets=[{"region": "us-west-2", "usage": "api"}],
max_staleness=-1,
hedge=None,
)
assert settings == {
"authentication_mechanism": None,
"authentication_source": None,
"authmechanismproperties": None,
"host": [funky_host],
"name": "db_api",
"password": "12345678",
"port": 27017,
"read_preference": read_pref,
"replicaSet": "s0",
"username": "root",
"uuidrepresentation": "javaLegacy",
}
def test_connect_passes_silently_connect_multiple_times_with_same_config(self):
# test default connection to `test`
connect()
connect()
assert len(mongoengine.connection._connections) == 1
connect("test01", alias="test01")
connect("test01", alias="test01")
assert len(mongoengine.connection._connections) == 2
connect(host="mongodb://localhost:27017/mongoenginetest02", alias="test02")
connect(host="mongodb://localhost:27017/mongoenginetest02", alias="test02")
assert len(mongoengine.connection._connections) == 3
def test_connect_with_invalid_db_name(self):
"""Ensure that connect() method fails fast if db name is invalid"""
with pytest.raises(InvalidName):
connect("mongodb://localhost")
def test_connect_with_db_name_external(self):
"""Ensure that connect() works if db name is $external"""
"""Ensure that the connect() method works properly."""
connect("$external")
conn = get_connection()
assert isinstance(conn, pymongo.mongo_client.MongoClient)
db = get_db()
assert isinstance(db, pymongo.database.Database)
assert db.name == "$external"
connect("$external", alias="testdb")
conn = get_connection("testdb")
assert isinstance(conn, pymongo.mongo_client.MongoClient)
def test_connect_with_invalid_db_name_type(self):
"""Ensure that connect() method fails fast if db name has invalid type"""
with pytest.raises(TypeError):
non_string_db_name = ["e. g. list instead of a string"]
connect(non_string_db_name)
def test_disconnect_cleans_globals(self):
"""Ensure that the disconnect() method cleans the globals objects"""
connections = mongoengine.connection._connections
dbs = mongoengine.connection._dbs
connection_settings = mongoengine.connection._connection_settings
connect("mongoenginetest")
assert len(connections) == 1
assert len(dbs) == 0
assert len(connection_settings) == 1
class TestDoc(Document):
pass
TestDoc.drop_collection() # triggers the db
assert len(dbs) == 1
disconnect()
assert len(connections) == 0
assert len(dbs) == 0
assert len(connection_settings) == 0
def test_disconnect_cleans_cached_collection_attribute_in_document(self):
"""Ensure that the disconnect() method works properly"""
connect("mongoenginetest")
class History(Document):
pass
assert History._collection is None
History.drop_collection()
History.objects.first() # will trigger the caching of _collection attribute
assert History._collection is not None
disconnect()
assert History._collection is None
with pytest.raises(ConnectionFailure) as exc_info:
History.objects.first()
assert "You have not defined a default connection" == str(exc_info.value)
def test_connect_disconnect_works_on_same_document(self):
"""Ensure that the connect/disconnect works properly with a single Document"""
db1 = "db1"
db2 = "db2"
# Ensure freshness of the 2 databases through pymongo
client = MongoClient("localhost", 27017)
client.drop_database(db1)
client.drop_database(db2)
# Save in db1
connect(db1)
class User(Document):
name = StringField(required=True)
user1 = User(name="John is in db1").save()
disconnect()
# Make sure save doesnt work at this stage
with pytest.raises(ConnectionFailure):
User(name="Wont work").save()
# Save in db2
connect(db2)
user2 = User(name="Bob is in db2").save()
disconnect()
db1_users = list(client[db1].user.find())
assert db1_users == [{"_id": user1.id, "name": "John is in db1"}]
db2_users = list(client[db2].user.find())
assert db2_users == [{"_id": user2.id, "name": "Bob is in db2"}]
def test_disconnect_silently_pass_if_alias_does_not_exist(self):
connections = mongoengine.connection._connections
assert len(connections) == 0
disconnect(alias="not_exist")
def test_disconnect_does_not_close_client_used_by_another_alias(self):
client1 = connect(alias="disconnect_reused_client_test_1")
client2 = connect(alias="disconnect_reused_client_test_2")
client3 = connect(alias="disconnect_reused_client_test_3", maxPoolSize=10)
assert client1 is client2
assert client1 is not client3
client1.admin.command("ping")
disconnect("disconnect_reused_client_test_1")
# The client is not closed because the second alias still exists.
client2.admin.command("ping")
disconnect("disconnect_reused_client_test_2")
# The client is now closed:
if PYMONGO_VERSION >= (4,):
with pytest.raises(InvalidOperation):
client2.admin.command("ping")
# 3rd client connected to the same cluster with different options
# is not closed either.
client3.admin.command("ping")
disconnect("disconnect_reused_client_test_3")
# 3rd client is now closed:
if PYMONGO_VERSION >= (4,):
with pytest.raises(InvalidOperation):
client3.admin.command("ping")
def test_disconnect_all(self):
connections = mongoengine.connection._connections
dbs = mongoengine.connection._dbs
connection_settings = mongoengine.connection._connection_settings
connect("mongoenginetest")
connect("mongoenginetest2", alias="db1")
class History(Document):
pass
class History1(Document):
name = StringField()
meta = {"db_alias": "db1"}
History.drop_collection() # will trigger the caching of _collection attribute
History.objects.first()
History1.drop_collection()
History1.objects.first()
assert History._collection is not None
assert History1._collection is not None
assert len(connections) == 2
assert len(dbs) == 2
assert len(connection_settings) == 2
disconnect_all()
assert History._collection is None
assert History1._collection is None
assert len(connections) == 0
assert len(dbs) == 0
assert len(connection_settings) == 0
with pytest.raises(ConnectionFailure):
History.objects.first()
with pytest.raises(ConnectionFailure):
History1.objects.first()
def test_disconnect_all_silently_pass_if_no_connection_exist(self):
disconnect_all()
def test_sharing_connections(self):
"""Ensure that connections are shared when the connection settings are exactly the same"""
connect("mongoenginetests", alias="testdb1")
expected_connection = get_connection("testdb1")
connect("mongoenginetests", alias="testdb2")
actual_connection = get_connection("testdb2")
expected_connection.server_info()
assert expected_connection == actual_connection
def test_connect_uri(self):
"""Ensure that the connect() method works properly with URIs."""
c = connect(db="mongoenginetest", alias="admin")
c.admin.system.users.delete_many({})
c.mongoenginetest.system.users.delete_many({})
c.admin.command("createUser", "admin", pwd="password", roles=["root"])
adminadmin_settings = mongoengine.connection._connection_settings[
"adminadmin"
] = mongoengine.connection._connection_settings["admin"].copy()
adminadmin_settings["username"] = "admin"
adminadmin_settings["password"] = "password"
ca = connect(db="mongoenginetest", alias="adminadmin")
ca.admin.command("createUser", "username", pwd="password", roles=["dbOwner"])
connect(
"testdb_uri", host="mongodb://username:password@localhost/mongoenginetest"
)
conn = get_connection()
assert isinstance(conn, pymongo.mongo_client.MongoClient)
db = get_db()
assert isinstance(db, pymongo.database.Database)
assert db.name == "mongoenginetest"
c.admin.system.users.delete_many({})
c.mongoenginetest.system.users.delete_many({})
def test_connect_uri_without_db(self):
"""Ensure connect() method works properly if the URI doesn't
include a database name.
"""
connect("mongoenginetest", host="mongodb://localhost/")
conn = get_connection()
assert isinstance(conn, pymongo.mongo_client.MongoClient)
db = get_db()
assert isinstance(db, pymongo.database.Database)
assert db.name == "mongoenginetest"
def test_connect_uri_default_db(self):
"""Ensure connect() defaults to the right database name if
the URI and the database_name don't explicitly specify it.
"""
connect(host="mongodb://localhost/")
conn = get_connection()
assert isinstance(conn, pymongo.mongo_client.MongoClient)
db = get_db()
assert isinstance(db, pymongo.database.Database)
assert db.name == "test"
def test_uri_without_credentials_doesnt_override_conn_settings(self):
"""Ensure connect() uses the username & password params if the URI
doesn't explicitly specify them.
"""
connect(
host="mongodb://localhost/mongoenginetest", username="user", password="pass"
)
# OperationFailure means that mongoengine attempted authentication
# w/ the provided username/password and failed - that's the desired
# behavior. If the MongoDB URI would override the credentials
if PYMONGO_VERSION >= (4,):
with pytest.raises(OperationFailure):
db = get_db()
# pymongo 4.x does not call db.authenticate and needs to perform an operation to trigger the failure
db.list_collection_names()
else:
with pytest.raises(OperationFailure):
get_db()
def test_connect_uri_with_authsource(self):
"""Ensure that the connect() method works well with `authSource`
option in the URI.
"""
# Create users
c = connect("mongoenginetest")
c.admin.system.users.delete_many({})
c.admin.command("createUser", "username2", pwd="password", roles=["dbOwner"])
# Authentication fails without "authSource"
test_conn = connect(
"mongoenginetest",
alias="test1",
host="mongodb://username2:password@localhost/mongoenginetest",
)
with pytest.raises(OperationFailure):
test_conn.server_info()
# Authentication succeeds with "authSource"
authd_conn = connect(
"mongoenginetest",
alias="test2",
host=(
"mongodb://username2:password@localhost/"
"mongoenginetest?authSource=admin"
),
)
db = get_db("test2")
assert isinstance(db, pymongo.database.Database)
assert db.name == "mongoenginetest"
# Clear all users
authd_conn.admin.system.users.delete_many({})
def test_register_connection(self):
"""Ensure that connections with different aliases may be registered."""
register_connection("testdb", "mongoenginetest2")
with pytest.raises(ConnectionFailure):
get_connection()
conn = get_connection("testdb")
assert isinstance(conn, pymongo.mongo_client.MongoClient)
db = get_db("testdb")
assert isinstance(db, pymongo.database.Database)
assert db.name == "mongoenginetest2"
def test_register_connection_defaults(self):
"""Ensure that defaults are used when the host and port are None."""
register_connection("testdb", "mongoenginetest", host=None, port=None)
conn = get_connection("testdb")
assert isinstance(conn, pymongo.mongo_client.MongoClient)
def test_connection_kwargs(self):
"""Ensure that connection kwargs get passed to pymongo."""
connect("mongoenginetest", alias="t1", tz_aware=True)
conn = get_connection("t1")
assert get_tz_awareness(conn)
connect("mongoenginetest2", alias="t2")
conn = get_connection("t2")
assert not get_tz_awareness(conn)
def test_connection_pool_via_kwarg(self):
"""Ensure we can specify a max connection pool size using
a connection kwarg.
"""
pool_size_kwargs = {"maxpoolsize": 100}
conn = connect(
"mongoenginetest", alias="max_pool_size_via_kwarg", **pool_size_kwargs
)
if PYMONGO_VERSION >= (4,):
assert conn.options.pool_options.max_pool_size == 100
else:
assert conn.max_pool_size == 100
def test_connection_pool_via_uri(self):
"""Ensure we can specify a max connection pool size using
an option in a connection URI.
"""
conn = connect(
host="mongodb://localhost/test?maxpoolsize=100",
alias="max_pool_size_via_uri",
)
if PYMONGO_VERSION >= (4,):
assert conn.options.pool_options.max_pool_size == 100
else:
assert conn.max_pool_size == 100
def test_write_concern(self):
"""Ensure write concern can be specified in connect() via
a kwarg or as part of the connection URI.
"""
conn1 = connect(
alias="conn1", host="mongodb://localhost/testing?w=1&journal=true"
)
conn2 = connect("testing", alias="conn2", w=1, journal=True)
assert conn1.write_concern.document == {"w": 1, "j": True}
assert conn2.write_concern.document == {"w": 1, "j": True}
def test_connect_with_replicaset_via_uri(self):
"""Ensure connect() works when specifying a replicaSet via the
MongoDB URI.
"""
connect(host="mongodb://localhost/test?replicaSet=local-rs")
db = get_db()
assert isinstance(db, pymongo.database.Database)
assert db.name == "test"
def test_connect_with_replicaset_via_kwargs(self):
"""Ensure connect() works when specifying a replicaSet via the
connection kwargs
"""
c = connect(replicaset="local-rs")
if hasattr(c, "_MongoClient__options"):
assert c._MongoClient__options.replica_set_name == "local-rs"
else: # pymongo >= 4.9
assert c._options.replica_set_name == "local-rs"
db = get_db()
assert isinstance(db, pymongo.database.Database)
assert db.name == "test"
def test_connect_tz_aware(self):
connect("mongoenginetest", tz_aware=True)
d = datetime.datetime(2010, 5, 5, tzinfo=utc)
class DateDoc(Document):
the_date = DateTimeField(required=True)
DateDoc.drop_collection()
DateDoc(the_date=d).save()
date_doc = DateDoc.objects.first()
assert d == date_doc.the_date
def test_read_preference_from_parse(self):
conn = connect(
host="mongodb://a1.vpc,a2.vpc,a3.vpc/prod?readPreference=secondaryPreferred"
)
assert conn.read_preference == ReadPreference.SECONDARY_PREFERRED
def test_multiple_connection_settings(self):
connect(
"mongoenginetest",
alias="t1",
host="localhost",
read_preference=ReadPreference.PRIMARY,
)
connect(
"mongoenginetest2",
alias="t2",
host="127.0.0.1",
read_preference=ReadPreference.PRIMARY_PREFERRED,
)
mongo_connections = mongoengine.connection._connections
assert len(mongo_connections.items()) == 2
assert "t1" in mongo_connections.keys()
assert "t2" in mongo_connections.keys()
# Handle PyMongo 3+ Async Connection (lazily established)
# Ensure we are connected, throws ServerSelectionTimeoutError otherwise.
# Purposely not catching exception to fail test if thrown.
mongo_connections["t1"].server_info()
mongo_connections["t2"].server_info()
assert mongo_connections["t1"].address[0] == "localhost"
assert mongo_connections["t2"].address[0] in (
"localhost",
"127.0.0.1",
) # weird but there is a discrepancy in the address in replicaset setup
assert mongo_connections["t1"].read_preference == ReadPreference.PRIMARY
assert (
mongo_connections["t2"].read_preference == ReadPreference.PRIMARY_PREFERRED
)
assert mongo_connections["t1"] is not mongo_connections["t2"]
def test_connect_2_databases_uses_same_client_if_only_dbname_differs(self):
c1 = connect(alias="testdb1", db="testdb1")
c2 = connect(alias="testdb2", db="testdb2")
assert c1 is c2
def test_connect_2_databases_uses_different_client_if_different_parameters(self):
c1 = connect(alias="testdb1", db="testdb1", username="u1", password="pass")
c2 = connect(alias="testdb2", db="testdb2", username="u2", password="pass")
assert c1 is not c2
def test_connect_uri_uuidrepresentation_set_in_uri(self):
rand = random_str()
tmp_conn = connect(
alias=rand,
host=f"mongodb://localhost:27017/{rand}?uuidRepresentation=csharpLegacy",
)
assert (
tmp_conn.options.codec_options.uuid_representation
== pymongo.common._UUID_REPRESENTATIONS["csharpLegacy"]
)
disconnect(rand)
def test_connect_uri_uuidrepresentation_set_as_arg(self):
rand = random_str()
tmp_conn = connect(alias=rand, db=rand, uuidRepresentation="javaLegacy")
assert (
tmp_conn.options.codec_options.uuid_representation
== pymongo.common._UUID_REPRESENTATIONS["javaLegacy"]
)
disconnect(rand)
def test_connect_uri_uuidrepresentation_set_both_arg_and_uri_arg_prevail(self):
rand = random_str()
tmp_conn = connect(
alias=rand,
host=f"mongodb://localhost:27017/{rand}?uuidRepresentation=csharpLegacy",
uuidRepresentation="javaLegacy",
)
assert (
tmp_conn.options.codec_options.uuid_representation
== pymongo.common._UUID_REPRESENTATIONS["javaLegacy"]
)
disconnect(rand)
def test_connect_uri_uuidrepresentation_default_to_pythonlegacy(self):
# To be changed soon to unspecified
rand = random_str()
tmp_conn = connect(alias=rand, db=rand)
assert (
tmp_conn.options.codec_options.uuid_representation
== pymongo.common._UUID_REPRESENTATIONS["pythonLegacy"]
)
disconnect(rand)
if __name__ == "__main__":
unittest.main()
| ConnectionTest |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 2047,
"end": 9823
} | class ____(NonStrictDataModel):
"""
:param id: Project id
:type id: str
:param name: Project name
:type name: str
:param description: Project description
:type description: str
:param user: Associated user id
:type user: str
:param company: Company id
:type company: str
:param created: Creation time
:type created: datetime.datetime
:param tags: User-defined tags
:type tags: Sequence[str]
:param system_tags: System tags. This field is reserved for system use, please
don't use it.
:type system_tags: Sequence[str]
:param default_output_destination: The default output destination URL for new
tasks under this project
:type default_output_destination: str
:param last_update: Last project update time. Reflects the last time the
project metadata was changed or a task in this project has changed status
:type last_update: datetime.datetime
"""
_schema = {
"properties": {
"company": {"description": "Company id", "type": ["string", "null"]},
"created": {
"description": "Creation time",
"format": "date-time",
"type": ["string", "null"],
},
"default_output_destination": {
"description": "The default output destination URL for new tasks under this project",
"type": ["string", "null"],
},
"description": {
"description": "Project description",
"type": ["string", "null"],
},
"id": {"description": "Project id", "type": ["string", "null"]},
"last_update": {
"description": "Last project update time. Reflects the last time the project metadata was changed or a task in this project has changed status",
"format": "date-time",
"type": ["string", "null"],
},
"name": {"description": "Project name", "type": ["string", "null"]},
"system_tags": {
"description": "System tags. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "User-defined tags",
"items": {"type": "string"},
"type": ["array", "null"],
},
"user": {"description": "Associated user id", "type": ["string", "null"]},
},
"type": "object",
}
def __init__(
self,
id: Optional[str] = None,
name: Optional[str] = None,
description: Optional[str] = None,
user: Optional[str] = None,
company: Optional[str] = None,
created: Optional[str] = None,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
default_output_destination: Optional[str] = None,
last_update: Optional[str] = None,
**kwargs: Any
) -> None:
super(Project, self).__init__(**kwargs)
self.id = id
self.name = name
self.description = description
self.user = user
self.company = company
self.created = created
self.tags = tags
self.system_tags = system_tags
self.default_output_destination = default_output_destination
self.last_update = last_update
@schema_property("id")
def id(self) -> Optional[str]:
return self._property_id
@id.setter
def id(self, value: Optional[str]) -> None:
if value is None:
self._property_id = None
return
self.assert_isinstance(value, "id", six.string_types)
self._property_id = value
@schema_property("name")
def name(self) -> Optional[str]:
return self._property_name
@name.setter
def name(self, value: Optional[str]) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("description")
def description(self) -> Optional[str]:
return self._property_description
@description.setter
def description(self, value: Optional[str]) -> None:
if value is None:
self._property_description = None
return
self.assert_isinstance(value, "description", six.string_types)
self._property_description = value
@schema_property("user")
def user(self) -> Optional[str]:
return self._property_user
@user.setter
def user(self, value: Optional[str]) -> None:
if value is None:
self._property_user = None
return
self.assert_isinstance(value, "user", six.string_types)
self._property_user = value
@schema_property("company")
def company(self) -> Optional[str]:
return self._property_company
@company.setter
def company(self, value: Optional[str]) -> None:
if value is None:
self._property_company = None
return
self.assert_isinstance(value, "company", six.string_types)
self._property_company = value
@schema_property("created")
def created(self) -> Optional[str]:
return self._property_created
@created.setter
def created(self, value: Optional[str]) -> None:
if value is None:
self._property_created = None
return
self.assert_isinstance(value, "created", six.string_types + (datetime,))
if not isinstance(value, datetime):
value = parse_datetime(value)
self._property_created = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("default_output_destination")
def default_output_destination(self) -> Optional[str]:
return self._property_default_output_destination
@default_output_destination.setter
def default_output_destination(self, value: Optional[str]) -> None:
if value is None:
self._property_default_output_destination = None
return
self.assert_isinstance(value, "default_output_destination", six.string_types)
self._property_default_output_destination = value
@schema_property("last_update")
def last_update(self) -> Optional[str]:
return self._property_last_update
@last_update.setter
def last_update(self, value: Optional[str]) -> None:
if value is None:
self._property_last_update = None
return
self.assert_isinstance(value, "last_update", six.string_types + (datetime,))
if not isinstance(value, datetime):
value = parse_datetime(value)
self._property_last_update = value
| Project |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-ideal-arrays.py | {
"start": 328,
"end": 2173
} | class ____(object):
def idealArrays(self, n, maxValue):
"""
:type n: int
:type maxValue: int
:rtype: int
"""
MOD = 10**9+7
fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]
def nCr(n, k):
while len(inv) <= n: # lazy initialization
fact.append(fact[-1]*len(inv) % MOD)
inv.append(inv[MOD%len(inv)]*(MOD-MOD//len(inv)) % MOD) # https://cp-algorithms.com/algebra/module-inverse.html
inv_fact.append(inv_fact[-1]*inv[-1] % MOD)
return (fact[n]*inv_fact[n-k] % MOD) * inv_fact[k] % MOD
def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n)
primes = []
spf = [-1]*(n+1) # the smallest prime factor
for i in xrange(2, n+1):
if spf[i] == -1:
spf[i] = i
primes.append(i)
for p in primes:
if i*p > n or p > spf[i]:
break
spf[i*p] = p
return primes
def prime_factors(x):
factors = collections.Counter()
for p in primes:
if p*p > x:
break
while x%p == 0:
factors[p] += 1
x //= p
if x != 1:
factors[x] += 1
return factors
primes = linear_sieve_of_eratosthenes(int(maxValue**0.5))
result = 0
for k in xrange(1, maxValue+1):
total = 1
for c in prime_factors(k).itervalues():
total = (total*nCr(n+c-1, c))%MOD # H(n, c) = nCr(n+c-1, n)
result = (result+total)%MOD
return result
# Time: O(n * mlogm)
# Space: O(n + m)
import collections
# dp, combinatorics
| Solution |
python | openai__openai-python | src/openai/types/beta/thread_deleted.py | {
"start": 190,
"end": 292
} | class ____(BaseModel):
id: str
deleted: bool
object: Literal["thread.deleted"]
| ThreadDeleted |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 73377,
"end": 76868
} | class ____(GithubStream):
"""
API docs: https://docs.github.com/en/rest/metrics/statistics?apiVersion=2022-11-28#get-all-contributor-commit-activity
"""
def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:
return f"repos/{stream_slice['repository']}/stats/contributors"
def request_headers(self, **kwargs) -> Mapping[str, Any]:
params = super().request_headers(**kwargs)
params.update({"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28"})
return params
def transform(self, record: MutableMapping[str, Any], stream_slice: Mapping[str, Any]) -> MutableMapping[str, Any]:
record["repository"] = stream_slice["repository"]
author = record.pop("author", None)
# It's been found that the author field can be None, so we check for it
if author:
record.update(author)
return record
def get_error_handler(self) -> Optional[ErrorHandler]:
return ContributorActivityErrorHandler(logger=self.logger, max_retries=5, error_mapping=GITHUB_DEFAULT_ERROR_MAPPING)
def get_backoff_strategy(self) -> Optional[Union[BackoffStrategy, List[BackoffStrategy]]]:
return ContributorActivityBackoffStrategy()
def parse_response(
self,
response: requests.Response,
stream_state: Mapping[str, Any],
stream_slice: Mapping[str, Any] = None,
next_page_token: Mapping[str, Any] = None,
) -> Iterable[Mapping]:
if response.status_code == requests.codes.NO_CONTENT:
self.logger.warning(f"Empty response received for {self.name} stats in repository {stream_slice.get('repository')}")
else:
yield from super().parse_response(
response, stream_state=stream_state, stream_slice=stream_slice, next_page_token=next_page_token
)
def read_records(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> Iterable[Mapping[str, Any]]:
repository = stream_slice.get("repository", "")
try:
yield from super().read_records(stream_slice=stream_slice, **kwargs)
# HTTP Client wraps BackoffException into MessageRepresentationAirbyteTracedErrors
except MessageRepresentationAirbyteTracedErrors as e:
if hasattr(e, "_exception") and hasattr(e._exception, "response"):
if e._exception.response.status_code == requests.codes.ACCEPTED:
yield AirbyteMessage(
type=MessageType.LOG,
log=AirbyteLogMessage(
level=Level.INFO,
message=f"Syncing `{self.__class__.__name__}` stream isn't available for repository `{repository}`.",
),
)
# In order to retain the existing stream behavior before we added RFR to this stream, we need to close out the
# partition after we give up the maximum number of retries on the 202 response. This does lead to the question
# of if we should prematurely exit in the first place, but for now we're going to aim for feature parity
partition_obj = stream_slice.get("partition")
if self.cursor and partition_obj:
self.cursor.close_slice(StreamSlice(cursor_slice={}, partition=partition_obj))
else:
raise e
| ContributorActivity |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 30537,
"end": 35156
} | class ____(IRNode):
device: torch.device
dtype: torch.dtype
inner_fn: Callable[..., Any]
ranges: Sequence[_IntLike]
@cache_on_self_and_args("Loops")
def get_free_symbol_uses(
self, unbacked_only: bool = False
) -> OrderedSet[sympy.Symbol]:
return OrderedSet().union(
*(get_free_symbols(e, unbacked_only) for e in self.ranges),
self.inner_fn_free_symbols(unbacked_only),
)
def _to_str(self, names: Sequence[str]) -> str:
return self.str_helper(
[
f"'{self.device.type}'",
str(self.dtype),
self.inner_fn_str(),
]
+ [f"{name}={getattr(self, name)}" for name in names]
+ [f"origin_node={self.origin_node!r}"]
)
def __str__(self) -> str:
return self._to_str(("ranges",))
__repr__ = __str__
def get_device(self) -> Optional[torch.device]:
return self.device
def get_origin_node(self) -> Optional[torch.fx.Node]:
return self.origin_node
def get_size(self) -> Sequence[Expr]:
return self.ranges
def get_pointwise_size(self) -> Sequence[Expr]:
return self.ranges
@classmethod
def create(
cls, *args: Any, **kwargs: Any
) -> Union[TensorBox, ShapeAsConstantBuffer]:
origin_node = kwargs.pop("origin_node", None)
tb = kwargs.pop("traceback", None)
r = cls(*args, **kwargs)
# Need to explicitly set origin_node here to propagate it down.
# todo(chilli): I think it would be better for IRNode to directly set
# origin_node
r._post_init_setattr("origin_node", origin_node)
r._post_init_setattr("traceback", tb or r.traceback)
return TensorBox.create(r)
@staticmethod
def _index(ranges: Sequence[_IntLike], prefix: SymT = SymT.INDEX) -> Sequence[Expr]:
return [
sympy.S.Zero if s == 1 else sympy_index_symbol_with_prefix(prefix, n)
for n, s in enumerate(ranges)
]
@cache_on_self
def inner_fn_opcount(self) -> OpCountResult:
opcounter = OpCounterCSE(V.MockHandler())
with (
V.set_ops_handler(opcounter),
patch.object(FlexibleLayout, "allow_indexing", True),
):
self.inner_fn(*self.inner_fn_args())
return opcounter.getvalue()
def inner_fn_args(self) -> Sequence[Sequence[_IntLike]]:
return (self._index(self.ranges),)
@cache_on_self
def inner_fn_str(self) -> str:
return V.KernelFormatterHandler.ir_to_string(
self.inner_fn, *self.inner_fn_args()
)
def has_large_inner_fn(self, threshold: Optional[int] = None) -> bool:
if threshold is None:
threshold = 0
threshold = max(threshold, config.realize_opcount_threshold)
return self.inner_fn_opcount().num_ops > threshold
def inner_fn_free_symbols(self, unbacked_only: bool = False) -> OrderedSet[Symbol]:
index = self._index(self.ranges)
return extract_free_symbols(self.inner_fn, index, unbacked_only=unbacked_only)
def get_reads(self) -> OrderedSet[Dep]:
with patch.object(FlexibleLayout, "allow_indexing", True):
if self.get_reduction_type():
return extract_read_writes(
self.make_loader(),
self.get_size(),
self.get_reduction_size(),
).reads
else:
return extract_read_writes(
self.make_loader(),
self.get_size(),
).reads
def get_read_names(self) -> OrderedSet[str]:
return OrderedSet(self.inner_fn_opcount().read_buffers)
def num_reads(self) -> int:
return len(self.inner_fn_opcount().read_buffers)
def get_reduction_size(self) -> Sequence[Expr]:
raise NotImplementedError(
f"get_reduction_size() is not implemented by {type(self)}!"
)
def get_reduction_type(self) -> Optional[str]:
raise NotImplementedError(
f"get_reduction_type() is not implemented by {type(self)}!"
)
def constant_to_device(self, device: torch.device) -> IRNode:
raise NotImplementedError(
f"constant_to_device() is not implemented by {type(self)}!"
)
def nop_loader_fn(idx: Union[Expr, Sequence[Expr]], *, dtype: torch.dtype) -> OpsValue:
if dtype.is_floating_point:
return ops.constant(float("nan"), dtype)
else:
return ops.constant(0, dtype)
@ir_dataclass
| Loops |
python | agronholm__apscheduler | src/apscheduler/eventbrokers/base.py | {
"start": 3309,
"end": 5808
} | class ____(BaseEventBroker, RetryMixin):
"""
Base class for event brokers that use an external service.
:param serializer: the serializer used to (de)serialize events for transport
"""
serializer: Serializer = attrs.field(factory=JSONSerializer)
def generate_notification(self, event: Event) -> bytes:
serialized = self.serializer.serialize(event.marshal())
return event.__class__.__name__.encode("ascii") + b" " + serialized
def generate_notification_str(self, event: Event) -> str:
serialized = self.serializer.serialize(event.marshal())
return event.__class__.__name__ + " " + b64encode(serialized).decode("ascii")
def _reconstitute_event(self, event_type: str, serialized: bytes) -> Event | None:
try:
kwargs = self.serializer.deserialize(serialized)
except DeserializationError:
self._logger.exception(
"Failed to deserialize an event of type %s",
event_type,
extra={"serialized": serialized},
)
return None
try:
event_class = getattr(_events, event_type)
except AttributeError:
self._logger.error(
"Receive notification for a nonexistent event type: %s",
event_type,
extra={"serialized": serialized},
)
return None
try:
return event_class.unmarshal(kwargs)
except Exception:
self._logger.exception("Error reconstituting event of type %s", event_type)
return None
def reconstitute_event(self, payload: bytes) -> Event | None:
try:
event_type_bytes, serialized = payload.split(b" ", 1)
except ValueError:
self._logger.error(
"Received malformatted notification", extra={"payload": payload}
)
return None
event_type = event_type_bytes.decode("ascii", errors="replace")
return self._reconstitute_event(event_type, serialized)
def reconstitute_event_str(self, payload: str) -> Event | None:
try:
event_type, b64_serialized = payload.split(" ", 1)
except ValueError:
self._logger.error(
"Received malformatted notification", extra={"payload": payload}
)
return None
return self._reconstitute_event(event_type, b64decode(b64_serialized))
| BaseExternalEventBroker |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 36804,
"end": 39282
} | class ____(BooleanFunction):
r"""
Logical implication.
A implies B is equivalent to if A then B. Mathematically, it is written
as `A \Rightarrow B` and is equivalent to `\neg A \vee B` or ``~A | B``.
Accepts two Boolean arguments; A and B.
Returns False if A is True and B is False
Returns True otherwise.
Examples
========
>>> from sympy.logic.boolalg import Implies
>>> from sympy import symbols
>>> x, y = symbols('x y')
>>> Implies(True, False)
False
>>> Implies(False, False)
True
>>> Implies(True, True)
True
>>> Implies(False, True)
True
>>> x >> y
Implies(x, y)
>>> y << x
Implies(x, y)
Notes
=====
The ``>>`` and ``<<`` operators are provided as a convenience, but note
that their use here is different from their normal use in Python, which is
bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different
things if ``a`` and ``b`` are integers. In particular, since Python
considers ``True`` and ``False`` to be integers, ``True >> True`` will be
the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To
avoid this issue, use the SymPy objects ``true`` and ``false``.
>>> from sympy import true, false
>>> True >> False
1
>>> true >> false
False
"""
@classmethod
def eval(cls, *args):
try:
newargs = []
for x in args:
if isinstance(x, Number) or x in (0, 1):
newargs.append(bool(x))
else:
newargs.append(x)
A, B = newargs
except ValueError:
raise ValueError(
"%d operand(s) used for an Implies "
"(pairs are required): %s" % (len(args), str(args)))
if A in (True, False) or B in (True, False):
return Or(Not(A), B)
elif A == B:
return true
elif A.is_Relational and B.is_Relational:
if A.canonical == B.canonical:
return true
if A.negated.canonical == B.canonical:
return B
else:
return Basic.__new__(cls, *args)
def to_nnf(self, simplify=True, form=None):
a, b = self.args
return Or._to_nnf(Not(a), b, simplify=simplify, form=form)
def to_anf(self, deep=True):
a, b = self.args
return Xor._to_anf(true, a, And(a, b), deep=deep)
| Implies |
python | joke2k__faker | faker/providers/automotive/en_NZ/__init__.py | {
"start": 48,
"end": 640
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``en_NZ`` locale.
Sources:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_New_Zealand
"""
license_formats = (
# Old plates
"??%##",
"??%###",
"??%###",
# Three letters since 2002
"A??%##",
"B??%##",
"C??%##",
"D??%##",
"E??%##",
"F??%##",
"G??%##",
"H??%##",
"J??%##",
"K??%##",
"L??%##",
"M??%##",
# After 2018
"N??%##",
)
| Provider |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 200787,
"end": 211953
} | class ____(multi_rv_generic):
r"""Contingency tables from independent samples with fixed marginal sums.
This is the distribution of random tables with given row and column vector
sums. This distribution represents the set of random tables under the null
hypothesis that rows and columns are independent. It is used in hypothesis
tests of independence.
Because of assumed independence, the expected frequency of each table
element can be computed from the row and column sums, so that the
distribution is completely determined by these two vectors.
Methods
-------
logpmf(x)
Log-probability of table `x` to occur in the distribution.
pmf(x)
Probability of table `x` to occur in the distribution.
mean(row, col)
Mean table.
rvs(row, col, size=None, method=None, random_state=None)
Draw random tables with given row and column vector sums.
Parameters
----------
%(_doc_row_col)s
%(_doc_random_state)s
Notes
-----
%(_doc_row_col_note)s
Random elements from the distribution are generated either with Boyett's
[1]_ or Patefield's algorithm [2]_. Boyett's algorithm has
O(N) time and space complexity, where N is the total sum of entries in the
table. Patefield's algorithm has O(K x log(N)) time complexity, where K is
the number of cells in the table and requires only a small constant work
space. By default, the `rvs` method selects the fastest algorithm based on
the input, but you can specify the algorithm with the keyword `method`.
Allowed values are "boyett" and "patefield".
.. versionadded:: 1.10.0
Examples
--------
>>> from scipy.stats import random_table
>>> row = [1, 5]
>>> col = [2, 3, 1]
>>> random_table.mean(row, col)
array([[0.33333333, 0.5 , 0.16666667],
[1.66666667, 2.5 , 0.83333333]])
Alternatively, the object may be called (as a function) to fix the row
and column vector sums, returning a "frozen" distribution.
>>> dist = random_table(row, col)
>>> dist.rvs(random_state=123)
array([[1, 0, 0],
[1, 3, 1]])
References
----------
.. [1] J. Boyett, AS 144 Appl. Statist. 28 (1979) 329-332
.. [2] W.M. Patefield, AS 159 Appl. Statist. 30 (1981) 91-97
"""
def __init__(self, seed=None):
super().__init__(seed)
def __call__(self, row, col, *, seed=None):
"""Create a frozen distribution of tables with given marginals.
See `random_table_frozen` for more information.
"""
return random_table_frozen(row, col, seed=seed)
def logpmf(self, x, row, col):
"""Log-probability of table to occur in the distribution.
Parameters
----------
%(_doc_x)s
%(_doc_row_col)s
Returns
-------
logpmf : ndarray or scalar
Log of the probability mass function evaluated at `x`.
Notes
-----
%(_doc_row_col_note)s
If row and column marginals of `x` do not match `row` and `col`,
negative infinity is returned.
Examples
--------
>>> from scipy.stats import random_table
>>> import numpy as np
>>> x = [[1, 5, 1], [2, 3, 1]]
>>> row = np.sum(x, axis=1)
>>> col = np.sum(x, axis=0)
>>> random_table.logpmf(x, row, col)
-1.6306401200847027
Alternatively, the object may be called (as a function) to fix the row
and column vector sums, returning a "frozen" distribution.
>>> d = random_table(row, col)
>>> d.logpmf(x)
-1.6306401200847027
"""
r, c, n = self._process_parameters(row, col)
x = np.asarray(x)
if x.ndim < 2:
raise ValueError("`x` must be at least two-dimensional")
dtype_is_int = np.issubdtype(x.dtype, np.integer)
with np.errstate(invalid='ignore'):
if not dtype_is_int and not np.all(x.astype(int) == x):
raise ValueError("`x` must contain only integral values")
# x does not contain NaN if we arrive here
if np.any(x < 0):
raise ValueError("`x` must contain only non-negative values")
r2 = np.sum(x, axis=-1)
c2 = np.sum(x, axis=-2)
if r2.shape[-1] != len(r):
raise ValueError("shape of `x` must agree with `row`")
if c2.shape[-1] != len(c):
raise ValueError("shape of `x` must agree with `col`")
res = np.empty(x.shape[:-2])
mask = np.all(r2 == r, axis=-1) & np.all(c2 == c, axis=-1)
def lnfac(x):
return gammaln(x + 1)
res[mask] = (np.sum(lnfac(r), axis=-1) + np.sum(lnfac(c), axis=-1)
- lnfac(n) - np.sum(lnfac(x[mask]), axis=(-1, -2)))
res[~mask] = -np.inf
return res[()]
def pmf(self, x, row, col):
"""Probability of table to occur in the distribution.
Parameters
----------
%(_doc_x)s
%(_doc_row_col)s
Returns
-------
pmf : ndarray or scalar
Probability mass function evaluated at `x`.
Notes
-----
%(_doc_row_col_note)s
If row and column marginals of `x` do not match `row` and `col`,
zero is returned.
Examples
--------
>>> from scipy.stats import random_table
>>> import numpy as np
>>> x = [[1, 5, 1], [2, 3, 1]]
>>> row = np.sum(x, axis=1)
>>> col = np.sum(x, axis=0)
>>> random_table.pmf(x, row, col)
0.19580419580419592
Alternatively, the object may be called (as a function) to fix the row
and column vector sums, returning a "frozen" distribution.
>>> d = random_table(row, col)
>>> d.pmf(x)
0.19580419580419592
"""
return np.exp(self.logpmf(x, row, col))
def mean(self, row, col):
"""Mean of distribution of conditional tables.
%(_doc_mean_params)s
Returns
-------
mean: ndarray
Mean of the distribution.
Notes
-----
%(_doc_row_col_note)s
Examples
--------
>>> from scipy.stats import random_table
>>> row = [1, 5]
>>> col = [2, 3, 1]
>>> random_table.mean(row, col)
array([[0.33333333, 0.5 , 0.16666667],
[1.66666667, 2.5 , 0.83333333]])
Alternatively, the object may be called (as a function) to fix the row
and column vector sums, returning a "frozen" distribution.
>>> d = random_table(row, col)
>>> d.mean()
array([[0.33333333, 0.5 , 0.16666667],
[1.66666667, 2.5 , 0.83333333]])
"""
r, c, n = self._process_parameters(row, col)
return np.outer(r, c) / n
def rvs(self, row, col, *, size=None, method=None, random_state=None):
"""Draw random tables with fixed column and row marginals.
Parameters
----------
%(_doc_row_col)s
size : integer, optional
Number of samples to draw (default 1).
method : str, optional
Which method to use, "boyett" or "patefield". If None (default),
selects the fastest method for this input.
%(_doc_random_state)s
Returns
-------
rvs : ndarray
Random 2D tables of shape (`size`, `len(row)`, `len(col)`).
Notes
-----
%(_doc_row_col_note)s
Examples
--------
>>> from scipy.stats import random_table
>>> row = [1, 5]
>>> col = [2, 3, 1]
>>> random_table.rvs(row, col, random_state=123)
array([[1., 0., 0.],
[1., 3., 1.]])
Alternatively, the object may be called (as a function) to fix the row
and column vector sums, returning a "frozen" distribution.
>>> d = random_table(row, col)
>>> d.rvs(random_state=123)
array([[1., 0., 0.],
[1., 3., 1.]])
"""
r, c, n = self._process_parameters(row, col)
size, shape = self._process_size_shape(size, r, c)
random_state = self._get_random_state(random_state)
meth = self._process_rvs_method(method, r, c, n)
return meth(r, c, n, size, random_state).reshape(shape)
@staticmethod
def _process_parameters(row, col):
"""
Check that row and column vectors are one-dimensional, that they do
not contain negative or non-integer entries, and that the sums over
both vectors are equal.
"""
r = np.array(row, dtype=np.int64, copy=True)
c = np.array(col, dtype=np.int64, copy=True)
if np.ndim(r) != 1:
raise ValueError("`row` must be one-dimensional")
if np.ndim(c) != 1:
raise ValueError("`col` must be one-dimensional")
if np.any(r < 0):
raise ValueError("each element of `row` must be non-negative")
if np.any(c < 0):
raise ValueError("each element of `col` must be non-negative")
n = np.sum(r)
if n != np.sum(c):
raise ValueError("sums over `row` and `col` must be equal")
if not np.all(r == np.asarray(row)):
raise ValueError("each element of `row` must be an integer")
if not np.all(c == np.asarray(col)):
raise ValueError("each element of `col` must be an integer")
return r, c, n
@staticmethod
def _process_size_shape(size, r, c):
"""
Compute the number of samples to be drawn and the shape of the output
"""
shape = (len(r), len(c))
if size is None:
return 1, shape
size = np.atleast_1d(size)
if not np.issubdtype(size.dtype, np.integer) or np.any(size < 0):
raise ValueError("`size` must be a non-negative integer or `None`")
return np.prod(size), tuple(size) + shape
@classmethod
def _process_rvs_method(cls, method, r, c, n):
known_methods = {
None: cls._rvs_select(r, c, n),
"boyett": cls._rvs_boyett,
"patefield": cls._rvs_patefield,
}
try:
return known_methods[method]
except KeyError:
raise ValueError(f"'{method}' not recognized, "
f"must be one of {set(known_methods)}")
@classmethod
def _rvs_select(cls, r, c, n):
fac = 1.0 # benchmarks show that this value is about 1
k = len(r) * len(c) # number of cells
# n + 1 guards against failure if n == 0
if n > fac * np.log(n + 1) * k:
return cls._rvs_patefield
return cls._rvs_boyett
@staticmethod
def _rvs_boyett(row, col, ntot, size, random_state):
return _rcont.rvs_rcont1(row, col, ntot, size, random_state)
@staticmethod
def _rvs_patefield(row, col, ntot, size, random_state):
return _rcont.rvs_rcont2(row, col, ntot, size, random_state)
random_table = random_table_gen()
| random_table_gen |
python | apache__avro | lang/py/avro/datafile.py | {
"start": 2077,
"end": 2178
} | class ____(TypedDict):
magic: bytes
meta: MutableMapping[str, bytes]
sync: bytes
| HeaderType |
python | pandas-dev__pandas | pandas/tests/indexing/test_partial.py | {
"start": 8178,
"end": 24131
} | class ____:
def test_partial_setting(self):
# GH2578, allow ix and friends to partially set
# series
s_orig = Series([1, 2, 3])
s = s_orig.copy()
s[5] = 5
expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
s = s_orig.copy()
s.loc[5] = 5
expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
s = s_orig.copy()
s[5] = 5.0
expected = Series([1, 2, 3, 5.0], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
s = s_orig.copy()
s.loc[5] = 5.0
expected = Series([1, 2, 3, 5.0], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
# iloc/iat raise
s = s_orig.copy()
msg = "iloc cannot enlarge its target object"
with pytest.raises(IndexError, match=msg):
s.iloc[3] = 5.0
msg = "index 3 is out of bounds for axis 0 with size 3"
with pytest.raises(IndexError, match=msg):
s.iat[3] = 5.0
@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning")
def test_partial_setting_frame(self):
df_orig = DataFrame(
np.arange(6).reshape(3, 2), columns=["A", "B"], dtype="int64"
)
# iloc/iat raise
df = df_orig.copy()
msg = "iloc cannot enlarge its target object"
with pytest.raises(IndexError, match=msg):
df.iloc[4, 2] = 5.0
msg = "index 2 is out of bounds for axis 0 with size 2"
with pytest.raises(IndexError, match=msg):
df.iat[4, 2] = 5.0
# row setting where it exists
expected = DataFrame({"A": [0, 4, 4], "B": [1, 5, 5]})
df = df_orig.copy()
df.iloc[1] = df.iloc[2]
tm.assert_frame_equal(df, expected)
expected = DataFrame({"A": [0, 4, 4], "B": [1, 5, 5]})
df = df_orig.copy()
df.loc[1] = df.loc[2]
tm.assert_frame_equal(df, expected)
# like 2578, partial setting with dtype preservation
expected = DataFrame({"A": [0, 2, 4, 4], "B": [1, 3, 5, 5]})
df = df_orig.copy()
df.loc[3] = df.loc[2]
tm.assert_frame_equal(df, expected)
# single dtype frame, overwrite
expected = DataFrame({"A": [0, 2, 4], "B": [0, 2, 4]})
df = df_orig.copy()
df.loc[:, "B"] = df.loc[:, "A"]
tm.assert_frame_equal(df, expected)
# mixed dtype frame, overwrite
expected = DataFrame({"A": [0, 2, 4], "B": Series([0.0, 2.0, 4.0])})
df = df_orig.copy()
df["B"] = df["B"].astype(np.float64)
# as of 2.0, df.loc[:, "B"] = ... attempts (and here succeeds) at
# setting inplace
df.loc[:, "B"] = df.loc[:, "A"]
tm.assert_frame_equal(df, expected)
# single dtype frame, partial setting
expected = df_orig.copy()
expected["C"] = df["A"]
df = df_orig.copy()
df.loc[:, "C"] = df.loc[:, "A"]
tm.assert_frame_equal(df, expected)
# mixed frame, partial setting
expected = df_orig.copy()
expected["C"] = df["A"]
df = df_orig.copy()
df.loc[:, "C"] = df.loc[:, "A"]
tm.assert_frame_equal(df, expected)
def test_partial_setting2(self):
# GH 8473
dates = date_range("1/1/2000", periods=8)
df_orig = DataFrame(
np.random.default_rng(2).standard_normal((8, 4)),
index=dates,
columns=["A", "B", "C", "D"],
)
expected = pd.concat(
[df_orig, DataFrame({"A": 7}, index=dates[-1:] + dates.freq)], sort=True
)
df = df_orig.copy()
df.loc[dates[-1] + dates.freq, "A"] = 7
tm.assert_frame_equal(df, expected)
df = df_orig.copy()
df.at[dates[-1] + dates.freq, "A"] = 7
tm.assert_frame_equal(df, expected)
exp_other = DataFrame({0: 7}, index=dates[-1:] + dates.freq)
expected = pd.concat([df_orig, exp_other], axis=1)
df = df_orig.copy()
df.loc[dates[-1] + dates.freq, 0] = 7
tm.assert_frame_equal(df, expected)
df = df_orig.copy()
df.at[dates[-1] + dates.freq, 0] = 7
tm.assert_frame_equal(df, expected)
def test_partial_setting_mixed_dtype(self):
# in a mixed dtype environment, try to preserve dtypes
# by appending
df = DataFrame([[True, 1], [False, 2]], columns=["female", "fitness"])
s = df.loc[1].copy()
s.name = 2
expected = pd.concat([df, DataFrame(s).T.infer_objects()])
df.loc[2] = df.loc[1]
tm.assert_frame_equal(df, expected)
def test_series_partial_set(self):
# partial set with new index
# Regression from GH4825
ser = Series([0.1, 0.2], index=[1, 2])
# loc equiv to .reindex
expected = Series([np.nan, 0.2, np.nan], index=[3, 2, 3])
with pytest.raises(KeyError, match=r"not in index"):
ser.loc[[3, 2, 3]]
result = ser.reindex([3, 2, 3])
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([np.nan, 0.2, np.nan, np.nan], index=[3, 2, 3, "x"])
with pytest.raises(KeyError, match="not in index"):
ser.loc[[3, 2, 3, "x"]]
result = ser.reindex([3, 2, 3, "x"])
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([0.2, 0.2, 0.1], index=[2, 2, 1])
result = ser.loc[[2, 2, 1]]
tm.assert_series_equal(result, expected, check_index_type=True)
expected = Series([0.2, 0.2, np.nan, 0.1], index=[2, 2, "x", 1])
with pytest.raises(KeyError, match="not in index"):
ser.loc[[2, 2, "x", 1]]
result = ser.reindex([2, 2, "x", 1])
tm.assert_series_equal(result, expected, check_index_type=True)
# raises as nothing is in the index
msg = (
rf"\"None of \[Index\(\[3, 3, 3\], dtype='{np.dtype(int)}'\)\] "
r"are in the \[index\]\""
)
with pytest.raises(KeyError, match=msg):
ser.loc[[3, 3, 3]]
expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3])
with pytest.raises(KeyError, match="not in index"):
ser.loc[[2, 2, 3]]
result = ser.reindex([2, 2, 3])
tm.assert_series_equal(result, expected, check_index_type=True)
s = Series([0.1, 0.2, 0.3], index=[1, 2, 3])
expected = Series([0.3, np.nan, np.nan], index=[3, 4, 4])
with pytest.raises(KeyError, match="not in index"):
s.loc[[3, 4, 4]]
result = s.reindex([3, 4, 4])
tm.assert_series_equal(result, expected, check_index_type=True)
s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4])
expected = Series([np.nan, 0.3, 0.3], index=[5, 3, 3])
with pytest.raises(KeyError, match="not in index"):
s.loc[[5, 3, 3]]
result = s.reindex([5, 3, 3])
tm.assert_series_equal(result, expected, check_index_type=True)
s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4])
expected = Series([np.nan, 0.4, 0.4], index=[5, 4, 4])
with pytest.raises(KeyError, match="not in index"):
s.loc[[5, 4, 4]]
result = s.reindex([5, 4, 4])
tm.assert_series_equal(result, expected, check_index_type=True)
s = Series([0.1, 0.2, 0.3, 0.4], index=[4, 5, 6, 7])
expected = Series([0.4, np.nan, np.nan], index=[7, 2, 2])
with pytest.raises(KeyError, match="not in index"):
s.loc[[7, 2, 2]]
result = s.reindex([7, 2, 2])
tm.assert_series_equal(result, expected, check_index_type=True)
s = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4])
expected = Series([0.4, np.nan, np.nan], index=[4, 5, 5])
with pytest.raises(KeyError, match="not in index"):
s.loc[[4, 5, 5]]
result = s.reindex([4, 5, 5])
tm.assert_series_equal(result, expected, check_index_type=True)
# iloc
expected = Series([0.2, 0.2, 0.1, 0.1], index=[2, 2, 1, 1])
result = ser.iloc[[1, 1, 0, 0]]
tm.assert_series_equal(result, expected, check_index_type=True)
def test_series_partial_set_with_name(self):
# GH 11497
idx = Index([1, 2], dtype="int64", name="idx")
ser = Series([0.1, 0.2], index=idx, name="s")
# loc
with pytest.raises(KeyError, match=r"\[3\] not in index"):
ser.loc[[3, 2, 3]]
with pytest.raises(KeyError, match=r"not in index"):
ser.loc[[3, 2, 3, "x"]]
exp_idx = Index([2, 2, 1], dtype="int64", name="idx")
expected = Series([0.2, 0.2, 0.1], index=exp_idx, name="s")
result = ser.loc[[2, 2, 1]]
tm.assert_series_equal(result, expected, check_index_type=True)
with pytest.raises(KeyError, match=r"\['x'\] not in index"):
ser.loc[[2, 2, "x", 1]]
# raises as nothing is in the index
msg = (
rf"\"None of \[Index\(\[3, 3, 3\], dtype='{np.dtype(int)}', "
r"name='idx'\)\] are in the \[index\]\""
)
with pytest.raises(KeyError, match=msg):
ser.loc[[3, 3, 3]]
with pytest.raises(KeyError, match="not in index"):
ser.loc[[2, 2, 3]]
idx = Index([1, 2, 3], dtype="int64", name="idx")
with pytest.raises(KeyError, match="not in index"):
Series([0.1, 0.2, 0.3], index=idx, name="s").loc[[3, 4, 4]]
idx = Index([1, 2, 3, 4], dtype="int64", name="idx")
with pytest.raises(KeyError, match="not in index"):
Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[5, 3, 3]]
idx = Index([1, 2, 3, 4], dtype="int64", name="idx")
with pytest.raises(KeyError, match="not in index"):
Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[5, 4, 4]]
idx = Index([4, 5, 6, 7], dtype="int64", name="idx")
with pytest.raises(KeyError, match="not in index"):
Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[7, 2, 2]]
idx = Index([1, 2, 3, 4], dtype="int64", name="idx")
with pytest.raises(KeyError, match="not in index"):
Series([0.1, 0.2, 0.3, 0.4], index=idx, name="s").loc[[4, 5, 5]]
# iloc
exp_idx = Index([2, 2, 1, 1], dtype="int64", name="idx")
expected = Series([0.2, 0.2, 0.1, 0.1], index=exp_idx, name="s")
result = ser.iloc[[1, 1, 0, 0]]
tm.assert_series_equal(result, expected, check_index_type=True)
@pytest.mark.parametrize("key", [100, 100.0])
def test_setitem_with_expansion_numeric_into_datetimeindex(self, key):
# GH#4940 inserting non-strings
orig = DataFrame(
np.random.default_rng(2).standard_normal((10, 4)),
columns=Index(list("ABCD"), dtype=object),
index=date_range("2000-01-01", periods=10, freq="B"),
)
df = orig.copy()
df.loc[key, :] = df.iloc[0]
ex_index = Index(list(orig.index) + [key], dtype=object, name=orig.index.name)
ex_data = np.concatenate([orig.values, df.iloc[[0]].values], axis=0)
expected = DataFrame(ex_data, index=ex_index, columns=orig.columns)
tm.assert_frame_equal(df, expected)
def test_partial_set_invalid(self):
# GH 4940
# allow only setting of 'valid' values
orig = DataFrame(
np.random.default_rng(2).standard_normal((10, 4)),
columns=Index(list("ABCD"), dtype=object),
index=date_range("2000-01-01", periods=10, freq="B"),
)
# allow object conversion here
df = orig.copy()
df.loc["a", :] = df.iloc[0]
ser = Series(df.iloc[0], name="a")
exp = pd.concat([orig, DataFrame(ser).T.infer_objects()])
tm.assert_frame_equal(df, exp)
tm.assert_index_equal(df.index, Index(orig.index.tolist() + ["a"]))
assert df.index.dtype == "object"
@pytest.mark.parametrize(
"idx,labels,expected_idx",
[
(
period_range(start="2000", periods=20, freq="D"),
["2000-01-04", "2000-01-08", "2000-01-12"],
[
Period("2000-01-04", freq="D"),
Period("2000-01-08", freq="D"),
Period("2000-01-12", freq="D"),
],
),
(
date_range(start="2000", periods=20, freq="D", unit="s"),
["2000-01-04", "2000-01-08", "2000-01-12"],
[
Timestamp("2000-01-04").as_unit("s"),
Timestamp("2000-01-08").as_unit("s"),
Timestamp("2000-01-12").as_unit("s"),
],
),
(
pd.timedelta_range(start="1 day", periods=20),
["4D", "8D", "12D"],
[pd.Timedelta("4 day"), pd.Timedelta("8 day"), pd.Timedelta("12 day")],
),
],
)
def test_loc_with_list_of_strings_representing_datetimes(
self, idx, labels, expected_idx, frame_or_series
):
# GH 11278
obj = frame_or_series(range(20), index=idx)
expected_value = [3, 7, 11]
expected = frame_or_series(expected_value, expected_idx)
tm.assert_equal(expected, obj.loc[labels])
if frame_or_series is Series:
tm.assert_series_equal(expected, obj[labels])
@pytest.mark.parametrize(
"idx,labels",
[
(
period_range(start="2000", periods=20, freq="D"),
["2000-01-04", "2000-01-30"],
),
(
date_range(start="2000", periods=20, freq="D"),
["2000-01-04", "2000-01-30"],
),
(pd.timedelta_range(start="1 day", periods=20), ["3 day", "30 day"]),
],
)
def test_loc_with_list_of_strings_representing_datetimes_missing_value(
self, idx, labels
):
# GH 11278
ser = Series(range(20), index=idx)
df = DataFrame(range(20), index=idx)
msg = r"not in index"
with pytest.raises(KeyError, match=msg):
ser.loc[labels]
with pytest.raises(KeyError, match=msg):
ser[labels]
with pytest.raises(KeyError, match=msg):
df.loc[labels]
@pytest.mark.parametrize(
"idx,labels,msg",
[
(
period_range(start="2000", periods=20, freq="D"),
Index(["4D", "8D"], dtype=object),
(
r"None of \[Index\(\['4D', '8D'\], dtype='object'\)\] "
r"are in the \[index\]"
),
),
(
date_range(start="2000", periods=20, freq="D"),
Index(["4D", "8D"], dtype=object),
(
r"None of \[Index\(\['4D', '8D'\], dtype='object'\)\] "
r"are in the \[index\]"
),
),
(
pd.timedelta_range(start="1 day", periods=20),
Index(["2000-01-04", "2000-01-08"], dtype=object),
(
r"None of \[Index\(\['2000-01-04', '2000-01-08'\], "
r"dtype='object'\)\] are in the \[index\]"
),
),
],
)
def test_loc_with_list_of_strings_representing_datetimes_not_matched_type(
self, idx, labels, msg
):
# GH 11278
ser = Series(range(20), index=idx)
df = DataFrame(range(20), index=idx)
with pytest.raises(KeyError, match=msg):
ser.loc[labels]
with pytest.raises(KeyError, match=msg):
ser[labels]
with pytest.raises(KeyError, match=msg):
df.loc[labels]
| TestPartialSetting |
python | realpython__materials | python-protocol/birds_v1.py | {
"start": 0,
"end": 138
} | class ____:
def quack(self):
return "The duck is quacking!"
def make_it_quack(duck: Duck) -> str:
return duck.quack()
| Duck |
python | doocs__leetcode | solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.py | {
"start": 1180,
"end": 1539
} | class ____:
def countSmaller(self, nums: List[int]) -> List[int]:
s = sorted(set(nums))
m = {v: i for i, v in enumerate(s, 1)}
tree = SegmentTree(len(s))
ans = []
for v in nums[::-1]:
x = m[v]
ans.append(tree.query(1, 1, x - 1))
tree.modify(1, x, 1)
return ans[::-1]
| Solution |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/serializers/group_open_period_serializer.py | {
"start": 1333,
"end": 2682
} | class ____(Serializer):
def get_attrs(self, item_list, user, **kwargs):
result: defaultdict[GroupOpenPeriod, dict[str, list[GroupOpenPeriodActivityResponse]]] = (
defaultdict(dict)
)
activities = GroupOpenPeriodActivity.objects.filter(
group_open_period__in=item_list
).order_by("id")
gopas = defaultdict(list)
for activity, serialized_activity in zip(
activities, serialize(list(activities), user=user, **kwargs)
):
gopas[activity.group_open_period].append(serialized_activity)
for item in item_list:
result[item]["activities"] = gopas[item][:100]
return result
def serialize(
self, obj: GroupOpenPeriod, attrs: Mapping[str, Any], user, **kwargs
) -> GroupOpenPeriodResponse:
time_window = kwargs.get("time_window", 0)
return GroupOpenPeriodResponse(
id=str(obj.id),
start=calculate_event_date_from_update_date(obj.date_started, time_window),
end=(
calculate_event_date_from_update_date(obj.date_ended, time_window)
if obj.date_ended is not None
else None
),
isOpen=obj.date_ended is None,
activities=attrs.get("activities"),
)
| GroupOpenPeriodSerializer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_blank05.py | {
"start": 315,
"end": 1514
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_blank05.xlsx")
self.ignore_elements = {"xl/drawings/drawing1.xml": ["<xdr:ext"]}
def test_create_file(self):
"""Test the worksheet properties of an XlsxWriter chartsheet file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chartsheet = workbook.add_chartsheet()
chart = workbook.add_chart({"type": "line"})
chart.axis_ids = [57619968, 57621504]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart.show_blanks_as("span")
chartsheet.set_chart(chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | getlogbook__logbook | src/logbook/more.py | {
"start": 13937,
"end": 14822
} | class ____(Handler, StringFormatterHandlerMixin):
"""An exception handler which raises exceptions of the given `exc_type`.
This is especially useful if you set a specific error `level` e.g. to treat
warnings as exceptions::
from logbook.more import ExceptionHandler
class ApplicationWarning(Exception):
pass
exc_handler = ExceptionHandler(ApplicationWarning, level="WARNING")
.. versionadded:: 0.3
"""
def __init__(
self, exc_type, level=NOTSET, format_string=None, filter=None, bubble=False
):
Handler.__init__(self, level, filter, bubble)
StringFormatterHandlerMixin.__init__(self, format_string)
self.exc_type = exc_type
def handle(self, record):
if self.should_handle(record):
raise self.exc_type(self.format(record))
return False
| ExceptionHandler |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 147636,
"end": 148305
} | class ____:
"""
A mock storage class that simulates pulling code from a remote location.
"""
def __init__(self):
self._base_path = Path.cwd()
def set_base_path(self, path: Path):
self._base_path = path
@property
def destination(self):
return self._base_path
@property
def pull_interval(self):
return 60
async def pull_code(self):
code = """
from prefect import Flow
@Flow
def test_flow():
return 1
"""
if self._base_path:
with open(self._base_path / "flows.py", "w") as f:
f.write(code)
def to_pull_step(self):
return {}
| MockStorage |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 442325,
"end": 443073
} | class ____(ExprNode):
# CyFunction's literal argument default value
#
# Evaluate literal only once.
subexprs = []
is_literal = True
is_temp = False
def __init__(self, pos, arg):
super().__init__(pos)
self.arg = arg
self.constant_result = arg.constant_result
self.type = self.arg.type
self.evaluated = False
def analyse_types(self, env):
return self
def generate_result_code(self, code):
pass
def generate_evaluation_code(self, code):
if not self.evaluated:
self.arg.generate_evaluation_code(code)
self.evaluated = True
def result(self):
return self.type.cast_code(self.arg.result())
| DefaultLiteralArgNode |
python | django__django | tests/migrations/test_migrations_conflict/0002_conflicting_second.py | {
"start": 43,
"end": 316
} | class ____(migrations.Migration):
dependencies = [("migrations", "0001_initial")]
operations = [
migrations.CreateModel(
"Something",
[
("id", models.AutoField(primary_key=True)),
],
)
]
| Migration |
python | huggingface__transformers | src/transformers/models/prompt_depth_anything/configuration_prompt_depth_anything.py | {
"start": 1436,
"end": 8090
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PromptDepthAnythingModel`]. It is used to instantiate a PromptDepthAnything
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the PromptDepthAnything
[LiheYoung/depth-anything-small-hf](https://huggingface.co/LiheYoung/depth-anything-small-hf) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
backbone_config (`Union[dict[str, Any], PreTrainedConfig]`, *optional*):
The configuration of the backbone model. Only used in case `is_hybrid` is `True` or in case you want to
leverage the [`AutoBackbone`] API.
backbone (`str`, *optional*):
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
Whether to use pretrained weights for the backbone.
use_timm_backbone (`bool`, *optional*, defaults to `False`):
Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
API.
backbone_kwargs (`dict`, *optional*):
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
patch_size (`int`, *optional*, defaults to 14):
The size of the patches to extract from the backbone features.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
reassemble_hidden_size (`int`, *optional*, defaults to 384):
The number of input channels of the reassemble layers.
reassemble_factors (`list[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
The up/downsampling factors of the reassemble layers.
neck_hidden_sizes (`list[str]`, *optional*, defaults to `[48, 96, 192, 384]`):
The hidden sizes to project to for the feature maps of the backbone.
fusion_hidden_size (`int`, *optional*, defaults to 64):
The number of channels before fusion.
head_in_index (`int`, *optional*, defaults to -1):
The index of the features to use in the depth estimation head.
head_hidden_size (`int`, *optional*, defaults to 32):
The number of output channels in the second convolution of the depth estimation head.
depth_estimation_type (`str`, *optional*, defaults to `"relative"`):
The type of depth estimation to use. Can be one of `["relative", "metric"]`.
max_depth (`float`, *optional*):
The maximum depth to use for the "metric" depth estimation head. 20 should be used for indoor models
and 80 for outdoor models. For "relative" depth estimation, this value is ignored.
Example:
```python
>>> from transformers import PromptDepthAnythingConfig, PromptDepthAnythingForDepthEstimation
>>> # Initializing a PromptDepthAnything small style configuration
>>> configuration = PromptDepthAnythingConfig()
>>> # Initializing a model from the PromptDepthAnything small style configuration
>>> model = PromptDepthAnythingForDepthEstimation(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "prompt_depth_anything"
sub_configs = {"backbone_config": AutoConfig}
def __init__(
self,
backbone_config=None,
backbone=None,
use_pretrained_backbone=False,
use_timm_backbone=False,
backbone_kwargs=None,
patch_size=14,
initializer_range=0.02,
reassemble_hidden_size=384,
reassemble_factors=[4, 2, 1, 0.5],
neck_hidden_sizes=[48, 96, 192, 384],
fusion_hidden_size=64,
head_in_index=-1,
head_hidden_size=32,
depth_estimation_type="relative",
max_depth=None,
**kwargs,
):
if backbone_config is None and backbone is None:
logger.info("`backbone_config` is `None`. Initializing the config with the default `Dinov2` backbone.")
backbone_config = CONFIG_MAPPING["dinov2"](
image_size=518,
hidden_size=384,
num_attention_heads=6,
out_indices=[9, 10, 11, 12],
apply_layernorm=True,
reshape_hidden_states=False,
)
elif isinstance(backbone_config, dict):
backbone_model_type = backbone_config.get("model_type")
config_class = CONFIG_MAPPING[backbone_model_type]
backbone_config = config_class.from_dict(backbone_config)
verify_backbone_config_arguments(
use_timm_backbone=use_timm_backbone,
use_pretrained_backbone=use_pretrained_backbone,
backbone=backbone,
backbone_config=backbone_config,
backbone_kwargs=backbone_kwargs,
)
self.backbone_config = backbone_config
self.backbone = backbone
self.use_pretrained_backbone = use_pretrained_backbone
self.use_timm_backbone = use_timm_backbone
self.backbone_kwargs = backbone_kwargs
self.reassemble_hidden_size = reassemble_hidden_size
self.patch_size = patch_size
self.initializer_range = initializer_range
self.reassemble_factors = reassemble_factors
self.neck_hidden_sizes = neck_hidden_sizes
self.fusion_hidden_size = fusion_hidden_size
self.head_in_index = head_in_index
self.head_hidden_size = head_hidden_size
if depth_estimation_type not in ["relative", "metric"]:
raise ValueError("depth_estimation_type must be one of ['relative', 'metric']")
self.depth_estimation_type = depth_estimation_type
self.max_depth = max_depth if max_depth else 1
super().__init__(**kwargs)
__all__ = ["PromptDepthAnythingConfig"]
| PromptDepthAnythingConfig |
python | pandas-dev__pandas | pandas/tseries/holiday.py | {
"start": 18885,
"end": 20445
} | class ____(AbstractHolidayCalendar):
"""
US Federal Government Holiday Calendar based on rules specified by:
https://www.opm.gov/policy-data-oversight/pay-leave/federal-holidays/
"""
rules = [
Holiday("New Year's Day", month=1, day=1, observance=nearest_workday),
USMartinLutherKingJr,
USPresidentsDay,
USMemorialDay,
Holiday(
"Juneteenth National Independence Day",
month=6,
day=19,
start_date="2021-06-18",
observance=nearest_workday,
),
Holiday("Independence Day", month=7, day=4, observance=nearest_workday),
USLaborDay,
USColumbusDay,
Holiday("Veterans Day", month=11, day=11, observance=nearest_workday),
USThanksgivingDay,
Holiday("Christmas Day", month=12, day=25, observance=nearest_workday),
]
def HolidayCalendarFactory(name: str, base, other, base_class=AbstractHolidayCalendar):
rules = AbstractHolidayCalendar.merge_class(base, other)
calendar_class = type(name, (base_class,), {"rules": rules, "name": name})
return calendar_class
__all__ = [
"FR",
"MO",
"SA",
"SU",
"TH",
"TU",
"WE",
"HolidayCalendarFactory",
"after_nearest_workday",
"before_nearest_workday",
"get_calendar",
"nearest_workday",
"next_monday",
"next_monday_or_tuesday",
"next_workday",
"previous_friday",
"previous_workday",
"register",
"sunday_to_monday",
"weekend_to_monday",
]
| USFederalHolidayCalendar |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 1400,
"end": 1499
} | class ____(BaseModel):
file_id: str
index: int
type: str = "file_path"
| AnnotationFilePath |
python | jazzband__django-polymorphic | src/polymorphic/showfields.py | {
"start": 5709,
"end": 5876
} | class ____(ShowFieldBase):
"""model mixin that shows the object's class, it's fields and field contents"""
polymorphic_showfield_content = True
| ShowFieldContent |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_indiana_zip.py | {
"start": 1743,
"end": 4078
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Indiana zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"valid_indiana_zip": ["46050", "46262", "46856", "47167"],
"invalid_indiana_zip": ["-10000", "1234", "99999", "25487"],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "valid_indiana_zip"},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "invalid_indiana_zip"},
"out": {"success": False},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_indiana_zip"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental", # "experimental", "beta", or "production"
"tags": [
"hackathon",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@luismdiaz01",
"@derekma73", # Don't forget to add your github handle here!
],
"requirements": ["zipcodes"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidIndianaZip().print_diagnostic_checklist()
| ExpectColumnValuesToBeValidIndianaZip |
python | openai__openai-python | src/openai/types/beta/thread_create_and_run_params.py | {
"start": 7071,
"end": 7355
} | class ____(TypedDict, total=False):
type: Required[Literal["file_search"]]
"""The type of tool being defined: `file_search`"""
ThreadMessageAttachmentTool: TypeAlias = Union[CodeInterpreterToolParam, ThreadMessageAttachmentToolFileSearch]
| ThreadMessageAttachmentToolFileSearch |
python | ansible__ansible | lib/ansible/plugins/httpapi/__init__.py | {
"start": 230,
"end": 3093
} | class ____(AnsiblePlugin):
def __init__(self, connection):
super(HttpApiBase, self).__init__()
self.connection = connection
self._become = False
self._become_pass = ''
def set_become(self, become_context):
self._become = become_context.become
self._become_pass = getattr(become_context, 'become_pass') or ''
def login(self, username, password):
"""Call a defined login endpoint to receive an authentication token.
This should only be implemented if the API has a single endpoint which
can turn HTTP basic auth into a token which can be reused for the rest
of the calls for the session.
"""
pass
def logout(self):
""" Call to implement session logout.
Method to clear session gracefully e.g. tokens granted in login
need to be revoked.
"""
pass
def update_auth(self, response, response_text):
"""Return per-request auth token.
The response should be a dictionary that can be plugged into the
headers of a request. The default implementation uses cookie data.
If no authentication data is found, return None
"""
cookie = response.info().get('Set-Cookie')
if cookie:
return {'Cookie': cookie}
return None
def handle_httperror(self, exc):
"""Overridable method for dealing with HTTP codes.
This method will attempt to handle known cases of HTTP status codes.
If your API uses status codes to convey information in a regular way,
you can override this method to handle it appropriately.
:returns:
* True if the code has been handled in a way that the request
may be resent without changes.
* False if the error cannot be handled or recovered from by the
plugin. This will result in the HTTPError being raised as an
exception for the caller to deal with as appropriate (most likely
by failing).
* Any other value returned is taken as a valid response from the
server without making another request. In many cases, this can just
be the original exception.
"""
if exc.code == 401:
if self.connection._auth:
# Stored auth appears to be invalid, clear and retry
self.connection._auth = None
self.login(self.connection.get_option('remote_user'), self.connection.get_option('password'))
return True
else:
# Unauthorized and there's no token. Return an error
return False
return exc
@abstractmethod
def send_request(self, data, **message_kwargs):
"""Prepares and sends request(s) to device."""
pass
| HttpApiBase |
python | wandb__wandb | wandb/vendor/pygments/lexers/j.py | {
"start": 415,
"end": 4525
} | class ____(RegexLexer):
"""
For `J <http://jsoftware.com/>`_ source code.
.. versionadded:: 2.1
"""
name = 'J'
aliases = ['j']
filenames = ['*.ijs']
mimetypes = ['text/x-j']
validName = r'\b[a-zA-Z]\w*'
tokens = {
'root': [
# Shebang script
(r'#!.*$', Comment.Preproc),
# Comments
(r'NB\..*', Comment.Single),
(r'\n+\s*Note', Comment.Multiline, 'comment'),
(r'\s*Note.*', Comment.Single),
# Whitespace
(r'\s+', Text),
# Strings
(r"'", String, 'singlequote'),
# Definitions
(r'0\s+:\s*0|noun\s+define\s*$', Name.Entity, 'nounDefinition'),
(r'(([1-4]|13)\s+:\s*0|(adverb|conjunction|dyad|monad|verb)\s+define)\b',
Name.Function, 'explicitDefinition'),
# Flow Control
(words(('for_', 'goto_', 'label_'), suffix=validName+'\.'), Name.Label),
(words((
'assert', 'break', 'case', 'catch', 'catchd',
'catcht', 'continue', 'do', 'else', 'elseif',
'end', 'fcase', 'for', 'if', 'return',
'select', 'throw', 'try', 'while', 'whilst',
), suffix='\.'), Name.Label),
# Variable Names
(validName, Name.Variable),
# Standard Library
(words((
'ARGV', 'CR', 'CRLF', 'DEL', 'Debug',
'EAV', 'EMPTY', 'FF', 'JVERSION', 'LF',
'LF2', 'Note', 'TAB', 'alpha17', 'alpha27',
'apply', 'bind', 'boxopen', 'boxxopen', 'bx',
'clear', 'cutLF', 'cutopen', 'datatype', 'def',
'dfh', 'drop', 'each', 'echo', 'empty',
'erase', 'every', 'evtloop', 'exit', 'expand',
'fetch', 'file2url', 'fixdotdot', 'fliprgb', 'getargs',
'getenv', 'hfd', 'inv', 'inverse', 'iospath',
'isatty', 'isutf8', 'items', 'leaf', 'list',
'nameclass', 'namelist', 'names', 'nc',
'nl', 'on', 'pick', 'rows',
'script', 'scriptd', 'sign', 'sminfo', 'smoutput',
'sort', 'split', 'stderr', 'stdin', 'stdout',
'table', 'take', 'timespacex', 'timex', 'tmoutput',
'toCRLF', 'toHOST', 'toJ', 'tolower', 'toupper',
'type', 'ucp', 'ucpcount', 'usleep', 'utf8',
'uucp',
)), Name.Function),
# Copula
(r'=[.:]', Operator),
# Builtins
(r'[-=+*#$%@!~`^&";:.,<>{}\[\]\\|/]', Operator),
# Short Keywords
(r'[abCdDeEfHiIjLMoprtT]\.', Keyword.Reserved),
(r'[aDiLpqsStux]\:', Keyword.Reserved),
(r'(_[0-9])\:', Keyword.Constant),
# Parens
(r'\(', Punctuation, 'parentheses'),
# Numbers
include('numbers'),
],
'comment': [
(r'[^)]', Comment.Multiline),
(r'^\)', Comment.Multiline, '#pop'),
(r'[)]', Comment.Multiline),
],
'explicitDefinition': [
(r'\b[nmuvxy]\b', Name.Decorator),
include('root'),
(r'[^)]', Name),
(r'^\)', Name.Label, '#pop'),
(r'[)]', Name),
],
'numbers': [
(r'\b_{1,2}\b', Number),
(r'_?\d+(\.\d+)?(\s*[ejr]\s*)_?\d+(\.?=\d+)?', Number),
(r'_?\d+\.(?=\d+)', Number.Float),
(r'_?\d+x', Number.Integer.Long),
(r'_?\d+', Number.Integer),
],
'nounDefinition': [
(r'[^)]', String),
(r'^\)', Name.Label, '#pop'),
(r'[)]', String),
],
'parentheses': [
(r'\)', Punctuation, '#pop'),
# include('nounDefinition'),
include('explicitDefinition'),
include('root'),
],
'singlequote': [
(r"[^']", String),
(r"''", String),
(r"'", String, '#pop'),
],
}
| JLexer |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 119168,
"end": 121694
} | class ____(
fixtures.TestBase, AssertsCompiledSQL, AssertsExecutionResults
):
__only_on__ = "postgresql"
__backend__ = True
def test_timestamp(self, connection):
s = select(text("timestamp '2007-12-25'"))
result = connection.execute(s).first()
eq_(result[0], datetime.datetime(2007, 12, 25, 0, 0))
def test_interval_arithmetic(self, connection):
# basically testing that we get timedelta back for an INTERVAL
# result. more of a driver assertion.
s = select(text("timestamp '2007-12-25' - timestamp '2007-11-15'"))
result = connection.execute(s).first()
eq_(result[0], datetime.timedelta(40))
def test_interval_coercion(self):
expr = column("bar", postgresql.INTERVAL) + column("foo", types.Date)
eq_(expr.type._type_affinity, types.DateTime)
expr = operators.null_op(
column("bar", postgresql.INTERVAL), column("foo", types.Numeric)
)
eq_(expr.type._type_affinity, types.Interval)
assert isinstance(expr.type, postgresql.INTERVAL)
def test_interval_coercion_literal(self):
expr = column("bar", postgresql.INTERVAL) == datetime.timedelta(days=1)
eq_(expr.right.type._type_affinity, types.Interval)
def test_interval_literal_processor(self, connection):
stmt = text("select :parameter - :parameter2")
result = connection.execute(
stmt.bindparams(
bindparam(
"parameter",
datetime.timedelta(days=1, minutes=3, seconds=4),
literal_execute=True,
),
bindparam(
"parameter2",
datetime.timedelta(days=0, minutes=1, seconds=4),
literal_execute=True,
),
)
).one()
eq_(result[0], datetime.timedelta(days=1, seconds=120))
@testing.combinations(
(
text("select :parameter").bindparams(
parameter=datetime.timedelta(days=2)
),
("select make_interval(secs=>172800.0)"),
),
(
text("select :parameter").bindparams(
parameter=datetime.timedelta(days=730, seconds=2323213392),
),
("select make_interval(secs=>2386285392.0)"),
),
)
def test_interval_literal_processor_compiled(self, type_, expected):
self.assert_compile(type_, expected, literal_binds=True)
| TimestampTest |
python | python__mypy | mypy/main.py | {
"start": 13017,
"end": 14884
} | class ____(argparse.ArgumentParser):
"""Override ArgumentParser methods that use sys.stdout/sys.stderr directly.
This is needed because hijacking sys.std* is not thread-safe,
yet output must be captured to properly support mypy.api.run.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
self.stdout = kwargs.pop("stdout", sys.stdout)
self.stderr = kwargs.pop("stderr", sys.stderr)
super().__init__(*args, **kwargs)
# =====================
# Help-printing methods
# =====================
def print_usage(self, file: SupportsWrite[str] | None = None) -> None:
if file is None:
file = self.stdout
self._print_message(self.format_usage(), file)
def print_help(self, file: SupportsWrite[str] | None = None) -> None:
if file is None:
file = self.stdout
self._print_message(self.format_help(), file)
def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None:
if message:
if file is None:
file = self.stderr
file.write(message)
# ===============
# Exiting methods
# ===============
def exit(self, status: int = 0, message: str | None = None) -> NoReturn:
if message:
self._print_message(message, self.stderr)
sys.exit(status)
def error(self, message: str) -> NoReturn:
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(self.stderr)
args = {"prog": self.prog, "message": message}
self.exit(2, gettext("%(prog)s: error: %(message)s\n") % args)
| CapturableArgumentParser |
python | great-expectations__great_expectations | great_expectations/metrics/column/values_match_regex_values.py | {
"start": 201,
"end": 418
} | class ____(ColumnMetric[ColumnValuesMatchRegexValuesResult]):
"""List of values in a column that match a regex"""
name = "column_values.match_regex"
regex: str
limit: int = 20
| ColumnValuesMatchRegexValues |
python | ansible__ansible | test/units/plugins/action/test_action.py | {
"start": 2720,
"end": 3019
} | class ____(ActionBase):
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=None):
# We're not testing the plugin run() method, just the helper
# methods ActionBase defines
return super(DerivedActionBase, self).run(tmp=tmp, task_vars=task_vars)
| DerivedActionBase |
python | tensorflow__tensorflow | tensorflow/python/keras/testing_utils.py | {
"start": 17149,
"end": 18712
} | class ____(models.Model):
"""A subclass model small MLP that uses a custom build method."""
def __init__(self, num_hidden, num_classes):
super(_SmallSubclassMLPCustomBuild, self).__init__()
self.layer_a = None
self.layer_b = None
self.num_hidden = num_hidden
self.num_classes = num_classes
def build(self, input_shape):
self.layer_a = layers.Dense(self.num_hidden, activation='relu')
activation = 'sigmoid' if self.num_classes == 1 else 'softmax'
self.layer_b = layers.Dense(self.num_classes, activation=activation)
def call(self, inputs, **kwargs):
x = self.layer_a(inputs)
return self.layer_b(x)
def get_small_subclass_mlp(num_hidden, num_classes):
return SmallSubclassMLP(num_hidden, num_classes)
def get_small_subclass_mlp_with_custom_build(num_hidden, num_classes):
return _SmallSubclassMLPCustomBuild(num_hidden, num_classes)
def get_small_mlp(num_hidden, num_classes, input_dim):
"""Get a small mlp of the model type specified by `get_model_type`."""
model_type = get_model_type()
if model_type == 'subclass':
return get_small_subclass_mlp(num_hidden, num_classes)
if model_type == 'subclass_custom_build':
return get_small_subclass_mlp_with_custom_build(num_hidden, num_classes)
if model_type == 'sequential':
return get_small_sequential_mlp(num_hidden, num_classes, input_dim)
if model_type == 'functional':
return get_small_functional_mlp(num_hidden, num_classes, input_dim)
raise ValueError('Unknown model type {}'.format(model_type))
| _SmallSubclassMLPCustomBuild |
python | django__django | tests/raw_query/models.py | {
"start": 1347,
"end": 1386
} | class ____(Author):
pass
| FriendlyAuthor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.