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 | apache__airflow | scripts/in_container/update_quarantined_test_status.py | {
"start": 1141,
"end": 1268
} | class ____(NamedTuple):
test_id: str
file: str
name: str
classname: str
line: str
result: bool
| TestResult |
python | Netflix__metaflow | metaflow/plugins/datastores/gs_storage.py | {
"start": 680,
"end": 4939
} | class ____(object):
"""
datastore_root aware Google Cloud Storage client. I.e. blob operations are
all done relative to datastore_root.
This must be picklable, so methods may be passed across process boundaries.
"""
def __init__(self, datastore_root):
if datastore_root is None:
raise MetaflowInternalError("datastore_root must be set")
self._datastore_root = datastore_root
def get_datastore_root(self):
return self._datastore_root
def get_blob_full_path(self, path):
"""
Full path means <blob_prefix>/<path> where:
datastore_root is gs://<bucket_name>/<blob_prefix>
"""
_, blob_prefix = parse_gs_full_path(self._datastore_root)
if blob_prefix is None:
return path
path = path.lstrip("/")
return "/".join([blob_prefix, path])
def get_bucket_client(self):
bucket_name, _ = parse_gs_full_path(self._datastore_root)
client = get_gs_storage_client()
return client.bucket(bucket_name)
def get_blob_client(self, path):
bucket = self.get_bucket_client()
blob_full_path = self.get_blob_full_path(path)
blob = bucket.blob(blob_full_path)
return blob
# GS blob operations. These are meant to be single units of work
# to be performed by thread or process pool workers.
def is_file_single(self, path):
"""Drives GSStorage.is_file()"""
try:
blob = self.get_blob_client(path)
result = blob.exists()
return result
except Exception as e:
process_gs_exception(e)
def list_content_single(self, path):
"""Drives GSStorage.list_content()"""
def _trim_result(name, prefix):
# Remove a prefix from the name, if present
if prefix is not None and name[: len(prefix)] == prefix:
name = name[len(prefix) + 1 :]
return name
try:
path = path.rstrip("/") + "/"
bucket_name, blob_prefix = parse_gs_full_path(self._datastore_root)
full_path = self.get_blob_full_path(path)
blobs = get_gs_storage_client().list_blobs(
bucket_name,
prefix=full_path,
delimiter="/",
include_trailing_delimiter=False,
)
result = []
for b in blobs:
result.append((_trim_result(b.name, blob_prefix), True))
for p in blobs.prefixes:
result.append((_trim_result(p, blob_prefix).rstrip("/"), False))
return result
except Exception as e:
process_gs_exception(e)
def save_bytes_single(
self,
path_tmpfile_metadata_triple,
overwrite=False,
):
try:
path, tmpfile, metadata = path_tmpfile_metadata_triple
blob = self.get_blob_client(path)
if not overwrite:
if blob.exists():
return
if metadata is not None:
blob.metadata = {"metaflow-user-attributes": json.dumps(metadata)}
from google.cloud.storage.retry import DEFAULT_RETRY
blob.upload_from_filename(
tmpfile, retry=DEFAULT_RETRY, timeout=(14400, 60)
) # generous timeout for massive uploads. Use the same values as for Azure (connection_timeout, read_timeout)
except Exception as e:
process_gs_exception(e)
def load_bytes_single(self, tmpdir, key):
"""Drives GSStorage.load_bytes()"""
tmp_filename = os.path.join(tmpdir, str(uuid.uuid4()))
blob = self.get_blob_client(key)
metaflow_user_attributes = None
import google.api_core.exceptions
try:
blob.reload()
if blob.metadata and "metaflow-user-attributes" in blob.metadata:
metaflow_user_attributes = json.loads(
blob.metadata["metaflow-user-attributes"]
)
blob.download_to_filename(tmp_filename)
except google.api_core.exceptions.NotFound:
tmp_filename = None
return key, tmp_filename, metaflow_user_attributes
| _GSRootClient |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/flare/output_parser.py | {
"start": 1280,
"end": 2093
} | class ____(BaseOutputParser):
"""
QueryTask output parser.
By default, parses output that contains "[Search(query)]" tags.
"""
def parse(self, output: str) -> Any:
"""Parse output."""
query_tasks = []
for idx, char in enumerate(output):
if char == "[":
start_idx = idx
elif char == "]":
end_idx = idx
raw_query_str = output[start_idx + 1 : end_idx]
query_str = raw_query_str.split("(")[1].split(")")[0]
query_tasks.append(QueryTask(query_str, start_idx, end_idx))
return query_tasks
def format(self, output: str) -> str:
"""Format a query with structured output formatting instructions."""
raise NotImplementedError
| QueryTaskOutputParser |
python | django__django | tests/admin_views/models.py | {
"start": 20448,
"end": 20980
} | class ____(models.Model):
"""
Regression test for #15938: a large max_length for the slugfield must not
be localized in prepopulated_fields_js.html or it might end up breaking
the JavaScript (ie, using THOUSAND_SEPARATOR ends up with maxLength=1,000)
"""
title = models.CharField(max_length=100)
published = models.BooleanField(default=False)
# `db_index=False` because MySQL cannot index large CharField (#21196).
slug = models.SlugField(max_length=1000, db_index=False)
| PrePopulatedPostLargeSlug |
python | falconry__falcon | tests/test_media_urlencoded.py | {
"start": 1142,
"end": 2305
} | class ____:
async def on_post(self, req, resp):
resp.media = await req.get_media()
@pytest.fixture
def client(asgi, util):
app = util.create_app(asgi)
app.add_route('/media', MediaMirrorAsync() if asgi else MediaMirror())
return testing.TestClient(app)
def test_empty_form(client):
resp = client.simulate_post(
'/media', headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
assert resp.content == b'{}'
@pytest.mark.parametrize(
'body,expected',
[
('a=1&b=&c=3', {'a': '1', 'b': '', 'c': '3'}),
('param=undefined', {'param': 'undefined'}),
('color=green&color=black', {'color': ['green', 'black']}),
(
'food=hamburger+%28%F0%9F%8D%94%29&sauce=BBQ',
{'food': 'hamburger (🍔)', 'sauce': 'BBQ'},
),
('flag%1&flag%2&flag%1&flag%2', {'flag%1': ['', ''], 'flag%2': ['', '']}),
],
)
def test_urlencoded_form(client, body, expected):
resp = client.simulate_post(
'/media',
body=body,
headers={'Content-Type': 'application/x-www-form-urlencoded'},
)
assert resp.json == expected
| MediaMirrorAsync |
python | kamyu104__LeetCode-Solutions | Python/number-of-unique-good-subsequences.py | {
"start": 29,
"end": 700
} | class ____(object):
def numberOfUniqueGoodSubsequences(self, binary):
"""
:type binary: str
:rtype: int
"""
MOD = 10**9+7
ends0, ends1 = 0, 0
has_zero = False
for b in binary:
if b == '1':
ends1 = (ends0+ends1+1)%MOD # curr subsequences end with 1 is all prev distinct subsequences appended by 1 and plus "1"
else:
ends0 = (ends0+ends1)%MOD # curr subsequences end with 0 is all prev distinct subsequences appended by 0 and don't plus "0"
has_zero = True
return (ends0+ends1+int(has_zero))%MOD # add "0" if has_zero
| Solution |
python | davidhalter__jedi | test/completion/docstring.py | {
"start": 3128,
"end": 3240
} | class ____():
"""
:type foo: str
"""
def __init__(self, foo):
#? str()
foo
| InClass |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py | {
"start": 1894,
"end": 2095
} | class ____:
def method1(self, v: object):
if type(self) == type(v):
reveal_type(self, expected_text="Self@F")
else:
reveal_type(self, expected_text="Self@F")
| F |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/errors.py | {
"start": 7564,
"end": 8364
} | class ____(HypothesisException):
"""Raised when a mutation method has been called on a ConjectureData object
after freeze() has been called."""
def __getattr__(name: str) -> Any:
if name == "MultipleFailures":
from hypothesis._settings import note_deprecation
from hypothesis.internal.compat import BaseExceptionGroup
note_deprecation(
"MultipleFailures is deprecated; use the builtin `BaseExceptionGroup` type "
"instead, or `exceptiongroup.BaseExceptionGroup` before Python 3.11",
since="2022-08-02",
has_codemod=False, # This would be a great PR though!
stacklevel=1,
)
return BaseExceptionGroup
raise AttributeError(f"Module 'hypothesis.errors' has no attribute {name}")
| Frozen |
python | google__pytype | pytype/types/functions.py | {
"start": 149,
"end": 1553
} | class ____(abc.ABC):
"""Representation of a Python function signature.
Attributes:
name: Name of the function.
param_names: A tuple of positional parameter names. This DOES include
positional-only parameters and does NOT include keyword-only parameters.
posonly_count: Number of positional-only parameters. (Python 3.8)
varargs_name: Name of the varargs parameter. (The "args" in *args)
kwonly_params: Tuple of keyword-only parameters. (Python 3) E.g. ("x", "y")
for "def f(a, *, x, y=2)". These do NOT appear in param_names. Ordered
like in the source file.
kwargs_name: Name of the kwargs parameter. (The "kwargs" in **kwargs)
posonly_params: Tuple of positional-only parameters
"""
name: str
param_names: tuple[str, ...]
posonly_count: int
varargs_name: str | None
kwonly_params: tuple[str, ...]
kwargs_name: str | None
@property
def posonly_params(self):
return self.param_names[: self.posonly_count]
@abc.abstractmethod
def has_default(self, name):
"""Whether the named arg has a default value."""
@abc.abstractmethod
def insert_varargs_and_kwargs(self, args):
"""Insert varargs and kwargs from args into the signature."""
@abc.abstractmethod
def iter_args(self, args):
"""Iterates through the given args, attaching names and expected types."""
@dataclasses.dataclass(eq=True, frozen=True)
| Signature |
python | huggingface__transformers | src/transformers/models/edgetam/configuration_edgetam.py | {
"start": 7737,
"end": 11044
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`EdgeTamMaskDecoder`]. It is used to instantiate a EDGETAM
memory encoder according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
hidden_size (`int`, *optional*, defaults to 256):
Dimensionality of the hidden states.
hidden_act (`str`, *optional*, defaults to `"gelu"`):
The non-linear activation function in the EDGETAM mask decoder.
mlp_dim (`int`, *optional*, defaults to 2048):
The dimension of the MLP in the two-way transformer.
num_hidden_layers (`int`, *optional*, defaults to 2):
The number of hidden layers in the two-way transformer.
num_attention_heads (`int`, *optional*, defaults to 8):
The number of attention heads in the two-way transformer.
attention_downsample_rate (`int`, *optional*, defaults to 2):
The downsample rate for the attention layers.
num_multimask_outputs (`int`, *optional*, defaults to 3):
The number of multimask outputs.
iou_head_depth (`int`, *optional*, defaults to 3):
The depth of the IoU head.
iou_head_hidden_dim (`int`, *optional*, defaults to 256):
The hidden dimension of the IoU head.
dynamic_multimask_via_stability (`bool`, *optional*, defaults to `True`):
Whether to use dynamic multimask via stability.
dynamic_multimask_stability_delta (`float`, *optional*, defaults to 0.05):
The stability delta for the dynamic multimask.
dynamic_multimask_stability_thresh (`float`, *optional*, defaults to 0.98):
The stability threshold for the dynamic multimask.
"""
base_config_key = "mask_decoder_config"
def __init__(
self,
hidden_size=256,
hidden_act="gelu",
mlp_dim=2048,
num_hidden_layers=2,
num_attention_heads=8,
attention_downsample_rate=2,
num_multimask_outputs=3,
iou_head_depth=3,
iou_head_hidden_dim=256,
dynamic_multimask_via_stability=True,
dynamic_multimask_stability_delta=0.05,
dynamic_multimask_stability_thresh=0.98,
**kwargs,
):
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.num_multimask_outputs = num_multimask_outputs
self.hidden_act = hidden_act
self.iou_head_depth = iou_head_depth
self.iou_head_hidden_dim = iou_head_hidden_dim
self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
# TwoWayTransformer configuration
self.num_hidden_layers = num_hidden_layers
self.hidden_size = hidden_size
self.num_attention_heads = num_attention_heads
self.mlp_dim = mlp_dim
self.attention_downsample_rate = attention_downsample_rate
| EdgeTamMaskDecoderConfig |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/eks.py | {
"start": 2039,
"end": 4248
} | class ____(AwsBaseSensor):
"""
Base class to check various EKS states.
Subclasses need to implement get_state and get_terminal_states methods.
:param cluster_name: The name of the Cluster
:param target_state: Will return successfully when that state is reached.
:param target_state_type: The enum containing the states,
will be used to convert the target state if it has to be converted from a string
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is ``None`` or empty then the default boto3 behaviour is used. If
running Airflow in a distributed manner and aws_conn_id is None or
empty, then default boto3 configuration would be used (and must be
maintained on each worker node).
:param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
:param verify: Whether or not to verify SSL certificates. See:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
"""
aws_hook_class = EksHook
def __init__(
self,
*,
cluster_name: str,
target_state: ClusterStates | NodegroupStates | FargateProfileStates,
target_state_type: type,
**kwargs,
):
super().__init__(**kwargs)
self.cluster_name = cluster_name
self.target_state = (
target_state
if isinstance(target_state, target_state_type)
else target_state_type(str(target_state).upper())
)
def poke(self, context: Context) -> bool:
state = self.get_state()
self.log.info("Current state: %s", state)
if state in (self.get_terminal_states() - {self.target_state}):
# If we reach a terminal state which is not the target state
raise AirflowException(
f"Terminal state reached. Current state: {state}, Expected state: {self.target_state}"
)
return state == self.target_state
@abstractmethod
def get_state(self) -> ClusterStates | NodegroupStates | FargateProfileStates: ...
@abstractmethod
def get_terminal_states(self) -> frozenset: ...
| EksBaseSensor |
python | scrapy__scrapy | tests/test_engine.py | {
"start": 12940,
"end": 17530
} | class ____(TestEngineBase):
@deferred_f_from_coro_f
async def test_crawler(self, mockserver: MockServer) -> None:
for spider in (
MySpider,
DictItemsSpider,
AttrsItemsSpider,
DataClassItemsSpider,
):
run = CrawlerRun(spider)
await run.run(mockserver)
self._assert_visited_urls(run)
self._assert_scheduled_requests(run, count=9)
self._assert_downloaded_responses(run, count=9)
self._assert_scraped_items(run)
self._assert_signals_caught(run)
self._assert_bytes_received(run)
@deferred_f_from_coro_f
async def test_crawler_dupefilter(self, mockserver: MockServer) -> None:
run = CrawlerRun(DupeFilterSpider)
await run.run(mockserver)
self._assert_scheduled_requests(run, count=8)
self._assert_dropped_requests(run)
@deferred_f_from_coro_f
async def test_crawler_itemerror(self, mockserver: MockServer) -> None:
run = CrawlerRun(ItemZeroDivisionErrorSpider)
await run.run(mockserver)
self._assert_items_error(run)
@deferred_f_from_coro_f
async def test_crawler_change_close_reason_on_idle(
self, mockserver: MockServer
) -> None:
run = CrawlerRun(ChangeCloseReasonSpider)
await run.run(mockserver)
assert {
"spider": run.crawler.spider,
"reason": "custom_reason",
} == run.signals_caught[signals.spider_closed]
@deferred_f_from_coro_f
async def test_close_downloader(self):
e = ExecutionEngine(get_crawler(MySpider), lambda _: None)
await e.close_async()
def test_close_without_downloader(self):
class CustomException(Exception):
pass
class BadDownloader:
def __init__(self, crawler):
raise CustomException
with pytest.raises(CustomException):
ExecutionEngine(
get_crawler(MySpider, {"DOWNLOADER": BadDownloader}), lambda _: None
)
@inlineCallbacks
def test_start_already_running_exception(self):
crawler = get_crawler(DefaultSpider)
crawler.spider = crawler._create_spider()
e = ExecutionEngine(crawler, lambda _: None)
yield deferred_from_coro(e.open_spider_async())
_schedule_coro(e.start_async())
with pytest.raises(RuntimeError, match="Engine already running"):
yield deferred_from_coro(e.start_async())
yield deferred_from_coro(e.stop_async())
@pytest.mark.only_asyncio
@deferred_f_from_coro_f
async def test_start_already_running_exception_asyncio(self):
crawler = get_crawler(DefaultSpider)
crawler.spider = crawler._create_spider()
e = ExecutionEngine(crawler, lambda _: None)
await e.open_spider_async()
with pytest.raises(RuntimeError, match="Engine already running"):
await asyncio.gather(e.start_async(), e.start_async())
await e.stop_async()
@inlineCallbacks
def test_start_request_processing_exception(self):
class BadRequestFingerprinter:
def fingerprint(self, request):
raise ValueError # to make Scheduler.enqueue_request() fail
class SimpleSpider(Spider):
name = "simple"
async def start(self):
yield Request("data:,")
crawler = get_crawler(
SimpleSpider, {"REQUEST_FINGERPRINTER_CLASS": BadRequestFingerprinter}
)
with LogCapture() as log:
yield crawler.crawl()
assert "Error while processing requests from start()" in str(log)
assert "Spider closed (shutdown)" in str(log)
def test_short_timeout(self):
args = (
sys.executable,
"-m",
"scrapy.cmdline",
"fetch",
"-s",
"CLOSESPIDER_TIMEOUT=0.001",
"-s",
"LOG_LEVEL=DEBUG",
"http://toscrape.com",
)
p = subprocess.Popen(
args,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
)
try:
_, stderr = p.communicate(timeout=15)
except subprocess.TimeoutExpired:
p.kill()
p.communicate()
pytest.fail("Command took too much time to complete")
stderr_str = stderr.decode("utf-8")
assert "AttributeError" not in stderr_str, stderr_str
assert "AssertionError" not in stderr_str, stderr_str
| TestEngine |
python | django__django | tests/admin_inlines/tests.py | {
"start": 34637,
"end": 35439
} | class ____(TestCase):
def test_immutable_content_type(self):
"""Regression for #9362
The problem depends only on InlineAdminForm and its "original"
argument, so we can safely set the other arguments to None/{}. We just
need to check that the content_type argument of Child isn't altered by
the internals of the inline form."""
sally = Teacher.objects.create(name="Sally")
john = Parent.objects.create(name="John")
joe = Child.objects.create(name="Joe", teacher=sally, parent=john)
iaf = InlineAdminForm(None, None, {}, {}, joe)
parent_ct = ContentType.objects.get_for_model(Parent)
self.assertEqual(iaf.original.content_type, parent_ct)
@override_settings(ROOT_URLCONF="admin_inlines.urls")
| TestInlineAdminForm |
python | getsentry__sentry | src/sentry/monitors/processing_errors/errors.py | {
"start": 4466,
"end": 5161
} | class ____(TypedDict):
"""
We have disabled checkin ingestion for this org. Contact support for details
"""
type: Literal[ProcessingErrorType.ORGANIZATION_KILLSWITCH_ENABLED]
ProcessingError = Union[
CheckinEnvironmentMismatch,
CheckinFinished,
CheckinGuidProjectMismatch,
CheckinInvalidDuration,
CheckinInvalidGuid,
CheckinValidationFailed,
MonitorDisabled,
MonitorDisabledNoQuota,
MonitorInvalidConfig,
MonitorInvalidEnvironment,
MonitorLimitExceeded,
MonitorNotFound,
MonitorOverQuota,
MonitorEnvironmentLimitExceeded,
MonitorEnviromentRateLimited,
OrganizationKillswitchEnabled,
]
| OrganizationKillswitchEnabled |
python | getsentry__sentry | src/sentry/middleware/integrations/parsers/gitlab.py | {
"start": 754,
"end": 4184
} | class ____(BaseRequestParser):
provider = EXTERNAL_PROVIDERS[ExternalProviders.GITLAB]
webhook_identifier = WebhookProviderIdentifier.GITLAB
_integration: Integration | None = None
_METRIC_CONTROL_PATH_FAILURE_KEY = "integrations.gitlab.get_integration_from_request.failure"
def _resolve_external_id(self) -> tuple[str, str] | HttpResponseBase:
clear_tags_and_context()
extra = {
# This tells us the Gitlab version being used (e.g. current gitlab.com version -> GitLab/15.4.0-pre)
"user-agent": self.request.META.get("HTTP_USER_AGENT"),
# Gitlab does not seem to be the only host sending events
# AppPlatformEvents also hit this API
"event-type": self.request.META.get("HTTP_X_GITLAB_EVENT"),
}
return get_gitlab_external_id(request=self.request, extra=extra)
@control_silo_function
def get_integration_from_request(self) -> Integration | None:
if self._integration:
return self._integration
if not self.is_json_request():
return None
try:
# Webhook endpoints
result = self._resolve_external_id()
if isinstance(result, tuple):
(external_id, _secret) = result
self._integration = Integration.objects.filter(
external_id=external_id, provider=self.provider
).first()
return self._integration
except Exception as e:
metrics.incr(
self._METRIC_CONTROL_PATH_FAILURE_KEY,
tags={"integration": self.provider, "error": str(e)},
)
logger.exception("Failed to get integration from request")
return None
def get_response_from_gitlab_webhook(self) -> HttpResponseBase:
maybe_http_response = self._resolve_external_id()
if isinstance(maybe_http_response, HttpResponseBase):
return maybe_http_response
try:
integration = self.get_integration_from_request()
if not integration:
return self.get_default_missing_integration_response()
regions = self.get_regions_from_organizations()
except Integration.DoesNotExist:
return self.get_default_missing_integration_response()
if len(regions) == 0:
return self.get_default_missing_integration_response()
try:
data = orjson.loads(self.request.body)
except orjson.JSONDecodeError:
data = {}
return self.get_response_from_webhookpayload(
regions=regions,
identifier=self.get_mailbox_identifier(integration, data),
integration_id=integration.id,
)
def mailbox_bucket_id(self, data: Mapping[str, Any]) -> int | None:
"""
Used by get_mailbox_identifier to find the project.id a payload is for.
In high volume gitlab instances we shard messages by project for greater
delivery throughput.
"""
project_id = data.get("project", {}).get("id", None)
if not project_id:
return None
return project_id
def get_response(self) -> HttpResponseBase:
if self.view_class == GitlabWebhookEndpoint:
return self.get_response_from_gitlab_webhook()
return self.get_response_from_control_silo()
| GitlabRequestParser |
python | neetcode-gh__leetcode | python/0014-longest-common-prefix.py | {
"start": 0,
"end": 256
} | class ____:
def longestCommonPrefix(self, strs: List[str]) -> str:
for i in range(len(strs[0])):
for s in strs:
if i >= len(s) or s[i] != strs[0][i]:
return strs[0][:i]
return strs[0]
| Solution |
python | encode__starlette | starlette/responses.py | {
"start": 5807,
"end": 5868
} | class ____(Response):
media_type = "text/html"
| HTMLResponse |
python | huggingface__transformers | src/transformers/models/olmoe/modeling_olmoe.py | {
"start": 2777,
"end": 5774
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: OlmoeConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = inv_freq
@staticmethod
def compute_default_rope_parameters(
config: Optional[OlmoeConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
| OlmoeRotaryEmbedding |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/execution_tests/pipes_tests/in_process_client.py | {
"start": 1069,
"end": 1317
} | class ____(PipesMessageWriterChannel):
def __init__(self) -> None:
self.messages: list[PipesMessage] = []
def write_message(self, message: PipesMessage) -> None:
self.messages.append(message)
| InProcessPipesMessageWriteChannel |
python | astropy__astropy | astropy/constants/codata2010.py | {
"start": 710,
"end": 3814
} | class ____(CODATA2010, EMConstant):
_registry = CODATA2010._registry
h = CODATA2010(
"h", "Planck constant", 6.62606957e-34, "J s", 0.00000029e-34, system="si"
)
hbar = CODATA2010(
"hbar",
"Reduced Planck constant",
h.value * 0.5 / np.pi,
"J s",
h.uncertainty * 0.5 / np.pi,
h.reference,
system="si",
)
k_B = CODATA2010(
"k_B", "Boltzmann constant", 1.3806488e-23, "J / (K)", 0.0000013e-23, system="si"
)
c = CODATA2010(
"c", "Speed of light in vacuum", 2.99792458e8, "m / (s)", 0.0, system="si"
)
G = CODATA2010(
"G", "Gravitational constant", 6.67384e-11, "m3 / (kg s2)", 0.00080e-11, system="si"
)
g0 = CODATA2010(
"g0", "Standard acceleration of gravity", 9.80665, "m / s2", 0.0, system="si"
)
m_p = CODATA2010(
"m_p", "Proton mass", 1.672621777e-27, "kg", 0.000000074e-27, system="si"
)
m_n = CODATA2010(
"m_n", "Neutron mass", 1.674927351e-27, "kg", 0.000000074e-27, system="si"
)
m_e = CODATA2010(
"m_e", "Electron mass", 9.10938291e-31, "kg", 0.00000040e-31, system="si"
)
u = CODATA2010("u", "Atomic mass", 1.660538921e-27, "kg", 0.000000073e-27, system="si")
sigma_sb = CODATA2010(
"sigma_sb",
"Stefan-Boltzmann constant",
5.670373e-8,
"W / (K4 m2)",
0.000021e-8,
system="si",
)
e = EMCODATA2010(
"e", "Electron charge", 1.602176565e-19, "C", 0.000000035e-19, system="si"
)
eps0 = EMCODATA2010(
"eps0", "Electric constant", 8.854187817e-12, "F/m", 0.0, system="si"
)
N_A = CODATA2010(
"N_A", "Avogadro's number", 6.02214129e23, "1 / (mol)", 0.00000027e23, system="si"
)
R = CODATA2010("R", "Gas constant", 8.3144621, "J / (K mol)", 0.0000075, system="si")
Ryd = CODATA2010(
"Ryd", "Rydberg constant", 10973731.568539, "1 / (m)", 0.000055, system="si"
)
a0 = CODATA2010(
"a0", "Bohr radius", 0.52917721092e-10, "m", 0.00000000017e-10, system="si"
)
muB = CODATA2010(
"muB", "Bohr magneton", 927.400968e-26, "J/T", 0.00002e-26, system="si"
)
alpha = CODATA2010(
"alpha",
"Fine-structure constant",
7.2973525698e-3,
"",
0.0000000024e-3,
system="si",
)
atm = CODATA2010("atm", "Standard atmosphere", 101325, "Pa", 0.0, system="si")
mu0 = CODATA2010("mu0", "Magnetic constant", 4.0e-7 * np.pi, "N/A2", 0.0, system="si")
sigma_T = CODATA2010(
"sigma_T",
"Thomson scattering cross-section",
0.6652458734e-28,
"m2",
0.0000000013e-28,
system="si",
)
b_wien = Constant(
"b_wien",
"Wien wavelength displacement law constant",
2.8977721e-3,
"m K",
0.0000026e-3,
"CODATA 2010",
system="si",
)
# cgs constants
# Only constants that cannot be converted directly from S.I. are defined here.
e_esu = EMCODATA2010(
e.abbrev,
e.name,
e.value * c.value * 10.0,
"statC",
e.uncertainty * c.value * 10.0,
system="esu",
)
e_emu = EMCODATA2010(
e.abbrev, e.name, e.value / 10, "abC", e.uncertainty / 10, system="emu"
)
e_gauss = EMCODATA2010(
e.abbrev,
e.name,
e.value * c.value * 10.0,
"Fr",
e.uncertainty * c.value * 10.0,
system="gauss",
)
| EMCODATA2010 |
python | wandb__wandb | wandb/vendor/pygments/lexers/business.py | {
"start": 627,
"end": 11584
} | class ____(RegexLexer):
"""
Lexer for OpenCOBOL code.
.. versionadded:: 1.6
"""
name = 'COBOL'
aliases = ['cobol']
filenames = ['*.cob', '*.COB', '*.cpy', '*.CPY']
mimetypes = ['text/x-cobol']
flags = re.IGNORECASE | re.MULTILINE
# Data Types: by PICTURE and USAGE
# Operators: **, *, +, -, /, <, >, <=, >=, =, <>
# Logical (?): NOT, AND, OR
# Reserved words:
# http://opencobol.add1tocobol.com/#reserved-words
# Intrinsics:
# http://opencobol.add1tocobol.com/#does-opencobol-implement-any-intrinsic-functions
tokens = {
'root': [
include('comment'),
include('strings'),
include('core'),
include('nums'),
(r'[a-z0-9]([\w\-]*[a-z0-9]+)?', Name.Variable),
# (r'[\s]+', Text),
(r'[ \t]+', Text),
],
'comment': [
(r'(^.{6}[*/].*\n|^.{6}|\*>.*\n)', Comment),
],
'core': [
# Figurative constants
(r'(^|(?<=[^\w\-]))(ALL\s+)?'
r'((ZEROES)|(HIGH-VALUE|LOW-VALUE|QUOTE|SPACE|ZERO)(S)?)'
r'\s*($|(?=[^\w\-]))',
Name.Constant),
# Reserved words STATEMENTS and other bolds
(words((
'ACCEPT', 'ADD', 'ALLOCATE', 'CALL', 'CANCEL', 'CLOSE', 'COMPUTE',
'CONFIGURATION', 'CONTINUE', 'DATA', 'DELETE', 'DISPLAY', 'DIVIDE',
'DIVISION', 'ELSE', 'END', 'END-ACCEPT',
'END-ADD', 'END-CALL', 'END-COMPUTE', 'END-DELETE', 'END-DISPLAY',
'END-DIVIDE', 'END-EVALUATE', 'END-IF', 'END-MULTIPLY', 'END-OF-PAGE',
'END-PERFORM', 'END-READ', 'END-RETURN', 'END-REWRITE', 'END-SEARCH',
'END-START', 'END-STRING', 'END-SUBTRACT', 'END-UNSTRING', 'END-WRITE',
'ENVIRONMENT', 'EVALUATE', 'EXIT', 'FD', 'FILE', 'FILE-CONTROL', 'FOREVER',
'FREE', 'GENERATE', 'GO', 'GOBACK', 'IDENTIFICATION', 'IF', 'INITIALIZE',
'INITIATE', 'INPUT-OUTPUT', 'INSPECT', 'INVOKE', 'I-O-CONTROL', 'LINKAGE',
'LOCAL-STORAGE', 'MERGE', 'MOVE', 'MULTIPLY', 'OPEN', 'PERFORM',
'PROCEDURE', 'PROGRAM-ID', 'RAISE', 'READ', 'RELEASE', 'RESUME',
'RETURN', 'REWRITE', 'SCREEN', 'SD', 'SEARCH', 'SECTION', 'SET',
'SORT', 'START', 'STOP', 'STRING', 'SUBTRACT', 'SUPPRESS',
'TERMINATE', 'THEN', 'UNLOCK', 'UNSTRING', 'USE', 'VALIDATE',
'WORKING-STORAGE', 'WRITE'), prefix=r'(^|(?<=[^\w\-]))',
suffix=r'\s*($|(?=[^\w\-]))'),
Keyword.Reserved),
# Reserved words
(words((
'ACCESS', 'ADDRESS', 'ADVANCING', 'AFTER', 'ALL',
'ALPHABET', 'ALPHABETIC', 'ALPHABETIC-LOWER', 'ALPHABETIC-UPPER',
'ALPHANUMERIC', 'ALPHANUMERIC-EDITED', 'ALSO', 'ALTER', 'ALTERNATE'
'ANY', 'ARE', 'AREA', 'AREAS', 'ARGUMENT-NUMBER', 'ARGUMENT-VALUE', 'AS',
'ASCENDING', 'ASSIGN', 'AT', 'AUTO', 'AUTO-SKIP', 'AUTOMATIC',
'AUTOTERMINATE', 'BACKGROUND-COLOR', 'BASED', 'BEEP', 'BEFORE', 'BELL',
'BLANK', 'BLINK', 'BLOCK', 'BOTTOM', 'BY', 'BYTE-LENGTH', 'CHAINING',
'CHARACTER', 'CHARACTERS', 'CLASS', 'CODE', 'CODE-SET', 'COL',
'COLLATING', 'COLS', 'COLUMN', 'COLUMNS', 'COMMA', 'COMMAND-LINE',
'COMMIT', 'COMMON', 'CONSTANT', 'CONTAINS', 'CONTENT', 'CONTROL',
'CONTROLS', 'CONVERTING', 'COPY', 'CORR', 'CORRESPONDING', 'COUNT', 'CRT',
'CURRENCY', 'CURSOR', 'CYCLE', 'DATE', 'DAY', 'DAY-OF-WEEK', 'DE',
'DEBUGGING', 'DECIMAL-POINT', 'DECLARATIVES', 'DEFAULT', 'DELIMITED',
'DELIMITER', 'DEPENDING', 'DESCENDING', 'DETAIL', 'DISK',
'DOWN', 'DUPLICATES', 'DYNAMIC', 'EBCDIC',
'ENTRY', 'ENVIRONMENT-NAME', 'ENVIRONMENT-VALUE', 'EOL', 'EOP',
'EOS', 'ERASE', 'ERROR', 'ESCAPE', 'EXCEPTION',
'EXCLUSIVE', 'EXTEND', 'EXTERNAL', 'FILE-ID', 'FILLER', 'FINAL',
'FIRST', 'FIXED', 'FLOAT-LONG', 'FLOAT-SHORT',
'FOOTING', 'FOR', 'FOREGROUND-COLOR', 'FORMAT', 'FROM', 'FULL',
'FUNCTION', 'FUNCTION-ID', 'GIVING', 'GLOBAL', 'GROUP',
'HEADING', 'HIGHLIGHT', 'I-O', 'ID',
'IGNORE', 'IGNORING', 'IN', 'INDEX', 'INDEXED', 'INDICATE',
'INITIAL', 'INITIALIZED', 'INPUT', 'INTO', 'INTRINSIC', 'INVALID',
'IS', 'JUST', 'JUSTIFIED', 'KEY', 'LABEL',
'LAST', 'LEADING', 'LEFT', 'LENGTH', 'LIMIT', 'LIMITS', 'LINAGE',
'LINAGE-COUNTER', 'LINE', 'LINES', 'LOCALE', 'LOCK',
'LOWLIGHT', 'MANUAL', 'MEMORY', 'MINUS', 'MODE', 'MULTIPLE',
'NATIONAL', 'NATIONAL-EDITED', 'NATIVE', 'NEGATIVE', 'NEXT', 'NO',
'NULL', 'NULLS', 'NUMBER', 'NUMBERS', 'NUMERIC', 'NUMERIC-EDITED',
'OBJECT-COMPUTER', 'OCCURS', 'OF', 'OFF', 'OMITTED', 'ON', 'ONLY',
'OPTIONAL', 'ORDER', 'ORGANIZATION', 'OTHER', 'OUTPUT', 'OVERFLOW',
'OVERLINE', 'PACKED-DECIMAL', 'PADDING', 'PAGE', 'PARAGRAPH',
'PLUS', 'POINTER', 'POSITION', 'POSITIVE', 'PRESENT', 'PREVIOUS',
'PRINTER', 'PRINTING', 'PROCEDURE-POINTER', 'PROCEDURES',
'PROCEED', 'PROGRAM', 'PROGRAM-POINTER', 'PROMPT', 'QUOTE',
'QUOTES', 'RANDOM', 'RD', 'RECORD', 'RECORDING', 'RECORDS', 'RECURSIVE',
'REDEFINES', 'REEL', 'REFERENCE', 'RELATIVE', 'REMAINDER', 'REMOVAL',
'RENAMES', 'REPLACING', 'REPORT', 'REPORTING', 'REPORTS', 'REPOSITORY',
'REQUIRED', 'RESERVE', 'RETURNING', 'REVERSE-VIDEO', 'REWIND',
'RIGHT', 'ROLLBACK', 'ROUNDED', 'RUN', 'SAME', 'SCROLL',
'SECURE', 'SEGMENT-LIMIT', 'SELECT', 'SENTENCE', 'SEPARATE',
'SEQUENCE', 'SEQUENTIAL', 'SHARING', 'SIGN', 'SIGNED', 'SIGNED-INT',
'SIGNED-LONG', 'SIGNED-SHORT', 'SIZE', 'SORT-MERGE', 'SOURCE',
'SOURCE-COMPUTER', 'SPECIAL-NAMES', 'STANDARD',
'STANDARD-1', 'STANDARD-2', 'STATUS', 'SUM',
'SYMBOLIC', 'SYNC', 'SYNCHRONIZED', 'TALLYING', 'TAPE',
'TEST', 'THROUGH', 'THRU', 'TIME', 'TIMES', 'TO', 'TOP', 'TRAILING',
'TRANSFORM', 'TYPE', 'UNDERLINE', 'UNIT', 'UNSIGNED',
'UNSIGNED-INT', 'UNSIGNED-LONG', 'UNSIGNED-SHORT', 'UNTIL', 'UP',
'UPDATE', 'UPON', 'USAGE', 'USING', 'VALUE', 'VALUES', 'VARYING',
'WAIT', 'WHEN', 'WITH', 'WORDS', 'YYYYDDD', 'YYYYMMDD'),
prefix=r'(^|(?<=[^\w\-]))', suffix=r'\s*($|(?=[^\w\-]))'),
Keyword.Pseudo),
# inactive reserved words
(words((
'ACTIVE-CLASS', 'ALIGNED', 'ANYCASE', 'ARITHMETIC', 'ATTRIBUTE',
'B-AND', 'B-NOT', 'B-OR', 'B-XOR', 'BIT', 'BOOLEAN', 'CD', 'CENTER',
'CF', 'CH', 'CHAIN', 'CLASS-ID', 'CLASSIFICATION', 'COMMUNICATION',
'CONDITION', 'DATA-POINTER', 'DESTINATION', 'DISABLE', 'EC', 'EGI',
'EMI', 'ENABLE', 'END-RECEIVE', 'ENTRY-CONVENTION', 'EO', 'ESI',
'EXCEPTION-OBJECT', 'EXPANDS', 'FACTORY', 'FLOAT-BINARY-16',
'FLOAT-BINARY-34', 'FLOAT-BINARY-7', 'FLOAT-DECIMAL-16',
'FLOAT-DECIMAL-34', 'FLOAT-EXTENDED', 'FORMAT', 'FUNCTION-POINTER',
'GET', 'GROUP-USAGE', 'IMPLEMENTS', 'INFINITY', 'INHERITS',
'INTERFACE', 'INTERFACE-ID', 'INVOKE', 'LC_ALL', 'LC_COLLATE',
'LC_CTYPE', 'LC_MESSAGES', 'LC_MONETARY', 'LC_NUMERIC', 'LC_TIME',
'LINE-COUNTER', 'MESSAGE', 'METHOD', 'METHOD-ID', 'NESTED', 'NONE',
'NORMAL', 'OBJECT', 'OBJECT-REFERENCE', 'OPTIONS', 'OVERRIDE',
'PAGE-COUNTER', 'PF', 'PH', 'PROPERTY', 'PROTOTYPE', 'PURGE',
'QUEUE', 'RAISE', 'RAISING', 'RECEIVE', 'RELATION', 'REPLACE',
'REPRESENTS-NOT-A-NUMBER', 'RESET', 'RESUME', 'RETRY', 'RF', 'RH',
'SECONDS', 'SEGMENT', 'SELF', 'SEND', 'SOURCES', 'STATEMENT',
'STEP', 'STRONG', 'SUB-QUEUE-1', 'SUB-QUEUE-2', 'SUB-QUEUE-3',
'SUPER', 'SYMBOL', 'SYSTEM-DEFAULT', 'TABLE', 'TERMINAL', 'TEXT',
'TYPEDEF', 'UCS-4', 'UNIVERSAL', 'USER-DEFAULT', 'UTF-16', 'UTF-8',
'VAL-STATUS', 'VALID', 'VALIDATE', 'VALIDATE-STATUS'),
prefix=r'(^|(?<=[^\w\-]))', suffix=r'\s*($|(?=[^\w\-]))'),
Error),
# Data Types
(r'(^|(?<=[^\w\-]))'
r'(PIC\s+.+?(?=(\s|\.\s))|PICTURE\s+.+?(?=(\s|\.\s))|'
r'(COMPUTATIONAL)(-[1-5X])?|(COMP)(-[1-5X])?|'
r'BINARY-C-LONG|'
r'BINARY-CHAR|BINARY-DOUBLE|BINARY-LONG|BINARY-SHORT|'
r'BINARY)\s*($|(?=[^\w\-]))', Keyword.Type),
# Operators
(r'(\*\*|\*|\+|-|/|<=|>=|<|>|==|/=|=)', Operator),
# (r'(::)', Keyword.Declaration),
(r'([(),;:&%.])', Punctuation),
# Intrinsics
(r'(^|(?<=[^\w\-]))(ABS|ACOS|ANNUITY|ASIN|ATAN|BYTE-LENGTH|'
r'CHAR|COMBINED-DATETIME|CONCATENATE|COS|CURRENT-DATE|'
r'DATE-OF-INTEGER|DATE-TO-YYYYMMDD|DAY-OF-INTEGER|DAY-TO-YYYYDDD|'
r'EXCEPTION-(?:FILE|LOCATION|STATEMENT|STATUS)|EXP10|EXP|E|'
r'FACTORIAL|FRACTION-PART|INTEGER-OF-(?:DATE|DAY|PART)|INTEGER|'
r'LENGTH|LOCALE-(?:DATE|TIME(?:-FROM-SECONDS)?)|LOG(?:10)?|'
r'LOWER-CASE|MAX|MEAN|MEDIAN|MIDRANGE|MIN|MOD|NUMVAL(?:-C)?|'
r'ORD(?:-MAX|-MIN)?|PI|PRESENT-VALUE|RANDOM|RANGE|REM|REVERSE|'
r'SECONDS-FROM-FORMATTED-TIME|SECONDS-PAST-MIDNIGHT|SIGN|SIN|SQRT|'
r'STANDARD-DEVIATION|STORED-CHAR-LENGTH|SUBSTITUTE(?:-CASE)?|'
r'SUM|TAN|TEST-DATE-YYYYMMDD|TEST-DAY-YYYYDDD|TRIM|'
r'UPPER-CASE|VARIANCE|WHEN-COMPILED|YEAR-TO-YYYY)\s*'
r'($|(?=[^\w\-]))', Name.Function),
# Booleans
(r'(^|(?<=[^\w\-]))(true|false)\s*($|(?=[^\w\-]))', Name.Builtin),
# Comparing Operators
(r'(^|(?<=[^\w\-]))(equal|equals|ne|lt|le|gt|ge|'
r'greater|less|than|not|and|or)\s*($|(?=[^\w\-]))', Operator.Word),
],
# \"[^\"\n]*\"|\'[^\'\n]*\'
'strings': [
# apparently strings can be delimited by EOL if they are continued
# in the next line
(r'"[^"\n]*("|\n)', String.Double),
(r"'[^'\n]*('|\n)", String.Single),
],
'nums': [
(r'\d+(\s*|\.$|$)', Number.Integer),
(r'[+-]?\d*\.\d+(E[-+]?\d+)?', Number.Float),
(r'[+-]?\d+\.\d*(E[-+]?\d+)?', Number.Float),
],
}
| CobolLexer |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_eventbridge.py | {
"start": 3781,
"end": 5946
} | class ____:
def test_init(self):
op = EventBridgePutRuleOperator(
task_id="events_put_rule_job",
name=RULE_NAME,
event_pattern=EVENT_PATTERN,
aws_conn_id="fake-conn-id",
region_name="eu-west-1",
verify="/spam/egg.pem",
botocore_config={"read_timeout": 42},
)
assert op.event_pattern == EVENT_PATTERN
assert op.hook.client_type == "events"
assert op.hook.resource_type is None
assert op.hook.aws_conn_id == "fake-conn-id"
assert op.hook._region_name == "eu-west-1"
assert op.hook._verify == "/spam/egg.pem"
assert op.hook._config is not None
assert op.hook._config.read_timeout == 42
op = EventBridgePutRuleOperator(
task_id="events_put_rule_job", name=RULE_NAME, event_pattern=EVENT_PATTERN
)
assert op.hook.aws_conn_id == "aws_default"
assert op.hook._region_name is None
assert op.hook._verify is None
assert op.hook._config is None
@mock.patch.object(EventBridgeHook, "conn")
def test_execute(self, mock_conn: MagicMock):
hook_response = {"RuleArn": "arn:aws:events:us-east-1:123456789012:rule/test"}
mock_conn.put_rule.return_value = hook_response
operator = EventBridgePutRuleOperator(
task_id="events_put_rule_job",
name=RULE_NAME,
event_pattern=EVENT_PATTERN,
)
result = operator.execute(context={})
assert result == hook_response
def test_put_rule_with_bad_json_fails(self):
operator = EventBridgePutRuleOperator(
task_id="failed_put_rule_job",
name=RULE_NAME,
event_pattern="invalid json",
)
with pytest.raises(ValueError, match="`event_pattern` must be a valid JSON string."):
operator.execute(None)
def test_template_fields(self):
operator = EventBridgePutRuleOperator(
task_id="events_put_rule_job", name=RULE_NAME, event_pattern=EVENT_PATTERN
)
validate_template_fields(operator)
| TestEventBridgePutRuleOperator |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 883,
"end": 1057
} | class ____(A1):
def m2(self, x):
_test_sink(x) # No issue
def no_call_to_parent_class(b: B1):
b.m0(_test_source())
"""
A2
/ \
B2 C2
\ /
D2
"""
| C1 |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 102231,
"end": 107398
} | class ____(ModelOutput):
"""
Base class for time series model's decoder outputs that also contain the loss as well as the parameters of the
chosen distribution.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when a `future_values` is provided):
Distributional loss.
params (`torch.FloatTensor` of shape `(batch_size, num_samples, num_params)`):
Parameters of the chosen distribution.
past_key_values (`EncoderDecoderCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.EncoderDecoderCache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
weighted average in the cross-attention heads.
encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
loc (`torch.FloatTensor` of shape `(batch_size,)` or `(batch_size, input_size)`, *optional*):
Shift values of each time series' context window which is used to give the model inputs of the same
magnitude and then used to shift back to the original magnitude.
scale (`torch.FloatTensor` of shape `(batch_size,)` or `(batch_size, input_size)`, *optional*):
Scaling values of each time series' context window which is used to give the model inputs of the same
magnitude and then used to rescale back to the original magnitude.
static_features (`torch.FloatTensor` of shape `(batch_size, feature size)`, *optional*):
Static features of each time series' in a batch which are copied to the covariates at inference time.
"""
loss: Optional[torch.FloatTensor] = None
params: Optional[tuple[torch.FloatTensor, ...]] = None
past_key_values: Optional[EncoderDecoderCache] = None
decoder_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
decoder_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
cross_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
encoder_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
loc: Optional[torch.FloatTensor] = None
scale: Optional[torch.FloatTensor] = None
static_features: Optional[torch.FloatTensor] = None
@dataclass
| Seq2SeqTSPredictionOutput |
python | ray-project__ray | rllib/examples/connectors/classes/add_other_agents_row_index_to_xy_pos.py | {
"start": 234,
"end": 4829
} | class ____(MultiAgentObservationPreprocessor):
"""Adds other agent's row index to an x/y-observation for an agent.
Run this connector with this env:
:py:class:`~ray.rllib.examples.env.classes.multi_agent.double_row_corridor_env.DoubleRowCorridorEnv` # noqa
In this env, 2 agents walk around in a grid-world and must, each separately, reach
their individual goal position to receive a final reward. However, if they collide
while search for these goal positions, another larger reward is given to both
agents. Thus, optimal policies aim at seeking the other agent first, and only then
proceeding to their agent's goal position.
Each agents' observation space is a 2-tuple encoding the x/y position
(x=row, y=column).
This connector converts these observations to:
A dict for `agent_0` of structure:
{
"agent": Discrete index encoding the position of the agent,
"other_agent_row": Discrete(2), indicating whether the other agent is in row 0
or row 1,
}
And a 3-tuple for `agent_1`, encoding the x/y position of `agent_1` plus the row
index (0 or 1) of `agent_0`.
Note that the row information for the respective other agent, which this connector
provides, is needed for learning an optimal policy for any of the agents, because
the env rewards the first collision between the two agents. Hence, an agent needs to
have information on which row the respective other agent is currently in, so it can
change to this row and try to collide with this other agent.
"""
@override(MultiAgentObservationPreprocessor)
def recompute_output_observation_space(
self,
input_observation_space,
input_action_space,
) -> gym.Space:
"""Maps the original (input) observation space to the new one.
Original observation space is `Dict({agent_n: Box(4,), ...})`.
Converts the space for `self.agent` into information specific to this agent,
plus the current row of the respective other agent.
Output observation space is then:
`Dict({`agent_n`: Dict(Discrete, Discrete), ...}), where the 1st Discrete
is the position index of the agent and the 2nd Discrete encodes the current row
of the other agent (0 or 1). If the other agent is already done with the episode
(has reached its goal state) a special value of 2 is used.
"""
agent_0_space = input_observation_space.spaces["agent_0"]
self._env_corridor_len = agent_0_space.high[1] + 1 # Box.high is inclusive.
# Env has always 2 rows (and `self._env_corridor_len` columns).
num_discrete = int(2 * self._env_corridor_len)
spaces = {
"agent_0": gym.spaces.Dict(
{
# Exact position of this agent (as an int index).
"agent": gym.spaces.Discrete(num_discrete),
# Row (0 or 1) of other agent. Or 2, if other agent is already done.
"other_agent_row": gym.spaces.Discrete(3),
}
),
"agent_1": gym.spaces.Box(
0,
agent_0_space.high[1], # 1=column
shape=(3,),
dtype=np.float32,
),
}
return gym.spaces.Dict(spaces)
@override(MultiAgentObservationPreprocessor)
def preprocess(self, observations, episode) -> Any:
# Observations: dict of keys "agent_0" and "agent_1", mapping to the respective
# x/y positions of these agents (x=row, y=col).
# For example: [1.0, 4.0] means the agent is in row 1 and column 4.
new_obs = {}
# 2=agent is already done
row_agent_0 = observations.get("agent_0", [2])[0]
row_agent_1 = observations.get("agent_1", [2])[0]
if "agent_0" in observations:
# Compute `agent_0` and `agent_1` enhanced observation.
index_obs_agent_0 = (
observations["agent_0"][0] * self._env_corridor_len
+ observations["agent_0"][1]
)
new_obs["agent_0"] = {
"agent": index_obs_agent_0,
"other_agent_row": row_agent_1,
}
if "agent_1" in observations:
new_obs["agent_1"] = np.array(
[
observations["agent_1"][0],
observations["agent_1"][1],
row_agent_0,
],
dtype=np.float32,
)
return new_obs
| AddOtherAgentsRowIndexToXYPos |
python | psf__black | src/black/lines.py | {
"start": 870,
"end": 17675
} | class ____:
"""Holds leaves and comments. Can be printed with `str(line)`."""
mode: Mode = field(repr=False)
depth: int = 0
leaves: list[Leaf] = field(default_factory=list)
# keys ordered like `leaves`
comments: dict[LeafID, list[Leaf]] = field(default_factory=dict)
bracket_tracker: BracketTracker = field(default_factory=BracketTracker)
inside_brackets: bool = False
should_split_rhs: bool = False
magic_trailing_comma: Leaf | None = None
def append(
self, leaf: Leaf, preformatted: bool = False, track_bracket: bool = False
) -> None:
"""Add a new `leaf` to the end of the line.
Unless `preformatted` is True, the `leaf` will receive a new consistent
whitespace prefix and metadata applied by :class:`BracketTracker`.
Trailing commas are maybe removed, unpacked for loop variables are
demoted from being delimiters.
Inline comments are put aside.
"""
has_value = (
leaf.type in BRACKETS
# empty fstring and tstring middles must not be truncated
or leaf.type in (token.FSTRING_MIDDLE, token.TSTRING_MIDDLE)
or bool(leaf.value.strip())
)
if not has_value:
return
if leaf.type == token.COLON and self.is_class_paren_empty:
del self.leaves[-2:]
if self.leaves and not preformatted:
# Note: at this point leaf.prefix should be empty except for
# imports, for which we only preserve newlines.
leaf.prefix += whitespace(
leaf,
complex_subscript=self.is_complex_subscript(leaf),
mode=self.mode,
)
if self.inside_brackets or not preformatted or track_bracket:
self.bracket_tracker.mark(leaf)
if self.mode.magic_trailing_comma:
if self.has_magic_trailing_comma(leaf):
self.magic_trailing_comma = leaf
elif self.has_magic_trailing_comma(leaf):
self.remove_trailing_comma()
if not self.append_comment(leaf):
self.leaves.append(leaf)
def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
"""Like :func:`append()` but disallow invalid standalone comment structure.
Raises ValueError when any `leaf` is appended after a standalone comment
or when a standalone comment is not the first leaf on the line.
"""
if (
self.bracket_tracker.depth == 0
or self.bracket_tracker.any_open_for_or_lambda()
):
if self.is_comment:
raise ValueError("cannot append to standalone comments")
if self.leaves and leaf.type == STANDALONE_COMMENT:
raise ValueError(
"cannot append standalone comments to a populated line"
)
self.append(leaf, preformatted=preformatted)
@property
def is_comment(self) -> bool:
"""Is this line a standalone comment?"""
return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
@property
def is_decorator(self) -> bool:
"""Is this line a decorator?"""
return bool(self) and self.leaves[0].type == token.AT
@property
def is_import(self) -> bool:
"""Is this an import line?"""
return bool(self) and is_import(self.leaves[0])
@property
def is_with_or_async_with_stmt(self) -> bool:
"""Is this a with_stmt line?"""
return bool(self) and is_with_or_async_with_stmt(self.leaves[0])
@property
def is_class(self) -> bool:
"""Is this line a class definition?"""
return (
bool(self)
and self.leaves[0].type == token.NAME
and self.leaves[0].value == "class"
)
@property
def is_stub_class(self) -> bool:
"""Is this line a class definition with a body consisting only of "..."?"""
return self.is_class and self.leaves[-3:] == [
Leaf(token.DOT, ".") for _ in range(3)
]
@property
def is_def(self) -> bool:
"""Is this a function definition? (Also returns True for async defs.)"""
try:
first_leaf = self.leaves[0]
except IndexError:
return False
try:
second_leaf: Leaf | None = self.leaves[1]
except IndexError:
second_leaf = None
return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
first_leaf.type == token.ASYNC
and second_leaf is not None
and second_leaf.type == token.NAME
and second_leaf.value == "def"
)
@property
def is_stub_def(self) -> bool:
"""Is this line a function definition with a body consisting only of "..."?"""
return self.is_def and self.leaves[-4:] == [Leaf(token.COLON, ":")] + [
Leaf(token.DOT, ".") for _ in range(3)
]
@property
def is_class_paren_empty(self) -> bool:
"""Is this a class with no base classes but using parentheses?
Those are unnecessary and should be removed.
"""
return (
bool(self)
and len(self.leaves) == 4
and self.is_class
and self.leaves[2].type == token.LPAR
and self.leaves[2].value == "("
and self.leaves[3].type == token.RPAR
and self.leaves[3].value == ")"
)
@property
def _is_triple_quoted_string(self) -> bool:
"""Is the line a triple quoted string?"""
if not self or self.leaves[0].type != token.STRING:
return False
value = self.leaves[0].value
if value.startswith(('"""', "'''")):
return True
if value.startswith(("r'''", 'r"""', "R'''", 'R"""')):
return True
return False
@property
def is_docstring(self) -> bool:
"""Is the line a docstring?"""
return bool(self) and is_docstring(self.leaves[0])
@property
def is_chained_assignment(self) -> bool:
"""Is the line a chained assignment"""
return [leaf.type for leaf in self.leaves].count(token.EQUAL) > 1
@property
def opens_block(self) -> bool:
"""Does this line open a new level of indentation."""
if len(self.leaves) == 0:
return False
return self.leaves[-1].type == token.COLON
def is_fmt_pass_converted(
self, *, first_leaf_matches: Callable[[Leaf], bool] | None = None
) -> bool:
"""Is this line converted from fmt off/skip code?
If first_leaf_matches is not None, it only returns True if the first
leaf of converted code matches.
"""
if len(self.leaves) != 1:
return False
leaf = self.leaves[0]
if (
leaf.type != STANDALONE_COMMENT
or leaf.fmt_pass_converted_first_leaf is None
):
return False
return first_leaf_matches is None or first_leaf_matches(
leaf.fmt_pass_converted_first_leaf
)
def contains_standalone_comments(self) -> bool:
"""If so, needs to be split before emitting."""
for leaf in self.leaves:
if leaf.type == STANDALONE_COMMENT:
return True
return False
def contains_implicit_multiline_string_with_comments(self) -> bool:
"""Chck if we have an implicit multiline string with comments on the line"""
for leaf_type, leaf_group_iterator in itertools.groupby(
self.leaves, lambda leaf: leaf.type
):
if leaf_type != token.STRING:
continue
leaf_list = list(leaf_group_iterator)
if len(leaf_list) == 1:
continue
for leaf in leaf_list:
if self.comments_after(leaf):
return True
return False
def contains_uncollapsable_type_comments(self) -> bool:
ignored_ids = set()
try:
last_leaf = self.leaves[-1]
ignored_ids.add(id(last_leaf))
if last_leaf.type == token.COMMA or (
last_leaf.type == token.RPAR and not last_leaf.value
):
# When trailing commas or optional parens are inserted by Black for
# consistency, comments after the previous last element are not moved
# (they don't have to, rendering will still be correct). So we ignore
# trailing commas and invisible.
last_leaf = self.leaves[-2]
ignored_ids.add(id(last_leaf))
except IndexError:
return False
# A type comment is uncollapsable if it is attached to a leaf
# that isn't at the end of the line (since that could cause it
# to get associated to a different argument) or if there are
# comments before it (since that could cause it to get hidden
# behind a comment.
comment_seen = False
for leaf_id, comments in self.comments.items():
for comment in comments:
if is_type_comment(comment, mode=self.mode):
if comment_seen or (
not is_type_ignore_comment(comment, mode=self.mode)
and leaf_id not in ignored_ids
):
return True
comment_seen = True
return False
def contains_unsplittable_type_ignore(self) -> bool:
if not self.leaves:
return False
# If a 'type: ignore' is attached to the end of a line, we
# can't split the line, because we can't know which of the
# subexpressions the ignore was meant to apply to.
#
# We only want this to apply to actual physical lines from the
# original source, though: we don't want the presence of a
# 'type: ignore' at the end of a multiline expression to
# justify pushing it all onto one line. Thus we
# (unfortunately) need to check the actual source lines and
# only report an unsplittable 'type: ignore' if this line was
# one line in the original code.
# Grab the first and last line numbers, skipping generated leaves
first_line = next((leaf.lineno for leaf in self.leaves if leaf.lineno != 0), 0)
last_line = next(
(leaf.lineno for leaf in reversed(self.leaves) if leaf.lineno != 0), 0
)
if first_line == last_line:
# We look at the last two leaves since a comma or an
# invisible paren could have been added at the end of the
# line.
for node in self.leaves[-2:]:
for comment in self.comments.get(id(node), []):
if is_type_ignore_comment(comment, mode=self.mode):
return True
return False
def contains_multiline_strings(self) -> bool:
return any(is_multiline_string(leaf) for leaf in self.leaves)
def has_magic_trailing_comma(self, closing: Leaf) -> bool:
"""Return True if we have a magic trailing comma, that is when:
- there's a trailing comma here
- it's not from single-element square bracket indexing
- it's not a one-tuple
"""
if not (
closing.type in CLOSING_BRACKETS
and self.leaves
and self.leaves[-1].type == token.COMMA
):
return False
if closing.type == token.RBRACE:
return True
if closing.type == token.RSQB:
if (
closing.parent is not None
and closing.parent.type == syms.trailer
and closing.opening_bracket is not None
and is_one_sequence_between(
closing.opening_bracket,
closing,
self.leaves,
brackets=(token.LSQB, token.RSQB),
)
):
assert closing.prev_sibling is not None
assert closing.prev_sibling.type == syms.subscriptlist
return False
return True
if self.is_import:
return True
if closing.opening_bracket is not None and not is_one_sequence_between(
closing.opening_bracket, closing, self.leaves
):
return True
return False
def append_comment(self, comment: Leaf) -> bool:
"""Add an inline or standalone comment to the line."""
if (
comment.type == STANDALONE_COMMENT
and self.bracket_tracker.any_open_brackets()
):
comment.prefix = ""
return False
if comment.type != token.COMMENT:
return False
if not self.leaves:
comment.type = STANDALONE_COMMENT
comment.prefix = ""
return False
last_leaf = self.leaves[-1]
if (
last_leaf.type == token.RPAR
and not last_leaf.value
and last_leaf.parent
and len(list(last_leaf.parent.leaves())) <= 3
and not is_type_comment(comment, mode=self.mode)
):
# Comments on an optional parens wrapping a single leaf should belong to
# the wrapped node except if it's a type comment. Pinning the comment like
# this avoids unstable formatting caused by comment migration.
if len(self.leaves) < 2:
comment.type = STANDALONE_COMMENT
comment.prefix = ""
return False
last_leaf = self.leaves[-2]
self.comments.setdefault(id(last_leaf), []).append(comment)
return True
def comments_after(self, leaf: Leaf) -> list[Leaf]:
"""Generate comments that should appear directly after `leaf`."""
return self.comments.get(id(leaf), [])
def remove_trailing_comma(self) -> None:
"""Remove the trailing comma and moves the comments attached to it."""
trailing_comma = self.leaves.pop()
trailing_comma_comments = self.comments.pop(id(trailing_comma), [])
self.comments.setdefault(id(self.leaves[-1]), []).extend(
trailing_comma_comments
)
def is_complex_subscript(self, leaf: Leaf) -> bool:
"""Return True iff `leaf` is part of a slice with non-trivial exprs."""
open_lsqb = self.bracket_tracker.get_open_lsqb()
if open_lsqb is None:
return False
subscript_start = open_lsqb.next_sibling
if isinstance(subscript_start, Node):
if subscript_start.type == syms.listmaker:
return False
if subscript_start.type == syms.subscriptlist:
subscript_start = child_towards(subscript_start, leaf)
return subscript_start is not None and any(
n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
)
def enumerate_with_length(
self, is_reversed: bool = False
) -> Iterator[tuple[Index, Leaf, int]]:
"""Return an enumeration of leaves with their length.
Stops prematurely on multiline strings and standalone comments.
"""
op = cast(
Callable[[Sequence[Leaf]], Iterator[tuple[Index, Leaf]]],
enumerate_reversed if is_reversed else enumerate,
)
for index, leaf in op(self.leaves):
length = len(leaf.prefix) + len(leaf.value)
if "\n" in leaf.value:
return # Multiline strings, we can't continue.
for comment in self.comments_after(leaf):
length += len(comment.value)
yield index, leaf, length
def clone(self) -> "Line":
return Line(
mode=self.mode,
depth=self.depth,
inside_brackets=self.inside_brackets,
should_split_rhs=self.should_split_rhs,
magic_trailing_comma=self.magic_trailing_comma,
)
def __str__(self) -> str:
"""Render the line."""
if not self:
return "\n"
indent = " " * self.depth
leaves = iter(self.leaves)
first = next(leaves)
res = f"{first.prefix}{indent}{first.value}"
res += "".join(str(leaf) for leaf in leaves)
comments_iter = itertools.chain.from_iterable(self.comments.values())
comments = [str(comment) for comment in comments_iter]
res += "".join(comments)
return res + "\n"
def __bool__(self) -> bool:
"""Return True if the line has leaves or comments."""
return bool(self.leaves or self.comments)
@dataclass
| Line |
python | getsentry__sentry | tests/sentry/incidents/models/test_incidents.py | {
"start": 7288,
"end": 9988
} | class ____(TestCase):
def test_simple(self) -> None:
title = "hello"
alert_rule = self.create_alert_rule()
incident = Incident.objects.create(
self.organization,
title=title,
type=IncidentType.ALERT_TRIGGERED.value,
alert_rule=alert_rule,
)
assert incident.identifier == 1
assert incident.title == title
# Check identifier correctly increments
incident = Incident.objects.create(
self.organization,
title=title,
type=IncidentType.ALERT_TRIGGERED.value,
alert_rule=alert_rule,
)
assert incident.identifier == 2
def test_identifier_conflict(self) -> None:
create_method = BaseManager.create
call_count = [0]
alert_rule = self.create_alert_rule()
def mock_base_create(*args, **kwargs):
if not call_count[0]:
call_count[0] += 1
# This incident will take the identifier we already fetched and
# use it, which will cause the database to throw an integrity
# error.
with transaction.atomic(router.db_for_write(Incident)):
incident = Incident.objects.create(
self.organization,
status=IncidentStatus.OPEN.value,
title="Conflicting Incident",
type=IncidentType.ALERT_TRIGGERED.value,
alert_rule=alert_rule,
)
assert incident.identifier == kwargs["identifier"]
create_method(*args, **kwargs)
self.fail("Expected an integrity error")
else:
call_count[0] += 1
return create_method(*args, **kwargs)
self.organization
with patch.object(BaseManager, "create", new=mock_base_create):
incident = Incident.objects.create(
self.organization,
alert_rule=alert_rule,
status=IncidentStatus.OPEN.value,
title="hi",
type=IncidentType.ALERT_TRIGGERED.value,
)
# We should have 3 calls - one for initial create, one for conflict,
# then the final one for the retry we get due to the conflict
assert call_count[0] == 3
# Ideally this would be 2, but because we create the conflicting
# row inside of a transaction it ends up rolled back. We just want
# to verify that it was created successfully.
assert incident.identifier == 1
@freeze_time()
| IncidentCreationTest |
python | huggingface__transformers | src/transformers/models/dbrx/modeling_dbrx.py | {
"start": 18213,
"end": 19513
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: DbrxConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.d_model
self.resid_pdrop = config.resid_pdrop
self.layer_idx = layer_idx
self.norm_attn_norm = DbrxNormAttentionNorm(
config=config,
layer_idx=layer_idx,
)
self.ffn = DbrxFFN(config=config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_embeddings: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Any,
):
resid_states, hidden_states = self.norm_attn_norm(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_embeddings=position_embeddings,
past_key_values=past_key_values,
cache_position=cache_position,
**kwargs,
)
hidden_states = self.ffn(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.resid_pdrop, training=self.training)
hidden_states = resid_states + hidden_states
return hidden_states
| DbrxBlock |
python | huggingface__transformers | src/transformers/models/diffllama/modeling_diffllama.py | {
"start": 35365,
"end": 35686
} | class ____(GenericForTokenClassification, DiffLlamaPreTrainedModel):
pass
__all__ = [
"DiffLlamaPreTrainedModel",
"DiffLlamaModel",
"DiffLlamaForCausalLM",
"DiffLlamaForSequenceClassification",
"DiffLlamaForQuestionAnswering",
"DiffLlamaForTokenClassification",
]
| DiffLlamaForTokenClassification |
python | django-mptt__django-mptt | tests/myapp/tests.py | {
"start": 81209,
"end": 81571
} | class ____(ModelAdmin):
list_filter = (
("books_fk", TreeRelatedFieldListFilter),
("books_m2m", TreeRelatedFieldListFilter),
)
ordering = ("id",)
@unittest.skipUnless(
django.VERSION < (5,),
"Django 5 has changed the way filters work and I don't want to spend the time writing the compatibility code right now.",
)
| CategoryAdmin |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/serdes/serdes.py | {
"start": 29706,
"end": 30941
} | class ____(ObjectSerializer[T_PydanticModel]):
def object_as_mapping(self, value: T_PydanticModel) -> Mapping[str, Any]:
value_dict = value.__dict__
result = {}
for key, field in self._model_fields.items():
if field.alias is None and (
field.serialization_alias is not None or field.validation_alias is not None
):
raise SerializationError(
"Can't serialize pydantic models with serialization or validation aliases. Use "
"the storage_field_names argument to whitelist_for_serdes instead."
)
result_key = field.alias if field.alias else key
result[result_key] = value_dict[key]
return result
@cached_property
def constructor_param_names(self) -> Sequence[str]: # pyright: ignore[reportIncompatibleMethodOverride]
return [field.alias or key for key, field in self._model_fields.items()]
@cached_property
def _model_fields(self) -> Mapping[str, Any]:
# defer for import performance
from dagster_shared.dagster_model.pydantic_compat_layer import model_fields
return model_fields(self.klass)
| PydanticModelSerializer |
python | pyca__cryptography | tests/x509/test_x509.py | {
"start": 262217,
"end": 266299
} | class ____:
def test_get_attribute_for_oid_challenge(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "challenge.pem"),
x509.load_pem_x509_csr,
)
assert request.attributes.get_attribute_for_oid(
x509.oid.AttributeOID.CHALLENGE_PASSWORD
) == x509.Attribute(
x509.oid.AttributeOID.CHALLENGE_PASSWORD,
b"challenge me!",
)
def test_get_attribute_for_oid_multiple(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "challenge-unstructured.pem"),
x509.load_pem_x509_csr,
)
assert request.attributes.get_attribute_for_oid(
x509.oid.AttributeOID.CHALLENGE_PASSWORD
) == x509.Attribute(
x509.oid.AttributeOID.CHALLENGE_PASSWORD,
b"beauty",
)
assert request.attributes.get_attribute_for_oid(
x509.oid.AttributeOID.UNSTRUCTURED_NAME
) == x509.Attribute(
x509.oid.AttributeOID.UNSTRUCTURED_NAME,
b"an unstructured field",
)
def test_unsupported_asn1_type_in_attribute(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "challenge-invalid.der"),
x509.load_der_x509_csr,
)
# supported in the new path where we just store the type and
# return raw bytes
attr = request.attributes.get_attribute_for_oid(
x509.oid.AttributeOID.CHALLENGE_PASSWORD
)
assert attr._type == 2
def test_long_form_asn1_tag_in_attribute(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "long-form-attribute.pem"),
x509.load_pem_x509_csr,
)
with pytest.raises(ValueError, match="Long-form"):
request.attributes
def test_challenge_multivalued(self, backend):
"""
We only support single-valued SETs in our X509 request attributes
"""
request = _load_cert(
os.path.join("x509", "requests", "challenge-multi-valued.der"),
x509.load_der_x509_csr,
)
with pytest.raises(ValueError, match="Only single-valued"):
request.attributes
def test_no_challenge_password(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "rsa_sha256.pem"),
x509.load_pem_x509_csr,
)
with pytest.raises(x509.AttributeNotFound) as exc:
request.attributes.get_attribute_for_oid(
x509.oid.AttributeOID.CHALLENGE_PASSWORD
)
assert exc.value.oid == x509.oid.AttributeOID.CHALLENGE_PASSWORD
def test_no_attributes(self, backend):
request = _load_cert(
os.path.join("x509", "requests", "rsa_sha256.pem"),
x509.load_pem_x509_csr,
)
assert len(request.attributes) == 0
def test_zero_element_attribute(self):
request = _load_cert(
os.path.join("x509", "requests", "zero-element-attribute.pem"),
x509.load_pem_x509_csr,
)
with pytest.raises(ValueError, match="Only single-valued"):
request.attributes
def test_load_pem_x509_certificates():
with pytest.raises(ValueError):
x509.load_pem_x509_certificates(b"")
certs = load_vectors_from_file(
filename=os.path.join("x509", "cryptography.io.chain.pem"),
loader=lambda pemfile: x509.load_pem_x509_certificates(pemfile.read()),
mode="rb",
)
assert len(certs) == 2
assert certs[0].serial_number == 16160
assert certs[1].serial_number == 146039
certs = load_vectors_from_file(
filename=os.path.join(
"x509", "cryptography.io.chain_with_garbage.pem"
),
loader=lambda pemfile: x509.load_pem_x509_certificates(pemfile.read()),
mode="rb",
)
assert len(certs) == 2
assert certs[0].serial_number == 16160
assert certs[1].serial_number == 146039
| TestRequestAttributes |
python | pytorch__pytorch | torch/_utils.py | {
"start": 26158,
"end": 33119
} | class ____:
r"""Wraps an exception plus traceback to communicate across threads"""
def __init__(self, exc_info=None, where="in background"):
# It is important that we don't store exc_info, see
# NOTE [ Python Traceback Reference Cycle Problem ]
if exc_info is None:
exc_info = sys.exc_info()
self.exc_type = exc_info[0]
# pyrefly: ignore [not-iterable]
self.exc_msg = "".join(traceback.format_exception(*exc_info))
self.where = where
def reraise(self):
r"""Reraises the wrapped exception in the current thread"""
# Format a message such as: "Caught ValueError in DataLoader worker
# process 2. Original Traceback:", followed by the traceback.
msg = f"Caught {self.exc_type.__name__} {self.where}.\nOriginal {self.exc_msg}" # pyrefly: ignore [missing-attribute]
if self.exc_type is KeyError:
# KeyError calls repr() on its argument (usually a dict key). This
# makes stack traces unreadable. It will not be changed in Python
# (https://bugs.python.org/issue2651), so we work around it.
msg = KeyErrorMessage(msg)
elif getattr(self.exc_type, "message", None):
# Some exceptions have first argument as non-str but explicitly
# have message field
# pyrefly: ignore [not-callable]
raise self.exc_type(
# pyrefly: ignore [unexpected-keyword]
message=msg
)
try:
exception = self.exc_type(msg) # pyrefly: ignore [not-callable]
except Exception:
# If the exception takes multiple arguments or otherwise can't
# be constructed, don't try to instantiate since we don't know how to
raise RuntimeError(msg) from None
raise exception
def _get_available_device_type():
if torch.cuda.is_available():
return "cuda"
if torch.backends.mps.is_available():
return "mps"
if hasattr(torch, "xpu") and torch.xpu.is_available(): # type: ignore[attr-defined]
return "xpu"
if hasattr(torch, "mtia") and torch.mtia.is_available():
return "mtia"
custom_backend_name = torch._C._get_privateuse1_backend_name()
custom_device_mod = getattr(torch, custom_backend_name, None)
if custom_device_mod and custom_device_mod.is_available():
return custom_backend_name
# add more available device types here
return None
def _get_device_attr(get_member):
device_type = _get_available_device_type()
if device_type and device_type.lower() == "cuda":
return get_member(torch.cuda)
if device_type and device_type.lower() == "mps":
return get_member(torch.mps)
if device_type and device_type.lower() == "xpu":
return get_member(torch.xpu) # type: ignore[attr-defined]
if device_type and device_type.lower() == "mtia":
return get_member(torch.mtia)
if device_type == torch._C._get_privateuse1_backend_name():
return get_member(getattr(torch, device_type))
# add more available device types here
return None
def _get_current_device_index():
# current device index
return _get_device_attr(lambda m: m.current_device())
def _get_all_device_indices():
# all device index
return _get_device_attr(lambda m: list(range(m.device_count())))
def _get_devices_properties(device_ids):
# all device properties
return [_get_device_attr(lambda m: m.get_device_properties(i)) for i in device_ids]
def get_current_device_index() -> int:
r"""Checks if there are CUDA devices available and
returns the device index of the current default CUDA device.
Returns -1 in case there are no CUDA devices available.
Arguments: ``None``
"""
if torch.cuda.device_count() > 0:
return torch.cuda.current_device()
return -1
def _get_device_index(
device: Any,
optional: bool = False,
allow_cpu: bool = False,
) -> int:
r"""Gets the device index from :attr:`device`, which can be a torch.device
object, a Python integer, or ``None``.
If :attr:`device` is a torch.device object, returns the device index if it
has index. Note that for a device without a specified index,
i.e., ``torch.device('xxx')``, this will return the current default
device of that type if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``,
CPU devices will be accepted and ``-1`` will be returned in this case.
If :attr:`device` is a Python integer, it is returned as is.
If :attr:`device` is ``None``, this will return the current default
device of the supported runtime platform if :attr:`optional` is ``True``.
i.e., the current default CUDA device will be returned if CUDA runtime is supported.
"""
if isinstance(device, str):
device = torch.device(device)
device_idx: Optional[int] = None
if isinstance(device, torch.device):
if not allow_cpu and device.type == "cpu":
raise ValueError(f"Expected a non cpu device, but got: {device}")
device_idx = -1 if device.type == "cpu" else device.index
if isinstance(device, int):
device_idx = device
if device_idx is None:
if optional:
# The eager API _get_current_device_index uses `lambda` functions which are
# not supported in JIT and hence not scriptable. The JIT equivalent API to get
# the current device index is `get_current_device_index()` which can
# be scripted. We use is_scripting to check the mode we are in and call the
# appropriate API.
if torch.jit.is_scripting():
device_idx = get_current_device_index()
else:
device_idx = _get_current_device_index()
else:
raise ValueError(
f"Expected a torch.device with a specified index or an integer, but got:{device}"
)
return device_idx
def _handle_complex(tensor):
"""
Returns a real view of a tensor if complex dtype else just the tensor
need to check if a UninitializedParameter because otherwise checking is_complex is an error for a LazyModule
"""
return (
torch.view_as_real(tensor)
if not isinstance(tensor, torch.nn.UninitializedParameter)
and tensor.is_complex()
else tensor
)
def _element_size(dtype):
"""
Returns the element size for a dtype, in bytes
"""
if not isinstance(dtype, torch.dtype):
raise RuntimeError(f"expected torch.dtype, but got {type(dtype)}")
if dtype.is_complex:
return torch.finfo(dtype).bits >> 2
elif dtype.is_floating_point:
return torch.finfo(dtype).bits >> 3
elif dtype == torch.bool:
# NOTE: torch.bool is not supported in torch.iinfo()
return 1
else:
return torch.iinfo(dtype).bits >> 3
| ExceptionWrapper |
python | donnemartin__system-design-primer | solutions/system_design/query_cache/query_cache_snippets.py | {
"start": 825,
"end": 1071
} | class ____(object):
def __init__(self):
self.head = None
self.tail = None
def move_to_front(self, node):
...
def append_to_front(self, node):
...
def remove_from_tail(self):
...
| LinkedList |
python | kamyu104__LeetCode-Solutions | Python/compare-version-numbers.py | {
"start": 48,
"end": 742
} | class ____(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
n1, n2 = len(version1), len(version2)
i, j = 0, 0
while i < n1 or j < n2:
v1, v2 = 0, 0
while i < n1 and version1[i] != '.':
v1 = v1 * 10 + int(version1[i])
i += 1
while j < n2 and version2[j] != '.':
v2 = v2 * 10 + int(version2[j])
j += 1
if v1 != v2:
return 1 if v1 > v2 else -1
i += 1
j += 1
return 0
# Time: O(n)
# Space: O(n)
| Solution |
python | pypa__pipenv | pipenv/vendor/dotenv/variables.py | {
"start": 288,
"end": 588
} | class ____(metaclass=ABCMeta):
def __ne__(self, other: object) -> bool:
result = self.__eq__(other)
if result is NotImplemented:
return NotImplemented
return not result
@abstractmethod
def resolve(self, env: Mapping[str, Optional[str]]) -> str: ...
| Atom |
python | graphql-python__graphene | graphene/relay/tests/test_node_custom.py | {
"start": 649,
"end": 785
} | class ____(ObjectType):
class Meta:
interfaces = [CustomNode]
name = String(description="The full name of the user")
| User |
python | django-extensions__django-extensions | tests/management/commands/shell_plus_tests/test_collision_resolver.py | {
"start": 771,
"end": 870
} | class ____(AppNameCR):
pass
def collision_resolver_which_is_not_class():
pass
| TestAppNameCR |
python | sympy__sympy | sympy/core/containers.py | {
"start": 9479,
"end": 10535
} | class ____(MutableSet):
def __init__(self, iterable=None):
if iterable:
self.map = OrderedDict((item, None) for item in iterable)
else:
self.map = OrderedDict()
def __len__(self):
return len(self.map)
def __contains__(self, key):
return key in self.map
def add(self, key):
self.map[key] = None
def discard(self, key):
self.map.pop(key)
def pop(self, last=True):
return self.map.popitem(last=last)[0]
def __iter__(self):
yield from self.map.keys()
def __repr__(self):
if not self.map:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.map.keys()))
def intersection(self, other):
return self.__class__([val for val in self if val in other])
def difference(self, other):
return self.__class__([val for val in self if val not in other])
def update(self, iterable):
for val in iterable:
self.add(val)
| OrderedSet |
python | ray-project__ray | release/k8s_tests/locustfile.py | {
"start": 564,
"end": 948
} | class ____(HttpUser):
wait_time = locust.wait_time.constant_throughput(10)
def on_start(self):
retries = Retry(
total=3, backoff_factor=0.5, status_forcelist=[429, 500, 502, 503, 504]
)
self.client.mount("http://", TimeoutHTTPAdapter(max_retries=retries, timeout=1))
@task
def index(self):
self.client.get("/?val=3")
| ServeTest |
python | doocs__leetcode | solution/0300-0399/0317.Shortest Distance from All Buildings/Solution.py | {
"start": 0,
"end": 1458
} | class ____:
def shortestDistance(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
q = deque()
total = 0
cnt = [[0] * n for _ in range(m)]
dist = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
total += 1
q.append((i, j))
d = 0
vis = set()
while q:
d += 1
for _ in range(len(q)):
r, c = q.popleft()
for a, b in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
x, y = r + a, c + b
if (
0 <= x < m
and 0 <= y < n
and grid[x][y] == 0
and (x, y) not in vis
):
cnt[x][y] += 1
dist[x][y] += d
q.append((x, y))
vis.add((x, y))
ans = inf
for i in range(m):
for j in range(n):
if grid[i][j] == 0 and cnt[i][j] == total:
ans = min(ans, dist[i][j])
return -1 if ans == inf else ans
| Solution |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/blobstore/api/main.py | {
"start": 1000,
"end": 1099
} | class ____(ndb.Model):
user = ndb.StringProperty()
blob_key = ndb.BlobKeyProperty()
| UserPhoto |
python | getsentry__sentry | src/sentry/notifications/notification_action/action_validation.py | {
"start": 7838,
"end": 11308
} | class ____:
provider = Action.Type.SENTRY_APP
def __init__(self, validated_data: dict[str, Any], organization: Organization) -> None:
self.validated_data = validated_data
self.organization = organization
def _get_sentry_app_installation(
self, sentry_app_identifier: SentryAppIdentifier, target_identifier: str
) -> RpcSentryAppInstallation | None:
"""
Get the sentry app installation based on whether the target identifier is an installation id or sentry app id
We do not want to accept SentryAppIdentifier.SENTRY_APP_INSTALLATION_UUID long term, this is temporary until we migrate the data over
"""
installations = None
installation = None
if sentry_app_identifier == SentryAppIdentifier.SENTRY_APP_INSTALLATION_UUID:
installations = app_service.get_many(
filter=dict(uuids=[target_identifier], organization_id=self.organization.id)
)
else:
installations = app_service.get_many(
filter=dict(app_ids=[int(target_identifier)], organization_id=self.organization.id)
)
if installations:
installation = installations[0]
return installation
def clean_data(self) -> dict[str, Any]:
sentry_app_identifier = SentryAppIdentifier(
self.validated_data["config"]["sentry_app_identifier"]
)
target_identifier = self.validated_data["config"]["target_identifier"]
installation = self._get_sentry_app_installation(sentry_app_identifier, target_identifier)
if not installation:
raise ValidationError("Sentry app installation not found.")
if sentry_app_identifier == SentryAppIdentifier.SENTRY_APP_INSTALLATION_UUID:
# convert to use sentry_app_id until we can migrate all the data
self.validated_data["config"][
"sentry_app_identifier"
] = SentryAppIdentifier.SENTRY_APP_ID
self.validated_data["config"]["target_identifier"] = str(installation.sentry_app.id)
settings = self.validated_data["data"].get("settings", [])
action = {
"settings": settings,
"sentryAppInstallationUuid": installation.uuid,
}
if not settings:
# XXX: it's only ok to not pass settings if there is no sentry app schema
# this means the app doesn't expect any settings
components = app_service.find_app_components(app_id=installation.sentry_app.id)
if any(
component.app_schema
for component in components
if component.type == "alert-rule-action"
):
raise ValidationError("'settings' is a required property")
else:
# Sentry app config blob expects value to be a string
for setting in settings:
if setting.get("value") is not None and not isinstance(setting["value"], str):
setting["value"] = json.dumps(setting["value"])
try:
# Only call creator for Sentry Apps with UI Components (settings) for actions
validate_sentry_app_action(action)
except SentryAppBaseError as e:
raise ValidationError(e.message) from e
return self.validated_data
@action_validator_registry.register(Action.Type.WEBHOOK)
| SentryAppActionValidatorHandler |
python | pydantic__pydantic | pydantic-core/tests/validators/test_is_subclass.py | {
"start": 154,
"end": 2319
} | class ____:
pass
def test_is_subclass_basic():
v = SchemaValidator(core_schema.is_subclass_schema(Foo))
assert v.validate_python(Foo) == Foo
with pytest.raises(ValidationError) as exc_info:
v.validate_python(Bar)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'is_subclass_of',
'loc': (),
'msg': 'Input should be a subclass of Foo',
'input': Bar,
'ctx': {'class': 'Foo'},
}
]
@pytest.mark.parametrize(
'input_value,valid',
[
(Foo, True),
(Foobar, True),
(Bar, False),
(type, False),
(1, False),
('foo', False),
(Foo(), False),
(Foobar(), False),
(Bar(), False),
],
)
def test_is_subclass(input_value, valid):
v = SchemaValidator(core_schema.is_subclass_schema(Foo))
assert v.isinstance_python(input_value) == valid
def test_not_parent():
v = SchemaValidator(core_schema.is_subclass_schema(Foobar))
assert v.isinstance_python(Foobar)
assert not v.isinstance_python(Foo)
def test_invalid_type():
with pytest.raises(SchemaError, match="TypeError: 'Foo' object cannot be cast as 'type"):
SchemaValidator(core_schema.is_subclass_schema(Foo()))
def test_custom_repr():
v = SchemaValidator(core_schema.is_subclass_schema(Foo, cls_repr='Spam'))
assert v.validate_python(Foo) == Foo
with pytest.raises(ValidationError) as exc_info:
v.validate_python(Bar)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'is_subclass_of',
'loc': (),
'msg': 'Input should be a subclass of Spam',
'input': Bar,
'ctx': {'class': 'Spam'},
}
]
def test_is_subclass_json() -> None:
v = SchemaValidator(core_schema.is_subclass_schema(Foo))
with pytest.raises(ValidationError) as exc_info:
v.validate_json("'Foo'")
assert exc_info.value.errors()[0]['type'] == 'needs_python_object'
| Bar |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 9431,
"end": 9519
} | class ____(A21):
@classmethod
def m1(cls, arg):
return transformX(arg)
| B21 |
python | pypa__warehouse | tests/unit/manage/test_views.py | {
"start": 3482,
"end": 39653
} | class ____:
@pytest.mark.parametrize(
("public_email", "expected_public_email"),
[(None, ""), (pretend.stub(email="some@email.com"), "some@email.com")],
)
def test_default_response(self, monkeypatch, public_email, expected_public_email):
breach_service = pretend.stub()
user_service = pretend.stub()
organization_service = pretend.stub()
name = pretend.stub()
user_id = pretend.stub()
request = pretend.stub(
find_service=lambda iface, **kw: {
IPasswordBreachedService: breach_service,
IUserService: user_service,
IOrganizationService: organization_service,
}[iface],
user=pretend.stub(name=name, id=user_id, public_email=public_email),
)
save_account_obj = pretend.stub()
save_account_cls = pretend.call_recorder(lambda **kw: save_account_obj)
monkeypatch.setattr(views, "SaveAccountForm", save_account_cls)
add_email_obj = pretend.stub()
add_email_cls = pretend.call_recorder(lambda **kw: add_email_obj)
monkeypatch.setattr(views, "AddEmailForm", add_email_cls)
change_pass_obj = pretend.stub()
change_pass_cls = pretend.call_recorder(lambda **kw: change_pass_obj)
monkeypatch.setattr(views, "ChangePasswordForm", change_pass_cls)
view = views.ManageVerifiedAccountViews(request)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "active_projects", pretend.stub()
)
assert view.default_response == {
"save_account_form": save_account_obj,
"add_email_form": add_email_obj,
"change_password_form": change_pass_obj,
"active_projects": view.active_projects,
}
assert view.request == request
assert view.user_service == user_service
assert save_account_cls.calls == [
pretend.call(
name=name,
public_email=expected_public_email,
user_service=user_service,
user_id=user_id,
)
]
assert add_email_cls.calls == [
pretend.call(request=request, user_id=user_id, user_service=user_service)
]
assert change_pass_cls.calls == [
pretend.call(
request=request,
user_service=user_service,
breach_service=breach_service,
)
]
def test_active_projects(self, db_request):
user = UserFactory.create()
another_user = UserFactory.create()
db_request.user = user
db_request.find_service = lambda *a, **kw: pretend.stub()
# A project with a sole owner that is the user
with_sole_owner = ProjectFactory.create()
RoleFactory.create(user=user, project=with_sole_owner, role_name="Owner")
RoleFactory.create(
user=another_user, project=with_sole_owner, role_name="Maintainer"
)
# A project with multiple owners, including the user
with_multiple_owners = ProjectFactory.create()
RoleFactory.create(user=user, project=with_multiple_owners, role_name="Owner")
RoleFactory.create(
user=another_user, project=with_multiple_owners, role_name="Owner"
)
# A project with a sole owner that is not the user
not_an_owner = ProjectFactory.create()
RoleFactory.create(user=user, project=not_an_owner, role_name="Maintainer")
RoleFactory.create(user=another_user, project=not_an_owner, role_name="Owner")
view = views.ManageVerifiedAccountViews(db_request)
assert view.active_projects == [with_sole_owner]
def test_manage_account(self, monkeypatch):
user_service = pretend.stub()
name = pretend.stub()
request = pretend.stub(
find_service=lambda *a, **kw: user_service, user=pretend.stub(name=name)
)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert view.manage_account() == view.default_response
assert view.request == request
assert view.user_service == user_service
def test_save_account(self, monkeypatch, pyramid_request):
update_user = pretend.call_recorder(lambda *a, **kw: None)
user_service = pretend.stub(update_user=update_user)
pyramid_request.POST = {"name": "new name", "public_email": ""}
pyramid_request.user = pretend.stub(
id=pretend.stub(),
name=pretend.stub(),
emails=[
pretend.stub(
primary=True, verified=True, public=True, email=pretend.stub()
)
],
)
pyramid_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
pyramid_request.find_service = lambda *a, **kw: user_service
save_account_obj = pretend.stub(
validate=lambda: True, data=pyramid_request.POST
)
monkeypatch.setattr(views, "SaveAccountForm", lambda *a, **kw: save_account_obj)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(pyramid_request)
assert isinstance(view.save_account(), HTTPSeeOther)
assert pyramid_request.session.flash.calls == [
pretend.call("Account details updated", queue="success")
]
assert update_user.calls == [
pretend.call(pyramid_request.user.id, **pyramid_request.POST)
]
def test_save_account_validation_fails(self, monkeypatch):
update_user = pretend.call_recorder(lambda *a, **kw: None)
user_service = pretend.stub(update_user=update_user)
request = pretend.stub(
POST={"name": "new name", "public_email": ""},
user=pretend.stub(id=pretend.stub(), name=pretend.stub()),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda *a, **kw: user_service,
)
save_account_obj = pretend.stub(validate=lambda: False)
monkeypatch.setattr(views, "SaveAccountForm", lambda *a, **kw: save_account_obj)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert view.save_account() == {
**view.default_response,
"save_account_form": save_account_obj,
}
assert request.session.flash.calls == []
assert update_user.calls == []
def test_add_email(self, monkeypatch, pyramid_request):
new_email_address = "new@example.com"
email = pretend.stub(id=pretend.stub(), email=new_email_address)
existing_email_address = "existing@example.com"
existing_email = pretend.stub(id=pretend.stub(), email=existing_email_address)
user_service = pretend.stub(
add_email=pretend.call_recorder(lambda *a, **kw: email),
)
pyramid_request.POST = {"email": new_email_address}
pyramid_request.db = pretend.stub(flush=lambda: None)
pyramid_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
pyramid_request.find_service = lambda a, **kw: user_service
pyramid_request.user = pretend.stub(
emails=[existing_email, email],
username="username",
name="Name",
id=pretend.stub(),
record_event=pretend.call_recorder(lambda *a, **kw: None),
)
monkeypatch.setattr(
views,
"AddEmailForm",
lambda *a, **kw: pretend.stub(
validate=lambda: True, email=pretend.stub(data=new_email_address)
),
)
send_email_verification_email = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(
views, "send_email_verification_email", send_email_verification_email
)
send_new_email_added_email = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(
views, "send_new_email_added_email", send_new_email_added_email
)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(pyramid_request)
assert isinstance(view.add_email(), HTTPSeeOther)
assert user_service.add_email.calls == [
pretend.call(pyramid_request.user.id, new_email_address),
]
assert pyramid_request.session.flash.calls == [
pretend.call(
f"Email {new_email_address} added - check your email for "
+ "a verification link",
queue="success",
)
]
assert send_email_verification_email.calls == [
pretend.call(pyramid_request, (pyramid_request.user, email)),
]
assert send_new_email_added_email.calls == [
pretend.call(
pyramid_request,
(pyramid_request.user, existing_email),
new_email_address=new_email_address,
),
]
assert pyramid_request.user.record_event.calls == [
pretend.call(
tag=EventTag.Account.EmailAdd,
request=pyramid_request,
additional={"email": new_email_address},
)
]
def test_add_email_validation_fails(self, monkeypatch):
email_address = "test@example.com"
request = pretend.stub(
POST={"email": email_address},
db=pretend.stub(flush=lambda: None),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda a, **kw: pretend.stub(),
user=pretend.stub(emails=[], name=pretend.stub(), id=pretend.stub()),
)
add_email_obj = pretend.stub(
validate=lambda: False, email=pretend.stub(data=email_address)
)
add_email_cls = pretend.call_recorder(lambda *a, **kw: add_email_obj)
monkeypatch.setattr(views, "AddEmailForm", add_email_cls)
email_obj = pretend.stub(id=pretend.stub(), email=email_address)
email_cls = pretend.call_recorder(lambda **kw: email_obj)
monkeypatch.setattr(views, "Email", email_cls)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert view.add_email() == {
**view.default_response,
"add_email_form": add_email_obj,
}
assert request.user.emails == []
assert email_cls.calls == []
assert request.session.flash.calls == []
def test_delete_email(self, monkeypatch):
email = pretend.stub(id=5, primary=False, email=pretend.stub())
some_other_email = pretend.stub()
user_service = pretend.stub(
record_event=pretend.call_recorder(lambda *a, **kw: None)
)
request = pretend.stub(
POST={"delete_email_id": str(email.id)},
user=pretend.stub(
id=pretend.stub(),
emails=[email, some_other_email],
name=pretend.stub(),
record_event=pretend.call_recorder(lambda *a, **kw: None),
),
db=pretend.stub(
query=lambda a: pretend.stub(
filter=lambda *a: pretend.stub(one=lambda: email)
)
),
find_service=lambda *a, **kw: user_service,
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
remote_addr="0.0.0.0",
path="request-path",
)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert isinstance(view.delete_email(), HTTPSeeOther)
assert request.session.flash.calls == [
pretend.call(f"Email address {email.email} removed", queue="success")
]
assert request.user.emails == [some_other_email]
assert request.user.record_event.calls == [
pretend.call(
tag=EventTag.Account.EmailRemove,
request=request,
additional={"email": email.email},
)
]
def test_delete_email_not_found(self, monkeypatch):
email = pretend.stub()
def raise_no_result():
raise NoResultFound
request = pretend.stub(
POST={"delete_email_id": "999999999999"},
user=pretend.stub(id=pretend.stub(), emails=[email], name=pretend.stub()),
db=pretend.stub(
query=lambda a: pretend.stub(
filter=lambda *a: pretend.stub(one=raise_no_result)
)
),
find_service=lambda *a, **kw: pretend.stub(),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert view.delete_email() == view.default_response
assert request.session.flash.calls == [
pretend.call("Email address not found", queue="error")
]
assert request.user.emails == [email]
def test_delete_email_is_primary(self, monkeypatch):
email = pretend.stub(primary=True)
request = pretend.stub(
POST={"delete_email_id": "99999"},
user=pretend.stub(id=pretend.stub(), emails=[email], name=pretend.stub()),
db=pretend.stub(
query=lambda a: pretend.stub(
filter=lambda *a: pretend.stub(one=lambda: email)
)
),
find_service=lambda *a, **kw: pretend.stub(),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert view.delete_email() == view.default_response
assert request.session.flash.calls == [
pretend.call("Cannot remove primary email address", queue="error")
]
assert request.user.emails == [email]
def test_change_primary_email(self, monkeypatch, db_request):
user = UserFactory()
user.record_event = pretend.call_recorder(lambda *a, **kw: None)
old_primary = EmailFactory(primary=True, user=user, email="old")
new_primary = EmailFactory(primary=False, verified=True, user=user, email="new")
db_request.user = user
user_service = pretend.stub()
db_request.find_service = lambda *a, **kw: user_service
db_request.POST = {"primary_email_id": str(new_primary.id)}
db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(db_request)
send_email = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(views, "send_primary_email_change_email", send_email)
assert isinstance(view.change_primary_email(), HTTPSeeOther)
assert send_email.calls == [
pretend.call(db_request, (db_request.user, old_primary))
]
assert db_request.session.flash.calls == [
pretend.call(
f"Email address {new_primary.email} set as primary", queue="success"
)
]
assert not old_primary.primary
assert new_primary.primary
assert user.record_event.calls == [
pretend.call(
tag=EventTag.Account.EmailPrimaryChange,
request=db_request,
additional={"old_primary": "old", "new_primary": "new"},
)
]
def test_change_primary_email_without_current(self, monkeypatch, db_request):
user = UserFactory()
user.record_event = pretend.call_recorder(lambda *a, **kw: None)
new_primary = EmailFactory(primary=False, verified=True, user=user)
db_request.user = user
user_service = pretend.stub()
db_request.find_service = lambda *a, **kw: user_service
db_request.POST = {"primary_email_id": str(new_primary.id)}
db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(db_request)
send_email = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(views, "send_primary_email_change_email", send_email)
assert isinstance(view.change_primary_email(), HTTPSeeOther)
assert send_email.calls == []
assert db_request.session.flash.calls == [
pretend.call(
f"Email address {new_primary.email} set as primary", queue="success"
)
]
assert new_primary.primary
assert db_request.user.record_event.calls == [
pretend.call(
tag=EventTag.Account.EmailPrimaryChange,
request=db_request,
additional={"old_primary": None, "new_primary": new_primary.email},
)
]
def test_change_primary_email_not_found(self, monkeypatch, db_request):
user = UserFactory()
old_primary = EmailFactory(primary=True, user=user)
missing_email_id = 9999
db_request.user = user
db_request.find_service = lambda *a, **kw: pretend.stub()
db_request.POST = {"primary_email_id": str(missing_email_id)}
db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(db_request)
assert view.change_primary_email() == view.default_response
assert db_request.session.flash.calls == [
pretend.call("Email address not found", queue="error")
]
assert old_primary.primary
def test_change_primary_email_2fa_disabled(self, monkeypatch, db_request):
user = UserFactory.create(totp_secret=None)
_ = EmailFactory(primary=True, verified=False, user=user)
secondary = EmailFactory(primary=False, verified=True, user=user)
db_request.user = user
db_request.find_service = lambda *a, **kw: pretend.stub(get_user=lambda a: user)
db_request.POST = {"primary_email_id": str(secondary.id)}
db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None)
db_request.route_path = pretend.call_recorder(lambda r, **kw: f"/{r}")
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", pretend.stub()
)
view = views.ManageVerifiedAccountViews(db_request)
assert view.change_primary_email() == view.default_response
assert db_request.session.flash.calls == [
pretend.call(
"Two factor authentication must be enabled to change primary "
"email address.",
queue="error",
)
]
@pytest.mark.parametrize(
("has_primary_verified_email", "expected_redirect"),
[
(True, "manage.account"),
(False, "manage.unverified-account"),
],
)
def test_reverify_email(
self, monkeypatch, has_primary_verified_email, expected_redirect
):
user = pretend.stub(
id=pretend.stub(),
username="username",
name="Name",
record_event=pretend.call_recorder(lambda *a, **kw: None),
has_primary_verified_email=has_primary_verified_email,
)
email = pretend.stub(
verified=False,
email="email_address",
user=user,
)
request = pretend.stub(
POST={"reverify_email_id": "99999"},
db=pretend.stub(
query=lambda *a: pretend.stub(
filter=lambda *a: pretend.stub(one=lambda: email)
)
),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda svc, name=None, context=None: {
IRateLimiter: pretend.stub(
test=pretend.call_recorder(lambda user_id: True),
hit=pretend.call_recorder(lambda user_id: None),
)
}.get(svc, pretend.stub()),
user=user,
remote_addr="0.0.0.0",
path="request-path",
route_path=pretend.call_recorder(lambda *a, **kw: "/foo/bar/"),
)
send_email = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(views, "send_email_verification_email", send_email)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert isinstance(view.reverify_email(), HTTPSeeOther)
assert request.session.flash.calls == [
pretend.call("Verification email for email_address resent", queue="success")
]
assert send_email.calls == [pretend.call(request, (request.user, email))]
assert user.record_event.calls == [
pretend.call(
tag=EventTag.Account.EmailReverify,
request=request,
additional={"email": email.email},
)
]
assert request.route_path.calls == [pretend.call(expected_redirect)]
def test_reverify_email_ratelimit_exceeded(self, monkeypatch):
user = pretend.stub(
id=pretend.stub(),
username="username",
name="Name",
record_event=pretend.call_recorder(lambda *a, **kw: None),
has_primary_verified_email=True,
)
email = pretend.stub(
verified=False,
email="email_address",
user=user,
)
request = pretend.stub(
POST={"reverify_email_id": "9999"},
db=pretend.stub(
query=lambda *a: pretend.stub(
filter=lambda *a: pretend.stub(one=lambda: email)
)
),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda svc, name=None, context=None: {
IRateLimiter: pretend.stub(
test=pretend.call_recorder(lambda user_id: False),
)
}.get(svc, pretend.stub()),
user=user,
remote_addr="0.0.0.0",
path="request-path",
route_path=pretend.call_recorder(lambda *a, **kw: "/foo/bar/"),
)
send_email = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(views, "send_email_verification_email", send_email)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert isinstance(view.reverify_email(), HTTPSeeOther)
assert request.session.flash.calls == [
pretend.call(
(
"Too many incomplete attempts to verify email address(es) for "
f"{request.user.username}. Complete a pending "
"verification or wait before attempting again."
),
queue="error",
)
]
assert send_email.calls == []
assert email.user.record_event.calls == []
@pytest.mark.parametrize("reverify_email_id", ["9999", "wutang"])
@pytest.mark.parametrize(
("has_primary_verified_email", "expected"),
[
(True, "manage.account"),
(False, "manage.unverified-account"),
],
)
def test_reverify_email_not_found(
self, monkeypatch, reverify_email_id, has_primary_verified_email, expected
):
def raise_no_result():
raise NoResultFound
request = pretend.stub(
POST={"reverify_email_id": reverify_email_id},
db=pretend.stub(
query=lambda *a: pretend.stub(
filter=lambda *a: pretend.stub(one=raise_no_result)
)
),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda *a, **kw: pretend.stub(),
user=pretend.stub(
id=pretend.stub(), has_primary_verified_email=has_primary_verified_email
),
route_path=pretend.call_recorder(lambda *a: "/some/url"),
)
send_email = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(views, "send_email_verification_email", send_email)
view = views.ManageVerifiedAccountViews(request)
assert isinstance(view.reverify_email(), HTTPSeeOther)
assert request.session.flash.calls == [
pretend.call("Email address not found", queue="error")
]
assert send_email.calls == []
assert request.route_path.calls == [pretend.call(expected)]
def test_reverify_email_already_verified(self, monkeypatch):
email = pretend.stub(verified=True, email="email_address")
request = pretend.stub(
POST={"reverify_email_id": "9999"},
db=pretend.stub(
query=lambda *a: pretend.stub(
filter=lambda *a: pretend.stub(one=lambda: email)
)
),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda *a, **kw: pretend.stub(),
user=pretend.stub(
id=pretend.stub(),
has_primary_verified_email=True,
),
path="request-path",
route_path=pretend.call_recorder(lambda *a, **kw: "/foo/bar/"),
)
send_email = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(views, "send_email_verification_email", send_email)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert isinstance(view.reverify_email(), HTTPSeeOther)
assert request.session.flash.calls == [
pretend.call("Email is already verified", queue="error")
]
assert send_email.calls == []
def test_change_password(self, monkeypatch):
old_password = "0ld_p455w0rd"
new_password = "n3w_p455w0rd"
user_service = pretend.stub(
update_user=pretend.call_recorder(lambda *a, **kw: None),
get_password_timestamp=lambda uid: 0,
)
request = pretend.stub(
POST={
"password": old_password,
"new_password": new_password,
"password_confirm": new_password,
},
session=pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None),
record_password_timestamp=lambda ts: None,
),
find_service=lambda *a, **kw: user_service,
user=pretend.stub(
id=pretend.stub(),
username=pretend.stub(),
email=pretend.stub(),
name=pretend.stub(),
record_event=pretend.call_recorder(lambda *a, **kw: None),
),
db=pretend.stub(
flush=lambda: None,
refresh=lambda obj: None,
),
remote_addr="0.0.0.0",
path="request-path",
)
change_pwd_obj = pretend.stub(
validate=lambda: True, new_password=pretend.stub(data=new_password)
)
change_pwd_cls = pretend.call_recorder(lambda *a, **kw: change_pwd_obj)
monkeypatch.setattr(views, "ChangePasswordForm", change_pwd_cls)
send_email = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(views, "send_password_change_email", send_email)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert isinstance(view.change_password(), HTTPSeeOther)
assert request.session.flash.calls == [
pretend.call("Password updated", queue="success")
]
assert send_email.calls == [pretend.call(request, request.user)]
assert user_service.update_user.calls == [
pretend.call(request.user.id, password=new_password)
]
assert request.user.record_event.calls == [
pretend.call(
tag=EventTag.Account.PasswordChange,
request=request,
)
]
def test_change_password_validation_fails(self, monkeypatch):
old_password = "0ld_p455w0rd"
new_password = "n3w_p455w0rd"
user_service = pretend.stub(
update_user=pretend.call_recorder(lambda *a, **kw: None)
)
request = pretend.stub(
POST={
"password": old_password,
"new_password": new_password,
"password_confirm": new_password,
},
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda *a, **kw: user_service,
user=pretend.stub(
id=pretend.stub(),
username=pretend.stub(),
email=pretend.stub(),
name=pretend.stub(),
),
)
change_pwd_obj = pretend.stub(
validate=lambda: False, new_password=pretend.stub(data=new_password)
)
change_pwd_cls = pretend.call_recorder(lambda *a, **kw: change_pwd_obj)
monkeypatch.setattr(views, "ChangePasswordForm", change_pwd_cls)
send_email = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(views, "send_password_change_email", send_email)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", {"_": pretend.stub()}
)
view = views.ManageVerifiedAccountViews(request)
assert view.change_password() == {
**view.default_response,
"change_password_form": change_pwd_obj,
}
assert request.session.flash.calls == []
assert send_email.calls == []
assert user_service.update_user.calls == []
def test_delete_account(self, monkeypatch, db_request):
user = UserFactory.create()
deleted_user = UserFactory.create(username="deleted-user")
jid = JournalEntryFactory.create(submitted_by=user).id
db_request.user = user
db_request.params = {"confirm_password": user.password}
db_request.find_service = lambda *a, **kw: pretend.stub()
confirm_password_obj = pretend.stub(validate=lambda: True)
confirm_password_cls = pretend.call_recorder(
lambda *a, **kw: confirm_password_obj
)
monkeypatch.setattr(views, "ConfirmPasswordForm", confirm_password_cls)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", pretend.stub()
)
monkeypatch.setattr(views.ManageVerifiedAccountViews, "active_projects", [])
send_email = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(views, "send_account_deletion_email", send_email)
logout_response = pretend.stub()
logout = pretend.call_recorder(lambda *a: logout_response)
monkeypatch.setattr(views, "logout", logout)
view = views.ManageVerifiedAccountViews(db_request)
assert view.delete_account() == logout_response
journal = (
db_request.db.query(JournalEntry)
.options(joinedload(JournalEntry.submitted_by))
.filter_by(id=jid)
.one()
)
assert journal.submitted_by == deleted_user
assert db_request.db.query(User).all() == [deleted_user]
assert send_email.calls == [pretend.call(db_request, user)]
assert logout.calls == [pretend.call(db_request)]
def test_delete_account_no_confirm(self, monkeypatch):
request = pretend.stub(
params={"confirm_password": ""},
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda *a, **kw: pretend.stub(),
)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", pretend.stub()
)
view = views.ManageVerifiedAccountViews(request)
assert view.delete_account() == view.default_response
assert request.session.flash.calls == [
pretend.call("Confirm the request", queue="error")
]
def test_delete_account_wrong_confirm(self, monkeypatch):
request = pretend.stub(
params={"confirm_password": "invalid"},
user=pretend.stub(username="username"),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda *a, **kw: pretend.stub(),
)
confirm_password_obj = pretend.stub(validate=lambda: False)
confirm_password_cls = pretend.call_recorder(
lambda *a, **kw: confirm_password_obj
)
monkeypatch.setattr(views, "ConfirmPasswordForm", confirm_password_cls)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", pretend.stub()
)
view = views.ManageVerifiedAccountViews(request)
assert view.delete_account() == view.default_response
assert request.session.flash.calls == [
pretend.call(
"Could not delete account - Invalid credentials. Please try again.",
queue="error",
)
]
def test_delete_account_has_active_projects(self, monkeypatch):
request = pretend.stub(
params={"confirm_password": "password"},
user=pretend.stub(username="username"),
session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)),
find_service=lambda *a, **kw: pretend.stub(),
)
confirm_password_obj = pretend.stub(validate=lambda: True)
confirm_password_cls = pretend.call_recorder(
lambda *a, **kw: confirm_password_obj
)
monkeypatch.setattr(views, "ConfirmPasswordForm", confirm_password_cls)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "default_response", pretend.stub()
)
monkeypatch.setattr(
views.ManageVerifiedAccountViews, "active_projects", [pretend.stub()]
)
view = views.ManageVerifiedAccountViews(request)
assert view.delete_account() == view.default_response
assert request.session.flash.calls == [
pretend.call(
"Cannot delete account with active project ownerships", queue="error"
)
]
| TestManageAccount |
python | kamyu104__LeetCode-Solutions | Python/find-valid-matrix-given-row-and-column-sums.py | {
"start": 835,
"end": 1352
} | class ____(object):
def restoreMatrix(self, rowSum, colSum):
"""
:type rowSum: List[int]
:type colSum: List[int]
:rtype: List[List[int]]
"""
matrix = [[0]*len(colSum) for _ in xrange(len(rowSum))]
for i in xrange(len(matrix)):
for j in xrange(len(matrix[i])):
matrix[i][j] = min(rowSum[i], colSum[j]) # greedily used
rowSum[i] -= matrix[i][j]
colSum[j] -= matrix[i][j]
return matrix
| Solution2 |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 26207,
"end": 26659
} | class ____(Domain):
re_part = re.compile(r"(?!-)[a-z\d\*-]{1,63}(?<!-)")
def __init__(self, domain: str) -> None:
super().__init__(domain)
mask = self._domain.replace(".", r"\.").replace("*", ".*")
self._mask = re.compile(mask)
@property
def canonical(self) -> str:
return self._mask.pattern
def match_domain(self, host: str) -> bool:
return self._mask.fullmatch(host) is not None
| MaskDomain |
python | fsspec__filesystem_spec | fsspec/tests/test_chained.py | {
"start": 163,
"end": 403
} | class ____(ChainedFileSystem):
protocol = "mychain"
def __init__(self, target_protocol="", target_options=None, **kwargs):
super().__init__(**kwargs)
self.fs = filesystem(target_protocol, **target_options)
| MyChainedFS |
python | jazzband__django-oauth-toolkit | oauth2_provider/models.py | {
"start": 22411,
"end": 22536
} | class ____(AbstractIDToken):
class Meta(AbstractIDToken.Meta):
swappable = "OAUTH2_PROVIDER_ID_TOKEN_MODEL"
| IDToken |
python | pennersr__django-allauth | allauth/socialaccount/providers/digitalocean/provider.py | {
"start": 231,
"end": 364
} | class ____(ProviderAccount):
def get_user_data(self):
return self.account.extra_data.get("account", {})
| DigitalOceanAccount |
python | encode__django-rest-framework | tests/test_templatetags.py | {
"start": 8615,
"end": 10497
} | class ____(TestCase):
"""
Test if JSON URLs are transformed into links well
"""
def _urlize_dict_check(self, data):
"""
For all items in dict test assert that the value is urlized key
"""
for original, urlized in data.items():
assert urlize(original, nofollow=False) == urlized
def test_json_with_url(self):
"""
Test if JSON URLs are transformed into links well
"""
data = {}
data['"url": "http://api/users/1/", '] = \
'"url": "<a href="http://api/users/1/">http://api/users/1/</a>", '
data['"foo_set": [\n "http://api/foos/1/"\n], '] = \
'"foo_set": [\n "<a href="http://api/foos/1/">http://api/foos/1/</a>"\n], '
self._urlize_dict_check(data)
def test_template_render_with_autoescape(self):
"""
Test that HTML is correctly escaped in Browsable API views.
"""
template = Template("{% load rest_framework %}{{ content|urlize }}")
rendered = template.render(Context({'content': '<script>alert()</script> http://example.com'}))
assert rendered == '<script>alert()</script>' \
' <a href="http://example.com" rel="nofollow">http://example.com</a>'
def test_template_render_with_noautoescape(self):
"""
Test if the autoescape value is getting passed to urlize filter.
"""
template = Template("{% load rest_framework %}"
"{% autoescape off %}{{ content|urlize }}"
"{% endautoescape %}")
rendered = template.render(Context({'content': '<b> "http://example.com" </b>'}))
assert rendered == '<b> "<a href="http://example.com" rel="nofollow">http://example.com</a>" </b>'
@unittest.skipUnless(coreapi, 'coreapi is not installed')
| URLizerTests |
python | sympy__sympy | sympy/series/formal.py | {
"start": 44077,
"end": 46400
} | class ____(FiniteFormalPowerSeries):
"""
Represents the composed formal power series of two functions.
Explanation
===========
No computation is performed. Terms are calculated using a term by term logic,
instead of a point by point logic.
There are two differences between a :obj:`FormalPowerSeries` object and a
:obj:`FormalPowerSeriesCompose` object. The first argument contains the outer
function and the inner function involved in the omposition. Also, the
coefficient sequence contains the generic sequence which is to be multiplied
by a custom ``bell_seq`` finite sequence. The finite terms will then be added up to
get the final terms.
See Also
========
sympy.series.formal.FormalPowerSeries
sympy.series.formal.FiniteFormalPowerSeries
"""
@property
def function(self):
"""Function for the composed formal power series."""
f, g, x = self.f, self.g, self.ffps.x
return f.subs(x, g)
def _eval_terms(self, n):
"""
Returns the first `n` terms of the composed formal power series.
Term by term logic is implemented here.
Explanation
===========
The coefficient sequence of the :obj:`FormalPowerSeriesCompose` object is the generic sequence.
It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
the final terms for the polynomial.
Examples
========
>>> from sympy import fps, sin, exp
>>> from sympy.abc import x
>>> f1 = fps(exp(x))
>>> f2 = fps(sin(x))
>>> fcomp = f1.compose(f2, x)
>>> fcomp._eval_terms(6)
-x**5/15 - x**4/8 + x**2/2 + x + 1
>>> fcomp._eval_terms(8)
x**7/90 - x**6/240 - x**5/15 - x**4/8 + x**2/2 + x + 1
See Also
========
sympy.series.formal.FormalPowerSeries.compose
sympy.series.formal.FormalPowerSeries.coeff_bell
"""
ffps, gfps = self.ffps, self.gfps
terms = [ffps.zero_coeff()]
for i in range(1, n):
bell_seq = gfps.coeff_bell(i)
seq = (ffps.bell_coeff_seq * bell_seq)
terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
return Add(*terms)
| FormalPowerSeriesCompose |
python | graphql-python__graphene | graphene/relay/tests/test_global_id.py | {
"start": 245,
"end": 342
} | class ____(ObjectType):
class Meta:
interfaces = [CustomNode]
name = String()
| User |
python | pytorch__pytorch | torch/cuda/__init__.py | {
"start": 19964,
"end": 23343
} | class ____(device):
r"""Context-manager that changes the current device to that of given object.
You can use both tensors and storages as arguments. If a given object is
not allocated on a GPU, this is a no-op.
Args:
obj (Tensor or Storage): object allocated on the selected device.
"""
def __init__(self, obj):
idx = obj.get_device() if obj.is_cuda else -1
super().__init__(idx)
def set_device(device: "Device") -> None:
r"""Set the current device.
Usage of this function is discouraged in favor of :any:`device`. In most
cases it's better to use ``CUDA_VISIBLE_DEVICES`` environmental variable.
Args:
device (torch.device or int): selected device. This function is a no-op
if this argument is negative.
"""
device = _get_device_index(device)
if device >= 0:
torch._C._cuda_setDevice(device)
def get_device_name(device: "Device" = None) -> str:
r"""Get the name of a device.
Args:
device (torch.device or int or str, optional): device for which to return the
name. This function is a no-op if this argument is a negative
integer. It uses the current device, given by :func:`~torch.cuda.current_device`,
if :attr:`device` is ``None`` (default).
Returns:
str: the name of the device
"""
return get_device_properties(device).name
def get_device_capability(device: "Device" = None) -> tuple[int, int]:
r"""Get the cuda capability of a device.
Args:
device (torch.device or int or str, optional): device for which to return the
device capability. This function is a no-op if this argument is
a negative integer. It uses the current device, given by
:func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
(default).
Returns:
tuple(int, int): the major and minor cuda capability of the device
"""
prop = get_device_properties(device)
return prop.major, prop.minor
# pyrefly: ignore [not-a-type]
def get_device_properties(device: "Device" = None) -> _CudaDeviceProperties:
r"""Get the properties of a device.
Args:
device (torch.device or int or str, optional): device for which to return the
properties of the device. It uses the current device, given by
:func:`~torch.cuda.current_device`, if :attr:`device` is ``None``
(default).
Returns:
_CudaDeviceProperties: the properties of the device
"""
_lazy_init() # will define _get_device_properties
device = _get_device_index(device, optional=True)
if device < 0 or device >= device_count():
raise AssertionError("Invalid device id")
return _get_device_properties(device) # type: ignore[name-defined]
def can_device_access_peer(device: "Device", peer_device: "Device") -> bool:
r"""Check if peer access between two devices is possible."""
_lazy_init()
device = _get_device_index(device, optional=True)
peer_device = _get_device_index(peer_device)
if device < 0 or device >= device_count():
raise AssertionError("Invalid device id")
if peer_device < 0 or peer_device >= device_count():
raise AssertionError("Invalid peer device id")
return torch._C._cuda_canDeviceAccessPeer(device, peer_device)
| device_of |
python | getsentry__sentry | src/sentry/models/commitfilechange.py | {
"start": 452,
"end": 736
} | class ____(BaseManager["CommitFileChange"]):
def get_count_for_commits(self, commits: Iterable[Any]) -> int:
return int(
self.filter(commit_id__in=[c.id for c in commits]).values("filename").distinct().count()
)
@region_silo_model
| CommitFileChangeManager |
python | django-debug-toolbar__django-debug-toolbar | tests/loaders.py | {
"start": 105,
"end": 337
} | class ____(Loader):
def get_template(self, *args, **kwargs):
# Force the template loader to run some SQL. Simulates a CMS.
User.objects.all().count()
return super().get_template(*args, **kwargs)
| LoaderWithSQL |
python | pytorch__pytorch | .ci/pytorch/smoke_test/max_autotune.py | {
"start": 204,
"end": 6280
} | class ____(nn.Module):
def __init__(self):
super(Net, self).__init__() # noqa: UP008
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print(
f"Train Epoch: {epoch} "
f"[{batch_idx * len(data)}/{len(train_loader.dataset)} "
f"({100.0 * batch_idx / len(train_loader):.0f}%)]\tLoss: {loss.item():.6f}"
)
if args.dry_run:
break
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += F.nll_loss(
output, target, reduction="sum"
).item() # sum up batch loss
pred = output.argmax(
dim=1, keepdim=True
) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print(
f"\nTest set: Average loss: {test_loss:.4f}, "
f"Accuracy: {correct}/{len(test_loader.dataset)} "
f"({100.0 * correct / len(test_loader.dataset):.0f}%)\n"
)
def timed(fn):
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
result = fn()
end.record()
torch.cuda.synchronize()
return result, start.elapsed_time(end) / 1000
def main():
# Training settings
parser = argparse.ArgumentParser(description="PyTorch MNIST Example")
parser.add_argument(
"--batch-size",
type=int,
default=64,
metavar="N",
help="input batch size for training (default: 64)",
)
parser.add_argument(
"--test-batch-size",
type=int,
default=1000,
metavar="N",
help="input batch size for testing (default: 1000)",
)
parser.add_argument(
"--epochs",
type=int,
default=4,
metavar="N",
help="number of epochs to train (default: 14)",
)
parser.add_argument(
"--lr",
type=float,
default=1.0,
metavar="LR",
help="learning rate (default: 1.0)",
)
parser.add_argument(
"--gamma",
type=float,
default=0.7,
metavar="M",
help="Learning rate step gamma (default: 0.7)",
)
parser.add_argument(
"--no-cuda", action="store_true", default=False, help="disables CUDA training"
)
parser.add_argument(
"--no-mps",
action="store_true",
default=False,
help="disables macOS GPU training",
)
parser.add_argument(
"--dry-run",
action="store_true",
default=False,
help="quickly check a single pass",
)
parser.add_argument(
"--seed", type=int, default=1, metavar="S", help="random seed (default: 1)"
)
parser.add_argument(
"--log-interval",
type=int,
default=100,
metavar="N",
help="how many batches to wait before logging training status",
)
parser.add_argument(
"--save-model",
action="store_true",
default=False,
help="For Saving the current Model",
)
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
use_mps = not args.no_mps and torch.backends.mps.is_available()
torch.manual_seed(args.seed)
torch.backends.cuda.matmul.allow_tf32 = True
if use_cuda:
device = torch.device("cuda")
elif use_mps:
device = torch.device("mps")
else:
device = torch.device("cpu")
train_kwargs = {"batch_size": args.batch_size}
test_kwargs = {"batch_size": args.test_batch_size}
if use_cuda:
cuda_kwargs = {"num_workers": 1, "pin_memory": True, "shuffle": True}
train_kwargs.update(cuda_kwargs)
test_kwargs.update(cuda_kwargs)
transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
)
dataset1 = datasets.MNIST("../data", train=True, download=True, transform=transform)
dataset2 = datasets.MNIST("../data", train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1, **train_kwargs)
test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
model = Net().to(device)
opt_model = torch.compile(model, mode="max-autotune")
optimizer = optim.Adadelta(opt_model.parameters(), lr=args.lr)
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
for epoch in range(1, args.epochs + 1):
print(
f"Training Time: {timed(lambda: train(args, opt_model, device, train_loader, optimizer, epoch))[1]}"
)
print(
f"Evaluation Time: {timed(lambda: test(opt_model, device, test_loader))[1]}"
)
scheduler.step()
if args.save_model:
torch.save(opt_model.state_dict(), "mnist_cnn.pt")
if __name__ == "__main__":
main()
| Net |
python | pytransitions__transitions | tests/test_markup.py | {
"start": 2678,
"end": 5839
} | class ____(TestCase):
def setUp(self):
self.machine_cls = MarkupMachine
self.states = ['A', 'B', 'C', 'D'] # type: Union[Sequence[StateConfig], Type[Enum]]
self.transitions = [
{'trigger': 'walk', 'source': 'A', 'dest': 'B'},
{'trigger': 'run', 'source': 'B', 'dest': 'C'},
{'trigger': 'sprint', 'source': 'C', 'dest': 'D'}
] # type: Sequence[TransitionConfig]
self.num_trans = len(self.transitions)
self.num_auto = len(self.states) ** 2
def test_markup_self(self):
m1 = self.machine_cls(states=self.states, transitions=self.transitions, initial='A')
m1.walk()
m2 = self.machine_cls(markup=m1.markup)
self.assertTrue(m1.state == m2.state or m1.state.name == m2.state)
self.assertEqual(len(m1.models), len(m2.models))
self.assertEqual(sorted(m1.states.keys()), sorted(m2.states.keys()))
self.assertEqual(sorted(m1.events.keys()), sorted(m2.events.keys()))
m2.run()
m2.sprint()
self.assertNotEqual(m1.state, m2.state)
def test_markup_model(self):
model1 = SimpleModel()
m1 = self.machine_cls(model1, states=self.states, transitions=self.transitions, initial='A')
model1.walk()
m2 = self.machine_cls(markup=m1.markup)
model2 = m2.models[0]
self.assertIsInstance(model2, SimpleModel)
self.assertEqual(len(m1.models), len(m2.models))
self.assertTrue(model1.state == model2.state or model1.state.name == model2.state)
self.assertEqual(sorted(m1.states.keys()), sorted(m2.states.keys()))
self.assertEqual(sorted(m1.events.keys()), sorted(m2.events.keys()))
def test_conditions_unless(self):
s = Stuff(machine_cls=self.machine_cls)
s.machine.add_transition('go', 'A', 'B', conditions='this_passes',
unless=['this_fails', 'this_fails_by_default'])
t = s.machine.markup['transitions']
self.assertEqual(len(t), 1)
self.assertEqual(t[0]['trigger'], 'go')
self.assertEqual(len(t[0]['conditions']), 1)
self.assertEqual(len(t[0]['unless']), 2)
def test_auto_transitions(self):
m1 = self.machine_cls(states=self.states, transitions=self.transitions, initial='A')
m2 = self.machine_cls(states=self.states, transitions=self.transitions, initial='A',
auto_transitions_markup=True)
self.assertEqual(len(m1.markup['transitions']), self.num_trans)
self.assertEqual(len(m2.markup['transitions']), self.num_trans + self.num_auto)
m1.add_transition('go', 'A', 'B')
m2.add_transition('go', 'A', 'B')
self.num_trans += 1
self.assertEqual(len(m1.markup['transitions']), self.num_trans)
self.assertEqual(len(m2.markup['transitions']), self.num_trans + self.num_auto)
m1.auto_transitions_markup = True
m2.auto_transitions_markup = False
self.assertEqual(len(m1.markup['transitions']), self.num_trans + self.num_auto)
self.assertEqual(len(m2.markup['transitions']), self.num_trans)
| TestMarkupMachine |
python | pytorch__pytorch | torchgen/utils.py | {
"start": 15479,
"end": 16787
} | class ____(Generic[T]):
storage: dict[T, None]
def __init__(self, iterable: Iterable[T] | None = None) -> None:
if iterable is None:
self.storage = {}
else:
self.storage = dict.fromkeys(iterable)
def __contains__(self, item: T) -> bool:
return item in self.storage
def __iter__(self) -> Iterator[T]:
return iter(self.storage.keys())
def update(self, items: OrderedSet[T]) -> None:
self.storage.update(items.storage)
def add(self, item: T) -> None:
self.storage[item] = None
def copy(self) -> OrderedSet[T]:
ret: OrderedSet[T] = OrderedSet()
ret.storage = self.storage.copy()
return ret
@staticmethod
def union(*args: OrderedSet[T]) -> OrderedSet[T]:
ret = args[0].copy()
for s in args[1:]:
ret.update(s)
return ret
def __or__(self, other: OrderedSet[T]) -> OrderedSet[T]:
return OrderedSet.union(self, other)
def __ior__(self, other: OrderedSet[T]) -> Self:
self.update(other)
return self
def __eq__(self, other: object) -> bool:
if isinstance(other, OrderedSet):
return self.storage == other.storage
else:
return set(self.storage.keys()) == other
| OrderedSet |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes1.py | {
"start": 414,
"end": 644
} | class ____[T](E, metaclass=type):
def my_method(self) -> "G":
reveal_type(__class__, expected_text="type[G[Unknown]]")
return __class__()
# This should generate an error because only one metaclass is supported.
| G |
python | astropy__astropy | astropy/visualization/stretch.py | {
"start": 19156,
"end": 21277
} | class ____(BaseStretch):
r"""
An asinh stretch.
The stretch is given by:
.. math::
y = \frac{{\rm asinh}(x / a)}{{\rm asinh}(1 / a)}.
Parameters
----------
a : float, optional
The ``a`` parameter used in the above formula. The value of this
parameter is where the asinh curve transitions from linear to
logarithmic behavior, expressed as a fraction of the normalized
image. The stretch becomes more linear for larger ``a`` values
and more logarithmic for smaller ``a`` values. ``a`` must be
greater than 0. Default is 0.1.
Examples
--------
.. plot::
:show-source-link:
import numpy as np
from astropy.visualization import AsinhStretch
from matplotlib import pyplot as plt
fig, ax = plt.subplots(figsize=(5, 5))
x = np.linspace(0, 1, 100)
a_vals = (0.01, 0.05, 0.1, 0.2, 0.3, 0.5, 0.9, 3.0)
for a in a_vals:
if a == 0.1:
lw = 3
else:
lw = 1
stretch = AsinhStretch(a)
label = f'{a=}'
ax.plot(x, stretch(x, clip=True), label=label, lw=lw)
ax.axis('equal')
ax.plot(x, x, ls='dotted', color='k', alpha=0.3)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_xlabel('Input Value')
ax.set_ylabel('Output Value')
ax.set_title(stretch.__class__.__name__)
ax.legend(loc='lower right', fontsize=8)
"""
def __init__(self, a=0.1):
super().__init__()
if a <= 0:
raise ValueError("a must be > 0")
self.a = a
def __call__(self, values, clip=True, out=None):
values = _prepare(values, clip=clip, out=out)
np.true_divide(values, self.a, out=values)
np.arcsinh(values, out=values)
np.true_divide(values, np.arcsinh(1.0 / self.a), out=values)
return values
@property
def inverse(self):
"""A stretch object that performs the inverse operation."""
return SinhStretch(a=1.0 / np.arcsinh(1.0 / self.a))
| AsinhStretch |
python | getsentry__sentry | tests/sentry/templatetags/test_sentry_api.py | {
"start": 83,
"end": 561
} | class ____(TestCase):
TEMPLATE = engines["django"].from_string(
"""
{% load sentry_api %}
{% serialize_detailed_org org %}
"""
)
def test_escapes_js(self) -> None:
org = self.create_organization(name="<script>alert(1);</script>")
result = self.TEMPLATE.render(context={"org": org})
assert "<script>" not in result
assert "\\u003cscript\\u003ealert(1);\\u003c/script\\u003e" in result
| SerializeDetailedOrgTest |
python | getsentry__sentry | src/sentry/api/bases/project.py | {
"start": 2573,
"end": 2967
} | class ____(ProjectPermission):
scope_map = {
"GET": ["project:read", "project:write", "project:admin", "project:releases", "org:ci"],
"POST": ["project:write", "project:admin", "project:releases", "org:ci"],
"PUT": ["project:write", "project:admin", "project:releases", "org:ci"],
"DELETE": ["project:admin", "project:releases"],
}
| ProjectReleasePermission |
python | fluentpython__example-code | attic/concurrency/wikipedia/daypicts.py | {
"start": 1350,
"end": 6505
} | class ____(ValueError):
'''Template:POTD did not exist before PODT_EARLIEST_TEMPLATE'''
def get_picture_url(iso_date):
page_url = POTD_BASE_URL + iso_date
print(page_url)
response = requests.get(page_url)
pict_url = POTD_IMAGE_RE.search(response.text)
if pict_url is None:
raise NoPictureForDate(iso_date)
return 'http:' + pict_url.group(1)
def validate_date(text):
try:
parts = [int(part) for part in text.split('-')]
except ValueError:
raise ValueError('date must use YYYY, YYYY-MM or YYYY-MM-DD format')
test_parts = parts[:]
while len(test_parts) < 3:
test_parts.append(1)
date = datetime.date(*(int(part) for part in test_parts))
iso_date = date.strftime(ISO_DATE_FMT)
iso_date = iso_date[:1+len(parts)*3]
if iso_date < PODT_EARLIEST_TEMPLATE:
raise NoPictureTemplateBefore(PODT_EARLIEST_TEMPLATE)
return iso_date
def gen_month_dates(iso_month):
first = datetime.datetime.strptime(iso_month+'-01', ISO_DATE_FMT)
one_day = datetime.timedelta(days=1)
date = first.date()
while date.month == first.month:
yield date.strftime(ISO_DATE_FMT)
date += one_day
def gen_year_dates(iso_year):
for i in range(1, 13):
yield from gen_month_dates(iso_year + '-{:02d}'.format(i))
def gen_dates(iso_parts):
if len(iso_parts) == 4:
yield from gen_year_dates(iso_parts)
elif len(iso_parts) == 7:
yield from gen_month_dates(iso_parts)
else:
yield iso_parts
def get_picture_urls(dates, verbose=False):
date_urls = []
count = 0
for date in dates:
try:
url = get_picture_url(date)
except NoPictureForDate as exc:
if verbose:
print('*** {!r} ***'.format(exc))
continue
count += 1
if verbose:
print(format(count, '3d'), end=' ')
print(url.split('/')[-1])
else:
print(url)
date_urls.append((date, url))
return date_urls
def picture_type(octets):
pict_type = imghdr.what(None, octets)
if pict_type is None:
if (octets.startswith(b'<') and
b'<svg' in octets[:200] and
octets.rstrip().endswith(b'</svg>')):
pict_type = 'svg'
return pict_type
def get_pictures(dates, verbose=False):
urls_ok = []
try:
os.makedirs(SAVE_DIR)
except FileExistsError:
pass
for date, url in get_picture_urls(dates, verbose):
if PICT_BASE_URL == LOCAL_PICT_BASE_URL:
url = url.replace(REMOTE_PICT_BASE_URL, PICT_BASE_URL)
response = requests.get(url)
if response.status_code != 200:
warnings.warn('HTTP code {}: {}'.format(response.status_code, url))
continue
octets = response.content
if date not in PICT_EXCEPTIONS:
assert picture_type(octets) is not None, url
file_path = url.replace(PICT_BASE_URL, '')
file_name = os.path.basename(file_path)
path = os.path.join(SAVE_DIR, date.split('-')[0])
file_path = os.path.join(path, file_name)
#import pdb; pdb.set_trace()
try:
os.makedirs(path)
except FileExistsError:
pass
with open(file_path, 'wb') as fp:
fp.write(octets)
urls_ok.append(url)
print(file_path)
return urls_ok
def parse_args(argv):
parser = argparse.ArgumentParser(description=main.__doc__)
date_help = 'YYYY-MM-DD or YYYY-MM or YYYY: year, month and day'
parser.add_argument('date', help=date_help)
parser.add_argument('-q', '--max_qty', type=int,
help='maximum number of items to fetch')
parser.add_argument('-u', '--url_only', action='store_true',
help='get picture URLS only')
parser.add_argument('-f', '--fixture_save', action='store_true',
help='save data for local test fixture')
parser.add_argument('-v', '--verbose', action='store_true',
help='display progress information')
args = parser.parse_args(argv)
try:
iso_parts = validate_date(args.date)
except ValueError as exc:
print('error:', exc.args[0])
parser.print_usage()
sys.exit(2)
dates = list(gen_dates(iso_parts))
if args.verbose:
if len(dates) == 1:
print('-> Date: ', dates[0])
else:
fmt = '-> {} days: {}...{}'
print(fmt.format(len(dates), dates[0], dates[-1]))
return dates, args
def main(argv, get_picture_urls):
"""Get Wikipedia "Picture of The Day" for date, month or year"""
dates, args = parse_args(argv)
t0 = time.time()
if args.url_only:
urls = get_picture_urls(dates, args.verbose)
else:
urls = get_pictures(dates, args.verbose)
elapsed = time.time() - t0
if args.verbose:
print('-> found: {} pictures | elapsed time: {:.2f}s'
.format(len(urls), elapsed))
if __name__ == '__main__':
main(sys.argv[1:], get_picture_urls)
| NoPictureTemplateBefore |
python | django__django | tests/i18n/test_percents.py | {
"start": 2482,
"end": 7190
} | class ____(FrenchTestCase):
"""
Test rendering of templates that use percent signs.
Ensures both translate and blocktranslate tags behave consistently.
Refs #11240, #11966, #24257
"""
def test_translates_with_a_percent_symbol_at_the_end(self):
expected = "Littérale avec un symbole de pour cent à la fin %"
trans_tpl = Template(
"{% load i18n %}"
'{% translate "Literal with a percent symbol at the end %" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}Literal with a percent symbol at "
"the end %{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
def test_translates_with_percent_symbol_in_the_middle(self):
expected = "Pour cent littérale % avec un symbole au milieu"
trans_tpl = Template(
"{% load i18n %}"
'{% translate "Literal with a percent % symbol in the middle" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}Literal with a percent % symbol "
"in the middle{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
def test_translates_with_percent_symbol_using_context(self):
trans_tpl = Template('{% load i18n %}{% translate "It is 100%" %}')
self.assertEqual(trans_tpl.render(Context({})), "Il est de 100%")
trans_tpl = Template(
'{% load i18n %}{% translate "It is 100%" context "female" %}'
)
self.assertEqual(trans_tpl.render(Context({})), "Elle est de 100%")
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}It is 100%{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), "Il est de 100%")
block_tpl = Template(
"{% load i18n %}"
'{% blocktranslate context "female" %}It is 100%{% endblocktranslate %}'
)
self.assertEqual(block_tpl.render(Context({})), "Elle est de 100%")
def test_translates_with_string_that_look_like_fmt_spec_with_trans(self):
# tests "%s"
expected = (
"On dirait un spec str fmt %s mais ne devrait pas être interprété comme "
"plus disponible"
)
trans_tpl = Template(
'{% load i18n %}{% translate "Looks like a str fmt spec %s but '
'should not be interpreted as such" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}Looks like a str fmt spec %s but "
"should not be interpreted as such{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
# tests "% o"
expected = (
"On dirait un spec str fmt % o mais ne devrait pas être interprété comme "
"plus disponible"
)
trans_tpl = Template(
"{% load i18n %}"
'{% translate "Looks like a str fmt spec % o but should not be '
'interpreted as such" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}"
"{% blocktranslate %}Looks like a str fmt spec % o but should not be "
"interpreted as such{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
def test_translates_multiple_percent_signs(self):
expected = (
"1 % signe pour cent, signes %% 2 pour cent, trois signes de pourcentage "
"%%%"
)
trans_tpl = Template(
'{% load i18n %}{% translate "1 percent sign %, 2 percent signs %%, '
'3 percent signs %%%" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}1 percent sign %, 2 percent signs "
"%%, 3 percent signs %%%{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
block_tpl = Template(
"{% load i18n %}{% blocktranslate %}{{name}} says: 1 percent sign %, "
"2 percent signs %%{% endblocktranslate %}"
)
self.assertEqual(
block_tpl.render(Context({"name": "Django"})),
"Django dit: 1 pour cent signe %, deux signes de pourcentage %%",
)
| RenderingTemplatesWithPercentSigns |
python | doocs__leetcode | solution/0300-0399/0351.Android Unlock Patterns/Solution.py | {
"start": 0,
"end": 864
} | class ____:
def numberOfPatterns(self, m: int, n: int) -> int:
def dfs(i: int, cnt: int = 1) -> int:
if cnt > n:
return 0
vis[i] = True
ans = int(cnt >= m)
for j in range(1, 10):
x = cross[i][j]
if not vis[j] and (x == 0 or vis[x]):
ans += dfs(j, cnt + 1)
vis[i] = False
return ans
cross = [[0] * 10 for _ in range(10)]
cross[1][3] = cross[3][1] = 2
cross[1][7] = cross[7][1] = 4
cross[1][9] = cross[9][1] = 5
cross[2][8] = cross[8][2] = 5
cross[3][7] = cross[7][3] = 5
cross[3][9] = cross[9][3] = 6
cross[4][6] = cross[6][4] = 5
cross[7][9] = cross[9][7] = 8
vis = [False] * 10
return dfs(1) * 4 + dfs(2) * 4 + dfs(5)
| Solution |
python | tensorflow__tensorflow | tensorflow/python/eager/context.py | {
"start": 15845,
"end": 16164
} | class ____(object):
"""A simple atomic counter."""
__slots__ = ["_value", "_lock"]
def __init__(self):
self._value = 0
self._lock = threading.Lock()
def increment_and_get(self):
with self._lock:
self._value += 1
return self._value
_context_id_counter = _AtomicCounter()
| _AtomicCounter |
python | kamyu104__LeetCode-Solutions | Python/concatenation-of-array.py | {
"start": 445,
"end": 610
} | class ____(object):
def getConcatenation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return nums*2
| Solution3 |
python | numpy__numpy | numpy/f2py/tests/test_regression.py | {
"start": 3334,
"end": 4005
} | class ____(util.F2PyTest):
# Check that comments are stripped from F77 continuation lines
sources = [util.getpath("tests", "src", "regression", "f77comments.f")]
@pytest.mark.slow
def test_gh26148(self):
x1 = np.array(3, dtype=np.int32)
x2 = np.array(5, dtype=np.int32)
res = self.module.testsub(x1, x2)
assert res[0] == 8
assert res[1] == 15
@pytest.mark.slow
def test_gh26466(self):
# Check that comments after PARAMETER directions are stripped
expected = np.arange(1, 11, dtype=np.float32) * 2
res = self.module.testsub2()
npt.assert_allclose(expected, res)
| TestF77Comments |
python | pytorch__pytorch | test/nn/test_init.py | {
"start": 414,
"end": 20988
} | class ____(TestCase):
def setUp(self):
super().setUp()
random.seed(123)
def _is_normal(self, tensor, mean, std):
samples = tensor.view(-1).tolist()
p_value = stats.kstest(samples, "norm", args=(mean, std))[1]
return p_value > 0.0001
def _is_trunc_normal(self, tensor, mean, std, a, b):
# scipy's trunc norm is suited for data drawn from N(0, 1),
# so we need to transform our data to test it using scipy.
z_samples = (tensor.view(-1) - mean) / std
z_samples = z_samples.tolist()
a0 = (a - mean) / std
b0 = (b - mean) / std
p_value = stats.kstest(z_samples, "truncnorm", args=(a0, b0))[1]
return p_value > 0.0001
def _is_uniform(self, tensor, a, b):
samples = tensor.view(-1).tolist()
p_value = stats.kstest(samples, "uniform", args=(a, (b - a)))[1]
return p_value > 0.0001
def _create_random_nd_tensor(self, dims, size_min, size_max):
size = [random.randint(size_min, size_max) for _ in range(dims)]
tensor = torch.zeros(size)
return tensor
def _random_float(self, a, b):
return (b - a) * random.random() + a
def test_calculate_gain_linear(self):
for fn in [
"linear",
"conv1d",
"conv2d",
"conv3d",
"conv_transpose2d",
"conv_transpose2d",
"conv_transpose3d",
]:
gain = init.calculate_gain(fn)
self.assertEqual(gain, 1)
def test_calculate_gain_nonlinear(self):
for fn in ["sigmoid", "tanh", "relu", "leaky_relu"]:
gain = init.calculate_gain(fn)
if fn == "sigmoid":
self.assertEqual(gain, 1)
elif fn == "tanh": # 5 / 3
self.assertEqual(gain, 1.6666666666666667)
elif fn == "relu": # sqrt(2)
self.assertEqual(gain, 1.4142135623730951)
elif fn == "leaky_relu": # sqrt(2 / 1 + slope^2))
self.assertEqual(gain, 1.4141428569978354)
elif fn == "selu":
self.assertEqual(gain, 0.75)
def test_calculate_gain_leaky_relu(self):
for param in [None, 0, 0.01, 10]:
gain = init.calculate_gain("leaky_relu", param)
if param is None: # Default slope is 0.01
self.assertEqual(gain, 1.4141428569978354)
elif param == 0: # No slope = same gain as normal ReLU
self.assertEqual(gain, 1.4142135623730951)
elif param == 0.01:
self.assertEqual(gain, 1.4141428569978354)
elif param == 10:
self.assertEqual(gain, 0.14071950894605836)
def test_calculate_gain_leaky_relu_only_accepts_numbers(self):
for param in [True, [1], {"a": "b"}]:
with self.assertRaises(ValueError):
init.calculate_gain("leaky_relu", param)
def test_calculate_gain_only_accepts_valid_nonlinearities(self):
for n in [2, 5, 25]:
# Generate random strings of lengths that definitely aren't supported
random_string = "".join(
[random.choice(string.ascii_lowercase) for i in range(n)]
)
with self.assertRaises(ValueError):
init.calculate_gain(random_string)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@skipIfTorchDynamo("scipy.kstest is failing under dynamo")
def test_uniform(self):
for dims in [1, 2, 4]:
input_tensor = self._create_random_nd_tensor(dims, size_min=30, size_max=50)
a = self._random_float(-3, 3)
b = a + self._random_float(1, 5)
init.uniform_(input_tensor, a=a, b=b)
assert self._is_uniform(input_tensor, a, b)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@skipIfTorchDynamo("scipy.kstest is failing under dynamo")
def test_normal(self):
for dims in [1, 2, 4]:
input_tensor = self._create_random_nd_tensor(dims, size_min=30, size_max=50)
mean = self._random_float(-3, 3)
std = self._random_float(1, 5)
init.normal_(input_tensor, mean=mean, std=std)
assert self._is_normal(input_tensor, mean, std)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@skipIfTorchDynamo("scipy.kstest is failing under dynamo")
def test_trunc_normal(self):
for dims in [1, 2, 4]:
input_tensor = self._create_random_nd_tensor(dims, size_min=30, size_max=50)
mean = self._random_float(-3, 3)
std = self._random_float(0.01, 1)
a = self._random_float(mean - 2 * std, mean)
b = self._random_float(mean, mean + 2 * std)
init.trunc_normal_(input_tensor, mean=mean, std=std, a=a, b=b)
assert self._is_trunc_normal(input_tensor, mean, std, a, b)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@skipIfTorchDynamo("scipy.kstest is failing under dynamo")
def test_trunc_normal_generator(self):
gen = torch.Generator()
gen.manual_seed(42)
input_tensor = torch.empty(5)
init.trunc_normal_(input_tensor, generator=gen)
ref = torch.empty(5)
torch.manual_seed(42)
init.trunc_normal_(ref)
self.assertEqual(input_tensor, ref)
assert self._is_trunc_normal(input_tensor, mean=0, std=1, a=0, b=1)
def test_constant(self):
for dims in [1, 2, 4]:
input_tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=5)
val = self._random_float(1, 10)
init.constant_(input_tensor, val)
self.assertEqual(input_tensor, input_tensor.clone().fill_(val))
def test_ones_and_zeros(self):
for init_fn_, val in zip([init.ones_, init.zeros_], [1, 0]):
for dims in [1, 2, 4]:
input_tensor = self._create_random_nd_tensor(
dims, size_min=1, size_max=5
)
init_fn_(input_tensor)
self.assertEqual(input_tensor, input_tensor.clone().fill_(val))
def test_eye(self):
input_tensor = self._create_random_nd_tensor(2, size_min=1, size_max=5)
init.eye_(input_tensor)
# Check every single element
for i in range(input_tensor.size(0)):
for j in range(input_tensor.size(1)):
if i == j:
assert input_tensor[i][j] == 1
else:
assert input_tensor[i][j] == 0
def test_eye_only_works_on_2d_inputs(self):
for dims in [1, 3]:
with self.assertRaises(ValueError):
tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=3)
init.eye_(tensor)
def test_dirac_properties(self):
for dims in [3, 4, 5]:
for groups in [1, 2, 3]:
# prepare random tensor with random sizes, but fits groups
a, c, d, e = (random.randint(1, 5) for _ in range(4))
b = random.randint(
1, 5 * groups
) # same range as a*groups but all range allowed
# make sure first dim divides by groups
input_tensor = torch.randn((a * groups, b, c, d, e)[:dims])
init.dirac_(input_tensor, groups)
c_out, c_in = input_tensor.size(0) // groups, input_tensor.size(1)
min_d = min(c_out, c_in)
# Check number of nonzeros is equivalent to smallest dim (for each group)
assert torch.nonzero(input_tensor).size(0) == min_d * groups
# Check sum of values (can have precision issues, hence assertEqual) is also equivalent
self.assertEqual(input_tensor.sum(), min_d * groups)
def test_dirac_identity(self):
for groups in [1, 3]:
batch, in_c, out_c, size, kernel_size = (
8,
3,
9,
5,
3,
) # in_c, out_c must divide by groups
eff_out_c = out_c // groups
# Test 1D
input_var = torch.randn(batch, in_c, size)
filter_var = torch.zeros(eff_out_c, in_c, kernel_size)
filter_var = torch.cat([filter_var] * groups)
init.dirac_(filter_var, groups)
output_var = F.conv1d(input_var, filter_var)
input_tensor, output_tensor = (
input_var.data,
output_var.data,
) # Variables do not support nonzero
for g in range(groups):
# Assert in_c outputs are preserved (per each group)
self.assertEqual(
input_tensor[:, :, 1:-1],
output_tensor[:, eff_out_c * g : eff_out_c * g + in_c, :],
)
# Assert extra outputs are 0
assert (
torch.nonzero(
output_tensor[:, eff_out_c * g + in_c : eff_out_c * (g + 1), :]
).numel()
== 0
)
# Test 2D
input_var = torch.randn(batch, in_c, size, size)
filter_var = torch.zeros(eff_out_c, in_c, kernel_size, kernel_size)
filter_var = torch.cat([filter_var] * groups)
init.dirac_(filter_var, groups)
output_var = F.conv2d(input_var, filter_var)
input_tensor, output_tensor = (
input_var.data,
output_var.data,
) # Variables do not support nonzero
for g in range(groups):
# Assert in_c outputs are preserved (per each group)
self.assertEqual(
input_tensor[:, :, 1:-1, 1:-1],
output_tensor[:, eff_out_c * g : eff_out_c * g + in_c, :, :],
)
# Assert extra outputs are 0
assert (
torch.nonzero(
output_tensor[
:, eff_out_c * g + in_c : eff_out_c * (g + 1), :, :
]
).numel()
== 0
)
# Test 3D
input_var = torch.randn(batch, in_c, size, size, size)
filter_var = torch.zeros(
eff_out_c, in_c, kernel_size, kernel_size, kernel_size
)
filter_var = torch.cat([filter_var] * groups)
init.dirac_(filter_var, groups)
output_var = F.conv3d(input_var, filter_var)
input_tensor, output_tensor = input_var.data, output_var.data
for g in range(groups):
# Assert in_c outputs are preserved (per each group)
self.assertEqual(
input_tensor[:, :, 1:-1, 1:-1, 1:-1],
output_tensor[:, eff_out_c * g : eff_out_c * g + in_c, :, :, :],
)
# Assert extra outputs are 0
assert (
torch.nonzero(
output_tensor[
:, eff_out_c * g + in_c : eff_out_c * (g + 1), :, :, :
]
).numel()
== 0
)
def test_dirac_only_works_on_3_4_5d_inputs(self):
for dims in [1, 2, 6]:
with self.assertRaises(ValueError):
tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=3)
init.dirac_(tensor)
def test_xavier_uniform_errors_on_inputs_smaller_than_2d(self):
for dims in [0, 1]:
tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=1)
with self.assertRaises(ValueError):
init.xavier_uniform_(tensor)
def test_xavier_normal_errors_on_inputs_smaller_than_2d(self):
for dims in [0, 1]:
tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=1)
with self.assertRaises(ValueError):
init.xavier_normal_(tensor)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@slowTest
def test_xavier_uniform(self):
for use_gain in [True, False]:
for dims in [2, 4]:
input_tensor = self._create_random_nd_tensor(
dims, size_min=20, size_max=25
)
gain = 1
if use_gain:
gain = self._random_float(0.1, 2)
init.xavier_uniform_(input_tensor, gain=gain)
else:
init.xavier_uniform_(input_tensor)
fan_in = input_tensor.size(1)
fan_out = input_tensor.size(0)
if input_tensor.dim() > 2:
fan_in *= input_tensor[0, 0].numel()
fan_out *= input_tensor[0, 0].numel()
expected_std = gain * math.sqrt(2.0 / (fan_in + fan_out))
bounds = expected_std * math.sqrt(3)
assert self._is_uniform(input_tensor, -bounds, bounds)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@skipIfTorchDynamo("scipy.kstest is failing under dynamo")
def test_xavier_normal(self):
for use_gain in [True, False]:
for dims in [2, 4]:
input_tensor = self._create_random_nd_tensor(
dims, size_min=20, size_max=25
)
gain = 1
if use_gain:
gain = self._random_float(0.1, 2)
init.xavier_normal_(input_tensor, gain=gain)
else:
init.xavier_normal_(input_tensor)
fan_in = input_tensor.size(1)
fan_out = input_tensor.size(0)
if input_tensor.dim() > 2:
fan_in *= input_tensor[0, 0].numel()
fan_out *= input_tensor[0, 0].numel()
expected_std = gain * math.sqrt(2.0 / (fan_in + fan_out))
assert self._is_normal(input_tensor, 0, expected_std)
def test_kaiming_uniform_errors_on_inputs_smaller_than_2d(self):
for dims in [0, 1]:
with self.assertRaises(ValueError):
tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=1)
init.kaiming_uniform_(tensor)
def test_kaiming_normal_errors_on_inputs_smaller_than_2d(self):
for dims in [0, 1]:
with self.assertRaises(ValueError):
tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=1)
init.kaiming_normal_(tensor)
def test_kaiming_uniform_warning_on_0element_tensor(self):
tensor = torch.empty(0, 1)
with self.assertWarnsRegex(
UserWarning, "Initializing zero-element tensors is a no-op"
):
_ = init.kaiming_uniform_(tensor)
def test_kaiming_normal_warning_on_0element_tensor(self):
tensor = torch.empty(0, 1)
with self.assertWarnsRegex(
UserWarning, "Initializing zero-element tensors is a no-op"
):
_ = init.kaiming_normal_(tensor)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@skipIfTorchDynamo("scipy.kstest is failing under dynamo")
def test_kaiming_uniform(self):
for use_a in [True, False]:
for dims in [2, 4]:
for mode in ["fan_in", "fan_out"]:
input_tensor = self._create_random_nd_tensor(
dims, size_min=20, size_max=25
)
if use_a:
a = self._random_float(0.1, 2)
init.kaiming_uniform_(input_tensor, a=a, mode=mode)
else:
a = 0
init.kaiming_uniform_(input_tensor, mode=mode)
fan_in = input_tensor.size(1)
fan_out = input_tensor.size(0)
if input_tensor.dim() > 2:
fan_in *= input_tensor[0, 0].numel()
fan_out *= input_tensor[0, 0].numel()
if mode == "fan_in":
n = fan_in
else:
n = fan_out
expected_std = math.sqrt(2.0 / ((1 + a**2) * n))
bounds = expected_std * math.sqrt(3.0)
assert self._is_uniform(input_tensor, -bounds, bounds)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@skipIfTorchDynamo("scipy.kstest is failing under dynamo")
def test_kaiming_normal(self):
for use_a in [True, False]:
for dims in [2, 4]:
for mode in ["fan_in", "fan_out"]:
input_tensor = self._create_random_nd_tensor(
dims, size_min=20, size_max=25
)
if use_a:
a = self._random_float(0.1, 2)
init.kaiming_normal_(input_tensor, a=a, mode=mode)
else:
a = 0
init.kaiming_normal_(input_tensor, mode=mode)
fan_in = input_tensor.size(1)
fan_out = input_tensor.size(0)
if input_tensor.dim() > 2:
fan_in *= input_tensor[0, 0].numel()
fan_out *= input_tensor[0, 0].numel()
if mode == "fan_in":
n = fan_in
else:
n = fan_out
expected_std = math.sqrt(2.0 / ((1 + a**2) * n))
assert self._is_normal(input_tensor, 0, expected_std)
def test_sparse_only_works_on_2d_inputs(self):
for dims in [1, 3]:
with self.assertRaises(ValueError):
sparsity = self._random_float(0.1, 0.9)
tensor = self._create_random_nd_tensor(dims, size_min=1, size_max=3)
init.sparse_(tensor, sparsity)
@unittest.skipIf(not TEST_SCIPY, "Scipy not found.")
@skipIfTorchDynamo("scipy.kstest is failing under dynamo")
def test_sparse_default_std(self):
for use_random_std in [True, False]:
input_tensor = self._create_random_nd_tensor(2, size_min=30, size_max=35)
rows = input_tensor.size(0)
sparsity = self._random_float(0.1, 0.2)
std = 0.01 # default std
if use_random_std:
std = self._random_float(0.01, 0.2)
init.sparse_(input_tensor, sparsity=sparsity, std=std)
else:
init.sparse_(input_tensor, sparsity=sparsity)
for col_idx in range(input_tensor.size(1)):
column = input_tensor[:, col_idx]
assert column[column == 0].nelement() >= math.ceil(sparsity * rows)
assert self._is_normal(input_tensor[input_tensor != 0], 0, std)
@skipIfNoLapack
def test_orthogonal(self):
for use_gain in [True, False]:
for tensor_size in [[3, 4], [4, 3], [20, 2, 3, 4], [2, 3, 4, 5]]:
input_tensor = torch.zeros(tensor_size)
gain = 1.0
if use_gain:
gain = self._random_float(0.1, 2)
init.orthogonal_(input_tensor, gain=gain)
else:
init.orthogonal_(input_tensor)
rows, cols = tensor_size[0], reduce(mul, tensor_size[1:])
flattened_tensor = input_tensor.view(rows, cols)
if rows > cols:
self.assertEqual(
torch.mm(flattened_tensor.t(), flattened_tensor),
torch.eye(cols) * gain**2,
atol=1e-6,
rtol=0,
)
else:
self.assertEqual(
torch.mm(flattened_tensor, flattened_tensor.t()),
torch.eye(rows) * gain**2,
atol=1e-6,
rtol=0,
)
def test_deprecation(self):
x = torch.randn(3, 3)
def fn():
init.normal(x)
with self.assertWarnsRegex(
FutureWarning,
"deprecated",
msg="methods not suffixed with underscore should be deprecated",
):
fn()
if __name__ == "__main__":
run_tests()
| TestNNInit |
python | pallets__itsdangerous | src/itsdangerous/signer.py | {
"start": 2296,
"end": 9647
} | class ____:
"""A signer securely signs bytes, then unsigns them to verify that
the value hasn't been changed.
The secret key should be a random string of ``bytes`` and should not
be saved to code or version control. Different salts should be used
to distinguish signing in different contexts. See :doc:`/concepts`
for information about the security of the secret key and salt.
:param secret_key: The secret key to sign and verify with. Can be a
list of keys, oldest to newest, to support key rotation.
:param salt: Extra key to combine with ``secret_key`` to distinguish
signatures in different contexts.
:param sep: Separator between the signature and value.
:param key_derivation: How to derive the signing key from the secret
key and salt. Possible values are ``concat``, ``django-concat``,
or ``hmac``. Defaults to :attr:`default_key_derivation`, which
defaults to ``django-concat``.
:param digest_method: Hash function to use when generating the HMAC
signature. Defaults to :attr:`default_digest_method`, which
defaults to :func:`hashlib.sha1`. Note that the security of the
hash alone doesn't apply when used intermediately in HMAC.
:param algorithm: A :class:`SigningAlgorithm` instance to use
instead of building a default :class:`HMACAlgorithm` with the
``digest_method``.
.. versionchanged:: 2.0
Added support for key rotation by passing a list to
``secret_key``.
.. versionchanged:: 0.18
``algorithm`` was added as an argument to the class constructor.
.. versionchanged:: 0.14
``key_derivation`` and ``digest_method`` were added as arguments
to the class constructor.
"""
#: The default digest method to use for the signer. The default is
#: :func:`hashlib.sha1`, but can be changed to any :mod:`hashlib` or
#: compatible object. Note that the security of the hash alone
#: doesn't apply when used intermediately in HMAC.
#:
#: .. versionadded:: 0.14
default_digest_method: t.Any = staticmethod(_lazy_sha1)
#: The default scheme to use to derive the signing key from the
#: secret key and salt. The default is ``django-concat``. Possible
#: values are ``concat``, ``django-concat``, and ``hmac``.
#:
#: .. versionadded:: 0.14
default_key_derivation: str = "django-concat"
def __init__(
self,
secret_key: str | bytes | cabc.Iterable[str] | cabc.Iterable[bytes],
salt: str | bytes | None = b"itsdangerous.Signer",
sep: str | bytes = b".",
key_derivation: str | None = None,
digest_method: t.Any | None = None,
algorithm: SigningAlgorithm | None = None,
):
#: The list of secret keys to try for verifying signatures, from
#: oldest to newest. The newest (last) key is used for signing.
#:
#: This allows a key rotation system to keep a list of allowed
#: keys and remove expired ones.
self.secret_keys: list[bytes] = _make_keys_list(secret_key)
self.sep: bytes = want_bytes(sep)
if self.sep in _base64_alphabet:
raise ValueError(
"The given separator cannot be used because it may be"
" contained in the signature itself. ASCII letters,"
" digits, and '-_=' must not be used."
)
if salt is not None:
salt = want_bytes(salt)
else:
salt = b"itsdangerous.Signer"
self.salt = salt
if key_derivation is None:
key_derivation = self.default_key_derivation
self.key_derivation: str = key_derivation
if digest_method is None:
digest_method = self.default_digest_method
self.digest_method: t.Any = digest_method
if algorithm is None:
algorithm = HMACAlgorithm(self.digest_method)
self.algorithm: SigningAlgorithm = algorithm
@property
def secret_key(self) -> bytes:
"""The newest (last) entry in the :attr:`secret_keys` list. This
is for compatibility from before key rotation support was added.
"""
return self.secret_keys[-1]
def derive_key(self, secret_key: str | bytes | None = None) -> bytes:
"""This method is called to derive the key. The default key
derivation choices can be overridden here. Key derivation is not
intended to be used as a security method to make a complex key
out of a short password. Instead you should use large random
secret keys.
:param secret_key: A specific secret key to derive from.
Defaults to the last item in :attr:`secret_keys`.
.. versionchanged:: 2.0
Added the ``secret_key`` parameter.
"""
if secret_key is None:
secret_key = self.secret_keys[-1]
else:
secret_key = want_bytes(secret_key)
if self.key_derivation == "concat":
return t.cast(bytes, self.digest_method(self.salt + secret_key).digest())
elif self.key_derivation == "django-concat":
return t.cast(
bytes, self.digest_method(self.salt + b"signer" + secret_key).digest()
)
elif self.key_derivation == "hmac":
mac = hmac.new(secret_key, digestmod=self.digest_method)
mac.update(self.salt)
return mac.digest()
elif self.key_derivation == "none":
return secret_key
else:
raise TypeError("Unknown key derivation method")
def get_signature(self, value: str | bytes) -> bytes:
"""Returns the signature for the given value."""
value = want_bytes(value)
key = self.derive_key()
sig = self.algorithm.get_signature(key, value)
return base64_encode(sig)
def sign(self, value: str | bytes) -> bytes:
"""Signs the given string."""
value = want_bytes(value)
return value + self.sep + self.get_signature(value)
def verify_signature(self, value: str | bytes, sig: str | bytes) -> bool:
"""Verifies the signature for the given value."""
try:
sig = base64_decode(sig)
except Exception:
return False
value = want_bytes(value)
for secret_key in reversed(self.secret_keys):
key = self.derive_key(secret_key)
if self.algorithm.verify_signature(key, value, sig):
return True
return False
def unsign(self, signed_value: str | bytes) -> bytes:
"""Unsigns the given string."""
signed_value = want_bytes(signed_value)
if self.sep not in signed_value:
raise BadSignature(f"No {self.sep!r} found in value")
value, sig = signed_value.rsplit(self.sep, 1)
if self.verify_signature(value, sig):
return value
raise BadSignature(f"Signature {sig!r} does not match", payload=value)
def validate(self, signed_value: str | bytes) -> bool:
"""Only validates the given signed value. Returns ``True`` if
the signature exists and is valid.
"""
try:
self.unsign(signed_value)
return True
except BadSignature:
return False
| Signer |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/too_many_positional_arguments.py | {
"start": 499,
"end": 1089
} | class ____:
def f(self, a, b, c, d, e): # OK
pass
def f(self, /, a, b, c, d, e): # OK
pass
def f(weird_self_name, a, b, c, d, e): # OK
pass
def f(self, a, b, c, d, e, g): # Too many positional arguments (6/5)
pass
@staticmethod
def f(self, a, b, c, d, e): # Too many positional arguments (6/5)
pass
@classmethod
def f(cls, a, b, c, d, e): # OK
pass
def f(*, self, a, b, c, d, e): # OK
pass
def f(self=1, a=1, b=1, c=1, d=1, e=1): # OK
pass
def f(): # OK
pass
| C |
python | Pylons__pyramid | src/pyramid/security.py | {
"start": 12319,
"end": 13782
} | class ____:
"""
A :term:`security policy` which provides a backwards compatibility shim for
the :term:`authentication policy` and the :term:`authorization policy`.
"""
def _get_authn_policy(self, request):
return request.registry.getUtility(IAuthenticationPolicy)
def _get_authz_policy(self, request):
return request.registry.getUtility(IAuthorizationPolicy)
def identity(self, request):
return self.authenticated_userid(request)
def authenticated_userid(self, request):
authn = self._get_authn_policy(request)
return authn.authenticated_userid(request)
def remember(self, request, userid, **kw):
authn = self._get_authn_policy(request)
return authn.remember(request, userid, **kw)
def forget(self, request, **kw):
if kw:
raise ValueError(
'Legacy authentication policies do not support keyword '
'arguments for `forget`'
)
authn = self._get_authn_policy(request)
return authn.forget(request)
def permits(self, request, context, permission):
authn = self._get_authn_policy(request)
authz = self._get_authz_policy(request)
principals = authn.effective_principals(request)
return authz.permits(context, principals, permission)
Everyone = 'system.Everyone'
Authenticated = 'system.Authenticated'
Allow = 'Allow'
Deny = 'Deny'
| LegacySecurityPolicy |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_core/test_worker.py | {
"start": 40025,
"end": 40149
} | class ____(LogGroomerTestBase):
"""Worker groomer."""
obj_name = "worker"
folder = "workers"
| TestWorkerLogGroomer |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchvision_models.py | {
"start": 13035,
"end": 13674
} | class ____(_SimpleSegmentationModel):
"""
Implements a Fully-Convolutional Network for semantic segmentation.
Args:
backbone (nn.Module): the network used to compute the features for the model.
The backbone should return an OrderedDict[Tensor], with the key being
"out" for the last feature map used, and "aux" if an auxiliary classifier
is used.
classifier (nn.Module): module that takes the "out" element returned from
the backbone and returns a dense prediction.
aux_classifier (nn.Module, optional): auxiliary classifier used during training
"""
| FCN |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/vendor/pretty.py | {
"start": 21959,
"end": 22146
} | class ____(Printable):
def __init__(self, depth: int) -> None:
self.depth = depth
self.breakables: deque[Breakable] = deque()
self.want_break: bool = False
| Group |
python | apache__avro | lang/py/avro/schema.py | {
"start": 30974,
"end": 35838
} | class ____(EqualByJsonMixin, NamedSchema):
@staticmethod
def make_field_objects(field_data: Sequence[Mapping[str, object]], names: avro.name.Names, validate_names: bool = True) -> Sequence[Field]:
"""We're going to need to make message parameters too."""
field_objects = []
field_names = []
for field in field_data:
if not callable(getattr(field, "get", None)):
raise avro.errors.SchemaParseException(f"Not a valid field: {field}")
type = field.get("type")
name = field.get("name")
# null values can have a default value of None
has_default = "default" in field
default = field.get("default")
order = field.get("order")
doc = field.get("doc")
other_props = get_other_props(field, FIELD_RESERVED_PROPS)
new_field = Field(type, name, has_default, default, order, names, doc, other_props, validate_names=validate_names)
# make sure field name has not been used yet
if new_field.name in field_names:
fail_msg = f"Field name {new_field.name} already in use."
raise avro.errors.SchemaParseException(fail_msg)
field_names.append(new_field.name)
field_objects.append(new_field)
return field_objects
def match(self, writer):
"""Return True if the current schema (as reader) matches the other schema.
@arg writer: the schema to match against
@return bool
"""
return writer.type == self.type and (self.type == "request" or self.check_props(writer, ["fullname"]))
def __init__(
self,
name,
namespace,
fields,
names=None,
schema_type="record",
doc=None,
other_props=None,
validate_names: bool = True,
):
# Ensure valid ctor args
if fields is None:
fail_msg = "Record schema requires a non-empty fields property."
raise avro.errors.SchemaParseException(fail_msg)
elif not isinstance(fields, list):
fail_msg = "Fields property must be a list of Avro schemas."
raise avro.errors.SchemaParseException(fail_msg)
# Call parent ctor (adds own name to namespace, too)
if schema_type == "request":
Schema.__init__(self, schema_type, other_props)
else:
NamedSchema.__init__(self, schema_type, name, namespace, names, other_props, validate_names=validate_names)
names = names or Names(validate_names=self.validate_names)
if schema_type == "record":
old_default = names.default_namespace
names.default_namespace = Name(name, namespace, names.default_namespace, validate_name=validate_names).space
# Add class members
field_objects = RecordSchema.make_field_objects(fields, names, validate_names=validate_names)
self.set_prop("fields", field_objects)
if doc is not None:
self.set_prop("doc", doc)
if schema_type == "record":
names.default_namespace = old_default
# read-only properties
@property
def fields(self):
return self.get_prop("fields")
@property
def doc(self):
return self.get_prop("doc")
@property
def fields_dict(self):
fields_dict = {}
for field in self.fields:
fields_dict[field.name] = field
return fields_dict
def to_json(self, names=None):
names = names or Names(validate_names=self.validate_names)
# Request records don't have names
if self.type == "request":
return [f.to_json(names) for f in self.fields]
if self.fullname in names.names:
return self.name_ref(names)
else:
names.names[self.fullname] = self
to_dump = names.prune_namespace(self.props.copy())
to_dump["fields"] = [f.to_json(names) for f in self.fields]
return to_dump
def to_canonical_json(self, names=None):
names = names or Names(validate_names=self.validate_names)
if self.type == "request":
raise NotImplementedError("Canonical form (probably) does not make sense on type request")
to_dump = self.canonical_properties
to_dump["name"] = self.fullname
if self.fullname in names.names:
return self.name_ref(names)
names.names[self.fullname] = self
to_dump["fields"] = [f.to_canonical_json(names) for f in self.fields]
return to_dump
def validate(self, datum):
"""Return self if datum is a valid representation of this schema, else None"""
return self if isinstance(datum, dict) and {f.name for f in self.fields}.issuperset(datum.keys()) else None
#
# Date Type
#
| RecordSchema |
python | pytorch__pytorch | test/quantization/core/test_workflow_module.py | {
"start": 1910,
"end": 21472
} | class ____(QuantizationTestCase):
@given(qdtype=st.sampled_from(_INT_DTYPES),
qscheme=st.sampled_from((torch.per_tensor_affine, torch.per_tensor_symmetric)),
reduce_range=st.booleans())
def test_per_tensor_observers(self, qdtype, qscheme, reduce_range):
# reduce_range cannot be true for symmetric quantization with uint8
if (qdtype == torch.quint8 and qscheme == torch.per_tensor_symmetric) or qdtype == torch.qint32:
reduce_range = False
if qdtype == torch.quint4x2:
return
ObserverList = [MinMaxObserver(dtype=qdtype, qscheme=qscheme, reduce_range=reduce_range),
MovingAverageMinMaxObserver(averaging_constant=0.5,
dtype=qdtype,
qscheme=qscheme,
reduce_range=reduce_range)]
def _get_ref_params(reduce_range, qscheme, dtype, input_scale, min_val, max_val):
assert dtype in _INT_DTYPES, f"Not supported dtype: {dtype}, supported dtypes are {_INT_DTYPES}"
eps = torch.tensor([tolerance])
if dtype in [torch.qint8, torch.int8]:
if reduce_range:
quant_min, quant_max = -64, 63
else:
quant_min, quant_max = -128, 127
elif dtype in [torch.quint8, torch.uint8]:
if reduce_range:
quant_min, quant_max = 0, 127
else:
quant_min, quant_max = 0, 255
elif dtype == torch.int16:
quant_min, quant_max = -1 * (2 ** 15), (2 ** 15) - 1
elif dtype == torch.uint16:
quant_min, quant_max = 0, (2 ** 16) - 1
elif dtype in [torch.qint32, torch.int32]:
quant_min, quant_max = -1 * (2 ** 31), (2 ** 31) - 1
min_val_neg = torch.tensor([0.])
max_val_pos = torch.tensor([input_scale * max_val]) if qdtype is torch.qint32 else torch.tensor([max_val])
scale, zero_point = 1.0, 0
if qscheme == torch.per_tensor_symmetric or qscheme == torch.per_channel_symmetric:
scale = torch.max(-min_val_neg, max_val_pos) / (float(quant_max - quant_min) / 2)
scale = torch.max(scale, eps)
if dtype in [torch.quint8, torch.uint8]:
zero_point = 128
if dtype in [torch.uint16]:
zero_point = 2 ** 15
else:
scale = torch.max((max_val_pos - min_val_neg) / float(quant_max - quant_min), eps)
zero_point = quant_min - torch.round(min_val_neg / scale).to(torch.int)
zero_point = torch.clamp(zero_point, quant_min, quant_max)
return scale, zero_point
for myobs in ObserverList:
# Calculate Qparams should return with a warning for observers with no data
qparams = myobs.calculate_qparams()
input_scale = 2**16 if qdtype is torch.qint32 else 1
if type(myobs) is MinMaxObserver:
x = torch.tensor([1.0, 2.0, 2.0, 3.0, 4.0, 5.0, 6.0]) * input_scale
y = torch.tensor([4.0, 5.0, 5.0, 6.0, 7.0, 8.0]) * input_scale
else:
# Moving average of min/max for x and y matches that of
# extreme values for x/y used for minmax observer
x = torch.tensor([0.0, 2.0, 2.0, 3.0, 4.0, 5.0, 6.0]) * input_scale
y = torch.tensor([2.0, 5.0, 5.0, 6.0, 7.0, 10.0]) * input_scale
result = myobs(x)
result = myobs(y)
self.assertEqual(result, y)
self.assertEqual(myobs.min_val, 1.0 * input_scale)
self.assertEqual(myobs.max_val, 8.0 * input_scale)
qparams = myobs.calculate_qparams()
ref_scale, ref_zero_point = _get_ref_params(reduce_range, qscheme, qdtype, input_scale, 1.0, 8.0)
self.assertEqual(qparams[1].item(), ref_zero_point)
self.assertEqual(qparams[0].item(), ref_scale, atol=1e-5, rtol=0)
state_dict = myobs.state_dict()
b = io.BytesIO()
torch.save(state_dict, b)
for weights_only in [True, False]:
b.seek(0)
loaded_dict = torch.load(b, weights_only=weights_only)
for key in state_dict:
self.assertEqual(state_dict[key], loaded_dict[key])
loaded_obs = MinMaxObserver(dtype=qdtype, qscheme=qscheme, reduce_range=reduce_range)
loaded_obs.load_state_dict(loaded_dict)
loaded_qparams = loaded_obs.calculate_qparams()
self.assertEqual(myobs.min_val, loaded_obs.min_val)
self.assertEqual(myobs.max_val, loaded_obs.max_val)
self.assertEqual(myobs.calculate_qparams(), loaded_obs.calculate_qparams())
@given(qdtype=st.sampled_from((torch.qint8, torch.quint8)),
qscheme=st.sampled_from((torch.per_channel_affine, torch.per_channel_symmetric, torch.per_channel_affine_float_qparams)),
ch_axis=st.sampled_from((0, 1, 2, 3)), reduce_range=st.booleans())
def test_per_channel_observers(self, qdtype, qscheme, ch_axis, reduce_range):
# reduce_range cannot be true for symmetric quantization with uint8
if qscheme == torch.per_channel_affine_float_qparams:
reduce_range = False
if qdtype == torch.quint8 and qscheme == torch.per_channel_symmetric:
reduce_range = False
ObserverList = [PerChannelMinMaxObserver(reduce_range=reduce_range,
ch_axis=ch_axis,
dtype=qdtype,
qscheme=qscheme),
MovingAveragePerChannelMinMaxObserver(averaging_constant=0.5,
reduce_range=reduce_range,
ch_axis=ch_axis,
dtype=qdtype,
qscheme=qscheme)]
for myobs in ObserverList:
# Calculate qparams should work for empty observers
qparams = myobs.calculate_qparams()
x = torch.tensor(
[
[[[1.0, 2.0], [2.0, 2.5]], [[3.0, 4.0], [4.5, 6.0]]],
[[[-4.0, -3.0], [5.0, 5.0]], [[6.0, 3.0], [7.0, 8.0]]],
]
)
if type(myobs) is MovingAveragePerChannelMinMaxObserver:
# Scaling the input tensor to model change in min/max values
# across batches
result = myobs(0.5 * x)
result = myobs(1.5 * x)
self.assertEqual(result, 1.5 * x)
else:
result = myobs(x)
self.assertEqual(result, x)
qparams = myobs.calculate_qparams()
ref_min_vals = [[1.0, -4.0], [-4.0, 3.0], [-4.0, 2.0], [-4.0, -3.0]]
ref_max_vals = [[6.0, 8.0], [5.0, 8.0], [6.0, 8.0], [7.0, 8.0]]
per_channel_symmetric_ref_scales = [
[0.04705882, 0.06274509],
[0.03921569, 0.0627451],
[0.04705882, 0.0627451],
[0.05490196, 0.0627451],
]
per_channel_affine_ref_scales = [
[0.02352941, 0.04705882],
[0.03529412, 0.03137255],
[0.03921569, 0.03137255],
[0.04313726, 0.04313726],
]
per_channel_affine_qint8_zp = [
[-128, -43],
[-15, -128],
[-26, -128],
[-35, -58],
]
per_channel_affine_float_qparams_ref_scales = [
[0.0196, 0.0471],
[0.0353, 0.0196],
[0.0392, 0.0235],
[0.0431, 0.0431],
]
per_channel_affine_quint8_zp = [[0, 85], [113, 0], [102, 0], [93, 70]]
self.assertEqual(myobs.min_val, ref_min_vals[ch_axis])
self.assertEqual(myobs.max_val, ref_max_vals[ch_axis])
if qscheme == torch.per_channel_symmetric:
ref_scales = per_channel_symmetric_ref_scales[ch_axis]
ref_zero_points = [0, 0] if qdtype is torch.qint8 else [128, 128]
elif qscheme == torch.per_channel_affine_float_qparams:
ref_scales = per_channel_affine_float_qparams_ref_scales[ch_axis]
ref_zero_points = [-1 * ref_min_vals[ch_axis][i] / ref_scales[i] for i in range(len(ref_scales))]
else:
ref_scales = per_channel_affine_ref_scales[ch_axis]
ref_zero_points = (
per_channel_affine_qint8_zp[ch_axis]
if qdtype is torch.qint8
else per_channel_affine_quint8_zp[ch_axis]
)
if reduce_range:
ref_scales = [s * 255 / 127 for s in ref_scales]
ref_zero_points = [math.floor(z / 2) for z in ref_zero_points]
self.assertEqual(qparams[0], torch.tensor(ref_scales, dtype=qparams[0].dtype), rtol=1e-5, atol=0.0001)
if qscheme == torch.per_channel_affine_float_qparams:
self.assertEqual(qparams[1], torch.tensor(ref_zero_points, dtype=qparams[1].dtype), rtol=1e-5, atol=1)
else:
self.assertEqual(qparams[1], torch.tensor(ref_zero_points, dtype=qparams[1].dtype))
# Test for serializability
state_dict = myobs.state_dict()
b = io.BytesIO()
torch.save(state_dict, b)
b.seek(0)
loaded_dict = torch.load(b)
for key in state_dict:
self.assertEqual(state_dict[key], loaded_dict[key])
loaded_obs = PerChannelMinMaxObserver(reduce_range=reduce_range, ch_axis=ch_axis, dtype=qdtype, qscheme=qscheme)
loaded_obs.load_state_dict(loaded_dict)
loaded_qparams = loaded_obs.calculate_qparams()
self.assertEqual(myobs.min_val, loaded_obs.min_val)
self.assertEqual(myobs.max_val, loaded_obs.max_val)
self.assertEqual(myobs.calculate_qparams(), loaded_obs.calculate_qparams())
def test_observer_scriptable(self):
obs_list = [MinMaxObserver(), MovingAverageMinMaxObserver()]
for obs in obs_list:
scripted = torch.jit.script(obs)
x = torch.rand(3, 4)
obs(x)
scripted(x)
self.assertEqual(obs.calculate_qparams(), scripted.calculate_qparams())
buf = io.BytesIO()
torch.jit.save(scripted, buf)
buf.seek(0)
loaded = torch.jit.load(buf)
self.assertEqual(obs.calculate_qparams(), loaded.calculate_qparams())
@unittest.skipIf(not TEST_MULTIGPU, "multi-GPU not supported")
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
@override_qengines
def test_state_dict_respects_device_affinity(self):
"""
Tests that loading from a state dict loads buffers to the correct
device.
"""
device_cpu = torch.device('cpu')
device_cuda = torch.device('cuda:0')
test_cases = itertools.product(
[device_cpu, device_cuda],
[device_cpu, device_cuda],
[MinMaxObserver, MovingAverageMinMaxObserver,
PerChannelMinMaxObserver,
MovingAveragePerChannelMinMaxObserver,
# TODO: enable this (separate PR)
# HistogramObserver,
PlaceholderObserver, RecordingObserver, NoopObserver,
FakeQuantize])
for device_source, device_target, obs_cls in test_cases:
# calibrated source model
model = obs_cls()
model.to(device_source)
model(torch.randn(4, 1, 4, 4, device=device_source))
# target model
model2 = obs_cls()
model2.to(device_target)
model2.load_state_dict(model.state_dict())
# verify that buffers stayed on model2's device
model_devices = {p.device for p in model2.parameters()} | \
{p.device for p in model2.buffers()}
# some observers do not have any buffers, so lessEqual instead of
# Equal
self.assertLessEqual(len(model_devices), 1)
if len(model_devices) == 1:
model_device = next(iter(model_devices))
self.assertEqual(model_device, device_target)
def test_histogram_observer_consistent_buffer_shape(self):
"""
Ensures that the buffer shapes do not change from uninitialized to
initialized states for HistogramObserver.
"""
obs = HistogramObserver()
min_shape_before = obs.min_val.shape
max_shape_before = obs.max_val.shape
for _ in range(2):
obs(torch.randn(4, 4, 4, 4))
self.assertEqual(min_shape_before, obs.min_val.shape)
self.assertEqual(max_shape_before, obs.max_val.shape)
def test_histogram_observer_ignore_infinity(self):
"""
Ensures that HistogramObserver doesn't record values of infinity
"""
obs = HistogramObserver()
obs2 = HistogramObserver()
x = torch.randn(4, 4, 4, 4)
obs(x * torch.inf)
obs(x)
obs2(x)
obs(x * torch.inf)
self.assertTrue(obs.min_val != -torch.inf and obs.max_val != torch.inf)
self.assertEqual(obs.histogram, obs2.histogram)
def test_histogram_observer_handle_close_to_infinity(self):
for sign in [-1, 1]:
obser = HistogramObserver.with_args(reduce_range=False)()
mask = torch.tensor([-3.4028234663852886 * 10**30, 0, 0, 0]) * sign
obser(mask)
obser(mask - sign)
scale, zp = obser.calculate_qparams()
input = torch.randn(1, 4)
ref_result = torch.softmax(input + mask, dim=1)
quant_mask = torch.quantize_per_tensor(mask, scale, zp, torch.quint8)
dequant_mask = quant_mask.dequantize()
result = torch.softmax(input + dequant_mask, dim=1)
self.assertEqual(result, ref_result)
def test_histogram_observer_handle_OOM_due_to_close_min_max_value(self):
obser = HistogramObserver.with_args(reduce_range=False)()
# close min and max value in the 1st forward() pass of observer tends
# to cause OOM in the following pass.
# This is due to the allocation of histogram tensor during _combine_histograms().
# With sanity check on the size of histogram tensor, we expect the histogram observer
# can still work by resetting the histogram
x1 = torch.tensor([0, 1e-9])
obser(x1)
x2 = torch.tensor([2.0, 3.0])
obser(x2)
def test_histogram_observer_save_load_state_dict(self):
"""
Smoke test on saving/loading state_dict
"""
obs1 = HistogramObserver()
obs1(torch.randn(4, 4, 4, 4))
obs2 = HistogramObserver()
obs2.load_state_dict(obs1.state_dict())
self.assertEqual(obs2.min_val.shape, torch.Size([]))
self.assertEqual(obs2.max_val.shape, torch.Size([]))
def test_save_load_state_dict_script(self):
"""
Tests that we can save and load state_dict for observers that are scripted
in a quantized model.
"""
obs_list = [MinMaxObserver, MovingAverageMinMaxObserver, HistogramObserver]
for obs in obs_list:
model = SingleLayerLinearModel().eval()
qconfig = QConfig(activation=default_observer, weight=obs)
qconfig_dict = {'' : qconfig}
scripted = torch.jit.script(model)
scripted = torch.ao.quantization.prepare_jit(scripted, qconfig_dict)
x = torch.rand(5, 5)
scripted(x)
obs_dict = torch.ao.quantization.get_observer_state_dict(scripted)
# Load stats
scripted_2 = torch.jit.script(model)
scripted_2 = torch.ao.quantization.prepare_jit(scripted_2, qconfig_dict)
torch.ao.quantization.load_observer_state_dict(scripted_2, obs_dict)
# Verify that state_dict matches exactly with original one.
self.assertEqual(scripted.state_dict(), scripted_2.state_dict())
@unittest.skipIf(not TEST_MULTIGPU, "multi-GPU not supported")
@unittest.skipIf(not TEST_CUDA, "CUDA unavailable")
def test_observer_qparams_respects_device_affinity(self):
"""
Ensure that the scale and zero_point returned by the observer
are on the same device as the input tensor.
"""
observerList = [MinMaxObserver(),
MovingAverageMinMaxObserver(),
PerChannelMinMaxObserver(),
MovingAveragePerChannelMinMaxObserver()]
for obs in observerList:
device = torch.device('cuda:1')
x = torch.randn(1, 2, device=device)
obs.to(device)
result = obs(x)
scale, zero_point = obs.calculate_qparams()
self.assertEqual(x.device, scale.device)
self.assertEqual(x.device, zero_point.device)
def test_zero_numel(self):
obs_list = [MinMaxObserver, MovingAverageMinMaxObserver,
PerChannelMinMaxObserver,
MovingAveragePerChannelMinMaxObserver, HistogramObserver,
FakeQuantize, FixedQParamsObserver]
for obs_cls in obs_list:
if obs_cls is FixedQParamsObserver:
obs = obs_cls(0.1, 0)
else:
obs = obs_cls()
x = torch.tensor([])
# verify no crash
x = obs(x)
def test_dynamic_quant_observer(self):
obs = MovingAverageMinMaxObserver(averaging_constant=1, is_dynamic=True)
x = torch.randn((3, 3))
obs(x)
params = obs.calculate_qparams()
for _ in range(20):
obs(10 * torch.randn((3, 3)))
self.assertNotEqual(params, obs.calculate_qparams())
obs(x)
self.assertEqual(params, obs.calculate_qparams())
def test_dynamic_quant_observer_matching_choose_qparams(self):
obs = MovingAverageMinMaxObserver(averaging_constant=1, is_dynamic=True)
for x in [torch.randn(3, 3), torch.rand(3, 3, 3), torch.randn(3, 3, 3, 3)]:
obs(x)
params = obs.calculate_qparams()
scale, zero_point = torch._choose_qparams_per_tensor(x)
self.assertEqual(scale, params[0])
self.assertEqual(zero_point, params[1])
def test_per_channel_observers_load_state_dict(self):
observer_list = [PerChannelMinMaxObserver, MovingAveragePerChannelMinMaxObserver]
for obs_cls in observer_list:
obs = obs_cls()
obs(torch.randn((32, 32)))
new_obs = obs_cls()
# make sure the state_dict can be loaded
new_obs.load_state_dict(obs.state_dict())
self.assertTrue(torch.equal(obs.min_val, new_obs.min_val))
self.assertTrue(torch.equal(obs.max_val, new_obs.max_val))
# HistogramObserver that works like it does on master
| TestObserver |
python | walkccc__LeetCode | solutions/3157. Find the Level of Tree with Minimum Sum/3157-2.py | {
"start": 0,
"end": 524
} | class ____:
# Similar to 1161. Maximum Level Sum of a Binary Tree
def minimumLevel(self, root: TreeNode | None) -> int:
# levelSums[i] := the sum of level (i + 1) (1-indexed)
levelSums = []
def dfs(root: TreeNode | None, level: int) -> None:
if not root:
return
if len(levelSums) == level:
levelSums.append(0)
levelSums[level] += root.val
dfs(root.left, level + 1)
dfs(root.right, level + 1)
dfs(root, 0)
return 1 + levelSums.index(min(levelSums))
| Solution |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 17516,
"end": 17752
} | class ____(permissions.BasePermission):
def has_permission(self, request, view):
raise PermissionDenied()
def has_object_permission(self, request, view, obj):
raise PermissionDenied()
| DenyAllUsingPermissionDenied |
python | astropy__astropy | astropy/units/tests/test_quantity_ufuncs.py | {
"start": 12345,
"end": 26116
} | class ____:
"""
Test other mathematical functions
"""
def test_multiply_scalar(self):
assert np.multiply(4.0 * u.m, 2.0 / u.s) == 8.0 * u.m / u.s
assert np.multiply(4.0 * u.m, 2.0) == 8.0 * u.m
assert np.multiply(4.0, 2.0 / u.s) == 8.0 / u.s
def test_multiply_array(self):
assert np.all(
np.multiply(np.arange(3.0) * u.m, 2.0 / u.s)
== np.arange(0, 6.0, 2.0) * u.m / u.s
)
def test_matmul(self):
q = np.arange(3.0) * u.m
r = np.matmul(q, q)
assert r == 5.0 * u.m**2
# less trivial case.
q1 = np.eye(3) * u.m
q2 = np.array(
[[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]],
[[0., 1., 0.],
[0., 0., 1.],
[1., 0., 0.]],
[[0., 0., 1.],
[1., 0., 0.],
[0., 1., 0.]]]
) / u.s # fmt: skip
r2 = np.matmul(q1, q2)
assert np.all(r2 == np.matmul(q1.value, q2.value) * q1.unit * q2.unit)
@pytest.mark.skipif(NUMPY_LT_2_0, reason="vecdot only added in numpy 2.0")
def test_vecdot(self):
q1 = np.array([1j, 2j, 3j]) * u.m
q2 = np.array([4j, 5j, 6j]) / u.s
o = np.vecdot(q1, q2)
assert o == (32.0 + 0j) * u.m / u.s
@pytest.mark.skipif(
NUMPY_LT_2_3, reason="np.matvec and np.vecmat are new in NumPy 2.3"
)
def test_matvec(self):
vec = np.arange(3) << u.s
mat = (
np.array(
[
[1.0, -1.0, 2.0],
[0.0, 3.0, -1.0],
[-1.0, -1.0, 1.0],
]
)
<< u.m
)
ref_matvec = (vec * mat).sum(-1)
res_matvec = np.matvec(mat, vec)
assert_array_equal(res_matvec, ref_matvec)
ref_vecmat = (vec * mat.T).sum(-1)
res_vecmat = np.vecmat(vec, mat)
assert_array_equal(res_vecmat, ref_vecmat)
@pytest.mark.parametrize("function", (np.divide, np.true_divide))
def test_divide_scalar(self, function):
assert function(4.0 * u.m, 2.0 * u.s) == function(4.0, 2.0) * u.m / u.s
assert function(4.0 * u.m, 2.0) == function(4.0, 2.0) * u.m
assert function(4.0, 2.0 * u.s) == function(4.0, 2.0) / u.s
@pytest.mark.parametrize("function", (np.divide, np.true_divide))
def test_divide_array(self, function):
assert np.all(
function(np.arange(3.0) * u.m, 2.0 * u.s)
== function(np.arange(3.0), 2.0) * u.m / u.s
)
def test_floor_divide_remainder_and_divmod(self):
inch = u.Unit(0.0254 * u.m)
dividend = np.array([1.0, 2.0, 3.0]) * u.m
divisor = np.array([3.0, 4.0, 5.0]) * inch
quotient = dividend // divisor
remainder = dividend % divisor
assert_allclose(quotient.value, [13.0, 19.0, 23.0])
assert quotient.unit == u.dimensionless_unscaled
assert_allclose(remainder.value, [0.0094, 0.0696, 0.079])
assert remainder.unit == dividend.unit
quotient2 = np.floor_divide(dividend, divisor)
remainder2 = np.remainder(dividend, divisor)
assert np.all(quotient2 == quotient)
assert np.all(remainder2 == remainder)
quotient3, remainder3 = divmod(dividend, divisor)
assert np.all(quotient3 == quotient)
assert np.all(remainder3 == remainder)
with pytest.raises(TypeError):
divmod(dividend, u.km)
with pytest.raises(TypeError):
dividend // u.km
with pytest.raises(TypeError):
dividend % u.km
quotient4, remainder4 = np.divmod(dividend, divisor)
assert np.all(quotient4 == quotient)
assert np.all(remainder4 == remainder)
with pytest.raises(TypeError):
np.divmod(dividend, u.km)
def test_sqrt_scalar(self):
assert np.sqrt(4.0 * u.m) == 2.0 * u.m**0.5
def test_sqrt_array(self):
assert np.all(
np.sqrt(np.array([1.0, 4.0, 9.0]) * u.m)
== np.array([1.0, 2.0, 3.0]) * u.m**0.5
)
def test_square_scalar(self):
assert np.square(4.0 * u.m) == 16.0 * u.m**2
def test_square_array(self):
assert np.all(
np.square(np.array([1.0, 2.0, 3.0]) * u.m)
== np.array([1.0, 4.0, 9.0]) * u.m**2
)
def test_reciprocal_scalar(self):
assert np.reciprocal(4.0 * u.m) == 0.25 / u.m
def test_reciprocal_array(self):
assert np.all(
np.reciprocal(np.array([1.0, 2.0, 4.0]) * u.m)
== np.array([1.0, 0.5, 0.25]) / u.m
)
def test_heaviside_scalar(self):
assert np.heaviside(0.0 * u.m, 0.5) == 0.5 * u.dimensionless_unscaled
assert (
np.heaviside(0.0 * u.s, 25 * u.percent) == 0.25 * u.dimensionless_unscaled
)
assert np.heaviside(2.0 * u.J, 0.25) == 1.0 * u.dimensionless_unscaled
def test_heaviside_array(self):
values = np.array([-1.0, 0.0, 0.0, +1.0])
halfway = np.array([0.75, 0.25, 0.75, 0.25]) * u.dimensionless_unscaled
assert np.all(
np.heaviside(values * u.m, halfway * u.dimensionless_unscaled)
== [0, 0.25, 0.75, +1.0] * u.dimensionless_unscaled
)
@pytest.mark.parametrize("function", (np.cbrt,))
def test_cbrt_scalar(self, function):
assert function(8.0 * u.m**3) == 2.0 * u.m
@pytest.mark.parametrize("function", (np.cbrt,))
def test_cbrt_array(self, function):
# Calculate cbrt on both sides since on Windows the cube root of 64
# does not exactly equal 4. See 4388.
values = np.array([1.0, 8.0, 64.0])
assert np.all(function(values * u.m**3) == function(values) * u.m)
def test_power_scalar(self):
assert np.power(4.0 * u.m, 2.0) == 16.0 * u.m**2
assert np.power(4.0, 200.0 * u.cm / u.m) == u.Quantity(
16.0, u.dimensionless_unscaled
)
# regression check on #1696
assert np.power(4.0 * u.m, 0.0) == 1.0 * u.dimensionless_unscaled
def test_power_scalar_filledarray(self):
result = np.power(4.0 * u.m, np.array([2.0, 2.0]))
assert np.all(result == 16.0 * u.m**2)
def test_power_scalar_strarray(self):
with pytest.raises(
expected_exception=ValueError,
match="could not convert string to float",
):
np.power(4.0 * u.m, np.array(["foo"]))
def test_power_array(self):
assert np.all(
np.power(np.array([1.0, 2.0, 3.0]) * u.m, 3.0)
== np.array([1.0, 8.0, 27.0]) * u.m**3
)
# regression check on #1696
assert np.all(
np.power(np.arange(4.0) * u.m, 0.0) == 1.0 * u.dimensionless_unscaled
)
def test_float_power_array(self):
assert np.all(
np.float_power(np.array([1.0, 2.0, 3.0]) * u.m, 3.0)
== np.array([1.0, 8.0, 27.0]) * u.m**3
)
# regression check on #1696
assert np.all(
np.float_power(np.arange(4.0) * u.m, 0.0) == 1.0 * u.dimensionless_unscaled
)
def test_power_array_array(self):
with pytest.raises(ValueError):
np.power(4.0 * u.m, [2.0, 4.0])
def test_power_array_array2(self):
with pytest.raises(ValueError):
np.power([2.0, 4.0] * u.m, [2.0, 4.0])
def test_power_array_array3(self):
# Identical unit fractions are converted automatically to dimensionless
# and should be allowed as base for np.power: #4764
q = [2.0, 4.0] * u.m / u.m
powers = [2.0, 4.0]
res = np.power(q, powers)
assert np.all(res.value == q.value**powers)
assert res.unit == u.dimensionless_unscaled
# The same holds for unit fractions that are scaled dimensionless.
q2 = [2.0, 4.0] * u.m / u.cm
# Test also against different types of exponent
for cls in (list, tuple, np.array, np.ma.array, u.Quantity):
res2 = np.power(q2, cls(powers))
assert np.all(res2.value == q2.to_value(1) ** powers)
assert res2.unit == u.dimensionless_unscaled
# Though for single powers, we keep the composite unit.
res3 = q2**2
assert np.all(res3.value == q2.value**2)
assert res3.unit == q2.unit**2
assert np.all(res3 == q2 ** [2, 2])
def test_power_invalid(self):
with pytest.raises(TypeError, match="raise something to a dimensionless"):
np.power(3.0, 4.0 * u.m)
def test_copysign_scalar(self):
assert np.copysign(3 * u.m, 1.0) == 3.0 * u.m
assert np.copysign(3 * u.m, 1.0 * u.s) == 3.0 * u.m
assert np.copysign(3 * u.m, -1.0) == -3.0 * u.m
assert np.copysign(3 * u.m, -1.0 * u.s) == -3.0 * u.m
def test_copysign_array(self):
assert np.all(
np.copysign(np.array([1.0, 2.0, 3.0]) * u.s, -1.0)
== -np.array([1.0, 2.0, 3.0]) * u.s
)
assert np.all(
np.copysign(np.array([1.0, 2.0, 3.0]) * u.s, -1.0 * u.m)
== -np.array([1.0, 2.0, 3.0]) * u.s
)
assert np.all(
np.copysign(
np.array([1.0, 2.0, 3.0]) * u.s, np.array([-2.0, 2.0, -4.0]) * u.m
)
== np.array([-1.0, 2.0, -3.0]) * u.s
)
q = np.copysign(np.array([1.0, 2.0, 3.0]), -3 * u.m)
assert np.all(q == np.array([-1.0, -2.0, -3.0]))
assert not isinstance(q, u.Quantity)
def test_ldexp_scalar(self):
assert np.ldexp(4.0 * u.m, 2) == 16.0 * u.m
def test_ldexp_array(self):
assert np.all(
np.ldexp(np.array([1.0, 2.0, 3.0]) * u.m, [3, 2, 1])
== np.array([8.0, 8.0, 6.0]) * u.m
)
def test_ldexp_invalid(self):
with pytest.raises(TypeError):
np.ldexp(3.0 * u.m, 4.0)
with pytest.raises(TypeError):
np.ldexp(3.0, u.Quantity(4, u.m, dtype=int))
@pytest.mark.parametrize(
"function", (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)
)
def test_exp_scalar(self, function):
q = function(3.0 * u.m / (6.0 * u.m))
assert q.unit == u.dimensionless_unscaled
assert q.value == function(0.5)
@pytest.mark.parametrize(
"function", (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)
)
def test_exp_array(self, function):
q = function(np.array([2.0, 3.0, 6.0]) * u.m / (6.0 * u.m))
assert q.unit == u.dimensionless_unscaled
assert np.all(q.value == function(np.array([1.0 / 3.0, 1.0 / 2.0, 1.0])))
# should also work on quantities that can be made dimensionless
q2 = function(np.array([2.0, 3.0, 6.0]) * u.m / (6.0 * u.cm))
assert q2.unit == u.dimensionless_unscaled
assert_allclose(q2.value, function(np.array([100.0 / 3.0, 100.0 / 2.0, 100.0])))
@pytest.mark.parametrize(
"function", (np.exp, np.expm1, np.exp2, np.log, np.log2, np.log10, np.log1p)
)
def test_exp_invalid_units(self, function):
# Can't use exp() with non-dimensionless quantities
with pytest.raises(
TypeError,
match=(
f"Can only apply '{function.__name__}' function "
"to dimensionless quantities"
),
):
function(3.0 * u.m / u.s)
def test_modf_scalar(self):
q = np.modf(9.0 * u.m / (600.0 * u.cm))
assert q == (0.5 * u.dimensionless_unscaled, 1.0 * u.dimensionless_unscaled)
def test_modf_array(self):
v = np.arange(10.0) * u.m / (500.0 * u.cm)
q = np.modf(v)
n = np.modf(v.to_value(u.dimensionless_unscaled))
assert q[0].unit == u.dimensionless_unscaled
assert q[1].unit == u.dimensionless_unscaled
assert all(q[0].value == n[0])
assert all(q[1].value == n[1])
def test_frexp_scalar(self):
q = np.frexp(3.0 * u.m / (6.0 * u.m))
assert q == (np.array(0.5), np.array(0.0))
def test_frexp_array(self):
q = np.frexp(np.array([2.0, 3.0, 6.0]) * u.m / (6.0 * u.m))
assert all(
(_q0, _q1) == np.frexp(_d)
for _q0, _q1, _d in zip(q[0], q[1], [1.0 / 3.0, 1.0 / 2.0, 1.0])
)
def test_frexp_invalid_units(self):
# Can't use prod() with non-dimensionless quantities
with pytest.raises(
TypeError,
match=(
"Can only apply 'frexp' function to unscaled dimensionless quantities"
),
):
np.frexp(3.0 * u.m / u.s)
# also does not work on quantities that can be made dimensionless
with pytest.raises(
TypeError,
match=(
"Can only apply 'frexp' function to unscaled dimensionless quantities"
),
):
np.frexp(np.array([2.0, 3.0, 6.0]) * u.m / (6.0 * u.cm))
@pytest.mark.parametrize("function", (np.logaddexp, np.logaddexp2))
def test_dimensionless_twoarg_array(self, function):
q = function(np.array([2.0, 3.0, 6.0]) * u.m / (6.0 * u.cm), 1.0)
assert q.unit == u.dimensionless_unscaled
assert_allclose(
q.value, function(np.array([100.0 / 3.0, 100.0 / 2.0, 100.0]), 1.0)
)
@pytest.mark.parametrize("function", (np.logaddexp, np.logaddexp2))
def test_dimensionless_twoarg_invalid_units(self, function):
with pytest.raises(
TypeError,
match=(
f"Can only apply '{function.__name__}' function to dimensionless"
" quantities"
),
):
function(1.0 * u.km / u.s, 3.0 * u.m / u.s)
| TestQuantityMathFuncs |
python | PyCQA__pylint | doc/data/messages/i/inconsistent-mro/bad.py | {
"start": 20,
"end": 43
} | class ____(A):
pass
| B |
python | modin-project__modin | modin/core/dataframe/base/interchange/dataframe_protocol/utils.py | {
"start": 1721,
"end": 2322
} | class ____(enum.IntEnum): # noqa PR01
"""
Integer enum for null type representation.
Attributes
----------
NON_NULLABLE : int
Non-nullable column.
USE_NAN : int
Use explicit float NaN value.
USE_SENTINEL : int
Sentinel value besides NaN.
USE_BITMASK : int
The bit is set/unset representing a null on a certain position.
USE_BYTEMASK : int
The byte is set/unset representing a null on a certain position.
"""
NON_NULLABLE = 0
USE_NAN = 1
USE_SENTINEL = 2
USE_BITMASK = 3
USE_BYTEMASK = 4
| ColumnNullType |
python | bokeh__bokeh | src/bokeh/core/property/factors.py | {
"start": 1580,
"end": 1911
} | class ____(SingleParameterizedProperty[FactorType]):
""" Represents a single categorical factor. """
def __init__(self, default: Init[FactorType] = Intrinsic, *, help: str | None = None) -> None:
type_param = Either(L1Factor, L2Factor, L3Factor)
super().__init__(type_param, default=default, help=help)
| Factor |
python | kamyu104__LeetCode-Solutions | Python/find-maximum-non-decreasing-array-length.py | {
"start": 1462,
"end": 2090
} | class ____(object):
def findMaximumLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = prefix = left = 0
stk = [(0, 0, 0)]
for right in xrange(len(nums)):
prefix += nums[right]
left = bisect.bisect_left(stk, (prefix+1, 0, 0))-1
last, dp = prefix-stk[left][1], stk[left][2]+1
while stk and stk[-1][0] >= last+prefix:
stk.pop()
stk.append((last+prefix, prefix, dp))
return dp
# Time: O(nlogn)
# Space: O(n)
import bisect
# dp, greedy, prefix sum, binary search
| Solution3 |
python | huggingface__transformers | src/transformers/models/sam2_video/video_processing_sam2_video.py | {
"start": 1014,
"end": 4928
} | class ____(BaseVideoProcessor):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_DEFAULT_MEAN
image_std = IMAGENET_DEFAULT_STD
size = {"height": 1024, "width": 1024}
do_resize = True
do_rescale = True
do_normalize = True
do_convert_rgb = True
model_input_names = ["pixel_values"]
def _preprocess(
self,
videos: list["torch.Tensor"],
size: SizeDict,
return_tensors: Optional[Union[str, TensorType]],
**kwargs,
) -> BatchFeature:
original_sizes = [video.shape[-2:] for video in videos]
reshaped_input_sizes = [(size.height, size.width) for _ in range(len(videos))]
batch_feature = super()._preprocess(videos, size=size, return_tensors=return_tensors, **kwargs)
batch_feature = BatchFeature(
data={
"original_sizes": original_sizes,
"reshaped_input_sizes": reshaped_input_sizes,
**batch_feature.data,
},
tensor_type=return_tensors,
)
return batch_feature
def post_process_masks(
self, masks, original_sizes, reshaped_input_sizes, mask_threshold=0.0, binarize=True, pad_size=None
):
"""
Remove padding and upscale masks to the original image size.
Args:
masks (`Union[List[torch.Tensor], List[np.ndarray]]`):
Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
The original sizes of each image before it was resized to the model's expected input shape, in (height,
width) format.
reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
mask_threshold (`float`, *optional*, defaults to 0.0):
The threshold to use for binarizing the masks.
binarize (`bool`, *optional*, defaults to `True`):
Whether to binarize the masks.
pad_size (`int`, *optional*, defaults to `self.pad_size`):
The target size the images were padded to before being passed to the model. If None, the target size is
assumed to be the processor's `pad_size`.
Returns:
(`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
is given by original_size.
"""
pad_size = self.size if pad_size is None else pad_size
target_image_size = (pad_size["height"], pad_size["width"])
if isinstance(original_sizes, (torch.Tensor, np.ndarray)):
original_sizes = original_sizes.tolist()
if isinstance(reshaped_input_sizes, (torch.Tensor, np.ndarray)):
reshaped_input_sizes = reshaped_input_sizes.tolist()
output_masks = []
for i, original_size in enumerate(original_sizes):
if isinstance(masks[i], np.ndarray):
masks[i] = torch.from_numpy(masks[i])
elif not isinstance(masks[i], torch.Tensor):
raise TypeError("Input masks should be a list of `torch.tensors` or a list of `np.ndarray`")
interpolated_mask = F.interpolate(masks[i], target_image_size, mode="bilinear", align_corners=False)
interpolated_mask = interpolated_mask[..., : reshaped_input_sizes[i][0], : reshaped_input_sizes[i][1]]
interpolated_mask = F.interpolate(interpolated_mask, original_size, mode="bilinear", align_corners=False)
if binarize:
interpolated_mask = interpolated_mask > mask_threshold
output_masks.append(interpolated_mask)
return output_masks
__all__ = ["Sam2VideoVideoProcessor"]
| Sam2VideoVideoProcessor |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/saved_model_utils.py | {
"start": 1255,
"end": 3473
} | class ____(trackable.Trackable):
"""Trackable class for captured constants."""
__slots__ = ("capture", "function", "_exported_tensor")
def __init__(self, capture, function):
self.capture = capture
self.function = function
self._exported_tensor = None
def _export_to_saved_model_graph(self, tensor_map, **unused_kwargs):
capture_constant_value = tensor_util.constant_value(self.capture)
if capture_constant_value is None:
raise ValueError(
f"Unable to save function {self.function.name} because it "
f"captures graph tensor {self.capture} from a parent function which "
"cannot be converted to a constant with `tf.get_static_value`.")
if numpy.prod(self.capture.shape.as_list()) > 1 and numpy.all(
capture_constant_value == capture_constant_value.flat[0]):
# For the common case of a constant array filled with the same
# value, rebuild the constant op specifically with the shape arg,
# since otherwise the whole array is written into the node def,
# causing performance and graph proto size issues (protos cannot be
# bigger than 2GB).
copied_tensor = constant_op.constant(
capture_constant_value.flat[0],
dtype=self.capture.dtype,
shape=self.capture.shape)
else:
copied_tensor = constant_op.constant(capture_constant_value)
tensor_map[self.capture] = copied_tensor
self._exported_tensor = copied_tensor
return [self.capture]
def _serialize_to_proto(self, object_proto=None, **kwargs):
object_proto.constant.operation = self._exported_tensor.op.name
@classmethod
def _deserialize_from_proto(cls, object_proto, operation_attributes,
**kwargs):
tensor_proto = (
operation_attributes[object_proto.constant.operation]["value"].tensor)
ndarray = tensor_util.MakeNdarray(tensor_proto)
if dtypes.as_dtype(tensor_proto.dtype) == dtypes.string:
with ops.device("CPU"):
# String operations should be done on the CPU.
imported_constant = constant_op.constant(ndarray)
else:
imported_constant = constant_op.constant(ndarray)
return imported_constant
| TrackableConstant |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 1504,
"end": 1646
} | class ____(ShowFieldContent, PolymorphicModel):
field1 = models.CharField(max_length=30)
m2m = models.ManyToManyField("self")
| ModelShow2 |
python | scikit-learn__scikit-learn | sklearn/model_selection/_split.py | {
"start": 31817,
"end": 41198
} | class ____(GroupsConsumerMixin, _BaseKFold):
"""Class-wise stratified K-Fold iterator variant with non-overlapping groups.
This cross-validation object is a variation of :class:`StratifiedKFold` that
attempts to return stratified folds with non-overlapping groups. The folds are made
by preserving the percentage of samples for each class in `y` in a binary or
multiclass classification setting.
Each group will appear exactly once in the test set across all folds (the
number of distinct groups has to be at least equal to the number of folds).
The difference between :class:`GroupKFold`
and `StratifiedGroupKFold` is that
the former attempts to create balanced folds such that the number of
distinct groups is approximately the same in each fold, whereas
`StratifiedGroupKFold` attempts to create folds which preserve the
percentage of samples from each class as much as possible given the
constraint of non-overlapping groups between splits.
Read more in the :ref:`User Guide <stratified_group_k_fold>`.
For visualisation of cross-validation behaviour and
comparison between common scikit-learn split methods
refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py`
.. note::
Stratification on the class label solves an engineering problem rather
than a statistical one. See :ref:`stratification` for more details.
Parameters
----------
n_splits : int, default=5
Number of folds. Must be at least 2.
shuffle : bool, default=False
Whether to shuffle each class's samples before splitting into batches.
Note that the samples within each split will not be shuffled.
This implementation can only shuffle groups that have approximately the
same `y` class distribution, no global shuffle will be performed.
random_state : int or RandomState instance, default=None
When `shuffle` is True, `random_state` affects the ordering of the
indices, which controls the randomness of each fold for each class.
Otherwise, leave `random_state` as `None`.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Examples
--------
>>> import numpy as np
>>> from sklearn.model_selection import StratifiedGroupKFold
>>> X = np.ones((17, 2))
>>> y = np.array([0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> groups = np.array([1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5, 6, 6, 7, 8, 8])
>>> sgkf = StratifiedGroupKFold(n_splits=3)
>>> sgkf.get_n_splits()
3
>>> print(sgkf)
StratifiedGroupKFold(n_splits=3, random_state=None, shuffle=False)
>>> for i, (train_index, test_index) in enumerate(sgkf.split(X, y, groups)):
... print(f"Fold {i}:")
... print(f" Train: index={train_index}")
... print(f" group={groups[train_index]}")
... print(f" Test: index={test_index}")
... print(f" group={groups[test_index]}")
Fold 0:
Train: index=[ 0 1 2 3 7 8 9 10 11 15 16]
group=[1 1 2 2 4 5 5 5 5 8 8]
Test: index=[ 4 5 6 12 13 14]
group=[3 3 3 6 6 7]
Fold 1:
Train: index=[ 4 5 6 7 8 9 10 11 12 13 14]
group=[3 3 3 4 5 5 5 5 6 6 7]
Test: index=[ 0 1 2 3 15 16]
group=[1 1 2 2 8 8]
Fold 2:
Train: index=[ 0 1 2 3 4 5 6 12 13 14 15 16]
group=[1 1 2 2 3 3 3 6 6 7 8 8]
Test: index=[ 7 8 9 10 11]
group=[4 5 5 5 5]
Notes
-----
The implementation is designed to:
* Mimic the behavior of :class:`StratifiedKFold` as much as possible for trivial
groups (e.g. when each group contains only one sample).
* Be invariant to class label: relabelling ``y = ["Happy", "Sad"]`` to
``y = [1, 0]`` should not change the indices generated.
* Stratify based on samples as much as possible while keeping
non-overlapping groups constraint. That means that in some cases when
there is a small number of groups containing a large number of samples
the stratification will not be possible and the behavior will be close
to :class:`GroupKFold`.
See also
--------
StratifiedKFold: Takes class information into account to build folds which
retain class distributions (for binary or multiclass classification
tasks).
GroupKFold: K-fold iterator variant with non-overlapping groups.
"""
def __init__(self, n_splits=5, shuffle=False, random_state=None):
super().__init__(n_splits=n_splits, shuffle=shuffle, random_state=random_state)
def _iter_test_indices(self, X, y, groups):
# Implementation is based on this kaggle kernel:
# https://www.kaggle.com/jakubwasikowski/stratified-group-k-fold-cross-validation
# and is a subject to Apache 2.0 License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0
# Changelist:
# - Refactored function to a class following scikit-learn KFold
# interface.
# - Added heuristic for assigning group to the least populated fold in
# cases when all other criteria are equal
# - Swtch from using python ``Counter`` to ``np.unique`` to get class
# distribution
# - Added scikit-learn checks for input: checking that target is binary
# or multiclass, checking passed random state, checking that number
# of splits is less than number of members in each class, checking
# that least populated class has more members than there are splits.
rng = check_random_state(self.random_state)
y = np.asarray(y)
type_of_target_y = type_of_target(y)
allowed_target_types = ("binary", "multiclass")
if type_of_target_y not in allowed_target_types:
raise ValueError(
"Supported target types are: {}. Got {!r} instead.".format(
allowed_target_types, type_of_target_y
)
)
y = column_or_1d(y)
_, y_inv, y_cnt = np.unique(y, return_inverse=True, return_counts=True)
if np.all(self.n_splits > y_cnt):
raise ValueError(
"n_splits=%d cannot be greater than the"
" number of members in each class." % (self.n_splits)
)
n_smallest_class = np.min(y_cnt)
if self.n_splits > n_smallest_class:
warnings.warn(
"The least populated class in y has only %d"
" members, which is less than n_splits=%d."
% (n_smallest_class, self.n_splits),
UserWarning,
)
n_classes = len(y_cnt)
_, groups_inv, groups_cnt = np.unique(
groups, return_inverse=True, return_counts=True
)
y_counts_per_group = np.zeros((len(groups_cnt), n_classes))
for class_idx, group_idx in zip(y_inv, groups_inv):
y_counts_per_group[group_idx, class_idx] += 1
y_counts_per_fold = np.zeros((self.n_splits, n_classes))
groups_per_fold = defaultdict(set)
if self.shuffle:
perm = np.arange(len(groups_cnt))
rng.shuffle(perm)
y_counts_per_group = y_counts_per_group[perm]
inv_perm = np.empty_like(perm)
inv_perm[perm] = np.arange(perm.size)
groups_inv = inv_perm[groups_inv]
# Stable sort to keep shuffled order for groups with the same
# class distribution variance
sorted_groups_idx = np.argsort(
-np.std(y_counts_per_group, axis=1), kind="mergesort"
)
for group_idx in sorted_groups_idx:
group_y_counts = y_counts_per_group[group_idx]
best_fold = self._find_best_fold(
y_counts_per_fold=y_counts_per_fold,
y_cnt=y_cnt,
group_y_counts=group_y_counts,
)
y_counts_per_fold[best_fold] += group_y_counts
groups_per_fold[best_fold].add(group_idx)
for i in range(self.n_splits):
test_indices = [
idx
for idx, group_idx in enumerate(groups_inv)
if group_idx in groups_per_fold[i]
]
yield test_indices
def _find_best_fold(self, y_counts_per_fold, y_cnt, group_y_counts):
best_fold = None
min_eval = np.inf
min_samples_in_fold = np.inf
for i in range(self.n_splits):
y_counts_per_fold[i] += group_y_counts
# Summarise the distribution over classes in each proposed fold
std_per_class = np.std(y_counts_per_fold / y_cnt.reshape(1, -1), axis=0)
y_counts_per_fold[i] -= group_y_counts
fold_eval = np.mean(std_per_class)
samples_in_fold = np.sum(y_counts_per_fold[i])
is_current_fold_better = fold_eval < min_eval or (
np.isclose(fold_eval, min_eval)
and samples_in_fold < min_samples_in_fold
)
if is_current_fold_better:
min_eval = fold_eval
min_samples_in_fold = samples_in_fold
best_fold = i
return best_fold
| StratifiedGroupKFold |
python | huggingface__transformers | src/transformers/models/marian/tokenization_marian.py | {
"start": 1298,
"end": 18119
} | class ____(PreTrainedTokenizer):
r"""
Construct a Marian tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
this superclass for more information regarding those methods.
Args:
source_spm (`str`):
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
contains the vocabulary for the source language.
target_spm (`str`):
[SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
contains the vocabulary for the target language.
source_lang (`str`, *optional*):
A string representing the source language.
target_lang (`str`, *optional*):
A string representing the target language.
unk_token (`str`, *optional*, defaults to `"<unk>"`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
eos_token (`str`, *optional*, defaults to `"</s>"`):
The end of sequence token.
pad_token (`str`, *optional*, defaults to `"<pad>"`):
The token used for padding, for example when batching sequences of different lengths.
model_max_length (`int`, *optional*, defaults to 512):
The maximum sentence length the model accepts.
additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
Additional special tokens used by the tokenizer.
sp_model_kwargs (`dict`, *optional*):
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
to set:
- `enable_sampling`: Enable subword regularization.
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
- `nbest_size = {0,1}`: No sampling is performed.
- `nbest_size > 1`: samples from the nbest_size results.
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
using forward-filtering-and-backward-sampling algorithm.
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
BPE-dropout.
Examples:
```python
>>> from transformers import MarianForCausalLM, MarianTokenizer
>>> model = MarianForCausalLM.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
>>> src_texts = ["I am a small frog.", "Tom asked his teacher for advice."]
>>> tgt_texts = ["Ich bin ein kleiner Frosch.", "Tom bat seinen Lehrer um Rat."] # optional
>>> inputs = tokenizer(src_texts, text_target=tgt_texts, return_tensors="pt", padding=True)
>>> outputs = model(**inputs) # should work
```"""
vocab_files_names = VOCAB_FILES_NAMES
model_input_names = ["input_ids", "attention_mask"]
def __init__(
self,
source_spm,
target_spm,
vocab,
target_vocab_file=None,
source_lang=None,
target_lang=None,
unk_token="<unk>",
eos_token="</s>",
pad_token="<pad>",
model_max_length=512,
sp_model_kwargs: Optional[dict[str, Any]] = None,
separate_vocabs=False,
**kwargs,
) -> None:
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
assert Path(source_spm).exists(), f"cannot find spm source {source_spm}"
self.separate_vocabs = separate_vocabs
self.encoder = load_json(vocab)
if str(unk_token) not in self.encoder:
raise KeyError("<unk> token must be in the vocab")
if separate_vocabs:
self.target_encoder = load_json(target_vocab_file)
self.decoder = {v: k for k, v in self.target_encoder.items()}
self.supported_language_codes = []
else:
self.decoder = {v: k for k, v in self.encoder.items()}
self.supported_language_codes: list = [k for k in self.encoder if k.startswith(">>") and k.endswith("<<")]
self.source_lang = source_lang
self.target_lang = target_lang
self.spm_files = [source_spm, target_spm]
# load SentencePiece model for pre-processing
self.spm_source = load_spm(source_spm, self.sp_model_kwargs)
self.spm_target = load_spm(target_spm, self.sp_model_kwargs)
self.current_spm = self.spm_source
self.current_encoder = self.encoder
# Multilingual target side: default to using first supported language code.
self._setup_normalizer()
self._decode_use_source_tokenizer = False
super().__init__(
# bos_token=bos_token, unused. Start decoding with config.decoder_start_token_id
source_lang=source_lang,
target_lang=target_lang,
unk_token=unk_token,
eos_token=eos_token,
pad_token=pad_token,
model_max_length=model_max_length,
sp_model_kwargs=self.sp_model_kwargs,
target_vocab_file=target_vocab_file,
separate_vocabs=separate_vocabs,
**kwargs,
)
def _setup_normalizer(self):
try:
from sacremoses import MosesPunctNormalizer
self.punc_normalizer = MosesPunctNormalizer(self.source_lang).normalize
except (ImportError, FileNotFoundError):
warnings.warn("Recommended: pip install sacremoses.")
self.punc_normalizer = lambda x: x
def normalize(self, x: str) -> str:
"""Cover moses empty string edge case. They return empty list for '' input!"""
return self.punc_normalizer(x) if x else ""
def _convert_token_to_id(self, token):
if token in self.current_encoder:
return self.current_encoder[token]
# The Marian vocab is not aligned with the SentencePiece IDs, so falling back to raw
# SentencePiece indices would map to unrelated tokens. Treat such pieces as unknown.
return self.current_encoder[self.unk_token]
def remove_language_code(self, text: str):
"""Remove language codes like >>fr<< before sentencepiece"""
code = []
if text.startswith(">>") and (end_loc := text.find("<<")) != -1:
code.append(text[: end_loc + 2])
text = text[end_loc + 2 :]
return code, text
def _tokenize(self, text: str) -> list[str]:
code, text = self.remove_language_code(text)
pieces = self.current_spm.encode(text, out_type=str)
return code + pieces
def _convert_id_to_token(self, index: int) -> str:
"""Converts an index (integer) in a token (str) using the decoder."""
if index in self.decoder:
return self.decoder[index]
# Fall back to SPM model for IDs not in external vocab
spm_model = self.spm_source if self._decode_use_source_tokenizer else self.spm_target
piece = spm_model.IdToPiece(index)
return piece if piece else self.unk_token
def batch_decode(self, sequences, **kwargs):
"""
Convert a list of lists of token ids into a list of strings by calling decode.
Args:
sequences (`Union[list[int], list[list[int]], np.ndarray, torch.Tensor]`):
List of tokenized input ids. Can be obtained using the `__call__` method.
skip_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not to remove special tokens in the decoding.
clean_up_tokenization_spaces (`bool`, *optional*):
Whether or not to clean up the tokenization spaces. If `None`, will default to
`self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
use_source_tokenizer (`bool`, *optional*, defaults to `False`):
Whether or not to use the source tokenizer to decode sequences (only applicable in sequence-to-sequence
problems).
kwargs (additional keyword arguments, *optional*):
Will be passed to the underlying model specific decode method.
Returns:
`list[str]`: The list of decoded sentences.
"""
return super().batch_decode(sequences, **kwargs)
def decode(self, token_ids, **kwargs):
"""
Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
tokens and clean up tokenization spaces.
Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
Args:
token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
List of tokenized input ids. Can be obtained using the `__call__` method.
skip_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not to remove special tokens in the decoding.
clean_up_tokenization_spaces (`bool`, *optional*):
Whether or not to clean up the tokenization spaces. If `None`, will default to
`self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
use_source_tokenizer (`bool`, *optional*, defaults to `False`):
Whether or not to use the source tokenizer to decode sequences (only applicable in sequence-to-sequence
problems).
kwargs (additional keyword arguments, *optional*):
Will be passed to the underlying model specific decode method.
Returns:
`str`: The decoded sentence.
"""
return super().decode(token_ids, **kwargs)
def _decode(
self,
token_ids,
skip_special_tokens: bool = False,
clean_up_tokenization_spaces: Optional[bool] = None,
**kwargs,
) -> str:
"""Internal decode method that handles use_source_tokenizer parameter."""
default_use_source = not self.separate_vocabs
self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", default_use_source)
return super()._decode(
token_ids=token_ids,
skip_special_tokens=skip_special_tokens,
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
**kwargs,
)
def convert_tokens_to_string(self, tokens: list[str]) -> str:
"""Uses source spm if _decode_use_source_tokenizer is True, and target spm otherwise"""
sp_model = self.spm_source if self._decode_use_source_tokenizer else self.spm_target
current_sub_tokens = []
out_string = ""
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += sp_model.decode_pieces(current_sub_tokens) + token + " "
current_sub_tokens = []
else:
current_sub_tokens.append(token)
out_string += sp_model.decode_pieces(current_sub_tokens)
out_string = out_string.replace(SPIECE_UNDERLINE, " ")
return out_string.strip()
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]:
"""Build model inputs from a sequence by appending eos_token_id."""
if token_ids_1 is None:
return token_ids_0 + [self.eos_token_id]
# We don't expect to process pairs, but leave the pair logic for API consistency
return token_ids_0 + token_ids_1 + [self.eos_token_id]
def _switch_to_input_mode(self):
self.current_spm = self.spm_source
self.current_encoder = self.encoder
def _switch_to_target_mode(self):
self.current_spm = self.spm_target
if self.separate_vocabs:
self.current_encoder = self.target_encoder
@property
def vocab_size(self) -> int:
return len(self.encoder)
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
if not os.path.isdir(save_directory):
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
return
saved_files = []
if self.separate_vocabs:
out_src_vocab_file = os.path.join(
save_directory,
(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"],
)
out_tgt_vocab_file = os.path.join(
save_directory,
(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["target_vocab_file"],
)
save_json(self.encoder, out_src_vocab_file)
save_json(self.target_encoder, out_tgt_vocab_file)
saved_files.append(out_src_vocab_file)
saved_files.append(out_tgt_vocab_file)
else:
out_vocab_file = os.path.join(
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"]
)
save_json(self.encoder, out_vocab_file)
saved_files.append(out_vocab_file)
for spm_save_filename, spm_orig_path, spm_model in zip(
[VOCAB_FILES_NAMES["source_spm"], VOCAB_FILES_NAMES["target_spm"]],
self.spm_files,
[self.spm_source, self.spm_target],
):
spm_save_path = os.path.join(
save_directory, (filename_prefix + "-" if filename_prefix else "") + spm_save_filename
)
if os.path.abspath(spm_orig_path) != os.path.abspath(spm_save_path) and os.path.isfile(spm_orig_path):
copyfile(spm_orig_path, spm_save_path)
saved_files.append(spm_save_path)
elif not os.path.isfile(spm_orig_path):
with open(spm_save_path, "wb") as fi:
content_spiece_model = spm_model.serialized_model_proto()
fi.write(content_spiece_model)
saved_files.append(spm_save_path)
return tuple(saved_files)
def get_vocab(self) -> dict:
return self.get_src_vocab()
def get_src_vocab(self):
return dict(self.encoder, **self.added_tokens_encoder)
def get_tgt_vocab(self):
return dict(self.target_encoder, **self.added_tokens_decoder)
def __getstate__(self) -> dict:
state = self.__dict__.copy()
state.update(
dict.fromkeys(["spm_source", "spm_target", "current_spm", "punc_normalizer", "target_vocab_file"])
)
return state
def __setstate__(self, d: dict) -> None:
self.__dict__ = d
# for backward compatibility
if not hasattr(self, "sp_model_kwargs"):
self.sp_model_kwargs = {}
if not hasattr(self, "_decode_use_source_tokenizer"):
self._decode_use_source_tokenizer = False
self.spm_source, self.spm_target = (load_spm(f, self.sp_model_kwargs) for f in self.spm_files)
self.current_spm = self.spm_source
self._setup_normalizer()
def num_special_tokens_to_add(self, *args, **kwargs):
"""Just EOS"""
return 1
def _special_token_mask(self, seq):
all_special_ids = set(self.all_special_ids) # call it once instead of inside list comp
all_special_ids.remove(self.unk_token_id) # <unk> is only sometimes special
return [1 if x in all_special_ids else 0 for x in seq]
def get_special_tokens_mask(
self, token_ids_0: list, token_ids_1: Optional[list] = None, already_has_special_tokens: bool = False
) -> list[int]:
"""Get list where entries are [1] if a token is [eos] or [pad] else 0."""
if already_has_special_tokens:
return self._special_token_mask(token_ids_0)
elif token_ids_1 is None:
return self._special_token_mask(token_ids_0) + [1]
else:
return self._special_token_mask(token_ids_0 + token_ids_1) + [1]
def load_spm(path: str, sp_model_kwargs: dict[str, Any]) -> sentencepiece.SentencePieceProcessor:
spm = sentencepiece.SentencePieceProcessor(**sp_model_kwargs)
spm.Load(path)
return spm
def save_json(data, path: str) -> None:
with open(path, "w") as f:
json.dump(data, f, indent=2)
def load_json(path: str) -> Union[dict, list]:
with open(path, "r") as f:
return json.load(f)
__all__ = ["MarianTokenizer"]
| MarianTokenizer |
python | huggingface__transformers | src/transformers/models/longformer/modeling_longformer.py | {
"start": 57813,
"end": 59233
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_id=0):
super().__init__()
self.attention = LongformerAttention(config, layer_id)
self.intermediate = LongformerIntermediate(config)
self.output = LongformerOutput(config)
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
def forward(
self,
hidden_states,
attention_mask=None,
is_index_masked=None,
is_index_global_attn=None,
is_global_attn=None,
output_attentions=False,
):
self_attn_outputs = self.attention(
hidden_states,
attention_mask=attention_mask,
is_index_masked=is_index_masked,
is_index_global_attn=is_index_global_attn,
is_global_attn=is_global_attn,
output_attentions=output_attentions,
)
attn_output = self_attn_outputs[0]
outputs = self_attn_outputs[1:]
layer_output = apply_chunking_to_forward(
self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attn_output
)
outputs = (layer_output,) + outputs
return outputs
def ff_chunk(self, attn_output):
intermediate_output = self.intermediate(attn_output)
layer_output = self.output(intermediate_output, attn_output)
return layer_output
| LongformerLayer |
python | huggingface__transformers | tests/models/marian/test_modeling_marian.py | {
"start": 8062,
"end": 15190
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (MarianModel, MarianMTModel) if is_torch_available() else ()
pipeline_model_mapping = (
{
"feature-extraction": MarianModel,
"summarization": MarianMTModel,
"text-generation": MarianForCausalLM,
"text2text-generation": MarianMTModel,
"translation": MarianMTModel,
}
if is_torch_available()
else {}
)
is_encoder_decoder = True
test_missing_keys = False
def setUp(self):
self.model_tester = MarianModelTester(self)
self.config_tester = ConfigTester(self, config_class=MarianConfig)
def test_config(self):
self.config_tester.run_common_tests()
def test_save_load_strict(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
self.assertEqual(info["missing_keys"], set())
def test_decoder_model_past_with_large_inputs(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
def test_encoder_decoder_model_standalone(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
@require_torch_fp16
def test_generate_fp16(self):
config, input_dict = self.model_tester.prepare_config_and_inputs()
input_ids = input_dict["input_ids"]
attention_mask = input_ids.ne(1).to(torch_device)
model = MarianMTModel(config).eval().to(torch_device)
model.half()
model.generate(input_ids, attention_mask=attention_mask)
model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
def test_share_encoder_decoder_embeddings(self):
config, input_dict = self.model_tester.prepare_config_and_inputs()
# check if embeddings are shared by default
for model_class in self.all_model_classes:
config.share_encoder_decoder_embeddings = True
config.tie_encoder_decoder = True
model = model_class(config)
self.assertIs(
model.get_encoder().embed_tokens.weight,
model.get_decoder().embed_tokens.weight,
msg=f"Failed for {model_class}",
)
# check if embeddings are not shared when config.share_encoder_decoder_embeddings = False
config.share_encoder_decoder_embeddings = False
config.tie_encoder_decoder = False
config.tie_word_embeddings = False
for model_class in self.all_model_classes:
model = model_class(config)
self.assertIsNot(
model.get_encoder().embed_tokens, model.get_decoder().embed_tokens, msg=f"Failed for {model_class}"
)
self.assertIsNot(
model.get_encoder().embed_tokens.weight,
model.get_decoder().embed_tokens.weight,
msg=f"Failed for {model_class}",
)
# check if a model with shared embeddings can be saved and loaded with share_encoder_decoder_embeddings = False
config, _ = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model = model_class.from_pretrained(tmpdirname, share_encoder_decoder_embeddings=False)
self.assertIsNot(model.get_encoder().embed_tokens, model.get_decoder().embed_tokens)
self.assertIsNot(model.get_encoder().embed_tokens.weight, model.get_decoder().embed_tokens.weight)
def test_resize_decoder_token_embeddings(self):
config, _ = self.model_tester.prepare_config_and_inputs()
# check if resize_decoder_token_embeddings raises an error when embeddings are shared
for model_class in self.all_model_classes:
model = model_class(config)
with self.assertRaises(ValueError):
model.resize_decoder_token_embeddings(config.vocab_size + 1)
# check if decoder embeddings are resized when config.share_encoder_decoder_embeddings = False
config.share_encoder_decoder_embeddings = False
for model_class in self.all_model_classes:
model = model_class(config)
model.resize_decoder_token_embeddings(config.vocab_size + 1)
self.assertEqual(model.get_decoder().embed_tokens.weight.shape, (config.vocab_size + 1, config.d_model))
# check if lm_head is also resized
config, _ = self.model_tester.prepare_config_and_inputs()
config.share_encoder_decoder_embeddings = False
model = MarianMTModel(config)
model.resize_decoder_token_embeddings(config.vocab_size + 1)
self.assertEqual(model.lm_head.weight.shape, (config.vocab_size + 1, config.d_model))
@unittest.skip
def test_tie_word_embeddings_decoder(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant_false(self):
pass
def assert_tensors_close(a, b, atol=1e-12, prefix=""):
"""If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if torch.allclose(a, b, atol=atol):
return True
raise Exception
except Exception:
pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
if a.numel() > 100:
msg = f"tensor values are {pct_different:.1%} percent different."
else:
msg = f"{a} != {b}"
if prefix:
msg = prefix + ": " + msg
raise AssertionError(msg)
def _long_tensor(tok_lst):
return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)
@require_torch
@require_sentencepiece
@require_tokenizers
| MarianModelTest |
python | neetcode-gh__leetcode | python/0124-binary-tree-maximum-path-sum.py | {
"start": 192,
"end": 760
} | class ____:
def maxPathSum(self, root: TreeNode) -> int:
res = [root.val]
# return max path sum without split
def dfs(root):
if not root:
return 0
leftMax = dfs(root.left)
rightMax = dfs(root.right)
leftMax = max(leftMax, 0)
rightMax = max(rightMax, 0)
# compute max path sum WITH split
res[0] = max(res[0], root.val + leftMax + rightMax)
return root.val + max(leftMax, rightMax)
dfs(root)
return res[0]
| Solution |
python | joke2k__faker | tests/providers/test_phone_number.py | {
"start": 4967,
"end": 5859
} | class ____:
"""Test de_AT phone number provider methods"""
landline_pattern: Pattern = re.compile(r"(\+43( \(0\))?|\(?0)\s?(?P<area_code>[0-9]{1,4})\)?\s?\/?[0-9 ]+")
cellphone_pattern: Pattern = re.compile(r"(\+43( \(0\))?|0)\s?(?P<dialing_code>[0-9]{3})\s?\/?[0-9 ]+")
def test_phone_number(self, faker, num_samples):
for _ in range(num_samples):
phone_number = faker.phone_number()
assert self.landline_pattern.fullmatch(phone_number)
def test_cellphone_number(self, faker, num_samples):
for _ in range(num_samples):
cellphone_number = faker.cellphone_number()
assert self.cellphone_pattern.fullmatch(cellphone_number)
assert (
self.cellphone_pattern.match(cellphone_number).group("dialing_code")
in DeAtPhoneNumberProvider.dialing_codes
)
| TestDeAt |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/components.py | {
"start": 1357,
"end": 3022
} | class ____(HttpRequester):
def __post_init__(self, parameters: Mapping[str, Any]) -> None:
self.api_budget = DEFAULT_API_BUDGET
self.error_handler.backoff_strategies = ExponentialBackoffStrategy(factor=30, config=self.config, parameters=parameters)
super().__post_init__(parameters)
def get_request_headers(
self,
*,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> Mapping[str, Any]:
return {"Accept": "application/json"}
def get_request_params(
self,
*,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> MutableMapping[str, Any]:
project_id = self.config.get("credentials", {}).get("project_id")
return {"project_id": project_id} if project_id else {}
def _request_params(
self,
stream_state: Optional[StreamState],
stream_slice: Optional[StreamSlice],
next_page_token: Optional[Mapping[str, Any]],
extra_params: Optional[Mapping[str, Any]] = None,
) -> Mapping[str, Any]:
"""
Flatten extra_params if it contains pagination information
"""
next_page_token = None # reset it, pagination data is in extra_params
if extra_params:
page = extra_params.pop("page", {})
extra_params.update(page)
return super()._request_params(stream_state, stream_slice, next_page_token, extra_params)
| MixpanelHttpRequester |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_rich_string01.py | {
"start": 315,
"end": 1024
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("rich_string01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
bold = workbook.add_format({"bold": 1})
italic = workbook.add_format({"italic": 1})
worksheet.write("A1", "Foo", bold)
worksheet.write("A2", "Bar", italic)
worksheet.write_rich_string("A3", "a", bold, "bc", "defg")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | joke2k__faker | faker/providers/emoji/en_US/__init__.py | {
"start": 43,
"end": 83
} | class ____(EmojiProvider):
pass
| Provider |
python | doocs__leetcode | solution/2700-2799/2712.Minimum Cost to Make All Characters Equal/Solution.py | {
"start": 0,
"end": 204
} | class ____:
def minimumCost(self, s: str) -> int:
ans, n = 0, len(s)
for i in range(1, n):
if s[i] != s[i - 1]:
ans += min(i, n - i)
return ans
| Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.