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 | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/types.py | {
"start": 25751,
"end": 26131
} | class ____(Protocol[StateT_contra, ContextT]):
"""Callable with `AgentState` and `Runtime` as arguments."""
def __call__(
self, state: StateT_contra, runtime: Runtime[ContextT]
) -> dict[str, Any] | Command | None | Awaitable[dict[str, Any] | Command | None]:
"""Perform some logic with the state and runtime."""
...
| _CallableWithStateAndRuntime |
python | ray-project__ray | python/ray/serve/_private/application_state.py | {
"start": 2598,
"end": 3169
} | class ____:
"""Stores info on the current in-progress build app task.
We use a class instead of only storing the task object ref because
when a new config is deployed, there can be an outdated in-progress
build app task. We attach the code version to the task info to
distinguish outdated build app tasks.
"""
obj_ref: ObjectRef
code_version: str
config: ServeApplicationSchema
target_capacity: Optional[float]
target_capacity_direction: Optional[TargetCapacityDirection]
finished: bool
@dataclass(eq=True)
| BuildAppTaskInfo |
python | psf__black | tests/data/cases/stub.py | {
"start": 38,
"end": 58
} | class ____:
...
| D |
python | sympy__sympy | sympy/tensor/indexed.py | {
"start": 18614,
"end": 24503
} | class ____(Expr):
"""Represents an integer index as an ``Integer`` or integer expression.
There are a number of ways to create an ``Idx`` object. The constructor
takes two arguments:
``label``
An integer or a symbol that labels the index.
``range``
Optionally you can specify a range as either
* ``Symbol`` or integer: This is interpreted as a dimension. Lower and
upper bounds are set to ``0`` and ``range - 1``, respectively.
* ``tuple``: The two elements are interpreted as the lower and upper
bounds of the range, respectively.
Note: bounds of the range are assumed to be either integer or infinite (oo
and -oo are allowed to specify an unbounded range). If ``n`` is given as a
bound, then ``n.is_integer`` must not return false.
For convenience, if the label is given as a string it is automatically
converted to an integer symbol. (Note: this conversion is not done for
range or dimension arguments.)
Examples
========
>>> from sympy import Idx, symbols, oo
>>> n, i, L, U = symbols('n i L U', integer=True)
If a string is given for the label an integer ``Symbol`` is created and the
bounds are both ``None``:
>>> idx = Idx('qwerty'); idx
qwerty
>>> idx.lower, idx.upper
(None, None)
Both upper and lower bounds can be specified:
>>> idx = Idx(i, (L, U)); idx
i
>>> idx.lower, idx.upper
(L, U)
When only a single bound is given it is interpreted as the dimension
and the lower bound defaults to 0:
>>> idx = Idx(i, n); idx.lower, idx.upper
(0, n - 1)
>>> idx = Idx(i, 4); idx.lower, idx.upper
(0, 3)
>>> idx = Idx(i, oo); idx.lower, idx.upper
(0, oo)
"""
is_integer = True
is_finite = True
is_real = True
is_symbol = True
is_Atom = True
_diff_wrt = True
def __new__(cls, label, range=None, **kw_args):
if isinstance(label, str):
label = Symbol(label, integer=True)
label, range = list(map(sympify, (label, range)))
if label.is_Number:
if not label.is_integer:
raise TypeError("Index is not an integer number.")
return label
if not label.is_integer:
raise TypeError("Idx object requires an integer label.")
elif is_sequence(range):
if len(range) != 2:
raise ValueError(filldedent(f"""
Idx range tuple must have length 2, but got {len(range)}"""))
for bound in range:
if (bound.is_integer is False and bound is not S.Infinity
and bound is not S.NegativeInfinity):
raise TypeError("Idx object requires integer bounds.")
args = label, Tuple(*range)
elif isinstance(range, Expr):
if range is not S.Infinity and fuzzy_not(range.is_integer):
raise TypeError("Idx object requires an integer dimension.")
args = label, Tuple(0, range - 1)
elif range:
raise TypeError(filldedent("""
The range must be an ordered iterable or
integer SymPy expression."""))
else:
args = label,
obj = Expr.__new__(cls, *args, **kw_args)
obj._assumptions["finite"] = True
obj._assumptions["real"] = True
return obj
@property
def label(self):
"""Returns the label (Integer or integer expression) of the Idx object.
Examples
========
>>> from sympy import Idx, Symbol
>>> x = Symbol('x', integer=True)
>>> Idx(x).label
x
>>> j = Symbol('j', integer=True)
>>> Idx(j).label
j
>>> Idx(j + 1).label
j + 1
"""
return self.args[0]
@property
def lower(self):
"""Returns the lower bound of the ``Idx``.
Examples
========
>>> from sympy import Idx
>>> Idx('j', 2).lower
0
>>> Idx('j', 5).lower
0
>>> Idx('j').lower is None
True
"""
try:
return self.args[1][0]
except IndexError:
return
@property
def upper(self):
"""Returns the upper bound of the ``Idx``.
Examples
========
>>> from sympy import Idx
>>> Idx('j', 2).upper
1
>>> Idx('j', 5).upper
4
>>> Idx('j').upper is None
True
"""
try:
return self.args[1][1]
except IndexError:
return
def _sympystr(self, p):
return p.doprint(self.label)
@property
def name(self):
return self.label.name if self.label.is_Symbol else str(self.label)
@property
def free_symbols(self):
return {self}
@dispatch(Idx, Idx)
def _eval_is_ge(lhs, rhs): # noqa:F811
other_upper = rhs if rhs.upper is None else rhs.upper
other_lower = rhs if rhs.lower is None else rhs.lower
if lhs.lower is not None and (lhs.lower >= other_upper) == True:
return True
if lhs.upper is not None and (lhs.upper < other_lower) == True:
return False
return None
@dispatch(Idx, Number) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa:F811
other_upper = rhs
other_lower = rhs
if lhs.lower is not None and (lhs.lower >= other_upper) == True:
return True
if lhs.upper is not None and (lhs.upper < other_lower) == True:
return False
return None
@dispatch(Number, Idx) # type:ignore
def _eval_is_ge(lhs, rhs): # noqa:F811
other_upper = lhs
other_lower = lhs
if rhs.upper is not None and (rhs.upper <= other_lower) == True:
return True
if rhs.lower is not None and (rhs.lower > other_upper) == True:
return False
return None
| Idx |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/pipes.py | {
"start": 16671,
"end": 19807
} | class ____(PipesBlobStoreMessageReader):
"""Message reader that reads messages by periodically reading message chunks from an
automatically-generated temporary directory on DBFS.
If `log_readers` is passed, this reader will also start the passed readers
when the first message is received from the external process.
Args:
interval (float): interval in seconds between attempts to download a chunk
client (WorkspaceClient): A databricks `WorkspaceClient` object.
cluster_log_root (Optional[str]): The root path on DBFS where the cluster logs are written.
If set, this will be used to read stderr/stdout logs.
include_stdio_in_messages (bool): Whether to send stdout/stderr to Dagster via Pipes messages. Defaults to False.
log_readers (Optional[Sequence[PipesLogReader]]): A set of log readers for logs on DBFS.
"""
def __init__(
self,
*,
interval: float = 10,
client: WorkspaceClient,
include_stdio_in_messages: bool = False,
log_readers: Optional[Sequence[PipesLogReader]] = None,
):
self.include_stdio_in_messages = check.bool_param(
include_stdio_in_messages, "include_stdio_in_messages"
)
super().__init__(
interval=interval,
log_readers=log_readers,
)
self.dbfs_client = files.DbfsAPI(client.api_client)
@contextmanager
def get_params(self) -> Iterator[PipesParams]:
with ExitStack() as stack:
params: PipesParams = {}
params["path"] = stack.enter_context(dbfs_tempdir(self.dbfs_client))
params[PipesBlobStoreMessageWriter.INCLUDE_STDIO_IN_MESSAGES_KEY] = (
self.include_stdio_in_messages
)
yield params
def messages_are_readable(self, params: PipesParams) -> bool:
try:
return self.dbfs_client.get_status(params["path"]) is not None
except Exception:
return False
def download_messages_chunk(self, index: int, params: PipesParams) -> Optional[str]:
message_path = os.path.join(params["path"], f"{index}.json")
try:
raw_message = self.dbfs_client.read(message_path)
message_data = check.not_none(raw_message.data, "Read message with null data.")
# Files written to dbfs using the Python IO interface used in PipesDbfsMessageWriter are
# base64-encoded.
return base64.b64decode(message_data).decode("utf-8")
# An error here is an expected result, since an IOError will be thrown if the next message
# chunk doesn't yet exist. Swallowing the error here is equivalent to doing a no-op on a
# status check showing a non-existent file.
except OSError:
return None
def no_messages_debug_text(self) -> str:
return (
"Attempted to read messages from a temporary file in dbfs. Expected"
" PipesDbfsMessageWriter to be explicitly passed to open_dagster_pipes in the external"
" process."
)
| PipesDbfsMessageReader |
python | kamyu104__LeetCode-Solutions | Python/distribute-candies-among-children-i.py | {
"start": 1086,
"end": 1347
} | class ____(object):
def distributeCandies(self, n, limit):
"""
:type n: int
:type limit: int
:rtype: int
"""
return sum(n-i-j <= limit for i in xrange(min(limit, n)+1) for j in xrange(min(limit, n-i)+1))
| Solution3 |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table33.py | {
"start": 315,
"end": 2506
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table33.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels",
]
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
xformat = workbook.add_format({"num_format": 2})
worksheet.set_column("B:K", 10.288)
worksheet.write_string("A1", "Column1")
worksheet.write_string("B1", "Column2")
worksheet.write_string("C1", "Column3")
worksheet.write_string("D1", "Column4")
worksheet.write_string("E1", "Column5")
worksheet.write_string("F1", "Column6")
worksheet.write_string("G1", "Column7")
worksheet.write_string("H1", "Column8")
worksheet.write_string("I1", "Column9")
worksheet.write_string("J1", "Column10")
worksheet.write_string("K1", "Total")
data = [0, 0, 0, None, None, 0, 0, 0, 0, 0]
worksheet.write_row("B4", data)
worksheet.write_row("B5", data)
worksheet.add_table(
"B3:K6",
{
"total_row": 1,
"columns": [
{"total_string": "Total"},
{},
{"total_function": "average"},
{"total_function": "count"},
{"total_function": "count_nums"},
{"total_function": "max"},
{"total_function": "min"},
{"total_function": "sum"},
{"total_function": "std_dev"},
{
"total_function": "=SUM([Column10])",
"formula": "SUM(Table1[[#This Row],[Column1]:[Column3]])",
"format": xformat,
},
],
},
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | matplotlib__matplotlib | galleries/examples/user_interfaces/embedding_in_wx4_sgskip.py | {
"start": 1311,
"end": 2229
} | class ____(wx.Frame):
def __init__(self):
super().__init__(None, -1, 'CanvasFrame', size=(550, 350))
self.figure = Figure(figsize=(5, 4), dpi=100)
self.axes = self.figure.add_subplot()
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2 * np.pi * t)
self.axes.plot(t, s)
self.canvas = FigureCanvas(self, -1, self.figure)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND)
self.toolbar = MyNavigationToolbar(self.canvas)
self.toolbar.Realize()
# By adding toolbar in sizer, we are able to put it at the bottom
# of the frame - so appearance is closer to GTK version.
self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
# update the axes menu on the toolbar
self.toolbar.update()
self.SetSizer(self.sizer)
self.Fit()
| CanvasFrame |
python | langchain-ai__langchain | libs/core/tests/unit_tests/runnables/test_runnable.py | {
"start": 2910,
"end": 6205
} | class ____(BaseTracer):
"""Fake tracer that records LangChain execution.
It replaces run IDs with deterministic UUIDs for snapshotting.
"""
def __init__(self) -> None:
"""Initialize the tracer."""
super().__init__()
self.runs: list[Run] = []
self.uuids_map: dict[UUID, UUID] = {}
self.uuids_generator = (
UUID(f"00000000-0000-4000-8000-{i:012}", version=4) for i in range(10000)
)
def _replace_uuid(self, uuid: UUID) -> UUID:
if uuid not in self.uuids_map:
self.uuids_map[uuid] = next(self.uuids_generator)
return self.uuids_map[uuid]
def _replace_message_id(self, maybe_message: Any) -> Any:
if isinstance(maybe_message, BaseMessage):
maybe_message.id = str(next(self.uuids_generator))
if isinstance(maybe_message, ChatGeneration):
maybe_message.message.id = str(next(self.uuids_generator))
if isinstance(maybe_message, LLMResult):
for i, gen_list in enumerate(maybe_message.generations):
for j, gen in enumerate(gen_list):
maybe_message.generations[i][j] = self._replace_message_id(gen)
if isinstance(maybe_message, dict):
for k, v in maybe_message.items():
maybe_message[k] = self._replace_message_id(v)
if isinstance(maybe_message, list):
for i, v in enumerate(maybe_message):
maybe_message[i] = self._replace_message_id(v)
return maybe_message
def _copy_run(self, run: Run) -> Run:
if run.dotted_order:
levels = run.dotted_order.split(".")
processed_levels = []
for level in levels:
timestamp, run_id = level.split("Z")
new_run_id = self._replace_uuid(UUID(run_id))
processed_level = f"{timestamp}Z{new_run_id}"
processed_levels.append(processed_level)
new_dotted_order = ".".join(processed_levels)
else:
new_dotted_order = None
return run.copy(
update={
"id": self._replace_uuid(run.id),
"parent_run_id": (
self.uuids_map[run.parent_run_id] if run.parent_run_id else None
),
"child_runs": [self._copy_run(child) for child in run.child_runs],
"trace_id": self._replace_uuid(run.trace_id) if run.trace_id else None,
"dotted_order": new_dotted_order,
"inputs": self._replace_message_id(run.inputs),
"outputs": self._replace_message_id(run.outputs),
}
)
def _persist_run(self, run: Run) -> None:
"""Persist a run."""
self.runs.append(self._copy_run(run))
def flattened_runs(self) -> list[Run]:
q = [*self.runs]
result = []
while q:
parent = q.pop()
result.append(parent)
if parent.child_runs:
q.extend(parent.child_runs)
return result
@property
def run_ids(self) -> list[uuid.UUID | None]:
runs = self.flattened_runs()
uuids_map = {v: k for k, v in self.uuids_map.items()}
return [uuids_map.get(r.id) for r in runs]
| FakeTracer |
python | pytorch__pytorch | torch/distributed/pipelining/schedules.py | {
"start": 1137,
"end": 4031
} | class ____(Enum):
# TODO(whc) rename to _ActType?
FORWARD = 1
BACKWARD_INPUT = 2
BACKWARD_WEIGHT = 3
UNSHARD = 4
RESHARD = 5
SEND_F = 6
RECV_F = 7
SEND_B = 8
RECV_B = 9
FULL_BACKWARD = 10
OVERLAP_F_B = 11
REDUCE_GRAD = 12
def __str__(self):
str_map = {
_ComputationType.FORWARD: "F",
_ComputationType.BACKWARD_INPUT: "I",
_ComputationType.BACKWARD_WEIGHT: "W",
_ComputationType.UNSHARD: "UNSHARD",
_ComputationType.RESHARD: "RESHARD",
_ComputationType.SEND_F: "SEND_F",
_ComputationType.RECV_F: "RECV_F",
_ComputationType.SEND_B: "SEND_B",
_ComputationType.RECV_B: "RECV_B",
_ComputationType.FULL_BACKWARD: "B",
_ComputationType.OVERLAP_F_B: "OVERLAP_F_B",
_ComputationType.REDUCE_GRAD: "REDUCE_GRAD",
}
return str_map[self]
@staticmethod
def from_str(action):
if action == "F":
return _ComputationType.FORWARD
elif action == "I":
return _ComputationType.BACKWARD_INPUT
elif action == "W":
return _ComputationType.BACKWARD_WEIGHT
elif action == "UNSHARD":
return _ComputationType.UNSHARD
elif action == "RESHARD":
return _ComputationType.RESHARD
elif action == "SEND_F":
return _ComputationType.SEND_F
elif action == "RECV_F":
return _ComputationType.RECV_F
elif action == "SEND_B":
return _ComputationType.SEND_B
elif action == "RECV_B":
return _ComputationType.RECV_B
elif action == "B":
return _ComputationType.FULL_BACKWARD
elif action == "OVERLAP_F_B":
return _ComputationType.OVERLAP_F_B
elif action == "REDUCE_GRAD":
return _ComputationType.REDUCE_GRAD
else:
raise RuntimeError(f"Invalid computation type {action}")
FORWARD = _ComputationType.FORWARD
BACKWARD_INPUT = _ComputationType.BACKWARD_INPUT
BACKWARD_WEIGHT = _ComputationType.BACKWARD_WEIGHT
UNSHARD = _ComputationType.UNSHARD
RESHARD = _ComputationType.RESHARD
SEND_F = _ComputationType.SEND_F
RECV_F = _ComputationType.RECV_F
SEND_B = _ComputationType.SEND_B
RECV_B = _ComputationType.RECV_B
FULL_BACKWARD = _ComputationType.FULL_BACKWARD
OVERLAP_F_B = _ComputationType.OVERLAP_F_B
REDUCE_GRAD = _ComputationType.REDUCE_GRAD
# Convenience shorthand for compute actions only since they are used in 'simple schedule format'
F = FORWARD
I = BACKWARD_INPUT
W = BACKWARD_WEIGHT
B = FULL_BACKWARD
# Helper to parse an action string like 1F0 into a tuple of (stage_index, computation_type, microbatch_index)
_action_regex = re.compile(
r"(\d+)(F|I|B|W|UNSHARD|RESHARD|REDUCE_GRAD|SEND_F|RECV_F|SEND_B|RECV_B)(\d*)"
)
| _ComputationType |
python | prabhupant__python-ds | data_structures/graphs/root_which_gives_min_height.py | {
"start": 213,
"end": 1387
} | class ____:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
self.degree = [0] * vertices
def add_edge(self, v, w):
self.graph[v].append(w)
self.graph[w].append(v)
self.degree[v] += 1
self.degree[w] += 1
def root_min_height(self):
q = Queue()
for i in range(self.V):
if self.degree[i] == 1: # To identify leaf nodes
q.put(i)
# now move inwards from the leaf node
while self.V > 2:
for i in range(q.qsize()):
t = q.get()
self.V -= 1
# For each neighbour decrease its degree and if it becomes
# leaf, insert into the queue
for j in self.graph[t]:
self.degree[j] -= 1
if self.degree[j] == 1:
q.put(j)
res = list()
while q.qsize() > 0:
res.append(q.get())
return res
g = Graph(6)
g.add_edge(0, 3)
g.add_edge(1, 3)
g.add_edge(2, 3)
g.add_edge(4, 3)
g.add_edge(5, 4)
print(g.root_min_height())
| Graph |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 14545,
"end": 15250
} | class ____(InactiveAssetsResponse):
"""Response of InactiveAssets requests."""
type: Literal["InactiveAssetsResult"] = "InactiveAssetsResult"
@classmethod
def from_inactive_assets_response(
cls, inactive_assets_response: InactiveAssetsResponse
) -> InactiveAssetsResult:
"""
Get InactiveAssetsResponse from InactiveAssetsResult.
InactiveAssetsResponse is autogenerated from the API schema, so we need to convert it to InactiveAssetsResult
for communication between the Supervisor and the task process.
"""
return cls(**inactive_assets_response.model_dump(exclude_defaults=True), type="InactiveAssetsResult")
| InactiveAssetsResult |
python | more-itertools__more-itertools | tests/test_recipes.py | {
"start": 11667,
"end": 12345
} | class ____(TestCase):
"""Tests for ``partition()``"""
def test_bool(self):
lesser, greater = mi.partition(lambda x: x > 5, range(10))
self.assertEqual(list(lesser), [0, 1, 2, 3, 4, 5])
self.assertEqual(list(greater), [6, 7, 8, 9])
def test_arbitrary(self):
divisibles, remainders = mi.partition(lambda x: x % 3, range(10))
self.assertEqual(list(divisibles), [0, 3, 6, 9])
self.assertEqual(list(remainders), [1, 2, 4, 5, 7, 8])
def test_pred_is_none(self):
falses, trues = mi.partition(None, range(3))
self.assertEqual(list(falses), [0])
self.assertEqual(list(trues), [1, 2])
| PartitionTests |
python | Pylons__pyramid | tests/test_view.py | {
"start": 159,
"end": 1337
} | class ____:
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def _registerView(self, reg, app, name):
from pyramid.interfaces import IViewClassifier
for_ = (IViewClassifier, IRequest, IContext)
from pyramid.interfaces import IView
reg.registerAdapter(app, for_, IView, name)
def _makeEnviron(self, **extras):
environ = {
'wsgi.url_scheme': 'http',
'wsgi.version': (1, 0),
'SERVER_NAME': 'localhost',
'SERVER_PORT': '8080',
'REQUEST_METHOD': 'GET',
'PATH_INFO': '/',
}
environ.update(extras)
return environ
def _makeRequest(self, **environ):
from pyramid.registry import Registry
from pyramid.request import Request
environ = self._makeEnviron(**environ)
request = Request(environ)
request.registry = Registry()
return request
def _makeContext(self):
from zope.interface import directlyProvides
context = DummyContext()
directlyProvides(context, IContext)
return context
| BaseTest |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 221,
"end": 497
} | class ____( # trailing class comment
Aaaaaaaaaaaaaaaaa, # trailing comment
# in between comment
Bbbbbbbbbbbbbbbb,
# another leading comment
DDDDDDDDDDDDDDDD,
EEEEEEEEEEEEEE,
# meta comment
metaclass=meta, # trailing meta comment
):
pass
| Test |
python | pytorch__pytorch | test/ao/sparsity/test_parametrization.py | {
"start": 1162,
"end": 6630
} | class ____(TestCase):
def test_masking_logic(self):
model = nn.Linear(16, 16, bias=False)
model.weight = nn.Parameter(torch.eye(16))
x = torch.randn(3, 16)
self.assertEqual(torch.mm(x, torch.eye(16)), model(x))
mask = torch.zeros(16, 16)
sparsity = utils.FakeSparsity(mask)
parametrize.register_parametrization(model, "weight", sparsity)
x = torch.randn(3, 16)
self.assertEqual(torch.zeros(3, 16), model(x))
def test_weights_parametrized(self):
model = ModelUnderTest(bias=False)
assert not hasattr(model.linear, "parametrizations")
assert not hasattr(model.seq[0], "parametrizations")
assert not hasattr(model.seq[1], "parametrizations")
mask = torch.eye(16)
parametrize.register_parametrization(
model.linear, "weight", utils.FakeSparsity(mask)
)
mask = torch.eye(16)
parametrize.register_parametrization(
model.seq[0], "weight", utils.FakeSparsity(mask)
)
mask = torch.eye(16)
parametrize.register_parametrization(
model.seq[1], "weight", utils.FakeSparsity(mask)
)
assert hasattr(model.linear, "parametrizations")
assert parametrize.is_parametrized(model.linear, "weight")
assert hasattr(model.seq[0], "parametrizations")
assert parametrize.is_parametrized(model.linear, "weight")
assert hasattr(model.seq[1], "parametrizations")
assert parametrize.is_parametrized(model.linear, "weight")
def test_state_dict_preserved(self):
model_save = ModelUnderTest(bias=False)
mask = torch.eye(16)
parametrize.register_parametrization(
model_save.linear, "weight", utils.FakeSparsity(mask)
)
mask = torch.eye(16)
parametrize.register_parametrization(
model_save.seq[0], "weight", utils.FakeSparsity(mask)
)
mask = torch.eye(16)
parametrize.register_parametrization(
model_save.seq[1], "weight", utils.FakeSparsity(mask)
)
state_dict = model_save.state_dict()
model_load = ModelUnderTest(bias=False)
mask = torch.zeros(model_load.linear.weight.shape)
parametrize.register_parametrization(
model_load.linear, "weight", utils.FakeSparsity(mask)
)
mask = torch.zeros(model_load.seq[0].weight.shape)
parametrize.register_parametrization(
model_load.seq[0], "weight", utils.FakeSparsity(mask)
)
mask = torch.zeros(model_load.seq[1].weight.shape)
parametrize.register_parametrization(
model_load.seq[1], "weight", utils.FakeSparsity(mask)
)
# Keep this strict, as we are not loading the 'mask'
model_load.load_state_dict(state_dict, strict=False)
# Check the parametrizations are preserved
assert hasattr(model_load.linear, "parametrizations")
assert parametrize.is_parametrized(model_load.linear, "weight")
assert hasattr(model_load.seq[0], "parametrizations")
assert parametrize.is_parametrized(model_load.linear, "weight")
assert hasattr(model_load.seq[1], "parametrizations")
assert parametrize.is_parametrized(model_load.linear, "weight")
# Check the weights are preserved
self.assertEqual(
model_save.linear.parametrizations["weight"].original,
model_load.linear.parametrizations["weight"].original,
)
self.assertEqual(
model_save.seq[0].parametrizations["weight"].original,
model_load.seq[0].parametrizations["weight"].original,
)
self.assertEqual(
model_save.seq[1].parametrizations["weight"].original,
model_load.seq[1].parametrizations["weight"].original,
)
# Check the masks are not preserved in the state_dict
# We store the state_dicts in the sparsifier, not in the model itself.
# TODO: Need to find a clean way of exporting the parametrized model
self.assertNotEqual(
model_save.linear.parametrizations["weight"][0].mask,
model_load.linear.parametrizations["weight"][0].mask,
)
self.assertNotEqual(
model_save.seq[0].parametrizations["weight"][0].mask,
model_load.seq[0].parametrizations["weight"][0].mask,
)
self.assertNotEqual(
model_save.seq[1].parametrizations["weight"][0].mask,
model_load.seq[1].parametrizations["weight"][0].mask,
)
def test_jit_trace(self):
model = ModelUnderTest(bias=False)
mask = torch.eye(16)
parametrize.register_parametrization(
model.linear, "weight", utils.FakeSparsity(mask)
)
mask = torch.eye(16)
parametrize.register_parametrization(
model.seq[0], "weight", utils.FakeSparsity(mask)
)
mask = torch.eye(16)
parametrize.register_parametrization(
model.seq[1], "weight", utils.FakeSparsity(mask)
)
# Tracing
example_x = torch.ones(3, 16)
model_trace = torch.jit.trace_module(model, {"forward": example_x})
x = torch.randn(3, 16)
y = model(x)
y_hat = model_trace(x)
self.assertEqual(y_hat, y)
if __name__ == "__main__":
raise_on_run_directly("test/test_ao_sparsity.py")
| TestFakeSparsity |
python | kubernetes-client__python | kubernetes/client/models/v1_pod_failure_policy_on_exit_codes_requirement.py | {
"start": 383,
"end": 8359
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'container_name': 'str',
'operator': 'str',
'values': 'list[int]'
}
attribute_map = {
'container_name': 'containerName',
'operator': 'operator',
'values': 'values'
}
def __init__(self, container_name=None, operator=None, values=None, local_vars_configuration=None): # noqa: E501
"""V1PodFailurePolicyOnExitCodesRequirement - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._container_name = None
self._operator = None
self._values = None
self.discriminator = None
if container_name is not None:
self.container_name = container_name
self.operator = operator
self.values = values
@property
def container_name(self):
"""Gets the container_name of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
Restricts the check for exit codes to the container with the specified name. When null, the rule applies to all containers. When specified, it should match one the container or initContainer names in the pod template. # noqa: E501
:return: The container_name of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
:rtype: str
"""
return self._container_name
@container_name.setter
def container_name(self, container_name):
"""Sets the container_name of this V1PodFailurePolicyOnExitCodesRequirement.
Restricts the check for exit codes to the container with the specified name. When null, the rule applies to all containers. When specified, it should match one the container or initContainer names in the pod template. # noqa: E501
:param container_name: The container_name of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
:type: str
"""
self._container_name = container_name
@property
def operator(self):
"""Gets the operator of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
Represents the relationship between the container exit code(s) and the specified values. Containers completed with success (exit code 0) are excluded from the requirement check. Possible values are: - In: the requirement is satisfied if at least one container exit code (might be multiple if there are multiple containers not restricted by the 'containerName' field) is in the set of specified values. - NotIn: the requirement is satisfied if at least one container exit code (might be multiple if there are multiple containers not restricted by the 'containerName' field) is not in the set of specified values. Additional values are considered to be added in the future. Clients should react to an unknown operator by assuming the requirement is not satisfied. # noqa: E501
:return: The operator of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
:rtype: str
"""
return self._operator
@operator.setter
def operator(self, operator):
"""Sets the operator of this V1PodFailurePolicyOnExitCodesRequirement.
Represents the relationship between the container exit code(s) and the specified values. Containers completed with success (exit code 0) are excluded from the requirement check. Possible values are: - In: the requirement is satisfied if at least one container exit code (might be multiple if there are multiple containers not restricted by the 'containerName' field) is in the set of specified values. - NotIn: the requirement is satisfied if at least one container exit code (might be multiple if there are multiple containers not restricted by the 'containerName' field) is not in the set of specified values. Additional values are considered to be added in the future. Clients should react to an unknown operator by assuming the requirement is not satisfied. # noqa: E501
:param operator: The operator of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and operator is None: # noqa: E501
raise ValueError("Invalid value for `operator`, must not be `None`") # noqa: E501
self._operator = operator
@property
def values(self):
"""Gets the values of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
Specifies the set of values. Each returned container exit code (might be multiple in case of multiple containers) is checked against this set of values with respect to the operator. The list of values must be ordered and must not contain duplicates. Value '0' cannot be used for the In operator. At least one element is required. At most 255 elements are allowed. # noqa: E501
:return: The values of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
:rtype: list[int]
"""
return self._values
@values.setter
def values(self, values):
"""Sets the values of this V1PodFailurePolicyOnExitCodesRequirement.
Specifies the set of values. Each returned container exit code (might be multiple in case of multiple containers) is checked against this set of values with respect to the operator. The list of values must be ordered and must not contain duplicates. Value '0' cannot be used for the In operator. At least one element is required. At most 255 elements are allowed. # noqa: E501
:param values: The values of this V1PodFailurePolicyOnExitCodesRequirement. # noqa: E501
:type: list[int]
"""
if self.local_vars_configuration.client_side_validation and values is None: # noqa: E501
raise ValueError("Invalid value for `values`, must not be `None`") # noqa: E501
self._values = values
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1PodFailurePolicyOnExitCodesRequirement):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1PodFailurePolicyOnExitCodesRequirement):
return True
return self.to_dict() != other.to_dict()
| V1PodFailurePolicyOnExitCodesRequirement |
python | PrefectHQ__prefect | tests/server/utilities/test_schemas.py | {
"start": 5270,
"end": 5401
} | class ____(PrefectDescriptorBase):
def __get__(self, *args: Any) -> Any:
return super().__get__(*args)
| ConcreteDescriptor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 355756,
"end": 356594
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of
UpdateOrganizationAllowPrivateRepositoryForkingSetting
"""
__schema__ = github_schema
__field_names__ = ("organization_id", "forking_enabled", "client_mutation_id")
organization_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="organizationId")
"""The ID of the organization on which to set the allow private
repository forking setting.
"""
forking_enabled = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="forkingEnabled")
"""Enable forking of private repositories in the organization?"""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
| UpdateOrganizationAllowPrivateRepositoryForkingSettingInput |
python | wandb__wandb | wandb/sdk/artifacts/_generated/update_artifact_sequence.py | {
"start": 259,
"end": 353
} | class ____(GQLResult):
result: Optional[UpdateArtifactSequenceResult]
| UpdateArtifactSequence |
python | pyca__cryptography | src/cryptography/hazmat/primitives/ciphers/modes.py | {
"start": 2627,
"end": 2715
} | class ____(Mode):
name = "ECB"
validate_for_algorithm = _check_aes_key_length
| ECB |
python | langchain-ai__langchain | libs/core/langchain_core/stores.py | {
"start": 599,
"end": 5852
} | class ____(ABC, Generic[K, V]):
"""Abstract interface for a key-value store.
This is an interface that's meant to abstract away the details of
different key-value stores. It provides a simple interface for
getting, setting, and deleting key-value pairs.
The basic methods are `mget`, `mset`, and `mdelete` for getting,
setting, and deleting multiple key-value pairs at once. The `yield_keys`
method is used to iterate over keys that match a given prefix.
The async versions of these methods are also provided, which are
meant to be used in async contexts. The async methods are named with
an `a` prefix, e.g., `amget`, `amset`, `amdelete`, and `ayield_keys`.
By default, the `amget`, `amset`, `amdelete`, and `ayield_keys` methods
are implemented using the synchronous methods. If the store can natively
support async operations, it should override these methods.
By design the methods only accept batches of keys and values, and not
single keys or values. This is done to force user code to work with batches
which will usually be more efficient by saving on round trips to the store.
Examples:
```python
from langchain.storage import BaseStore
class MyInMemoryStore(BaseStore[str, int]):
def __init__(self) -> None:
self.store: dict[str, int] = {}
def mget(self, keys: Sequence[str]) -> list[int | None]:
return [self.store.get(key) for key in keys]
def mset(self, key_value_pairs: Sequence[tuple[str, int]]) -> None:
for key, value in key_value_pairs:
self.store[key] = value
def mdelete(self, keys: Sequence[str]) -> None:
for key in keys:
if key in self.store:
del self.store[key]
def yield_keys(self, prefix: str | None = None) -> Iterator[str]:
if prefix is None:
yield from self.store.keys()
else:
for key in self.store.keys():
if key.startswith(prefix):
yield key
```
"""
@abstractmethod
def mget(self, keys: Sequence[K]) -> list[V | None]:
"""Get the values associated with the given keys.
Args:
keys: A sequence of keys.
Returns:
A sequence of optional values associated with the keys.
If a key is not found, the corresponding value will be `None`.
"""
async def amget(self, keys: Sequence[K]) -> list[V | None]:
"""Async get the values associated with the given keys.
Args:
keys: A sequence of keys.
Returns:
A sequence of optional values associated with the keys.
If a key is not found, the corresponding value will be `None`.
"""
return await run_in_executor(None, self.mget, keys)
@abstractmethod
def mset(self, key_value_pairs: Sequence[tuple[K, V]]) -> None:
"""Set the values for the given keys.
Args:
key_value_pairs: A sequence of key-value pairs.
"""
async def amset(self, key_value_pairs: Sequence[tuple[K, V]]) -> None:
"""Async set the values for the given keys.
Args:
key_value_pairs: A sequence of key-value pairs.
"""
return await run_in_executor(None, self.mset, key_value_pairs)
@abstractmethod
def mdelete(self, keys: Sequence[K]) -> None:
"""Delete the given keys and their associated values.
Args:
keys: A sequence of keys to delete.
"""
async def amdelete(self, keys: Sequence[K]) -> None:
"""Async delete the given keys and their associated values.
Args:
keys: A sequence of keys to delete.
"""
return await run_in_executor(None, self.mdelete, keys)
@abstractmethod
def yield_keys(self, *, prefix: str | None = None) -> Iterator[K] | Iterator[str]:
"""Get an iterator over keys that match the given prefix.
Args:
prefix: The prefix to match.
Yields:
An iterator over keys that match the given prefix.
This method is allowed to return an iterator over either K or str
depending on what makes more sense for the given store.
"""
async def ayield_keys(
self, *, prefix: str | None = None
) -> AsyncIterator[K] | AsyncIterator[str]:
"""Async get an iterator over keys that match the given prefix.
Args:
prefix: The prefix to match.
Yields:
The keys that match the given prefix.
This method is allowed to return an iterator over either K or str
depending on what makes more sense for the given store.
"""
iterator = await run_in_executor(None, self.yield_keys, prefix=prefix)
done = object()
while True:
item = await run_in_executor(None, lambda it: next(it, done), iterator)
if item is done:
break
yield item # type: ignore[misc]
ByteStore = BaseStore[str, bytes]
| BaseStore |
python | mlflow__mlflow | mlflow/genai/scorers/builtin_scorers.py | {
"start": 43385,
"end": 50245
} | class ____(BuiltInScorer):
"""
Correctness ensures that the agent's responses are correct and accurate.
You can invoke the scorer directly with a single input for testing, or pass it to
`mlflow.genai.evaluate` for running full evaluation on a dataset.
Args:
name: The name of the scorer. Defaults to "correctness".
model: {{ model }}
Example (direct usage):
.. code-block:: python
import mlflow
from mlflow.genai.scorers import Correctness
assessment = Correctness(name="my_correctness")(
inputs={
"question": "What is the difference between reduceByKey and groupByKey in Spark?"
},
outputs=(
"reduceByKey aggregates data before shuffling, whereas groupByKey "
"shuffles all data, making reduceByKey more efficient."
),
expectations=[
{"expected_response": "reduceByKey aggregates data before shuffling"},
{"expected_response": "groupByKey shuffles all data"},
],
)
print(assessment)
Example (with evaluate):
.. code-block:: python
import mlflow
from mlflow.genai.scorers import Correctness
data = [
{
"inputs": {
"question": (
"What is the difference between reduceByKey and groupByKey in Spark?"
)
},
"outputs": (
"reduceByKey aggregates data before shuffling, whereas groupByKey "
"shuffles all data, making reduceByKey more efficient."
),
"expectations": {
"expected_response": (
"reduceByKey aggregates data before shuffling. "
"groupByKey shuffles all data"
),
},
}
]
result = mlflow.genai.evaluate(data=data, scorers=[Correctness()])
"""
name: str = "correctness"
model: str | None = None
required_columns: set[str] = {"inputs", "outputs"}
description: str = (
"Check whether the agent's response matches the facts in expected_response or "
"expected_facts."
)
@property
def instructions(self) -> str:
"""Get the instructions of what this scorer evaluates."""
return CORRECTNESS_PROMPT_INSTRUCTIONS
def validate_columns(self, columns: set[str]) -> None:
super().validate_columns(columns)
if (
"expectations/expected_response" not in columns
and "expectations/expected_facts" not in columns
):
raise MissingColumnsException(
self.name,
["expectations/expected_response or expectations/expected_facts"],
)
def get_input_fields(self) -> list[JudgeField]:
"""
Get the input fields for the Correctness judge.
Returns:
List of JudgeField objects defining the input fields based on the __call__ method.
"""
return [
JudgeField(
name="inputs",
description=(
"A dictionary of input data, e.g. "
"{'question': 'What is the capital of France?'}."
),
),
JudgeField(
name="outputs",
description="The response from the model, e.g. 'The capital of France is Paris.'",
),
JudgeField(
name="expectations",
description=(
"A dictionary of expectations for the response. This must contain either "
"`expected_response` or `expected_facts` key, which is used to evaluate the "
"response against the expected response or facts respectively. "
"E.g., {'expected_facts': ['Paris', 'France', 'Capital']}"
),
),
]
def __call__(
self,
*,
inputs: dict[str, Any] | None = None,
outputs: Any | None = None,
expectations: dict[str, Any] | None = None,
trace: Trace | None = None,
) -> Feedback:
"""
Evaluate correctness of the response against expectations.
This scorer can be used in two ways:
1. Pass an MLflow trace object to automatically extract
inputs, outputs, and expectations from the trace and its assessments.
2. Directly provide inputs, outputs, and expectations to evaluate.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
Optional when trace is provided.
outputs: The response from the model, e.g. "The capital of France is Paris."
Optional when trace is provided.
expectations: A dictionary of expectations for the response. This must contain either
`expected_response` or `expected_facts` key. Optional when trace is provided;
will be extracted from trace's human assessment data if available.
trace: MLflow trace object containing the execution to evaluate. When provided,
inputs, outputs, and expectations will be automatically extracted from the trace.
Returns:
An :py:class:`mlflow.entities.assessment.Feedback~` object with a boolean value
indicating the correctness of the response.
"""
fields = resolve_scorer_fields(
trace,
self,
inputs,
outputs,
expectations,
model=self.model,
extract_expectations=True,
)
_validate_required_fields(fields, self, "Correctness scorer")
if not fields.expectations or (
fields.expectations.get("expected_response") is None
and fields.expectations.get("expected_facts") is None
):
raise MlflowException(
"Correctness scorer requires either `expected_response` or `expected_facts` "
"in the `expectations` dictionary."
)
request = parse_inputs_to_str(fields.inputs)
response = parse_outputs_to_str(fields.outputs)
expected_facts = fields.expectations.get("expected_facts")
expected_response = fields.expectations.get("expected_response")
feedback = judges.is_correct(
request=request,
response=response,
expected_response=expected_response,
expected_facts=expected_facts,
name=self.name,
model=self.model,
)
return _sanitize_scorer_feedback(feedback)
@format_docstring(_MODEL_API_DOC)
| Correctness |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol3.py | {
"start": 3985,
"end": 4394
} | class ____:
val1: ClassVar = [1, 2, 3]
# This should generate an error because of a ClassVar mismatch.
p12_1: Proto12 = Concrete12()
def func12(p11: Proto11, p12: Proto12):
# This should generate an error because of a ClassVar mismatch.
v1: Proto12 = p11
# This should generate an error because of a ClassVar mismatch.
v2: Proto11 = p12
T13 = TypeVar("T13", covariant=True)
| Concrete12 |
python | pytorch__pytorch | torch/__init__.py | {
"start": 70979,
"end": 71201
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.half
| HalfStorage |
python | walkccc__LeetCode | solutions/616. Add Bold Tag in String/616-2.py | {
"start": 108,
"end": 1240
} | class ____:
def addBoldTag(self, s: str, words: list[str]) -> str:
n = len(s)
ans = []
# bold[i] := True if s[i] should be bolded
bold = [0] * n
root = TrieNode()
def insert(word: str) -> None:
node = root
for c in word:
node = node.children.setdefault(c, TrieNode())
node.isWord = True
def find(s: str, i: int) -> int:
node = root
ans = -1
for j in range(i, len(s)):
if s[j] not in node.children:
node.children[s[j]] = TrieNode()
node = node.children[s[j]]
if node.isWord:
ans = j
return ans
for word in words:
insert(word)
boldEnd = -1 # `s[i..boldEnd]` should be bolded.
for i in range(n):
boldEnd = max(boldEnd, find(s, i))
bold[i] = boldEnd >= i
# Construct the with bold tags
i = 0
while i < n:
if bold[i]:
j = i
while j < n and bold[j]:
j += 1
# `s[i..j)` should be bolded.
ans.append('<b>' + s[i:j] + '</b>')
i = j
else:
ans.append(s[i])
i += 1
return ''.join(ans)
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 115247,
"end": 115675
} | class ____(sgqlc.types.Enum):
"""The possible default commit titles for squash merges.
Enumeration Choices:
* `COMMIT_OR_PR_TITLE`: Default to the commit's title (if only one
commit) or the pull request's title (when more than one commit).
* `PR_TITLE`: Default to the pull request's title.
"""
__schema__ = github_schema
__choices__ = ("COMMIT_OR_PR_TITLE", "PR_TITLE")
| SquashMergeCommitTitle |
python | arrow-py__arrow | tests/test_api.py | {
"start": 15,
"end": 770
} | class ____:
def test_get(self, mocker):
mocker.patch("arrow.api._factory.get", return_value="result")
assert arrow.api.get() == "result"
def test_utcnow(self, mocker):
mocker.patch("arrow.api._factory.utcnow", return_value="utcnow")
assert arrow.api.utcnow() == "utcnow"
def test_now(self, mocker):
mocker.patch("arrow.api._factory.now", tz="tz", return_value="now")
assert arrow.api.now("tz") == "now"
def test_factory(self):
class MockCustomArrowClass(arrow.Arrow):
pass
result = arrow.api.factory(MockCustomArrowClass)
assert isinstance(result, arrow.factory.ArrowFactory)
assert isinstance(result.utcnow(), MockCustomArrowClass)
| TestModule |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_parameters.py | {
"start": 2427,
"end": 4299
} | class ____(ParameterTestMixin):
"""Tests for `astropy.cosmology.Parameter` Om0 on a Cosmology.
Om0 is a descriptor, which are tested by mixin, here with ``TestFLRW``.
These tests expect dicts ``_cls_args`` and ``cls_kwargs`` which give the
args and kwargs for the cosmology class, respectively. See ``TestFLRW``.
"""
def test_Om0(self, cosmo_cls: type[Cosmology], cosmo: Cosmology):
"""Test Parameter ``Om0``."""
# on the class
Om0 = cosmo_cls.parameters["Om0"]
assert isinstance(Om0, Parameter)
assert "Omega matter" in Om0.__doc__
assert Om0.default is MISSING
# validation
assert Om0.validate(cosmo, 1) == 1
assert Om0.validate(cosmo, 10 * u.one) == 10
with pytest.raises(ValueError, match="Om0 cannot be negative"):
Om0.validate(cosmo, -1)
# on the instance
assert cosmo.Om0 is cosmo.__dict__["Om0"]
assert cosmo.Om0 == self._cls_args["Om0"]
assert isinstance(cosmo.Om0, float)
def test_init_Om0(self, cosmo_cls: type[Cosmology], ba: BoundArguments):
"""Test initialization for values of ``Om0``."""
# test that it works with units
ba.arguments["Om0"] = ba.arguments["Om0"] << u.one # ensure units
cosmo = cosmo_cls(*ba.args, **ba.kwargs)
assert cosmo.Om0 == ba.arguments["Om0"]
# also without units
ba.arguments["Om0"] = ba.arguments["Om0"].value # strip units
cosmo = cosmo_cls(*ba.args, **ba.kwargs)
assert cosmo.Om0 == ba.arguments["Om0"]
# fails for negative numbers
ba.arguments["Om0"] = -0.27
with pytest.raises(ValueError, match="Om0 cannot be negative."):
cosmo_cls(*ba.args, **ba.kwargs)
# =============================================================================
| ParameterOm0TestMixin |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_neptune.py | {
"start": 1794,
"end": 8070
} | class ____:
@mock.patch.object(NeptuneHook, "conn")
@mock.patch.object(NeptuneHook, "get_waiter")
def test_start_cluster_wait_for_completion(self, mock_hook_get_waiter, mock_conn):
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=False,
wait_for_completion=True,
aws_conn_id="aws_default",
)
resp = operator.execute(None)
mock_hook_get_waiter.assert_called_once_with("cluster_available")
assert resp == EXPECTED_RESPONSE
@mock.patch.object(NeptuneHook, "conn")
@mock.patch.object(NeptuneHook, "get_waiter")
def test_start_cluster_no_wait(self, mock_hook_get_waiter, mock_conn):
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=False,
wait_for_completion=False,
aws_conn_id="aws_default",
)
resp = operator.execute(None)
mock_hook_get_waiter.assert_not_called()
assert resp == EXPECTED_RESPONSE
@mock.patch.object(NeptuneHook, "conn")
@mock.patch.object(NeptuneHook, "get_cluster_status")
@mock.patch.object(NeptuneHook, "get_waiter")
def test_start_cluster_cluster_available(self, mock_waiter, mock_get_cluster_status, mock_conn):
mock_get_cluster_status.return_value = "available"
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=False,
wait_for_completion=True,
aws_conn_id="aws_default",
)
resp = operator.execute(None)
mock_conn.start_db_cluster.assert_not_called()
mock_waiter.assert_not_called()
assert resp == {"db_cluster_id": CLUSTER_ID}
@mock.patch.object(NeptuneHook, "conn")
def test_start_cluster_deferrable(self, mock_conn):
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=True,
wait_for_completion=False,
aws_conn_id="aws_default",
)
with pytest.raises(TaskDeferred):
operator.execute(None)
@mock.patch.object(NeptuneHook, "conn")
@mock.patch.object(NeptuneHook, "get_cluster_status")
@mock.patch.object(NeptuneHook, "get_waiter")
def test_start_cluster_cluster_error(self, mock_waiter, mock_get_cluster_status, mock_conn):
mock_get_cluster_status.return_value = "migration-failed"
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=False,
wait_for_completion=True,
aws_conn_id="aws_default",
)
with pytest.raises(AirflowException):
operator.execute(None)
@mock.patch("airflow.providers.amazon.aws.operators.neptune.NeptuneStartDbClusterOperator.defer")
@mock.patch("airflow.providers.amazon.aws.operators.neptune.handle_waitable_exception")
@mock.patch.object(NeptuneHook, "conn")
def test_start_cluster_not_ready_defer(self, mock_conn, mock_wait, mock_defer):
err_response = {"Error": {"Code": "InvalidClusterState", "Message": "Test message"}}
exception = client("neptune").exceptions.ClientError(err_response, "test")
returned_exception = type(exception)
mock_conn.exceptions.InvalidClusterStateFault = returned_exception
mock_conn.start_db_cluster.side_effect = exception
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=True,
wait_for_completion=False,
aws_conn_id="aws_default",
)
operator.execute(None)
mock_wait.assert_called_once_with(
operator=operator,
err="InvalidClusterState",
)
assert mock_defer.call_count == 1
@mock.patch.object(NeptuneHook, "get_waiter")
@mock.patch.object(NeptuneHook, "conn")
def test_start_cluster_instances_not_ready(self, mock_conn, mock_get_waiter):
err_response = {"Error": {"Code": "InvalidDBInstanceState", "Message": "Test message"}}
exception = client("neptune").exceptions.ClientError(err_response, "test")
returned_exception = type(exception)
mock_conn.exceptions.InvalidClusterStateFault = returned_exception
mock_conn.start_db_cluster.side_effect = exception
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=False,
wait_for_completion=False,
aws_conn_id="aws_default",
)
operator.execute(None)
mock_get_waiter.assert_any_call("db_instance_available")
@mock.patch("airflow.providers.amazon.aws.operators.neptune.NeptuneStartDbClusterOperator.defer")
@mock.patch.object(NeptuneHook, "conn")
def test_start_cluster_instances_not_ready_defer(self, mock_conn, mock_defer):
"""Tests both waiters are called if an instance exception is raised"""
err_response = {"Error": {"Code": "InvalidDBInstanceState", "Message": "Test message"}}
exception = client("neptune").exceptions.ClientError(err_response, "test")
returned_exception = type(exception)
mock_conn.exceptions.InvalidClusterStateFault = returned_exception
mock_conn.start_db_cluster.side_effect = exception
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=True,
wait_for_completion=False,
aws_conn_id="aws_default",
)
operator.execute(None)
# mock_defer.assert_has_calls(calls)
assert mock_defer.call_count == 2
def test_template_fields(self):
operator = NeptuneStartDbClusterOperator(
task_id="task_test",
db_cluster_id=CLUSTER_ID,
deferrable=True,
wait_for_completion=False,
aws_conn_id="aws_default",
)
validate_template_fields(operator)
| TestNeptuneStartClusterOperator |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 21544,
"end": 21837
} | class ____(HTTPException):
"""*451* `Unavailable For Legal Reasons`
This status code indicates that the server is denying access to the
resource as a consequence of a legal demand.
"""
code = 451
description = "Unavailable for legal reasons."
| UnavailableForLegalReasons |
python | kamyu104__LeetCode-Solutions | Python/remove-zeros-in-decimal-representation.py | {
"start": 531,
"end": 751
} | class ____(object):
def removeZeros(self, n):
"""
:type n: int
:rtype: int
"""
result = "".join(x for x in str(n) if x != '0')
return int(result) if result else 0
| Solution2 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 8420,
"end": 8603
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("EMAIL",)
| EnterpriseServerUserAccountEmailOrderField |
python | wandb__wandb | wandb/sdk/wandb_login.py | {
"start": 455,
"end": 4974
} | class ____(Exception):
"""OIDC is configured but not allowed."""
def _handle_host_wandb_setting(host: str | None, cloud: bool = False) -> None:
"""Write the host parameter to the global settings file.
This takes the parameter from wandb.login or wandb login for use by the
application's APIs.
"""
_api = InternalApi()
if host == "https://api.wandb.ai" or (host is None and cloud):
_api.clear_setting("base_url", globally=True, persist=True)
# To avoid writing an empty local settings file, we only clear if it exists
if os.path.exists(OldSettings._local_path()):
_api.clear_setting("base_url", persist=True)
elif host:
host = host.rstrip("/")
# force relogin if host is specified
_api.set_setting("base_url", host, globally=True, persist=True)
def _clear_anonymous_setting() -> None:
"""Delete the 'anonymous' setting from the global settings file.
This setting is being removed, and this helps users remove it from their
settings file by using `wandb login`. We do it here because `wandb login`
used to automatically write the anonymous setting.
"""
api = InternalApi()
api.clear_setting("anonymous", globally=True, persist=True)
def login(
key: str | None = None,
relogin: bool | None = None,
host: str | None = None,
force: bool | None = None,
timeout: int | None = None,
verify: bool = False,
referrer: str | None = None,
anonymous: DoNotSet = UNSET,
) -> bool:
"""Log into W&B.
You generally don't have to use this because most W&B methods that need
authentication can log in implicitly. This is the programmatic counterpart
to the `wandb login` CLI.
This updates global credentials for the session (affecting all wandb usage
in the current Python process after this call) and possibly the .netrc file.
If the identity_token_file setting is set, like through the
WANDB_IDENTITY_TOKEN_FILE environment variable, then this is a no-op.
Otherwise, if an explicit API key is provided, it is used and written to
the system .netrc file. If no key is provided, but the session is already
authenticated, then the session key is used for verification (if verify
is True) and the .netrc file is not updated.
If none of the above is true, then this gets the API key from the first of:
- The WANDB_API_KEY environment variable
- The api_key setting in a system or workspace settings file
- The .netrc file (either ~/.netrc, ~/_netrc or the path specified by the
NETRC environment variable)
- An interactive prompt (if available)
Args:
key: The API key to use.
relogin: If true, get the API key from an interactive prompt, skipping
reading .netrc, environment variables, etc.
host: The W&B server URL to connect to.
force: If true, disallows selecting offline mode in the interactive
prompt.
timeout: Number of seconds to wait for user input in the interactive
prompt. This can be used as a failsafe if an interactive prompt
is incorrectly shown in a non-interactive environment.
verify: Verify the credentials with the W&B server and raise an
AuthenticationError on failure.
referrer: The referrer to use in the URL login request for analytics.
Returns:
bool: If `key` is configured.
Raises:
AuthenticationError: If `api_key` fails verification with the server.
UsageError: If `api_key` cannot be configured and no tty.
"""
if anonymous is not UNSET:
term.termwarn(
"The anonymous parameter to wandb.login() has no effect and will"
+ " be removed in future versions.",
repeat=False,
)
if wandb.run is not None:
term.termwarn("Calling wandb.login() after wandb.init() has no effect.")
return False
global_settings = wandb_setup.singleton().settings
if global_settings._noop:
return False
if global_settings._offline and not global_settings.x_cli_only_mode:
term.termwarn("Unable to verify login in offline mode.")
return False
_handle_host_wandb_setting(host)
_clear_anonymous_setting()
logged_in, _ = _login(
key=key,
relogin=relogin,
host=host,
force=force,
timeout=timeout,
verify=verify,
referrer=referrer,
)
return logged_in
| OidcError |
python | getsentry__sentry | tests/apidocs/endpoints/projects/test_service_hooks.py | {
"start": 136,
"end": 1227
} | class ____(APIDocsTestCase):
def setUp(self) -> None:
self.create_service_hook(project=self.project, events=("event.created",))
self.create_service_hook(project=self.project, events=("event.alert",))
self.url = reverse(
"sentry-api-0-service-hooks",
kwargs={
"organization_id_or_slug": self.organization.slug,
"project_id_or_slug": self.project.slug,
},
)
self.login_as(user=self.user)
def test_get(self) -> None:
with self.feature("projects:servicehooks"):
response = self.client.get(self.url)
request = RequestFactory().get(self.url)
self.validate_schema(request, response)
def test_post(self) -> None:
data = {"url": "https://example.com/other-sentry-hook", "events": ["event.created"]}
with self.feature("projects:servicehooks"):
response = self.client.post(self.url, data)
request = RequestFactory().post(self.url, data)
self.validate_schema(request, response)
| ProjectServiceHooksDocs |
python | getsentry__sentry-python | sentry_sdk/integrations/tornado.py | {
"start": 1234,
"end": 6225
} | class ____(Integration):
identifier = "tornado"
origin = f"auto.http.{identifier}"
@staticmethod
def setup_once():
# type: () -> None
_check_minimum_version(TornadoIntegration, TORNADO_VERSION)
if not HAS_REAL_CONTEXTVARS:
# Tornado is async. We better have contextvars or we're going to leak
# state between requests.
raise DidNotEnable(
"The tornado integration for Sentry requires Python 3.7+ or the aiocontextvars package"
+ CONTEXTVARS_ERROR_MESSAGE
)
ignore_logger("tornado.access")
old_execute = RequestHandler._execute
awaitable = iscoroutinefunction(old_execute)
if awaitable:
# Starting Tornado 6 RequestHandler._execute method is a standard Python coroutine (async/await)
# In that case our method should be a coroutine function too
async def sentry_execute_request_handler(self, *args, **kwargs):
# type: (RequestHandler, *Any, **Any) -> Any
with _handle_request_impl(self):
return await old_execute(self, *args, **kwargs)
else:
@coroutine # type: ignore
def sentry_execute_request_handler(self, *args, **kwargs):
# type: (RequestHandler, *Any, **Any) -> Any
with _handle_request_impl(self):
result = yield from old_execute(self, *args, **kwargs)
return result
RequestHandler._execute = sentry_execute_request_handler
old_log_exception = RequestHandler.log_exception
def sentry_log_exception(self, ty, value, tb, *args, **kwargs):
# type: (Any, type, BaseException, Any, *Any, **Any) -> Optional[Any]
_capture_exception(ty, value, tb)
return old_log_exception(self, ty, value, tb, *args, **kwargs)
RequestHandler.log_exception = sentry_log_exception
@contextlib.contextmanager
def _handle_request_impl(self):
# type: (RequestHandler) -> Generator[None, None, None]
integration = sentry_sdk.get_client().get_integration(TornadoIntegration)
if integration is None:
yield
weak_handler = weakref.ref(self)
with sentry_sdk.isolation_scope() as scope:
headers = self.request.headers
scope.clear_breadcrumbs()
processor = _make_event_processor(weak_handler)
scope.add_event_processor(processor)
transaction = continue_trace(
headers,
op=OP.HTTP_SERVER,
# Like with all other integrations, this is our
# fallback transaction in case there is no route.
# sentry_urldispatcher_resolve is responsible for
# setting a transaction name later.
name="generic Tornado request",
source=TransactionSource.ROUTE,
origin=TornadoIntegration.origin,
)
with sentry_sdk.start_transaction(
transaction, custom_sampling_context={"tornado_request": self.request}
):
yield
@ensure_integration_enabled(TornadoIntegration)
def _capture_exception(ty, value, tb):
# type: (type, BaseException, Any) -> None
if isinstance(value, HTTPError):
return
event, hint = event_from_exception(
(ty, value, tb),
client_options=sentry_sdk.get_client().options,
mechanism={"type": "tornado", "handled": False},
)
sentry_sdk.capture_event(event, hint=hint)
def _make_event_processor(weak_handler):
# type: (Callable[[], RequestHandler]) -> EventProcessor
def tornado_processor(event, hint):
# type: (Event, dict[str, Any]) -> Event
handler = weak_handler()
if handler is None:
return event
request = handler.request
with capture_internal_exceptions():
method = getattr(handler, handler.request.method.lower())
event["transaction"] = transaction_from_function(method) or ""
event["transaction_info"] = {"source": TransactionSource.COMPONENT}
with capture_internal_exceptions():
extractor = TornadoRequestExtractor(request)
extractor.extract_into_event(event)
request_info = event["request"]
request_info["url"] = "%s://%s%s" % (
request.protocol,
request.host,
request.path,
)
request_info["query_string"] = request.query
request_info["method"] = request.method
request_info["env"] = {"REMOTE_ADDR": request.remote_ip}
request_info["headers"] = _filter_headers(dict(request.headers))
with capture_internal_exceptions():
if handler.current_user and should_send_default_pii():
event.setdefault("user", {}).setdefault("is_authenticated", True)
return event
return tornado_processor
| TornadoIntegration |
python | getsentry__sentry | tests/social_auth/test_utils.py | {
"start": 293,
"end": 1215
} | class ____(TestCase):
def test_model_to_ctype(self) -> None:
val = model_to_ctype(1)
assert val == 1
val = model_to_ctype(None)
assert val is None
user = self.create_user()
val = model_to_ctype(user)
assert val == {"pk": user.id, "ctype": ContentType.objects.get_for_model(user).pk}
rpc_user = serialize_rpc_user(user)
val = model_to_ctype(rpc_user)
assert val == rpc_user.dict()
def test_ctype_to_model(self) -> None:
val = ctype_to_model(1)
assert val == 1
val = ctype_to_model(None)
assert val is None
user = self.create_user()
ctype_val = {"pk": user.id, "ctype": ContentType.objects.get_for_model(user).pk}
assert ctype_to_model(ctype_val) == user
rpc_user = serialize_rpc_user(user)
assert ctype_to_model(rpc_user.dict()) == rpc_user
| TestSocialAuthUtils |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/bedrock.py | {
"start": 2697,
"end": 3343
} | class ____(AwsBaseHook):
"""
Interact with the Amazon Agents for Bedrock API.
Provide thin wrapper around :external+boto3:py:class:`boto3.client("bedrock-agent-runtime") <AgentsforBedrockRuntime.Client>`.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.
.. seealso::
- :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
"""
client_type = "bedrock-agent-runtime"
def __init__(self, *args, **kwargs) -> None:
kwargs["client_type"] = self.client_type
super().__init__(*args, **kwargs)
| BedrockAgentRuntimeHook |
python | keras-team__keras | keras/src/layers/pooling/global_average_pooling1d.py | {
"start": 295,
"end": 3131
} | class ____(BaseGlobalPooling):
"""Global average pooling operation for temporal data.
Args:
data_format: string, either `"channels_last"` or `"channels_first"`.
The ordering of the dimensions in the inputs. `"channels_last"`
corresponds to inputs with shape `(batch, steps, features)`
while `"channels_first"` corresponds to inputs with shape
`(batch, features, steps)`. It defaults to the `image_data_format`
value found in your Keras config file at `~/.keras/keras.json`.
If you never set it, then it will be `"channels_last"`.
keepdims: A boolean, whether to keep the temporal dimension or not.
If `keepdims` is `False` (default), the rank of the tensor is
reduced for spatial dimensions. If `keepdims` is `True`, the
temporal dimension are retained with length 1.
The behavior is the same as for `tf.reduce_mean` or `np.mean`.
Call arguments:
inputs: A 3D tensor.
mask: Binary tensor of shape `(batch_size, steps)` indicating whether
a given step should be masked (excluded from the average).
Input shape:
- If `data_format='channels_last'`:
3D tensor with shape:
`(batch_size, steps, features)`
- If `data_format='channels_first'`:
3D tensor with shape:
`(batch_size, features, steps)`
Output shape:
- If `keepdims=False`:
2D tensor with shape `(batch_size, features)`.
- If `keepdims=True`:
- If `data_format="channels_last"`:
3D tensor with shape `(batch_size, 1, features)`
- If `data_format="channels_first"`:
3D tensor with shape `(batch_size, features, 1)`
Example:
>>> x = np.random.rand(2, 3, 4)
>>> y = keras.layers.GlobalAveragePooling1D()(x)
>>> y.shape
(2, 4)
"""
def __init__(self, data_format=None, keepdims=False, **kwargs):
super().__init__(
pool_dimensions=1,
data_format=data_format,
keepdims=keepdims,
**kwargs,
)
self.supports_masking = True
def call(self, inputs, mask=None):
steps_axis = 1 if self.data_format == "channels_last" else 2
if mask is not None:
mask = backend.cast(mask, inputs[0].dtype)
mask = ops.expand_dims(
mask, 2 if self.data_format == "channels_last" else 1
)
inputs *= mask
return ops.sum(
inputs, axis=steps_axis, keepdims=self.keepdims
) / ops.sum(mask, axis=steps_axis, keepdims=self.keepdims)
else:
return ops.mean(inputs, axis=steps_axis, keepdims=self.keepdims)
def compute_mask(self, inputs, mask=None):
return None
| GlobalAveragePooling1D |
python | pypa__setuptools | setuptools/tests/test_build_ext.py | {
"start": 557,
"end": 6669
} | class ____:
def test_get_ext_filename(self):
"""
Setuptools needs to give back the same
result as distutils, even if the fullname
is not in ext_map.
"""
dist = Distribution()
cmd = build_ext(dist)
cmd.ext_map['foo/bar'] = ''
res = cmd.get_ext_filename('foo')
wanted = orig.build_ext.get_ext_filename(cmd, 'foo')
assert res == wanted
def test_abi3_filename(self):
"""
Filename needs to be loadable by several versions
of Python 3 if 'is_abi3' is truthy on Extension()
"""
print(get_abi3_suffix())
extension = Extension('spam.eggs', ['eggs.c'], py_limited_api=True)
dist = Distribution(dict(ext_modules=[extension]))
cmd = build_ext(dist)
cmd.finalize_options()
assert 'spam.eggs' in cmd.ext_map
res = cmd.get_ext_filename('spam.eggs')
if not get_abi3_suffix():
assert res.endswith(get_config_var('EXT_SUFFIX'))
elif sys.platform == 'win32':
assert res.endswith('eggs.pyd')
else:
assert 'abi3' in res
def test_ext_suffix_override(self):
"""
SETUPTOOLS_EXT_SUFFIX variable always overrides
default extension options.
"""
dist = Distribution()
cmd = build_ext(dist)
cmd.ext_map['for_abi3'] = ext = Extension(
'for_abi3',
['s.c'],
# Override shouldn't affect abi3 modules
py_limited_api=True,
)
# Mock value needed to pass tests
ext._links_to_dynamic = False
if not IS_PYPY:
expect = cmd.get_ext_filename('for_abi3')
else:
# PyPy builds do not use ABI3 tag, so they will
# also get the overridden suffix.
expect = 'for_abi3.test-suffix'
try:
os.environ['SETUPTOOLS_EXT_SUFFIX'] = '.test-suffix'
res = cmd.get_ext_filename('normal')
assert 'normal.test-suffix' == res
res = cmd.get_ext_filename('for_abi3')
assert expect == res
finally:
del os.environ['SETUPTOOLS_EXT_SUFFIX']
def dist_with_example(self):
files = {
"src": {"mypkg": {"subpkg": {"ext2.c": ""}}},
"c-extensions": {"ext1": {"main.c": ""}},
}
ext1 = Extension("mypkg.ext1", ["c-extensions/ext1/main.c"])
ext2 = Extension("mypkg.subpkg.ext2", ["src/mypkg/subpkg/ext2.c"])
ext3 = Extension("ext3", ["c-extension/ext3.c"])
path.build(files)
return Distribution({
"script_name": "%test%",
"ext_modules": [ext1, ext2, ext3],
"package_dir": {"": "src"},
})
def test_get_outputs(self, tmpdir_cwd, monkeypatch):
monkeypatch.setenv('SETUPTOOLS_EXT_SUFFIX', '.mp3') # make test OS-independent
monkeypatch.setattr('setuptools.command.build_ext.use_stubs', False)
dist = self.dist_with_example()
# Regular build: get_outputs not empty, but get_output_mappings is empty
build_ext = dist.get_command_obj("build_ext")
build_ext.editable_mode = False
build_ext.ensure_finalized()
build_lib = build_ext.build_lib.replace(os.sep, "/")
outputs = [x.replace(os.sep, "/") for x in build_ext.get_outputs()]
assert outputs == [
f"{build_lib}/ext3.mp3",
f"{build_lib}/mypkg/ext1.mp3",
f"{build_lib}/mypkg/subpkg/ext2.mp3",
]
assert build_ext.get_output_mapping() == {}
# Editable build: get_output_mappings should contain everything in get_outputs
dist.reinitialize_command("build_ext")
build_ext.editable_mode = True
build_ext.ensure_finalized()
mapping = {
k.replace(os.sep, "/"): v.replace(os.sep, "/")
for k, v in build_ext.get_output_mapping().items()
}
assert mapping == {
f"{build_lib}/ext3.mp3": "src/ext3.mp3",
f"{build_lib}/mypkg/ext1.mp3": "src/mypkg/ext1.mp3",
f"{build_lib}/mypkg/subpkg/ext2.mp3": "src/mypkg/subpkg/ext2.mp3",
}
def test_get_output_mapping_with_stub(self, tmpdir_cwd, monkeypatch):
monkeypatch.setenv('SETUPTOOLS_EXT_SUFFIX', '.mp3') # make test OS-independent
monkeypatch.setattr('setuptools.command.build_ext.use_stubs', True)
dist = self.dist_with_example()
# Editable build should create compiled stubs (.pyc files only, no .py)
build_ext = dist.get_command_obj("build_ext")
build_ext.editable_mode = True
build_ext.ensure_finalized()
for ext in build_ext.extensions:
monkeypatch.setattr(ext, "_needs_stub", True)
build_lib = build_ext.build_lib.replace(os.sep, "/")
mapping = {
k.replace(os.sep, "/"): v.replace(os.sep, "/")
for k, v in build_ext.get_output_mapping().items()
}
def C(file):
"""Make it possible to do comparisons and tests in a OS-independent way"""
return _compiled_file_name(file).replace(os.sep, "/")
assert mapping == {
C(f"{build_lib}/ext3.py"): C("src/ext3.py"),
f"{build_lib}/ext3.mp3": "src/ext3.mp3",
C(f"{build_lib}/mypkg/ext1.py"): C("src/mypkg/ext1.py"),
f"{build_lib}/mypkg/ext1.mp3": "src/mypkg/ext1.mp3",
C(f"{build_lib}/mypkg/subpkg/ext2.py"): C("src/mypkg/subpkg/ext2.py"),
f"{build_lib}/mypkg/subpkg/ext2.mp3": "src/mypkg/subpkg/ext2.mp3",
}
# Ensure only the compiled stubs are present not the raw .py stub
assert f"{build_lib}/mypkg/ext1.py" not in mapping
assert f"{build_lib}/mypkg/subpkg/ext2.py" not in mapping
# Visualize what the cached stub files look like
example_stub = C(f"{build_lib}/mypkg/ext1.py")
assert example_stub in mapping
assert example_stub.startswith(f"{build_lib}/mypkg/__pycache__/ext1")
assert example_stub.endswith(".pyc")
| TestBuildExt |
python | keras-team__keras | keras/src/backend/tensorflow/core.py | {
"start": 1032,
"end": 21802
} | class ____(
KerasVariable,
tf.__internal__.types.Tensor,
tf.__internal__.tracking.Trackable,
):
_should_act_as_resource_variable = True
@property
def handle(self):
return self.value.handle
def _initialize(self, value):
if isinstance(value, tf.Variable):
self._value = value
else:
self._value = tf.Variable(
value,
dtype=self._dtype,
trainable=self.trainable,
name=self.name,
aggregation=self._map_aggregation(self.aggregation),
synchronization=self._map_synchronization(self.synchronization),
)
def _initialize_with_initializer(self, initializer):
self._initialize(lambda: initializer(self._shape, dtype=self._dtype))
def _deferred_initialize(self):
if self._value is not None:
raise ValueError(f"Variable {self.path} is already initialized.")
if in_stateless_scope():
raise ValueError(
"You are attempting to initialize a variable "
"while in a stateless scope. This is disallowed. "
"Make sure that all variables are initialized "
"before you start using your layer/model objects."
)
with tf.init_scope():
self._initialize_with_initializer(self._initializer)
self._initializer = None
def _direct_assign(self, value):
self._value.assign(tf.cast(value, self._value.dtype))
def _convert_to_tensor(self, value, dtype=None):
return convert_to_tensor(value, dtype=dtype)
def numpy(self): # noqa: F811
return self.value.numpy()
@property
def shape(self):
return tf.TensorShape(super().shape)
# Overload native accessor.
def __tf_tensor__(self, dtype=None, name=None):
return tf.convert_to_tensor(self.value, dtype=dtype, name=name)
# Methods below are for SavedModel support
@property
def _shared_name(self):
return self.value._shared_name
def _serialize_to_tensors(self):
try:
return self.value._serialize_to_tensors()
except NotImplementedError:
return {"VARIABLE_VALUE": self.value}
def _restore_from_tensors(self, restored_tensors):
try:
return self.value._restore_from_tensors(restored_tensors)
except NotImplementedError:
self.assign(restored_tensors["VARIABLE_VALUE"])
return self.value
def _copy_trackable_to_cpu(self, object_map):
self.value._copy_trackable_to_cpu(object_map)
object_map[self] = tf.Variable(object_map[self.value])
def _export_to_saved_model_graph(
self, object_map, tensor_map, options, **kwargs
):
resource_list = self.value._export_to_saved_model_graph(
object_map, tensor_map, options, **kwargs
)
object_map[self] = tf.Variable(object_map[self.value])
return resource_list
def _write_object_proto(self, proto, options):
return self.value._write_object_proto(proto, options)
def _map_aggregation(self, aggregation):
mapping = {
"none": tf.VariableAggregation.NONE,
"sum": tf.VariableAggregation.SUM,
"mean": tf.VariableAggregation.MEAN,
"only_first_replica": tf.VariableAggregation.ONLY_FIRST_REPLICA,
}
return mapping[aggregation]
def _map_synchronization(self, synchronization):
mapping = {
"none": tf.VariableSynchronization.NONE,
"on_read": tf.VariableSynchronization.ON_READ,
"on_write": tf.VariableSynchronization.ON_WRITE,
"auto": tf.VariableSynchronization.AUTO,
}
return mapping[synchronization]
def convert_to_tensor(x, dtype=None, sparse=None, ragged=None):
if isinstance(x, tf.SparseTensor) and sparse is not None and not sparse:
x = sparse_to_dense(x)
if isinstance(x, tf.RaggedTensor) and ragged is not None and not ragged:
x = x.to_tensor()
if dtype is not None:
dtype = standardize_dtype(dtype)
if not tf.is_tensor(x):
if dtype == "bool" or is_int_dtype(dtype):
# TensorFlow conversion is stricter than other backends, it does not
# allow ints for bools or floats for ints. We convert without dtype
# and cast instead.
x = tf.convert_to_tensor(x)
return tf.cast(x, dtype)
return tf.convert_to_tensor(x, dtype=dtype)
elif dtype is not None and not standardize_dtype(x.dtype) == dtype:
if isinstance(x, tf.SparseTensor):
x_shape = x.shape
x = tf.cast(x, dtype)
x.set_shape(x_shape)
return x
return tf.cast(x, dtype=dtype)
return x
def convert_to_numpy(x):
if isinstance(x, tf.SparseTensor):
x = sparse_to_dense(x)
elif isinstance(x, tf.IndexedSlices):
x = tf.convert_to_tensor(x)
elif isinstance(x, tf.RaggedTensor):
x = x.to_tensor()
return np.array(x)
def is_tensor(x):
return tf.is_tensor(x)
def shape(x):
"""Always return a tuple shape.
`tf.shape` will return a `tf.Tensor`, which differs from the tuple return
type on the torch and jax backends. We write our own method instead which
always returns a tuple, with integer values when the shape is known, and
tensor values when the shape is unknown (this is tf specific, as dynamic
shapes do not apply in other backends).
"""
if isinstance(x, KerasTensor):
return x.shape
if not tf.is_tensor(x):
x = tf.convert_to_tensor(x)
if x.shape == tf.TensorShape(None):
raise ValueError(
"All tensors passed to `ops.shape` must have a statically known "
f"rank. Received: x={x} with unknown rank."
)
shape = x.shape.as_list()
dynamic = tf.shape(x)
for i in range(len(shape)):
if shape[i] is None:
try:
shape[i] = dynamic[i]
except:
# With RaggedTensors, accessing a ragged dimension will fail,
# we leave it as None.
pass
return tuple(shape)
def cast(x, dtype):
dtype = standardize_dtype(dtype)
if isinstance(x, tf.SparseTensor):
x_shape = x.shape
x = tf.cast(x, dtype)
x.set_shape(x_shape)
return x
else:
return tf.cast(x, dtype=dtype)
def compute_output_spec(fn, *args, **kwargs):
with StatelessScope(), SymbolicScope():
graph_name = auto_name("scratch_graph")
with tf.__internal__.FuncGraph(graph_name).as_default():
def convert_keras_tensor_to_tf(x):
if isinstance(x, KerasTensor):
if x.sparse:
return tf.compat.v1.sparse_placeholder(
shape=x.shape, dtype=x.dtype
)
else:
return tf.compat.v1.placeholder(
shape=x.shape, dtype=x.dtype
)
return x
args, kwargs = tree.map_structure(
convert_keras_tensor_to_tf, (args, kwargs)
)
tf_out = fn(*args, **kwargs)
def convert_tf_to_keras_tensor(x):
if tf.is_tensor(x):
return KerasTensor(
x.shape, x.dtype, sparse=isinstance(x, tf.SparseTensor)
)
return x
output_spec = tree.map_structure(convert_tf_to_keras_tensor, tf_out)
return output_spec
def cond(pred, true_fn, false_fn):
if isinstance(pred, tf.Variable):
return tf.cond(pred, true_fn=true_fn, false_fn=false_fn)
return tf.__internal__.smart_cond.smart_cond(
pred, true_fn=true_fn, false_fn=false_fn
)
def vectorized_map(function, elements):
return tf.vectorized_map(function, elements)
def map(f, xs):
xs = tree.map_structure(convert_to_tensor, xs)
def get_fn_output_signature(x):
out = f(x)
return tree.map_structure(tf.TensorSpec.from_tensor, out)
if tree.is_nested(xs):
input = tree.pack_sequence_as(xs, [x[0] for x in tree.flatten(xs)])
fn_output_signature = get_fn_output_signature(input)
return tf.map_fn(f, xs, fn_output_signature=fn_output_signature)
else:
fn_output_signature = get_fn_output_signature(xs[0])
return tf.map_fn(f, xs, fn_output_signature=fn_output_signature)
def scan(f, init, xs=None, length=None, reverse=False, unroll=1):
# We have reimplemented `scan` to match the behavior of `jax.lax.scan`
# Ref: tf.scan, jax.lax.scan
if not callable(f):
raise TypeError(f"`f` should be a callable. Received: f={f}")
if not isinstance(unroll, bool):
if not isinstance(unroll, int) or unroll < 1:
raise ValueError(
"`unroll` must be an positive integer or boolean. "
f"Received: unroll={unroll}"
)
if xs is None and length is None:
raise ValueError("Got no `xs` to scan over and `length` not provided.")
input_is_sequence = tree.is_nested(xs)
output_is_sequence = tree.is_nested(init)
def pack_input(x):
return tree.pack_sequence_as(xs, x) if input_is_sequence else x[0]
def pack_output(x):
return tree.pack_sequence_as(init, x) if output_is_sequence else x[0]
if xs is None:
xs_flat = []
n = int(length)
else:
# xs_flat = flatten_input(xs)
xs_flat = tree.flatten(xs)
xs_flat = [tf.convert_to_tensor(elem) for elem in xs_flat]
n = int(length) if length is not None else tf.shape(xs_flat[0])[0]
# TensorArrays are always flat
xs_array = [
tf.TensorArray(
dtype=x.dtype,
size=n,
dynamic_size=False,
element_shape=x.shape[1:],
infer_shape=True,
)
for x in xs_flat
]
xs_array = [x_a.unstack(x) for x_a, x in zip(xs_array, xs_flat)]
init_flat = tree.flatten(init)
carry_flat = [tf.convert_to_tensor(init) for init in init_flat]
# Store the intermediate values
# Note: there is a constraint that the output of `f` must have the same
# shape and dtype as carry (`init`).
ys_array = [
tf.TensorArray(
dtype=carry.dtype,
size=n,
dynamic_size=False,
element_shape=carry.shape,
infer_shape=True,
)
for carry in carry_flat
]
carry_array = [
tf.TensorArray(
dtype=carry.dtype,
size=1,
dynamic_size=False,
clear_after_read=False,
element_shape=carry.shape,
infer_shape=True,
)
for carry in carry_flat
]
carry_array = [
carry.write(0, c) for (carry, c) in zip(carry_array, carry_flat)
]
def loop_body(i, carry_array, ys_array):
packed_xs = (
pack_input([xs.read(i) for xs in xs_array])
if len(xs_array) > 0
else None
)
packed_carry = pack_output([carry.read(0) for carry in carry_array])
carry, ys = f(packed_carry, packed_xs)
if ys is not None:
flat_ys = tree.flatten(ys)
ys_array = [ys.write(i, v) for (ys, v) in zip(ys_array, flat_ys)]
if carry is not None:
flat_carry = tree.flatten(carry)
carry_array = [
carry.write(0, v) for (carry, v) in zip(carry_array, flat_carry)
]
next_i = i + 1 if not reverse else i - 1
return (next_i, carry_array, ys_array)
if isinstance(unroll, bool):
unroll = max(n, 1) if unroll else 1
_, carry_array, ys_array = tf.while_loop(
lambda i, _1, _2: i >= 0 if reverse else i < n,
loop_body,
(n - 1 if reverse else 0, carry_array, ys_array),
parallel_iterations=unroll,
)
ys_flat = [ys.stack() for ys in ys_array]
carry_flat = [carry.read(0) for carry in carry_array]
if xs is not None:
n_static = xs_flat[0].get_shape().with_rank_at_least(1)[0]
if not isinstance(n_static, int):
for x in xs_flat[1:]:
n_static.assert_is_compatible_with(
x.get_shape().with_rank_at_least(1)[0]
)
for r in ys_flat:
r.set_shape(tf.TensorShape(n_static).concatenate(r.get_shape()[1:]))
return pack_output(carry_flat), pack_output(ys_flat)
def associative_scan(f, elems, reverse=False, axis=0):
# Implementation is the same as tfp.math.scan_associative
# with additional checks to ensure similar behavior with jax
if not callable(f):
raise TypeError(f"`f` should be a callable. Received: f={f}")
elems_flat = tree.flatten(elems)
elems_flat = [tf.convert_to_tensor(elem) for elem in elems_flat]
if reverse:
elems_flat = [tf.reverse(elem, [axis]) for elem in elems_flat]
def _combine(a_flat, b_flat):
a = tree.pack_sequence_as(elems, a_flat)
b = tree.pack_sequence_as(elems, b_flat)
c = f(a, b)
c_flat = tree.flatten(c)
return c_flat
def _get_dim(x):
return shape(x)[axis]
# TODO add constant dim check
num_elems = _get_dim(elems_flat[0])
if not all(_get_dim(elem) == num_elems for elem in elems_flat[1:]):
raise ValueError(
"Array inputs to associative_scan must have the same "
"first dimension. (saw: {})".format(
[tf.shape(elem) for elem in elems_flat]
)
)
def _interleave(a, b, axis):
# [a b c ...] [d e f ...] -> [a d b e c f ...]
num_elems_a = _get_dim(a)
num_elems_b = _get_dim(b)
# Note that interleaving implies rank(a)==rank(b).
axis = tf.where(axis >= 0, axis, tf.rank(a) + axis)
axis = (
int(axis) # Avoid ndarray values.
if tf.get_static_value(axis) is not None
else axis
)
def _interleave_with_b(a):
return tf.reshape(
# Work around lack of support for Tensor axes in
# `tf.stack` by using `concat` and `expand_dims` instead.
tf.concat(
[
tf.expand_dims(a, axis=axis + 1),
tf.expand_dims(b, axis=axis + 1),
],
axis=axis + 1,
),
tf.concat(
[
a.get_shape()[:axis],
[2 * num_elems_b],
a.get_shape()[axis + 1 :],
],
axis=0,
),
)
return tf.cond(
tf.equal(num_elems_a, num_elems_b + 1),
lambda: tf.concat(
[
_interleave_with_b(
slice_along_axis(a, None, -1, axis=axis)
),
slice_along_axis(a, -1, None, axis=axis),
],
axis=axis,
),
lambda: _interleave_with_b(a),
)
def _scan(elems):
elem_length = _get_dim(elems[0])
a = [slice_along_axis(elem, 0, -1, step=2, axis=axis) for elem in elems]
b = [
slice_along_axis(elem, 1, None, step=2, axis=axis) for elem in elems
]
reduced_elems = _combine(a, b)
def _handle_base_case_elem_length_two():
return [
tf.concat(
[slice_along_axis(elem, 0, 1, axis=axis), reduced_elem],
axis=axis,
)
for (reduced_elem, elem) in zip(reduced_elems, elems)
]
def _handle_base_case_elem_length_three():
reduced_reduced_elems = _combine(
reduced_elems,
[slice_along_axis(elem, 2, 3, axis=axis) for elem in elems],
)
return [
tf.concat(
[
slice_along_axis(elem, 0, 1, axis=axis),
reduced_elem,
reduced_reduced_elem,
],
axis=axis,
)
for (reduced_reduced_elem, reduced_elem, elem) in zip(
reduced_reduced_elems, reduced_elems, elems
)
]
at_base_case = tf.logical_or(
tf.equal(elem_length, 2), tf.equal(elem_length, 3)
)
def _base_case():
return tf.cond(
tf.equal(elem_length, 2),
_handle_base_case_elem_length_two,
_handle_base_case_elem_length_three,
)
def _recursive_case():
odd_elems = _scan(reduced_elems)
def _even_length_case():
return _combine(
[
slice_along_axis(odd_elem, 0, -1, axis=axis)
for odd_elem in odd_elems
],
[
slice_along_axis(elem, 2, None, 2, axis=axis)
for elem in elems
],
)
def _odd_length_case():
return _combine(
[odd_elem for odd_elem in odd_elems],
[
slice_along_axis(elem, 2, None, 2, axis=axis)
for elem in elems
],
)
results = tf.cond(
tf.equal(elem_length % 2, 0),
_even_length_case,
_odd_length_case,
)
even_elems = [
tf.concat(
[slice_along_axis(elem, 0, 1, axis=axis), result], axis=axis
)
for (elem, result) in zip(elems, results)
]
return list(
builtins.map(
lambda a, b: _interleave(a, b, axis=axis),
even_elems,
odd_elems,
)
)
return tf.cond(at_base_case, _base_case, _recursive_case)
scans = _scan(elems_flat)
if reverse:
scans = [tf.reverse(scanned, [axis]) for scanned in scans]
return tree.pack_sequence_as(elems, scans)
def scatter(indices, values, shape):
return tf.scatter_nd(indices, values, shape)
def scatter_update(inputs, indices, updates):
return tf.tensor_scatter_nd_update(inputs, indices, updates)
def slice(inputs, start_indices, shape):
return tf.slice(inputs, start_indices, shape)
def slice_update(inputs, start_indices, updates):
return dynamic_update_slice(inputs, updates, start_indices)
def switch(index, branches, *operands):
index = convert_to_tensor(index, "int32")
index = tf.clip_by_value(index, 0, len(branches) - 1)
# Workaround to deal with python closures. More details:
# https://github.com/tensorflow/tensorflow/issues/8776#issuecomment-311383887
def gen_fn(i):
return lambda: branches[i](*operands)
branch_fns = [gen_fn(i) for i in range(len(branches))]
return tf.switch_case(index, branch_fns)
def while_loop(
cond,
body,
loop_vars,
maximum_iterations=None,
):
is_tuple = isinstance(loop_vars, (tuple, list))
loop_vars = tuple(loop_vars) if is_tuple else (loop_vars,)
def _body(*args):
outputs = body(*args)
return tuple(outputs) if is_tuple else (outputs,)
outputs = tf.while_loop(
cond,
_body,
loop_vars,
maximum_iterations=maximum_iterations,
)
return outputs if is_tuple else outputs[0]
def fori_loop(lower, upper, body_fun, init_val):
return tf.while_loop(
lambda i, val: i < upper,
lambda i, val: (i + 1, body_fun(i, val)),
(lower, init_val),
)[1]
def stop_gradient(variable):
return tf.stop_gradient(variable)
def unstack(x, num=None, axis=0):
return tf.unstack(x, num=num, axis=axis)
def random_seed_dtype():
# tensorflow random operation only works on int32/int64, not uint32.
return "int64"
def custom_gradient(fun):
return tf.custom_gradient(f=fun)
def remat(f):
"""Implementation of rematerialization.
Args:
f: The function or operation to rematerialize.
Returns:
A function wrapping f that defines a custom gradient, which
recomputes f on the backwards pass of a gradient call.
"""
return tf.recompute_grad(f)
| Variable |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py | {
"start": 1169,
"end": 1264
} | class ____(metaclass=ABCMeta):
@abstractmethod
def method(self):
foo()
| MetaBase_2 |
python | pandas-dev__pandas | asv_bench/benchmarks/reindex.py | {
"start": 4414,
"end": 4948
} | class ____:
# blog "pandas escaped the zoo"
def setup(self):
n = 50000
indices = Index([f"i-{i}" for i in range(n)], dtype=object)
subsample_size = 40000
self.x = Series(np.random.randn(n), indices)
self.y = Series(
np.random.randn(subsample_size),
index=np.random.choice(indices, subsample_size, replace=False),
)
def time_align_series_irregular_string(self):
self.x + self.y
from .pandas_vb_common import setup # noqa: F401 isort:skip
| Align |
python | huggingface__transformers | src/transformers/models/fnet/modeling_fnet.py | {
"start": 14537,
"end": 14782
} | class ____(PreTrainedModel):
config: FNetConfig
base_model_prefix = "fnet"
supports_gradient_checkpointing = True
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`FNetForPreTraining`].
"""
)
| FNetPreTrainedModel |
python | urllib3__urllib3 | src/urllib3/connectionpool.py | {
"start": 1673,
"end": 3394
} | class ____:
"""
Base class for all connection pools, such as
:class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
.. note::
ConnectionPool.urlopen() does not normalize or percent-encode target URIs
which is useful if your target server doesn't support percent-encoded
target URIs.
"""
scheme: str | None = None
QueueCls = queue.LifoQueue
def __init__(self, host: str, port: int | None = None) -> None:
if not host:
raise LocationValueError("No host specified.")
self.host = _normalize_host(host, scheme=self.scheme)
self.port = port
# This property uses 'normalize_host()' (not '_normalize_host()')
# to avoid removing square braces around IPv6 addresses.
# This value is sent to `HTTPConnection.set_tunnel()` if called
# because square braces are required for HTTP CONNECT tunneling.
self._tunnel_host = normalize_host(host, scheme=self.scheme).lower()
def __str__(self) -> str:
return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})"
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> typing.Literal[False]:
self.close()
# Return False to re-raise any potential exceptions
return False
def close(self) -> None:
"""
Close all pooled connections and disable the pool.
"""
# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252
_blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}
| ConnectionPool |
python | mlflow__mlflow | mlflow/gateway/providers/togetherai.py | {
"start": 11588,
"end": 17022
} | class ____(BaseProvider):
NAME = "TogetherAI"
CONFIG_TYPE = TogetherAIConfig
def __init__(self, config: EndpointConfig) -> None:
super().__init__(config)
if config.model.config is None or not isinstance(config.model.config, TogetherAIConfig):
# Should be unreachable
raise MlflowException.invalid_parameter_value(
f"Invalid config type {config.model.config}"
)
self.togetherai_config: TogetherAIConfig = config.model.config
@property
def base_url(self):
# togetherai seems to support only this url
return "https://api.together.xyz/v1"
@property
def headers(self):
return {"Authorization": f"Bearer {self.togetherai_config.togetherai_api_key}"}
@property
def adapter_class(self) -> type[ProviderAdapter]:
return TogetherAIAdapter
def get_endpoint_url(self, route_type: str) -> str:
if route_type == "llm/v1/chat":
return f"{self.base_url}/chat/completions"
elif route_type == "llm/v1/completions":
return f"{self.base_url}/completions"
elif route_type == "llm/v1/embeddings":
return f"{self.base_url}/embeddings"
else:
raise ValueError(f"Invalid route type {route_type}")
async def _request(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
return await send_request(
headers=self.headers,
base_url=self.base_url,
path=path,
payload=payload,
)
async def _stream_request(
self, path: str, payload: dict[str, Any]
) -> AsyncGenerator[bytes, None]:
return send_stream_request(
headers=self.headers,
base_url=self.base_url,
path=path,
payload=payload,
)
async def embeddings(
self, payload: embeddings_schema.RequestPayload
) -> embeddings_schema.ResponsePayload:
from fastapi.encoders import jsonable_encoder
payload = jsonable_encoder(payload, exclude_none=True)
resp = await self._request(
path="embeddings",
payload=TogetherAIAdapter.embeddings_to_model(payload, self.config),
)
return TogetherAIAdapter.model_to_embeddings(resp, self.config)
async def completions_stream(
self, payload: completions_schema.RequestPayload
) -> AsyncIterable[completions_schema.StreamResponsePayload]:
from fastapi.encoders import jsonable_encoder
payload = jsonable_encoder(payload, exclude_none=True)
if not payload.get("max_tokens"):
raise AIGatewayException(
status_code=422,
detail=(
"max_tokens is not present in payload."
"It is a required parameter for TogetherAI completions."
),
)
stream = await self._stream_request(
path="completions",
payload=TogetherAIAdapter.completions_streaming_to_model(payload, self.config),
)
async for chunk in stream:
chunk = chunk.strip()
if not chunk:
continue
chunk = strip_sse_prefix(chunk.decode("utf-8"))
if chunk == "[DONE]":
return
resp = json.loads(chunk)
yield TogetherAIAdapter.model_to_completions_streaming(resp, self.config)
async def completions(
self, payload: completions_schema.RequestPayload
) -> completions_schema.ResponsePayload:
from fastapi.encoders import jsonable_encoder
payload = jsonable_encoder(payload, exclude_none=True)
if not payload.get("max_tokens"):
raise AIGatewayException(
status_code=422,
detail=(
"max_tokens is not present in payload."
"It is a required parameter for TogetherAI completions."
),
)
resp = await self._request(
path="completions", payload=TogetherAIAdapter.completions_to_model(payload, self.config)
)
return TogetherAIAdapter.model_to_completions(resp, self.config)
async def chat_stream(self, payload: chat_schema.RequestPayload) -> chat_schema.ResponsePayload:
from fastapi.encoders import jsonable_encoder
payload = jsonable_encoder(payload, exclude_none=True)
stream = await self._stream_request(
path="chat/completions",
payload=TogetherAIAdapter.chat_streaming_to_model(payload, self.config),
)
async for chunk in stream:
chunk = chunk.strip()
if not chunk:
continue
chunk = strip_sse_prefix(chunk.decode("utf-8"))
if chunk == "[DONE]":
return
resp = json.loads(chunk)
yield TogetherAIAdapter.model_to_chat_streaming(resp, self.config)
async def chat(self, payload: chat_schema.RequestPayload) -> chat_schema.ResponsePayload:
from fastapi.encoders import jsonable_encoder
payload = jsonable_encoder(payload, exclude_none=True)
resp = await self._request(
path="chat/completions",
payload=TogetherAIAdapter.chat_to_model(payload, self.config),
)
return TogetherAIAdapter.model_to_chat(resp, self.config)
| TogetherAIProvider |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/comms.py | {
"start": 504,
"end": 5768
} | class ____(MetaQObjectHasTraits(
'NewBase', (LoggingConfigurable, SuperQObject), {})):
"""
Manager for Comms in the Frontend
"""
def __init__(self, kernel_client, *args, **kwargs):
super().__init__(*args, **kwargs)
self.comms = {}
self.targets = {}
if kernel_client:
self.init_kernel_client(kernel_client)
def init_kernel_client(self, kernel_client):
"""
connect the kernel, and register message handlers
"""
self.kernel_client = kernel_client
kernel_client.iopub_channel.message_received.connect(self._dispatch)
@QtCore.Slot(object)
def _dispatch(self, msg):
"""Dispatch messages"""
msg_type = msg['header']['msg_type']
handled_msg_types = ['comm_open', 'comm_msg', 'comm_close']
if msg_type in handled_msg_types:
getattr(self, msg_type)(msg)
def new_comm(self, target_name, data=None, metadata=None,
comm_id=None, buffers=None):
"""
Create a new Comm, register it, and open its Kernel-side counterpart
Mimics the auto-registration in `Comm.__init__` in the Jupyter Comm.
argument comm_id is optional
"""
comm = Comm(target_name, self.kernel_client, comm_id)
self.register_comm(comm)
try:
comm.open(data, metadata, buffers)
except Exception:
self.unregister_comm(comm)
raise
return comm
def register_target(self, target_name, f):
"""Register a callable f for a given target name
f will be called with two arguments when a comm_open message is
received with `target`:
- the Comm instance
- the `comm_open` message itself.
f can be a Python callable or an import string for one.
"""
if isinstance(f, str):
f = import_item(f)
self.targets[target_name] = f
def unregister_target(self, target_name, f):
"""Unregister a callable registered with register_target"""
return self.targets.pop(target_name)
def register_comm(self, comm):
"""Register a new comm"""
comm_id = comm.comm_id
comm.kernel_client = self.kernel_client
self.comms[comm_id] = comm
comm.sig_is_closing.connect(self.unregister_comm)
return comm_id
@QtCore.Slot(object)
def unregister_comm(self, comm):
"""Unregister a comm, and close its counterpart."""
# unlike get_comm, this should raise a KeyError
comm.sig_is_closing.disconnect(self.unregister_comm)
self.comms.pop(comm.comm_id)
def get_comm(self, comm_id, closing=False):
"""Get a comm with a particular id
Returns the comm if found, otherwise None.
This will not raise an error,
it will log messages if the comm cannot be found.
If the comm is closing, it might already have closed,
so this is ignored.
"""
try:
return self.comms[comm_id]
except KeyError:
if closing:
return
self.log.warning("No such comm: %s", comm_id)
# don't create the list of keys if debug messages aren't enabled
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug("Current comms: %s", list(self.comms.keys()))
# comm message handlers
def comm_open(self, msg):
"""Handler for comm_open messages"""
content = msg['content']
comm_id = content['comm_id']
target_name = content['target_name']
f = self.targets.get(target_name, None)
comm = Comm(target_name, self.kernel_client, comm_id)
self.register_comm(comm)
if f is None:
self.log.error("No such comm target registered: %s", target_name)
else:
try:
f(comm, msg)
return
except Exception:
self.log.error("Exception opening comm with target: %s",
target_name, exc_info=True)
# Failure.
try:
comm.close()
except Exception:
self.log.error(
"Could not close comm during `comm_open` failure "
"clean-up. The comm may not have been opened yet.""",
exc_info=True)
def comm_close(self, msg):
"""Handler for comm_close messages"""
content = msg['content']
comm_id = content['comm_id']
comm = self.get_comm(comm_id, closing=True)
if comm is None:
return
self.unregister_comm(comm)
try:
comm.handle_close(msg)
except Exception:
self.log.error('Exception in comm_close for %s', comm_id,
exc_info=True)
def comm_msg(self, msg):
"""Handler for comm_msg messages"""
content = msg['content']
comm_id = content['comm_id']
comm = self.get_comm(comm_id)
if comm is None:
return
try:
comm.handle_msg(msg)
except Exception:
self.log.error('Exception in comm_msg for %s', comm_id,
exc_info=True)
| CommManager |
python | uqfoundation__dill | dill/_dill.py | {
"start": 11906,
"end": 12208
} | class ____(dict):
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __missing__(self, key):
if issubclass(key, type):
return save_type
else:
raise KeyError()
| MetaCatchingDict |
python | sympy__sympy | sympy/printing/printer.py | {
"start": 13984,
"end": 15875
} | class ____:
"""
Function wrapper to replace ``**settings`` in the signature with printer defaults
"""
def __init__(self, f, print_cls: Type[Printer]):
# find all the non-setting arguments
params = list(inspect.signature(f).parameters.values())
assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD
self.__other_params = params
self.__print_cls = print_cls
update_wrapper(self, f)
def __reduce__(self):
# Since this is used as a decorator, it replaces the original function.
# The default pickling will try to pickle self.__wrapped__ and fail
# because the wrapped function can't be retrieved by name.
return self.__wrapped__.__qualname__
def __call__(self, *args, **kwargs):
return self.__wrapped__(*args, **kwargs)
@property
def __signature__(self) -> inspect.Signature:
settings = self.__print_cls._get_initial_settings()
return inspect.Signature(
parameters=self.__other_params + [
inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v)
for k, v in settings.items()
],
return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore
)
def print_function(print_cls):
""" A decorator to replace kwargs with the printer settings in __signature__ """
def decorator(f):
if sys.version_info < (3, 9):
# We have to create a subclass so that `help` actually shows the docstring in older Python versions.
# IPython and Sphinx do not need this, only a raw Python console.
cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), {"__doc__": f.__doc__})
else:
cls = _PrintFunction
return cls(f, print_cls)
return decorator
| _PrintFunction |
python | davidhalter__jedi | test/completion/arrays.py | {
"start": 4273,
"end": 4476
} | class ____():
def __getitem__(self, index):
return [1, 1.0, 's'][index]
#? float()
GetItemWithList()[1]
for i in 0, 2:
#? int() str()
GetItemWithList()[i]
# With super
| GetItemWithList |
python | django__django | tests/migrations/models.py | {
"start": 1434,
"end": 1518
} | class ____(BaseFoodManager.from_queryset(FoodQuerySet)):
pass
| NoMigrationFoodManager |
python | kamyu104__LeetCode-Solutions | Python/next-palindrome-using-same-digits.py | {
"start": 29,
"end": 1185
} | class ____(object):
def nextPalindrome(self, num):
"""
:type num: str
:rtype: str
"""
def next_permutation(nums, begin, end):
def reverse(nums, begin, end):
left, right = begin, end-1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
k, l = begin-1, begin
for i in reversed(xrange(begin, end-1)):
if nums[i] < nums[i+1]:
k = i
break
else:
reverse(nums, begin, end)
return False
for i in reversed(xrange(k+1, end)):
if nums[i] > nums[k]:
l = i
break
nums[k], nums[l] = nums[l], nums[k]
reverse(nums, k+1, end)
return True
nums = list(num)
if not next_permutation(nums, 0, len(nums)//2):
return ""
for i in xrange(len(nums)//2):
nums[-1-i] = nums[i]
return "".join(nums)
| Solution |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 15183,
"end": 16348
} | class ____(MarkdownList):
"""An ordered list Markdown block."""
DEFAULT_CSS = """
MarkdownOrderedList {
margin: 0 0 1 0;
padding: 0 0;
}
MarkdownOrderedList Horizontal {
height: auto;
width: 1fr;
}
MarkdownOrderedList Vertical {
height: auto;
width: 1fr;
}
"""
def compose(self) -> ComposeResult:
suffix = ". "
start = 1
if self._blocks and isinstance(self._blocks[0], MarkdownOrderedListItem):
try:
start = int(self._blocks[0].bullet)
except ValueError:
pass
symbol_size = max(
len(f"{number}{suffix}")
for number, block in enumerate(self._blocks, start)
if isinstance(block, MarkdownListItem)
)
for number, block in enumerate(self._blocks, start):
if isinstance(block, MarkdownListItem):
bullet = MarkdownBullet()
bullet.symbol = f"{number}{suffix}".rjust(symbol_size + 1)
yield Horizontal(bullet, Vertical(*block._blocks))
self._blocks.clear()
| MarkdownOrderedList |
python | getsentry__sentry | src/sentry/utils/types.py | {
"start": 361,
"end": 1557
} | class ____(typing.Generic[T]):
"""Base Type that provides type coercion"""
name = ""
# Default value to be returned when initializing
default: T
# Types that do not need to be coerced
expected_types: tuple[type[object], ...] = ()
# Types that are acceptable for coercion
compatible_types: tuple[type[object], ...] = (str,)
def __call__(self, value: object | None = None) -> T:
if value is None:
return self._default()
if self.test(value):
return value
if isinstance(value, self.compatible_types):
rv = self.convert(value)
# Make sure convert was able to do the right thing
# and give us the type we were expecting
if self.test(rv):
return rv
raise InvalidTypeError(f"{value!r} is not a valid {self!r}")
def convert(self, value):
return value
def _default(self) -> T:
return self.default
def test(self, value: object) -> TypeGuard[T]:
"""Check if the value is the correct type or not"""
return isinstance(value, self.expected_types)
def __repr__(self) -> str:
return self.name
| Type |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/bigquery.py | {
"start": 5460,
"end": 13574
} | class ____(
_BigQueryDbHookMixin, SQLCheckOperator, _BigQueryOperatorsEncryptionConfigurationMixin
):
"""
Performs checks against BigQuery.
This operator expects a SQL query that returns a single row. Each value on
that row is evaluated using a Python ``bool`` cast. If any of the values
is falsy, the check errors out.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BigQueryCheckOperator`
Note that Python bool casting evals the following as *False*:
* ``False``
* ``0``
* Empty string (``""``)
* Empty list (``[]``)
* Empty dictionary or set (``{}``)
Given a query like ``SELECT COUNT(*) FROM foo``, it will fail only if
the count equals to zero. You can craft much more complex query that could,
for instance, check that the table has the same number of rows as the source
table upstream, or that the count of today's partition is greater than
yesterday's partition, or that a set of metrics are less than three standard
deviation for the 7-day average.
This operator can be used as a data quality check in your pipeline.
Depending on where you put it in your DAG, you have the choice to stop the
critical path, preventing from publishing dubious data, or on the side and
receive email alerts without stopping the progress of the DAG.
:param sql: SQL to execute.
:param gcp_conn_id: Connection ID for Google Cloud.
:param use_legacy_sql: Whether to use legacy SQL (true) or standard SQL (false).
:param location: The geographic location of the job. See details at:
https://cloud.google.com/bigquery/docs/locations#specifying_your_location
:param impersonation_chain: Optional service account to impersonate using
short-term credentials, or chained list of accounts required to get the
access token of the last account in the list, which will be impersonated
in the request. If set as a string, the account must grant the
originating account the Service Account Token Creator IAM role. If set
as a sequence, the identities from the list must grant Service Account
Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account. (templated)
:param labels: a dictionary containing labels for the table, passed to BigQuery.
:param encryption_configuration: (Optional) Custom encryption configuration (e.g., Cloud KMS keys).
.. code-block:: python
encryption_configuration = {
"kmsKeyName": "projects/PROJECT/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY",
}
:param deferrable: Run operator in the deferrable mode.
:param poll_interval: (Deferrable mode only) polling period in seconds to
check for the status of job.
:param query_params: a list of dictionary containing query parameter types and
values, passed to BigQuery. The structure of dictionary should look like
'queryParameters' in Google BigQuery Jobs API:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs.
For example, [{ 'name': 'corpus', 'parameterType': { 'type': 'STRING' },
'parameterValue': { 'value': 'romeoandjuliet' } }]. (templated)
:param project_id: Google Cloud Project where the job is running
"""
template_fields: Sequence[str] = (
"sql",
"gcp_conn_id",
"impersonation_chain",
"labels",
"query_params",
)
template_ext: Sequence[str] = (".sql",)
ui_color = BigQueryUIColors.CHECK.value
conn_id_field = "gcp_conn_id"
def __init__(
self,
*,
sql: str,
gcp_conn_id: str = "google_cloud_default",
project_id: str = PROVIDE_PROJECT_ID,
use_legacy_sql: bool = True,
location: str | None = None,
impersonation_chain: str | Sequence[str] | None = None,
labels: dict | None = None,
encryption_configuration: dict | None = None,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
poll_interval: float = 4.0,
query_params: list | None = None,
**kwargs,
) -> None:
super().__init__(sql=sql, **kwargs)
self.gcp_conn_id = gcp_conn_id
self.use_legacy_sql = use_legacy_sql
self.location = location
self.impersonation_chain = impersonation_chain
self.labels = labels
self.encryption_configuration = encryption_configuration
self.deferrable = deferrable
self.poll_interval = poll_interval
self.query_params = query_params
self.project_id = project_id
def _submit_job(
self,
hook: BigQueryHook,
job_id: str,
) -> BigQueryJob:
"""Submit a new job and get the job id for polling the status using Trigger."""
configuration = {"query": {"query": self.sql, "useLegacySql": self.use_legacy_sql}}
if self.query_params:
configuration["query"]["queryParameters"] = self.query_params
self.include_encryption_configuration(configuration, "query")
return hook.insert_job(
configuration=configuration,
project_id=self.project_id,
location=self.location,
job_id=job_id,
nowait=True,
)
def execute(self, context: Context):
if not self.deferrable:
super().execute(context=context)
else:
hook = BigQueryHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
if self.project_id is None:
self.project_id = hook.project_id
job = self._submit_job(hook, job_id="")
context["ti"].xcom_push(key="job_id", value=job.job_id)
if job.running():
self.defer(
timeout=self.execution_timeout,
trigger=BigQueryCheckTrigger(
conn_id=self.gcp_conn_id,
job_id=job.job_id,
project_id=self.project_id,
location=self.location or hook.location,
poll_interval=self.poll_interval,
impersonation_chain=self.impersonation_chain,
),
method_name="execute_complete",
)
self._handle_job_error(job)
# job.result() returns a RowIterator. Mypy expects an instance of SupportsNext[Any] for
# the next() call which the RowIterator does not resemble to. Hence, ignore the arg-type error.
# Row passed to _validate_records is a collection of values only, without column names.
self._validate_records(next(iter(job.result()), [])) # type: ignore[arg-type]
self.log.info("Current state of job %s is %s", job.job_id, job.state)
@staticmethod
def _handle_job_error(job: BigQueryJob | UnknownJob) -> None:
if job.error_result:
raise AirflowException(f"BigQuery job {job.job_id} failed: {job.error_result}")
def _validate_records(self, records) -> None:
if not records:
raise AirflowException(f"The following query returned zero rows: {self.sql}")
if not all(records):
self._raise_exception(f"Test failed.\nQuery:\n{self.sql}\nResults:\n{records!s}")
def execute_complete(self, context: Context, event: dict[str, Any]) -> None:
"""
Act as a callback for when the trigger fires.
This returns immediately. It relies on trigger to throw an exception,
otherwise it assumes execution was successful.
"""
if event["status"] == "error":
raise AirflowException(event["message"])
self._validate_records(event["records"])
self.log.info("Record: %s", event["records"])
self.log.info("Success.")
| BigQueryCheckOperator |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/components/simple_asset.py | {
"start": 390,
"end": 970
} | class ____(Component, Resolvable, Model):
"""A simple asset that returns a constant string value."""
asset_key: ResolvedAssetKey
value: str
@classmethod
def get_spec(cls):
return ComponentTypeSpec(
owners=["john@dagster.io", "jane@dagster.io"],
tags=["a", "b", "c"],
)
def build_defs(self, context: ComponentLoadContext) -> Definitions:
@asset(key=self.asset_key)
def dummy(context: AssetExecutionContext):
return self.value
return Definitions(assets=[dummy])
| SimpleAssetComponent |
python | django-extensions__django-extensions | django_extensions/db/fields/__init__.py | {
"start": 10498,
"end": 15158
} | class ____(UniqueFieldMixin, CharField):
"""
RandomCharField
By default, sets editable=False, blank=True, unique=False.
Required arguments:
length
Specifies the length of the field
Optional arguments:
unique
If set to True, duplicate entries are not allowed (default: False)
lowercase
If set to True, lowercase the alpha characters (default: False)
uppercase
If set to True, uppercase the alpha characters (default: False)
include_alpha
If set to True, include alpha characters (default: True)
include_digits
If set to True, include digit characters (default: True)
include_punctuation
If set to True, include punctuation characters (default: False)
keep_default
If set to True, keeps the default initialization value (default: False)
"""
def __init__(self, *args, **kwargs):
kwargs.setdefault("blank", True)
kwargs.setdefault("editable", False)
self.length = kwargs.pop("length", None)
if self.length is None:
raise ValueError("missing 'length' argument")
kwargs["max_length"] = self.length
self.lowercase = kwargs.pop("lowercase", False)
self.check_is_bool("lowercase")
self.uppercase = kwargs.pop("uppercase", False)
self.check_is_bool("uppercase")
if self.uppercase and self.lowercase:
raise ValueError(
"the 'lowercase' and 'uppercase' arguments are mutually exclusive"
)
self.include_digits = kwargs.pop("include_digits", True)
self.check_is_bool("include_digits")
self.include_alpha = kwargs.pop("include_alpha", True)
self.check_is_bool("include_alpha")
self.include_punctuation = kwargs.pop("include_punctuation", False)
self.keep_default = kwargs.pop("keep_default", False)
self.check_is_bool("include_punctuation")
self.max_unique_query_attempts = kwargs.pop(
"max_unique_query_attempts", MAX_UNIQUE_QUERY_ATTEMPTS
)
# Set unique=False unless it's been set manually.
if "unique" not in kwargs:
kwargs["unique"] = False
super().__init__(*args, **kwargs)
def random_char_generator(self, chars):
for i in range(self.max_unique_query_attempts):
yield "".join(get_random_string(self.length, chars))
raise RuntimeError(
"max random character attempts exceeded (%s)"
% self.max_unique_query_attempts
)
def in_unique_together(self, model_instance):
for params in model_instance._meta.unique_together:
if self.attname in params:
return True
return False
def pre_save(self, model_instance, add):
if (not add or self.keep_default) and getattr(
model_instance, self.attname
) != "":
return getattr(model_instance, self.attname)
population = ""
if self.include_alpha:
if self.lowercase:
population += string.ascii_lowercase
elif self.uppercase:
population += string.ascii_uppercase
else:
population += string.ascii_letters
if self.include_digits:
population += string.digits
if self.include_punctuation:
population += string.punctuation
random_chars = self.random_char_generator(population)
if not self.unique and not self.in_unique_together(model_instance):
new = next(random_chars)
setattr(model_instance, self.attname, new)
return new
return self.find_unique(
model_instance,
model_instance._meta.get_field(self.attname),
random_chars,
)
def internal_type(self):
return "CharField"
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
kwargs["length"] = self.length
del kwargs["max_length"]
if self.lowercase is True:
kwargs["lowercase"] = self.lowercase
if self.uppercase is True:
kwargs["uppercase"] = self.uppercase
if self.include_alpha is False:
kwargs["include_alpha"] = self.include_alpha
if self.include_digits is False:
kwargs["include_digits"] = self.include_digits
if self.include_punctuation is True:
kwargs["include_punctuation"] = self.include_punctuation
if self.unique is True:
kwargs["unique"] = self.unique
return name, path, args, kwargs
| RandomCharField |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/invocation.py | {
"start": 6704,
"end": 7453
} | class ____:
"""Maintains information about the execution that can only be updated during execution (when
the context is bound), but can be read after execution is complete. It needs to be cleared before
the context is used for another execution.
This is not implemented as a NamedTuple because the various attributes will be mutated during
execution.
"""
def __init__(self):
self.user_events: list[UserEvent] = []
self.seen_outputs: dict[str, Union[str, set[str]]] = {}
self.output_metadata: dict[str, dict[str, Union[Any, Mapping[str, Any]]]] = {}
self.requires_typed_event_stream: bool = False
self.typed_event_stream_error_message: Optional[str] = None
| DirectExecutionProperties |
python | numba__numba | numba/tests/test_dyn_array.py | {
"start": 18236,
"end": 22541
} | class ____(ConstructorBaseTest, TestCase):
def setUp(self):
super(TestNdZeros, self).setUp()
self.pyfunc = np.zeros
def check_result_value(self, ret, expected):
np.testing.assert_equal(ret, expected)
def test_0d(self):
pyfunc = self.pyfunc
def func():
return pyfunc(())
self.check_0d(func)
def test_1d(self):
pyfunc = self.pyfunc
def func(n):
return pyfunc(n)
self.check_1d(func)
def test_1d_dtype(self):
pyfunc = self.pyfunc
def func(n):
return pyfunc(n, np.int32)
self.check_1d(func)
def test_1d_dtype_instance(self):
# dtype as numpy dtype, not as scalar class
pyfunc = self.pyfunc
_dtype = np.dtype('int32')
def func(n):
return pyfunc(n, _dtype)
self.check_1d(func)
def test_1d_dtype_str(self):
pyfunc = self.pyfunc
_dtype = 'int32'
def func(n):
return pyfunc(n, _dtype)
self.check_1d(func)
def func(n):
return pyfunc(n, 'complex128')
self.check_1d(func)
def test_1d_dtype_str_alternative_spelling(self):
# like test_1d_dtype_str but using the shorthand type spellings
pyfunc = self.pyfunc
_dtype = 'i4'
def func(n):
return pyfunc(n, _dtype)
self.check_1d(func)
def func(n):
return pyfunc(n, 'c8')
self.check_1d(func)
def test_1d_dtype_str_structured_dtype(self):
# test_1d_dtype_str but using a structured dtype
pyfunc = self.pyfunc
_dtype = "i4, (2,3)f8"
def func(n):
return pyfunc(n, _dtype)
self.check_1d(func)
def test_1d_dtype_non_const_str(self):
pyfunc = self.pyfunc
@njit
def func(n, dt):
return pyfunc(n, dt)
with self.assertRaises(TypingError) as raises:
func(5, 'int32')
excstr = str(raises.exception)
msg = (f"If np.{self.pyfunc.__name__} dtype is a string it must be a "
"string constant.")
self.assertIn(msg, excstr)
def test_1d_dtype_invalid_str(self):
pyfunc = self.pyfunc
@njit
def func(n):
return pyfunc(n, 'ABCDEF')
with self.assertRaises(TypingError) as raises:
func(5)
excstr = str(raises.exception)
self.assertIn("Invalid NumPy dtype specified: 'ABCDEF'", excstr)
def test_2d(self):
pyfunc = self.pyfunc
def func(m, n):
return pyfunc((m, n))
self.check_2d(func)
def test_2d_shape_dtypes(self):
# Test for issue #4575
pyfunc = self.pyfunc
def func1(m, n):
return pyfunc((np.int16(m), np.int32(n)))
self.check_2d(func1)
# Using a 64-bit value checks that 32 bit systems will downcast to intp
def func2(m, n):
return pyfunc((np.int64(m), np.int8(n)))
self.check_2d(func2)
# Make sure an error is thrown if we can't downcast safely
if config.IS_32BITS:
cfunc = nrtjit(lambda m, n: pyfunc((m, n)))
with self.assertRaises(ValueError):
cfunc(np.int64(1 << (32 - 1)), 1)
def test_2d_dtype_kwarg(self):
pyfunc = self.pyfunc
def func(m, n):
return pyfunc((m, n), dtype=np.complex64)
self.check_2d(func)
def test_2d_dtype_str_kwarg(self):
pyfunc = self.pyfunc
def func(m, n):
return pyfunc((m, n), dtype='complex64')
self.check_2d(func)
def test_2d_dtype_str_kwarg_alternative_spelling(self):
# as test_2d_dtype_str_kwarg but with the numpy shorthand type spelling
pyfunc = self.pyfunc
def func(m, n):
return pyfunc((m, n), dtype='c8')
self.check_2d(func)
def test_alloc_size(self):
pyfunc = self.pyfunc
width = types.intp.bitwidth
def gen_func(shape, dtype):
return lambda : pyfunc(shape, dtype)
# Under these values numba will segfault, but that's another issue
self.check_alloc_size(gen_func(1 << width - 2, np.intp))
self.check_alloc_size(gen_func((1 << width - 8, 64), np.intp))
| TestNdZeros |
python | Textualize__textual | src/textual/filter.py | {
"start": 1917,
"end": 2487
} | class ____(LineFilter):
"""Convert all colors to monochrome."""
def apply(self, segments: list[Segment], background: Color) -> list[Segment]:
"""Transform a list of segments.
Args:
segments: A list of segments.
background: The background color.
Returns:
A new list of segments.
"""
_monochrome_style = monochrome_style
_Segment = Segment
return [
_Segment(text, _monochrome_style(style), None)
for text, style, _ in segments
]
| Monochrome |
python | scikit-learn__scikit-learn | sklearn/linear_model/_stochastic_gradient.py | {
"start": 50449,
"end": 61783
} | class ____(RegressorMixin, BaseSGD):
loss_functions = {
"squared_error": (CyHalfSquaredError,),
"huber": (CyHuberLoss, DEFAULT_EPSILON),
"epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON),
"squared_epsilon_insensitive": (SquaredEpsilonInsensitive, DEFAULT_EPSILON),
}
_parameter_constraints: dict = {
**BaseSGD._parameter_constraints,
"loss": [StrOptions(set(loss_functions))],
"early_stopping": ["boolean"],
"validation_fraction": [Interval(Real, 0, 1, closed="neither")],
"n_iter_no_change": [Interval(Integral, 1, None, closed="left")],
}
@abstractmethod
def __init__(
self,
loss="squared_error",
*,
penalty="l2",
alpha=0.0001,
l1_ratio=0.15,
fit_intercept=True,
max_iter=1000,
tol=1e-3,
shuffle=True,
verbose=0,
epsilon=DEFAULT_EPSILON,
random_state=None,
learning_rate="invscaling",
eta0=0.01,
power_t=0.25,
early_stopping=False,
validation_fraction=0.1,
n_iter_no_change=5,
warm_start=False,
average=False,
):
super().__init__(
loss=loss,
penalty=penalty,
alpha=alpha,
l1_ratio=l1_ratio,
fit_intercept=fit_intercept,
max_iter=max_iter,
tol=tol,
shuffle=shuffle,
verbose=verbose,
epsilon=epsilon,
random_state=random_state,
learning_rate=learning_rate,
eta0=eta0,
power_t=power_t,
early_stopping=early_stopping,
validation_fraction=validation_fraction,
n_iter_no_change=n_iter_no_change,
warm_start=warm_start,
average=average,
)
def _partial_fit(
self,
X,
y,
alpha,
loss,
learning_rate,
max_iter,
sample_weight,
coef_init,
intercept_init,
):
first_call = getattr(self, "coef_", None) is None
X, y = validate_data(
self,
X,
y,
accept_sparse="csr",
copy=False,
order="C",
dtype=[np.float64, np.float32],
accept_large_sparse=False,
reset=first_call,
)
y = y.astype(X.dtype, copy=False)
n_samples, n_features = X.shape
sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype)
# Allocate datastructures from input arguments
if first_call:
self._allocate_parameter_mem(
n_classes=1,
n_features=n_features,
input_dtype=X.dtype,
coef_init=coef_init,
intercept_init=intercept_init,
)
if self.average > 0 and getattr(self, "_average_coef", None) is None:
self._average_coef = np.zeros(n_features, dtype=X.dtype, order="C")
self._average_intercept = np.zeros(1, dtype=X.dtype, order="C")
self._fit_regressor(X, y, alpha, loss, learning_rate, sample_weight, max_iter)
return self
@_fit_context(prefer_skip_nested_validation=True)
def partial_fit(self, X, y, sample_weight=None):
"""Perform one epoch of stochastic gradient descent on given samples.
Internally, this method uses ``max_iter = 1``. Therefore, it is not
guaranteed that a minimum of the cost function is reached after calling
it once. Matters such as objective convergence and early stopping
should be handled by the user.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Subset of training data.
y : numpy array of shape (n_samples,)
Subset of target values.
sample_weight : array-like, shape (n_samples,), default=None
Weights applied to individual samples.
If not provided, uniform weights are assumed.
Returns
-------
self : object
Returns an instance of self.
"""
if not hasattr(self, "coef_"):
self._more_validate_params(for_partial_fit=True)
return self._partial_fit(
X,
y,
self.alpha,
loss=self.loss,
learning_rate=self.learning_rate,
max_iter=1,
sample_weight=sample_weight,
coef_init=None,
intercept_init=None,
)
def _fit(
self,
X,
y,
alpha,
loss,
learning_rate,
coef_init=None,
intercept_init=None,
sample_weight=None,
):
if self.warm_start and getattr(self, "coef_", None) is not None:
if coef_init is None:
coef_init = self.coef_
if intercept_init is None:
intercept_init = self.intercept_
else:
self.coef_ = None
self.intercept_ = None
# Clear iteration count for multiple call to fit.
self.t_ = 1.0
self._partial_fit(
X,
y,
alpha,
loss,
learning_rate,
self.max_iter,
sample_weight,
coef_init,
intercept_init,
)
if (
self.tol is not None
and self.tol > -np.inf
and self.n_iter_ == self.max_iter
):
warnings.warn(
(
"Maximum number of iteration reached before "
"convergence. Consider increasing max_iter to "
"improve the fit."
),
ConvergenceWarning,
)
if self.power_t < 0:
warnings.warn(
"Negative values for `power_t` are deprecated in version 1.8 "
"and will raise an error in 1.10. "
"Use values in the range [0.0, inf) instead.",
FutureWarning,
)
return self
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,)
Target values.
coef_init : ndarray of shape (n_features,), default=None
The initial coefficients to warm-start the optimization.
intercept_init : ndarray of shape (1,), default=None
The initial intercept to warm-start the optimization.
sample_weight : array-like, shape (n_samples,), default=None
Weights applied to individual samples (1. for unweighted).
Returns
-------
self : object
Fitted `SGDRegressor` estimator.
"""
self._more_validate_params()
return self._fit(
X,
y,
alpha=self.alpha,
loss=self.loss,
learning_rate=self.learning_rate,
coef_init=coef_init,
intercept_init=intercept_init,
sample_weight=sample_weight,
)
def _decision_function(self, X):
"""Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
ndarray of shape (n_samples,)
Predicted target values per element in X.
"""
check_is_fitted(self)
X = validate_data(self, X, accept_sparse="csr", reset=False)
scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_
return scores.ravel()
def predict(self, X):
"""Predict using the linear model.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Input data.
Returns
-------
ndarray of shape (n_samples,)
Predicted target values per element in X.
"""
return self._decision_function(X)
def _fit_regressor(self, X, y, alpha, loss, learning_rate, sample_weight, max_iter):
loss_function = self._get_loss_function(loss)
penalty_type = self._get_penalty_type(self.penalty)
learning_rate_type = self._get_learning_rate_type(learning_rate)
if not hasattr(self, "t_"):
self.t_ = 1.0
validation_mask = self._make_validation_split(y, sample_mask=sample_weight > 0)
validation_score_cb = self._make_validation_score_cb(
validation_mask, X, y, sample_weight
)
random_state = check_random_state(self.random_state)
# numpy mtrand expects a C long which is a signed 32 bit integer under
# Windows
seed = random_state.randint(0, MAX_INT)
dataset, intercept_decay = make_dataset(
X, y, sample_weight, random_state=random_state
)
tol = self.tol if self.tol is not None else -np.inf
if self.average:
coef = self._standard_coef
intercept = self._standard_intercept
average_coef = self._average_coef
average_intercept = self._average_intercept
else:
coef = self.coef_
intercept = self.intercept_
average_coef = None # Not used
average_intercept = [0] # Not used
_plain_sgd = _get_plain_sgd_function(input_dtype=coef.dtype)
coef, intercept, average_coef, average_intercept, self.n_iter_ = _plain_sgd(
coef,
intercept[0],
average_coef,
average_intercept[0],
loss_function,
penalty_type,
alpha,
self._get_l1_ratio(),
dataset,
validation_mask,
self.early_stopping,
validation_score_cb,
int(self.n_iter_no_change),
max_iter,
tol,
int(self.fit_intercept),
int(self.verbose),
int(self.shuffle),
seed,
1.0,
1.0,
learning_rate_type,
self.eta0,
self.power_t,
0,
self.t_,
intercept_decay,
self.average,
)
self.t_ += self.n_iter_ * X.shape[0]
if self.average > 0:
self._average_intercept = np.atleast_1d(average_intercept)
self._standard_intercept = np.atleast_1d(intercept)
if self.average <= self.t_ - 1.0:
# made enough updates for averaging to be taken into account
self.coef_ = average_coef
self.intercept_ = np.atleast_1d(average_intercept)
else:
self.coef_ = coef
self.intercept_ = np.atleast_1d(intercept)
else:
self.intercept_ = np.atleast_1d(intercept)
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.sparse = True
return tags
| BaseSGDRegressor |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 44440,
"end": 45721
} | class ____(BaseValidator):
"""
"colorlist": {
"description": "A list of colors. Must be an {array} containing
valid colors.",
"requiredOpts": [],
"otherOpts": [
"dflt"
]
}
"""
def __init__(self, plotly_name, parent_name, **kwargs):
super(ColorlistValidator, self).__init__(
plotly_name=plotly_name, parent_name=parent_name, **kwargs
)
def description(self):
return """\
The '{plotly_name}' property is a colorlist that may be specified
as a tuple, list, one-dimensional numpy array, or pandas Series of valid
color strings""".format(plotly_name=self.plotly_name)
def validate_coerce(self, v):
if is_none_or_typed_array_spec(v):
pass
elif is_array(v):
validated_v = [
ColorValidator.perform_validate_coerce(e, allow_number=False) for e in v
]
invalid_els = [
el for el, validated_el in zip(v, validated_v) if validated_el is None
]
if invalid_els:
self.raise_invalid_elements(invalid_els)
v = to_scalar_or_list(v)
else:
self.raise_invalid_val(v)
return v
| ColorlistValidator |
python | euske__pdfminer | pdfminer/pdfinterp.py | {
"start": 1273,
"end": 2583
} | class ____:
def __init__(self):
self.font = None
self.fontsize = 0
self.charspace = 0
self.wordspace = 0
self.scaling = 100
self.leading = 0
self.render = 0
self.rise = 0
self.reset()
# self.matrix is set
# self.linematrix is set
return
def __repr__(self):
return ('<PDFTextState: font=%r, fontsize=%r, charspace=%r, wordspace=%r, '
' scaling=%r, leading=%r, render=%r, rise=%r, '
' matrix=%r, linematrix=%r>' %
(self.font, self.fontsize, self.charspace, self.wordspace,
self.scaling, self.leading, self.render, self.rise,
self.matrix, self.linematrix))
def copy(self):
obj = PDFTextState()
obj.font = self.font
obj.fontsize = self.fontsize
obj.charspace = self.charspace
obj.wordspace = self.wordspace
obj.scaling = self.scaling
obj.leading = self.leading
obj.render = self.render
obj.rise = self.rise
obj.matrix = self.matrix
obj.linematrix = self.linematrix
return obj
def reset(self):
self.matrix = MATRIX_IDENTITY
self.linematrix = (0, 0)
return
## PDFGraphicState
##
| PDFTextState |
python | django__django | tests/custom_lookups/tests.py | {
"start": 2731,
"end": 3704
} | class ____(models.lookups.Lookup):
lookup_name = "exact"
def as_sql(self, compiler, connection):
# We will need to skip the extract part, and instead go
# directly with the originating field, that is self.lhs.lhs
lhs_sql, lhs_params = self.process_lhs(compiler, connection, self.lhs.lhs)
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
# Note that we must be careful so that we have params in the
# same order as we have the parts in the SQL.
params = lhs_params + rhs_params + lhs_params + rhs_params
# We use PostgreSQL specific SQL here. Note that we must do the
# conversions in SQL instead of in Python to support F() references.
return (
"%(lhs)s >= (%(rhs)s || '-01-01')::date "
"AND %(lhs)s <= (%(rhs)s || '-12-31')::date"
% {"lhs": lhs_sql, "rhs": rhs_sql},
params,
)
@YearTransform.register_lookup
| YearExact |
python | openai__openai-python | src/openai/_module_client.py | {
"start": 3653,
"end": 3805
} | class ____(LazyProxy["VectorStores"]):
@override
def __load__(self) -> VectorStores:
return _load_client().vector_stores
| VectorStoresProxy |
python | ipython__ipython | IPython/testing/plugin/pytest_ipdoctest.py | {
"start": 19883,
"end": 30053
} | class ____(pytest.Module):
def collect(self) -> Iterable[IPDoctestItem]:
import doctest
from .ipdoctest import DocTestFinder, IPDocTestParser
class MockAwareDocTestFinder(DocTestFinder):
"""A hackish ipdoctest finder that overrides stdlib internals to fix a stdlib bug.
https://github.com/pytest-dev/pytest/issues/3456
https://bugs.python.org/issue25532
"""
def _find_lineno(self, obj, source_lines):
"""Doctest code does not take into account `@property`, this
is a hackish way to fix it. https://bugs.python.org/issue17446
Wrapped Doctests will need to be unwrapped so the correct
line number is returned. This will be reported upstream. #8796
"""
if isinstance(obj, property):
obj = getattr(obj, "fget", obj)
if hasattr(obj, "__wrapped__"):
# Get the main obj in case of it being wrapped
obj = inspect.unwrap(obj)
# Type ignored because this is a private function.
return super()._find_lineno( # type:ignore[misc]
obj,
source_lines,
)
def _find(
self, tests, obj, name, module, source_lines, globs, seen
) -> None:
if _is_mocked(obj):
return
with _patch_unwrap_mock_aware():
# Type ignored because this is a private function.
super()._find( # type:ignore[misc]
tests, obj, name, module, source_lines, globs, seen
)
if self.path.name == "conftest.py":
if pytest_version[0] < 7:
module = self.config.pluginmanager._importconftest(
self.path,
self.config.getoption("importmode"),
)
else:
kwargs = {"rootpath": self.config.rootpath}
if pytest_version >= (8, 1):
kwargs["consider_namespace_packages"] = False
module = self.config.pluginmanager._importconftest(
self.path,
self.config.getoption("importmode"),
**kwargs,
)
else:
try:
kwargs = {"root": self.config.rootpath}
if pytest_version >= (8, 1):
kwargs["consider_namespace_packages"] = False
module = import_path(self.path, **kwargs)
except ImportError:
if self.config.getvalue("ipdoctest_ignore_import_errors"):
pytest.skip("unable to import module %r" % self.path)
else:
raise
# Uses internal doctest module parsing mechanism.
finder = MockAwareDocTestFinder(parser=IPDocTestParser())
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=False,
optionflags=optionflags,
checker=_get_checker(),
continue_on_failure=_get_continue_on_failure(self.config),
)
for test in finder.find(module, module.__name__):
if test.examples: # skip empty ipdoctests
yield IPDoctestItem.from_parent(
self, name=test.name, runner=runner, dtest=test
)
if pytest_version[0] < 7:
@property
def path(self) -> Path:
return Path(self.fspath)
@classmethod
def from_parent(
cls,
parent,
*,
fspath=None,
path: Optional[Path] = None,
**kw,
):
if path is not None:
import py.path
fspath = py.path.local(path)
return super().from_parent(parent=parent, fspath=fspath, **kw)
def _setup_fixtures(doctest_item: IPDoctestItem) -> FixtureRequest:
"""Used by IPDoctestTextfile and IPDoctestItem to setup fixture information."""
def func() -> None:
pass
doctest_item.funcargs = {} # type: ignore[attr-defined]
fm = doctest_item.session._fixturemanager
kwargs = {"node": doctest_item, "func": func, "cls": None}
if pytest_version <= (8, 0):
kwargs["funcargs"] = False
doctest_item._fixtureinfo = fm.getfixtureinfo( # type: ignore[attr-defined]
**kwargs
)
fixture_request = FixtureRequest(doctest_item, _ispytest=True)
if pytest_version <= (8, 0):
fixture_request._fillfixtures()
return fixture_request
def _init_checker_class() -> Type["IPDoctestOutputChecker"]:
import doctest
import re
from .ipdoctest import IPDoctestOutputChecker
class LiteralsOutputChecker(IPDoctestOutputChecker):
# Based on doctest_nose_plugin.py from the nltk project
# (https://github.com/nltk/nltk) and on the "numtest" doctest extension
# by Sebastien Boisgerault (https://github.com/boisgera/numtest).
_unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
_number_re = re.compile(
r"""
(?P<number>
(?P<mantissa>
(?P<integer1> [+-]?\d*)\.(?P<fraction>\d+)
|
(?P<integer2> [+-]?\d+)\.
)
(?:
[Ee]
(?P<exponent1> [+-]?\d+)
)?
|
(?P<integer3> [+-]?\d+)
(?:
[Ee]
(?P<exponent2> [+-]?\d+)
)
)
""",
re.VERBOSE,
)
def check_output(self, want: str, got: str, optionflags: int) -> bool:
if super().check_output(want, got, optionflags):
return True
allow_unicode = optionflags & _get_allow_unicode_flag()
allow_bytes = optionflags & _get_allow_bytes_flag()
allow_number = optionflags & _get_number_flag()
if not allow_unicode and not allow_bytes and not allow_number:
return False
def remove_prefixes(regex: Pattern[str], txt: str) -> str:
return re.sub(regex, r"\1\2", txt)
if allow_unicode:
want = remove_prefixes(self._unicode_literal_re, want)
got = remove_prefixes(self._unicode_literal_re, got)
if allow_bytes:
want = remove_prefixes(self._bytes_literal_re, want)
got = remove_prefixes(self._bytes_literal_re, got)
if allow_number:
got = self._remove_unwanted_precision(want, got)
return super().check_output(want, got, optionflags)
def _remove_unwanted_precision(self, want: str, got: str) -> str:
wants = list(self._number_re.finditer(want))
gots = list(self._number_re.finditer(got))
if len(wants) != len(gots):
return got
offset = 0
for w, g in zip(wants, gots):
fraction: Optional[str] = w.group("fraction")
exponent: Optional[str] = w.group("exponent1")
if exponent is None:
exponent = w.group("exponent2")
precision = 0 if fraction is None else len(fraction)
if exponent is not None:
precision -= int(exponent)
if float(w.group()) == approx(float(g.group()), abs=10**-precision):
# They're close enough. Replace the text we actually
# got with the text we want, so that it will match when we
# check the string literally.
got = (
got[: g.start() + offset] + w.group() + got[g.end() + offset :]
)
offset += w.end() - w.start() - (g.end() - g.start())
return got
return LiteralsOutputChecker
def _get_checker() -> "IPDoctestOutputChecker":
"""Return a IPDoctestOutputChecker subclass that supports some
additional options:
* ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b''
prefixes (respectively) in string literals. Useful when the same
ipdoctest should run in Python 2 and Python 3.
* NUMBER to ignore floating-point differences smaller than the
precision of the literal number in the ipdoctest.
An inner class is used to avoid importing "ipdoctest" at the module
level.
"""
global CHECKER_CLASS
if CHECKER_CLASS is None:
CHECKER_CLASS = _init_checker_class()
return CHECKER_CLASS()
def _get_allow_unicode_flag() -> int:
"""Register and return the ALLOW_UNICODE flag."""
import doctest
return doctest.register_optionflag("ALLOW_UNICODE")
def _get_allow_bytes_flag() -> int:
"""Register and return the ALLOW_BYTES flag."""
import doctest
return doctest.register_optionflag("ALLOW_BYTES")
def _get_number_flag() -> int:
"""Register and return the NUMBER flag."""
import doctest
return doctest.register_optionflag("NUMBER")
def _get_report_choice(key: str) -> int:
"""Return the actual `ipdoctest` module flag value.
We want to do it as late as possible to avoid importing `ipdoctest` and all
its dependencies when parsing options, as it adds overhead and breaks tests.
"""
import doctest
return {
DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
DOCTEST_REPORT_CHOICE_NONE: 0,
}[key]
@pytest.fixture(scope="session")
def ipdoctest_namespace() -> Dict[str, Any]:
"""Fixture that returns a :py:class:`dict` that will be injected into the
namespace of ipdoctests."""
return dict()
| IPDoctestModule |
python | realpython__materials | django-diary/source_code_step_6/entries/views.py | {
"start": 918,
"end": 1230
} | class ____(DeleteView):
model = Entry
success_url = reverse_lazy("entry-list")
success_message = "Your entry was deleted!"
def delete(self, request, *args, **kwargs):
messages.success(self.request, self.success_message)
return super().delete(request, *args, **kwargs)
| EntryDeleteView |
python | PyCQA__pylint | tests/functional/n/names_in__all__.py | {
"start": 692,
"end": 846
} | class ____:
"""A class defined in this module."""
pass
DUMMY = Dummy()
def function():
"""Function docstring
"""
pass
function()
| Dummy |
python | paramiko__paramiko | tests/test_config.py | {
"start": 36074,
"end": 36596
} | class ____(object):
def test_finally(self):
result = load_config("match-final").lookup("finally")
assert result["proxyjump"] == "jump"
assert result["port"] == "1001"
def test_default_port(self):
result = load_config("match-final").lookup("default-port")
assert result["proxyjump"] == "jump"
assert result["port"] == "1002"
def test_negated(self):
result = load_config("match-final").lookup("jump")
assert result["port"] == "1003"
| TestFinalMatching |
python | gevent__gevent | src/greentest/3.14/test_urllib.py | {
"start": 41696,
"end": 51282
} | class ____(unittest.TestCase):
"""Tests for unquote() and unquote_plus()
See the doc string for quoting_Tests for details on quoting and such.
"""
def test_unquoting(self):
# Make sure unquoting of all ASCII values works
escape_list = []
for num in range(128):
given = hexescape(chr(num))
expect = chr(num)
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
result = urllib.parse.unquote_plus(given)
self.assertEqual(expect, result,
"using unquote_plus(): %r != %r" %
(expect, result))
escape_list.append(given)
escape_string = ''.join(escape_list)
del escape_list
result = urllib.parse.unquote(escape_string)
self.assertEqual(result.count('%'), 1,
"using unquote(): not all characters escaped: "
"%s" % result)
def test_unquote_rejects_none_and_tuple(self):
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None)
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ())
def test_unquoting_badpercent(self):
# Test unquoting on bad percent-escapes
given = '%xab'
expect = given
result = urllib.parse.unquote(given)
self.assertEqual(expect, result, "using unquote(): %r != %r"
% (expect, result))
given = '%x'
expect = given
result = urllib.parse.unquote(given)
self.assertEqual(expect, result, "using unquote(): %r != %r"
% (expect, result))
given = '%'
expect = given
result = urllib.parse.unquote(given)
self.assertEqual(expect, result, "using unquote(): %r != %r"
% (expect, result))
# unquote_to_bytes
given = '%xab'
expect = bytes(given, 'ascii')
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
% (expect, result))
given = '%x'
expect = bytes(given, 'ascii')
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
% (expect, result))
given = '%'
expect = bytes(given, 'ascii')
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
% (expect, result))
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, None)
self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, ())
def test_unquoting_mixed_case(self):
# Test unquoting on mixed-case hex digits in the percent-escapes
given = '%Ab%eA'
expect = b'\xab\xea'
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
def test_unquoting_parts(self):
# Make sure unquoting works when have non-quoted characters
# interspersed
given = 'ab%sd' % hexescape('c')
expect = "abcd"
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using quote(): %r != %r" % (expect, result))
result = urllib.parse.unquote_plus(given)
self.assertEqual(expect, result,
"using unquote_plus(): %r != %r" % (expect, result))
def test_unquoting_plus(self):
# Test difference between unquote() and unquote_plus()
given = "are+there+spaces..."
expect = given
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
expect = given.replace('+', ' ')
result = urllib.parse.unquote_plus(given)
self.assertEqual(expect, result,
"using unquote_plus(): %r != %r" % (expect, result))
def test_unquote_to_bytes(self):
given = 'br%C3%BCckner_sapporo_20050930.doc'
expect = b'br\xc3\xbcckner_sapporo_20050930.doc'
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
# Test on a string with unescaped non-ASCII characters
# (Technically an invalid URI; expect those characters to be UTF-8
# encoded).
result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC")
expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc"
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
# Test with a bytes as input
given = b'%A2%D8ab%FF'
expect = b'\xa2\xd8ab\xff'
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
# Test with a bytes as input, with unescaped non-ASCII bytes
# (Technically an invalid URI; expect those bytes to be preserved)
given = b'%A2\xd8ab%FF'
expect = b'\xa2\xd8ab\xff'
result = urllib.parse.unquote_to_bytes(given)
self.assertEqual(expect, result,
"using unquote_to_bytes(): %r != %r"
% (expect, result))
def test_unquote_with_unicode(self):
# Characters in the Latin-1 range, encoded with UTF-8
given = 'br%C3%BCckner_sapporo_20050930.doc'
expect = 'br\u00fcckner_sapporo_20050930.doc'
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Characters in the Latin-1 range, encoded with None (default)
result = urllib.parse.unquote(given, encoding=None, errors=None)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Characters in the Latin-1 range, encoded with Latin-1
result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc',
encoding="latin-1")
expect = 'br\u00fcckner_sapporo_20050930.doc'
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Characters in BMP, encoded with UTF-8
given = "%E6%BC%A2%E5%AD%97"
expect = "\u6f22\u5b57" # "Kanji"
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Decode with UTF-8, invalid sequence
given = "%F3%B1"
expect = "\ufffd" # Replacement character
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Decode with UTF-8, invalid sequence, replace errors
result = urllib.parse.unquote(given, errors="replace")
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# Decode with UTF-8, invalid sequence, ignoring errors
given = "%F3%B1"
expect = ""
result = urllib.parse.unquote(given, errors="ignore")
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# A mix of non-ASCII and percent-encoded characters, UTF-8
result = urllib.parse.unquote("\u6f22%C3%BC")
expect = '\u6f22\u00fc'
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# A mix of non-ASCII and percent-encoded characters, Latin-1
# (Note, the string contains non-Latin-1-representable characters)
result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1")
expect = '\u6f22\u00fc'
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
def test_unquoting_with_bytes_input(self):
# ASCII characters decoded to a string
given = b'blueberryjam'
expect = 'blueberryjam'
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# A mix of non-ASCII hex-encoded characters and ASCII characters
given = b'bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'
expect = 'bl\u00e5b\u00e6rsyltet\u00f8y'
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
# A mix of non-ASCII percent-encoded characters and ASCII characters
given = b'bl%c3%a5b%c3%a6rsyltet%c3%b8j'
expect = 'bl\u00e5b\u00e6rsyltet\u00f8j'
result = urllib.parse.unquote(given)
self.assertEqual(expect, result,
"using unquote(): %r != %r" % (expect, result))
| UnquotingTests |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 16699,
"end": 17013
} | class ____(TypedDict):
ids: List[ID]
embeddings: Optional[
Union[Embeddings, PyEmbeddings, NDArray[Union[np.int32, np.float32]]]
]
documents: Optional[List[Document]]
uris: Optional[URIs]
data: Optional[Loadable]
metadatas: Optional[List[Metadata]]
included: Include
| GetResult |
python | falconry__falcon | examples/things_advanced_asgi.py | {
"start": 356,
"end": 560
} | class ____(Exception):
@staticmethod
async def handle(req, resp, ex, params):
# TODO: Log the error, clean up, etc. before raising
raise falcon.HTTPInternalServerError()
| StorageError |
python | kamyu104__LeetCode-Solutions | Python/xor-operation-in-an-array.py | {
"start": 609,
"end": 840
} | class ____(object):
def xorOperation(self, n, start):
"""
:type n: int
:type start: int
:rtype: int
"""
return reduce(operator.xor, (i for i in xrange(start, start+2*n, 2)))
| Solution2 |
python | huggingface__transformers | tests/models/moshi/test_modeling_moshi.py | {
"start": 22824,
"end": 37201
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (MoshiForConditionalGeneration,) if is_torch_available() else ()
# training is not supported yet for Moshi
test_resize_embeddings = False
def setUp(self):
self.model_tester = MoshiTester(self)
# special case for labels
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
if return_labels:
inputs_dict["text_labels"] = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length),
dtype=torch.long,
device=torch_device,
)
return inputs_dict
def _get_input_ids_and_config(self, batch_size=2):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common(batch_size)
input_ids = inputs_dict.pop("input_ids").to(torch_device)
attention_mask = inputs_dict.pop("attention_mask").to(torch_device)
# Make sure we only return `input_ids`.
# Note that audio_codes will still be generated internally, so the ability to test audio codes is still there.
# There are further tests to test that audio waveforms and codes are well generated.
inputs_dict["return_audio_waveforms"] = False
inputs_dict["return_audio_codes"] = False
inputs_dict["concat_unconditional_inputs"] = False
return config, input_ids, attention_mask, inputs_dict
def prepare_config_and_inputs_for_generate(self, batch_size=2):
config, filtered_inputs_dict = super().prepare_config_and_inputs_for_generate(batch_size=batch_size)
# Make sure we only return `input_ids`.
# Note that audio_codes will still be generated internally, so the ability to test audio codes is still there.
# There are further tests to test that audio waveforms and codes are well generated.
filtered_inputs_dict["return_audio_waveforms"] = False
filtered_inputs_dict["return_audio_codes"] = False
filtered_inputs_dict["concat_unconditional_inputs"] = False
return config, filtered_inputs_dict
def _check_generate_outputs(self, output, config, use_cache=False, num_return_sequences=1, num_beams=1):
# Overwrite because the generate method actually always uses `inputs_embeds` so `use_cache` is always `True`
super()._check_generate_outputs(
output, config, use_cache=True, num_return_sequences=num_return_sequences, num_beams=num_beams
)
@unittest.skip(reason="Continuing from past key values is not straightforward as we're dealing with 3 inputs")
def test_generate_continue_from_past_key_values(self):
pass
@unittest.skip(
"Moshi either needs default generation config or fix for fullgraph compile because it hardcodes SlidingWindowCache in custom generation loop."
)
def test_greedy_generate_dict_outputs_use_cache(self):
pass
@unittest.skip(
"Moshi either needs default generation config or fix for fullgraph compile because it hardcodes SlidingWindowCache in custom generation loop."
)
def test_beam_search_generate_dict_outputs_use_cache(self):
pass
@parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION)
@unittest.skip(reason="Unimplemented. Relies on `test_eager_matches_sdpa_generate` to check correctness.")
def test_eager_matches_sdpa_inference(
self, name, dtype, padding_side, use_attention_mask, output_attentions, enable_kernels
):
pass
@unittest.skip(reason="The Moshi model does not have support dynamic compile yet")
@pytest.mark.torch_compile_test
def test_sdpa_can_compile_dynamic(self):
pass
@pytest.mark.generate
def test_left_padding_compatibility(self):
# Overwrite -- Moshi needs to prepare the audio codes, and they must be padded accordingly
config, inputs_dict = self.prepare_config_and_inputs_for_generate()
input_ids = inputs_dict["input_ids"]
moshi_audio_codes = inputs_dict["moshi_audio_codes"]
user_audio_codes = inputs_dict["user_audio_codes"]
pad_size = (input_ids.shape[0], 32)
padding = (
torch.ones((pad_size[0], self.model_tester.num_codebooks, 32), dtype=input_ids.dtype, device=torch_device)
* config.audio_vocab_size
)
padded_moshi_audio_codes = torch.cat((padding, moshi_audio_codes), dim=2)
padded_user_audio_codes = torch.cat((padding, user_audio_codes), dim=2)
# the audio codes are randomly generated in `prepare_config_and_inputs_for_generate`, and they must match
# their padded version for the test to be valid -- we need to pass both
unpadded_custom_inputs = {"moshi_audio_codes": moshi_audio_codes, "user_audio_codes": user_audio_codes}
padded_custom_inputs = {
"moshi_audio_codes": padded_moshi_audio_codes,
"user_audio_codes": padded_user_audio_codes,
}
super().test_left_padding_compatibility(
unpadded_custom_inputs=unpadded_custom_inputs, padded_custom_inputs=padded_custom_inputs
)
@slow
@is_flaky(max_attempts=5, description="flaky on some models.")
def test_eager_matches_sdpa_generate(self):
"""Overwritten -- mochi has custom inputs and custom output checks"""
max_new_tokens = 5
for model_class in self.all_generative_model_classes:
if not model_class._supports_sdpa:
self.skipTest(f"{model_class.__name__} does not support SDPA")
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
dummy_input = inputs_dict[model_class.main_input_name]
if dummy_input.dtype in [torch.float32, torch.bfloat16]:
dummy_input = dummy_input.to(torch.float16)
inputs_dict[model_class.main_input_name] = dummy_input
# make sure that all models have enough positions for generation
if hasattr(config, "max_position_embeddings"):
config.max_position_embeddings = max_new_tokens + dummy_input.shape[1] + 1
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model_sdpa = model_class.from_pretrained(
tmpdirname,
dtype=torch.float16,
).to(torch_device)
self.assertTrue(model_sdpa.config._attn_implementation == "sdpa")
model_eager = model_class.from_pretrained(
tmpdirname,
dtype=torch.float16,
attn_implementation="eager",
).to(torch_device)
self.assertTrue(model_eager.config._attn_implementation == "eager")
for name, submodule in model_eager.named_modules():
class_name = submodule.__class__.__name__
if "SdpaAttention" in class_name or "SdpaSelfAttention" in class_name:
raise ValueError("The eager model should not have SDPA attention layers")
has_sdpa = False
for name, submodule in model_sdpa.named_modules():
class_name = submodule.__class__.__name__
if "SdpaAttention" in class_name or "SdpaSelfAttention" in class_name:
has_sdpa = True
break
if not has_sdpa:
raise ValueError("The SDPA model should have SDPA attention layers")
# Just test that a large cache works as expected
res_eager = model_eager.generate(
**inputs_dict,
max_new_tokens=max_new_tokens,
do_sample=False,
depth_decoder_do_sample=False,
)
res_sdpa = model_sdpa.generate(
**inputs_dict,
max_new_tokens=max_new_tokens,
do_sample=False,
depth_decoder_do_sample=False,
)
torch.testing.assert_close(res_eager.sequences, res_sdpa.sequences)
torch.testing.assert_close(res_eager.audio_sequences, res_sdpa.audio_sequences)
@pytest.mark.generate
def test_generate_without_input_ids(self):
config, _, _, _ = self._get_input_ids_and_config()
for model_class in self.all_generative_model_classes:
model = model_class(config).to(torch_device)
model.eval()
output_ids_generate = model.generate(
do_sample=False, max_new_tokens=self.max_new_tokens, remove_invalid_values=True
)
print(output_ids_generate)
self.assertIsNotNone(output_ids_generate)
@unittest.skip(reason="The audio encoder has no gradients.")
def test_training_gradient_checkpointing(self):
pass
@unittest.skip(reason="The audio encoder has no gradients.")
def test_training_gradient_checkpointing_use_reentrant(self):
pass
@unittest.skip(reason="The audio encoder has no gradients.")
def test_training_gradient_checkpointing_use_reentrant_false(self):
pass
def test_generate_from_input_values(self):
for model_class in self.all_generative_model_classes:
config, input_ids, _, _ = self._get_input_ids_and_config()
model = model_class(config).to(torch_device).eval()
input_values_length = int(
self.model_tester.seq_length * config.sampling_rate / config.audio_encoder_config.frame_rate
)
user_input_values = floats_tensor((input_ids.shape[0], 1, input_values_length))
moshi_input_values = floats_tensor((input_ids.shape[0], 1, input_values_length))
user_audio_codes = model.audio_encoder.encode(user_input_values, num_quantizers=model.num_codebooks)[0]
moshi_audio_codes = model.audio_encoder.encode(moshi_input_values, num_quantizers=model.num_codebooks)[0]
outputs_from_audio_codes = model.generate(
input_ids, max_new_tokens=5, user_audio_codes=user_audio_codes, moshi_audio_codes=moshi_audio_codes
)
outputs_from_audio_values = model.generate(
input_ids, max_new_tokens=5, user_input_values=user_input_values, moshi_input_values=moshi_input_values
)
self.assertTrue((outputs_from_audio_values.sequences == outputs_from_audio_codes.sequences).all())
self.assertTrue(
torch.allclose(outputs_from_audio_codes.audio_sequences, outputs_from_audio_values.audio_sequences)
)
def test_generate_depth_decoder_kwargs(self):
# test sampling and beam search
for model_class in self.all_generative_model_classes:
config, input_ids, _, input_dict = self._get_input_ids_and_config()
model = model_class(config).to(torch_device).eval()
model.generate(input_ids, max_new_tokens=5, **input_dict, depth_decoder_do_sample=True)
model.generate(
input_ids, max_new_tokens=5, **input_dict, depth_decoder_do_sample=True, depth_decoder_num_beams=5
)
def test_generate_from_unconditional(self):
# test sampling and beam search
for model_class in self.all_generative_model_classes:
config, input_ids, _, input_dict = self._get_input_ids_and_config()
model = model_class(config).to(torch_device).eval()
# check bs>1
model.generate(
**model.get_unconditional_inputs(num_samples=4), max_new_tokens=5, concat_unconditional_inputs=False
)
# check same results from unconditional or no inputs
outputs_from_unconditional = model.generate(
**model.get_unconditional_inputs(num_samples=1), max_new_tokens=5, concat_unconditional_inputs=False
)
outputs_from_none = model.generate(max_new_tokens=5)
self.assertTrue((outputs_from_unconditional.sequences == outputs_from_none.sequences).all())
self.assertTrue(
torch.allclose(outputs_from_unconditional.audio_sequences, outputs_from_none.audio_sequences)
)
@unittest.skip(reason="Compile not yet supported because in Moshi models")
def test_sdpa_can_dispatch_on_flash(self):
pass
@unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
def test_cpu_offload(self):
pass
@unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
def test_disk_offload_bin(self):
pass
@unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
def test_disk_offload_safetensors(self):
pass
@unittest.skip(reason="Test becomes too complex with Moshi requiring multiple modalities")
def test_generate_continue_from_inputs_embeds(self):
pass
@is_flaky(max_attempts=5, description="flaky on some models.")
def test_save_load(self):
super().test_save_load()
@pytest.mark.generate
@unittest.skip(reason="Moshi requires setting `model.generated_audio_codes` in generate() before preparing inputs")
def test_prepare_inputs_for_generation_kwargs_forwards(self):
# If in the future `model.generated_audio_codes` is not required, this test can be re-enabled
super().test_prepare_inputs_for_generation_kwargs_forwards(
last_hidden_state=torch.randn(2, 3, 32), kwargs_depth_decoder={}
)
@unittest.skip(reason="Moshi has no separate base model without a head.")
def test_model_base_model_prefix(self):
pass
def place_dict_on_device(dict_to_place, device):
for key in dict_to_place:
if dict_to_place[key] is not None and isinstance(dict_to_place[key], torch.Tensor):
dict_to_place[key] = dict_to_place[key].to(device)
return dict_to_place
@require_torch
| MoshiTest |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 4732,
"end": 4863
} | class ____(DataContextError):
def __init__(self) -> None:
super().__init__("Missing DataContext")
| MissingDataContextError |
python | django__django | tests/utils_tests/test_lazyobject.py | {
"start": 13283,
"end": 13655
} | class ____(Baz):
"""
A class that acts as a proxy for Baz. It does some scary mucking about with
dicts, which simulates some crazy things that people might do with
e.g. proxy models.
"""
def __init__(self, baz):
self.__dict__ = baz.__dict__
self._baz = baz
# Grandparent super
super(BaseBaz, self).__init__()
| BazProxy |
python | bokeh__bokeh | src/bokeh/models/widgets/inputs.py | {
"start": 11965,
"end": 12477
} | class ____(TextLikeInput):
''' Multi-line input widget.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
cols = Int(default=20, help="""
Specifies the width of the text area (in average character width). Default: 20
""")
rows = Int(default=2, help="""
Specifies the height of the text area (in lines). Default: 2
""")
max_length = Override(default=500)
| TextAreaInput |
python | facelessuser__soupsieve | soupsieve/css_types.py | {
"start": 8205,
"end": 8818
} | class ____(Immutable):
"""Selector language rules."""
__slots__ = ("languages", "_hash",)
languages: tuple[str, ...]
def __init__(self, languages: Iterable[str]):
"""Initialize."""
super().__init__(languages=tuple(languages))
def __iter__(self) -> Iterator[str]:
"""Iterator."""
return iter(self.languages)
def __len__(self) -> int: # pragma: no cover
"""Length."""
return len(self.languages)
def __getitem__(self, index: int) -> str: # pragma: no cover
"""Get item."""
return self.languages[index]
| SelectorLang |
python | facebook__pyre-check | pyre_extensions/tests/safe_json_test.py | {
"start": 583,
"end": 646
} | class ____(Movie):
int_or_str: Union[int, str]
| MovieWithUnion |
python | pytorch__pytorch | torch/distributions/gumbel.py | {
"start": 484,
"end": 3052
} | class ____(TransformedDistribution):
r"""
Samples from a Gumbel Distribution.
Examples::
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> m = Gumbel(torch.tensor([1.0]), torch.tensor([2.0]))
>>> m.sample() # sample from Gumbel distribution with loc=1, scale=2
tensor([ 1.0124])
Args:
loc (float or Tensor): Location parameter of the distribution
scale (float or Tensor): Scale parameter of the distribution
"""
arg_constraints = {"loc": constraints.real, "scale": constraints.positive}
# pyrefly: ignore [bad-override]
support = constraints.real
def __init__(
self,
loc: Union[Tensor, float],
scale: Union[Tensor, float],
validate_args: Optional[bool] = None,
) -> None:
self.loc, self.scale = broadcast_all(loc, scale)
finfo = torch.finfo(self.loc.dtype)
if isinstance(loc, _Number) and isinstance(scale, _Number):
base_dist = Uniform(finfo.tiny, 1 - finfo.eps, validate_args=validate_args)
else:
base_dist = Uniform(
torch.full_like(self.loc, finfo.tiny),
torch.full_like(self.loc, 1 - finfo.eps),
validate_args=validate_args,
)
transforms = [
ExpTransform().inv,
AffineTransform(loc=0, scale=-torch.ones_like(self.scale)),
ExpTransform().inv,
AffineTransform(loc=loc, scale=-self.scale),
]
super().__init__(base_dist, transforms, validate_args=validate_args)
def expand(self, batch_shape, _instance=None):
new = self._get_checked_instance(Gumbel, _instance)
new.loc = self.loc.expand(batch_shape)
new.scale = self.scale.expand(batch_shape)
return super().expand(batch_shape, _instance=new)
# Explicitly defining the log probability function for Gumbel due to precision issues
def log_prob(self, value):
if self._validate_args:
self._validate_sample(value)
y = (self.loc - value) / self.scale
return (y - y.exp()) - self.scale.log()
@property
def mean(self) -> Tensor:
return self.loc + self.scale * euler_constant
@property
def mode(self) -> Tensor:
return self.loc
@property
def stddev(self) -> Tensor:
return (math.pi / math.sqrt(6)) * self.scale
@property
def variance(self) -> Tensor:
return self.stddev.pow(2)
def entropy(self):
return self.scale.log() + (1 + euler_constant)
| Gumbel |
python | tornadoweb__tornado | tornado/test/gen_test.py | {
"start": 18016,
"end": 18407
} | class ____(RequestHandler):
@gen.coroutine
def prepare(self):
self.chunks = [] # type: List[str]
yield gen.moment
self.chunks.append("1")
@gen.coroutine
def get(self):
self.chunks.append("2")
yield gen.moment
self.chunks.append("3")
yield gen.moment
self.write("".join(self.chunks))
| UndecoratedCoroutinesHandler |
python | ray-project__ray | python/ray/train/v2/_internal/exceptions.py | {
"start": 3038,
"end": 3294
} | class ____(RayTrainError):
"""Exception raised when the cluster has insufficient resources.
Example scenario: A worker that requires 1 GPU is scheduled onto a cluster
that only has CPU worker node types.
"""
| InsufficientClusterResourcesError |
python | doocs__leetcode | solution/1700-1799/1759.Count Number of Homogenous Substrings/Solution2.py | {
"start": 0,
"end": 239
} | class ____:
def countHomogenous(self, s: str) -> int:
mod = 10**9 + 7
ans = cnt = 1
for a, b in pairwise(s):
cnt = cnt + 1 if a == b else 1
ans = (ans + cnt) % mod
return ans
| Solution |
python | scrapy__scrapy | scrapy/extensions/postprocessing.py | {
"start": 1944,
"end": 3331
} | class ____:
"""
Compresses received data using `lzma <https://en.wikipedia.org/wiki/Lempel–Ziv–Markov_chain_algorithm>`_.
Accepted ``feed_options`` parameters:
- `lzma_format`
- `lzma_check`
- `lzma_preset`
- `lzma_filters`
.. note::
``lzma_filters`` cannot be used in pypy version 7.3.1 and older.
See :py:class:`lzma.LZMAFile` for more info about parameters.
"""
def __init__(self, file: BinaryIO, feed_options: dict[str, Any]) -> None:
self.file = file
self.feed_options = feed_options
format_ = self.feed_options.get("lzma_format")
check = self.feed_options.get("lzma_check", -1)
preset = self.feed_options.get("lzma_preset")
filters = self.feed_options.get("lzma_filters")
self.lzmafile = LZMAFile(
filename=self.file,
mode="wb",
format=format_,
check=check,
preset=preset,
filters=filters,
)
def write(self, data: bytes) -> int:
return self.lzmafile.write(data)
def close(self) -> None:
self.lzmafile.close()
# io.IOBase is subclassed here, so that exporters can use the PostProcessingManager
# instance as a file like writable object. This could be needed by some exporters
# such as CsvItemExporter which wraps the feed storage with io.TextIOWrapper.
| LZMAPlugin |
python | ray-project__ray | python/ray/tests/test_autoscaling_policy.py | {
"start": 3727,
"end": 15875
} | class ____:
"""This autoscaler simulator consists of a few components.
State is stored in 3 main data structures:
* Resource management state is stored in self.ip_to_nodes
* The scheduler's work queue is stored in self.work_queue
* An event queue which acts as the simulation's "timeline" in
self.event_queue
The logic is organized into 3 functions (and their helpers):
* self.run_autoscaler plays the role of `monitor.py` and translates
resource management state for load_metrics to consume.
* self.schedule is the only consumer of the work queue. It dispatches
work to the appropriate schedulers, which mutate cluster state and
produce events for the event queue.
* self.process_event is the sole consumer of the event queue. It
dispatches work to the appropriate event handlers.
There are 3 main ways of interacting with the simulator:
* simulator.submit: To submit tasks
* simulator.step: To go to the next "event"
* task/actor/placement group start/done callbacks
"""
def __init__(
self,
config_path,
provider,
autoscaler_update_interval_s=AUTOSCALER_UPDATE_INTERVAL_S,
node_startup_delay_s=120,
):
self.config_path = config_path
self.provider = provider
self.autoscaler_update_interval_s = autoscaler_update_interval_s
self.node_startup_delay_s = node_startup_delay_s
self._setup_autoscaler()
self._setup_simulator()
def _setup_autoscaler(self):
self.runner = MockProcessRunner()
self.config = yaml.safe_load(open(self.config_path).read())
self.provider.create_node(
{},
{
TAG_RAY_NODE_KIND: NODE_KIND_HEAD,
TAG_RAY_USER_NODE_TYPE: self.config["head_node_type"],
},
1,
)
self.head_ip = self.provider.non_terminated_node_ips({})[0]
self.load_metrics = LoadMetrics()
self.autoscaler = MockAutoscaler(
self.config_path,
self.load_metrics,
MockGcsClient(),
# Don't let the autoscaler start any node launchers. Instead, we
# will launch nodes ourself after every update call.
max_concurrent_launches=0,
max_failures=0,
process_runner=self.runner,
update_interval_s=0,
)
# Manually create a node launcher. Note that we won't start it as a
# separate thread.
self.node_launcher = NodeLauncher(
provider=self.autoscaler.provider,
pending=self.autoscaler.pending_launches,
event_summarizer=self.autoscaler.event_summarizer,
node_provider_availability_tracker=self.autoscaler.node_provider_availability_tracker, # noqa: E501 Flake and black disagree how to format this.
queue=self.autoscaler.launch_queue,
index=0,
node_types=self.autoscaler.available_node_types,
)
def _setup_simulator(self):
self.virtual_time = 0
self.ip_to_nodes = {}
self._update_cluster_state(join_immediately=True)
self.work_queue = []
self.event_queue = PriorityQueue()
self.event_queue.put(Event(0, SIMULATOR_EVENT_AUTOSCALER_UPDATE))
def _update_cluster_state(self, join_immediately=False):
nodes = self.provider.non_terminated_nodes(tag_filters={})
for node_id in nodes:
ip = self.provider.internal_ip(node_id)
if ip in self.ip_to_nodes:
continue
node_tags = self.provider.node_tags(node_id)
if TAG_RAY_USER_NODE_TYPE in node_tags:
node_type = node_tags[TAG_RAY_USER_NODE_TYPE]
resources = self.config["available_node_types"][node_type].get(
"resources", {}
)
node = Node(resources, join_immediately, node_type, self.virtual_time)
self.ip_to_nodes[ip] = node
if not join_immediately:
join_time = self.virtual_time + self.node_startup_delay_s
self.event_queue.put(
Event(join_time, SIMULATOR_EVENT_NODE_JOINED, node)
)
def submit(self, work):
if isinstance(work, list):
self.work_queue.extend(work)
else:
self.work_queue.append(work)
def _get_node_to_run(self, bundle, nodes):
for ip, node in nodes.items():
if node.bundle_fits(bundle):
return ip, node
return None, None
def _schedule_placement_group(self, pg, nodes):
# This scheduling algorithm is bad, but it is approximately as bad as
# the real placement group scheduler.
to_allocate = []
if (
pg.strategy == PlacementStrategy.STRICT_PACK
or pg.strategy == PlacementStrategy.PACK
):
combined = collections.defaultdict(float)
for bundle in pg.bundles:
for k, v in bundle.items():
combined[k] += v
ip, node_to_run = self._get_node_to_run(combined, nodes)
if node_to_run is None:
return False
to_allocate.append((combined, ip))
elif (
pg.strategy == PlacementStrategy.STRICT_SPREAD
or pg.strategy == PlacementStrategy.SPREAD
):
# TODO (Alex): More accurate handling of non-STRICT_PACK groups.
remaining_nodes = nodes.copy()
for bundle in pg.bundles:
ip, node_to_run = self._get_node_to_run(bundle, remaining_nodes)
if node_to_run is None:
return False
del remaining_nodes[ip]
to_allocate.append((bundle, ip))
for bundle, ip in to_allocate:
node = self.ip_to_nodes[ip]
node.allocate(bundle)
pg.start_time = self.virtual_time
end_time = self.virtual_time + pg.duration
self.event_queue.put(
Event(end_time, SIMULATOR_EVENT_PG_DONE, (pg, to_allocate))
)
if pg.start_callback:
pg.start_callback()
return True
def _schedule_task(self, task, nodes):
ip, node = self._get_node_to_run(task.resources, nodes)
if node is None:
return False
node.allocate(task.resources)
task.node = node
task.start_time = self.virtual_time
end_time = self.virtual_time + task.duration
self.event_queue.put(Event(end_time, SIMULATOR_EVENT_TASK_DONE, task))
if task.start_callback:
task.start_callback()
return True
def schedule(self):
# TODO (Alex): Implement a more realistic scheduling algorithm.
new_work_queue = []
for work in self.work_queue:
if isinstance(work, Task):
scheduled = self._schedule_task(work, self.ip_to_nodes)
elif isinstance(work, PlacementGroup):
scheduled = self._schedule_placement_group(work, self.ip_to_nodes)
else:
assert False, "Unknown work object!"
if scheduled is False:
new_work_queue.append(work)
self.work_queue = new_work_queue
def _launch_nodes(self):
"""Launch all queued nodes. Since this will be run serially after
`autoscaler.update` there are no race conditions in checking if the
queue is empty.
"""
while not self.node_launcher.queue.empty():
config, count, node_type = self.node_launcher.queue.get()
try:
self.node_launcher._launch_node(config, count, node_type)
except Exception:
pass
finally:
self.node_launcher.pending.dec(node_type, count)
def _infeasible(self, bundle):
for node in self.ip_to_nodes.values():
if node.feasible(bundle):
return False
return True
def run_autoscaler(self):
waiting_bundles = []
infeasible_bundles = []
placement_groups = []
for work in self.work_queue:
if isinstance(work, Task):
shape = work.resources
if self._infeasible(shape):
infeasible_bundles.append(shape)
else:
waiting_bundles.append(shape)
if isinstance(work, PlacementGroup):
placement_groups.append(
PlacementGroupTableData(
state=PlacementGroupTableData.PENDING,
strategy=work.strategy,
bundles=[
Bundle(unit_resources=bundle) for bundle in work.bundles
],
)
)
for ip, node in self.ip_to_nodes.items():
if not node.in_cluster:
continue
self.load_metrics.update(
ip=ip,
node_id=node.node_id,
static_resources=node.total_resources,
dynamic_resources=node.available_resources,
node_idle_duration_s=0,
waiting_bundles=waiting_bundles,
infeasible_bundles=infeasible_bundles,
pending_placement_groups=placement_groups,
)
self.autoscaler.update()
self._launch_nodes()
self._update_cluster_state()
def process_event(self, event):
if event.event_type == SIMULATOR_EVENT_AUTOSCALER_UPDATE:
self.run_autoscaler()
next_update = self.virtual_time + self.autoscaler_update_interval_s
self.event_queue.put(Event(next_update, SIMULATOR_EVENT_AUTOSCALER_UPDATE))
elif event.event_type == SIMULATOR_EVENT_TASK_DONE:
task = event.data
task.node.free(task.resources)
if task.done_callback:
task.done_callback()
elif event.event_type == SIMULATOR_EVENT_NODE_JOINED:
node = event.data
node.in_cluster = True
elif event.event_type == SIMULATOR_EVENT_PG_DONE:
pg, allocated = event.data
for bundle, ip in allocated:
self.ip_to_nodes[ip].free(bundle)
if pg.done_callback:
pg.done_callback()
else:
assert False, "Unknown event!"
def step(self):
self.virtual_time = self.event_queue.queue[0].time
while self.event_queue.queue[0].time == self.virtual_time:
event = self.event_queue.get()
self.process_event(event)
self.schedule()
print(self.info_string())
return self.virtual_time
def node_costs(self):
"""Returns the cost of nodes. Cost is measured in terms of cumulative hours of
runtime per node type.
"""
costs = collections.defaultdict(float)
for node in self.ip_to_nodes.values():
if not node.in_cluster:
continue
runtime = self.virtual_time - node.start_time
costs[node.node_type] += runtime
return costs
def info_string(self):
num_connected_nodes = len(
[node for node in self.ip_to_nodes.values() if node.in_cluster]
)
num_pending_nodes = len(self.ip_to_nodes) - num_connected_nodes
return (
f"[t={self.virtual_time}] "
f"Connected: {num_connected_nodes}, "
f"Pending: {num_pending_nodes}, "
f"Remaining: {len(self.work_queue)}"
)
SAMPLE_CLUSTER_CONFIG = copy.deepcopy(MULTI_WORKER_CLUSTER)
SAMPLE_CLUSTER_CONFIG["min_workers"] = 0
SAMPLE_CLUSTER_CONFIG["max_workers"] = 9999
SAMPLE_CLUSTER_CONFIG["target_utilization_fraction"] = 0.5
SAMPLE_CLUSTER_CONFIG["available_node_types"]["m4.16xlarge"]["max_workers"] = 100
SAMPLE_CLUSTER_CONFIG["available_node_types"]["m4.4xlarge"]["max_workers"] = 10000
| Simulator |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_ticker.py | {
"start": 22988,
"end": 23339
} | class ____:
def test_set_params(self):
"""
Create fixed locator with 5 nbins, and change it to something else.
See if change was successful.
Should not exception.
"""
fixed = mticker.FixedLocator(range(0, 24), nbins=5)
fixed.set_params(nbins=7)
assert fixed.nbins == 7
| TestFixedLocator |
python | kubernetes-client__python | kubernetes/client/models/v1_volume_attachment.py | {
"start": 383,
"end": 7530
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'spec': 'V1VolumeAttachmentSpec',
'status': 'V1VolumeAttachmentStatus'
}
attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'spec': 'spec',
'status': 'status'
}
def __init__(self, api_version=None, kind=None, metadata=None, spec=None, status=None, local_vars_configuration=None): # noqa: E501
"""V1VolumeAttachment - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._kind = None
self._metadata = None
self._spec = None
self._status = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
self.spec = spec
if status is not None:
self.status = status
@property
def api_version(self):
"""Gets the api_version of this V1VolumeAttachment. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1VolumeAttachment. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1VolumeAttachment.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1VolumeAttachment. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def kind(self):
"""Gets the kind of this V1VolumeAttachment. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1VolumeAttachment. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1VolumeAttachment.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1VolumeAttachment. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1VolumeAttachment. # noqa: E501
:return: The metadata of this V1VolumeAttachment. # noqa: E501
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1VolumeAttachment.
:param metadata: The metadata of this V1VolumeAttachment. # noqa: E501
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def spec(self):
"""Gets the spec of this V1VolumeAttachment. # noqa: E501
:return: The spec of this V1VolumeAttachment. # noqa: E501
:rtype: V1VolumeAttachmentSpec
"""
return self._spec
@spec.setter
def spec(self, spec):
"""Sets the spec of this V1VolumeAttachment.
:param spec: The spec of this V1VolumeAttachment. # noqa: E501
:type: V1VolumeAttachmentSpec
"""
if self.local_vars_configuration.client_side_validation and spec is None: # noqa: E501
raise ValueError("Invalid value for `spec`, must not be `None`") # noqa: E501
self._spec = spec
@property
def status(self):
"""Gets the status of this V1VolumeAttachment. # noqa: E501
:return: The status of this V1VolumeAttachment. # noqa: E501
:rtype: V1VolumeAttachmentStatus
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this V1VolumeAttachment.
:param status: The status of this V1VolumeAttachment. # noqa: E501
:type: V1VolumeAttachmentStatus
"""
self._status = status
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1VolumeAttachment):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1VolumeAttachment):
return True
return self.to_dict() != other.to_dict()
| V1VolumeAttachment |
python | pypa__pip | src/pip/_vendor/rich/layout.py | {
"start": 2420,
"end": 3009
} | class ____(Splitter):
"""Split a layout region in to rows."""
name = "row"
def get_tree_icon(self) -> str:
return "[layout.tree.row]⬌"
def divide(
self, children: Sequence["Layout"], region: Region
) -> Iterable[Tuple["Layout", Region]]:
x, y, width, height = region
render_widths = ratio_resolve(width, children)
offset = 0
_Region = Region
for child, child_width in zip(children, render_widths):
yield child, _Region(x + offset, y, child_width, height)
offset += child_width
| RowSplitter |
python | pennersr__django-allauth | allauth/socialaccount/providers/douban/views.py | {
"start": 275,
"end": 1397
} | class ____(OAuth2Adapter):
provider_id = "douban"
access_token_url = "https://www.douban.com/service/auth2/token" # nosec
authorize_url = "https://www.douban.com/service/auth2/auth"
profile_url = "https://api.douban.com/v2/user/~me"
def complete_login(self, request, app, token, **kwargs):
headers = {"Authorization": "Bearer %s" % token.token}
resp = (
get_adapter().get_requests_session().get(self.profile_url, headers=headers)
)
extra_data = resp.json()
"""
Douban may return data like this:
{
'code': 128,
'request': 'GET /v2/user/~me',
'msg': 'user_is_locked:53358092'
}
"""
if "id" not in extra_data:
msg = extra_data.get("msg", _("Invalid profile data"))
raise ProviderException(msg)
return self.get_provider().sociallogin_from_response(request, extra_data)
oauth2_login = OAuth2LoginView.adapter_view(DoubanOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(DoubanOAuth2Adapter)
| DoubanOAuth2Adapter |
python | tensorflow__tensorflow | tensorflow/python/summary/plugin_asset_test.py | {
"start": 1289,
"end": 1394
} | class ____(_UnnamedPluginAsset):
plugin_name = "_ExamplePluginAsset"
| _ExamplePluginThatWillCauseCollision |
python | pytorch__pytorch | torch/nn/modules/instancenorm.py | {
"start": 13169,
"end": 14965
} | class ____(_LazyNormBase, _InstanceNorm):
r"""A :class:`torch.nn.InstanceNorm2d` module with lazy initialization of the ``num_features`` argument.
The ``num_features`` argument of the :class:`InstanceNorm2d` is inferred from the ``input.size(1)``.
The attributes that will be lazily initialized are `weight`, `bias`,
`running_mean` and `running_var`.
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
on lazy modules and their limitations.
Args:
num_features: :math:`C` from an expected input of size
:math:`(N, C, H, W)` or :math:`(C, H, W)`
eps: a value added to the denominator for numerical stability. Default: 1e-5
momentum: the value used for the running_mean and running_var computation. Default: 0.1
affine: a boolean value that when set to ``True``, this module has
learnable affine parameters, initialized the same way as done for batch normalization.
Default: ``False``.
track_running_stats: a boolean value that when set to ``True``, this
module tracks the running mean and variance, and when set to ``False``,
this module does not track such statistics and always uses batch
statistics in both training and eval modes. Default: ``False``
Shape:
- Input: :math:`(N, C, H, W)` or :math:`(C, H, W)`
- Output: :math:`(N, C, H, W)` or :math:`(C, H, W)` (same shape as input)
"""
cls_to_become = InstanceNorm2d # type: ignore[assignment]
def _get_no_batch_dim(self) -> int:
return 3
def _check_input_dim(self, input) -> None:
if input.dim() not in (3, 4):
raise ValueError(f"expected 3D or 4D input (got {input.dim()}D input)")
| LazyInstanceNorm2d |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 5025,
"end": 5169
} | class ____(SecurityWarning):
"""Warned when certain TLS/SSL configuration is not available on a platform."""
pass
| InsecurePlatformWarning |
python | numpy__numpy | numpy/ma/tests/test_extras.py | {
"start": 72625,
"end": 75260
} | class ____:
def test_stack_1d(self):
a = masked_array([0, 1, 2], mask=[0, 1, 0])
b = masked_array([9, 8, 7], mask=[1, 0, 0])
c = stack([a, b], axis=0)
assert_equal(c.shape, (2, 3))
assert_array_equal(a.mask, c[0].mask)
assert_array_equal(b.mask, c[1].mask)
d = vstack([a, b])
assert_array_equal(c.data, d.data)
assert_array_equal(c.mask, d.mask)
c = stack([a, b], axis=1)
assert_equal(c.shape, (3, 2))
assert_array_equal(a.mask, c[:, 0].mask)
assert_array_equal(b.mask, c[:, 1].mask)
def test_stack_masks(self):
a = masked_array([0, 1, 2], mask=True)
b = masked_array([9, 8, 7], mask=False)
c = stack([a, b], axis=0)
assert_equal(c.shape, (2, 3))
assert_array_equal(a.mask, c[0].mask)
assert_array_equal(b.mask, c[1].mask)
d = vstack([a, b])
assert_array_equal(c.data, d.data)
assert_array_equal(c.mask, d.mask)
c = stack([a, b], axis=1)
assert_equal(c.shape, (3, 2))
assert_array_equal(a.mask, c[:, 0].mask)
assert_array_equal(b.mask, c[:, 1].mask)
def test_stack_nd(self):
# 2D
shp = (3, 2)
d1 = np.random.randint(0, 10, shp)
d2 = np.random.randint(0, 10, shp)
m1 = np.random.randint(0, 2, shp).astype(bool)
m2 = np.random.randint(0, 2, shp).astype(bool)
a1 = masked_array(d1, mask=m1)
a2 = masked_array(d2, mask=m2)
c = stack([a1, a2], axis=0)
c_shp = (2,) + shp
assert_equal(c.shape, c_shp)
assert_array_equal(a1.mask, c[0].mask)
assert_array_equal(a2.mask, c[1].mask)
c = stack([a1, a2], axis=-1)
c_shp = shp + (2,)
assert_equal(c.shape, c_shp)
assert_array_equal(a1.mask, c[..., 0].mask)
assert_array_equal(a2.mask, c[..., 1].mask)
# 4D
shp = (3, 2, 4, 5,)
d1 = np.random.randint(0, 10, shp)
d2 = np.random.randint(0, 10, shp)
m1 = np.random.randint(0, 2, shp).astype(bool)
m2 = np.random.randint(0, 2, shp).astype(bool)
a1 = masked_array(d1, mask=m1)
a2 = masked_array(d2, mask=m2)
c = stack([a1, a2], axis=0)
c_shp = (2,) + shp
assert_equal(c.shape, c_shp)
assert_array_equal(a1.mask, c[0].mask)
assert_array_equal(a2.mask, c[1].mask)
c = stack([a1, a2], axis=-1)
c_shp = shp + (2,)
assert_equal(c.shape, c_shp)
assert_array_equal(a1.mask, c[..., 0].mask)
assert_array_equal(a2.mask, c[..., 1].mask)
| TestStack |
python | getsentry__sentry | src/sentry/models/artifactbundle.py | {
"start": 6114,
"end": 6692
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
organization_id = BoundedBigIntegerField(db_index=True)
debug_id = models.UUIDField()
artifact_bundle = FlexibleForeignKey("sentry.ArtifactBundle")
source_file_type = models.IntegerField(choices=SourceFileType.choices())
date_added = models.DateTimeField(default=timezone.now)
class Meta:
app_label = "sentry"
db_table = "sentry_debugidartifactbundle"
indexes = (models.Index(fields=("debug_id", "artifact_bundle")),)
@region_silo_model
| DebugIdArtifactBundle |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_theme_color04.py | {
"start": 350,
"end": 1193
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("theme_color04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with a theme color."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
# Add theme colors to the worksheet.
for row in range(6):
col = 0
color = col + 3 # Theme color index.
shade = row + 0 # Theme shade index.
theme_color = Color((color, shade))
color_format = workbook.add_format({"bg_color": theme_color})
worksheet.write(row, col, "", color_format)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/1712. Ways to Split Array Into Three Subarrays/1712-2.py | {
"start": 0,
"end": 672
} | class ____:
def waysToSplit(self, nums: list[int]) -> int:
MOD = 1_000_000_007
n = len(nums)
ans = 0
prefix = list(itertools.accumulate(nums))
j = 0
k = 0
for i in range(n - 2):
# Find the first index j s.t.
# left = prefix[i] <= mid = prefix[j] - prefix[i]
j = max(j, i + 1)
while j < n - 1 and prefix[i] > prefix[j] - prefix[i]:
j += 1
# Find the first index k s.t.
# mid = prefix[k] - prefix[i] > right = prefix[-1] - prefix[k]
k = max(k, j)
while k < n - 1 and prefix[k] - prefix[i] <= prefix[-1] - prefix[k]:
k += 1
ans += k - j
ans %= MOD
return ans
| Solution |
python | pytorch__pytorch | test/nn/attention/test_open_registry.py | {
"start": 181,
"end": 1507
} | class ____(TestCase):
def setUp(self):
super().setUp()
self._saved_impls = dict(_registry._FLASH_ATTENTION_IMPLS)
self._saved_active = attention.current_flash_attention_impl()
_registry._FLASH_ATTENTION_IMPLS.clear()
_registry._FLASH_ATTENTION_ACTIVE = None
def tearDown(self):
_registry._FLASH_ATTENTION_IMPLS.clear()
_registry._FLASH_ATTENTION_IMPLS.update(self._saved_impls)
_registry._FLASH_ATTENTION_ACTIVE = self._saved_active
super().tearDown()
def test_register_and_activate_impl(self):
calls: dict[str, bool] = {}
def fake_register():
calls["called"] = True
attention.register_flash_attention_impl("TEST_FA", register_fn=fake_register)
self.assertIn("TEST_FA", attention.list_flash_attention_impls())
attention.activate_flash_attention_impl("TEST_FA")
self.assertTrue(calls.get("called", False))
self.assertEqual("TEST_FA", attention.current_flash_attention_impl())
def test_activate_unknown_impl_errors(self):
with self.assertRaisesRegex(
ValueError, "Unknown flash attention impl 'missing'"
):
attention.activate_flash_attention_impl("missing")
if __name__ == "__main__":
run_tests()
| TestFlashAttentionRegistry |
python | sphinx-doc__sphinx | sphinx/writers/latex.py | {
"start": 2703,
"end": 8504
} | class ____:
"""A table data"""
def __init__(self, node: Element) -> None:
self.header: list[str] = []
self.body: list[str] = []
self.align = node.get('align', 'default')
self.classes: list[str] = node.get('classes', [])
self.styles: list[str] = []
if 'standard' in self.classes:
self.styles.append('standard')
elif 'borderless' in self.classes:
self.styles.append('borderless')
elif 'booktabs' in self.classes:
self.styles.append('booktabs')
if 'nocolorrows' in self.classes:
self.styles.append('nocolorrows')
elif 'colorrows' in self.classes:
self.styles.append('colorrows')
self.colcount = 0
self.colspec: str = ''
if 'booktabs' in self.styles or 'borderless' in self.styles:
self.colsep: str | None = ''
elif 'standard' in self.styles:
self.colsep = '|'
else:
self.colsep = None
self.colwidths: list[int] = []
self.has_problematic = False
self.has_verbatim = False
# cf https://github.com/sphinx-doc/sphinx/issues/13646#issuecomment-2958309632
self.is_nested = False
self.caption: list[str] = []
self.stubs: list[int] = []
# current position
self.col = 0
self.row = 0
# A dict mapping a table location to a cell_id (cell = rectangular area)
self.cells: dict[tuple[int, int], int] = defaultdict(int)
self.cell_id = 0 # last assigned cell_id
def is_longtable(self) -> bool:
"""True if and only if table uses longtable environment.
In absence of longtable class can only be used trustfully on departing
the table, as the number of rows is not known until then.
"""
return self.row > 30 or 'longtable' in self.classes
def get_table_type(self) -> str:
"""Returns the LaTeX environment name for the table.
It is used at time of ``depart_table()`` and again via ``get_colspec()``.
The class currently supports:
* longtable
* tabular
* tabulary
"""
if self.is_longtable() and not self.is_nested:
return 'longtable'
elif self.has_verbatim:
return 'tabular'
elif self.colspec:
# tabulary complains (only a LaTeX warning) if none of its column
# types is used. The next test will have false positive from
# syntax such as >{\RaggedRight} but it will catch *{3}{J} which
# does require tabulary and would crash tabular
# It is user responsibility not to use a tabulary column type for
# a column having a problematic cell.
if any(c in 'LRCJT' for c in self.colspec):
return 'tabulary'
else:
return 'tabular'
elif self.has_problematic or (
self.colwidths and 'colwidths-given' in self.classes
):
return 'tabular'
else:
# A nested tabulary in a longtable can not use any \hline's,
# i.e. it can not use "booktabs" or "standard" styles (due to a
# LaTeX upstream bug we do not try to solve). But we can't know
# here if it ends up in a tabular or longtable. So it is via
# LaTeX macros inserted by the tabulary template that the problem
# will be solved.
return 'tabulary'
def get_colspec(self) -> str:
r"""Returns a column spec of table.
This is what LaTeX calls the 'preamble argument' of the used table environment.
.. note::
This is used by the template renderer at time of depart_table().
The ``\\X`` and ``T`` column type specifiers are defined in
``sphinxlatextables.sty``.
"""
if self.colspec:
return self.colspec
_colsep = self.colsep
assert _colsep is not None
if self.colwidths and 'colwidths-given' in self.classes:
total = sum(self.colwidths)
colspecs = [r'\X{%d}{%d}' % (width, total) for width in self.colwidths]
return f'{{{_colsep}{_colsep.join(colspecs)}{_colsep}}}' + CR
elif self.has_problematic:
return (
r'{%s*{%d}{\X{1}{%d}%s}}'
% (_colsep, self.colcount, self.colcount, _colsep)
+ CR
)
elif self.get_table_type() == 'tabulary':
# sphinx.sty sets T to be J by default.
return '{' + _colsep + (('T' + _colsep) * self.colcount) + '}' + CR
else:
return '{' + _colsep + (('l' + _colsep) * self.colcount) + '}' + CR
def add_cell(self, height: int, width: int) -> None:
"""Adds a new cell to a table.
It will be located at current position: (``self.row``, ``self.col``).
"""
self.cell_id += 1
for col in range(width):
for row in range(height):
assert self.cells[self.row + row, self.col + col] == 0
self.cells[self.row + row, self.col + col] = self.cell_id
def cell(
self,
row: int | None = None,
col: int | None = None,
) -> TableCell | None:
"""Returns a cell object (i.e. rectangular area) containing given position.
If no option arguments: ``row`` or ``col`` are given, the current position;
``self.row`` and ``self.col`` are used to get a cell object by default.
"""
try:
if row is None:
row = self.row
if col is None:
col = self.col
return TableCell(self, row, col)
except IndexError:
return None
| Table |
python | rapidsai__cudf | python/cudf/cudf/core/index.py | {
"start": 152857,
"end": 162083
} | class ____(Index):
"""
Immutable, ordered and sliceable sequence of timedelta64 data,
represented internally as int64.
Parameters
----------
data : array-like (1-dimensional), optional
Optional datetime-like data to construct index with.
unit : str, optional
This is not yet supported
copy : bool
Make a copy of input.
freq : str, optional
This is not yet supported
closed : str, optional
This is not yet supported
dtype : str or :class:`numpy.dtype`, optional
Data type for the output Index. If not specified, the
default dtype will be ``timedelta64[ns]``.
name : object
Name to be stored in the index.
Attributes
----------
days
seconds
microseconds
nanoseconds
components
inferred_freq
Methods
-------
None
Returns
-------
TimedeltaIndex
Examples
--------
>>> import cudf
>>> cudf.TimedeltaIndex([1132223, 2023232, 342234324, 4234324],
... dtype="timedelta64[ns]")
TimedeltaIndex(['0 days 00:00:00.001132223', '0 days 00:00:00.002023232',
'0 days 00:00:00.342234324', '0 days 00:00:00.004234324'],
dtype='timedelta64[ns]')
>>> cudf.TimedeltaIndex([1, 2, 3, 4], dtype="timedelta64[s]",
... name="delta-index")
TimedeltaIndex(['0 days 00:00:01', '0 days 00:00:02', '0 days 00:00:03',
'0 days 00:00:04'],
dtype='timedelta64[s]', name='delta-index')
"""
@_performance_tracking
def __init__(
self,
data=None,
unit=None,
freq=None,
closed=None,
dtype=None,
copy: bool = False,
name=None,
nan_as_null=no_default,
):
if freq is not None:
raise NotImplementedError("freq is not yet supported")
if closed is not None:
warnings.warn(
"The 'closed' keyword is "
"deprecated and will be removed in a future version. ",
FutureWarning,
)
raise NotImplementedError("closed is not yet supported")
if unit is not None:
warnings.warn(
"The 'unit' keyword is "
"deprecated and will be removed in a future version. ",
FutureWarning,
)
raise NotImplementedError(
"unit is not yet supported, alternatively "
"dtype parameter is supported"
)
name = _getdefault_name(data, name=name)
col = as_column(data)
if col.dtype == CUDF_STRING_DTYPE:
# String -> Timedelta parsing via astype isn't rigorous enough yet
# to cover cudf.pandas test cases, go through pandas instead.
col = as_column(pd.to_timedelta(data))
if dtype is not None:
dtype = cudf.dtype(dtype)
if dtype.kind != "m":
raise TypeError("dtype must be a timedelta type")
col = col.astype(dtype)
elif col.dtype.kind != "m":
# nanosecond default matches pandas
col = col.astype(np.dtype("timedelta64[ns]"))
if copy:
col = col.copy()
SingleColumnFrame.__init__(
self, ColumnAccessor({name: col}, verify=False)
)
@classmethod
@_performance_tracking
def _from_column(
cls, column: ColumnBase, *, name: Hashable = None, freq: Any = None
) -> Self:
if column.dtype.kind != "m":
raise ValueError("column must have a timedelta type.")
return super()._from_column(column, name=name)
def __getitem__(self, index):
value = super().__getitem__(index)
if cudf.get_option("mode.pandas_compatible") and isinstance(
value, np.timedelta64
):
return pd.Timedelta(value)
return value
def as_unit(self, unit: str, round_ok: bool = True) -> Self:
"""
Convert to a dtype with the given unit resolution.
Currently not implemented.
Parameters
----------
unit : {'s', 'ms', 'us', 'ns'}
round_ok : bool, default True
If False and the conversion requires rounding, raise ValueError.
"""
raise NotImplementedError("as_unit is currently not implemented")
@cached_property
def _constructor(self):
return TimedeltaIndex
@cached_property
def inferred_type(self) -> str:
return "timedelta64"
@property
def freq(self) -> DateOffset | None:
raise NotImplementedError("freq is currently not implemented")
@property
def freqstr(self) -> str:
raise NotImplementedError("freqstr is currently not implemented")
@property
def resolution(self) -> str:
"""
Returns day, hour, minute, second, millisecond or microsecond
"""
raise NotImplementedError("resolution is currently not implemented")
@property
def unit(self) -> str:
return self._column.time_unit
def to_pytimedelta(self) -> np.ndarray:
"""
Return an ndarray of ``datetime.timedelta`` objects.
Returns
-------
numpy.ndarray
An ndarray of ``datetime.timedelta`` objects.
"""
return self.to_pandas().to_pytimedelta()
@cached_property
def asi8(self) -> cupy.ndarray:
return self._column.astype(np.dtype(np.int64)).values
def sum(self, *, skipna: bool = True, axis: int | None = 0):
return self._column.sum(skipna=skipna)
def mean(self, *, skipna: bool = True, axis: int | None = 0):
return self._column.mean(skipna=skipna)
def median(self, *, skipna: bool = True, axis: int | None = 0):
return self._column.median(skipna=skipna)
def std(self, *, skipna: bool = True, axis: int | None = 0, ddof: int = 1):
return self._column.std(skipna=skipna, ddof=ddof)
def total_seconds(self) -> Index:
"""
Return total duration of each element expressed in seconds.
This method is currently not implemented.
"""
return Index._from_column(self._column.total_seconds(), name=self.name)
def ceil(self, freq: str) -> Self:
"""
Ceil to the specified resolution.
This method is currently not implemented.
"""
return type(self)._from_column(self._column.ceil(freq), name=self.name)
def floor(self, freq: str) -> Self:
"""
Floor to the specified resolution.
This method is currently not implemented.
"""
return type(self)._from_column(
self._column.floor(freq), name=self.name
)
def round(self, freq: str) -> Self:
"""
Round to the specified resolution.
This method is currently not implemented.
"""
return type(self)._from_column(
self._column.round(freq), name=self.name
)
@property
@_performance_tracking
def days(self) -> Index:
"""
Number of days for each element.
"""
# .days is already a cached_property
# Need to specifically return `int64` to avoid overflow.
return Index._from_column(
self._column.days.astype(np.dtype(np.int64)), name=self.name
)
@property
@_performance_tracking
def seconds(self) -> Index:
"""
Number of seconds (>= 0 and less than 1 day) for each element.
"""
# .seconds is already a cached_property
return Index._from_column(
self._column.seconds.astype(np.dtype(np.int32)), name=self.name
)
@property
@_performance_tracking
def microseconds(self) -> Index:
"""
Number of microseconds (>= 0 and less than 1 second) for each element.
"""
# .microseconds is already a cached_property
return Index._from_column(
self._column.microseconds.astype(np.dtype(np.int32)),
name=self.name,
)
@property
@_performance_tracking
def nanoseconds(self) -> Index:
"""
Number of nanoseconds (>= 0 and less than 1 microsecond) for each
element.
"""
# .nanoseconds is already a cached_property
return Index._from_column(
self._column.nanoseconds.astype(np.dtype(np.int32)), name=self.name
)
@property
@_performance_tracking
def components(self) -> DataFrame:
"""
Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
"""
# .components is already a cached_property
ca = ColumnAccessor(self._column.components, verify=False)
return cudf.DataFrame._from_data(ca)
@property
def inferred_freq(self):
"""
Infers frequency of TimedeltaIndex.
Notes
-----
This property is currently not supported.
"""
raise NotImplementedError("inferred_freq is not yet supported")
def _is_boolean(self) -> bool:
return False
| TimedeltaIndex |
python | mahmoud__boltons | misc/table_html_app.py | {
"start": 2337,
"end": 5605
} | class ____:
_default_mime = 'application/json'
_format_mime_map = {'html': 'text/html',
'json': 'application/json'}
def __init__(self, dev_mode=True, qp_name='format'):
self.qp_name = qp_name
self.json_render = JSONRender(dev_mode=dev_mode)
self.autotable_render = AutoTableRenderer()
def render_response(self, request, context, _route):
from collections.abc import Sized
if isinstance(context, str): # already serialized
if self._guess_json(context):
return Response(context, mimetype="application/json")
elif '<html' in context[:168]:
# based on the longest DOCTYPE I found in a brief search
return Response(context, mimetype="text/html")
else:
return Response(context, mimetype="text/plain")
# not serialized yet, time to guess what the requester wants
if not isinstance(context, Sized):
return Response(str(context), mimetype="text/plain")
return self._serialize_to_resp(context, request, _route)
__call__ = render_response
def _serialize_to_resp(self, context, request, _route):
req_format = request.args.get(self.qp_name) # explicit GET query param
if req_format and req_format not in self._format_mime_map:
# TODO: badrequest
raise ValueError('format expected one of %r, not %r'
% (self.formats, req_format))
resp_mime = self._format_mime_map.get(req_format)
if not resp_mime and request.accept_mimetypes:
resp_mime = request.accept_mimetypes.best_match(self.mimetypes)
if resp_mime not in self._mime_format_map:
resp_mime = self._default_mime
if resp_mime == 'application/json':
return self.json_render(context)
elif resp_mime == 'text/html':
return self.autotable_render(context, _route)
return Response(str(context), mimetype="text/plain")
@property
def _mime_format_map(self):
return {v: k for k, v in self._format_mime_map.items()}
@property
def formats(self):
return self._format_mime_map.keys()
@property
def mimetypes(self):
return self._format_mime_map.values()
@staticmethod
def _guess_json(text):
if not text:
return False
elif text[0] == '{' and text[-1] == '}':
return True
elif text[0] == '[' and text[-1] == ']':
return True
else:
return False
@classmethod
def factory(cls, *a, **kw):
def basic_render_factory(render_arg):
# behavior doesn't change depending on render_arg
return cls(*a, **kw)
return basic_render_factory
def ident_ep(data):
return data
def main():
rsc = {'data': _DATA}
gpm = GetParamMiddleware('url')
atr = AutoTableRenderer(max_depth=5)
render_basic = BasicRender()
app = Application([('/', ident_ep, render_basic),
('/json', ident_ep, render_basic),
('/fetch', fetch_json, render_basic)], rsc, [gpm])
app.serve()
if __name__ == '__main__':
main()
| BasicRender |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.