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 | PyCQA__pylint | pylint/utils/linterstats.py | {
"start": 730,
"end": 905
} | class ____(TypedDict):
"""TypedDict to store counts of lines of code types."""
code: int
comment: int
docstring: int
empty: int
total: int
| CodeTypeCount |
python | nedbat__coveragepy | tests/test_config.py | {
"start": 36466,
"end": 37740
} | class ____(CoverageTest):
"""Tests of serializing the configuration for subprocesses."""
def test_them(self) -> None:
tmpsrc = str(Path(tempfile.gettempdir()) / "more_source")
self.make_file(
".coveragerc",
f"""\
[run]
timid = True
data_file = somewhere/the_data.db
debug_file = somewhere/debug.out
source = my_src, their_src
source_dirs = my_src, their_src, {tmpsrc}
debug = this_thing, that_thing
""",
)
self.make_file("my_src/__init__.py")
self.make_file("that_thing/__init__.py")
cov = coverage.Coverage()
config2 = CoverageConfig.deserialize(cov.config.serialize())
assert config2.timid
assert config2.data_file == os.path.abspath("somewhere/the_data.db")
assert config2.debug_file == os.path.abspath("somewhere/debug.out")
assert config2.source == [
os.path.abspath("my_src"),
"their_src",
]
assert config2.source_dirs == [
os.path.abspath("my_src"),
os.path.abspath("their_src"),
tmpsrc,
]
assert config2.debug == ["this_thing", "that_thing"]
| SerializeConfigTest |
python | celery__celery | t/smoke/tests/quorum_queues/conftest.py | {
"start": 1949,
"end": 3441
} | class ____(SmokeWorkerContainer):
@classmethod
def log_level(cls) -> str:
return "INFO"
@classmethod
def worker_queue(cls) -> str:
return "celery"
@pytest.fixture
def default_worker_container_cls() -> type[SmokeWorkerContainer]:
return QuorumWorkerContainer
@pytest.fixture(scope="session")
def default_worker_container_session_cls() -> type[SmokeWorkerContainer]:
return QuorumWorkerContainer
celery_dev_worker_image = build(
path=".",
dockerfile="t/smoke/workers/docker/dev",
tag="t/smoke/worker:dev",
buildargs=QuorumWorkerContainer.buildargs(),
)
default_worker_container = container(
image="{celery_dev_worker_image.id}",
ports=fxtr("default_worker_ports"),
environment=fxtr("default_worker_env"),
network="{default_pytest_celery_network.name}",
volumes={
# Volume: Worker /app
"{default_worker_volume.name}": defaults.DEFAULT_WORKER_VOLUME,
# Mount: Celery source
os.path.abspath(os.getcwd()): {
"bind": "/celery",
"mode": "rw",
},
},
wrapper_class=QuorumWorkerContainer,
timeout=defaults.DEFAULT_WORKER_CONTAINER_TIMEOUT,
command=fxtr("default_worker_command"),
)
@pytest.fixture
def default_worker_app(default_worker_app: Celery) -> Celery:
app = default_worker_app
app.conf.broker_transport_options = {"confirm_publish": True}
app.conf.task_default_queue_type = "quorum"
return app
| QuorumWorkerContainer |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 361536,
"end": 361803
} | class ____(stats.rv_continuous):
def _pdf(self, x, a, b):
return a + b
def _cdf(self, x, a):
# Different # of shape params from _pdf, to be able to check that
# inspection catches the inconsistency.
return 42 * a + x
| _distr3_gen |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/enums.py | {
"start": 1892,
"end": 2108
} | class ____(ToUpperCase, enum.Enum):
"""this is enum class"""
x = 'x'
def say_hello(self):
"""docstring"""
@classmethod
def say_goodbye(cls):
"""docstring"""
| EnumClassWithMixinType |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 21942,
"end": 22843
} | class ____(TestCase):
def test_basic(self):
it = iter(['item'])
self.assertEqual(mi.one(it), 'item')
def test_too_short_new(self):
it = iter([])
self.assertRaises(ValueError, lambda: mi.one(it))
self.assertRaises(
OverflowError, lambda: mi.one(it, too_short=OverflowError)
)
def test_too_long(self):
it = count()
self.assertRaises(ValueError, lambda: mi.one(it)) # burn 0 and 1
self.assertEqual(next(it), 2)
self.assertRaises(
OverflowError, lambda: mi.one(it, too_long=OverflowError)
)
def test_too_long_default_message(self):
it = count()
self.assertRaisesRegex(
ValueError,
"Expected exactly one item in "
"iterable, but got 0, 1, and "
"perhaps more.",
lambda: mi.one(it),
)
| OneTests |
python | ray-project__ray | rllib/algorithms/dqn/tests/test_dqn.py | {
"start": 142,
"end": 1363
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_dqn_compilation(self):
"""Test whether DQN can be built and trained."""
num_iterations = 2
config = (
dqn.dqn.DQNConfig()
.environment("CartPole-v1")
.env_runners(num_env_runners=2)
.training(num_steps_sampled_before_learning_starts=0)
)
# Double-dueling DQN.
print("Double-dueling")
algo = config.build()
for i in range(num_iterations):
results = algo.train()
check_train_results_new_api_stack(results)
print(results)
algo.stop()
# Rainbow.
print("Rainbow")
config.training(num_atoms=10, double_q=True, dueling=True, n_step=5)
algo = config.build()
for i in range(num_iterations):
results = algo.train()
check_train_results_new_api_stack(results)
print(results)
algo.stop()
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", __file__]))
| TestDQN |
python | gevent__gevent | src/gevent/_greenlet_primitives.py | {
"start": 955,
"end": 1700
} | class ____(greenlet):
def __init__(self, function, parent):
greenlet.__init__(self, function, parent)
# See greenlet.py's Greenlet class. We capture the cheap
# parts to maintain the tree structure, but we do not capture
# the stack because that's too expensive for 'spawn_raw'.
current = getcurrent() # pylint:disable=undefined-variable
self.spawning_greenlet = wref(current)
# See Greenlet for how trees are maintained.
try:
self.spawn_tree_locals = current.spawn_tree_locals
except AttributeError:
self.spawn_tree_locals = {}
if current.parent:
current.spawn_tree_locals = self.spawn_tree_locals
| TrackedRawGreenlet |
python | pytorch__pytorch | torch/_inductor/ops_handler.py | {
"start": 22882,
"end": 25421
} | class ____(OpsHandler[Any]):
def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
"""
Default implementation for all ops. Override in a subclass to
provide generic op behavior.
Args:
name: name of the op, see OpHandler.{name}
args: positional args passed to the op
kwargs: keyword args passed to the op
Returns:
return value of the op
"""
raise NotImplementedError
def __getattr__(self, name: str) -> Any:
def fallback(*args: Any, **kwargs: Any) -> Any:
return self._default(name, args, kwargs)
# would like to remove this function entirely, but it's used in MTIA backend
warnings.warn(f"undefined OpHandler.{name}, please add missing op schema")
return fallback
@staticmethod
def _call_default(target: str):
def call_default(self, *args, **kwargs):
return self._default(target, args, kwargs)
call_default.__name__ = target
return call_default
@classmethod
def _init_cls(cls):
"""
Here we codegen many functions of the form:
def add(self, a, b):
return self._default('add', (a, b), {})
and install them in cls. This is the same as _call_default above,
but is about 1.2x faster since CPython varargs parsing is slow.
"""
code = StringIO()
for target in OP_NAMES:
sig = inspect.signature(getattr(OpsHandler, target))
if all(
p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
and p.default is inspect.Parameter.empty
for p in sig.parameters.values()
):
self_arg, *args = sig.parameters.keys()
assert self_arg == "self"
code.write(
f"""
def {target}(self, {", ".join(args)}):
return self._default({target!r}, ({", ".join(args)}, ), {{}})
""".strip()
)
code.write("\n\n")
else:
# slower fallback for ops with default or variadic arguments
setattr(cls, target, cls._call_default(target))
ctx: dict[str, Any] = {}
exec(code.getvalue(), ctx)
for target, impl in ctx.items():
if target in OP_NAMES:
setattr(cls, target, impl)
DefaultHandler._init_cls()
| DefaultHandler |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_feature_store.py | {
"start": 7105,
"end": 9740
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("feature_store.FeatureStoreHook"))
def test_execute(self, mock_hook_class):
feature_view_conf_params = {
"big_query_source": FeatureView.BigQuerySource(
uri="bq://{BQ_TABLE}",
entity_id_columns=["entity_id"],
),
"sync_config": FeatureView.SyncConfig(cron="TZ=Europe/London 56 * * * *"),
}
FEATURE_VIEW_CONF = FeatureView(**feature_view_conf_params)
sample_result = {
"big_query_source": {"entity_id_columns": ["entity_id"], "uri": "bq://{BQ_TABLE}"},
"etag": "",
"labels": {},
"name": "projects/test-project/locations/us-central1/featureOnlineStores/test-store"
"/featureViews/test-view",
"satisfies_pzi": False,
"satisfies_pzs": False,
"service_account_email": "",
"service_agent_type": 0,
"sync_config": {"cron": "TZ=Europe/London 56 * * * *"},
}
mock_hook = mock.MagicMock()
mock_hook_class.return_value = mock_hook
# Set up the return value for hook method to match the hook implementation
sample_operation = mock.MagicMock()
sample_operation.result.return_value = FeatureView(
{**feature_view_conf_params, **{"name": FEATURE_VIEW_NAME}}
)
mock_hook.create_feature_view.return_value = sample_operation
mock_hook.return_value.wait_for_operation_result.side_effect = lambda operation: operation.result()
common_kwargs = {
"project_id": GCP_PROJECT,
"location": GCP_LOCATION,
"feature_online_store_id": FEATURE_ONLINE_STORE_ID,
"feature_view_id": FEATURE_VIEW_ID,
"feature_view": FEATURE_VIEW_CONF,
"run_sync_immediately": False,
"metadata": (),
"timeout": 100,
"retry": None,
}
op = CreateFeatureViewOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
**common_kwargs,
)
result = op.execute(context={"ti": mock.MagicMock()})
# Verify hook initialization
mock_hook_class.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
# Verify hook method call
mock_hook.create_feature_view.assert_called_once_with(**common_kwargs)
# Verify result matches expected value
assert result == sample_result
| TestCreateFeatureViewOperator |
python | pytest-dev__pytest | src/_pytest/outcomes.py | {
"start": 296,
"end": 1180
} | class ____(BaseException):
"""OutcomeException and its subclass instances indicate and contain info
about test and collection outcomes."""
def __init__(self, msg: str | None = None, pytrace: bool = True) -> None:
if msg is not None and not isinstance(msg, str):
error_msg = ( # type: ignore[unreachable]
"{} expected string as 'msg' parameter, got '{}' instead.\n"
"Perhaps you meant to use a mark?"
)
raise TypeError(error_msg.format(type(self).__name__, type(msg).__name__))
super().__init__(msg)
self.msg = msg
self.pytrace = pytrace
def __repr__(self) -> str:
if self.msg is not None:
return self.msg
return f"<{self.__class__.__name__} instance>"
__str__ = __repr__
TEST_OUTCOME = (OutcomeException, Exception)
| OutcomeException |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py30.py | {
"start": 663,
"end": 1048
} | class ____:
""" Other annotation problems. """
Undef = 42
ABC = 42
class InnerScope:
""" Test inner scope definition. """
def test_undefined(self)->Undef: # [undefined-variable]
""" Looking at a higher scope is impossible. """
def test1(self)->ABC: # [undefined-variable]
""" Triggers undefined-variable. """
| Undefined1 |
python | huggingface__transformers | src/transformers/models/switch_transformers/modeling_switch_transformers.py | {
"start": 2390,
"end": 5657
} | class ____(nn.Module):
"""
Router using tokens choose top-1 experts assignment.
This router uses the same mechanism as in Switch Transformer (https://huggingface.co/papers/2101.03961) and V-MoE
(https://huggingface.co/papers/2106.05974): tokens choose their top experts. Items are sorted by router_probs and then
routed to their choice of expert until the expert's expert_capacity is reached. **There is no guarantee that each
token is processed by an expert**, or that each expert receives at least one token.
"""
def __init__(self, config: SwitchTransformersConfig):
super().__init__()
self.num_experts = config.num_experts
self.expert_capacity = config.expert_capacity
self.classifier = nn.Linear(config.hidden_size, self.num_experts, bias=config.router_bias)
self.jitter_noise = config.router_jitter_noise
self.ignore_padding_tokens = config.router_ignore_padding_tokens
self.dtype = getattr(torch, config.router_dtype)
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""
Computes router probabilities from input hidden states.
Args:
hidden_states (`torch.Tensor`):
(batch_size, sequence_length, hidden_dim) from which router probabilities are computed.
Returns:
router_probabilities (`torch.Tensor`):
Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabilities for each
token and expert. Used for routing tokens to experts.
router_logits (`torch.Tensor`):
Logits tensor of shape (batch_size, sequence_length, num_experts) corresponding to raw router logits.
This is used later for computing router z-loss.
"""
# float32 is used to ensure stability. See the discussion of "selective precision" in
# https://huggingface.co/papers/2101.03961.
# We also store the previous dtype to cast back the output to the previous dtype
self.input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(self.dtype)
if self.training and self.jitter_noise > 0:
# Multiply the token inputs by the uniform distribution - adding some noise
hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.jitter_noise, 1.0 + self.jitter_noise)
router_logits = self.classifier(hidden_states)
# Apply Softmax and cast back to the original `dtype`
router_probs = nn.functional.softmax(router_logits, dim=-1, dtype=self.dtype).to(self.input_dtype)
router_logits, expert_index = torch.max(router_probs, dim=-1, keepdim=True)
expert_index = torch.nn.functional.one_hot(expert_index, num_classes=self.num_experts)
token_priority = torch.cumsum(expert_index, dim=-2)
# mask if the token routed to to the expert will overflow
expert_capacity_mask = token_priority <= self.expert_capacity
expert_index = expert_index * expert_capacity_mask
router_probs = torch.max(router_probs, dim=-1).values.unsqueeze(-1)
return router_probs, expert_index, router_logits
| SwitchTransformersTop1Router |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1574552,
"end": 1577434
} | class ____(sgqlc.types.Type, Node):
"""A domain that can be verified or approved for an organization or
an enterprise.
"""
__schema__ = github_schema
__field_names__ = (
"created_at",
"database_id",
"dns_host_name",
"domain",
"has_found_host_name",
"has_found_verification_token",
"is_approved",
"is_required_for_policy_enforcement",
"is_verified",
"owner",
"punycode_encoded_domain",
"token_expiration_time",
"updated_at",
"verification_token",
)
created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt")
"""Identifies the date and time when the object was created."""
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
"""Identifies the primary key from the database."""
dns_host_name = sgqlc.types.Field(URI, graphql_name="dnsHostName")
"""The DNS host name that should be used for verification."""
domain = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="domain")
"""The unicode encoded domain."""
has_found_host_name = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="hasFoundHostName")
"""Whether a TXT record for verification with the expected host name
was found.
"""
has_found_verification_token = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="hasFoundVerificationToken")
"""Whether a TXT record for verification with the expected
verification token was found.
"""
is_approved = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isApproved")
"""Whether or not the domain is approved."""
is_required_for_policy_enforcement = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isRequiredForPolicyEnforcement")
"""Whether this domain is required to exist for an organization or
enterprise policy to be enforced.
"""
is_verified = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isVerified")
"""Whether or not the domain is verified."""
owner = sgqlc.types.Field(sgqlc.types.non_null("VerifiableDomainOwner"), graphql_name="owner")
"""The owner of the domain."""
punycode_encoded_domain = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="punycodeEncodedDomain")
"""The punycode encoded domain."""
token_expiration_time = sgqlc.types.Field(DateTime, graphql_name="tokenExpirationTime")
"""The time that the current verification token will expire."""
updated_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="updatedAt")
"""Identifies the date and time when the object was last updated."""
verification_token = sgqlc.types.Field(String, graphql_name="verificationToken")
"""The current verification token for the domain."""
| VerifiableDomain |
python | Pylons__pyramid | tests/test_scripts/dummy.py | {
"start": 2234,
"end": 3389
} | class ____:
def __init__(
self,
app=None,
registry=None,
request=None,
root=None,
root_factory=None,
closer=None,
):
self.app = app or DummyApp()
if registry is None:
registry = DummyRegistry()
self.registry = registry
if request is None:
request = DummyRequest({})
self.request = request
if root is None:
root = Dummy()
self.root = root
if root_factory is None:
root_factory = Dummy()
self.root_factory = root_factory
if closer is None:
closer = DummyCloser()
self.closer = closer
def __call__(self, *a, **kw):
self.a = a
self.kw = kw
registry = kw.get('registry', self.registry)
request = kw.get('request', self.request)
request.registry = registry
return {
'app': self.app,
'registry': registry,
'request': request,
'root': self.root,
'root_factory': self.root_factory,
'closer': self.closer,
}
| DummyBootstrap |
python | huggingface__transformers | src/transformers/models/edgetam_video/modular_edgetam_video.py | {
"start": 20827,
"end": 25240
} | class ____(Sam2VideoAttention):
pass
def apply_rotary_pos_emb_2d_self_attn(
q: torch.Tensor,
k: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Apply rotary position embedding to query and key tensors for self-attention.
Args:
q: Query tensor of shape (..., seq_len, head_dim)
k: Key tensor of shape (..., seq_len, head_dim)
cos: Cosine position embedding of shape (seq_len, head_dim)
sin: Sine position embedding of shape (seq_len, head_dim)
Returns:
Rotated (q, k) tensors
"""
# Apply RoPE to queries
q_embed = q.float() # force upscale to float32 as in the original implementation
q_embed = (q_embed * cos) + (rotate_pairwise(q_embed) * sin)
# Apply RoPE to keys (same embeddings as queries for self-attention)
k_embed = k.float() # force upscale to float32 as in the original implementation
k_embed = (k_embed * cos) + (rotate_pairwise(k_embed) * sin)
return q_embed.type_as(q), k_embed.type_as(k)
def apply_rotary_pos_emb_2d_cross_attn(
q: torch.Tensor,
k: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
cos_k: torch.Tensor,
sin_k: torch.Tensor,
num_k_exclude_rope: int = 0,
repeat_freqs_k: int = 1,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Apply rotary position embedding to query and key tensors for cross-attention.
Args:
q: Query tensor of shape (..., seq_len, head_dim)
k: Key tensor of shape (..., seq_len, head_dim)
cos: Cosine position embedding of shape (seq_len, head_dim)
sin: Sine position embedding of shape (seq_len, head_dim)
cos_k: Cosine position embedding for keys of shape (seq_len, head_dim)
sin_k: Sine position embedding for keys of shape (seq_len, head_dim)
num_k_exclude_rope: Number of tokens at end of k to exclude from RoPE (e.g., object pointer tokens)
repeat_freqs_k: Frequency repetition for keys in cross-attention (e.g., for spatial memory tokens)
Returns:
Rotated (q, k) tensors
"""
# Apply RoPE to queries (always straightforward)
q_embed = q.float()
q_embed = (q_embed * cos) + (rotate_pairwise(q_embed) * sin)
# Split keys: RoPE tokens and excluded tokens (e.g., object pointers)
num_total_k_tokens = k.shape[-2]
k_for_rope = k[..., : num_total_k_tokens - num_k_exclude_rope, :]
k_excluded = k[..., num_total_k_tokens - num_k_exclude_rope :, :]
# Early return if no keys need RoPE
if k_for_rope.shape[-2] == 0:
return q_embed.type_as(q), k_excluded
batch_size, num_heads, k_seq_len, channels_per_head = k_for_rope.shape
# Handle temporal/spatial token structure for memory
# Keys have temporal + spatial structure, only spatial tokens get RoPE
tokens_per_group = k_seq_len // repeat_freqs_k
spatial_tokens = cos_k.shape[-2]
temporal_tokens = tokens_per_group - spatial_tokens
# Reshape and separate temporal/spatial tokens
k_grouped = k_for_rope.view(batch_size, num_heads, repeat_freqs_k, tokens_per_group, channels_per_head)
k_temporal = k_grouped[..., :temporal_tokens, :].reshape(batch_size, num_heads, -1, channels_per_head)
k_spatial = k_grouped[..., temporal_tokens:, :].reshape(batch_size, num_heads, -1, channels_per_head)
# Only apply RoPE to spatial tokens
k_rope_input = k_spatial
# Prepare position embeddings for repeated groups
if repeat_freqs_k > 1:
cos_k = cos_k.repeat(1, 1, repeat_freqs_k, 1)
sin_k = sin_k.repeat(1, 1, repeat_freqs_k, 1)
# Apply RoPE to spatial tokens
k_spatial_embed = k_rope_input.float()
k_spatial_embed = (k_spatial_embed * cos_k) + (rotate_pairwise(k_spatial_embed) * sin_k)
# Reconstruct: temporal + spatial tokens back to original structure
k_spatial_reshaped = k_spatial_embed.view(batch_size, num_heads, repeat_freqs_k, -1, channels_per_head)
k_temporal_reshaped = k_temporal.view(batch_size, num_heads, repeat_freqs_k, -1, channels_per_head)
k_final = torch.cat([k_temporal_reshaped, k_spatial_reshaped], dim=3)
k_final = k_final.view(batch_size, num_heads, k_seq_len, channels_per_head)
# Combine RoPE-processed keys with excluded tokens
k_embed = torch.cat([k_final.type_as(k), k_excluded], dim=-2)
return q_embed.type_as(q), k_embed
| EdgeTamVideoAttention |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 10340,
"end": 10519
} | class ____(Where):
"""Less than comparison"""
key: str
value: Any
def to_dict(self) -> Dict[str, Any]:
return {self.key: {"$lt": self.value}}
@dataclass
| Lt |
python | PyCQA__isort | isort/exceptions.py | {
"start": 2869,
"end": 3337
} | class ____(ISortError):
"""Raised when the specified sorting function isn't available"""
def __init__(self, sort_order: str, available_sort_orders: list[str]):
super().__init__(
f"Specified sort_order of {sort_order} does not exist. "
f"Available sort_orders: {','.join(available_sort_orders)}."
)
self.sort_order = sort_order
self.available_sort_orders = available_sort_orders
| SortingFunctionDoesNotExist |
python | joblib__joblib | joblib/pool.py | {
"start": 7673,
"end": 14134
} | class ____(PicklingPool):
"""Process pool that shares large arrays to avoid memory copy.
This drop-in replacement for `multiprocessing.pool.Pool` makes
it possible to work efficiently with shared memory in a numpy
context.
Existing instances of numpy.memmap are preserved: the child
suprocesses will have access to the same shared memory in the
original mode except for the 'w+' mode that is automatically
transformed as 'r+' to avoid zeroing the original data upon
instantiation.
Furthermore large arrays from the parent process are automatically
dumped to a temporary folder on the filesystem such as child
processes to access their content via memmapping (file system
backed shared memory).
Note: it is important to call the terminate method to collect
the temporary folder used by the pool.
Parameters
----------
processes: int, optional
Number of worker processes running concurrently in the pool.
initializer: callable, optional
Callable executed on worker process creation.
initargs: tuple, optional
Arguments passed to the initializer callable.
temp_folder: (str, callable) optional
If str:
Folder to be used by the pool for memmapping large arrays
for sharing memory with worker processes. If None, this will try in
order:
- a folder pointed by the JOBLIB_TEMP_FOLDER environment variable,
- /dev/shm if the folder exists and is writable: this is a RAMdisk
filesystem available by default on modern Linux distributions,
- the default system temporary folder that can be overridden
with TMP, TMPDIR or TEMP environment variables, typically /tmp
under Unix operating systems.
if callable:
An callable in charge of dynamically resolving a temporary folder
for memmapping large arrays.
max_nbytes int or None, optional, 1e6 by default
Threshold on the size of arrays passed to the workers that
triggers automated memory mapping in temp_folder.
Use None to disable memmapping of large arrays.
mmap_mode: {'r+', 'r', 'w+', 'c'}
Memmapping mode for numpy arrays passed to workers.
See 'max_nbytes' parameter documentation for more details.
forward_reducers: dictionary, optional
Reducers used to pickle objects passed from main process to worker
processes: see below.
backward_reducers: dictionary, optional
Reducers used to pickle return values from workers back to the
main process.
verbose: int, optional
Make it possible to monitor how the communication of numpy arrays
with the subprocess is handled (pickling or memmapping)
prewarm: bool or str, optional, "auto" by default.
If True, force a read on newly memmapped array to make sure that OS
pre-cache it in memory. This can be useful to avoid concurrent disk
access when the same data array is passed to different worker
processes. If "auto" (by default), prewarm is set to True, unless the
Linux shared memory partition /dev/shm is available and used as temp
folder.
`forward_reducers` and `backward_reducers` are expected to be
dictionaries with key/values being `(type, callable)` pairs where
`callable` is a function that give an instance of `type` will return
a tuple `(constructor, tuple_of_objects)` to rebuild an instance out
of the pickled `tuple_of_objects` as would return a `__reduce__`
method. See the standard library documentation on pickling for more
details.
"""
def __init__(
self,
processes=None,
temp_folder=None,
max_nbytes=1e6,
mmap_mode="r",
forward_reducers=None,
backward_reducers=None,
verbose=0,
prewarm=False,
**kwargs,
):
manager = TemporaryResourcesManager(temp_folder)
self._temp_folder_manager = manager
# The usage of a temp_folder_resolver over a simple temp_folder is
# superfluous for multiprocessing pools, as they don't get reused, see
# get_memmapping_executor for more details. We still use it for code
# simplicity.
forward_reducers, backward_reducers = get_memmapping_reducers(
temp_folder_resolver=manager.resolve_temp_folder_name,
max_nbytes=max_nbytes,
mmap_mode=mmap_mode,
forward_reducers=forward_reducers,
backward_reducers=backward_reducers,
verbose=verbose,
unlink_on_gc_collect=False,
prewarm=prewarm,
)
poolargs = dict(
processes=processes,
forward_reducers=forward_reducers,
backward_reducers=backward_reducers,
)
poolargs.update(kwargs)
super(MemmappingPool, self).__init__(**poolargs)
def terminate(self):
n_retries = 10
for i in range(n_retries):
try:
super(MemmappingPool, self).terminate()
break
except OSError as e:
if isinstance(e, WindowsError):
# Workaround occasional "[Error 5] Access is denied" issue
# when trying to terminate a process under windows.
sleep(0.1)
if i + 1 == n_retries:
warnings.warn(
"Failed to terminate worker processes in"
" multiprocessing pool: %r" % e
)
# Clean up the temporary resources as the workers should now be off.
self._temp_folder_manager._clean_temporary_resources()
@property
def _temp_folder(self):
# Legacy property in tests. could be removed if we refactored the
# memmapping tests. SHOULD ONLY BE USED IN TESTS!
# We cache this property because it is called late in the tests - at
# this point, all context have been unregistered, and
# resolve_temp_folder_name raises an error.
if getattr(self, "_cached_temp_folder", None) is not None:
return self._cached_temp_folder
else:
self._cached_temp_folder = (
self._temp_folder_manager.resolve_temp_folder_name()
) # noqa
return self._cached_temp_folder
| MemmappingPool |
python | tensorflow__tensorflow | tensorflow/python/ops/resource_variable_ops.py | {
"start": 105925,
"end": 115474
} | class ____(tensor_module.DenseSpec):
"""Describes a tf.Variable.
A `VariableSpec` provides metadata describing the `tf.Variable` objects
accepted or returned by TensorFlow 2.x APIs.
"""
__slots__ = ["trainable", "alias_id"]
value_type = property(lambda self: ResourceVariable)
def __init__(self, shape, dtype=dtypes.float32, trainable=True,
alias_id=None):
super(VariableSpec, self).__init__(shape, dtype=dtype)
self.trainable = trainable
self.alias_id = alias_id
def is_compatible_with(self, spec_or_value):
"""Returns True if `spec_or_value` is compatible with this `VariableSpec`.
`spec_or_value` is considered to be compatible with this `VariableSpec` if
* `spec_or_value` is a `Variable` or `VariableSpec`,
* their shapes are compatible,
* their dtypes are the same,
* they are both trainable or not trainable.
* they share the same alias_id if `spec_or_value` is a `VariableSpec`.
Example:
>>> v = tf.Variable([1., 2., 3.])
>>> spec = VariableSpec([None])
>>> spec.is_compatible_with(v)
True
>>> v = tf.Variable(1)
>>> spec.is_compatible_with(v)
False
Args:
spec_or_value: A VariableSpec or Variable to compare against.
Returns:
True if `spec_or_value` is compatible with this `VariableSpec`.
"""
if not isinstance(spec_or_value, (type(self), self.value_type)):
return False
compatible = (self.shape.is_compatible_with(spec_or_value.shape) and
self.dtype == spec_or_value.dtype and
self.trainable == spec_or_value.trainable)
if isinstance(spec_or_value, type(self)):
# alias_id must be the same to be compatible.
return compatible and self.alias_id == spec_or_value.alias_id
return compatible
@classmethod
def from_value(cls, value):
"""Creates a `VariableSpec` from the given `Variable`.
`value`'s shape, dtype, and trainable attributes will be used to create
the new `VariableSpec`.
Example:
>>> v = tf.Variable([1., 2., 3.])
>>> VariableSpec.from_value(v)
VariableSpec(shape=(3,), dtype=tf.float32, trainable=True, alias_id=None)
Args:
value: A Variable.
Returns:
A `VariableSpec` created from `value`.
"""
return cls(value.shape, dtype=value.dtype, trainable=value.trainable)
def _to_components(self, value):
return [value.handle]
def _from_components(self, components):
if not isinstance(components, (list, tuple)):
raise TypeError(f"Components of a ResourceVariable must be a list or "
f"tuple, got f{components} instead.")
if len(components) != 1:
raise ValueError(f"Components of a ResourceVariable must only contain "
f"its resource handle, got f{components} instead.")
handle = components[0]
if not isinstance(
handle, tensor_module.Tensor) or handle.dtype != dtypes.resource:
raise ValueError(f"The handle of a ResourceVariable must be a resource "
f"tensor, got {handle} instead.")
return ResourceVariable(trainable=self.trainable,
shape=self.shape,
dtype=self.dtype,
handle=handle)
@property
def _component_specs(self):
return [
tensor_module.TensorSpec(
[],
dtypes.DType(
dtypes.resource._type_enum, # pylint: disable=protected-access
dtypes.HandleData(alias_id=self.alias_id),
),
)
]
def _serialize(self):
return self.shape, self.dtype, self.trainable, self.alias_id
# TraceType method
def is_subtype_of(self, other):
if type(self) is not type(other):
return False
# Remove this once we add alias_id to all CompositeTensors with
# ResourceVariable components.
if self.alias_id is None and other.alias_id is None:
return super().is_subtype_of(other)
if self.alias_id is None or other.alias_id is None:
raise NotImplementedError(f"VariableSpec.is_subtype_of doesn't support "
f"alias_id=None, got self: {self} and other: "
f"{other}.")
return super().is_subtype_of(other)
# TraceType method
def most_specific_common_supertype(self, others):
if any(type(self) is not type(other) for other in others):
return None
# It is a special case for tf.nest, which often takes CompositeTensors and
# converts to TypeSpecs internally, such as tf.nest.assert_same_structure.
if (self.alias_id is None and
all(other.alias_id is None for other in others)):
return super().most_specific_common_supertype(others)
if self.alias_id is None or any(other.alias_id is None for other in others):
raise NotImplementedError(f"VariableSpec.most_specific_common_supertype "
f"doesn't support alias_id=None, got self: "
f"{self} and others: {others}.")
return super().most_specific_common_supertype(others)
# TraceType method
def placeholder_value(self, placeholder_context):
if placeholder_context.unnest_only:
return self
name = self.name or placeholder_context.naming_scope
context_graph = placeholder_context.context_graph
if placeholder_context.has_placeholder(self.alias_id):
# Get reference to the existing variable if alias_id already
# exists in the PlaceholderContext
variable = placeholder_context.get_placeholder(self.alias_id)
else:
spec = tensor_module.TensorSpec([], dtypes.resource)
spec_context = trace_type.InternalPlaceholderContext(
context_graph.outer_graph)
spec_context.update_naming_scope(name)
placeholder = spec.placeholder_value(spec_context)
variable = self._from_components([placeholder])
# (b/262771247) ShardedVariable break without this and VariableSpecs
# without alias_id are not TraceTypes.
if self.alias_id is not None:
placeholder_context.add_placeholder(self.alias_id, variable)
# Capture the Variable's placeholder within the default graph of
# the current thread.
placeholder = context_graph.capture(variable.handle, name=name)
placeholder.op._set_attr( # pylint: disable=protected-access
"_user_specified_name",
attr_value_pb2.AttrValue(s=compat.as_bytes(name)))
return variable
def to_tensors(self, value):
assert isinstance(value, BaseResourceVariable)
variable_accessed(value)
return [value.handle]
def cast(self, value, _):
assert isinstance(value, BaseResourceVariable)
return value
def _get_structure(self):
# shape, dtype, trainable, and alias_id are all leaves.
return PList(PLeaf(), PLeaf(), PLeaf(), PLeaf())
def __repr__(self):
return (f"{type(self).__name__}(shape={self.shape}, dtype={self.dtype!r}, "
f"trainable={self.trainable!r}, alias_id={self.alias_id!r})")
def __hash__(self):
return hash((self.shape, self.dtype, self.trainable, self.alias_id))
def __eq__(self, other):
return (type(self) is type(other) and self.shape == other.shape and
self.dtype == other.dtype and self.trainable == other.trainable and
self.alias_id == other.alias_id)
nested_structure_coder.register_codec(
nested_structure_coder.BuiltInTypeSpecCodec(
VariableSpec, struct_pb2.TypeSpecProto.VARIABLE_SPEC
)
)
def write_object_proto_for_resource_variable(resource_variable,
proto,
options,
enforce_naming=True):
"""Writes additional information of the variable into the SavedObject proto.
This allows users to define a `hook` to provide extra information of the
variable to the SavedObject.
For example, DistributedVariable class would fill in components in the
distributed context.
Args:
resource_variable: A `ResourceVariable` or `DistributedValue` that has the
information to be saved into the proto.
proto: `SavedObject` proto to update.
options: A `SaveOption` instance that configures save behavior.
enforce_naming: A bool determining whether to check that names end in the
expected string ':0'
"""
proto.variable.SetInParent()
if enforce_naming and not resource_variable.name.endswith(":0"):
raise ValueError(f"Cowardly refusing to save variable "
f"{resource_variable.name} because of "
f"unexpected suffix in the name (expected ':0')"
f"which won't be restored.")
proto.variable.name = tensor_module.get_op_name(resource_variable.name)
proto.variable.trainable = resource_variable.trainable
proto.variable.dtype = resource_variable.dtype.as_datatype_enum
proto.variable.synchronization = resource_variable.synchronization.value
proto.variable.aggregation = resource_variable.aggregation.value
proto.variable.shape.CopyFrom(resource_variable.shape.as_proto())
if options.experimental_variable_policy._save_variable_devices( # pylint: disable=protected-access
):
if hasattr(resource_variable, "device"):
proto.variable.device = resource_variable.device
def get_xla_sharding(var: BaseResourceVariable) -> Any:
"""Returns the XLA sharding associated with the variable."""
return var._get_xla_sharding() # pylint: disable=protected-access
| VariableSpec |
python | walkccc__LeetCode | solutions/1277. Count Square Submatrices with All Ones/1277.py | {
"start": 0,
"end": 346
} | class ____:
def countSquares(self, matrix: list[list[int]]) -> int:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 1 and i > 0 and j > 0:
matrix[i][j] += min(matrix[i - 1][j - 1],
matrix[i - 1][j], matrix[i][j - 1])
return sum(map(sum, matrix))
| Solution |
python | cython__cython | Cython/Compiler/Main.py | {
"start": 1639,
"end": 25350
} | class ____:
# This class encapsulates the context needed for compiling
# one or more Cython implementation files along with their
# associated and imported declaration files. It includes
# the root of the module import namespace and the list
# of directories to search for include files.
#
# modules {string : ModuleScope}
# include_directories [string]
# future_directives [object]
# language_level int currently 2 or 3 for Python 2/3
cython_scope = None
language_level = None # warn when not set but default to Py2
def __init__(self, include_directories, compiler_directives, cpp=False,
language_level=None, options=None):
# cython_scope is a hack, set to False by subclasses, in order to break
# an infinite loop.
# Better code organization would fix it.
from . import Builtin, CythonScope
self.modules = {"__builtin__" : Builtin.builtin_scope}
self.cython_scope = CythonScope.create_cython_scope(self)
self.modules["cython"] = self.cython_scope
self.include_directories = include_directories
self.future_directives = set()
self.compiler_directives = compiler_directives
self.cpp = cpp
self.options = options
self.pxds = {} # full name -> node tree
self.utility_pxds = {} # pxd name -> node tree
self._interned = {} # (type(value), value, *key_args) -> interned_value
if language_level is not None:
self.set_language_level(language_level)
self.legacy_implicit_noexcept = self.compiler_directives.get('legacy_implicit_noexcept', False)
self.gdb_debug_outputwriter = None
@classmethod
def from_options(cls, options):
return cls(options.include_path, options.compiler_directives,
options.cplus, options.language_level, options=options)
@property
def shared_c_file_path(self):
return self.options.shared_c_file_path if self.options else None
@property
def shared_utility_qualified_name(self):
return self.options.shared_utility_qualified_name if self.options else None
def set_language_level(self, level):
from .Future import print_function, unicode_literals, absolute_import, division, generator_stop
future_directives = set()
if level == '3str':
level = 3
else:
level = int(level)
if level >= 3:
future_directives.update([unicode_literals, print_function, absolute_import, division, generator_stop])
self.language_level = level
self.future_directives = future_directives
if level >= 3:
self.modules['builtins'] = self.modules['__builtin__']
def intern_ustring(self, value, encoding=None):
key = (EncodedString, value, encoding)
try:
return self._interned[key]
except KeyError:
pass
value = EncodedString(value)
if encoding:
value.encoding = encoding
self._interned[key] = value
return value
# pipeline creation functions can now be found in Pipeline.py
def process_pxd(self, source_desc, scope, module_name):
from . import Pipeline
if isinstance(source_desc, FileSourceDescriptor) and source_desc._file_type == 'pyx':
source = CompilationSource(source_desc, module_name, os.getcwd())
result_sink = create_default_resultobj(source, self.options)
pipeline = Pipeline.create_pyx_as_pxd_pipeline(self, result_sink)
result = Pipeline.run_pipeline(pipeline, source)
elif source_desc.in_utility_code:
from . import ParseTreeTransforms
transform = ParseTreeTransforms.CnameDirectivesTransform(self)
pipeline = Pipeline.create_pxd_pipeline(self, scope, module_name)
pipeline = Pipeline.insert_into_pipeline(
pipeline, transform,
before=ParseTreeTransforms.InterpretCompilerDirectives)
result = Pipeline.run_pipeline(pipeline, source_desc)
else:
pipeline = Pipeline.create_pxd_pipeline(self, scope, module_name)
result = Pipeline.run_pipeline(pipeline, source_desc)
return result
def nonfatal_error(self, exc):
return Errors.report_error(exc)
def _split_qualified_name(self, qualified_name, relative_import=False):
# Splits qualified_name into parts in form of 2-tuples: (PART_NAME, IS_PACKAGE).
qualified_name_parts = qualified_name.split('.')
last_part = qualified_name_parts.pop()
qualified_name_parts = [(p, True) for p in qualified_name_parts]
if last_part != '__init__':
# If Last part is __init__, then it is omitted. Otherwise, we need to check whether we can find
# __init__.pyx/__init__.py file to determine if last part is package or not.
is_package = False
for suffix in ('.py', '.pyx'):
path = self.search_include_directories(
qualified_name, suffix=suffix, source_pos=None, source_file_path=None, sys_path=not relative_import)
if path:
is_package = self._is_init_file(path)
break
qualified_name_parts.append((last_part, is_package))
return qualified_name_parts
@staticmethod
def _is_init_file(path):
return os.path.basename(path) in ('__init__.pyx', '__init__.py', '__init__.pxd') if path else False
@staticmethod
def _check_pxd_filename(pos, pxd_pathname, qualified_name):
if not pxd_pathname:
return
pxd_filename = os.path.basename(pxd_pathname)
if '.' in qualified_name and qualified_name == os.path.splitext(pxd_filename)[0]:
warning(pos, "Dotted filenames ('%s') are deprecated."
" Please use the normal Python package directory layout." % pxd_filename, level=1)
def find_module(self, module_name, from_module=None, pos=None, need_pxd=1,
absolute_fallback=True, relative_import=False):
# Finds and returns the module scope corresponding to
# the given relative or absolute module name. If this
# is the first time the module has been requested, finds
# the corresponding .pxd file and process it.
# If from_module is not None, it must be a module scope,
# and the module will first be searched for relative to
# that module, provided its name is not a dotted name.
debug_find_module = 0
if debug_find_module:
print("Context.find_module: module_name = %s, from_module = %s, pos = %s, need_pxd = %s" % (
module_name, from_module, pos, need_pxd))
scope = None
pxd_pathname = None
if from_module:
if module_name:
# from .module import ...
qualified_name = from_module.qualify_name(module_name)
else:
# from . import ...
qualified_name = from_module.qualified_name
scope = from_module
from_module = None
else:
qualified_name = module_name
if not module_name_pattern.match(qualified_name):
raise CompileError(pos or (module_name, 0, 0),
"'%s' is not a valid module name" % module_name)
if from_module:
if debug_find_module:
print("...trying relative import")
scope = from_module.lookup_submodule(module_name)
if not scope:
pxd_pathname = self.find_pxd_file(qualified_name, pos, sys_path=not relative_import)
self._check_pxd_filename(pos, pxd_pathname, qualified_name)
if pxd_pathname:
is_package = self._is_init_file(pxd_pathname)
scope = from_module.find_submodule(module_name, as_package=is_package)
if not scope:
if debug_find_module:
print("...trying absolute import")
if absolute_fallback:
qualified_name = module_name
scope = self
for name, is_package in self._split_qualified_name(qualified_name, relative_import=relative_import):
scope = scope.find_submodule(name, as_package=is_package)
if debug_find_module:
print("...scope = %s" % scope)
if not scope.pxd_file_loaded:
if debug_find_module:
print("...pxd not loaded")
if not pxd_pathname:
if debug_find_module:
print("...looking for pxd file")
# Only look in sys.path if we are explicitly looking
# for a .pxd file.
pxd_pathname = self.find_pxd_file(qualified_name, pos, sys_path=need_pxd and not relative_import)
self._check_pxd_filename(pos, pxd_pathname, qualified_name)
if debug_find_module:
print("......found %s" % pxd_pathname)
if not pxd_pathname and need_pxd:
# Set pxd_file_loaded such that we don't need to
# look for the non-existing pxd file next time.
scope.pxd_file_loaded = True
package_pathname = self.search_include_directories(
qualified_name, suffix=".py", source_pos=pos, sys_path=not relative_import)
if package_pathname and package_pathname.endswith(Utils.PACKAGE_FILES):
pass
else:
error(pos, "'%s.pxd' not found" % qualified_name.replace('.', os.sep))
if pxd_pathname:
scope.pxd_file_loaded = True
try:
if debug_find_module:
print("Context.find_module: Parsing %s" % pxd_pathname)
rel_path = module_name.replace('.', os.sep) + os.path.splitext(pxd_pathname)[1]
if not pxd_pathname.endswith(rel_path):
rel_path = pxd_pathname # safety measure to prevent printing incorrect paths
source_desc = FileSourceDescriptor(pxd_pathname, rel_path)
err, result = self.process_pxd(source_desc, scope, qualified_name)
if err:
raise err
(pxd_codenodes, pxd_scope) = result
self.pxds[module_name] = (pxd_codenodes, pxd_scope)
except CompileError:
pass
return scope
def find_pxd_file(self, qualified_name, pos=None, sys_path=True, source_file_path=None):
# Search include path (and sys.path if sys_path is True) for
# the .pxd file corresponding to the given fully-qualified
# module name.
# Will find either a dotted filename or a file in a
# package directory. If a source file position is given,
# the directory containing the source file is searched first
# for a dotted filename, and its containing package root
# directory is searched first for a non-dotted filename.
pxd = self.search_include_directories(
qualified_name, suffix=".pxd", source_pos=pos, sys_path=sys_path, source_file_path=source_file_path)
if pxd is None and Options.cimport_from_pyx:
return self.find_pyx_file(qualified_name, pos, sys_path=sys_path)
return pxd
def find_pyx_file(self, qualified_name, pos=None, sys_path=True, source_file_path=None):
# Search include path for the .pyx file corresponding to the
# given fully-qualified module name, as for find_pxd_file().
return self.search_include_directories(
qualified_name, suffix=".pyx", source_pos=pos, sys_path=sys_path, source_file_path=source_file_path)
def find_include_file(self, filename, pos=None, source_file_path=None):
# Search list of include directories for filename.
# Reports an error and returns None if not found.
path = self.search_include_directories(
filename, source_pos=pos, include=True, source_file_path=source_file_path)
if not path:
error(pos, "'%s' not found" % filename)
return path
def search_include_directories(self, qualified_name,
suffix=None, source_pos=None, include=False, sys_path=False, source_file_path=None):
include_dirs = self.include_directories
if sys_path:
include_dirs = include_dirs + sys.path
# include_dirs must be hashable for caching in @cached_function
include_dirs = tuple(include_dirs + [standard_include_path])
return search_include_directories(
include_dirs, qualified_name, suffix or "", source_pos, include, source_file_path)
def find_root_package_dir(self, file_path):
return Utils.find_root_package_dir(file_path)
def check_package_dir(self, dir, package_names):
return Utils.check_package_dir(dir, tuple(package_names))
def c_file_out_of_date(self, source_path, output_path):
if not os.path.exists(output_path):
return 1
c_time = Utils.modification_time(output_path)
if Utils.file_newer_than(source_path, c_time):
return 1
pxd_path = Utils.replace_suffix(source_path, ".pxd")
if os.path.exists(pxd_path) and Utils.file_newer_than(pxd_path, c_time):
return 1
for kind, name in self.read_dependency_file(source_path):
if kind == "cimport":
dep_path = self.find_pxd_file(name, source_file_path=source_path)
elif kind == "include":
dep_path = self.search_include_directories(name, source_file_path=source_path)
else:
continue
if dep_path and Utils.file_newer_than(dep_path, c_time):
return 1
return 0
def find_cimported_module_names(self, source_path):
return [ name for kind, name in self.read_dependency_file(source_path)
if kind == "cimport" ]
def is_package_dir(self, dir_path):
return Utils.is_package_dir(dir_path)
def read_dependency_file(self, source_path):
dep_path = Utils.replace_suffix(source_path, ".dep")
if os.path.exists(dep_path):
with open(dep_path) as f:
chunks = [ line.split(" ", 1)
for line in (l.strip() for l in f)
if " " in line ]
return chunks
else:
return ()
def lookup_submodule(self, name):
# Look up a top-level module. Returns None if not found.
return self.modules.get(name, None)
def find_submodule(self, name, as_package=False):
# Find a top-level module, creating a new one if needed.
scope = self.lookup_submodule(name)
if not scope:
scope = ModuleScope(name,
parent_module = None, context = self, is_package=as_package)
self.modules[name] = scope
return scope
def parse(self, source_desc, scope, pxd, full_module_name):
if not isinstance(source_desc, FileSourceDescriptor):
raise RuntimeError("Only file sources for code supported")
scope.cpp = self.cpp
# Parse the given source file and return a parse tree.
num_errors = Errors.get_errors_count()
try:
with source_desc.get_file_object() as f:
from . import Parsing
s = PyrexScanner(f, source_desc, source_encoding = f.encoding,
scope = scope, context = self)
tree = Parsing.p_module(s, pxd, full_module_name)
if self.options.formal_grammar:
try:
from ..Parser import ConcreteSyntaxTree
except ImportError:
raise RuntimeError(
"Formal grammar can only be used with compiled Cython with an available pgen.")
ConcreteSyntaxTree.p_module(source_desc.filename)
except UnicodeDecodeError as e:
#import traceback
#traceback.print_exc()
raise self._report_decode_error(source_desc, e)
if Errors.get_errors_count() > num_errors:
raise CompileError()
return tree
def _report_decode_error(self, source_desc, exc):
msg = exc.args[-1]
position = exc.args[2]
encoding = exc.args[0]
line = 1
column = idx = 0
with open(source_desc.filename, encoding='iso8859-1', newline='') as f:
for line, data in enumerate(f, 1):
idx += len(data)
if idx >= position:
column = position - (idx - len(data)) + 1
break
return error((source_desc, line, column),
"Decoding error, missing or incorrect coding=<encoding-name> "
"at top of source (cannot decode with encoding %r: %s)" % (encoding, msg))
def extract_module_name(self, path, options):
# Find fully_qualified module name from the full pathname
# of a source file.
dir, filename = os.path.split(path)
module_name, _ = os.path.splitext(filename)
if "." in module_name:
return module_name
names = [module_name]
while self.is_package_dir(dir):
parent, package_name = os.path.split(dir)
if parent == dir:
break
names.append(package_name)
dir = parent
names.reverse()
return ".".join(names)
def setup_errors(self, options, result):
Errors.reset()
if options.use_listing_file:
path = result.listing_file = Utils.replace_suffix(result.main_source_file, ".lis")
else:
path = None
Errors.open_listing_file(path=path, echo_to_stderr=options.errors_to_stderr)
def teardown_errors(self, err, options, result):
source_desc = result.compilation_source.source_desc
if not isinstance(source_desc, FileSourceDescriptor):
raise RuntimeError("Only file sources for code supported")
Errors.close_listing_file()
result.num_errors = Errors.get_errors_count()
if result.num_errors > 0:
err = True
if err and result.c_file:
try:
Utils.castrate_file(result.c_file, os.stat(source_desc.filename))
except OSError:
pass
result.c_file = None
def get_output_filename(source_filename, cwd, options):
if options.cplus:
c_suffix = ".cpp"
else:
c_suffix = ".c"
suggested_file_name = Utils.replace_suffix(source_filename, c_suffix)
if options.output_file:
out_path = os.path.join(cwd, options.output_file)
if os.path.isdir(out_path):
return os.path.join(out_path, os.path.basename(suggested_file_name))
else:
return out_path
else:
return suggested_file_name
def create_default_resultobj(compilation_source, options):
result = CompilationResult()
result.main_source_file = compilation_source.source_desc.filename
result.compilation_source = compilation_source
source_desc = compilation_source.source_desc
result.c_file = get_output_filename(source_desc.filename,
compilation_source.cwd, options)
result.embedded_metadata = options.embedded_metadata
return result
def setup_source_object(source, source_ext, full_module_name, options, context):
cwd = os.getcwd()
abs_path = os.path.abspath(source)
full_module_name = full_module_name or context.extract_module_name(source, options)
full_module_name = EncodedString(full_module_name)
Utils.raise_error_if_module_name_forbidden(full_module_name)
if options.relative_path_in_code_position_comments:
rel_path = full_module_name.replace('.', os.sep) + source_ext
if not abs_path.endswith(rel_path):
rel_path = source # safety measure to prevent printing incorrect paths
else:
rel_path = abs_path
source_desc = FileSourceDescriptor(abs_path, rel_path)
return CompilationSource(source_desc, full_module_name, cwd)
def run_cached_pipeline(source, options, full_module_name, context, cache, fingerprint):
cwd = os.getcwd()
output_filename = get_output_filename(source, cwd, options)
cached = cache.lookup_cache(output_filename, fingerprint)
if cached:
cache.load_from_cache(output_filename, cached)
source_ext = os.path.splitext(source)[1]
options.configure_language_defaults(source_ext[1:]) # py/pyx
source = setup_source_object(source, source_ext, full_module_name, options, context)
# Set up result object
return create_default_resultobj(source, options)
result = run_pipeline(source, options, full_module_name, context)
if fingerprint:
cache.store_to_cache(output_filename, fingerprint, result)
return result
def run_pipeline(source, options, full_module_name, context):
from . import Pipeline
if options.verbose:
sys.stderr.write("Compiling %s\n" % source)
source_ext = os.path.splitext(source)[1]
abs_path = os.path.abspath(source)
options.configure_language_defaults(source_ext[1:]) # py/pyx
source = setup_source_object(source, source_ext, full_module_name, options, context)
# Set up result object
result = create_default_resultobj(source, options)
if options.annotate is None:
# By default, decide based on whether an html file already exists.
html_filename = os.path.splitext(result.c_file)[0] + ".html"
if os.path.exists(html_filename):
with open(html_filename, encoding="UTF-8") as html_file:
if '<!-- Generated by Cython' in html_file.read(100):
options.annotate = True
# Get pipeline
if source_ext.lower() == '.py' or not source_ext:
pipeline = Pipeline.create_py_pipeline(context, options, result)
else:
pipeline = Pipeline.create_pyx_pipeline(context, options, result)
context.setup_errors(options, result)
if '.' in source.full_module_name and '.' in os.path.splitext(os.path.basename(abs_path))[0]:
warning((source.source_desc, 1, 0),
"Dotted filenames ('%s') are deprecated."
" Please use the normal Python package directory layout." % os.path.basename(abs_path), level=1)
if re.search("[.]c(pp|[+][+]|xx)$", result.c_file, re.RegexFlag.IGNORECASE) and not context.cpp:
warning((source.source_desc, 1, 0),
"Filename implies a c++ file but Cython is not in c++ mode.",
level=1)
err, enddata = Pipeline.run_pipeline(pipeline, source)
context.teardown_errors(err, options, result)
if err is None and options.depfile:
from ..Build.Dependencies import create_dependency_tree
dependencies = create_dependency_tree(context).all_dependencies(result.main_source_file)
Utils.write_depfile(result.c_file, result.main_source_file, dependencies)
return result
# ------------------------------------------------------------------------
#
# Main Python entry points
#
# ------------------------------------------------------------------------
| Context |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP037_0.py | {
"start": 460,
"end": 502
} | class ____(NamedTuple):
x: "MyClass"
| Foo |
python | pytorch__pytorch | torch/xpu/__init__.py | {
"start": 5935,
"end": 6546
} | class ____:
r"""Context-manager that changes the selected device.
Args:
device (torch.device or int or str): device index to select. It's a no-op if
this argument is a negative integer or ``None``.
"""
def __init__(self, device: Any) -> None:
self.idx = _get_device_index(device, optional=True)
self.prev_idx = -1
def __enter__(self):
self.prev_idx = torch.xpu._exchange_device(self.idx)
def __exit__(self, type: Any, value: Any, traceback: Any):
self.idx = torch.xpu._maybe_exchange_device(self.prev_idx)
return False
| device |
python | ethereum__web3.py | web3/_utils/datatypes.py | {
"start": 556,
"end": 1653
} | class ____(type):
def __init__(
cls,
name: str,
bases: tuple[type[Any], ...],
namespace: dict[str, Any],
**kwargs: dict[str, Any],
) -> None:
# see PEP487. To accept kwargs in __new__, they need to be
# filtered out here.
super().__init__(name, bases, namespace)
# __new__ must return a class instance
def __new__(
mcs,
name: str,
bases: tuple[type],
namespace: dict[str, Any],
normalizers: dict[str, Any] | None = None,
) -> "PropertyCheckingFactory":
all_bases = set(concat(base.__mro__ for base in bases))
all_keys = set(concat(base.__dict__.keys() for base in all_bases))
for key in namespace:
verify_attr(name, key, all_keys)
if normalizers:
processed_namespace = apply_formatters_to_dict(
normalizers,
namespace,
)
else:
processed_namespace = namespace
return super().__new__(mcs, name, bases, processed_namespace)
| PropertyCheckingFactory |
python | redis__redis-py | redis/ocsp.py | {
"start": 6121,
"end": 11452
} | class ____:
"""A class to verify ssl sockets for RFC6960/RFC6961. This can be used
when using direct validation of OCSP responses and certificate revocations.
@see https://datatracker.ietf.org/doc/html/rfc6960
@see https://datatracker.ietf.org/doc/html/rfc6961
"""
def __init__(self, sock, host, port, ca_certs=None):
self.SOCK = sock
self.HOST = host
self.PORT = port
self.CA_CERTS = ca_certs
def _bin2ascii(self, der):
"""Convert SSL certificates in a binary (DER) format to ASCII PEM."""
pem = ssl.DER_cert_to_PEM_cert(der)
cert = x509.load_pem_x509_certificate(pem.encode(), backends.default_backend())
return cert
def components_from_socket(self):
"""This function returns the certificate, primary issuer, and primary ocsp
server in the chain for a socket already wrapped with ssl.
"""
# convert the binary certifcate to text
der = self.SOCK.getpeercert(True)
if der is False:
raise ConnectionError("no certificate found for ssl peer")
cert = self._bin2ascii(der)
return self._certificate_components(cert)
def _certificate_components(self, cert):
"""Given an SSL certificate, retract the useful components for
validating the certificate status with an OCSP server.
Args:
cert ([bytes]): A PEM encoded ssl certificate
"""
try:
aia = cert.extensions.get_extension_for_oid(
x509.oid.ExtensionOID.AUTHORITY_INFORMATION_ACCESS
).value
except cryptography.x509.extensions.ExtensionNotFound:
raise ConnectionError("No AIA information present in ssl certificate")
# fetch certificate issuers
issuers = [
i
for i in aia
if i.access_method == x509.oid.AuthorityInformationAccessOID.CA_ISSUERS
]
try:
issuer = issuers[0].access_location.value
except IndexError:
issuer = None
# now, the series of ocsp server entries
ocsps = [
i
for i in aia
if i.access_method == x509.oid.AuthorityInformationAccessOID.OCSP
]
try:
ocsp = ocsps[0].access_location.value
except IndexError:
raise ConnectionError("no ocsp servers in certificate")
return cert, issuer, ocsp
def components_from_direct_connection(self):
"""Return the certificate, primary issuer, and primary ocsp server
from the host defined by the socket. This is useful in cases where
different certificates are occasionally presented.
"""
pem = ssl.get_server_certificate((self.HOST, self.PORT), ca_certs=self.CA_CERTS)
cert = x509.load_pem_x509_certificate(pem.encode(), backends.default_backend())
return self._certificate_components(cert)
def build_certificate_url(self, server, cert, issuer_cert):
"""Return the complete url to the ocsp"""
orb = ocsp.OCSPRequestBuilder()
# add_certificate returns an initialized OCSPRequestBuilder
orb = orb.add_certificate(
cert, issuer_cert, cryptography.hazmat.primitives.hashes.SHA256()
)
request = orb.build()
path = base64.b64encode(
request.public_bytes(hazmat.primitives.serialization.Encoding.DER)
)
url = urljoin(server, path.decode("ascii"))
return url
def check_certificate(self, server, cert, issuer_url):
"""Checks the validity of an ocsp server for an issuer"""
r = requests.get(issuer_url)
if not r.ok:
raise ConnectionError("failed to fetch issuer certificate")
der = r.content
issuer_cert = self._bin2ascii(der)
ocsp_url = self.build_certificate_url(server, cert, issuer_cert)
# HTTP 1.1 mandates the addition of the Host header in ocsp responses
header = {
"Host": urlparse(ocsp_url).netloc,
"Content-Type": "application/ocsp-request",
}
r = requests.get(ocsp_url, headers=header)
if not r.ok:
raise ConnectionError("failed to fetch ocsp certificate")
return _check_certificate(issuer_cert, r.content, True)
def is_valid(self):
"""Returns the validity of the certificate wrapping our socket.
This first retrieves for validate the certificate, issuer_url,
and ocsp_server for certificate validate. Then retrieves the
issuer certificate from the issuer_url, and finally checks
the validity of OCSP revocation status.
"""
# validate the certificate
try:
cert, issuer_url, ocsp_server = self.components_from_socket()
if issuer_url is None:
raise ConnectionError("no issuers found in certificate chain")
return self.check_certificate(ocsp_server, cert, issuer_url)
except AuthorizationError:
cert, issuer_url, ocsp_server = self.components_from_direct_connection()
if issuer_url is None:
raise ConnectionError("no issuers found in certificate chain")
return self.check_certificate(ocsp_server, cert, issuer_url)
| OCSPVerifier |
python | huggingface__transformers | utils/modular_integrations.py | {
"start": 6697,
"end": 7139
} | class ____(cst.CSTTransformer):
def __init__(self, relative_path: str, source_library: str):
super().__init__()
self.relative_path = relative_path
self.source_library = source_library
def leave_ImportFrom(self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom) -> cst.ImportFrom:
return convert_to_relative_import(updated_node, self.relative_path, self.source_library)
| RelativeImportTransformer |
python | wandb__wandb | wandb/automations/_filters/run_metrics.py | {
"start": 1065,
"end": 1284
} | class ____(LenientStrEnum): # from: Aggregation
"""Supported run metric aggregation operations."""
MAX = "MAX"
MIN = "MIN"
AVERAGE = "AVERAGE"
# Shorter aliases for convenience
AVG = AVERAGE
| Agg |
python | pyparsing__pyparsing | pyparsing/results.py | {
"start": 344,
"end": 723
} | class ____:
tup: tuple[ParseResults, int]
__slots__ = ["tup"]
def __init__(self, p1: ParseResults, p2: int) -> None:
self.tup: tuple[ParseResults, int] = (p1, p2)
def __getitem__(self, i):
return self.tup[i]
def __getstate__(self):
return self.tup
def __setstate__(self, *args):
self.tup = args[0]
| _ParseResultsWithOffset |
python | lxml__lxml | src/lxml/tests/test_xslt.py | {
"start": 326,
"end": 35003
} | class ____(HelperTestCase):
"""XSLT tests etree"""
def test_xslt(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="/a/b/text()" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree)
self.assertEqual('''\
<?xml version="1.0"?>
<foo>B</foo>
''',
str(res))
def test_xslt_elementtree_error(self):
self.assertRaises(ValueError, etree.XSLT, etree.ElementTree())
def test_xslt_input_none(self):
self.assertRaises(TypeError, etree.XSLT, None)
def test_xslt_invalid_stylesheet(self):
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:stylesheet />
</xsl:stylesheet>''')
self.assertRaises(
etree.XSLTParseError, etree.XSLT, style)
def test_xslt_copy(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="/a/b/text()" /></foo>
</xsl:template>
</xsl:stylesheet>''')
transform = etree.XSLT(style)
res = transform(tree)
self.assertEqual('''\
<?xml version="1.0"?>
<foo>B</foo>
''',
str(res))
transform_copy = copy.deepcopy(transform)
res = transform_copy(tree)
self.assertEqual('''\
<?xml version="1.0"?>
<foo>B</foo>
''',
str(res))
transform = etree.XSLT(style)
res = transform(tree)
self.assertEqual('''\
<?xml version="1.0"?>
<foo>B</foo>
''',
str(res))
@contextlib.contextmanager
def _xslt_setup(
self, encoding='UTF-16', expected_encoding=None,
expected='<?xml version="1.0" encoding="%(ENCODING)s"?><foo>\uF8D2</foo>'):
tree = self.parse('<a><b>\uF8D2</b><c>\uF8D2</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="%(ENCODING)s"/>
<xsl:template match="/">
<foo><xsl:value-of select="/a/b/text()" /></foo>
</xsl:template>
</xsl:stylesheet>''' % {'ENCODING': encoding})
st = etree.XSLT(style)
res = st(tree)
expected = dedent(expected).strip().replace('\n', '') % {
'ENCODING': expected_encoding or encoding,
}
data = [res]
yield data
self.assertEqual(expected, data[0].replace('\n', ''))
def test_xslt_utf8(self):
with self._xslt_setup(encoding='UTF-8') as res:
res[0] = bytes(res[0]).decode('UTF-8')
assert 'UTF-8' in res[0]
def test_xslt_encoding(self):
with self._xslt_setup() as res:
res[0] = bytes(res[0]).decode('UTF-16')
assert 'UTF-16' in res[0]
def test_xslt_encoding_override(self):
with self._xslt_setup(encoding='UTF-8', expected_encoding='UTF-16') as res:
f = BytesIO()
res[0].write(f, encoding='UTF-16')
output = str(f.getvalue(), 'UTF-16')
res[0] = output.replace("'", '"')
def test_xslt_write_output_bytesio(self):
with self._xslt_setup() as res:
f = BytesIO()
res[0].write_output(f)
res[0] = f.getvalue().decode('UTF-16')
def test_xslt_write_output_failure(self):
class Writer:
def write(self, data):
raise ValueError("FAILED!")
try:
with self._xslt_setup() as res:
res[0].write_output(Writer())
except ValueError as exc:
self.assertTrue("FAILED!" in str(exc), exc)
else:
self.assertTrue(False, "exception not raised")
def test_xslt_write_output_file(self):
with self._xslt_setup() as res:
f = NamedTemporaryFile(delete=False)
try:
try:
res[0].write_output(f)
finally:
f.close()
with open(f.name, encoding='UTF-16') as f:
res[0] = f.read()
finally:
os.unlink(f.name)
def test_xslt_write_output_file_path(self):
with self._xslt_setup() as res:
f = NamedTemporaryFile(delete=False)
try:
try:
res[0].write_output(f.name, compression=9)
finally:
f.close()
with gzip.GzipFile(f.name) as f:
res[0] = f.read().decode("UTF-16")
finally:
os.unlink(f.name)
def test_xslt_write_output_file_pathlike(self):
with self._xslt_setup() as res:
f = NamedTemporaryFile(delete=False)
try:
try:
res[0].write_output(SimpleFSPath(f.name), compression=9)
finally:
f.close()
with gzip.GzipFile(f.name) as f:
res[0] = f.read().decode("UTF-16")
finally:
os.unlink(f.name)
def test_xslt_write_output_file_path_urlescaped(self):
# libxml2 should not unescape file paths.
with self._xslt_setup() as res:
f = NamedTemporaryFile(prefix='tmp%2e', suffix='.xml.gz', delete=False)
try:
try:
res[0].write_output(f.name, compression=3)
finally:
f.close()
with gzip.GzipFile(f.name) as f:
res[0] = f.read().decode("UTF-16")
finally:
os.unlink(f.name)
def test_xslt_write_output_file_path_urlescaped_plus(self):
with self._xslt_setup() as res:
f = NamedTemporaryFile(prefix='p+%2e', suffix='.xml.gz', delete=False)
try:
try:
res[0].write_output(f.name, compression=1)
finally:
f.close()
with gzip.GzipFile(f.name) as f:
res[0] = f.read().decode("UTF-16")
finally:
os.unlink(f.name)
def test_xslt_write_output_file_oserror(self):
with self._xslt_setup(expected='') as res:
tempdir = mkdtemp()
try:
res[0].write_output(os.path.join(tempdir, 'missing_subdir', 'out.xml'))
except OSError:
res[0] = ''
else:
self.fail("IOError not raised")
finally:
os.rmdir(tempdir)
def test_xslt_unicode(self):
expected = '''
<?xml version="1.0"?>
<foo>\uF8D2</foo>
'''
with self._xslt_setup(expected=expected) as res:
res[0] = str(res[0])
def test_xslt_unicode_standalone(self):
tree = self.parse('<a><b>\uF8D2</b><c>\uF8D2</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="UTF-16" standalone="no"/>
<xsl:template match="/">
<foo><xsl:value-of select="/a/b/text()" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree)
expected = '''\
<?xml version="1.0" standalone="no"?>
<foo>\uF8D2</foo>
'''
self.assertEqual(expected,
str(res))
def test_xslt_input(self):
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="/a/b/text()" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
st = etree.XSLT(style.getroot())
def test_xslt_input_partial_doc(self):
style = self.parse('''\
<otherroot>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="/a/b/text()" /></foo>
</xsl:template>
</xsl:stylesheet>
</otherroot>''')
self.assertRaises(etree.XSLTParseError, etree.XSLT, style)
root_node = style.getroot()
self.assertRaises(etree.XSLTParseError, etree.XSLT, root_node)
st = etree.XSLT(root_node[0])
def test_xslt_broken(self):
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:foo />
</xsl:stylesheet>''')
self.assertRaises(etree.XSLTParseError,
etree.XSLT, style)
def test_xslt_parsing_error_log(self):
tree = self.parse('<a/>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:foo />
</xsl:stylesheet>''')
self.assertRaises(etree.XSLTParseError,
etree.XSLT, style)
exc = None
try:
etree.XSLT(style)
except etree.XSLTParseError as e:
exc = e
else:
self.assertFalse(True, "XSLT processing should have failed but didn't")
self.assertTrue(exc is not None)
self.assertTrue(len(exc.error_log))
for error in exc.error_log:
self.assertTrue(':ERROR:XSLT:' in str(error))
def test_xslt_apply_error_log(self):
tree = self.parse('<a/>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="a">
<xsl:copy>
<xsl:message terminate="yes">FAIL</xsl:message>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>''')
self.assertRaises(etree.XSLTApplyError,
etree.XSLT(style), tree)
transform = etree.XSLT(style)
exc = None
try:
transform(tree)
except etree.XSLTApplyError as e:
exc = e
else:
self.assertFalse(True, "XSLT processing should have failed but didn't")
self.assertTrue(exc is not None)
self.assertTrue(len(exc.error_log))
self.assertEqual(len(transform.error_log), len(exc.error_log))
for error in exc.error_log:
self.assertTrue(':ERROR:XSLT:' in str(error))
for error in transform.error_log:
self.assertTrue(':ERROR:XSLT:' in str(error))
def test_xslt_parameters(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<foo><xsl:value-of select="$bar" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree, bar="'Bar'")
self.assertEqual('''\
<?xml version="1.0"?>
<foo>Bar</foo>
''',
str(res))
def test_xslt_string_parameters(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<foo><xsl:value-of select="$bar" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree, bar=etree.XSLT.strparam('''it's me, "Bar"'''))
self.assertEqual('''\
<?xml version="1.0"?>
<foo>it's me, "Bar"</foo>
''',
str(res))
def test_xslt_parameter_invalid(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="bar"/>
<xsl:template match="/">
<foo><xsl:value-of select="$bar" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = self.assertRaises(etree.XSLTApplyError,
st, tree, bar="<test/>")
res = self.assertRaises(etree.XSLTApplyError,
st, tree, bar="....")
def test_xslt_parameter_missing(self):
# apply() without needed parameter will lead to XSLTApplyError
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<foo><xsl:value-of select="$bar" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
# at least libxslt 1.1.28 produces this error, earlier ones (e.g. 1.1.18) might not ...
self.assertRaises(etree.XSLTApplyError, st, tree)
def test_xslt_multiple_parameters(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="$bar" /></foo>
<foo><xsl:value-of select="$baz" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree, bar="'Bar'", baz="'Baz'")
self.assertEqual('''\
<?xml version="1.0"?>
<foo>Bar</foo><foo>Baz</foo>
''',
str(res))
def test_xslt_parameter_xpath(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="$bar" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree, bar="/a/b/text()")
self.assertEqual('''\
<?xml version="1.0"?>
<foo>B</foo>
''',
str(res))
def test_xslt_parameter_xpath_object(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="$bar" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree, bar=etree.XPath("/a/b/text()"))
self.assertEqual('''\
<?xml version="1.0"?>
<foo>B</foo>
''',
str(res))
def test_xslt_default_parameters(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="bar" select="'Default'" />
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="$bar" /></foo>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree, bar="'Bar'")
self.assertEqual('''\
<?xml version="1.0"?>
<foo>Bar</foo>
''',
str(res))
res = st(tree)
self.assertEqual('''\
<?xml version="1.0"?>
<foo>Default</foo>
''',
str(res))
def test_xslt_html_output(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<html><body><xsl:value-of select="/a/b/text()" /></body></html>
</xsl:template>
</xsl:stylesheet>''')
st = etree.XSLT(style)
res = st(tree)
self.assertEqual('<html><body>B</body></html>',
str(res).strip())
def test_xslt_include(self):
tree = etree.parse(fileInTestDir('test1.xslt'))
st = etree.XSLT(tree)
def test_xslt_include_from_filelike(self):
f = open(fileInTestDir('test1.xslt'), 'rb')
tree = etree.parse(f)
f.close()
st = etree.XSLT(tree)
def test_xslt_multiple_transforms(self):
xml = '<a/>'
xslt = '''\
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<response>Some text</response>
</xsl:template>
</xsl:stylesheet>
'''
source = self.parse(xml)
styledoc = self.parse(xslt)
style = etree.XSLT(styledoc)
result = style(source)
etree.tostring(result.getroot())
source = self.parse(xml)
styledoc = self.parse(xslt)
style = etree.XSLT(styledoc)
result = style(source)
etree.tostring(result.getroot())
def test_xslt_repeat_transform(self):
xml = '<a/>'
xslt = '''\
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<response>Some text</response>
</xsl:template>
</xsl:stylesheet>
'''
source = self.parse(xml)
styledoc = self.parse(xslt)
transform = etree.XSLT(styledoc)
result = transform(source)
result = transform(source)
etree.tostring(result.getroot())
result = transform(source)
etree.tostring(result.getroot())
str(result)
result1 = transform(source)
result2 = transform(source)
self.assertEqual(str(result1), str(result2))
result = transform(source)
str(result)
def test_xslt_empty(self):
# could segfault if result contains "empty document"
xml = '<blah/>'
xslt = '''
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/" />
</xsl:stylesheet>
'''
source = self.parse(xml)
styledoc = self.parse(xslt)
style = etree.XSLT(styledoc)
result = style(source)
self.assertEqual('', str(result))
def test_xslt_message(self):
xml = '<blah/>'
xslt = '''
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:message>TEST TEST TEST</xsl:message>
</xsl:template>
</xsl:stylesheet>
'''
source = self.parse(xml)
styledoc = self.parse(xslt)
style = etree.XSLT(styledoc)
result = style(source)
self.assertEqual('', str(result))
self.assertTrue("TEST TEST TEST" in [entry.message
for entry in style.error_log])
def test_xslt_message_terminate(self):
xml = '<blah/>'
xslt = '''
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:message terminate="yes">TEST TEST TEST</xsl:message>
</xsl:template>
</xsl:stylesheet>
'''
source = self.parse(xml)
styledoc = self.parse(xslt)
style = etree.XSLT(styledoc)
self.assertRaises(etree.XSLTApplyError, style, source)
self.assertTrue("TEST TEST TEST" in [entry.message
for entry in style.error_log])
def test_xslt_shortcut(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<doc>
<foo><xsl:value-of select="$bar" /></foo>
<foo><xsl:value-of select="$baz" /></foo>
</doc>
</xsl:template>
</xsl:stylesheet>''')
result = tree.xslt(style, bar="'Bar'", baz="'Baz'")
self.assertEqual(
b'<doc><foo>Bar</foo><foo>Baz</foo></doc>',
etree.tostring(result.getroot()))
def test_multiple_elementrees(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="a"><A><xsl:apply-templates/></A></xsl:template>
<xsl:template match="b"><B><xsl:apply-templates/></B></xsl:template>
<xsl:template match="c"><C><xsl:apply-templates/></C></xsl:template>
</xsl:stylesheet>''')
self.assertEqual(self._rootstring(tree),
b'<a><b>B</b><c>C</c></a>')
result = tree.xslt(style)
self.assertEqual(self._rootstring(tree),
b'<a><b>B</b><c>C</c></a>')
self.assertEqual(self._rootstring(result),
b'<A><B>B</B><C>C</C></A>')
b_tree = etree.ElementTree(tree.getroot()[0])
self.assertEqual(self._rootstring(b_tree),
b'<b>B</b>')
result = b_tree.xslt(style)
self.assertEqual(self._rootstring(tree),
b'<a><b>B</b><c>C</c></a>')
self.assertEqual(self._rootstring(result),
b'<B>B</B>')
c_tree = etree.ElementTree(tree.getroot()[1])
self.assertEqual(self._rootstring(c_tree),
b'<c>C</c>')
result = c_tree.xslt(style)
self.assertEqual(self._rootstring(tree),
b'<a><b>B</b><c>C</c></a>')
self.assertEqual(self._rootstring(result),
b'<C>C</C>')
def test_xslt_document_XML(self):
# make sure document('') works from parsed strings
xslt = etree.XSLT(etree.XML("""\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<test>TEXT<xsl:copy-of select="document('')//test"/></test>
</xsl:template>
</xsl:stylesheet>
"""))
result = xslt(etree.XML('<a/>'))
root = result.getroot()
self.assertEqual(root.tag,
'test')
self.assertEqual(root[0].tag,
'test')
self.assertEqual(root[0].text,
'TEXT')
self.assertEqual(root[0][0].tag,
'{http://www.w3.org/1999/XSL/Transform}copy-of')
def test_xslt_document_parse(self):
# make sure document('') works from loaded files
xslt = etree.XSLT(etree.parse(fileInTestDir("test-document.xslt")))
result = xslt(etree.XML('<a/>'))
root = result.getroot()
self.assertEqual(root.tag,
'test')
self.assertEqual(root[0].tag,
'{http://www.w3.org/1999/XSL/Transform}stylesheet')
def test_xslt_document_elementtree(self):
# make sure document('') works from loaded files
xslt = etree.XSLT(etree.ElementTree(file=fileInTestDir("test-document.xslt")))
result = xslt(etree.XML('<a/>'))
root = result.getroot()
self.assertEqual(root.tag,
'test')
self.assertEqual(root[0].tag,
'{http://www.w3.org/1999/XSL/Transform}stylesheet')
def test_xslt_document_error(self):
xslt = etree.XSLT(etree.XML("""\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<test>TEXT<xsl:copy-of select="document('uri:__junkfood__is__evil__')//test"/></test>
</xsl:template>
</xsl:stylesheet>
"""))
errors = None
try:
xslt(etree.XML('<a/>'))
except etree.XSLTApplyError as exc:
errors = exc.error_log
else:
self.assertFalse(True, "XSLT processing should have failed but didn't")
self.assertTrue(len(errors))
for error in errors:
if ':ERROR:XSLT:' in str(error):
break
else:
self.assertFalse(True, 'No XSLT errors found in error log:\n%s' % errors)
def test_xslt_document_XML_resolver(self):
# make sure document('') works when custom resolvers are in use
assertEqual = self.assertEqual
called = {'count' : 0}
class TestResolver(etree.Resolver):
def resolve(self, url, id, context):
assertEqual(url, 'file://ANYTHING')
called['count'] += 1
return self.resolve_string('<CALLED/>', context)
parser = etree.XMLParser()
parser.resolvers.add(TestResolver())
xslt = etree.XSLT(etree.XML(b"""\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:l="local">
<xsl:template match="/">
<test>
<xsl:for-each select="document('')//l:data/l:entry">
<xsl:copy-of select="document('file://ANYTHING')"/>
<xsl:copy>
<xsl:attribute name="value">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:copy>
</xsl:for-each>
</test>
</xsl:template>
<l:data>
<l:entry>A</l:entry>
<l:entry>B</l:entry>
</l:data>
</xsl:stylesheet>
""", parser))
self.assertEqual(called['count'], 0)
result = xslt(etree.XML('<a/>'))
self.assertEqual(called['count'], 1)
root = result.getroot()
self.assertEqual(root.tag,
'test')
self.assertEqual(len(root), 4)
self.assertEqual(root[0].tag,
'CALLED')
self.assertEqual(root[1].tag,
'{local}entry')
self.assertEqual(root[1].text,
None)
self.assertEqual(root[1].get("value"),
'A')
self.assertEqual(root[2].tag,
'CALLED')
self.assertEqual(root[3].tag,
'{local}entry')
self.assertEqual(root[3].text,
None)
self.assertEqual(root[3].get("value"),
'B')
def test_xslt_resolver_url_building(self):
assertEqual = self.assertEqual
called = {'count' : 0}
expected_url = None
class TestResolver(etree.Resolver):
def resolve(self, url, id, context):
assertEqual(url, expected_url)
called['count'] += 1
return self.resolve_string('<CALLED/>', context)
stylesheet_xml = b"""\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:l="local">
<xsl:template match="/">
<xsl:copy-of select="document('test.xml')"/>
</xsl:template>
</xsl:stylesheet>
"""
parser = etree.XMLParser()
parser.resolvers.add(TestResolver())
# test without base_url => relative path only
expected_url = 'test.xml'
xslt = etree.XSLT(etree.XML(stylesheet_xml, parser))
self.assertEqual(called['count'], 0)
result = xslt(etree.XML('<a/>'))
self.assertEqual(called['count'], 1)
# now the same thing with a stylesheet base URL on the filesystem
called['count'] = 0
expected_url = 'MY/BASE/test.xml' # seems to be the same on Windows
xslt = etree.XSLT(etree.XML(
stylesheet_xml, parser,
base_url=os.path.join('MY', 'BASE', 'FILE')))
self.assertEqual(called['count'], 0)
result = xslt(etree.XML('<a/>'))
self.assertEqual(called['count'], 1)
# now the same thing with a stylesheet base URL
called['count'] = 0
expected_url = 'http://server.com/BASE/DIR/test.xml'
xslt = etree.XSLT(etree.XML(
stylesheet_xml, parser,
base_url='http://server.com/BASE/DIR/FILE'))
self.assertEqual(called['count'], 0)
result = xslt(etree.XML('<a/>'))
self.assertEqual(called['count'], 1)
# now the same thing with a stylesheet base file:// URL
called['count'] = 0
expected_url = 'file://BASE/DIR/test.xml'
xslt = etree.XSLT(etree.XML(
stylesheet_xml, parser,
base_url='file://BASE/DIR/FILE'))
self.assertEqual(called['count'], 0)
result = xslt(etree.XML('<a/>'))
self.assertEqual(called['count'], 1)
def test_xslt_document_parse_allow(self):
access_control = etree.XSLTAccessControl(read_file=True)
xslt = etree.XSLT(etree.parse(fileInTestDir("test-document.xslt")),
access_control=access_control)
result = xslt(etree.XML('<a/>'))
root = result.getroot()
self.assertEqual(root.tag,
'test')
self.assertEqual(root[0].tag,
'{http://www.w3.org/1999/XSL/Transform}stylesheet')
def test_xslt_document_parse_deny(self):
access_control = etree.XSLTAccessControl(read_file=False)
xslt = etree.XSLT(etree.parse(fileInTestDir("test-document.xslt")),
access_control=access_control)
self.assertRaises(etree.XSLTApplyError, xslt, etree.XML('<a/>'))
def test_xslt_document_parse_deny_all(self):
access_control = etree.XSLTAccessControl.DENY_ALL
xslt = etree.XSLT(etree.parse(fileInTestDir("test-document.xslt")),
access_control=access_control)
self.assertRaises(etree.XSLTApplyError, xslt, etree.XML('<a/>'))
def test_xslt_access_control_repr(self):
access_control = etree.XSLTAccessControl.DENY_ALL
self.assertTrue(repr(access_control).startswith(type(access_control).__name__))
self.assertEqual(repr(access_control), repr(access_control))
self.assertNotEqual(repr(etree.XSLTAccessControl.DENY_ALL),
repr(etree.XSLTAccessControl.DENY_WRITE))
self.assertNotEqual(repr(etree.XSLTAccessControl.DENY_ALL),
repr(etree.XSLTAccessControl()))
def test_xslt_move_result(self):
root = etree.XML(b'''\
<transform>
<widget displayType="fieldset"/>
</transform>''')
xslt = etree.XSLT(etree.XML(b'''\
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="no"/>
<xsl:template match="/">
<html>
<xsl:apply-templates/>
</html>
</xsl:template>
<xsl:template match="widget">
<xsl:element name="{@displayType}"/>
</xsl:template>
</xsl:stylesheet>'''))
result = xslt(root[0])
root[:] = result.getroot()[:]
del root # segfaulted before
def test_xslt_pi(self):
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="%s"?>
<a>
<b>B</b>
<c>C</c>
</a>''' % fileInTestDir("test1.xslt"))
style_root = tree.getroot().getprevious().parseXSL().getroot()
self.assertEqual("{http://www.w3.org/1999/XSL/Transform}stylesheet",
style_root.tag)
def test_xslt_pi_embedded_xmlid(self):
# test xml:id dictionary lookup mechanism
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="#style"?>
<a>
<b>B</b>
<c>C</c>
<xsl:stylesheet version="1.0" xml:id="style"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="/a/b/text()" /></foo>
</xsl:template>
</xsl:stylesheet>
</a>''')
style_root = tree.getroot().getprevious().parseXSL().getroot()
self.assertEqual("{http://www.w3.org/1999/XSL/Transform}stylesheet",
style_root.tag)
st = etree.XSLT(style_root)
res = st(tree)
self.assertEqual('''\
<?xml version="1.0"?>
<foo>B</foo>
''',
str(res))
def test_xslt_pi_embedded_id(self):
# test XPath lookup mechanism
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="#style"?>
<a>
<b>B</b>
<c>C</c>
</a>''')
style = self.parse('''\
<xsl:stylesheet version="1.0" xml:id="style"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:value-of select="/a/b/text()" /></foo>
</xsl:template>
</xsl:stylesheet>
''')
tree.getroot().append(style.getroot())
style_root = tree.getroot().getprevious().parseXSL().getroot()
self.assertEqual("{http://www.w3.org/1999/XSL/Transform}stylesheet",
style_root.tag)
st = etree.XSLT(style_root)
res = st(tree)
self.assertEqual('''\
<?xml version="1.0"?>
<foo>B</foo>
''',
str(res))
def test_xslt_pi_get(self):
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="TEST"?>
<a>
<b>B</b>
<c>C</c>
</a>''')
pi = tree.getroot().getprevious()
self.assertEqual("TEST", pi.get("href"))
def test_xslt_pi_get_all(self):
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="TEST"?>
<a>
<b>B</b>
<c>C</c>
</a>''')
pi = tree.getroot().getprevious()
self.assertEqual("TEST", pi.get("href"))
self.assertEqual("text/xsl", pi.get("type"))
self.assertEqual(None, pi.get("motz"))
def test_xslt_pi_get_all_reversed(self):
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet href="TEST" type="text/xsl"?>
<a>
<b>B</b>
<c>C</c>
</a>''')
pi = tree.getroot().getprevious()
self.assertEqual("TEST", pi.get("href"))
self.assertEqual("text/xsl", pi.get("type"))
self.assertEqual(None, pi.get("motz"))
def test_xslt_pi_get_unknown(self):
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="TEST"?>
<a>
<b>B</b>
<c>C</c>
</a>''')
pi = tree.getroot().getprevious()
self.assertEqual(None, pi.get("unknownattribute"))
def test_xslt_pi_set_replace(self):
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="TEST"?>
<a>
<b>B</b>
<c>C</c>
</a>''')
pi = tree.getroot().getprevious()
self.assertEqual("TEST", pi.get("href"))
pi.set("href", "TEST123")
self.assertEqual("TEST123", pi.get("href"))
def test_xslt_pi_set_new(self):
tree = self.parse('''\
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl"?>
<a>
<b>B</b>
<c>C</c>
</a>''')
pi = tree.getroot().getprevious()
self.assertEqual(None, pi.get("href"))
pi.set("href", "TEST")
self.assertEqual("TEST", pi.get("href"))
| ETreeXSLTTestCase |
python | fsspec__filesystem_spec | fsspec/implementations/reference.py | {
"start": 713,
"end": 1566
} | class ____(RuntimeError):
def __init__(self, reference, target, *args):
super().__init__(*args)
self.reference = reference
self.target = target
def __str__(self):
return f'Reference "{self.reference}" failed to fetch target {self.target}'
def _first(d):
return next(iter(d.values()))
def _prot_in_references(path, references):
ref = references.get(path)
if isinstance(ref, (list, tuple)) and isinstance(ref[0], str):
return split_protocol(ref[0])[0] if ref[0] else ref[0]
def _protocol_groups(paths, references):
if isinstance(paths, str):
return {_prot_in_references(paths, references): [paths]}
out = {}
for path in paths:
protocol = _prot_in_references(path, references)
out.setdefault(protocol, []).append(path)
return out
| ReferenceNotReachable |
python | pytorch__pytorch | torch/_dynamo/variables/lists.py | {
"start": 501,
"end": 1672
} | class ____ handles its unique behaviors while integrating with Dynamo's
variable tracking system.
"""
import collections
import inspect
import operator
import sys
from collections.abc import Sequence
from typing import Any, Optional, TYPE_CHECKING
import torch
import torch.fx
from .. import graph_break_hints, polyfills, variables
from ..bytecode_transformation import (
create_build_tuple,
create_call_function,
create_instruction,
create_rot_n,
)
from ..exc import raise_observed_exception, unimplemented
from ..source import AttrSource, NamedTupleFieldsSource
from ..utils import (
cmp_name_to_op_mapping,
cmp_name_to_op_str_mapping,
get_fake_value,
guard_if_dyn,
iter_contains,
Lit,
namedtuple_fields,
odict_values,
raise_args_mismatch,
range_iterator,
set_example_value,
)
from .base import ValueMutationNew, VariableTracker
from .constant import ConstantVariable
from .functions import UserFunctionVariable, UserMethodVariable
from .iter import IteratorVariable
if TYPE_CHECKING:
from torch._dynamo.codegen import PyCodegen
from torch._dynamo.symbolic_convert import InstructionTranslator
| that |
python | davidhalter__jedi | jedi/api/exceptions.py | {
"start": 503,
"end": 990
} | class ____(_JediError):
"""
Refactorings can fail for various reasons. So if you work with refactorings
like :meth:`.Script.rename`, :meth:`.Script.inline`,
:meth:`.Script.extract_variable` and :meth:`.Script.extract_function`, make
sure to catch these. The descriptions in the errors are usually valuable
for end users.
A typical ``RefactoringError`` would tell the user that inlining is not
possible if no name is under the cursor.
"""
| RefactoringError |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/column_map_expectation_template.py | {
"start": 996,
"end": 2468
} | class ____(ColumnMapMetricProvider):
# </snippet>
# This is the id string that will be used to reference your metric.
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_map_expectation_template.py metric_name">
condition_metric_name = "METRIC NAME GOES HERE"
# </snippet>
# This method implements the core logic for the PandasExecutionEngine
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_map_expectation_template.py pandas">
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
raise NotImplementedError
# </snippet>
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_map_expectation_template.py ExpectColumnValuesToMatchSomeCriteria class_def">
| ColumnValuesMatchSomeCriteria |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 21975,
"end": 23380
} | class ____(Expr):
fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")
node: Expr
name: str
args: list[Expr]
kwargs: list[Pair]
dyn_args: Expr | None
dyn_kwargs: Expr | None
abstract = True
_is_filter = True
def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any:
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if self._is_filter:
env_map = eval_ctx.environment.filters
else:
env_map = eval_ctx.environment.tests
func = env_map.get(self.name)
pass_arg = _PassArg.from_obj(func) # type: ignore
if func is None or pass_arg is _PassArg.context:
raise Impossible()
if eval_ctx.environment.is_async and (
getattr(func, "jinja_async_variant", False) is True
or inspect.iscoroutinefunction(func)
):
raise Impossible()
args, kwargs = args_as_const(self, eval_ctx)
args.insert(0, self.node.as_const(eval_ctx))
if pass_arg is _PassArg.eval_context:
args.insert(0, eval_ctx)
elif pass_arg is _PassArg.environment:
args.insert(0, eval_ctx.environment)
try:
return func(*args, **kwargs)
except Exception as e:
raise Impossible() from e
| _FilterTestCommon |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 26622,
"end": 27133
} | class ____(models.Model):
"""
Non-historic table with one to one relationship to historic table.
In this case it should simply behave like ForeignKey because
the origin model (this one) cannot be historic, so foreign key
lookups are always "current".
"""
name = models.CharField(max_length=15, unique=True)
organization = HistoricOneToOneField(
TestOrganizationWithHistory, on_delete=CASCADE, related_name="participant"
)
| TestParticipantToHistoricOrganizationOneToOne |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/generic.py | {
"start": 580,
"end": 879
} | class ____(ReadWriteScopedResourceMixin, ProtectedResourceView):
"""
Generic view protecting resources with OAuth2 authentication and read/write scopes.
GET, HEAD, OPTIONS http methods require "read" scope. Otherwise "write" scope is required.
"""
pass
| ReadWriteScopedResourceView |
python | getsentry__sentry | src/sentry/sentry_metrics/configuration.py | {
"start": 1221,
"end": 1319
} | class ____(Enum):
POSTGRES = "postgres"
MOCK = "mock"
@dataclass(frozen=True)
| IndexerStorage |
python | pandas-dev__pandas | pandas/core/computation/pytables.py | {
"start": 1395,
"end": 2456
} | class ____(ops.Term):
env: PyTablesScope
def __new__(cls, name, env, side=None, encoding=None):
if isinstance(name, str):
klass = cls
else:
klass = Constant
return object.__new__(klass)
def __init__(self, name, env: PyTablesScope, side=None, encoding=None) -> None:
super().__init__(name, env, side=side, encoding=encoding)
def _resolve_name(self):
# must be a queryables
if self.side == "left":
# Note: The behavior of __new__ ensures that self.name is a str here
if self.name not in self.env.queryables:
raise NameError(f"name {self.name!r} is not defined")
return self.name
# resolve the rhs (and allow it to be None)
try:
return self.env.resolve(self.name, is_local=False)
except UndefinedVariableError:
return self.name
# read-only property overwriting read/write property
@property # type: ignore[misc]
def value(self):
return self._value
| Term |
python | dask__dask | dask/tests/test_expr.py | {
"start": 2441,
"end": 2511
} | class ____(MySingletonWithCustomInit): ...
| MySingletonInheritsCustomInit |
python | walkccc__LeetCode | solutions/1456. Maximum Number of Vowels in a Substring of Given Length/1456.py | {
"start": 0,
"end": 272
} | class ____:
def maxVowels(self, s: str, k: int) -> int:
ans = 0
mx = 0
VOWELS = 'aeiou'
for i, c in enumerate(s):
if c in VOWELS:
mx += 1
if i >= k and s[i - k] in VOWELS:
mx -= 1
ans = max(ans, mx)
return ans
| Solution |
python | jmcnamara__XlsxWriter | examples/django_simple.py | {
"start": 517,
"end": 1820
} | class ____(View):
def get(self, request):
# Create an in-memory output file for the new workbook.
output = io.BytesIO()
# Even though the final file will be in memory the module uses temp
# files during assembly for efficiency. To avoid this on servers that
# don't allow temp files, for example the Google APP Engine, set the
# 'in_memory' Workbook() constructor option as shown in the docs.
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
# Get some data to write to the spreadsheet.
data = get_simple_table_data()
# Write some test data.
for row_num, columns in enumerate(data):
for col_num, cell_data in enumerate(columns):
worksheet.write(row_num, col_num, cell_data)
# Close the workbook before sending the data.
workbook.close()
# Rewind the buffer.
output.seek(0)
# Set up the Http response.
filename = "django_simple.xlsx"
response = HttpResponse(
output,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
response["Content-Disposition"] = f"attachment; filename={filename}"
return response
| MyView |
python | pytorch__pytorch | torch/fx/experimental/unification/match.py | {
"start": 1219,
"end": 3414
} | class ____(Dispatcher):
"""A dispatcher that calls functions with variable names
>>> # xdoctest: +SKIP
>>> d = VarDispatcher("d")
>>> x = var("x")
>>> @d.register("inc", x)
... def f(x):
... return x + 1
>>> @d.register("double", x)
... def f(x):
... return x * 2
>>> d("inc", 10)
11
>>> d("double", 10)
20
"""
def __call__(self, *args, **kwargs):
func, s = self.resolve(args)
d = {k.token: v for k, v in s.items()}
return func(**d)
global_namespace = {} # type: ignore[var-annotated]
def match(*signature, **kwargs):
namespace = kwargs.get("namespace", global_namespace)
dispatcher = kwargs.get("Dispatcher", Dispatcher)
def _(func):
name = func.__name__
if name not in namespace:
namespace[name] = dispatcher(name)
d = namespace[name]
d.add(signature, func)
return d
return _
def supercedes(a, b):
"""``a`` is a more specific match than ``b``"""
if isvar(b) and not isvar(a):
return True
s = unify(a, b)
if s is False:
return False
s = {k: v for k, v in s.items() if not isvar(k) or not isvar(v)}
if reify(a, s) == a:
return True
if reify(b, s) == b:
return False
# Taken from multipledispatch
def edge(a, b, tie_breaker=hash):
"""A should be checked before B
Tie broken by tie_breaker, defaults to ``hash``
"""
if supercedes(a, b):
if supercedes(b, a):
return tie_breaker(a) > tie_breaker(b)
else:
return True
return False
# Taken from multipledispatch
def ordering(signatures):
"""A sane ordering of signatures to check, first to last
Topological sort of edges as given by ``edge`` and ``supercedes``
"""
signatures = list(map(tuple, signatures))
edges = [(a, b) for a in signatures for b in signatures if edge(a, b)]
edges = groupby(first, edges)
for s in signatures:
if s not in edges:
edges[s] = []
edges = {k: [b for a, b in v] for k, v in edges.items()} # type: ignore[attr-defined, assignment]
return _toposort(edges)
| VarDispatcher |
python | huggingface__transformers | src/transformers/models/idefics/perceiver.py | {
"start": 8626,
"end": 9426
} | class ____(nn.Module):
def __init__(self, intermediate_size, config: IdeficsConfig):
"""Simple MLP block with intermediate_size and embedding size"""
super().__init__()
self.embed_dim = config.vision_config.embed_dim
self.ln = nn.LayerNorm(self.embed_dim)
self.fc = nn.Linear(self.embed_dim, intermediate_size, bias=False)
self.act = nn.ReLU()
self.c_proj = nn.Linear(intermediate_size, self.embed_dim, bias=False)
def forward(self, hidden_states: Optional[tuple[torch.FloatTensor]]) -> torch.FloatTensor:
hidden_states = self.ln(hidden_states)
hidden_states = self.fc(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.c_proj(hidden_states)
return hidden_states
| IdeficsMLP |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 41870,
"end": 41970
} | class ____:
def __init__(self, value=None):
self.value = value
__hash__ = None
| NoHash |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 90837,
"end": 90912
} | class ____(BinOpFrame):
operation = M.lt
_operator_repr = "<"
| LTFrame |
python | getsentry__sentry | src/sentry/api/endpoints/organization_stats_v2.py | {
"start": 6474,
"end": 6635
} | class ____(TypedDict): # this response is pretty dynamic, leaving generic
by: dict[str, Any]
totals: dict[str, Any]
series: dict[str, Any]
| _StatsGroup |
python | django__django | django/contrib/gis/db/models/aggregates.py | {
"start": 2920,
"end": 3015
} | class ____(GeoAggregate):
name = "MakeLine"
output_field_class = LineStringField
| MakeLine |
python | huggingface__transformers | src/transformers/models/detr/modeling_detr.py | {
"start": 9337,
"end": 11646
} | class ____(nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters are fixed.
Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
torchvision.models.resnet[18,34,50,101] produce nans.
"""
def __init__(self, n):
super().__init__()
self.register_buffer("weight", torch.ones(n))
self.register_buffer("bias", torch.zeros(n))
self.register_buffer("running_mean", torch.zeros(n))
self.register_buffer("running_var", torch.ones(n))
def _load_from_state_dict(
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
):
num_batches_tracked_key = prefix + "num_batches_tracked"
if num_batches_tracked_key in state_dict:
del state_dict[num_batches_tracked_key]
super()._load_from_state_dict(
state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
)
def forward(self, x):
# move reshapes to the beginning
# to make it user-friendly
weight = self.weight.reshape(1, -1, 1, 1)
bias = self.bias.reshape(1, -1, 1, 1)
running_var = self.running_var.reshape(1, -1, 1, 1)
running_mean = self.running_mean.reshape(1, -1, 1, 1)
epsilon = 1e-5
scale = weight * (running_var + epsilon).rsqrt()
bias = bias - running_mean * scale
return x * scale + bias
def replace_batch_norm(model):
r"""
Recursively replace all `torch.nn.BatchNorm2d` with `DetrFrozenBatchNorm2d`.
Args:
model (torch.nn.Module):
input model
"""
for name, module in model.named_children():
if isinstance(module, nn.BatchNorm2d):
new_module = DetrFrozenBatchNorm2d(module.num_features)
if module.weight.device != torch.device("meta"):
new_module.weight.copy_(module.weight)
new_module.bias.copy_(module.bias)
new_module.running_mean.copy_(module.running_mean)
new_module.running_var.copy_(module.running_var)
model._modules[name] = new_module
if len(list(module.children())) > 0:
replace_batch_norm(module)
| DetrFrozenBatchNorm2d |
python | realpython__materials | tic-tac-toe-ai-python/source_code_bonus/tic-tac-toe/library/src/tic_tac_toe/logic/models.py | {
"start": 1149,
"end": 3679
} | class ____:
grid: Grid
starting_mark: Mark = Mark("X")
def __post_init__(self) -> None:
validate_game_state(self)
@cached_property
def current_mark(self) -> Mark:
if self.grid.x_count == self.grid.o_count:
return self.starting_mark
else:
return self.starting_mark.other
@cached_property
def game_not_started(self) -> bool:
return self.grid.empty_count == 9
@cached_property
def game_over(self) -> bool:
return self.winner is not None or self.tie
@cached_property
def tie(self) -> bool:
return self.winner is None and self.grid.empty_count == 0
@cached_property
def winner(self) -> Mark | None:
for pattern in WINNING_PATTERNS:
for mark in Mark:
if re.match(pattern.replace("?", mark), self.grid.cells):
return mark
return None
@cached_property
def winning_cells(self) -> list[int]:
for pattern in WINNING_PATTERNS:
for mark in Mark:
if re.match(pattern.replace("?", mark), self.grid.cells):
return [
match.start() for match in re.finditer(r"\?", pattern)
]
return []
@cached_property
def possible_moves(self) -> list[Move]:
moves = []
if not self.game_over:
for match in re.finditer(r"\s", self.grid.cells):
moves.append(self.make_move_to(match.start()))
return moves
def make_random_move(self) -> Move | None:
try:
return random.choice(self.possible_moves)
except IndexError:
return None
def make_move_to(self, index: int) -> Move:
if self.grid.cells[index] != " ":
raise InvalidMove("Cell is not empty")
return Move(
mark=self.current_mark,
cell_index=index,
before_state=self,
after_state=GameState(
Grid(
self.grid.cells[:index]
+ self.current_mark
+ self.grid.cells[index + 1 :]
),
self.starting_mark,
),
)
def evaluate_score(self, mark: Mark) -> int:
if self.game_over:
if self.tie:
return 0
if self.winner is mark:
return 1
else:
return -1
raise UnknownGameScore("Game is not over yet")
| GameState |
python | pappasam__jedi-language-server | jedi_language_server/server.py | {
"start": 7545,
"end": 37830
} | class ____(LanguageServer):
"""Jedi language server.
:attr initialization_options: initialized in lsp_initialize from the
protocol_cls.
:attr project: a Jedi project. This value is created in
`JediLanguageServerProtocol.lsp_initialize`.
"""
initialization_options: InitializationOptions
project: Optional[Project]
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
SERVER = JediLanguageServer(
name="jedi-language-server",
version=__version__,
protocol_cls=JediLanguageServerProtocol,
# Advertise support for Python notebook cells.
notebook_document_sync=NotebookDocumentSyncOptions(
notebook_selector=[
NotebookDocumentFilterWithCells(
cells=[NotebookCellLanguage(language="python")]
)
]
),
)
# Server capabilities
@SERVER.feature(COMPLETION_ITEM_RESOLVE)
def completion_item_resolve(
server: JediLanguageServer, params: CompletionItem
) -> CompletionItem:
"""Resolves documentation and detail of given completion item."""
markup_kind = _choose_markup(server)
return jedi_utils.lsp_completion_item_resolve(
params, markup_kind=markup_kind
)
@SERVER.feature(
TEXT_DOCUMENT_COMPLETION,
CompletionOptions(
trigger_characters=[".", "'", '"'], resolve_provider=True
),
)
@notebook_utils.supports_notebooks
def completion(
server: JediLanguageServer, params: CompletionParams
) -> Optional[CompletionList]:
"""Returns completion items."""
snippet_disable = server.initialization_options.completion.disable_snippets
resolve_eagerly = server.initialization_options.completion.resolve_eagerly
ignore_patterns = server.initialization_options.completion.ignore_patterns
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
completions_jedi_raw = jedi_script.complete(*jedi_lines)
if not ignore_patterns:
# A performance optimization. ignore_patterns should usually be empty;
# this special case avoid repeated filter checks for the usual case.
completions_jedi = (comp for comp in completions_jedi_raw)
else:
completions_jedi = (
comp
for comp in completions_jedi_raw
if not any(i.match(comp.name) for i in ignore_patterns)
)
snippet_support = get_capability(
server.client_capabilities,
"text_document.completion.completion_item.snippet_support",
False,
)
markup_kind = _choose_markup(server)
is_import_context = jedi_utils.is_import(
script_=jedi_script,
line=jedi_lines[0],
column=jedi_lines[1],
)
enable_snippets = (
snippet_support and not snippet_disable and not is_import_context
)
char_before_cursor = pygls_utils.char_before_cursor(
document=server.workspace.get_text_document(params.text_document.uri),
position=params.position,
)
char_after_cursor = pygls_utils.char_after_cursor(
document=server.workspace.get_text_document(params.text_document.uri),
position=params.position,
)
jedi_utils.clear_completions_cache()
# number of characters in the string representation of the total number of
# completions returned by jedi.
total_completion_chars = len(str(len(completions_jedi_raw)))
completion_items = [
jedi_utils.lsp_completion_item(
completion=completion,
char_before_cursor=char_before_cursor,
char_after_cursor=char_after_cursor,
enable_snippets=enable_snippets,
resolve_eagerly=resolve_eagerly,
markup_kind=markup_kind,
sort_append_text=str(count).zfill(total_completion_chars),
)
for count, completion in enumerate(completions_jedi)
if completion.type != "path"
]
return (
CompletionList(is_incomplete=False, items=completion_items)
if completion_items
else None
)
@SERVER.feature(
TEXT_DOCUMENT_SIGNATURE_HELP,
SignatureHelpOptions(trigger_characters=["(", ","]),
)
@notebook_utils.supports_notebooks
def signature_help(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[SignatureHelp]:
"""Returns signature help.
Note: for docstring, we currently choose plaintext because coc doesn't
handle markdown well in the signature. Will update if this changes in the
future.
"""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
signatures_jedi = jedi_script.get_signatures(*jedi_lines)
markup_kind = _choose_markup(server)
signatures = [
SignatureInformation(
label=jedi_utils.signature_string(signature),
documentation=MarkupContent(
kind=markup_kind,
value=jedi_utils.convert_docstring(
signature.docstring(raw=True),
markup_kind,
),
),
parameters=[
ParameterInformation(label=info.to_string())
for info in signature.params
],
active_parameter=signature.index,
)
for signature in signatures_jedi
]
return (
SignatureHelp(
signatures=signatures,
active_signature=0,
active_parameter=(
signatures_jedi[0].index if signatures_jedi else 0
),
)
if signatures
else None
)
@SERVER.feature(TEXT_DOCUMENT_DECLARATION)
@notebook_utils.supports_notebooks
def declaration(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[Location]]:
"""Support Goto Declaration."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.goto(*jedi_lines)
definitions = [
definition
for definition in (jedi_utils.lsp_location(name) for name in names)
if definition is not None
]
return definitions if definitions else None
@SERVER.feature(TEXT_DOCUMENT_DEFINITION)
@notebook_utils.supports_notebooks
def definition(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[Location]]:
"""Support Goto Definition."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.goto(
*jedi_lines,
follow_imports=True,
follow_builtin_imports=True,
)
definitions = [
definition
for definition in (jedi_utils.lsp_location(name) for name in names)
if definition is not None
]
return definitions if definitions else None
@SERVER.feature(TEXT_DOCUMENT_TYPE_DEFINITION)
@notebook_utils.supports_notebooks
def type_definition(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[Location]]:
"""Support Goto Type Definition."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.infer(*jedi_lines)
definitions = [
definition
for definition in (jedi_utils.lsp_location(name) for name in names)
if definition is not None
]
return definitions if definitions else None
@SERVER.feature(TEXT_DOCUMENT_DOCUMENT_HIGHLIGHT)
def highlight(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[DocumentHighlight]]:
"""Support document highlight request.
This function is called frequently, so we minimize the number of expensive
calls. These calls are:
1. Getting assignment of current symbol (script.goto)
2. Getting all names in the current script (script.get_names)
Finally, we only return names if there are more than 1. Otherwise, we don't
want to highlight anything.
"""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.get_references(*jedi_lines, scope="file")
lsp_ranges = [jedi_utils.lsp_range(name) for name in names]
highlight_names = [
DocumentHighlight(range=lsp_range)
for lsp_range in lsp_ranges
if lsp_range
]
return highlight_names if highlight_names else None
# Registered with HOVER dynamically
@notebook_utils.supports_notebooks
def hover(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[Hover]:
"""Support Hover."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
markup_kind = _choose_markup(server)
hover_text = jedi_utils.hover_text(
jedi_script.help(*jedi_lines),
markup_kind,
server.initialization_options,
)
if not hover_text:
return None
contents = MarkupContent(kind=markup_kind, value=hover_text)
_range = pygls_utils.current_word_range(document, params.position)
return Hover(contents=contents, range=_range)
@SERVER.feature(TEXT_DOCUMENT_REFERENCES)
@notebook_utils.supports_notebooks
def references(
server: JediLanguageServer, params: TextDocumentPositionParams
) -> Optional[List[Location]]:
"""Obtain all references to text."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
names = jedi_script.get_references(*jedi_lines)
locations = [
location
for location in (jedi_utils.lsp_location(name) for name in names)
if location is not None
]
return locations if locations else None
@SERVER.feature(TEXT_DOCUMENT_DOCUMENT_SYMBOL)
def document_symbol(
server: JediLanguageServer, params: DocumentSymbolParams
) -> Optional[Union[List[DocumentSymbol], List[SymbolInformation]]]:
"""Document Python document symbols, hierarchically if possible.
In Jedi, valid values for `name.type` are:
- `module`
- `class`
- `instance`
- `function`
- `param`
- `path`
- `keyword`
- `statement`
We do some cleaning here. For hierarchical symbols, names from scopes that
aren't directly accessible with dot notation are removed from display. For
non-hierarchical symbols, we simply remove `param` symbols. Others are
included for completeness.
"""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
names = jedi_script.get_names(all_scopes=True, definitions=True)
if get_capability(
server.client_capabilities,
"text_document.document_symbol.hierarchical_document_symbol_support",
False,
):
document_symbols = jedi_utils.lsp_document_symbols(names)
return document_symbols if document_symbols else None
symbol_information = [
symbol_info
for symbol_info in (
jedi_utils.lsp_symbol_information(name, document.uri)
for name in names
if name.type != "param"
)
if symbol_info is not None
]
return symbol_information if symbol_information else None
def _ignore_folder(path_check: str, jedi_ignore_folders: List[str]) -> bool:
"""Determines whether there's an ignore folder in the path.
Intended to be used with the `workspace_symbol` function
"""
for ignore_folder in jedi_ignore_folders:
if f"/{ignore_folder}/" in path_check:
return True
return False
@SERVER.feature(WORKSPACE_SYMBOL)
def workspace_symbol(
server: JediLanguageServer, params: WorkspaceSymbolParams
) -> Optional[List[SymbolInformation]]:
"""Document Python workspace symbols.
Returns up to maxSymbols, or all symbols if maxSymbols is <= 0, ignoring
the following symbols:
1. Those that don't have a module_path associated with them (built-ins)
2. Those that are not rooted in the current workspace.
3. Those whose folders contain a directory that is ignored (.venv, etc)
"""
if not server.project:
return None
names = server.project.complete_search(params.query)
workspace_root = server.workspace.root_path
ignore_folders = (
server.initialization_options.workspace.symbols.ignore_folders
)
unignored_names = (
name
for name in names
if name.module_path is not None
and str(name.module_path).startswith(workspace_root)
and not _ignore_folder(str(name.module_path), ignore_folders)
)
_symbols = (
symbol
for symbol in (
jedi_utils.lsp_symbol_information(name) for name in unignored_names
)
if symbol is not None
)
max_symbols = server.initialization_options.workspace.symbols.max_symbols
symbols = (
list(itertools.islice(_symbols, max_symbols))
if max_symbols > 0
else list(_symbols)
)
return symbols if symbols else None
@SERVER.feature(TEXT_DOCUMENT_RENAME)
@notebook_utils.supports_notebooks
def rename(
server: JediLanguageServer, params: RenameParams
) -> Optional[WorkspaceEdit]:
"""Rename a symbol across a workspace."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
jedi_lines = jedi_utils.line_column(params.position)
try:
refactoring = jedi_script.rename(*jedi_lines, new_name=params.new_name)
except RefactoringError:
return None
changes = text_edit_utils.lsp_document_changes(
server.workspace, refactoring
)
return WorkspaceEdit(document_changes=changes) if changes else None
@SERVER.feature(
TEXT_DOCUMENT_CODE_ACTION,
CodeActionOptions(
code_action_kinds=[
CodeActionKind.RefactorInline,
CodeActionKind.RefactorExtract,
],
),
)
@notebook_utils.supports_notebooks
def code_action(
server: JediLanguageServer, params: CodeActionParams
) -> Optional[List[CodeAction]]:
"""Get code actions.
Currently supports:
1. Inline variable
2. Extract variable
3. Extract function
"""
# Code actions are not yet supported for notebooks.
notebook = server.workspace.get_notebook_document(
cell_uri=params.text_document.uri
)
if notebook is not None:
return None
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
code_actions = []
jedi_lines = jedi_utils.line_column(params.range.start)
jedi_lines_extract = jedi_utils.line_column_range(params.range)
try:
if params.range.start.line != params.range.end.line:
# refactor this at some point; control flow with exception == bad
raise RefactoringError("inline only viable for single-line range")
inline_refactoring = jedi_script.inline(*jedi_lines)
except (RefactoringError, AttributeError, IndexError):
inline_changes = []
else:
inline_changes = text_edit_utils.lsp_document_changes(
server.workspace, inline_refactoring
)
if inline_changes:
code_actions.append(
CodeAction(
title="Inline variable",
kind=CodeActionKind.RefactorInline,
edit=WorkspaceEdit(
document_changes=inline_changes,
),
)
)
extract_var = (
server.initialization_options.code_action.name_extract_variable
)
try:
extract_variable_refactoring = jedi_script.extract_variable(
new_name=extract_var, **jedi_lines_extract
)
except (RefactoringError, AttributeError, IndexError):
extract_variable_changes = []
else:
extract_variable_changes = text_edit_utils.lsp_document_changes(
server.workspace, extract_variable_refactoring
)
if extract_variable_changes:
code_actions.append(
CodeAction(
title=f"Extract expression into variable '{extract_var}'",
kind=CodeActionKind.RefactorExtract,
edit=WorkspaceEdit(
document_changes=extract_variable_changes,
),
)
)
extract_func = (
server.initialization_options.code_action.name_extract_function
)
try:
extract_function_refactoring = jedi_script.extract_function(
new_name=extract_func, **jedi_lines_extract
)
except (RefactoringError, AttributeError, IndexError):
extract_function_changes = []
else:
extract_function_changes = text_edit_utils.lsp_document_changes(
server.workspace, extract_function_refactoring
)
if extract_function_changes:
code_actions.append(
CodeAction(
title=f"Extract expression into function '{extract_func}'",
kind=CodeActionKind.RefactorExtract,
edit=WorkspaceEdit(
document_changes=extract_function_changes,
),
)
)
return code_actions if code_actions else None
@SERVER.feature(WORKSPACE_DID_CHANGE_CONFIGURATION)
def did_change_configuration(
server: JediLanguageServer,
params: DidChangeConfigurationParams,
) -> None:
"""Implement event for workspace/didChangeConfiguration.
Currently does nothing, but necessary for pygls. See::
<https://github.com/pappasam/jedi-language-server/issues/58>
"""
EncodedSemanticToken = NamedTuple(
"EncodedSemanticToken",
[
("line", int),
("start", int),
("length", int),
("tokenType", int),
("tokenModifiers", int),
],
)
"""
Semantic token encoded into integers. Applicable for both absolute and relative positions.
See the LSP spec for details:
<https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_semanticTokens>
"""
def _raw_semantic_token(
server: JediLanguageServer, n: Name
) -> Union[EncodedSemanticToken, None]:
"""Find an appropriate semantic token for the name.
This works by looking up the definition (using jedi ``goto``) of the name and
matching the definition's type to one of the availabile semantic tokens. Further
improvements are possible by inspecting context, e.g. semantic token modifiers such
as ``abstract`` or ``async`` or even different tokens, e.g. ``property`` or
``method``. Dunder methods may warrant special treatment/modifiers as well.
The return is a "raw" semantic token rather than a "diff." This is in the form of a
length 5 array of integers where the elements are the line number, starting
character, length, token index, and modifiers (as an integer whose binary
representation has bits set at the indices of all applicable modifiers).
"""
definitions: list[Name] = n.goto(
follow_imports=True,
follow_builtin_imports=True,
only_stubs=False,
prefer_stubs=False,
)
if not definitions:
server.window_log_message(
LogMessageParams(
type=MessageType.Debug,
message=f"no definitions found for name \"{n.description}\" of type '{n.type}' ({n.line}:{n.column})",
)
)
return None
if len(definitions) > 1:
def_lines = "\n".join(
map(lambda n: str(n), definitions)
) # f-string expression part cannot include a backslash
msg = (
f"multiple definitions found for name \"{n.description}\" of type '{n.type}' ({n.line}:{n.column}):\n"
f" {def_lines}"
)
server.window_log_message(
LogMessageParams(type=MessageType.Debug, message=msg)
)
definition, *_ = definitions
definition_type = SEMANTIC_TO_TOKEN_ID.get(definition.type, None)
if definition_type is None:
server.window_log_message(
LogMessageParams(
type=MessageType.Debug,
message=f"no matching semantic token for \"{n.description}\" of type '{n.type}' ({n.line}:{n.column})",
)
)
return None
return EncodedSemanticToken(
n.line - 1, n.column, len(n.name), definition_type, 0
)
@SERVER.thread()
def semantic_tokens_full(
server: JediLanguageServer, params: SemanticTokensParams
) -> SemanticTokens:
"""Thin wrap around _semantic_tokens_range()."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
server.window_log_message(
LogMessageParams(
type=MessageType.Log,
message=f"semantic_tokens_full {params.text_document.uri} ",
)
)
return _semantic_tokens_range(
server,
jedi_script,
Range(Position(0, 0), Position(INTEGER_MAX_VALUE, INTEGER_MAX_VALUE)),
)
@SERVER.thread()
def semantic_tokens_range(
server: JediLanguageServer, params: SemanticTokensRangeParams
) -> SemanticTokens:
"""Thin wrap around _semantic_tokens_range()."""
document = server.workspace.get_text_document(params.text_document.uri)
jedi_script = jedi_utils.script(server.project, document)
server.window_log_message(
LogMessageParams(
type=MessageType.Log,
message=f"semantic_tokens_range {params.text_document.uri} {params.range}",
)
)
return _semantic_tokens_range(server, jedi_script, params.range)
def _semantic_tokens_range(
server: JediLanguageServer, jedi_script: Script, doc_range: Range
) -> SemanticTokens:
"""General purpose function to do full / range semantic tokens."""
line, column = doc_range.start.line, doc_range.start.character
names = jedi_script.get_names(
all_scopes=True, definitions=True, references=True
)
data: list[int] = []
for n in names:
if (
not doc_range.start
< Position(n.line - 1, n.column)
< doc_range.end
):
continue
token = _raw_semantic_token(server, n)
if token is None:
continue
token_line, token_column = token.line, token.start
delta_column = (
token_column - column if token_line == line else token_column
)
delta_line = token_line - line
line = token_line
column = token_column
data.extend(
[
delta_line,
delta_column,
token.length,
token.tokenType,
token.tokenModifiers,
]
)
return SemanticTokens(data=data)
# Static capability or initializeOptions functions that rely on a specific
# client capability or user configuration. These are associated with
# JediLanguageServer within JediLanguageServerProtocol.lsp_initialize
@jedi_utils.debounce(1, keyed_by="uri")
def _publish_diagnostics(
server: JediLanguageServer, uri: str, filename: Optional[str] = None
) -> None:
"""Helper function to publish diagnostics for a file."""
# The debounce decorator delays the execution by 1 second
# canceling notifications that happen in that interval.
# Since this function is executed after a delay, we need to check
# whether the document still exists
if uri not in server.workspace.text_documents:
return
if filename is None:
filename = uri
doc = server.workspace.get_text_document(uri)
diagnostic = jedi_utils.lsp_python_diagnostic(filename, doc.source)
diagnostics = [diagnostic] if diagnostic else []
server.text_document_publish_diagnostics(
PublishDiagnosticsParams(
uri=uri, diagnostics=diagnostics, version=doc.version
)
)
# TEXT_DOCUMENT_DID_SAVE
def did_save_diagnostics(
server: JediLanguageServer, params: DidSaveTextDocumentParams
) -> None:
"""Actions run on textDocument/didSave: diagnostics."""
_publish_diagnostics(server, params.text_document.uri)
def did_save_default(
server: JediLanguageServer,
params: DidSaveTextDocumentParams,
) -> None:
"""Actions run on textDocument/didSave: default."""
# TEXT_DOCUMENT_DID_CHANGE
def did_change_diagnostics(
server: JediLanguageServer, params: DidChangeTextDocumentParams
) -> None:
"""Actions run on textDocument/didChange: diagnostics."""
_publish_diagnostics(server, params.text_document.uri)
def did_change_default(
server: JediLanguageServer,
params: DidChangeTextDocumentParams,
) -> None:
"""Actions run on textDocument/didChange: default."""
# TEXT_DOCUMENT_DID_OPEN
def did_open_diagnostics(
server: JediLanguageServer, params: DidOpenTextDocumentParams
) -> None:
"""Actions run on textDocument/didOpen: diagnostics."""
_publish_diagnostics(server, params.text_document.uri)
def did_open_default(
server: JediLanguageServer,
params: DidOpenTextDocumentParams,
) -> None:
"""Actions run on textDocument/didOpen: default."""
# TEXT_DOCUMENT_DID_CLOSE
def did_close_diagnostics(
server: JediLanguageServer, params: DidCloseTextDocumentParams
) -> None:
"""Actions run on textDocument/didClose: diagnostics."""
_clear_diagnostics(server, params.text_document.uri)
def did_close_default(
server: JediLanguageServer,
params: DidCloseTextDocumentParams,
) -> None:
"""Actions run on textDocument/didClose: default."""
# NOTEBOOK_DOCUMENT_DID_SAVE
def did_save_notebook_diagnostics(
server: JediLanguageServer,
params: DidSaveNotebookDocumentParams,
) -> None:
"""Actions run on notebookDocument/didSave: diagnostics."""
notebook_document = server.workspace.get_notebook_document(
notebook_uri=params.notebook_document.uri
)
if notebook_document:
for cell in notebook_document.cells:
text_document = server.workspace.text_documents[cell.document]
_publish_cell_diagnostics(server, text_document.uri)
def did_save_notebook_default(
server: JediLanguageServer,
params: DidSaveNotebookDocumentParams,
) -> None:
"""Actions run on notebookDocument/didSave: default."""
# NOTEBOOK_DOCUMENT_DID_CHANGE
def did_change_notebook_diagnostics(
server: JediLanguageServer,
params: DidChangeNotebookDocumentParams,
) -> None:
"""Actions run on notebookDocument/didChange: diagnostics."""
cells = params.change.cells
if cells:
structure = cells.structure
if structure:
did_open = structure.did_open
if did_open:
for text_document_item in did_open:
_publish_cell_diagnostics(
server,
text_document_item.uri,
)
did_close = structure.did_close
if did_close:
for text_document in did_close:
_clear_diagnostics(server, text_document.uri)
text_content = cells.text_content
if text_content:
for change in text_content:
_publish_cell_diagnostics(server, change.document.uri)
def did_change_notebook_default(
server: JediLanguageServer,
params: DidChangeNotebookDocumentParams,
) -> None:
"""Actions run on notebookDocument/didChange: default."""
# NOTEBOOK_DOCUMENT_DID_OPEN
def did_open_notebook_diagnostics(
server: JediLanguageServer,
params: DidOpenNotebookDocumentParams,
) -> None:
"""Actions run on notebookDocument/didOpen: diagnostics."""
for text_document in params.cell_text_documents:
_publish_cell_diagnostics(server, text_document.uri)
def did_open_notebook_default(
server: JediLanguageServer,
params: DidOpenNotebookDocumentParams,
) -> None:
"""Actions run on notebookDocument/didOpen: default."""
# NOTEBOOK_DOCUMENT_DID_CLOSE
def did_close_notebook_diagnostics(
server: JediLanguageServer,
params: DidCloseNotebookDocumentParams,
) -> None:
"""Actions run on notebookDocument/didClose: diagnostics."""
for text_document in params.cell_text_documents:
_clear_diagnostics(server, text_document.uri)
def did_close_notebook_default(
server: JediLanguageServer,
params: DidCloseNotebookDocumentParams,
) -> None:
"""Actions run on notebookDocument/didClose: default."""
def _clear_diagnostics(server: JediLanguageServer, uri: str) -> None:
"""Helper function to clear diagnostics for a file."""
server.text_document_publish_diagnostics(
PublishDiagnosticsParams(uri=uri, diagnostics=[])
)
def _publish_cell_diagnostics(server: JediLanguageServer, uri: str) -> None:
filename = notebook_utils.cell_filename(server.workspace, uri)
return _publish_diagnostics(server, uri, filename)
def _choose_markup(server: JediLanguageServer) -> MarkupKind:
"""Returns the preferred or first of supported markup kinds."""
markup_preferred = server.initialization_options.markup_kind_preferred
markup_supported = get_capability(
server.client_capabilities,
"text_document.completion.completion_item.documentation_format",
[MarkupKind.PlainText],
)
return MarkupKind(
markup_preferred
if markup_preferred in markup_supported
else markup_supported[0]
)
| JediLanguageServer |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_W.py | {
"start": 8742,
"end": 9739
} | class ____(Benchmark):
r"""
Wolfe objective function.
This class defines the Wolfe [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Wolfe}}(x) = \frac{4}{3}(x_1^2 + x_2^2 - x_1x_2)^{0.75} + x_3
with :math:`x_i \in [0, 2]` for :math:`i = 1, 2, 3`.
*Global optimum*: :math:`f(x) = 0` for :math:`x = [0, 0, 0]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
"""
def __init__(self, dimensions=3):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([0.0] * self.N, [2.0] * self.N))
self.global_optimum = [[0.0 for _ in range(self.N)]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
return 4 / 3 * (x[0] ** 2 + x[1] ** 2 - x[0] * x[1]) ** 0.75 + x[2]
| Wolfe |
python | tornadoweb__tornado | tornado/websocket.py | {
"start": 3105,
"end": 3580
} | class ____:
def __init__(
self,
ping_interval: Optional[float] = None,
ping_timeout: Optional[float] = None,
max_message_size: int = _default_max_message_size,
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
self.ping_interval = ping_interval
self.ping_timeout = ping_timeout
self.max_message_size = max_message_size
self.compression_options = compression_options
| _WebSocketParams |
python | numba__numba | numba/tests/test_locals.py | {
"start": 88,
"end": 335
} | class ____(unittest.TestCase):
def test_seed_types(self):
cfunc = njit((), locals={'x': float32})(foo)
self.assertEqual(cfunc.nopython_signatures[0].return_type, float32)
if __name__ == '__main__':
unittest.main()
| TestLocals |
python | pytest-dev__pytest | src/_pytest/subtests.py | {
"start": 10312,
"end": 13235
} | class ____:
handler: LogCaptureHandler
def pytest_report_to_serializable(report: TestReport) -> dict[str, Any] | None:
if isinstance(report, SubtestReport):
return report._to_json()
return None
def pytest_report_from_serializable(data: dict[str, Any]) -> SubtestReport | None:
if data.get("_report_type") == "SubTestReport":
return SubtestReport._from_json(data)
return None
# Dict of nodeid -> number of failed subtests.
# Used to fail top-level tests that passed but contain failed subtests.
failed_subtests_key = StashKey[defaultdict[str, int]]()
def pytest_configure(config: Config) -> None:
config.stash[failed_subtests_key] = defaultdict(int)
@hookimpl(tryfirst=True)
def pytest_report_teststatus(
report: TestReport,
config: Config,
) -> tuple[str, str, str | Mapping[str, bool]] | None:
if report.when != "call":
return None
quiet = config.get_verbosity(Config.VERBOSITY_SUBTESTS) == 0
if isinstance(report, SubtestReport):
outcome = report.outcome
description = report._sub_test_description()
if hasattr(report, "wasxfail"):
if quiet:
return "", "", ""
elif outcome == "skipped":
category = "xfailed"
short = "y" # x letter is used for regular xfail, y for subtest xfail
status = "SUBXFAIL"
# outcome == "passed" in an xfail is only possible via a @pytest.mark.xfail mark, which
# is not applicable to a subtest, which only handles pytest.xfail().
else: # pragma: no cover
# This should not normally happen, unless some plugin is setting wasxfail without
# the correct outcome. Pytest expects the call outcome to be either skipped or
# passed in case of xfail.
# Let's pass this report to the next hook.
return None
return category, short, f"{status}{description}"
if report.failed:
return outcome, "u", f"SUBFAILED{description}"
else:
if report.passed:
if quiet:
return "", "", ""
else:
return f"subtests {outcome}", "u", f"SUBPASSED{description}"
elif report.skipped:
if quiet:
return "", "", ""
else:
return outcome, "-", f"SUBSKIPPED{description}"
else:
failed_subtests_count = config.stash[failed_subtests_key][report.nodeid]
# Top-level test, fail if it contains failed subtests and it has passed.
if report.passed and failed_subtests_count > 0:
report.outcome = "failed"
suffix = "s" if failed_subtests_count > 1 else ""
report.longrepr = f"contains {failed_subtests_count} failed subtest{suffix}"
return None
| CapturedLogs |
python | PrefectHQ__prefect | src/prefect/server/exceptions.py | {
"start": 50,
"end": 296
} | class ____(PrefectException):
"""
Error raised by the Prefect REST API when a requested object is not found.
If thrown during a request, this exception will be caught and
a 404 response will be returned.
"""
| ObjectNotFoundError |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/components/airflow_instance/component.py | {
"start": 4042,
"end": 4221
} | class ____(Resolvable):
dag_id: str
assets: Optional[Sequence[ResolvedMappedAsset]] = None
task_mappings: Optional[Sequence[AirflowTaskMapping]] = None
| AirflowDagMapping |
python | astropy__astropy | astropy/modeling/tests/test_input.py | {
"start": 23298,
"end": 33781
} | class ____:
"""
A suite of tests to check various cases of parameter and input combinations
on models with n_input = 1 but n_output = 2 on a toy model with n_models=1.
As of writing there are not enough controls to adjust how outputs from such
a model should be formatted (currently the shapes of outputs are assumed to
be directly associated with the shapes of corresponding inputs when
n_inputs == n_outputs). For now, the approach taken for cases like this is
to assume all outputs should have the same format.
"""
def test_scalar_parameters_scalar_input(self):
"""
Scalar parameters with a scalar input should return a scalar.
"""
t = TModel_1_2(1, 10, 1000)
y, z = t(100)
assert isinstance(y, float)
assert isinstance(z, float)
assert np.ndim(y) == np.ndim(z) == 0
assert y == 111
assert z == 1111
def test_scalar_parameters_1d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_2(1, 10, 1000)
y, z = t(np.arange(5) * 100)
assert isinstance(y, np.ndarray)
assert isinstance(z, np.ndarray)
assert np.shape(y) == np.shape(z) == (5,)
assert np.all(y == [11, 111, 211, 311, 411])
assert np.all(z == (y + 1000))
def test_scalar_parameters_2d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_2(1, 10, 1000)
y, z = t(np.arange(6).reshape(2, 3) * 100)
assert isinstance(y, np.ndarray)
assert isinstance(z, np.ndarray)
assert np.shape(y) == np.shape(z) == (2, 3)
assert np.all(y == [[11, 111, 211], [311, 411, 511]])
assert np.all(z == (y + 1000))
def test_scalar_parameters_3d_array_input(self):
"""
Scalar parameters should broadcast with an array input to result in an
array output of the same shape as the input.
"""
t = TModel_1_2(1, 10, 1000)
y, z = t(np.arange(12).reshape(2, 3, 2) * 100)
assert isinstance(y, np.ndarray)
assert isinstance(z, np.ndarray)
assert np.shape(y) == np.shape(z) == (2, 3, 2)
assert np.all(
y
== [
[[11, 111], [211, 311], [411, 511]],
[[611, 711], [811, 911], [1011, 1111]],
]
)
assert np.all(z == (y + 1000))
def test_1d_array_parameters_scalar_input(self):
"""
Array parameters should all be broadcastable with each other, and with
a scalar input the output should be broadcast to the maximum dimensions
of the parameters.
"""
t = TModel_1_2([1, 2], [10, 20], [1000, 2000])
y, z = t(100)
assert isinstance(y, np.ndarray)
assert isinstance(z, np.ndarray)
assert np.shape(y) == np.shape(z) == (2,)
assert np.all(y == [111, 122])
assert np.all(z == [1111, 2122])
def test_1d_array_parameters_1d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_2([1, 2], [10, 20], [1000, 2000])
y1, z1 = t([100, 200])
assert np.shape(y1) == np.shape(z1) == (2,)
assert np.all(y1 == [111, 222])
assert np.all(z1 == [1111, 2222])
y2, z2 = t([[100], [200]])
assert np.shape(y2) == np.shape(z2) == (2, 2)
assert np.all(y2 == [[111, 122], [211, 222]])
assert np.all(z2 == [[1111, 2122], [1211, 2222]])
with pytest.raises(ValueError, match="broadcast"):
# Doesn't broadcast
y3, z3 = t([100, 200, 300])
def test_2d_array_parameters_2d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_2(
[[1, 2], [3, 4]], [[10, 20], [30, 40]], [[1000, 2000], [3000, 4000]]
)
y1, z1 = t([[100, 200], [300, 400]])
assert np.shape(y1) == np.shape(z1) == (2, 2)
assert np.all(y1 == [[111, 222], [333, 444]])
assert np.all(z1 == [[1111, 2222], [3333, 4444]])
y2, z2 = t([[[[100]], [[200]]], [[[300]], [[400]]]])
assert np.shape(y2) == np.shape(z2) == (2, 2, 2, 2)
assert np.all(
y2
== [
[[[111, 122], [133, 144]], [[211, 222], [233, 244]]],
[[[311, 322], [333, 344]], [[411, 422], [433, 444]]],
]
)
assert np.all(
z2
== [
[[[1111, 2122], [3133, 4144]], [[1211, 2222], [3233, 4244]]],
[[[1311, 2322], [3333, 4344]], [[1411, 2422], [3433, 4444]]],
]
)
with pytest.raises(ValueError, match="broadcast"):
# Doesn't broadcast
y3, z3 = t([[100, 200, 300], [400, 500, 600]])
def test_mixed_array_parameters_1d_array_input(self):
"""
When given an array input it must be broadcastable with all the
parameters.
"""
t = TModel_1_2(
[
[[0.01, 0.02, 0.03], [0.04, 0.05, 0.06]],
[[0.07, 0.08, 0.09], [0.10, 0.11, 0.12]],
],
[1, 2, 3],
[100, 200, 300],
)
y1, z1 = t([10, 20, 30])
assert np.shape(y1) == np.shape(z1) == (2, 2, 3)
assert_allclose(
y1,
[
[[11.01, 22.02, 33.03], [11.04, 22.05, 33.06]],
[[11.07, 22.08, 33.09], [11.10, 22.11, 33.12]],
],
)
assert_allclose(
z1,
[
[[111.01, 222.02, 333.03], [111.04, 222.05, 333.06]],
[[111.07, 222.08, 333.09], [111.10, 222.11, 333.12]],
],
)
y2, z2 = t([[[[10]]], [[[20]]], [[[30]]]])
assert np.shape(y2) == np.shape(z2) == (3, 2, 2, 3)
assert_allclose(
y2,
[
[
[[11.01, 12.02, 13.03], [11.04, 12.05, 13.06]],
[[11.07, 12.08, 13.09], [11.10, 12.11, 13.12]],
],
[
[[21.01, 22.02, 23.03], [21.04, 22.05, 23.06]],
[[21.07, 22.08, 23.09], [21.10, 22.11, 23.12]],
],
[
[[31.01, 32.02, 33.03], [31.04, 32.05, 33.06]],
[[31.07, 32.08, 33.09], [31.10, 32.11, 33.12]],
],
],
)
assert_allclose(
z2,
[
[
[[111.01, 212.02, 313.03], [111.04, 212.05, 313.06]],
[[111.07, 212.08, 313.09], [111.10, 212.11, 313.12]],
],
[
[[121.01, 222.02, 323.03], [121.04, 222.05, 323.06]],
[[121.07, 222.08, 323.09], [121.10, 222.11, 323.12]],
],
[
[[131.01, 232.02, 333.03], [131.04, 232.05, 333.06]],
[[131.07, 232.08, 333.09], [131.10, 232.11, 333.12]],
],
],
)
# test broadcasting rules
broadcast_models = [
{"model": models.Identity(2), "inputs": [0, [1, 1]], "outputs": [0, [1, 1]]},
{"model": models.Identity(2), "inputs": [[1, 1], 0], "outputs": [[1, 1], 0]},
{"model": models.Mapping((0, 1)), "inputs": [0, [1, 1]], "outputs": [0, [1, 1]]},
{"model": models.Mapping((1, 0)), "inputs": [0, [1, 1]], "outputs": [[1, 1], 0]},
{
"model": models.Mapping((1, 0), n_inputs=3),
"inputs": [0, [1, 1], 2],
"outputs": [[1, 1], 0],
},
{
"model": models.Mapping((0, 1, 0)),
"inputs": [0, [1, 1]],
"outputs": [0, [1, 1], 0],
},
{
"model": models.Mapping((0, 1, 1)),
"inputs": [0, [1, 1]],
"outputs": [0, [1, 1], [1, 1]],
},
{"model": models.Polynomial2D(1, c0_0=1), "inputs": [0, [1, 1]], "outputs": [1, 1]},
{"model": models.Polynomial2D(1, c0_0=1), "inputs": [0, 1], "outputs": 1},
{
"model": models.Gaussian2D(1, 1, 2, 1, 1.2),
"inputs": [0, [1, 1]],
"outputs": [0.42860385, 0.42860385],
},
{
"model": models.Gaussian2D(1, 1, 2, 1, 1.2),
"inputs": [0, 1],
"outputs": 0.428603846153,
},
{
"model": models.Polynomial2D(1, c0_0=1) & models.Polynomial2D(1, c0_0=2),
"inputs": [1, 1, 1, 1],
"outputs": (1, 2),
},
{
"model": models.Polynomial2D(1, c0_0=1) & models.Polynomial2D(1, c0_0=2),
"inputs": [1, 1, [1, 1], [1, 1]],
"outputs": (1, [2, 2]),
},
{
"model": models.math.MultiplyUfunc(),
"inputs": [np.array([np.linspace(0, 1, 5)]).T, np.arange(2)],
"outputs": np.array(
[[0.0, 0.0], [0.0, 0.25], [0.0, 0.5], [0.0, 0.75], [0.0, 1.0]]
),
},
]
@pytest.mark.parametrize("model", broadcast_models)
def test_mixed_input(model):
result = model["model"](*model["inputs"])
if np.isscalar(result):
assert_allclose(result, model["outputs"])
else:
for i in range(len(result)):
assert_allclose(result[i], model["outputs"][i])
def test_more_outputs():
class M(FittableModel):
standard_broadcasting = False
n_inputs = 2
n_outputs = 3
a = Parameter()
def evaluate(self, x, y, a):
return a * x, a - x, a + y
def __call__(self, *args, **kwargs):
inputs, _ = super().prepare_inputs(*args, **kwargs)
outputs = self.evaluate(*inputs, *self.parameters)
output_shapes = [out.shape for out in outputs]
output_shapes = [() if shape == (1,) else shape for shape in output_shapes]
return self.prepare_outputs((tuple(output_shapes),), *outputs, **kwargs)
c = M(1)
result = c([1, 1], 1)
expected = [[1.0, 1.0], [0.0, 0.0], 2.0]
for r, e in zip(result, expected):
assert_allclose(r, e)
c = M(1)
result = c(1, [1, 1])
expected = [1.0, 0.0, [2.0, 2.0]]
for r, e in zip(result, expected):
assert_allclose(r, e)
| TestSingleInputDoubleOutputSingleModel |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 115706,
"end": 116792
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("model_service.Model.to_dict"))
@mock.patch(VERTEX_AI_PATH.format("model_service.ModelServiceHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = SetDefaultVersionOnModelOperator(
task_id=TASK_ID,
model_id=TEST_MODEL_NAME,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()})
mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
mock_hook.return_value.set_version_as_default.assert_called_once_with(
region=GCP_LOCATION,
project_id=GCP_PROJECT,
model_id=TEST_MODEL_NAME,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
| TestVertexAISetDefaultVersionOnModelOperator |
python | django__django | tests/admin_views/models.py | {
"start": 26739,
"end": 26845
} | class ____(models.Model):
# Don't point any FK at this model.
pass
# Models for #23934
| NotReferenced |
python | pypa__warehouse | tests/conftest.py | {
"start": 23598,
"end": 25781
} | class ____:
"""
Just enough Redis for our tests.
In-memory only, no persistence.
Does NOT implement the full Redis API.
"""
def __init__(self, cache=None):
self.cache = cache
if not self.cache: # pragma: no cover
self.cache = dict()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
def delete(self, key):
del self.cache[key]
def execute(self):
pass
def exists(self, key):
return key in self.cache
def expire(self, _key, _seconds):
pass
def from_url(self, _url):
return self
def hget(self, hash_, key):
try:
return self.cache[hash_][key]
except KeyError:
return None
def hset(self, hash_, key, value, *_args, **_kwargs):
if hash_ not in self.cache: # pragma: no cover
self.cache[hash_] = dict()
self.cache[hash_][key] = value
def get(self, key):
return self.cache.get(key)
def pipeline(self):
return self
def register_script(self, script):
return script # pragma: no cover
def scan_iter(self, search, count):
del count # unused
return [key for key in self.cache.keys() if re.search(search, key)]
def set(self, key, value, *_args, **_kwargs):
self.cache[key] = value
def setex(self, key, value, _seconds):
self.cache[key] = value
@pytest.fixture
def mockredis():
return _MockRedis()
@pytest.fixture
def gitlab_provenance() -> Provenance:
"""
Provenance from
https://test.pypi.org/integrity/pep740-sampleproject/1.0.0/pep740_sampleproject-1.0.0.tar.gz/provenance
"""
return Provenance.model_validate_json(
(_FIXTURES / "pep740-sampleproject-1.0.0.tar.gz.provenance").read_text()
)
@pytest.fixture
def github_provenance() -> Provenance:
"""
Provenance from
https://pypi.org/integrity/sampleproject/4.0.0/sampleproject-4.0.0.tar.gz/provenance
"""
return Provenance.model_validate_json(
(_FIXTURES / "sampleproject-4.0.0.tar.gz.provenance").read_text()
)
| _MockRedis |
python | scipy__scipy | scipy/special/tests/test_precompute_utils.py | {
"start": 439,
"end": 1165
} | class ____:
@pytest.mark.xfail_on_32bit("rtol only 2e-9, see gh-6938")
def test_log(self):
with mp.workdps(30):
logcoeffs = mp.taylor(lambda x: mp.log(1 + x), 0, 10)
expcoeffs = mp.taylor(lambda x: mp.exp(x) - 1, 0, 10)
invlogcoeffs = lagrange_inversion(logcoeffs)
mp_assert_allclose(invlogcoeffs, expcoeffs)
@pytest.mark.xfail_on_32bit("rtol only 1e-15, see gh-6938")
def test_sin(self):
with mp.workdps(30):
sincoeffs = mp.taylor(mp.sin, 0, 10)
asincoeffs = mp.taylor(mp.asin, 0, 10)
invsincoeffs = lagrange_inversion(sincoeffs)
mp_assert_allclose(invsincoeffs, asincoeffs, atol=1e-30)
| TestInversion |
python | numpy__numpy | numpy/matrixlib/tests/test_masked_matrix.py | {
"start": 8116,
"end": 8822
} | class ____:
# Tests for mr_, the equivalent of r_ for masked arrays.
def test_matrix_builder(self):
assert_raises(np.ma.MAError, lambda: mr_['1, 2; 3, 4'])
def test_matrix(self):
# Test consistency with unmasked version. If we ever deprecate
# matrix, this test should either still pass, or both actual and
# expected should fail to be build.
actual = mr_['r', 1, 2, 3]
expected = np.ma.array(np.r_['r', 1, 2, 3])
assert_array_equal(actual, expected)
# outer type is masked array, inner type is matrix
assert_equal(type(actual), type(expected))
assert_equal(type(actual.data), type(expected.data))
| TestConcatenator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_worksheet07.py | {
"start": 400,
"end": 2720
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with formulas in cells."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle(fh)
worksheet.str_table = SharedStringTable()
worksheet.select()
# Write some data and formulas.
worksheet.write_number(0, 0, 1)
worksheet.write_number(1, 0, 2)
worksheet.write_formula(2, 2, "=A1+A2", None, 3)
worksheet.write_formula(4, 1, """="<&>" & ";"" '\"""", None, """<&>;" '""")
worksheet._assemble_xml_file()
exp = _xml_to_list(
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<dimension ref="A1:C5"/>
<sheetViews>
<sheetView tabSelected="1" workbookViewId="0"/>
</sheetViews>
<sheetFormatPr defaultRowHeight="15"/>
<sheetData>
<row r="1" spans="1:3">
<c r="A1">
<v>1</v>
</c>
</row>
<row r="2" spans="1:3">
<c r="A2">
<v>2</v>
</c>
</row>
<row r="3" spans="1:3">
<c r="C3">
<f>A1+A2</f>
<v>3</v>
</c>
</row>
<row r="5" spans="1:3">
<c r="B5" t="str">
<f>"<&>" & ";"" '"</f>
<v><&>;" '</v>
</c>
</row>
</sheetData>
<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
</worksheet>
"""
)
got = _xml_to_list(fh.getvalue())
self.assertEqual(exp, got)
| TestAssembleWorksheet |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 200005,
"end": 200446
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "column_edge", "project")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
column_edge = sgqlc.types.Field("ProjectColumnEdge", graphql_name="columnEdge")
project = sgqlc.types.Field("Project", graphql_name="project")
| AddProjectColumnPayload |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 10440,
"end": 12290
} | class ____(serializers.ModelSerializer):
aliases = serializers.SerializerMethodField()
ref = serializers.CharField()
downloads = serializers.SerializerMethodField()
urls = VersionURLsSerializer(source="*")
_links = VersionLinksSerializer(source="*")
class Meta:
model = Version
fields = [
"aliases",
"id",
"slug",
"verbose_name",
"identifier",
"ref",
"built",
"active",
"hidden",
"type",
"downloads",
"urls",
"_links",
"privacy_level",
]
def __init__(self, *args, resolver=None, **kwargs):
# Use a shared resolver to reduce the amount of DB queries while
# resolving version URLs.
self.resolver = resolver or Resolver()
super().__init__(*args, **kwargs)
def get_downloads(self, obj):
downloads = obj.get_downloads(resolver=self.resolver)
data = {}
for k, v in downloads.items():
if k in ("html", "pdf", "epub"):
# Keep backward compatibility
if k == "html":
k = "htmlzip"
data[k] = ("http:" if settings.DEBUG else "https:") + v
return data
def get_aliases(self, obj):
if obj.machine and obj.slug in (STABLE, LATEST):
if obj.slug == STABLE:
alias_version = obj.project.get_original_stable_version()
if obj.slug == LATEST:
alias_version = obj.project.get_original_latest_version()
if alias_version and alias_version.active:
# NOTE: we use __class__, as this serializer can be subclassed.
return [self.__class__(alias_version).data]
return []
| VersionSerializer |
python | pytorch__pytorch | test/distributed/tensor/test_random_ops.py | {
"start": 26999,
"end": 30368
} | class ____(DTensorTestBase):
@property
def world_size(self):
return 8
@skip_if_lt_x_gpu(8)
@with_comms
def test_hsdp_tp_model_meta_init(self):
# initialize the 3-d device mesh
global_mesh = init_device_mesh(
self.device_type,
mesh_shape=(self.world_size // 4, 2, 2),
mesh_dim_names=("dp_replicate", "dp_shard", "tp"),
)
tp_mesh = global_mesh["tp"]
dp_mesh = global_mesh["dp_replicate", "dp_shard"]
# model meta init
with torch.device("meta"):
model = torch.nn.Linear(self.world_size, self.world_size, bias=False)
self.assertEqual(model.weight.device, torch.device("meta"))
parallelize_module(model, tp_mesh, ColwiseParallel())
if random._rng_tracker is not None:
random._rng_tracker.distribute_region_enabled = True
fully_shard(model, mesh=dp_mesh)
self.assertEqual(model.weight.device, torch.device("meta"))
# actual initialization
device = torch.device(
self.device_type, torch.get_device_module(self.device_type).current_device()
)
model.to_empty(device=device)
model.reset_parameters()
self.assertTrue(
random._rng_tracker is not None
and isinstance(random._rng_tracker, OffsetBasedRNGTracker)
)
self.assertEqual(model.weight.device, device)
assert isinstance(model.weight, DTensor)
# gather all the shards to compare initialization results
WORLD = torch.distributed.group.WORLD
assert WORLD is not None
weight_local = model.weight.to_local()
weight_gather = funcol.all_gather_tensor(
weight_local,
gather_dim=0,
group=WORLD,
)
weight_gather = weight_gather.wait()
weight_gather = (
weight_gather.reconcile()
if isinstance(weight_gather, LocalTensor)
else weight_gather
)
@maybe_run_for_local_tensor
def compute_rankwise_if_local_tensor(weight_local, rank):
# verify the weights are initialized differently on all ranks
shard_dim_0_len = self.world_size // 4
for other_rank in range(self.world_size):
other_rank_dim_0_start = other_rank * shard_dim_0_len
other_rank_dim_0_end = other_rank_dim_0_start + shard_dim_0_len
if rank % 4 != other_rank % 4:
self.assertNotEqual(
weight_local,
weight_gather[other_rank_dim_0_start:other_rank_dim_0_end, :],
)
else:
self.assertEqual(
weight_local,
weight_gather[other_rank_dim_0_start:other_rank_dim_0_end, :],
)
compute_rankwise_if_local_tensor(weight_local, self.rank)
DistTensorRandomInitTestWithLocalTensor = create_local_tensor_test_class(
DistTensorRandomInitTest,
)
DistTensorRandomOpTestWithLocalTensor = create_local_tensor_test_class(
DistTensorRandomOpTest,
)
DistTensorRandomOpsTest3DWithLocalTensor = create_local_tensor_test_class(
DistTensorRandomOpsTest3D,
)
if __name__ == "__main__":
run_tests()
| DistTensorRandomOpsTest3D |
python | scrapy__scrapy | tests/test_mail.py | {
"start": 188,
"end": 5073
} | class ____:
def test_send(self):
mailsender = MailSender(debug=True)
mailsender.send(
to=["test@scrapy.org"],
subject="subject",
body="body",
_callback=self._catch_mail_sent,
)
assert self.catched_msg
assert self.catched_msg["to"] == ["test@scrapy.org"]
assert self.catched_msg["subject"] == "subject"
assert self.catched_msg["body"] == "body"
msg = self.catched_msg["msg"]
assert msg["to"] == "test@scrapy.org"
assert msg["subject"] == "subject"
assert msg.get_payload() == "body"
assert msg.get("Content-Type") == "text/plain"
def test_send_single_values_to_and_cc(self):
mailsender = MailSender(debug=True)
mailsender.send(
to="test@scrapy.org",
subject="subject",
body="body",
cc="test@scrapy.org",
_callback=self._catch_mail_sent,
)
def test_send_html(self):
mailsender = MailSender(debug=True)
mailsender.send(
to=["test@scrapy.org"],
subject="subject",
body="<p>body</p>",
mimetype="text/html",
_callback=self._catch_mail_sent,
)
msg = self.catched_msg["msg"]
assert msg.get_payload() == "<p>body</p>"
assert msg.get("Content-Type") == "text/html"
def test_send_attach(self):
attach = BytesIO()
attach.write(b"content")
attach.seek(0)
attachs = [("attachment", "text/plain", attach)]
mailsender = MailSender(debug=True)
mailsender.send(
to=["test@scrapy.org"],
subject="subject",
body="body",
attachs=attachs,
_callback=self._catch_mail_sent,
)
assert self.catched_msg
assert self.catched_msg["to"] == ["test@scrapy.org"]
assert self.catched_msg["subject"] == "subject"
assert self.catched_msg["body"] == "body"
msg = self.catched_msg["msg"]
assert msg["to"] == "test@scrapy.org"
assert msg["subject"] == "subject"
payload = msg.get_payload()
assert isinstance(payload, list)
assert len(payload) == 2
text, attach = payload
assert text.get_payload(decode=True) == b"body"
assert text.get_charset() == Charset("us-ascii")
assert attach.get_payload(decode=True) == b"content"
def _catch_mail_sent(self, **kwargs):
self.catched_msg = {**kwargs}
def test_send_utf8(self):
subject = "sübjèçt"
body = "bödÿ-àéïöñß"
mailsender = MailSender(debug=True)
mailsender.send(
to=["test@scrapy.org"],
subject=subject,
body=body,
charset="utf-8",
_callback=self._catch_mail_sent,
)
assert self.catched_msg
assert self.catched_msg["subject"] == subject
assert self.catched_msg["body"] == body
msg = self.catched_msg["msg"]
assert msg["subject"] == subject
assert msg.get_payload(decode=True).decode("utf-8") == body
assert msg.get_charset() == Charset("utf-8")
assert msg.get("Content-Type") == 'text/plain; charset="utf-8"'
def test_send_attach_utf8(self):
subject = "sübjèçt"
body = "bödÿ-àéïöñß"
attach = BytesIO()
attach.write(body.encode("utf-8"))
attach.seek(0)
attachs = [("attachment", "text/plain", attach)]
mailsender = MailSender(debug=True)
mailsender.send(
to=["test@scrapy.org"],
subject=subject,
body=body,
attachs=attachs,
charset="utf-8",
_callback=self._catch_mail_sent,
)
assert self.catched_msg
assert self.catched_msg["subject"] == subject
assert self.catched_msg["body"] == body
msg = self.catched_msg["msg"]
assert msg["subject"] == subject
assert msg.get_charset() == Charset("utf-8")
assert msg.get("Content-Type") == 'multipart/mixed; charset="utf-8"'
payload = msg.get_payload()
assert isinstance(payload, list)
assert len(payload) == 2
text, attach = payload
assert text.get_payload(decode=True).decode("utf-8") == body
assert text.get_charset() == Charset("utf-8")
assert attach.get_payload(decode=True).decode("utf-8") == body
def test_create_sender_factory_with_host(self):
mailsender = MailSender(debug=False, smtphost="smtp.testhost.com")
factory = mailsender._create_sender_factory(
to_addrs=["test@scrapy.org"], msg="test", d=defer.Deferred()
)
context = factory.buildProtocol("test@scrapy.org").context
assert isinstance(context, ClientTLSOptions)
| TestMailSender |
python | kamyu104__LeetCode-Solutions | Python/maximum-coins-from-k-consecutive-bags.py | {
"start": 70,
"end": 923
} | class ____(object):
def maximumCoins(self, coins, k):
"""
:type coins: List[List[int]]
:type k: int
:rtype: int
"""
def max_amount():
coins.sort()
result = curr = left = 0
for right in xrange(len(coins)):
curr += (coins[right][1]-coins[right][0]+1)*coins[right][2]
while coins[right][1]-coins[left][1]+1 > k:
curr -= (coins[left][1]-coins[left][0]+1)*coins[left][2]
left += 1
result = max(result, curr-max((coins[right][1]-coins[left][0]+1)-k, 0)*coins[left][2])
return result
result = max_amount()
for i, (l, r, w) in enumerate(coins):
coins[i][:] = [-r, -l, w]
result = max(result, max_amount())
return result
| Solution |
python | realpython__materials | python-property/circle_v4.py | {
"start": 25,
"end": 335
} | class ____:
def __init__(self, radius):
self.radius = radius
self._diameter = None
@property
def diameter(self):
if self._diameter is None:
sleep(0.5) # Simulate a costly computation
self._diameter = self.radius * 2
return self._diameter
| Circle |
python | huggingface__transformers | src/transformers/models/flaubert/modeling_flaubert.py | {
"start": 70993,
"end": 77975
} | class ____(FlaubertPreTrainedModel):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.transformer = FlaubertModel(config)
self.sequence_summary = FlaubertSequenceSummary(config)
self.logits_proj = nn.Linear(config.num_labels, 1)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
langs: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
lengths: Optional[torch.Tensor] = None,
cache: Optional[dict[str, torch.Tensor]] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, MultipleChoiceModelOutput]:
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
langs (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
languages ids which can be obtained from the language names by using two conversion mappings provided in
the configuration of the model (only provided for multilingual models). More precisely, the *language name
to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
*language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
See usage examples detailed in the [multilingual documentation](../multilingual).
token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Length of each sentence that can be used to avoid performing attention on padding token indices. You can
also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
`[0, ..., input_ids.size(-1)]`.
cache (`dict[str, torch.FloatTensor]`, *optional*):
Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
decoding.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
`input_ids` above)
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
langs = langs.view(-1, langs.size(-1)) if langs is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
if lengths is not None:
logger.warning(
"The `lengths` parameter cannot be used with the Flaubert multiple choice models. Please use the "
"attention mask instead."
)
lengths = None
transformer_outputs = self.transformer(
input_ids=input_ids,
attention_mask=attention_mask,
langs=langs,
token_type_ids=token_type_ids,
position_ids=position_ids,
lengths=lengths,
cache=cache,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
output = transformer_outputs[0]
logits = self.sequence_summary(output)
logits = self.logits_proj(logits)
reshaped_logits = logits.view(-1, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
if not return_dict:
output = (reshaped_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
__all__ = [
"FlaubertForMultipleChoice",
"FlaubertForQuestionAnswering",
"FlaubertForQuestionAnsweringSimple",
"FlaubertForSequenceClassification",
"FlaubertForTokenClassification",
"FlaubertModel",
"FlaubertWithLMHeadModel",
"FlaubertPreTrainedModel",
]
| FlaubertForMultipleChoice |
python | huggingface__transformers | src/transformers/models/xlm/modeling_xlm.py | {
"start": 31372,
"end": 40450
} | class ____(XLMPreTrainedModel):
def __init__(self, config):
super().__init__(config)
# encoder / decoder, output layer
self.is_encoder = config.is_encoder
self.is_decoder = not config.is_encoder
if self.is_decoder:
raise NotImplementedError("Currently XLM can only be used as an encoder")
# self.with_output = with_output
self.causal = config.causal
# dictionary / languages
self.n_langs = config.n_langs
self.use_lang_emb = config.use_lang_emb
self.n_words = config.n_words
self.eos_index = config.eos_index
self.pad_index = config.pad_index
# self.dico = dico
# self.id2lang = config.id2lang
# self.lang2id = config.lang2id
# assert len(self.dico) == self.n_words
# assert len(self.id2lang) == len(self.lang2id) == self.n_langs
# model parameters
self.dim = config.emb_dim # 512 by default
self.hidden_dim = self.dim * 4 # 2048 by default
self.n_heads = config.n_heads # 8 by default
self.n_layers = config.n_layers
self.dropout = config.dropout
self.attention_dropout = config.attention_dropout
assert self.dim % self.n_heads == 0, "transformer dim must be a multiple of n_heads"
# embeddings
self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.dim)
if config.n_langs > 1 and config.use_lang_emb:
self.lang_embeddings = nn.Embedding(self.n_langs, self.dim)
self.embeddings = nn.Embedding(self.n_words, self.dim, padding_idx=self.pad_index)
self.layer_norm_emb = nn.LayerNorm(self.dim, eps=config.layer_norm_eps)
# transformer layers
self.attentions = nn.ModuleList()
self.layer_norm1 = nn.ModuleList()
self.ffns = nn.ModuleList()
self.layer_norm2 = nn.ModuleList()
# if self.is_decoder:
# self.layer_norm15 = nn.ModuleList()
# self.encoder_attn = nn.ModuleList()
for i in range(self.n_layers):
self.attentions.append(MultiHeadAttention(self.n_heads, self.dim, config=config, layer_idx=i))
self.layer_norm1.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
# if self.is_decoder:
# self.layer_norm15.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
# self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))
self.ffns.append(TransformerFFN(self.dim, self.hidden_dim, self.dim, config=config))
self.layer_norm2.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
# Initialize weights and apply final processing
self.post_init()
self.register_buffer(
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
)
def get_input_embeddings(self):
return self.embeddings
def set_input_embeddings(self, new_embeddings):
self.embeddings = new_embeddings
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
langs: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
lengths: Optional[torch.Tensor] = None,
cache: Optional[dict[str, torch.Tensor]] = None,
inputs_embeds: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.Tensor] = None,
**kwargs, # Dummy kwargs for now
) -> Union[tuple, BaseModelOutput]:
r"""
langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
languages ids which can be obtained from the language names by using two conversion mappings provided in
the configuration of the model (only provided for multilingual models). More precisely, the *language name
to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
*language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
See usage examples detailed in the [multilingual documentation](../multilingual).
lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Length of each sentence that can be used to avoid performing attention on padding token indices. You can
also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
`[0, ..., input_ids.size(-1)]`.
cache (`dict[str, torch.FloatTensor]`, *optional*):
Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
decoding.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None:
bs, slen = input_ids.size()
else:
bs, slen = inputs_embeds.size()[:-1]
device = input_ids.device if input_ids is not None else inputs_embeds.device
if cache is None:
cache = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
if lengths is None:
if input_ids is not None:
lengths = (input_ids != self.pad_index).sum(dim=1).long()
else:
lengths = torch.tensor([slen] * bs, device=device)
# check inputs
assert lengths.size(0) == bs
assert lengths.max().item() <= slen
# generate masks
mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
# position_ids
if position_ids is None:
position_ids = self.position_ids[:, :slen]
else:
assert position_ids.size() == (bs, slen) # (slen, bs)
# langs
if langs is not None:
assert langs.size() == (bs, slen) # (slen, bs)
# do not recompute cached elements
if cache is not None and input_ids is not None:
_slen = slen - cache.get_seq_length()
input_ids = input_ids[:, -_slen:]
position_ids = position_ids[:, -_slen:]
if langs is not None:
langs = langs[:, -_slen:]
mask = mask[:, -_slen:]
attn_mask = attn_mask[:, -_slen:]
# embeddings
if inputs_embeds is None:
inputs_embeds = self.embeddings(input_ids)
tensor = inputs_embeds + self.position_embeddings(position_ids).expand_as(inputs_embeds)
if langs is not None and self.use_lang_emb and self.n_langs > 1:
tensor = tensor + self.lang_embeddings(langs)
if token_type_ids is not None:
tensor = tensor + self.embeddings(token_type_ids)
tensor = self.layer_norm_emb(tensor)
tensor = nn.functional.dropout(tensor, p=self.dropout, training=self.training)
tensor *= mask.unsqueeze(-1).to(tensor.dtype)
# transformer layers
hidden_states = () if output_hidden_states else None
attentions = () if output_attentions else None
for i in range(self.n_layers):
if output_hidden_states:
hidden_states = hidden_states + (tensor,)
# self attention
attn_outputs = self.attentions[i](
tensor,
attn_mask,
cache=cache,
output_attentions=output_attentions,
cache_position=cache_position,
)
attn = attn_outputs[0]
if output_attentions:
attentions = attentions + (attn_outputs[1],)
attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
tensor = tensor + attn
tensor = self.layer_norm1[i](tensor)
# FFN
tensor = tensor + self.ffns[i](tensor)
tensor = self.layer_norm2[i](tensor)
tensor *= mask.unsqueeze(-1).to(tensor.dtype)
# Add last hidden state
if output_hidden_states:
hidden_states = hidden_states + (tensor,)
if not return_dict:
return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)
return BaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)
| XLMModel |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_framework.py | {
"start": 30164,
"end": 36872
} | class ____:
"""Test before_agent and after_agent hooks working together."""
@pytest.mark.parametrize("is_async", [False, True])
async def test_execution_order(self, is_async: bool) -> None:
"""Test that before_agent executes before after_agent in both sync and async modes."""
from langchain.agents.middleware import after_agent, before_agent
execution_log: list[str] = []
if is_async:
@before_agent
async def log_before(state: AgentState, runtime) -> None:
execution_log.append("before")
@after_agent
async def log_after(state: AgentState, runtime) -> None:
execution_log.append("after")
else:
@before_agent
def log_before(state: AgentState, runtime) -> None:
execution_log.append("before")
@after_agent
def log_after(state: AgentState, runtime) -> None:
execution_log.append("after")
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
model = GenericFakeChatModel(messages=iter([AIMessage(content="Response")]))
agent = create_agent(model=model, tools=[], middleware=[log_before, log_after])
if is_async:
await agent.ainvoke({"messages": [HumanMessage("Test")]})
else:
agent.invoke({"messages": [HumanMessage("Test")]})
assert execution_log == ["before", "after"]
def test_state_passthrough(self) -> None:
"""Test that state modifications in before_agent are visible to after_agent."""
from langchain.agents.middleware import before_agent
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
@before_agent
def modify_in_before(state: AgentState, runtime) -> dict[str, Any]:
return {"messages": [HumanMessage("Added by before_agent")]}
model = GenericFakeChatModel(messages=iter([AIMessage(content="Response")]))
agent = create_agent(model=model, tools=[], middleware=[modify_in_before])
result = agent.invoke({"messages": [HumanMessage("Original")]})
message_contents = [msg.content for msg in result["messages"]]
assert message_contents[1] == "Added by before_agent"
def test_multiple_middleware_instances(self) -> None:
"""Test multiple before_agent and after_agent middleware instances."""
from langchain.agents.middleware import after_agent, before_agent
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
execution_log = []
@before_agent
def before_one(state: AgentState, runtime) -> None:
execution_log.append("before_1")
@before_agent
def before_two(state: AgentState, runtime) -> None:
execution_log.append("before_2")
@after_agent
def after_one(state: AgentState, runtime) -> None:
execution_log.append("after_1")
@after_agent
def after_two(state: AgentState, runtime) -> None:
execution_log.append("after_2")
model = GenericFakeChatModel(messages=iter([AIMessage(content="Response")]))
agent = create_agent(
model=model, tools=[], middleware=[before_one, before_two, after_one, after_two]
)
agent.invoke({"messages": [HumanMessage("Test")]})
assert execution_log == ["before_1", "before_2", "after_2", "after_1"]
def test_agent_hooks_run_once_with_multiple_model_calls(self) -> None:
"""Test that before_agent and after_agent run only once per thread.
This test verifies that agent-level hooks (before_agent, after_agent) execute
exactly once per agent invocation, regardless of how many tool calling loops occur.
This is different from model-level hooks (before_model, after_model) which run
on every model invocation within the tool calling loop.
"""
from langchain.agents.middleware import (
after_agent,
after_model,
before_agent,
before_model,
)
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
execution_log = []
@tool
def sample_tool_agent(query: str) -> str:
"""A sample tool for testing."""
return f"Result for: {query}"
@before_agent
def log_before_agent(state: AgentState, runtime) -> None:
execution_log.append("before_agent")
@before_model
def log_before_model(state: AgentState, runtime) -> None:
execution_log.append("before_model")
@after_agent
def log_after_agent(state: AgentState, runtime) -> None:
execution_log.append("after_agent")
@after_model
def log_after_model(state: AgentState, runtime) -> None:
execution_log.append("after_model")
# Model will call a tool twice, then respond with final answer
# This creates 3 model invocations total, but agent hooks should still run once
model = FakeToolCallingModel(
tool_calls=[
[{"name": "sample_tool_agent", "args": {"query": "first"}, "id": "1"}],
[{"name": "sample_tool_agent", "args": {"query": "second"}, "id": "2"}],
[], # Third call returns no tool calls (final answer)
]
)
agent = create_agent(
model=model,
tools=[sample_tool_agent],
middleware=[log_before_agent, log_before_model, log_after_model, log_after_agent],
)
agent.invoke(
{"messages": [HumanMessage("Test")]}, config={"configurable": {"thread_id": "abc"}}
)
assert execution_log == [
"before_agent",
"before_model",
"after_model",
"before_model",
"after_model",
"before_model",
"after_model",
"after_agent",
]
agent.invoke(
{"messages": [HumanMessage("Test")]}, config={"configurable": {"thread_id": "abc"}}
)
assert execution_log == [
"before_agent",
"before_model",
"after_model",
"before_model",
"after_model",
"before_model",
"after_model",
"after_agent",
"before_agent",
"before_model",
"after_model",
"before_model",
"after_model",
"before_model",
"after_model",
"after_agent",
]
| TestAgentHooksCombined |
python | google__jax | jax/experimental/mosaic/gpu/utils.py | {
"start": 6360,
"end": 11121
} | class ____:
ref: ir.Value
@property
def type(self) -> ir.Type:
return ir.MemRefType(self.ref.type)
def store(self, value: ir.Value, indices: Sequence[ir.Value]):
ptr = memref_ptr(memref_slice(self.ref, tuple(indices)))
multimem_store(ptr, value)
def multimem_store(ptr: ir.Value, value: ir.Value):
i32 = ir.IntegerType.get_signless(32)
if (bw := bitwidth(value.type)) not in {32, 64, 128}:
raise ValueError("Only 32-, 64- and 128-bit stores are supported")
vector_length = bw // 32
value = bitcast(value, ir.VectorType.get((vector_length,), i32))
regs = [
llvm.extractelement(value, arith.constant(i32, i))
for i in range(vector_length)
]
if vector_length == 1:
vec_ptx = "$1"
vec_mod = ""
else:
vec_ptx = f"{{{','.join(f'${i}' for i in range(1, vector_length + 1))}}}"
vec_mod = ".v" + str(vector_length)
# It's unclear to me why, but at least according to PTX docs, we have to use
# the floating-point instructions here to be able to store vectors.
llvm.inline_asm(
ir.Type.parse("!llvm.void"),
[ptr, *regs],
f"multimem.st.relaxed.sys.global{vec_mod}.f32 [$0], {vec_ptx};",
"l" + ",r" * len(regs),
has_side_effects=True,
)
MultimemReductionOp = Literal["add", "min", "max", "and", "or", "xor"]
def multimem_load_reduce(
ty: ir.Type,
ptr: ir.Value,
reduction: MultimemReductionOp,
is_signed: bool | None = None,
):
i32 = ir.IntegerType.get_signless(32)
if bitwidth(ty) not in {32, 64, 128}:
raise ValueError("Only 32-, 64- and 128-bit loads are supported")
if ir.VectorType.isinstance(ty):
vty = ir.VectorType(ty)
if len(vty.shape) > 1:
raise ValueError("Only 1D vectors are supported")
vector_length = vty.shape[0]
vector_i32_length = vector_length * bitwidth(vty.element_type) // 32
if ir.IntegerType.isinstance(vty.element_type):
# TODO(apaszke): Emulate this by unrolling.
if vector_length != 1:
raise NotImplementedError(
"Only single-element integer operations are supported"
)
if bitwidth(vty.element_type) not in {32, 64}:
raise NotImplementedError(
"Only 32-bit and 64-bit integer operations are supported"
)
if reduction in {"and", "or", "xor"}:
ptx_ty = f"b{bitwidth(vty.element_type)}"
elif reduction in {"min", "max", "add"}:
if is_signed is None:
raise ValueError(
"Signedness must be specified for integer min, max and add"
" reductions"
)
ptx_ty = f"{'s' if is_signed else 'u'}{bitwidth(vty.element_type)}"
else:
raise ValueError(f"Unsupported reduction operation: {reduction}")
elif ir.FloatType.isinstance(vty.element_type):
if reduction not in {"add", "min", "max"}:
raise ValueError("Only add, min and max are supported for floats")
if ir.F32Type.isinstance(vty.element_type):
if reduction != "add":
raise ValueError("Only add is supported for f32")
ptx_ty = "f32"
elif ir.BF16Type.isinstance(vty.element_type):
ptx_ty = "bf16x2"
elif ir.F16Type.isinstance(vty.element_type):
ptx_ty = "f16x2"
elif ir.Float8E5M2Type.isinstance(vty.element_type):
ptx_ty = "e5m2x4"
elif ir.Float8E4M3FNType.isinstance(vty.element_type):
ptx_ty = "e4m3x4"
else:
raise NotImplementedError(vty.element_type)
else:
raise NotImplementedError(vty.element_type)
else:
raise NotImplementedError(ty)
if vector_i32_length == 1:
vec_ptx = "$0"
vec_mod = ""
else:
vec_ptx = f"{{{','.join(f'${i}' for i in range(vector_i32_length))}}}"
vec_mod = ".v" + str(vector_i32_length)
# It's unclear to me why, but at least according to PTX docs, we have to use
# the floating-point instructions here to be able to store vectors.
acc_prec = ""
if vector_i32_length == 1:
asm_out_ty = i32
else:
asm_out_ty = ir.Type.parse(
f"!llvm.struct<({','.join(['i32'] * vector_i32_length)})>"
)
out_reg_struct = llvm.inline_asm(
asm_out_ty,
[ptr],
f"multimem.ld_reduce.relaxed.sys.global.{reduction}{acc_prec}{vec_mod}.{ptx_ty} {vec_ptx},"
f" [${vector_i32_length}];",
"=r," * vector_i32_length + "l",
has_side_effects=True,
)
if vector_i32_length == 1:
return bitcast(out_reg_struct, ty)
else:
out_regs = [
llvm.extractvalue(i32, out_reg_struct, [i])
for i in range(vector_i32_length)
]
vec_i32_ty = ir.VectorType.get((1,), i32)
return bitcast(
vector_concat([bitcast(out_reg, vec_i32_ty) for out_reg in out_regs]),
ty,
)
@dataclasses.dataclass(frozen=True)
| MultimemRef |
python | doocs__leetcode | solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.py | {
"start": 0,
"end": 357
} | class ____:
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
f = g = 0
ans = 0
mod = 10**9 + 7
for c in binary:
if c == "0":
g = (g + f) % mod
ans = 1
else:
f = (f + g + 1) % mod
ans = (ans + f + g) % mod
return ans
| Solution |
python | PrefectHQ__prefect | tests/test_artifacts.py | {
"start": 26776,
"end": 34735
} | class ____:
async def test_update_progress_artifact_updates_progress_async(
self, client: httpx.AsyncClient
):
progress = 0.0
@flow
async def my_flow():
artifact_id = await acreate_progress_artifact(progress)
assert isinstance(artifact_id, UUID)
response = await client.get(f"/artifacts/{artifact_id}")
my_artifact = schemas.core.Artifact.model_validate(response.json())
assert my_artifact.data == progress
assert my_artifact.type == "progress"
new_progress = 50.0
await aupdate_progress_artifact(artifact_id, new_progress)
response = await client.get(f"/artifacts/{artifact_id}")
assert response.status_code == 200
my_artifact = schemas.core.Artifact.model_validate(response.json())
assert my_artifact.data == new_progress
await my_flow()
def test_update_progress_artifact_updates_progress_sync(
self, sync_client: TestClient
):
progress = 0.0
@flow
def my_flow():
artifact_id = create_progress_artifact(progress)
assert isinstance(artifact_id, UUID)
response = sync_client.get(f"/artifacts/{artifact_id}")
my_artifact = schemas.core.Artifact.model_validate(response.json())
assert my_artifact.data == progress
assert my_artifact.type == "progress"
new_progress = 50.0
update_progress_artifact(artifact_id, new_progress)
response = sync_client.get(f"/artifacts/{artifact_id}")
assert response.status_code == 200
my_artifact = schemas.core.Artifact.model_validate(response.json())
assert my_artifact.data == new_progress
my_flow()
async def test_update_progress_artifact_in_task(self, client: httpx.AsyncClient):
@task
def my_task():
run_context = get_run_context()
assert isinstance(run_context, TaskRunContext)
assert run_context.task_run is not None
task_run_id = run_context.task_run.id
artifact_id = create_progress_artifact(
key="task-link-artifact-3",
progress=0.0,
description="my-artifact-description",
)
assert isinstance(artifact_id, UUID)
update_progress_artifact(artifact_id, 50.0)
return artifact_id, task_run_id
@flow
def my_flow():
run_context = get_run_context()
assert isinstance(run_context, FlowRunContext)
assert run_context.flow_run is not None
flow_run_id = run_context.flow_run.id
artifact_id, task_run_id = my_task()
return artifact_id, flow_run_id, task_run_id
my_artifact_id, flow_run_id, task_run_id = my_flow()
response = await client.get(f"/artifacts/{my_artifact_id}")
assert response.status_code == 200
my_progress_artifact = schemas.core.Artifact.model_validate(response.json())
assert my_progress_artifact.flow_run_id == flow_run_id
assert my_progress_artifact.task_run_id == task_run_id
assert my_progress_artifact.data == 50.0
assert my_progress_artifact.type == "progress"
assert my_progress_artifact.description == "my-artifact-description"
async def test_update_progress_artifact_in_async_task(
self, client: httpx.AsyncClient
):
@task
async def my_task():
run_context = get_run_context()
assert isinstance(run_context, TaskRunContext)
assert run_context.task_run is not None
task_run_id = run_context.task_run.id
artifact_id_coro = create_progress_artifact(
key="task-link-artifact-3",
progress=0.0,
description="my-artifact-description",
)
assert asyncio.iscoroutine(artifact_id_coro)
artifact_id = await artifact_id_coro
assert isinstance(artifact_id, UUID)
update_coro = update_progress_artifact(artifact_id, 50.0)
assert asyncio.iscoroutine(update_coro)
await update_coro
return artifact_id, task_run_id
@flow
async def my_flow():
run_context = get_run_context()
assert isinstance(run_context, FlowRunContext)
assert run_context.flow_run is not None
flow_run_id = run_context.flow_run.id
artifact_id, task_run_id = await my_task()
return artifact_id, flow_run_id, task_run_id
my_artifact_id, flow_run_id, task_run_id = await my_flow()
response = await client.get(f"/artifacts/{my_artifact_id}")
assert response.status_code == 200
my_progress_artifact = schemas.core.Artifact.model_validate(response.json())
assert my_progress_artifact.flow_run_id == flow_run_id
assert my_progress_artifact.task_run_id == task_run_id
assert my_progress_artifact.data == 50.0
assert my_progress_artifact.type == "progress"
assert my_progress_artifact.description == "my-artifact-description"
async def test_update_progress_artifact_in_flow(self, client: httpx.AsyncClient):
@flow
def my_flow():
run_context = get_run_context()
assert isinstance(run_context, FlowRunContext)
assert run_context.flow_run is not None
flow_run_id = run_context.flow_run.id
artifact_id = create_progress_artifact(
key="task-link-artifact-4",
progress=0.0,
description="my-artifact-description",
)
assert isinstance(artifact_id, UUID)
update_progress_artifact(artifact_id, 50.0)
return artifact_id, flow_run_id
my_artifact_id, flow_run_id = my_flow()
response = await client.get(f"/artifacts/{my_artifact_id}")
assert response.status_code == 200
my_progress_artifact = schemas.core.Artifact.model_validate(response.json())
assert my_progress_artifact.flow_run_id == flow_run_id
assert my_progress_artifact.task_run_id is None
assert my_progress_artifact.data == 50.0
assert my_progress_artifact.type == "progress"
assert my_progress_artifact.description == "my-artifact-description"
async def test_update_progress_artifact_in_async_flow(
self, client: httpx.AsyncClient
):
@flow
async def my_flow():
run_context = get_run_context()
assert isinstance(run_context, FlowRunContext)
assert run_context.flow_run is not None
flow_run_id = run_context.flow_run.id
artifact_id_coro = create_progress_artifact(
key="task-link-artifact-4",
progress=0.0,
description="my-artifact-description",
)
assert asyncio.iscoroutine(artifact_id_coro)
artifact_id = await artifact_id_coro
assert isinstance(artifact_id, UUID)
update_coro = update_progress_artifact(artifact_id, 50.0)
assert asyncio.iscoroutine(update_coro)
await update_coro
return artifact_id, flow_run_id
my_artifact_id, flow_run_id = await my_flow()
response = await client.get(f"/artifacts/{my_artifact_id}")
assert response.status_code == 200
my_progress_artifact = schemas.core.Artifact.model_validate(response.json())
assert my_progress_artifact.flow_run_id == flow_run_id
assert my_progress_artifact.task_run_id is None
assert my_progress_artifact.data == 50.0
assert my_progress_artifact.type == "progress"
assert my_progress_artifact.description == "my-artifact-description"
| TestUpdateArtifacts |
python | python-openxml__python-docx | tests/image/test_png.py | {
"start": 4914,
"end": 7530
} | class ____:
def it_can_construct_from_a_stream(self, stream_, _ChunkParser_, chunk_parser_, _Chunks__init_):
chunk_lst = [1, 2]
chunk_parser_.iter_chunks.return_value = iter(chunk_lst)
chunks = _Chunks.from_stream(stream_)
_ChunkParser_.from_stream.assert_called_once_with(stream_)
chunk_parser_.iter_chunks.assert_called_once_with()
_Chunks__init_.assert_called_once_with(ANY, chunk_lst)
assert isinstance(chunks, _Chunks)
def it_provides_access_to_the_IHDR_chunk(self, IHDR_fixture):
chunks, IHDR_chunk_ = IHDR_fixture
assert IHDR_chunk_ == chunks.IHDR
def it_provides_access_to_the_pHYs_chunk(self, pHYs_fixture):
chunks, expected_chunk = pHYs_fixture
assert chunks.pHYs == expected_chunk
def it_raises_if_theres_no_IHDR_chunk(self, no_IHDR_fixture):
chunks = no_IHDR_fixture
with pytest.raises(InvalidImageStreamError):
chunks.IHDR
# fixtures -------------------------------------------------------
@pytest.fixture
def _ChunkParser_(self, request, chunk_parser_):
_ChunkParser_ = class_mock(request, "docx.image.png._ChunkParser")
_ChunkParser_.from_stream.return_value = chunk_parser_
return _ChunkParser_
@pytest.fixture
def chunk_parser_(self, request):
return instance_mock(request, _ChunkParser)
@pytest.fixture
def _Chunks__init_(self, request):
return initializer_mock(request, _Chunks)
@pytest.fixture
def IHDR_fixture(self, IHDR_chunk_, pHYs_chunk_):
chunks = (IHDR_chunk_, pHYs_chunk_)
chunks = _Chunks(chunks)
return chunks, IHDR_chunk_
@pytest.fixture
def IHDR_chunk_(self, request):
return instance_mock(request, _IHDRChunk, type_name=PNG_CHUNK_TYPE.IHDR)
@pytest.fixture
def no_IHDR_fixture(self, pHYs_chunk_):
chunks = (pHYs_chunk_,)
chunks = _Chunks(chunks)
return chunks
@pytest.fixture
def pHYs_chunk_(self, request):
return instance_mock(request, _pHYsChunk, type_name=PNG_CHUNK_TYPE.pHYs)
@pytest.fixture(params=[True, False])
def pHYs_fixture(self, request, IHDR_chunk_, pHYs_chunk_):
has_pHYs_chunk = request.param
chunks = [IHDR_chunk_]
if has_pHYs_chunk:
chunks.append(pHYs_chunk_)
expected_chunk = pHYs_chunk_ if has_pHYs_chunk else None
chunks = _Chunks(chunks)
return chunks, expected_chunk
@pytest.fixture
def stream_(self, request):
return instance_mock(request, io.BytesIO)
| Describe_Chunks |
python | tornadoweb__tornado | tornado/iostream.py | {
"start": 3426,
"end": 3542
} | class ____(Exception):
"""Exception raised by `IOStream` methods when the buffer is full."""
| StreamBufferFullError |
python | openai__openai-python | src/openai/types/responses/response_web_search_call_in_progress_event.py | {
"start": 213,
"end": 704
} | class ____(BaseModel):
item_id: str
"""Unique ID for the output item associated with the web search call."""
output_index: int
"""The index of the output item that the web search call is associated with."""
sequence_number: int
"""The sequence number of the web search call being processed."""
type: Literal["response.web_search_call.in_progress"]
"""The type of the event. Always `response.web_search_call.in_progress`."""
| ResponseWebSearchCallInProgressEvent |
python | doocs__leetcode | lcof2/剑指 Offer II 006. 排序数组中两个数字之和/Solution.py | {
"start": 0,
"end": 298
} | class ____:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
n = len(numbers)
for i in range(n - 1):
x = target - numbers[i]
j = bisect_left(numbers, x, lo=i + 1)
if j < n and numbers[j] == x:
return [i, j]
| Solution |
python | modin-project__modin | modin/core/storage_formats/pandas/groupby.py | {
"start": 9114,
"end": 18208
} | class ____:
"""Provide MapReduce, Range-Partitioning and Full-Column implementations for 'pivot_table()'."""
@classmethod
def map_reduce_impl(
cls, qc, unique_keys, drop_column_level, pivot_kwargs
): # noqa: PR01
"""Compute 'pivot_table()' using MapReduce implementation."""
if pivot_kwargs["margins"]:
raise NotImplementedError(
"MapReduce 'pivot_table' implementation doesn't support 'margins=True' parameter"
)
index, columns, values = (
pivot_kwargs["index"],
pivot_kwargs["columns"],
pivot_kwargs["values"],
)
aggfunc = pivot_kwargs["aggfunc"]
if not GroupbyReduceImpl.has_impl_for(aggfunc):
raise NotImplementedError(
"MapReduce 'pivot_table' implementation only supports 'aggfuncs' that are implemented in 'GroupbyReduceImpl'"
)
if len(set(index).intersection(columns)) > 0:
raise NotImplementedError(
"MapReduce 'pivot_table' implementation doesn't support intersections of 'index' and 'columns'"
)
to_group, keys_columns = cls._separate_data_from_grouper(
qc, values, unique_keys
)
to_unstack = columns if index else None
result = GroupbyReduceImpl.build_qc_method(
aggfunc,
finalizer_fn=lambda df: cls._pivot_table_from_groupby(
df,
pivot_kwargs["dropna"],
drop_column_level,
to_unstack,
pivot_kwargs["fill_value"],
),
)(
to_group,
by=keys_columns,
axis=0,
groupby_kwargs={
"observed": pivot_kwargs["observed"],
"sort": pivot_kwargs["sort"],
},
agg_args=(),
agg_kwargs={},
drop=True,
)
if to_unstack is None:
result = result.transpose()
return result
@classmethod
def full_axis_impl(
cls, qc, unique_keys, drop_column_level, pivot_kwargs
): # noqa: PR01
"""Compute 'pivot_table()' using full-column-axis implementation."""
index, columns, values = (
pivot_kwargs["index"],
pivot_kwargs["columns"],
pivot_kwargs["values"],
)
to_group, keys_columns = cls._separate_data_from_grouper(
qc, values, unique_keys
)
def applyier(df, other): # pragma: no cover
"""
Build pivot table for a single partition.
Parameters
----------
df : pandas.DataFrame
Partition of the self frame.
other : pandas.DataFrame
Broadcasted partition that contains `value` columns
of the self frame.
Returns
-------
pandas.DataFrame
Pivot table for this particular partition.
"""
concated = pandas.concat([df, other], axis=1, copy=False)
# to reduce peak memory consumption
del df, other
result = pandas.pivot_table(
concated,
**pivot_kwargs,
)
# to reduce peak memory consumption
del concated
# if only one value is specified, removing level that maps
# columns from `values` to the actual values
if drop_column_level is not None:
result = result.droplevel(drop_column_level, axis=1)
# in that case Pandas transposes the result of `pivot_table`,
# transposing it back to be consistent with column axis values along
# different partitions
if len(index) == 0 and len(columns) > 0:
common_type = find_common_type(result.dtypes.tolist())
# TODO: remove find_common_type+astype after pandas fix the following issue
# transpose loses dtypes: https://github.com/pandas-dev/pandas/issues/43337
result = result.transpose().astype(common_type, copy=False)
return result
result = qc.__constructor__(
to_group._modin_frame.broadcast_apply_full_axis(
axis=0, func=applyier, other=keys_columns._modin_frame
)
)
# transposing the result again, to be consistent with Pandas result
if len(index) == 0 and len(columns) > 0:
result = result.transpose()
return result
@classmethod
def range_partition_impl(
cls, qc, unique_keys, drop_column_level, pivot_kwargs
): # noqa: PR01
"""Compute 'pivot_table()' using Range-Partitioning implementation."""
if pivot_kwargs["margins"]:
raise NotImplementedError(
"Range-partitioning 'pivot_table' implementation doesn't support 'margins=True' parameter"
)
index, columns, values = (
pivot_kwargs["index"],
pivot_kwargs["columns"],
pivot_kwargs["values"],
)
if len(set(index).intersection(columns)) > 0:
raise NotImplementedError(
"Range-partitioning 'pivot_table' implementation doesn't support intersections of 'index' and 'columns'"
)
if values is not None:
to_take = list(np.unique(list(index) + list(columns) + list(values)))
qc = qc.getitem_column_array(to_take, ignore_order=True)
to_unstack = columns if index else None
groupby_result = qc._groupby_shuffle(
by=list(unique_keys),
agg_func=pivot_kwargs["aggfunc"],
axis=0,
groupby_kwargs={
"observed": pivot_kwargs["observed"],
"sort": pivot_kwargs["sort"],
},
agg_args=(),
agg_kwargs={},
drop=True,
)
# the length of 'groupby_result' is typically really small here,
# so it's okay to call full-column function
result = groupby_result._modin_frame.apply_full_axis(
axis=0,
func=lambda df: cls._pivot_table_from_groupby(
df,
pivot_kwargs["dropna"],
drop_column_level,
to_unstack,
pivot_kwargs["fill_value"],
# FIXME: Range-partitioning impl has a problem with the resulting order in case of multiple grouping keys,
# so passing 'sort=True' explicitly in this case
# https://github.com/modin-project/modin/issues/6875
sort=pivot_kwargs["sort"] if len(unique_keys) > 1 else False,
),
)
if to_unstack is None:
result = result.transpose()
return qc.__constructor__(result)
@staticmethod
def _pivot_table_from_groupby(
df, dropna, drop_column_level, to_unstack, fill_value, sort=False
):
"""
Convert group by aggregation result to a pivot table.
Parameters
----------
df : pandas.DataFrame
Group by aggregation result.
dropna : bool
Whether to drop NaN columns.
drop_column_level : int or None
An extra columns level to drop.
to_unstack : list of labels or None
Group by keys to pass to ``.unstack()``. Reperent `columns` parameter
for ``.pivot_table()``.
fill_value : bool
Fill value for NaN values.
sort : bool, default: False
Whether to sort the result along index.
Returns
-------
pandas.DataFrame
"""
if df.index.nlevels > 1 and to_unstack is not None:
df = df.unstack(level=to_unstack)
if drop_column_level is not None:
df = df.droplevel(drop_column_level, axis=1)
if dropna:
df = df.dropna(axis=1, how="all")
if fill_value is not None:
df = df.fillna(fill_value, downcast="infer")
if sort:
df = df.sort_index(axis=0)
return df
@staticmethod
def _separate_data_from_grouper(qc, values, unique_keys):
"""
Split `qc` for key columns to group by and values to aggregate.
Parameters
----------
qc : PandasQueryCompiler
values : list of labels or None
List of columns to aggregate. ``None`` means all columns except 'unique_keys'.
unique_keys : list of labels
List of key columns to group by.
Returns
-------
to_aggregate : PandasQueryCompiler
keys_to_group : PandasQueryCompiler
"""
if values is None:
to_aggregate = qc.drop(columns=unique_keys)
else:
to_aggregate = qc.getitem_column_array(np.unique(values), ignore_order=True)
keys_to_group = qc.getitem_column_array(unique_keys, ignore_order=True)
return to_aggregate, keys_to_group
| PivotTableImpl |
python | getsentry__sentry | src/sentry/apidocs/examples/dashboard_examples.py | {
"start": 5613,
"end": 6478
} | class ____:
DASHBOARD_GET_RESPONSE = [
OpenApiExample(
"Dashboard GET response",
value=DASHBOARD_OBJECT,
status_codes=["200"],
response_only=True,
)
]
DASHBOARD_PUT_RESPONSE = [
OpenApiExample(
"Dashboard PUT response",
value=DASHBOARD_OBJECT,
status_codes=["200"],
response_only=True,
)
]
DASHBOARD_POST_RESPONSE = [
OpenApiExample(
"Create Dashboard",
value=DASHBOARD_OBJECT,
status_codes=["201"],
response_only=True,
)
]
DASHBOARDS_QUERY_RESPONSE = [
OpenApiExample(
"Query Dashboards",
value=DASHBOARDS_OBJECT,
status_codes=["200"],
response_only=True,
)
]
| DashboardExamples |
python | numba__numba | numba/core/debuginfo.py | {
"start": 2037,
"end": 17525
} | class ____(AbstractDIBuilder):
DWARF_VERSION = 4
DEBUG_INFO_VERSION = 3
DBG_CU_NAME = 'llvm.dbg.cu'
_DEBUG = False
def __init__(self, module, filepath, cgctx, directives_only):
self.module = module
self.filepath = os.path.abspath(filepath)
self.difile = self._di_file()
self.subprograms = []
self.cgctx = cgctx
if directives_only:
self.emission_kind = 'DebugDirectivesOnly'
else:
self.emission_kind = 'FullDebug'
self.initialize()
def initialize(self):
# Create the compile unit now because it is referenced when
# constructing subprograms
self.dicompileunit = self._di_compile_unit()
def _var_type(self, lltype, size, datamodel=None):
if self._DEBUG:
print("-->", lltype, size, datamodel,
getattr(datamodel, 'fe_type', 'NO FE TYPE'))
m = self.module
bitsize = _BYTE_SIZE * size
int_type = ir.IntType,
real_type = ir.FloatType, ir.DoubleType
# For simple numeric types, choose the closest encoding.
# We treat all integers as unsigned when there's no known datamodel.
if isinstance(lltype, int_type + real_type):
if datamodel is None:
# This is probably something like an `i8*` member of a struct
name = str(lltype)
if isinstance(lltype, int_type):
ditok = 'DW_ATE_unsigned'
else:
ditok = 'DW_ATE_float'
else:
# This is probably a known int/float scalar type
name = str(datamodel.fe_type)
if isinstance(datamodel.fe_type, types.Integer):
if datamodel.fe_type.signed:
ditok = 'DW_ATE_signed'
else:
ditok = 'DW_ATE_unsigned'
else:
ditok = 'DW_ATE_float'
mdtype = m.add_debug_info('DIBasicType', {
'name': name,
'size': bitsize,
'encoding': ir.DIToken(ditok),
})
elif isinstance(datamodel, ComplexModel):
# TODO: Is there a better way of determining "this is a complex
# number"?
#
# NOTE: Commented below is the way to generate the metadata for a
# C99 complex type that's directly supported by DWARF. Numba however
# generates a struct with real/imag cf. CPython to give a more
# pythonic feel to inspection.
#
# mdtype = m.add_debug_info('DIBasicType', {
# 'name': f"{datamodel.fe_type} ({str(lltype)})",
# 'size': bitsize,
# 'encoding': ir.DIToken('DW_ATE_complex_float'),
#})
meta = []
offset = 0
for ix, name in enumerate(('real', 'imag')):
component = lltype.elements[ix]
component_size = self.cgctx.get_abi_sizeof(component)
component_basetype = m.add_debug_info('DIBasicType', {
'name': str(component),
'size': _BYTE_SIZE * component_size, # bits
'encoding': ir.DIToken('DW_ATE_float'),
})
derived_type = m.add_debug_info('DIDerivedType', {
'tag': ir.DIToken('DW_TAG_member'),
'name': name,
'baseType': component_basetype,
'size': _BYTE_SIZE * component_size, # DW_TAG_member size is in bits
'offset': offset,
})
meta.append(derived_type)
offset += (_BYTE_SIZE * component_size) # offset is in bits
mdtype = m.add_debug_info('DICompositeType', {
'tag': ir.DIToken('DW_TAG_structure_type'),
'name': f"{datamodel.fe_type} ({str(lltype)})",
'identifier': str(lltype),
'elements': m.add_metadata(meta),
'size': offset,
}, is_distinct=True)
elif isinstance(datamodel, UniTupleModel):
element = lltype.element
el_size = self.cgctx.get_abi_sizeof(element)
basetype = self._var_type(element, el_size)
name = f"{datamodel.fe_type} ({str(lltype)})"
count = size // el_size
mdrange = m.add_debug_info('DISubrange', {
'count': count,
})
mdtype = m.add_debug_info('DICompositeType', {
'tag': ir.DIToken('DW_TAG_array_type'),
'baseType': basetype,
'name': name,
'size': bitsize,
'identifier': str(lltype),
'elements': m.add_metadata([mdrange]),
})
elif isinstance(lltype, ir.PointerType):
model = getattr(datamodel, '_pointee_model', None)
basetype = self._var_type(lltype.pointee,
self.cgctx.get_abi_sizeof(lltype.pointee),
model)
mdtype = m.add_debug_info('DIDerivedType', {
'tag': ir.DIToken('DW_TAG_pointer_type'),
'baseType': basetype,
'size': _BYTE_SIZE * self.cgctx.get_abi_sizeof(lltype)
})
elif isinstance(lltype, ir.LiteralStructType):
# Struct type
meta = []
offset = 0
if datamodel is None or not datamodel.inner_models():
name = f"Anonymous struct ({str(lltype)})"
for field_id, element in enumerate(lltype.elements):
size = self.cgctx.get_abi_sizeof(element)
basetype = self._var_type(element, size)
derived_type = m.add_debug_info('DIDerivedType', {
'tag': ir.DIToken('DW_TAG_member'),
'name': f'<field {field_id}>',
'baseType': basetype,
'size': _BYTE_SIZE * size, # DW_TAG_member size is in bits
'offset': offset,
})
meta.append(derived_type)
offset += (_BYTE_SIZE * size) # offset is in bits
else:
name = f"{datamodel.fe_type} ({str(lltype)})"
for element, field, model in zip(lltype.elements,
datamodel._fields,
datamodel.inner_models()):
size = self.cgctx.get_abi_sizeof(element)
basetype = self._var_type(element, size, datamodel=model)
derived_type = m.add_debug_info('DIDerivedType', {
'tag': ir.DIToken('DW_TAG_member'),
'name': field,
'baseType': basetype,
'size': _BYTE_SIZE * size, # DW_TAG_member size is in bits
'offset': offset,
})
meta.append(derived_type)
offset += (_BYTE_SIZE * size) # offset is in bits
mdtype = m.add_debug_info('DICompositeType', {
'tag': ir.DIToken('DW_TAG_structure_type'),
'name': name,
'identifier': str(lltype),
'elements': m.add_metadata(meta),
'size': offset,
}, is_distinct=True)
elif isinstance(lltype, ir.ArrayType):
element = lltype.element
el_size = self.cgctx.get_abi_sizeof(element)
basetype = self._var_type(element, el_size)
count = size // el_size
mdrange = m.add_debug_info('DISubrange', {
'count': count,
})
mdtype = m.add_debug_info('DICompositeType', {
'tag': ir.DIToken('DW_TAG_array_type'),
'baseType': basetype,
'name': str(lltype),
'size': bitsize,
'identifier': str(lltype),
'elements': m.add_metadata([mdrange]),
})
else:
# For all other types, describe it as sequence of bytes
count = size
mdrange = m.add_debug_info('DISubrange', {
'count': count,
})
mdbase = m.add_debug_info('DIBasicType', {
'name': 'byte',
'size': _BYTE_SIZE,
'encoding': ir.DIToken('DW_ATE_unsigned_char'),
})
mdtype = m.add_debug_info('DICompositeType', {
'tag': ir.DIToken('DW_TAG_array_type'),
'baseType': mdbase,
'name': str(lltype),
'size': bitsize,
'identifier': str(lltype),
'elements': m.add_metadata([mdrange]),
})
return mdtype
def mark_variable(self, builder, allocavalue, name, lltype, size, line,
datamodel=None, argidx=None):
arg_index = 0 if argidx is None else argidx
m = self.module
fnty = ir.FunctionType(ir.VoidType(), [ir.MetaDataType()] * 3)
decl = cgutils.get_or_insert_function(m, fnty, 'llvm.dbg.declare')
mdtype = self._var_type(lltype, size, datamodel=datamodel)
name = name.replace('.', '$') # for gdb to work correctly
mdlocalvar = m.add_debug_info('DILocalVariable', {
'name': name,
'arg': arg_index,
'scope': self.subprograms[-1],
'file': self.difile,
'line': line,
'type': mdtype,
})
mdexpr = m.add_debug_info('DIExpression', {})
return builder.call(decl, [allocavalue, mdlocalvar, mdexpr])
def mark_location(self, builder, line):
builder.debug_metadata = self._add_location(line)
def mark_subprogram(self, function, qualname, argnames, argtypes, line):
name = qualname
argmap = dict(zip(argnames, argtypes))
di_subp = self._add_subprogram(name=name, linkagename=function.name,
line=line, function=function,
argmap=argmap)
function.set_metadata("dbg", di_subp)
def finalize(self):
dbgcu = cgutils.get_or_insert_named_metadata(self.module, self.DBG_CU_NAME)
dbgcu.add(self.dicompileunit)
self._set_module_flags()
#
# Internal APIs
#
def _set_module_flags(self):
"""Set the module flags metadata
"""
module = self.module
mflags = cgutils.get_or_insert_named_metadata(module, 'llvm.module.flags')
# Set *require* behavior to warning
# See http://llvm.org/docs/LangRef.html#module-flags-metadata
require_warning_behavior = self._const_int(2)
if self.DWARF_VERSION is not None:
dwarf_version = module.add_metadata([
require_warning_behavior,
"Dwarf Version",
self._const_int(self.DWARF_VERSION)
])
if dwarf_version not in mflags.operands:
mflags.add(dwarf_version)
debuginfo_version = module.add_metadata([
require_warning_behavior,
"Debug Info Version",
self._const_int(self.DEBUG_INFO_VERSION)
])
if debuginfo_version not in mflags.operands:
mflags.add(debuginfo_version)
def _add_subprogram(self, name, linkagename, line, function, argmap):
"""Emit subprogram metadata
"""
subp = self._di_subprogram(name, linkagename, line, function, argmap)
self.subprograms.append(subp)
return subp
def _add_location(self, line):
"""Emit location metatdaa
"""
loc = self._di_location(line)
return loc
@classmethod
def _const_int(cls, num, bits=32):
"""Util to create constant int in metadata
"""
return ir.IntType(bits)(num)
@classmethod
def _const_bool(cls, boolean):
"""Util to create constant boolean in metadata
"""
return ir.IntType(1)(boolean)
#
# Helpers to emit the metadata nodes
#
def _di_file(self):
return self.module.add_debug_info('DIFile', {
'directory': os.path.dirname(self.filepath),
'filename': os.path.basename(self.filepath),
})
def _di_compile_unit(self):
return self.module.add_debug_info('DICompileUnit', {
'language': ir.DIToken('DW_LANG_C_plus_plus'),
'file': self.difile,
# Numba has to pretend to be clang to ensure the prologue is skipped
# correctly in gdb. See:
# https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=gdb/amd64-tdep.c;h=e563d369d8cb3eb3c2f732c2fa850ec70ba8d63b;hb=a4b0231e179607e47b1cdf1fe15c5dc25e482fad#l2521
# Note the "producer_is_llvm" call to specialise the prologue
# handling, this is defined here:
# https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=gdb/producer.c;h=cdfd80d904c09394febd18749bb90359b2d128cc;hb=a4b0231e179607e47b1cdf1fe15c5dc25e482fad#l124
# and to get a match for this condition the 'producer' must start
# with "clang ", hence the following...
'producer': 'clang (Numba)',
'runtimeVersion': 0,
'isOptimized': config.OPT != 0,
'emissionKind': ir.DIToken(self.emission_kind),
}, is_distinct=True)
def _di_subroutine_type(self, line, function, argmap):
# The function call conv needs encoding.
llfunc = function
md = []
for idx, llarg in enumerate(llfunc.args):
if not llarg.name.startswith('arg.'):
name = llarg.name.replace('.', '$') # for gdb to work correctly
lltype = llarg.type
size = self.cgctx.get_abi_sizeof(lltype)
mdtype = self._var_type(lltype, size, datamodel=None)
md.append(mdtype)
for idx, (name, nbtype) in enumerate(argmap.items()):
name = name.replace('.', '$') # for gdb to work correctly
datamodel = self.cgctx.data_model_manager[nbtype]
lltype = self.cgctx.get_value_type(nbtype)
size = self.cgctx.get_abi_sizeof(lltype)
mdtype = self._var_type(lltype, size, datamodel=datamodel)
md.append(mdtype)
return self.module.add_debug_info('DISubroutineType', {
'types': self.module.add_metadata(md),
})
def _di_subprogram(self, name, linkagename, line, function, argmap):
return self.module.add_debug_info('DISubprogram', {
'name': name,
'linkageName': linkagename,
'scope': self.difile,
'file': self.difile,
'line': line,
'type': self._di_subroutine_type(line, function, argmap),
'isLocal': False,
'isDefinition': True,
'scopeLine': line,
'isOptimized': config.OPT != 0,
'unit': self.dicompileunit,
}, is_distinct=True)
def _di_location(self, line):
return self.module.add_debug_info('DILocation', {
'line': line,
'column': 1,
'scope': self.subprograms[-1],
})
| DIBuilder |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 107383,
"end": 114722
} | class ____(GenericView):
@staticmethod
def handle_negative_index(idx: Expr, size: Expr) -> Expr:
idx = sympy.expand(idx)
size = sympy.expand(size)
evaluate_expr = V.graph.sizevars.shape_env.evaluate_expr
if evaluate_expr(sympy.Lt(idx, 0)):
idx = idx + size
return idx
@classmethod
def create(cls, x: IRNode, new_size: Sequence[Expr]) -> IRNode: # type: ignore[override]
assert isinstance(new_size, Sequence), type(new_size)
old_size, new_size = cls.resolve_negative_size(x.get_size(), new_size)
# Skip pointless views
if V.graph.sizevars.statically_known_list_equals(old_size, new_size):
return x
unbacked_symbols_in_sizes = False
if (
len(free_unbacked_symbols(old_size)) > 0
or len(free_unbacked_symbols(new_size)) > 0
):
unbacked_symbols_in_sizes = True
if 0 in new_size:
def fake_reindex(index: Any) -> tuple[int, ...]:
return tuple([0] * len(old_size))
return cls(data=x, size=list(new_size), reindex=fake_reindex)
# TODO: a new class for FixedTransferLayout that output layout is constrained by input layout
elif is_contiguous_storage_and_layout(x) or unbacked_symbols_in_sizes:
if unbacked_symbols_in_sizes and (not is_contiguous_storage_and_layout(x)):
# realize x; otherwise, the dynamic_reshape_indexer below will fail
# due to the size_hint's inability to process unbacked SymInts
# TODO: unbacked should not diverge from backed in determining striding
# Need to require contiguous here instead of realize, see:
# https://github.com/pytorch/pytorch/issues/145561
x = ExternKernel.require_contiguous(x)
storage, old_layout = as_storage_and_layout(x, want_contiguous=True)
new_layout = FixedLayout(
old_layout.device,
old_layout.dtype,
new_size,
FlexibleLayout.contiguous_strides(new_size),
old_layout.offset,
old_layout.is_pinned,
)
return ReinterpretView(data=storage, layout=new_layout)
reindex = cls.dynamic_reshape_indexer(old_size, new_size)
return cls(data=x, size=list(new_size), reindex=reindex)
@staticmethod
def resolve_negative_size(
old_size: Sequence[Expr], new_size: Sequence[Expr]
) -> tuple[list[Expr], list[Expr]]:
new_size = [V.graph.sizevars.simplify(x) for x in new_size]
old_size = [V.graph.sizevars.simplify(x) for x in old_size]
new_size = list(new_size)
for i in range(len(new_size)):
if new_size[i] == -1:
new_size[i] = sympy.S.One
new_size[i] = CleanDiv(sympy_product(old_size), sympy_product(new_size))
break
V.graph.sizevars.check_equals(sympy_product(old_size), sympy_product(new_size))
return old_size, new_size
@classmethod
def dynamic_reshape_indexer(
cls,
old_size: Sequence[_IntLike],
new_size: Sequence[_IntLike],
dense_dim: Optional[int] = None,
) -> Callable[[Sequence[_T]], Sequence[_V]]:
try:
reindex = cls._dynamic_reshape_indexer(old_size, new_size, dense_dim)
except (AssertionError, IndexError):
# optimistic algorithm failed, lets do a fallback
flat = [sympy_product(old_size)]
reindex1 = cls._dynamic_reshape_indexer(old_size, flat)
reindex2 = cls._dynamic_reshape_indexer(flat, new_size)
reindex = fuse_reindexing(reindex1, reindex2)
return reindex
@staticmethod
def _dynamic_reshape_indexer(
old_size: Sequence[Expr],
new_size: Sequence[Expr],
dense_dim: Optional[int] = None,
) -> Callable[[Sequence[Expr]], Sequence[Expr]]:
"""
Perform a reshape entirely by modifying indexing math
"""
size_hint = V.graph.sizevars.size_hint
# TODO: These symbols may not escape, if they don't assert so and
# treat them as temporary
vars = [
sympy_index_symbol_with_prefix(SymT.VIEW, i) for i in range(len(new_size))
]
stack_new = list(zip(vars, new_size))
stack_old = list(old_size)
# process the dense dim first
reordering_dense_dim = (
dense_dim is not None
and dense_dim != len(stack_old) - 1
and len(new_size) == 1
)
if reordering_dense_dim:
assert dense_dim is not None # mypy
old_dim = stack_old.pop(dense_dim)
stack_old.append(old_dim)
view_expr = []
while stack_new and stack_old:
size_old = stack_old.pop()
var, size_new = stack_new.pop()
if size_old == 1:
view_expr.append(sympy.S.Zero)
stack_new.append((var, size_new)) # re-add
elif size_new == 1:
stack_old.append(size_old) # re-add
elif size_hint(size_new) == size_hint(size_old):
view_expr.append(var)
V.graph.sizevars.check_equals(size_new, size_old)
elif size_hint(size_new) < size_hint(size_old):
while size_hint(size_new) < size_hint(size_old):
var2, size_new2 = stack_new.pop()
var = var2 * size_new + var
size_new = size_new * size_new2
view_expr.append(var)
V.graph.sizevars.check_equals(size_new, size_old)
elif size_hint(size_new) > size_hint(size_old):
divisor = sympy.S.One
modulus = size_old
view_expr.append(ModularIndexing(var, divisor, modulus))
divisor = divisor * modulus
while size_hint(size_new) > size_hint(size_old):
modulus = stack_old.pop()
view_expr.append(ModularIndexing(var, divisor, modulus))
divisor = divisor * modulus
size_old = size_old * modulus
V.graph.sizevars.check_equals(size_new, size_old)
else:
raise AssertionError
while stack_old:
size_old = stack_old.pop()
V.graph.sizevars.check_equals(size_old, 1)
view_expr.append(sympy.S.Zero)
while stack_new:
var, size_new = stack_new.pop()
V.graph.sizevars.check_equals(size_new, 1)
if dense_dim is not None and len(new_size) == 1:
view_expr.reverse()
# Move the last expression (dense dim) to its original position
dense_expr = view_expr.pop()
view_expr.insert(dense_dim, dense_expr)
else:
view_expr.reverse()
assert len(view_expr) == len(old_size)
def reindex(
index: Sequence[Expr],
) -> Sequence[Expr]:
assert len(index) == len(vars), (len(index), len(vars))
replacements = dict(zip(vars, index))
return tuple(sympy_subs(x, replacements) for x in view_expr)
return reindex
@ir_dataclass
| View |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 24120,
"end": 24543
} | class ____(RequestHandler):
def get(self):
if self.get_argument("permanent", None) is not None:
self.redirect("/", permanent=bool(int(self.get_argument("permanent"))))
elif self.get_argument("status", None) is not None:
self.redirect("/", status=int(self.get_argument("status")))
else:
raise Exception("didn't get permanent or status arguments")
| RedirectHandler |
python | donnemartin__system-design-primer | solutions/system_design/web_crawler/web_crawler_snippets.py | {
"start": 1183,
"end": 2202
} | class ____(object):
def __init__(self, pages, data_store, reverse_index_queue, doc_index_queue):
self.pages = pages
self.data_store = data_store
self.reverse_index_queue = reverse_index_queue
self.doc_index_queue = doc_index_queue
def crawl_page(self, page):
for url in page.child_urls:
self.data_store.add_link_to_crawl(url)
self.reverse_index_queue.generate(page)
self.doc_index_queue.generate(page)
self.data_store.remove_link_to_crawl(page.url)
self.data_store.insert_crawled_link(page.url, page.signature)
def crawl(self):
while True:
page = self.data_store.extract_max_priority_page()
if page is None:
break
if self.data_store.crawled_similar(page.signature):
self.data_store.reduce_priority_link_to_crawl(page.url)
else:
self.crawl_page(page)
page = self.data_store.extract_max_priority_page()
| Crawler |
python | dask__dask | dask/tests/test_delayed.py | {
"start": 3029,
"end": 3093
} | class ____:
a: int
@dataclass(frozen=True)
| ANonFrozenDataClass |
python | nedbat__coveragepy | coverage/parser.py | {
"start": 20721,
"end": 21410
} | class ____(Block):
"""A block on the block stack representing a `for` or `while` loop."""
def __init__(self, start: TLineNo) -> None:
# The line number where the loop starts.
self.start = start
# A set of ArcStarts, the arcs from break statements exiting this loop.
self.break_exits: set[ArcStart] = set()
def process_break_exits(self, exits: set[ArcStart], add_arc: TAddArcFn) -> bool:
self.break_exits.update(exits)
return True
def process_continue_exits(self, exits: set[ArcStart], add_arc: TAddArcFn) -> bool:
for xit in exits:
add_arc(xit.lineno, self.start, xit.cause)
return True
| LoopBlock |
python | PrefectHQ__prefect | src/prefect/server/events/ordering/__init__.py | {
"start": 1148,
"end": 1231
} | class ____(Protocol):
CausalOrdering: type["CausalOrdering"]
| CausalOrderingModule |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pep8_naming/N815.py | {
"start": 97,
"end": 427
} | class ____:
lower = 0
CONSTANT = 0
mixedCase = 0
_mixedCase = 0
mixed_Case = 0
myObj1 = collections.namedtuple("MyObj1", ["a", "b"])
myObj2 = namedtuple("MyObj2", ["a", "b"])
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
| C |
python | astropy__astropy | astropy/modeling/tests/test_models.py | {
"start": 41294,
"end": 41493
} | class ____(Model):
slope = Parameter()
intercept = Parameter()
_separable = False
@staticmethod
def evaluate(x, slope, intercept):
return slope * x + intercept
| ModelDefault |
python | openai__openai-python | src/openai/types/realtime/realtime_response_create_params_param.py | {
"start": 1116,
"end": 4316
} | class ____(TypedDict, total=False):
audio: RealtimeResponseCreateAudioOutputParam
"""Configuration for audio input and output."""
conversation: Union[str, Literal["auto", "none"]]
"""Controls which conversation the response is added to.
Currently supports `auto` and `none`, with `auto` as the default value. The
`auto` value means that the contents of the response will be added to the
default conversation. Set this to `none` to create an out-of-band response which
will not add items to default conversation.
"""
input: Iterable[ConversationItemParam]
"""Input items to include in the prompt for the model.
Using this field creates a new context for this Response instead of using the
default conversation. An empty array `[]` will clear the context for this
Response. Note that this can include references to items that previously
appeared in the session using their id.
"""
instructions: str
"""The default system instructions (i.e.
system message) prepended to model calls. This field allows the client to guide
the model on desired responses. The model can be instructed on response content
and format, (e.g. "be extremely succinct", "act friendly", "here are examples of
good responses") and on audio behavior (e.g. "talk quickly", "inject emotion
into your voice", "laugh frequently"). The instructions are not guaranteed to be
followed by the model, but they provide guidance to the model on the desired
behavior. Note that the server sets default instructions which will be used if
this field is not set and are visible in the `session.created` event at the
start of the session.
"""
max_output_tokens: Union[int, Literal["inf"]]
"""
Maximum number of output tokens for a single assistant response, inclusive of
tool calls. Provide an integer between 1 and 4096 to limit output tokens, or
`inf` for the maximum available tokens for a given model. Defaults to `inf`.
"""
metadata: Optional[Metadata]
"""Set of 16 key-value pairs that can be attached to an object.
This can be useful for storing additional information about the object in a
structured format, and querying for objects via API or the dashboard.
Keys are strings with a maximum length of 64 characters. Values are strings with
a maximum length of 512 characters.
"""
output_modalities: List[Literal["text", "audio"]]
"""
The set of modalities the model used to respond, currently the only possible
values are `[\"audio\"]`, `[\"text\"]`. Audio output always include a text
transcript. Setting the output to mode `text` will disable audio output from the
model.
"""
prompt: Optional[ResponsePromptParam]
"""
Reference to a prompt template and its variables.
[Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts).
"""
tool_choice: ToolChoice
"""How the model chooses tools.
Provide one of the string modes or force a specific function/MCP tool.
"""
tools: Iterable[Tool]
"""Tools available to the model."""
| RealtimeResponseCreateParamsParam |
python | kubernetes-client__python | kubernetes/client/api/storagemigration_api.py | {
"start": 543,
"end": 5205
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_api_group(self, **kwargs): # noqa: E501
"""get_api_group # noqa: E501
get information of a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_group(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1APIGroup
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.get_api_group_with_http_info(**kwargs) # noqa: E501
def get_api_group_with_http_info(self, **kwargs): # noqa: E501
"""get_api_group # noqa: E501
get information of a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_group_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1APIGroup, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_group" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/storagemigration.k8s.io/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIGroup', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
| StoragemigrationApi |
python | django__django | tests/admin_inlines/admin.py | {
"start": 7219,
"end": 7643
} | class ____(admin.TabularInline):
model = BinaryTree
def get_extra(self, request, obj=None, **kwargs):
extra = 2
if obj:
return extra - obj.binarytree_set.count()
return extra
def get_max_num(self, request, obj=None, **kwargs):
max_num = 3
if obj:
return max_num - obj.binarytree_set.count()
return max_num
# admin for #19524
| BinaryTreeAdmin |
python | django-haystack__django-haystack | test_haystack/test_models.py | {
"start": 384,
"end": 525
} | class ____(std_logging.Handler):
logs_seen = []
def emit(self, record):
CaptureHandler.logs_seen.append(record)
| CaptureHandler |
python | getsentry__sentry | src/sentry/analytics/events/sentryapp_issue_webhooks.py | {
"start": 359,
"end": 470
} | class ____(SentryAppIssueEvent):
pass
@analytics.eventclass("sentry_app.issue.ignored")
| SentryAppIssueCreated |
python | tensorflow__tensorflow | tensorflow/python/distribute/test_util_test.py | {
"start": 1605,
"end": 2606
} | class ____(test.TestCase, parameterized.TestCase):
def testOne(self, strategy):
@def_function.function
def f():
return array_ops.ones((), dtypes.float32)
results = test_util.gather(strategy, strategy.run(f))
self.assertAllEqual(
self.evaluate(results), [1.] * strategy.num_replicas_in_sync)
def testNest(self, strategy):
@def_function.function
def f():
return {
'foo':
array_ops.ones((), dtypes.float32),
'bar': [
array_ops.zeros((), dtypes.float32),
array_ops.ones((), dtypes.float32),
]
}
results = test_util.gather(strategy, strategy.run(f))
self.assertAllEqual(
self.evaluate(results['foo']), [1.] * strategy.num_replicas_in_sync)
self.assertAllEqual(
self.evaluate(results['bar'][0]), [0.] * strategy.num_replicas_in_sync)
self.assertAllEqual(
self.evaluate(results['bar'][1]), [1.] * strategy.num_replicas_in_sync)
| GatherTest |
python | facebook__pyre-check | tools/typeshed_patcher/tests/transforms_test.py | {
"start": 271,
"end": 21121
} | class ____(testslide.TestCase):
def assert_transform(
self,
original_code: str,
patch: patch_specs.Patch,
expected_code: str,
) -> None:
actual_output = transforms.apply_patches_in_sequence(
code=textwrap.dedent(original_code),
patches=[patch],
)
try:
self.assertEqual(
actual_output.strip(),
textwrap.dedent(expected_code).strip(),
)
except AssertionError as err:
print("--- Expected ---")
print(textwrap.dedent(expected_code))
print("--- Actual ---")
print(actual_output)
raise err
def test_add_to_module__top(self) -> None:
self.assert_transform(
original_code=(
"""
b: str
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.AddAction(
content=textwrap.dedent(
"""
from foo import Bar
a: Bar
"""
),
position=patch_specs.AddPosition.TOP_OF_SCOPE,
),
),
expected_code=(
"""
from foo import Bar
a: Bar
b: str
"""
),
)
def test_add_to_module__bottom(self) -> None:
self.assert_transform(
original_code=(
"""
b: str
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.AddAction(
content=textwrap.dedent(
"""
def f(x: int) -> int: ...
y: float
"""
),
position=patch_specs.AddPosition.BOTTOM_OF_SCOPE,
),
),
expected_code=(
"""
b: str
def f(x: int) -> int: ...
y: float
"""
),
)
def test_add_to_class__top(self) -> None:
self.assert_transform(
original_code=(
"""
class MyClass:
b: int
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string("MyClass"),
action=patch_specs.AddAction(
content=textwrap.dedent(
"""
a: float
def f(self, x: int) -> int: ...
"""
),
position=patch_specs.AddPosition.TOP_OF_SCOPE,
),
),
expected_code=(
"""
class MyClass:
a: float
def f(self, x: int) -> int: ...
b: int
"""
),
)
def test_add_to_class__bottom(self) -> None:
self.assert_transform(
original_code=(
"""
class MyClass:
b: int
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string("MyClass"),
action=patch_specs.AddAction(
content=textwrap.dedent(
"""
a: float
def f(self, x: int) -> int: ...
"""
),
position=patch_specs.AddPosition.BOTTOM_OF_SCOPE,
),
),
expected_code=(
"""
class MyClass:
b: int
a: float
def f(self, x: int) -> int: ...
"""
),
)
def test_add_to_class__force_indent(self) -> None:
# This test is needed to exercise the forced conversion of
# class bodies that aren't indented (which is a type cast in libcst)
self.assert_transform(
original_code=(
"""
class MyClass: b: int
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string("MyClass"),
action=patch_specs.AddAction(
content=textwrap.dedent(
"""
a: float
def f(self, x: int) -> int: ...
"""
),
position=patch_specs.AddPosition.BOTTOM_OF_SCOPE,
),
),
expected_code=(
"""
class MyClass:
b: int
a: float
def f(self, x: int) -> int: ...
"""
),
)
def test_add_to_class_nested_classes(self) -> None:
# This test is needed to exercise the forced conversion of
# class bodies that aren't indented (which is a type cast in libcst).
# We also add extra classes to make sure the name tracking works.
self.assert_transform(
original_code=(
"""
class OuterClass0:
pass
class OuterClass1:
class InnerClass0:
b: int
class InnerClass1:
b: int
class InnerClass2:
b: int
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string("OuterClass1.InnerClass1"),
action=patch_specs.AddAction(
content=textwrap.dedent(
"""
def f(self, x: int) -> int: ...
"""
),
position=patch_specs.AddPosition.BOTTOM_OF_SCOPE,
),
),
expected_code=(
"""
class OuterClass0:
pass
class OuterClass1:
class InnerClass0:
b: int
class InnerClass1:
b: int
def f(self, x: int) -> int: ...
class InnerClass2:
b: int
"""
),
)
def test_add_under_import_header(self) -> None:
self.assert_transform(
original_code=(
"""
import foo, bar
if condition:
from baz import Baz
if condition1:
import qux1 as quux
elif condition2:
import qux2 as quux
else:
import qux3 as quux
x: int
import this_is_out_of_order
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.AddAction(
content=textwrap.dedent(
"""
from typing import TypeVar
T = TypeVar('T')
"""
),
position=patch_specs.AddPosition.TOP_OF_SCOPE,
),
),
expected_code=(
"""
import foo, bar
if condition:
from baz import Baz
if condition1:
import qux1 as quux
elif condition2:
import qux2 as quux
else:
import qux3 as quux
from typing import TypeVar
T = TypeVar('T')
x: int
import this_is_out_of_order
"""
),
)
def test_delete__ann_assign(self) -> None:
self.assert_transform(
original_code=(
"""
x: int
y: str
z: float
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="y",
),
),
expected_code=(
"""
x: int
z: float
"""
),
)
def test_delete__if_block(self) -> None:
self.assert_transform(
original_code=(
"""
y: str
if condition0:
def f(x: int) -> int: ...
elif condition1:
def f(x: str) -> str: ...
else:
def f(x: float) -> float: ...
z: float
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="f",
),
),
expected_code=(
"""
y: str
z: float
"""
),
)
def test_delete__multistatement_if_block(self) -> None:
self.assert_transform(
original_code=(
"""
if condition:
class A:
pass
class B:
pass
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="A",
),
),
expected_code=(
"""
if condition:
class B:
pass
"""
),
)
def test_delete__typealias(self) -> None:
self.assert_transform(
original_code=(
"""
from foo import Foo
Baz = Foo
x: int
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="Baz",
),
),
expected_code=(
"""
from foo import Foo
x: int
"""
),
)
def test_delete__class(self) -> None:
self.assert_transform(
original_code=(
"""
class A: pass
@classdecorator
class B: pass
class C: pass
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="B",
),
),
expected_code=(
"""
class A: pass
class C: pass
"""
),
)
def test_delete__function(self) -> None:
self.assert_transform(
original_code=(
"""
def f(x: int) -> int: ...
def g(x: int) -> int: ...
def h(x: int) -> int: ...
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="g",
),
),
expected_code=(
"""
def f(x: int) -> int: ...
def h(x: int) -> int: ...
"""
),
)
def test_delete__overloads(self) -> None:
self.assert_transform(
original_code=(
"""
def f(x: int) -> int: ...
@overload
def g(x: int) -> int: ...
@overload
def g(x: int) -> int: ...
def g(object) -> object: ...
def h(x: int) -> int: ...
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="g",
),
),
expected_code=(
"""
def f(x: int) -> int: ...
def h(x: int) -> int: ...
"""
),
)
def test_delete__in_nested_class(self) -> None:
self.assert_transform(
original_code=(
"""
class OuterClass0:
class InnerClass1:
x: int
class OuterClass1:
class InnerClass0:
x: int
class InnerClass1:
x: int
class InnerClass2:
x: int
class OuterClass2:
class InnerClass1:
x: int
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string("OuterClass1.InnerClass1"),
action=patch_specs.DeleteAction(
name="x",
),
),
expected_code=(
"""
class OuterClass0:
class InnerClass1:
x: int
class OuterClass1:
class InnerClass0:
x: int
class InnerClass1:
pass
class InnerClass2:
x: int
class OuterClass2:
class InnerClass1:
x: int
"""
),
)
def test_delete__import(self) -> None:
self.assert_transform(
original_code=(
"""
import foo
if condition0:
import bar
else:
from baz import bar
from bar import qux
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="bar",
),
),
expected_code=(
"""
import foo
from bar import qux
"""
),
)
def test_delete__import_as(self) -> None:
self.assert_transform(
original_code=(
"""
import foo
import bar_alt as bar
from baz import bar_alt as bar
from bar import qux
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.DeleteAction(
name="bar",
),
),
expected_code=(
"""
import foo
from bar import qux
"""
),
)
def test_replace__ann_assign(self) -> None:
self.assert_transform(
original_code=(
"""
x: int
y: str
z: float
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.ReplaceAction(
name="y",
content=textwrap.dedent(
"""
w: str
"""
),
),
),
expected_code=(
"""
x: int
w: str
z: float
"""
),
)
def test_replace__function_with_overloads(self) -> None:
self.assert_transform(
original_code=(
"""
def f(x: int) -> int: ...
@overload
def g(x: int) -> int: ...
@overload
def g(x: float) -> float: ...
def h(x: int) -> int: ...
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.ReplaceAction(
name="g",
content=textwrap.dedent(
"""
T = TypeVar('T')
def g(x: T) -> T: ...
"""
),
),
),
expected_code=(
"""
def f(x: int) -> int: ...
T = TypeVar('T')
def g(x: T) -> T: ...
def h(x: int) -> int: ...
"""
),
)
def test_replace__nested_class(self) -> None:
self.assert_transform(
original_code=(
"""
class OuterClass0:
class InnerClass1:
x: int
class OuterClass1:
class InnerClass0:
x: int
class InnerClass1:
x: int
class InnerClass2:
x: int
class OuterClass2:
class InnerClass1:
x: int
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string("OuterClass1.InnerClass1"),
action=patch_specs.ReplaceAction(
name="x",
content="y: float",
),
),
expected_code=(
"""
class OuterClass0:
class InnerClass1:
x: int
class OuterClass1:
class InnerClass0:
x: int
class InnerClass1:
y: float
class InnerClass2:
x: int
class OuterClass2:
class InnerClass1:
x: int
"""
),
)
def test_replace__import(self) -> None:
self.assert_transform(
original_code=(
"""
import baz
from foo import Bar
x: Bar
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.ReplaceAction(
name="Bar",
content="Bar = baz.Bar",
),
),
expected_code=(
"""
import baz
Bar = baz.Bar
x: Bar
"""
),
)
def test_replace__multistatement_if_block(self) -> None:
self.assert_transform(
original_code=(
"""
if condition:
class A:
pass
class B:
pass
"""
),
patch=patch_specs.Patch(
parent=patch_specs.QualifiedName.from_string(""),
action=patch_specs.ReplaceAction(
name="A",
content="A = int",
),
),
expected_code=(
"""
if condition:
A = int
class B:
pass
"""
),
)
| PatchTransformsTest |
python | streamlit__streamlit | scripts/cli_regression_tests.py | {
"start": 931,
"end": 8476
} | class ____:
"""Suite of CLI regression tests to be run against a release build of the Streamlit library.
Before running, ensure that you have:
- An isolated environment with Streamlit installed in production mode (not development) as
well as pytest. This can include the current version, nightly, or local build/wheel, like
one of the following:
pip install streamlit-nightly=[nightly tag]
pip install lib/dist/<WHEEL_FILE>
pip install streamlit
- The STREAMLIT_RELEASE_VERSION environment variable must be set, such as:
export STREAMLIT_RELEASE_VERSION=1.5.1
You can then run the tests from the root of the Streamlit repository using:
pytest scripts/cli_regression_tests.py
This test suite makes use of Python's built-in assert statement. Note that assertions in the
form of `assert <expression>` use Pytest's assertion introspection. In some cases, a more clear
error message is specified manually by using `assert <expression>, <message>`. See
https://docs.pytest.org/en/7.0.x/how-to/assert.html#assert-details for more details.
"""
@pytest.fixture(scope="module", autouse=True)
def setup(self) -> Generator[None, None, None]:
# ---- Initialization
global CONFIG_FILE_PATH # noqa: PLW0603
CONFIG_FILE_PATH = os.path.expanduser("~/.streamlit/config.toml")
global CREDENTIALS_FILE_PATH # noqa: PLW0603
CREDENTIALS_FILE_PATH = os.path.expanduser("~/.streamlit/credentials.toml")
global REPO_ROOT # noqa: PLW0603
REPO_ROOT = os.getcwd()
global STREAMLIT_RELEASE_VERSION # noqa: PLW0603
STREAMLIT_RELEASE_VERSION = os.environ.get("STREAMLIT_RELEASE_VERSION", None)
# Ensure that there aren't any previously stored credentials
if os.path.exists(CREDENTIALS_FILE_PATH):
os.remove(CREDENTIALS_FILE_PATH)
yield # Run tests
# ---- Tear Down
# Remove testing credentials
if os.path.exists(CREDENTIALS_FILE_PATH):
os.remove(CREDENTIALS_FILE_PATH)
if os.path.exists(CONFIG_FILE_PATH):
os.remove(CONFIG_FILE_PATH)
self.run_command("streamlit cache clear")
def parameterize(self, params: str) -> list[str]:
return params.split(" ")
def read_process_output(
self, proc: subprocess.Popen[bytes], num_lines_to_read: int
) -> str:
num_lines_read = 0
output = ""
while num_lines_read < num_lines_to_read:
assert proc.stdout is not None
output += proc.stdout.readline().decode("UTF-8")
num_lines_read += 1
return output
def run_command(self, command: str) -> str:
return subprocess.check_output(self.parameterize(command)).decode("UTF-8")
def run_single_proc(self, command: str, num_lines_to_read: int = 4) -> str:
proc = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
preexec_fn=os.setpgrp, # noqa: PLW1509
)
output = self.read_process_output(proc, num_lines_to_read)
try:
os.kill(os.getpgid(proc.pid), signal.SIGTERM)
except ProcessLookupError:
# The process may have exited already. If so, we don't need to do anything
pass
return output
def run_double_proc(
self, command_one: str, command_two: str, num_lines_to_read: int = 4
) -> tuple[str, str]:
proc_one = subprocess.Popen(
command_one,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
preexec_fn=os.setpgrp, # noqa: PLW1509
)
# Getting the output from process one ensures the process started first
output_one = self.read_process_output(proc_one, num_lines_to_read)
proc_two = subprocess.Popen(
command_two,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
preexec_fn=os.setpgrp, # noqa: PLW1509
)
output_two = self.read_process_output(proc_two, num_lines_to_read)
try:
os.killpg(os.getpgid(proc_one.pid), signal.SIGKILL)
os.killpg(os.getpgid(proc_two.pid), signal.SIGKILL)
except ProcessLookupError:
# The process may have exited already. If so, we don't need to do anything
pass
return output_one, output_two
@pytest.mark.skipif(
os.environ.get("SKIP_VERSION_CHECK", "false").lower() == "true",
reason="Skip version verification when `SKIP_VERSION_CHECK` env var is set",
)
def test_streamlit_version(self) -> None:
assert STREAMLIT_RELEASE_VERSION is not None
assert STREAMLIT_RELEASE_VERSION != "", (
"You must set the $STREAMLIT_RELEASE_VERSION env variable"
)
assert STREAMLIT_RELEASE_VERSION in self.run_command("streamlit version"), (
f"Package version does not match the desired version of {STREAMLIT_RELEASE_VERSION}"
)
def test_streamlit_activate(self) -> None:
process = subprocess.Popen(
"streamlit activate", stdin=subprocess.PIPE, shell=True
)
process.stdin.write(b"regressiontest@streamlit.io\n") # type: ignore
process.stdin.flush() # type: ignore
process.communicate()
with open(CREDENTIALS_FILE_PATH) as f:
assert "regressiontest@streamlit.io" in f.read(), (
"Email address was not found in the credentials file"
)
def test_port_reassigned(self) -> None:
"""When starting a new Streamlit session, it will run on port 8501 by default. If 8501 is
not available, it will use the next available port.
"""
out_one, out_two = self.run_double_proc(
f"streamlit run --server.headless=true {REPO_ROOT}/e2e_playwright/st_file_uploader.py",
f"streamlit run --server.headless=true {REPO_ROOT}/e2e_playwright/st_file_uploader.py",
)
assert ":8501" in out_one, f"Incorrect port. See output:\n{out_one}"
assert ":8502" in out_two, f"Incorrect port. See output:\n{out_two}"
def test_conflicting_port(self) -> None:
out_one, out_two = self.run_double_proc(
f"streamlit run --server.headless=true {REPO_ROOT}/e2e_playwright/st_file_uploader.py",
f"streamlit run --server.headless=true --server.port=8501 {REPO_ROOT}/e2e_playwright/st_file_uploader.py",
)
assert ":8501" in out_one, f"Incorrect port. See output:\n{out_one}"
assert "Port 8501 is already in use" in out_two, (
f"Incorrect conflict. See output:\n{out_one}"
)
def test_cli_defined_port(self) -> None:
out = self.run_single_proc(
f"streamlit run --server.headless=true --server.port=9999 {REPO_ROOT}/e2e_playwright/st_file_uploader.py",
)
assert ":9999" in out, f"Incorrect port. See output:\n{out}"
def test_config_toml_defined_port(self) -> None:
with open(CONFIG_FILE_PATH, "w") as file:
file.write("[server]\n port=8888")
out = self.run_single_proc(
f"streamlit run --server.headless=true {REPO_ROOT}/e2e_playwright/st_file_uploader.py",
)
assert ":8888" in out, f"Incorrect port. See output:\n{out}"
| TestCLIRegressions |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 31258,
"end": 31792
} | class ____(CheckTestCase):
def test_not_integer(self):
class TestModelAdmin(ModelAdmin):
list_max_show_all = "hello"
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'list_max_show_all' must be an integer.",
"admin.E119",
)
def test_valid_case(self):
class TestModelAdmin(ModelAdmin):
list_max_show_all = 200
self.assertIsValid(TestModelAdmin, ValidationTestModel)
| ListMaxShowAllCheckTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.