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 | mlflow__mlflow | mlflow/tracing/utils/timeout.py | {
"start": 1704,
"end": 3900
} | class ____(Cache):
"""
This code is ported from cachetools library to avoid depending on the private class.
https://github.com/tkem/cachetools/blob/d44c98407030d2e91cbe82c3997be042d9c2f0de/src/cachetools/__init__.py#L376
"""
class _Timer:
def __init__(self, timer):
self.__timer = timer
self.__nesting = 0
def __call__(self):
if self.__nesting == 0:
return self.__timer()
else:
return self.__time
def __enter__(self):
if self.__nesting == 0:
self.__time = time = self.__timer()
else:
time = self.__time
self.__nesting += 1
return time
def __exit__(self, *exc):
self.__nesting -= 1
def __reduce__(self):
return _TimedCache._Timer, (self.__timer,)
def __getattr__(self, name):
return getattr(self.__timer, name)
def __init__(self, maxsize, timer=time.monotonic, getsizeof=None):
Cache.__init__(self, maxsize, getsizeof)
self.__timer = _TimedCache._Timer(timer)
def __repr__(self, cache_repr=Cache.__repr__):
with self.__timer as time:
self.expire(time)
return cache_repr(self)
def __len__(self, cache_len=Cache.__len__):
with self.__timer as time:
self.expire(time)
return cache_len(self)
@property
def currsize(self):
with self.__timer as time:
self.expire(time)
return super().currsize
@property
def timer(self):
"""The timer function used by the cache."""
return self.__timer
def clear(self):
with self.__timer as time:
self.expire(time)
Cache.clear(self)
def get(self, *args, **kwargs):
with self.__timer:
return Cache.get(self, *args, **kwargs)
def pop(self, *args, **kwargs):
with self.__timer:
return Cache.pop(self, *args, **kwargs)
def setdefault(self, *args, **kwargs):
with self.__timer:
return Cache.setdefault(self, *args, **kwargs)
| _TimedCache |
python | marshmallow-code__marshmallow | tests/base.py | {
"start": 4409,
"end": 6017
} | class ____(Schema):
name = fields.String()
age: fields.Field = fields.Float()
created = fields.DateTime()
created_formatted = fields.DateTime(
format="%Y-%m-%d", attribute="created", dump_only=True
)
created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True)
updated = fields.DateTime()
species = fields.String(attribute="SPECIES")
id = fields.String(dump_default="no-id")
uppername = Uppercased(attribute="name", dump_only=True)
homepage = fields.Url()
email = fields.Email()
balance = fields.Decimal()
is_old: fields.Field = fields.Method("get_is_old")
lowername = fields.Function(get_lowername)
registered = fields.Boolean()
hair_colors = fields.List(fields.Raw)
sex_choices = fields.List(fields.Raw)
finger_count = fields.Integer()
uid = fields.UUID()
time_registered = fields.Time()
birthdate = fields.Date()
birthtime = fields.Time()
activation_date = fields.Date()
since_created = fields.TimeDelta()
sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__)))
various_data = fields.Dict()
class Meta:
render_module = simplejson
def get_is_old(self, obj):
if obj is None:
return missing
if isinstance(obj, dict):
age = obj.get("age", 0)
else:
age = obj.age
try:
return age > 80
except TypeError as te:
raise ValidationError(str(te)) from te
@post_load
def make_user(self, data, **kwargs):
return User(**data)
| UserSchema |
python | explosion__spaCy | spacy/lang/el/__init__.py | {
"start": 410,
"end": 696
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
prefixes = TOKENIZER_PREFIXES
suffixes = TOKENIZER_SUFFIXES
infixes = TOKENIZER_INFIXES
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
syntax_iterators = SYNTAX_ITERATORS
| GreekDefaults |
python | facelessuser__pymdown-extensions | pymdownx/snippets.py | {
"start": 1518,
"end": 1595
} | class ____(Exception):
"""Snippet missing exception."""
| SnippetMissingError |
python | django__django | django/tasks/base.py | {
"start": 5272,
"end": 7527
} | class ____:
task: Task
id: str # Unique identifier for the task result.
status: TaskResultStatus
enqueued_at: Optional[datetime] # Time the task was enqueued.
started_at: Optional[datetime] # Time the task was started.
finished_at: Optional[datetime] # Time the task was finished.
# Time the task was last attempted to be run.
last_attempted_at: Optional[datetime]
args: list # Arguments to pass to the task function.
kwargs: Dict[str, Any] # Keyword arguments to pass to the task function.
backend: str
errors: list[TaskError] # Errors raised when running the task.
worker_ids: list[str] # Workers which have processed the task.
_return_value: Optional[Any] = field(init=False, default=None)
def __post_init__(self):
object.__setattr__(self, "args", normalize_json(self.args))
object.__setattr__(self, "kwargs", normalize_json(self.kwargs))
@property
def return_value(self):
"""
The return value of the task.
If the task didn't succeed, an exception is raised.
This is to distinguish against the task returning None.
"""
if self.status == TaskResultStatus.SUCCESSFUL:
return self._return_value
elif self.status == TaskResultStatus.FAILED:
raise ValueError("Task failed")
else:
raise ValueError("Task has not finished yet")
@property
def is_finished(self):
return self.status in {TaskResultStatus.FAILED, TaskResultStatus.SUCCESSFUL}
@property
def attempts(self):
return len(self.worker_ids)
def refresh(self):
"""Reload the cached task data from the task store."""
refreshed_task = self.task.get_backend().get_result(self.id)
for attr in TASK_REFRESH_ATTRS:
object.__setattr__(self, attr, getattr(refreshed_task, attr))
async def arefresh(self):
"""
Reload the cached task data from the task store
"""
refreshed_task = await self.task.get_backend().aget_result(self.id)
for attr in TASK_REFRESH_ATTRS:
object.__setattr__(self, attr, getattr(refreshed_task, attr))
@dataclass(frozen=True, slots=True, kw_only=True)
| TaskResult |
python | huggingface__transformers | src/transformers/models/falcon_h1/modular_falcon_h1.py | {
"start": 7983,
"end": 10127
} | class ____(LlamaAttention):
def __init__(self, config: FalconH1Config, layer_idx: int):
super().__init__(config, layer_idx)
self.key_multiplier = config.key_multiplier
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) * self.key_multiplier
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| FalconH1Attention |
python | numba__numba | numba/tests/test_boundscheck.py | {
"start": 4064,
"end": 6803
} | class ____(TestCase):
@TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
def test_basic_array_boundscheck(self):
self.assertIsNone(config.BOUNDSCHECK)
a = np.arange(5)
# Check the numpy behavior to make sure the test is correct
with self.assertRaises(IndexError):
# TODO: When we raise the same error message as numpy, test that
# they are the same
basic_array_access(a)
at = typeof(a)
boundscheck = njit((at,), boundscheck=True)(basic_array_access)
with self.assertRaises(IndexError):
boundscheck(a)
@TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
def test_slice_array_boundscheck(self):
self.assertIsNone(config.BOUNDSCHECK)
a = np.ones((5, 5))
b = np.ones((5, 20))
with self.assertRaises(IndexError):
# TODO: When we raise the same error message as numpy, test that
# they are the same
slice_array_access(a)
# Out of bounds on a slice doesn't raise
slice_array_access(b)
at = typeof(a)
rt = float64[:]
boundscheck = njit(rt(at), boundscheck=True)(slice_array_access)
with self.assertRaises(IndexError):
boundscheck(a)
@TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
def test_fancy_indexing_boundscheck(self):
self.assertIsNone(config.BOUNDSCHECK)
a = np.arange(3)
b = np.arange(4)
# Check the numpy behavior to ensure the test is correct.
with self.assertRaises(IndexError):
# TODO: When we raise the same error message as numpy, test that
# they are the same
fancy_array_access(a)
fancy_array_access(b)
at = typeof(a)
rt = at.dtype[:]
boundscheck = njit(rt(at), boundscheck=True)(fancy_array_access)
with self.assertRaises(IndexError):
boundscheck(a)
@TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''})
def test_fancy_indexing_with_modification_boundscheck(self):
self.assertIsNone(config.BOUNDSCHECK)
a = np.arange(3)
b = np.arange(4)
# Check the numpy behavior to ensure the test is correct.
with self.assertRaises(IndexError):
# TODO: When we raise the same error message as numpy, test that
# they are the same
fancy_array_modify(a)
fancy_array_modify(b)
at = typeof(a)
rt = at.dtype[:]
boundscheck = njit(rt(at), boundscheck=True)(fancy_array_modify)
with self.assertRaises(IndexError):
boundscheck(a)
| TestBoundsCheckError |
python | ray-project__ray | python/ray/llm/_internal/serve/serving_patterns/prefill_decode/pd_server.py | {
"start": 893,
"end": 6416
} | class ____(LLMServerProtocol):
"""Proxy between P/D LLM servers.
This class implements the LLMServerProtocol but doesn't have a real engine.
It forwards requests to prefill and decode servers for disaggregated inference.
For chat and completions, proxy sends the request to the prefill server and
then parses the response to send to the decode server.
Args:
prefill_server: The prefill server deployment handle.
decode_server: The decode server deployment handle.
"""
async def __init__(
self,
prefill_server: DeploymentHandle,
decode_server: DeploymentHandle,
):
# Store llm_config from prefill_server for the model_id,
# such that /v1/models endpoint can work correctly.
# TODO(lk-chen): refactor OpenAiIngress <-> LLMServer such that router
# query model_id through API, instead of passing it in as an argument.
# We obtain llm_config from prefill_server for obtaining model_id
# assuming there is no mismatch between prefill and decode server.
self._llm_config = await prefill_server.llm_config.remote()
self.prefill_server = prefill_server.options(stream=True)
self.decode_server = decode_server.options(stream=True)
async def start(self) -> None:
"""Start is a no-op for PDProxyServer since it's just a proxy."""
pass
async def check_health(self) -> None:
"""Health check is a no-op for PDProxyServer."""
pass
async def reset_prefix_cache(self) -> None:
"""Prefix cache reset is not supported for P/D disaggregation."""
raise NotImplementedError(
"reset_prefix_cache is not supported for P/D disaggregation"
)
async def start_profile(self) -> None:
"""Profiling is not supported for P/D disaggregation."""
raise NotImplementedError(
"start_profile is not supported for P/D disaggregation"
)
async def stop_profile(self) -> None:
"""Profiling is not supported for P/D disaggregation."""
raise NotImplementedError(
"stop_profile is not supported for P/D disaggregation"
)
async def llm_config(self) -> Optional[LLMConfig]:
"""Return the LLM configuration."""
return self._llm_config
def _prepare_prefill_request(self, request: RequestType) -> RequestType:
assert (
getattr(request, "kv_transfer_params", None) is None
), "kv_transfer_params should be empty before proxy"
prefill_request = request.model_copy(deep=True)
prefill_request.kv_transfer_params = {
"do_remote_decode": True,
"do_remote_prefill": False,
"remote_engine_id": None,
"remote_block_ids": None,
"remote_host": None,
"remote_port": None,
}
prefill_request.max_tokens = 1
prefill_request.stream = False
return prefill_request
def _prepare_decode_request(
self,
request: RequestType,
prefill_chunk: Union[ChatCompletionResponse, CompletionResponse],
) -> RequestType:
decode_request = request.model_copy(deep=True)
decode_request.kv_transfer_params = prefill_chunk.kv_transfer_params
return decode_request
def _maybe_add_request_id_to_request(
self,
request: Union[ChatCompletionRequest, CompletionRequest],
) -> None:
"""Add the request id to the request."""
request_id = get_serve_request_id()
if request_id:
request.request_id = request_id
async def _handle_request(
self,
request: RequestType,
) -> AsyncGenerator[
Union[str, ChatCompletionResponse, CompletionResponse, ErrorResponse], None
]:
self._maybe_add_request_id_to_request(request)
if isinstance(request, ChatCompletionRequest):
method = "chat"
elif isinstance(request, CompletionRequest):
method = "completions"
else:
raise ValueError(f"Unsupported request type: {type(request)}")
prefill_request = self._prepare_prefill_request(request)
prefill_gen = getattr(self.prefill_server, method).remote(prefill_request)
prefill_chunk = await prefill_gen.__anext__()
if isinstance(prefill_chunk, ErrorResponse):
logger.error(f"Prefill returned error: {prefill_chunk}")
yield prefill_chunk
return
decode_request = self._prepare_decode_request(request, prefill_chunk)
decode_gen = getattr(self.decode_server, method).remote(decode_request)
async for chunk in decode_gen:
yield chunk
async def chat(
self, request: ChatCompletionRequest
) -> AsyncGenerator[Union[str, ChatCompletionResponse, ErrorResponse], None]:
return self._handle_request(request)
async def completions(
self, request: CompletionRequest
) -> AsyncGenerator[Union[str, CompletionResponse, ErrorResponse], None]:
return self._handle_request(request)
async def embeddings(
self, request: EmbeddingRequest
) -> AsyncGenerator[EmbeddingResponse, None]:
raise NotImplementedError("Embedding is not supported for P/D disaggregation")
@classmethod
def get_deployment_options(
cls, prefill_config: "LLMConfig", decode_config: "LLMConfig"
) -> Dict[str, Any]:
return DEFAULT_PD_PROXY_SERVER_OPTIONS
| PDProxyServer |
python | apache__airflow | providers/trino/tests/unit/trino/hooks/test_trino.py | {
"start": 2156,
"end": 12323
} | class ____:
@patch(BASIC_AUTHENTICATION)
@patch(TRINO_DBAPI_CONNECT)
@patch(HOOK_GET_CONNECTION)
def test_get_conn_basic_auth(self, mock_get_connection, mock_connect, mock_basic_auth):
self.set_get_connection_return_value(mock_get_connection, password="password")
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, auth=mock_basic_auth)
mock_basic_auth.assert_called_once_with("login", "password")
@patch("airflow.providers.trino.hooks.trino.generate_trino_client_info")
@patch(BASIC_AUTHENTICATION)
@patch(TRINO_DBAPI_CONNECT)
@patch(HOOK_GET_CONNECTION)
def test_http_headers(
self,
mock_get_connection,
mock_connect,
mock_basic_auth,
mocked_generate_airflow_trino_client_info_header,
):
mock_get_connection.return_value = Connection(
login="login", password="password", host="host", schema="hive"
)
date_key = "logical_date" if AIRFLOW_V_3_0_PLUS else "execution_date"
client = json.dumps(
{
"dag_id": "dag-id",
date_key: "2022-01-01T00:00:00",
"task_id": "task-id",
"try_number": "1",
"dag_run_id": "dag-run-id",
"dag_owner": "dag-owner",
},
sort_keys=True,
)
http_headers = {"X-Trino-Client-Info": client}
mocked_generate_airflow_trino_client_info_header.return_value = http_headers["X-Trino-Client-Info"]
conn = TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, auth=mock_basic_auth, http_headers=http_headers)
mock_basic_auth.assert_called_once_with("login", "password")
assert mock_connect.return_value == conn
@patch(HOOK_GET_CONNECTION)
def test_get_conn_invalid_auth(self, mock_get_connection):
extras = {"auth": "kerberos"}
self.set_get_connection_return_value(
mock_get_connection,
password="password",
extra=json.dumps(extras),
)
with pytest.raises(
AirflowException,
match=re.escape(
"Multiple authentication methods specified: password, kerberos. Only one is allowed."
),
):
TrinoHook().get_conn()
@patch(JWT_AUTHENTICATION)
@patch(TRINO_DBAPI_CONNECT)
@patch(HOOK_GET_CONNECTION)
def test_get_conn_jwt_auth(self, mock_get_connection, mock_connect, mock_jwt_auth):
extras = {
"auth": "jwt",
"jwt__token": "TEST_JWT_TOKEN",
}
self.set_get_connection_return_value(
mock_get_connection,
extra=json.dumps(extras),
)
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, auth=mock_jwt_auth)
@patch(JWT_AUTHENTICATION)
@patch(TRINO_DBAPI_CONNECT)
@patch(HOOK_GET_CONNECTION)
def test_get_conn_jwt_file(self, mock_get_connection, mock_connect, mock_jwt_auth, jwt_token_file):
extras = {
"auth": "jwt",
"jwt__file": jwt_token_file,
}
self.set_get_connection_return_value(
mock_get_connection,
extra=json.dumps(extras),
)
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, auth=mock_jwt_auth)
@pytest.mark.parametrize(
("jwt_file", "jwt_token", "error_suffix"),
[
pytest.param(True, True, "provided both", id="provided-both-params"),
pytest.param(False, False, "none of them provided", id="no-jwt-provided"),
],
)
@patch(HOOK_GET_CONNECTION)
def test_exactly_one_jwt_token(
self, mock_get_connection, jwt_file, jwt_token, error_suffix, jwt_token_file
):
error_match = f"When auth set to 'jwt'.*{error_suffix}"
extras = {"auth": "jwt"}
if jwt_file:
extras["jwt__file"] = jwt_token_file
if jwt_token:
extras["jwt__token"] = "TEST_JWT_TOKEN"
self.set_get_connection_return_value(mock_get_connection, extra=json.dumps(extras))
with pytest.raises(ValueError, match=error_match):
TrinoHook().get_conn()
@patch(CERT_AUTHENTICATION)
@patch(TRINO_DBAPI_CONNECT)
@patch(HOOK_GET_CONNECTION)
def test_get_conn_cert_auth(self, mock_get_connection, mock_connect, mock_cert_auth):
extras = {
"auth": "certs",
"certs__client_cert_path": "/path/to/client.pem",
"certs__client_key_path": "/path/to/client.key",
}
self.set_get_connection_return_value(
mock_get_connection,
extra=json.dumps(extras),
)
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, auth=mock_cert_auth)
mock_cert_auth.assert_called_once_with("/path/to/client.pem", "/path/to/client.key")
@patch(KERBEROS_AUTHENTICATION)
@patch(TRINO_DBAPI_CONNECT)
@patch(HOOK_GET_CONNECTION)
def test_get_conn_kerberos_auth(self, mock_get_connection, mock_connect, mock_auth):
extras = {
"auth": "kerberos",
"kerberos__config": "TEST_KERBEROS_CONFIG",
"kerberos__service_name": "TEST_SERVICE_NAME",
"kerberos__mutual_authentication": "TEST_MUTUAL_AUTHENTICATION",
"kerberos__force_preemptive": True,
"kerberos__hostname_override": "TEST_HOSTNAME_OVERRIDE",
"kerberos__sanitize_mutual_error_response": True,
"kerberos__principal": "TEST_PRINCIPAL",
"kerberos__delegate": "TEST_DELEGATE",
"kerberos__ca_bundle": "TEST_CA_BUNDLE",
"verify": "true",
}
self.set_get_connection_return_value(
mock_get_connection,
extra=json.dumps(extras),
)
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, auth=mock_auth)
@patch(HOOK_GET_CONNECTION)
@patch(TRINO_DBAPI_CONNECT)
def test_get_conn_session_properties(self, mock_connect, mock_get_connection):
extras = {
"session_properties": {
"scale_writers": "true",
"task_writer_count": "1",
"writer_min_size": "100MB",
},
}
self.set_get_connection_return_value(mock_get_connection, extra=extras)
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, session_properties=extras["session_properties"])
@patch(HOOK_GET_CONNECTION)
@patch(TRINO_DBAPI_CONNECT)
def test_get_conn_client_tags(self, mock_connect, mock_get_connection):
extras = {"client_tags": ["abc", "xyz"]}
self.set_get_connection_return_value(mock_get_connection, extra=extras)
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, client_tags=extras["client_tags"])
@pytest.mark.parametrize(
("current_verify", "expected_verify"),
[
("False", False),
("false", False),
("true", True),
("True", True),
("/tmp/cert.crt", "/tmp/cert.crt"),
],
)
@patch(HOOK_GET_CONNECTION)
@patch(TRINO_DBAPI_CONNECT)
def test_get_conn_verify(self, mock_connect, mock_get_connection, current_verify, expected_verify):
extras = {"verify": current_verify}
self.set_get_connection_return_value(mock_get_connection, extra=json.dumps(extras))
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, verify=expected_verify)
@patch(HOOK_GET_CONNECTION)
@patch(TRINO_DBAPI_CONNECT)
def test_get_conn_timezone(self, mock_connect, mock_get_connection):
extras = {"timezone": "Asia/Jerusalem"}
self.set_get_connection_return_value(mock_get_connection, extra=json.dumps(extras))
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, timezone="Asia/Jerusalem")
@patch(HOOK_GET_CONNECTION)
@patch(TRINO_DBAPI_CONNECT)
def test_get_conn_extra_credential(self, mock_connect, mock_get_connection):
extras = {"extra_credential": [["a.username", "bar"], ["a.password", "foo"]]}
self.set_get_connection_return_value(mock_get_connection, extra=json.dumps(extras))
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, extra_credential=extras["extra_credential"])
@patch(HOOK_GET_CONNECTION)
@patch(TRINO_DBAPI_CONNECT)
def test_get_conn_roles(self, mock_connect, mock_get_connection):
extras = {"roles": {"catalog1": "trinoRoleA", "catalog2": "trinoRoleB"}}
self.set_get_connection_return_value(mock_get_connection, extra=json.dumps(extras))
TrinoHook().get_conn()
self.assert_connection_called_with(mock_connect, roles=extras["roles"])
@staticmethod
def set_get_connection_return_value(mock_get_connection, extra=None, password=None):
mocked_connection = Connection(
login="login", password=password, host="host", schema="hive", extra=extra or "{}"
)
mock_get_connection.return_value = mocked_connection
@staticmethod
def assert_connection_called_with(
mock_connect,
http_headers=mock.ANY,
auth=None,
verify=True,
session_properties=None,
client_tags=None,
timezone=None,
extra_credential=None,
roles=None,
):
mock_connect.assert_called_once_with(
catalog="hive",
host="host",
port=None,
http_scheme="http",
http_headers=http_headers,
schema="hive",
source="airflow",
user="login",
isolation_level=IsolationLevel.AUTOCOMMIT,
auth=None if not auth else auth.return_value,
verify=verify,
session_properties=session_properties,
client_tags=client_tags,
timezone=timezone,
extra_credential=extra_credential,
roles=roles,
)
| TestTrinoHookConn |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/common.py | {
"start": 884,
"end": 948
} | class ____(Exception):
"""Scheduled job failed"""
| JobException |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 65938,
"end": 66626
} | class ____(Operation):
def call(self, x):
return backend.numpy.cos(x)
def compute_output_spec(self, x):
dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
if dtype == "int64":
dtype = backend.floatx()
else:
dtype = dtypes.result_type(dtype, float)
return KerasTensor(x.shape, dtype=dtype)
@keras_export(["keras.ops.cos", "keras.ops.numpy.cos"])
def cos(x):
"""Cosine, element-wise.
Args:
x: Input tensor.
Returns:
The corresponding cosine values.
"""
if any_symbolic_tensors((x,)):
return Cos().symbolic_call(x)
return backend.numpy.cos(x)
| Cos |
python | scipy__scipy | scipy/signal/tests/test_peak_finding.py | {
"start": 11813,
"end": 16430
} | class ____:
def test_empty(self):
"""
Test if an empty array is returned if no peaks are provided.
"""
out = peak_prominences([1, 2, 3], [])
for arr, dtype in zip(out, [np.float64, np.intp, np.intp]):
assert arr.size == 0
assert arr.dtype == dtype
out = peak_prominences([], [])
for arr, dtype in zip(out, [np.float64, np.intp, np.intp]):
assert arr.size == 0
assert arr.dtype == dtype
def test_basic(self):
"""
Test if height of prominences is correctly calculated in signal with
rising baseline (peak widths are 1 sample).
"""
# Prepare basic signal
x = np.array([-1, 1.2, 1.2, 1, 3.2, 1.3, 2.88, 2.1])
peaks = np.array([1, 2, 4, 6])
lbases = np.array([0, 0, 0, 5])
rbases = np.array([3, 3, 5, 7])
proms = x[peaks] - np.max([x[lbases], x[rbases]], axis=0)
# Test if calculation matches handcrafted result
out = peak_prominences(x, peaks)
xp_assert_equal(out[0], proms, check_dtype=False)
xp_assert_equal(out[1], lbases, check_dtype=False)
xp_assert_equal(out[2], rbases, check_dtype=False)
def test_edge_cases(self):
"""
Test edge cases.
"""
# Peaks have same height, prominence and bases
x = [0, 2, 1, 2, 1, 2, 0]
peaks = [1, 3, 5]
proms, lbases, rbases = peak_prominences(x, peaks)
xp_assert_equal(proms, np.asarray([2.0, 2, 2]), check_dtype=False)
xp_assert_equal(lbases, [0, 0, 0], check_dtype=False)
xp_assert_equal(rbases, [6, 6, 6], check_dtype=False)
# Peaks have same height & prominence but different bases
x = [0, 1, 0, 1, 0, 1, 0]
peaks = np.array([1, 3, 5])
proms, lbases, rbases = peak_prominences(x, peaks)
xp_assert_equal(proms, np.asarray([1.0, 1, 1]))
xp_assert_equal(lbases, peaks - 1, check_dtype=False)
xp_assert_equal(rbases, peaks + 1, check_dtype=False)
def test_non_contiguous(self):
"""
Test with non-C-contiguous input arrays.
"""
x = np.repeat([-9, 9, 9, 0, 3, 1], 2)
peaks = np.repeat([1, 2, 4], 2)
proms, lbases, rbases = peak_prominences(x[::2], peaks[::2])
xp_assert_equal(proms, np.asarray([9.0, 9, 2]))
xp_assert_equal(lbases, [0, 0, 3], check_dtype=False)
xp_assert_equal(rbases, [3, 3, 5], check_dtype=False)
def test_wlen(self):
"""
Test if wlen actually shrinks the evaluation range correctly.
"""
x = [0, 1, 2, 3, 1, 0, -1]
peak = [3]
# Test rounding behavior of wlen
proms = peak_prominences(x, peak)
for prom, val in zip(proms, [3.0, 0, 6]):
assert prom == val
for wlen, i in [(8, 0), (7, 0), (6, 0), (5, 1), (3.2, 1), (3, 2), (1.1, 2)]:
proms = peak_prominences(x, peak, wlen)
for prom, val in zip(proms, [3. - i, 0 + i, 6 - i]):
assert prom == val
def test_exceptions(self):
"""
Verify that exceptions and warnings are raised.
"""
# x with dimension > 1
with raises(ValueError, match='1-D array'):
peak_prominences([[0, 1, 1, 0]], [1, 2])
# peaks with dimension > 1
with raises(ValueError, match='1-D array'):
peak_prominences([0, 1, 1, 0], [[1, 2]])
# x with dimension < 1
with raises(ValueError, match='1-D array'):
peak_prominences(3, [0,])
# empty x with supplied
with raises(ValueError, match='not a valid index'):
peak_prominences([], [0])
# invalid indices with non-empty x
for p in [-100, -1, 3, 1000]:
with raises(ValueError, match='not a valid index'):
peak_prominences([1, 0, 2], [p])
# peaks is not cast-able to np.intp
with raises(TypeError, match='cannot safely cast'):
peak_prominences([0, 1, 1, 0], [1.1, 2.3])
# wlen < 3
with raises(ValueError, match='wlen'):
peak_prominences(np.arange(10), [3, 5], wlen=1)
def test_warnings(self):
"""
Verify that appropriate warnings are raised.
"""
msg = "some peaks have a prominence of 0"
for p in [0, 1, 2]:
with warns(PeakPropertyWarning, match=msg):
peak_prominences([1, 0, 2], [p,])
with warns(PeakPropertyWarning, match=msg):
peak_prominences([0, 1, 1, 1, 0], [2], wlen=2)
| TestPeakProminences |
python | sympy__sympy | sympy/solvers/diophantine/diophantine.py | {
"start": 22434,
"end": 24995
} | class ____(DiophantineEquationType):
"""
Representation of a homogeneous ternary quadratic normal diophantine equation.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadraticNormal
>>> HomogeneousTernaryQuadraticNormal(4*x**2 - 5*y**2 + z**2).solve()
{(1, 2, 4)}
"""
name = 'homogeneous_ternary_quadratic_normal'
def matches(self):
if not (self.total_degree == 2 and self.dimension == 3):
return False
if not self.homogeneous:
return False
if not self.homogeneous_order:
return False
nonzero = [k for k in self.coeff if self.coeff[k]]
return len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols)
def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet:
self.pre_solve(parameters)
var = self.free_symbols
coeff = self.coeff
x, y, z = var
a = coeff[x**2]
b = coeff[y**2]
c = coeff[z**2]
(sqf_of_a, sqf_of_b, sqf_of_c), (a_1, b_1, c_1), (a_2, b_2, c_2) = \
sqf_normal(a, b, c, steps=True)
A = -a_2*c_2
B = -b_2*c_2
result = DiophantineSolutionSet(var, parameters=self.parameters)
# If following two conditions are satisfied then there are no solutions
if A < 0 and B < 0:
return result
if (
sqrt_mod(-b_2*c_2, a_2) is None or
sqrt_mod(-c_2*a_2, b_2) is None or
sqrt_mod(-a_2*b_2, c_2) is None):
return result
z_0, x_0, y_0 = descent(A, B)
z_0, q = _rational_pq(z_0, abs(c_2))
x_0 *= q
y_0 *= q
x_0, y_0, z_0 = _remove_gcd(x_0, y_0, z_0)
# Holzer reduction
if sign(a) == sign(b):
x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2))
elif sign(a) == sign(c):
x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2))
else:
y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2))
x_0 = reconstruct(b_1, c_1, x_0)
y_0 = reconstruct(a_1, c_1, y_0)
z_0 = reconstruct(a_1, b_1, z_0)
sq_lcm = ilcm(sqf_of_a, sqf_of_b, sqf_of_c)
x_0 = abs(x_0*sq_lcm // sqf_of_a)
y_0 = abs(y_0*sq_lcm // sqf_of_b)
z_0 = abs(z_0*sq_lcm // sqf_of_c)
result.add(_remove_gcd(x_0, y_0, z_0))
return result
| HomogeneousTernaryQuadraticNormal |
python | getsentry__sentry | tests/sentry/integrations/utils/test_sync.py | {
"start": 9000,
"end": 29093
} | class ____(TestCase):
@pytest.fixture(autouse=True)
def mock_where_should_sync(self):
with mock.patch(
"sentry.integrations.utils.sync.where_should_sync"
) as mock_where_should_sync:
mock_where_should_sync.return_value = [self.organization]
yield mock_where_should_sync
def setUp(self) -> None:
self.example_integration = self.create_integration(
organization=self.group.organization,
external_id="123456",
provider="github",
oi_params={
"config": {
"sync_comments": True,
"sync_status_outbound": True,
"sync_status_inbound": True,
"sync_assignee_outbound": True,
"sync_assignee_inbound": True,
}
},
)
self.test_user = self.create_user("test@example.com")
self.create_member(organization=self.organization, user=self.test_user, teams=[self.team])
with assume_test_silo_mode_of(UserEmail):
UserEmail.objects.filter(user=self.test_user).update(is_verified=True)
assert UserEmail.objects.filter(
user=self.test_user, email="test@example.com", is_verified=True
).exists()
def assign_default_group_to_user(self, user: User, group: Group | None = None):
group_to_update: Group = group or self.group
GroupAssignee.objects.assign(group_to_update, serialize_rpc_user(user))
group_to_update.refresh_from_db()
group_assignee = group_to_update.get_assignee()
assert group_assignee is not None and group_assignee.id == user.id
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_no_affected_groups(self, mock_record_event: mock.MagicMock) -> None:
"""Test when no groups are affected by the external issue."""
self.assign_default_group_to_user(self.test_user)
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="johndoe",
external_issue_key="this-does-not-exist",
assign=True,
)
mock_record_event.record_event(EventLifecycleOutcome.SUCCESS)
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_unassign(self, mock_record_event: mock.MagicMock) -> None:
"""Test unassigning a group via external actor."""
self.assign_default_group_to_user(self.test_user)
external_issue = self.create_integration_external_issue(
group=self.group,
key="JIRA-123",
integration=self.example_integration,
)
# Create external user mapping
self.create_external_user(
user=self.test_user,
external_name="johndoe",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="johndoe",
external_issue_key=external_issue.key,
assign=False,
)
assert self.group.get_assignee() is None
mock_record_event.assert_called_with(EventLifecycleOutcome.SUCCESS, None, False, None)
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_assignment_with_external_actor(
self,
mock_record_event: mock.MagicMock,
) -> None:
"""Test assigning a group to a user via external actor."""
assert self.group.get_assignee() is None
external_issue = self.create_integration_external_issue(
group=self.group,
key="JIRA-123",
integration=self.example_integration,
)
# Create external user mapping
self.create_external_user(
user=self.test_user,
external_name="johndoe",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="johndoe",
external_issue_key=external_issue.key,
assign=True,
)
updated_assignee = self.group.get_assignee()
assert updated_assignee is not None
assert updated_assignee.id == self.test_user.id
assert updated_assignee.email == "test@example.com"
mock_record_event.assert_called_with(EventLifecycleOutcome.SUCCESS, None, False, None)
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_assignment_with_external_actor_case_insensitive(
self,
mock_record_event: mock.MagicMock,
) -> None:
"""Test assigning a group to a user via external actor."""
assert self.group.get_assignee() is None
external_issue = self.create_integration_external_issue(
group=self.group,
key="JIRA-123",
integration=self.example_integration,
)
# Create external user mapping
self.create_external_user(
user=self.test_user,
external_name="@JohnDoe",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="@johndoe",
external_issue_key=external_issue.key,
assign=True,
)
updated_assignee = self.group.get_assignee()
assert updated_assignee is not None
assert updated_assignee.id == self.test_user.id
assert updated_assignee.email == "test@example.com"
mock_record_event.assert_called_with(EventLifecycleOutcome.SUCCESS, None, False, None)
@mock.patch("sentry.integrations.utils.sync.where_should_sync")
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_assign_with_multiple_groups(
self, mock_record_event: mock.MagicMock, mock_where_should_sync: mock.MagicMock
) -> None:
"""Test assigning multiple groups via external actor."""
# Create a couple new test unassigned test groups
groups_to_assign: list[Group] = []
orgs_to_assign: list[Organization] = []
for _ in range(2):
org = self.create_organization(owner=self.create_user())
team = self.create_team(organization=org)
project = self.create_project(organization=org, teams=[team])
self.create_member(organization=org, user=self.test_user, teams=[team])
self.create_organization_integration(
organization_id=org.id,
integration=self.example_integration,
config={"sync_reverse_assignment": True},
)
groups_to_assign.append(
self.create_group(project=project),
)
orgs_to_assign.append(org)
mock_where_should_sync.return_value = orgs_to_assign
external_issue_key = "JIRA-456"
for group in groups_to_assign:
assert group.get_assignee() is None
self.create_integration_external_issue(
group=group,
key=external_issue_key,
integration=self.example_integration,
)
# Create external user mapping
self.create_external_user(
user=self.test_user,
external_name="johndoe",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="johndoe",
external_issue_key=external_issue_key,
assign=True,
)
for group in groups_to_assign:
assignee = group.get_assignee()
assert assignee is not None
assert isinstance(assignee, RpcUser)
assert assignee.id == self.test_user.id
assert assignee.email == "test@example.com"
mock_record_event.assert_called_with(EventLifecycleOutcome.SUCCESS, None, False, None)
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_halt")
def test_assign_with_no_external_actor_found(self, mock_record_halt: mock.MagicMock) -> None:
"""Test assignment when no external actor mapping exists."""
assert self.group.get_assignee() is None
external_issue = self.create_integration_external_issue(
group=self.group,
key="JIRA-789",
integration=self.example_integration,
)
# Don't create any external user mapping - this should cause a halt
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="unknownuser",
external_issue_key=external_issue.key,
assign=True,
)
updated_assignee = self.group.get_assignee()
assert updated_assignee is None
mock_record_halt.assert_called_with(
"inbound-assignee-not-found",
extra={
"integration_id": self.example_integration.id,
"external_user_name": "unknownuser",
"issue_key": external_issue.key,
"method": AssigneeInboundSyncMethod.EXTERNAL_ACTOR.value,
"assign": True,
"user_ids": [],
"groups_assigned_count": 0,
"affected_groups_count": 1,
},
)
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_halt")
def test_assign_with_user_not_in_project(self, mock_record_halt: mock.MagicMock) -> None:
"""Test assignment when user exists but is not a member of the project."""
assert self.group.get_assignee() is None
# Create a user that is not a member of the project
other_user = self.create_user("other@example.com")
external_issue = self.create_integration_external_issue(
group=self.group,
key="JIRA-999",
integration=self.example_integration,
)
# Create external user mapping for the user who is not in the project
self.create_external_user(
user=other_user,
external_name="outsider",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="outsider",
external_issue_key=external_issue.key,
assign=True,
)
updated_assignee = self.group.get_assignee()
assert updated_assignee is None
mock_record_halt.assert_called_with(
"inbound-assignee-not-found",
extra={
"integration_id": self.example_integration.id,
"external_user_name": "outsider",
"issue_key": external_issue.key,
"method": AssigneeInboundSyncMethod.EXTERNAL_ACTOR.value,
"assign": True,
"user_ids": [other_user.id],
"groups_assigned_count": 0,
"affected_groups_count": 1,
},
)
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_failure")
@mock.patch("sentry.models.groupassignee.GroupAssigneeManager.assign")
def test_assignment_fails(
self,
mock_group_assign: mock.MagicMock,
mock_record_failure: mock.MagicMock,
) -> None:
"""Test handling when assignment operation fails."""
def raise_exception(*_args, **_kwargs):
raise Exception("oops, something went wrong during assignment")
assert self.group.get_assignee() is None
mock_group_assign.side_effect = raise_exception
external_issue = self.create_integration_external_issue(
group=self.group,
key="JIRA-ERROR",
integration=self.example_integration,
)
# Create external user mapping
self.create_external_user(
user=self.test_user,
external_name="johndoe",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
with pytest.raises(Exception) as exc:
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="johndoe",
external_issue_key=external_issue.key,
assign=True,
)
assert exc.match("oops, something went wrong during assignment")
updated_assignee = self.group.get_assignee()
assert updated_assignee is None
mock_record_failure.assert_called_once_with(mock.ANY, create_issue=True)
exception_param = mock_record_failure.call_args_list[0].args[0]
assert isinstance(exception_param, Exception)
assert exception_param.args[0] == "oops, something went wrong during assignment"
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_multiple_external_actors_same_name(self, mock_record_event: mock.MagicMock) -> None:
"""Test assignment when multiple users have the same external name (should use the first one found)."""
assert self.group.get_assignee() is None
# Create another user
another_user = self.create_user("another@example.com")
self.create_member(organization=self.organization, user=another_user, teams=[self.team])
external_issue = self.create_integration_external_issue(
group=self.group,
key="JIRA-DUP",
integration=self.example_integration,
)
# Create external user mappings with the same external name
self.create_external_user(
user=self.test_user,
external_name="duplicate_name",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
self.create_external_user(
user=another_user,
external_name="duplicate_name",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="duplicate_name",
external_issue_key=external_issue.key,
assign=True,
)
updated_assignee = self.group.get_assignee()
assert updated_assignee is not None
# The assignment should succeed with one of the users
assert updated_assignee.id in [self.test_user.id, another_user.id]
mock_record_event.assert_called_with(EventLifecycleOutcome.SUCCESS, None, False, None)
@mock.patch("sentry.integrations.utils.sync.where_should_sync")
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_same_external_name_different_users_across_orgs(
self, mock_record_event: mock.MagicMock, mock_where_should_sync: mock.MagicMock
) -> None:
"""Test when the same external_user_name maps to different users in different orgs.
Scenario 1: Both users should be assigned to their respective groups.
Scenario 2: When only one user has a group with the external issue, only that user is affected.
"""
# Create two different organizations
# org1 is self.organization (already exists)
org2 = self.create_organization(owner=self.create_user())
mock_where_should_sync.return_value = [self.organization, org2]
# Create two different users
user1 = self.test_user # Already exists in org1
user2 = self.create_user("user2@example.com")
# Create teams and memberships
team2 = self.create_team(organization=org2)
self.create_member(organization=org2, user=user2, teams=[team2])
# Create projects and groups for each org
project2 = self.create_project(organization=org2, teams=[team2])
group1 = self.group # Already exists in org1
group2 = self.create_group(project=project2)
# Setup organization integrations for both orgs
self.create_organization_integration(
organization_id=org2.id,
integration=self.example_integration,
config={"sync_reverse_assignment": True},
)
# Create external user mappings - same external name, different users in different orgs
self.create_external_user(
user=user1,
external_name="shared_github_username",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
self.create_external_user(
user=user2,
external_name="shared_github_username",
provider=ExternalProviders.GITHUB.value,
integration=self.example_integration,
)
# Scenario 1: Both groups have the same external issue key
external_issue_key = "SHARED-123"
# Create external issues for both groups
self.create_integration_external_issue(
group=group1,
key=external_issue_key,
integration=self.example_integration,
)
self.create_integration_external_issue(
group=group2,
key=external_issue_key,
integration=self.example_integration,
)
# Verify both groups are unassigned initially
assert group1.get_assignee() is None
assert group2.get_assignee() is None
# Perform the sync
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="shared_github_username",
external_issue_key=external_issue_key,
assign=True,
)
# Both groups should be assigned to their respective users
assignee1 = group1.get_assignee()
assert assignee1 is not None
assert assignee1.id == user1.id
assert assignee1.email == "test@example.com"
assignee2 = group2.get_assignee()
assert assignee2 is not None
assert assignee2.id == user2.id
assert assignee2.email == "user2@example.com"
mock_record_event.assert_called_with(EventLifecycleOutcome.SUCCESS, None, False, None)
# Scenario 2: Only one group has a different external issue
group3 = self.create_group(project=self.project)
group4 = self.create_group(project=project2)
unique_issue_key = "UNIQUE-456"
# Only create external issue for group3 (user1's group)
self.create_integration_external_issue(
group=group3,
key=unique_issue_key,
integration=self.example_integration,
)
# group4 does NOT have this external issue
# Verify both are unassigned initially
assert group3.get_assignee() is None
assert group4.get_assignee() is None
# Perform the sync with the unique issue key
sync_group_assignee_inbound_by_external_actor(
integration=self.example_integration,
external_user_name="shared_github_username",
external_issue_key=unique_issue_key,
assign=True,
)
# Only group3 should be assigned (to user1)
assignee3 = group3.get_assignee()
assert assignee3 is not None
assert assignee3.id == user1.id
# group4 should remain unassigned
assert group4.get_assignee() is None
| TestSyncAssigneeInboundByExternalActor |
python | getsentry__sentry | src/sentry/preprod/models.py | {
"start": 18244,
"end": 20657
} | class ____(DefaultFieldsModel):
"""
Represents a size comparison between two preprod artifact size analyses.
This is created when a user manually compares builds or when Git based comparisons are run.
"""
__relocation_scope__ = RelocationScope.Excluded
head_size_analysis = FlexibleForeignKey(
"preprod.PreprodArtifactSizeMetrics",
on_delete=models.CASCADE,
related_name="size_comparisons_head_size_analysis",
)
base_size_analysis = FlexibleForeignKey(
"preprod.PreprodArtifactSizeMetrics",
on_delete=models.CASCADE,
related_name="size_comparisons_base_size_analysis",
)
organization_id = BoundedBigIntegerField(db_index=True)
# File id of the size diff json in filestore
file_id = BoundedBigIntegerField(db_index=True, null=True)
class State(IntEnum):
PENDING = 0
"""The comparison has not started yet."""
PROCESSING = 1
"""The comparison is in progress."""
SUCCESS = 2
"""The comparison completed successfully."""
FAILED = 3
"""The comparison failed. See error_code and error_message for details."""
@classmethod
def as_choices(cls) -> tuple[tuple[int, str], ...]:
return (
(cls.PENDING, "pending"),
(cls.PROCESSING, "processing"),
(cls.SUCCESS, "success"),
(cls.FAILED, "failed"),
)
# The state of the comparison
state = BoundedPositiveIntegerField(
default=State.PENDING,
choices=State.as_choices(),
)
class ErrorCode(IntEnum):
UNKNOWN = 0
"""The error code is unknown. Try to use a descriptive error code if possible."""
TIMEOUT = 1
"""The size analysis comparison timed out."""
@classmethod
def as_choices(cls) -> tuple[tuple[int, str], ...]:
return (
(cls.UNKNOWN, "unknown"),
(cls.TIMEOUT, "timeout"),
)
# Set when state is FAILED
error_code = BoundedPositiveIntegerField(choices=ErrorCode.as_choices(), null=True)
error_message = models.TextField(null=True)
class Meta:
app_label = "preprod"
db_table = "sentry_preprodartifactsizecomparison"
unique_together = ("organization_id", "head_size_analysis", "base_size_analysis")
| PreprodArtifactSizeComparison |
python | Delgan__loguru | loguru/_file_sink.py | {
"start": 2487,
"end": 5093
} | class ____:
@staticmethod
def forward_day(t):
return t + datetime.timedelta(days=1)
@staticmethod
def forward_weekday(t, weekday):
while True:
t += datetime.timedelta(days=1)
if t.weekday() == weekday:
return t
@staticmethod
def forward_interval(t, interval):
return t + interval
@staticmethod
def rotation_size(message, file, size_limit):
file.seek(0, 2)
return file.tell() + len(message) > size_limit
class RotationTime:
def __init__(self, step_forward, time_init=None):
self._step_forward = step_forward
self._time_init = time_init
self._limit = None
def __call__(self, message, file):
record_time = message.record["time"]
if self._limit is None:
filepath = os.path.realpath(file.name)
creation_time = get_ctime(filepath)
set_ctime(filepath, creation_time)
start_time = datetime.datetime.fromtimestamp(
creation_time, tz=datetime.timezone.utc
)
time_init = self._time_init
if time_init is None:
limit = start_time.astimezone(record_time.tzinfo).replace(tzinfo=None)
limit = self._step_forward(limit)
else:
tzinfo = record_time.tzinfo if time_init.tzinfo is None else time_init.tzinfo
limit = start_time.astimezone(tzinfo).replace(
hour=time_init.hour,
minute=time_init.minute,
second=time_init.second,
microsecond=time_init.microsecond,
)
if limit <= start_time:
limit = self._step_forward(limit)
if time_init.tzinfo is None:
limit = limit.replace(tzinfo=None)
self._limit = limit
if self._limit.tzinfo is None:
record_time = record_time.replace(tzinfo=None)
if record_time >= self._limit:
while self._limit <= record_time:
self._limit = self._step_forward(self._limit)
return True
return False
class RotationGroup:
def __init__(self, rotations) -> None:
self._rotations = rotations
def __call__(self, message, file) -> bool:
return any(rotation(message, file) for rotation in self._rotations)
| Rotation |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/bind_override.py | {
"start": 158,
"end": 494
} | class ____(Widget, can_focus=True):
BINDINGS = [
Binding("space", "app.bell", "Bell (Widget)"),
Binding("a", "app.notify('a widget')", "widget"),
Binding("b", "app.notify('b widget')", "widget"),
]
DEFAULT_CSS = """
MyWidget {
border: solid green;
height: 5;
}
"""
| MyWidget |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/matmul_op_test.py | {
"start": 5162,
"end": 7824
} | class ____(test_lib.TestCase):
pass # Will be filled in below.
def _GetMatMulGradientTest(a_np_, b_np_, use_static_shape_, **kwargs_):
@test_util.run_without_tensor_float_32("Tests matmul")
def Test(self):
if not use_static_shape_ or a_np_.dtype in (np.int32, np.int64, np.float16):
self.skipTest("Skipping infeasible gradient test.")
if (a_np_.dtype == dtypes.bfloat16.as_numpy_dtype and
not test_util.is_gpu_available()):
self.skipTest("The bfloat16 tests might fail on CPU")
# Transpose and possibly conjugate a_np_ and b_np_ according to the
# attributes such that tf.matmul(effective_a_np, effective_b_np, **kwargs)
# results in a valid matrix multiplication and produces the same result as
# np.matrix(a_np_) * np.matrix(b_np_)
effective_a_np = _GetTransposedMatrices(a_np_, "a", kwargs_)
effective_b_np = _GetTransposedMatrices(b_np_, "b", kwargs_)
# np.finfo doesn't support bfloat16. So, we manually compute the eps which
# defines the difference between 1.0 and the next smallest representable
# float larger than 1.0. For bfloat16, the difference is 1/128.
if a_np_.dtype == dtypes.bfloat16.as_numpy_dtype:
epsilon = 0.0078125
else:
epsilon = np.finfo(a_np_.dtype).eps
delta = epsilon**(1.0 / 3.0)
tol = 20 * delta
with self.session():
theoretical, numerical = gradient_checker_v2.compute_gradient(
lambda x: math_ops.matmul(x, effective_b_np, **kwargs_),
[effective_a_np],
delta=delta)
self.assertAllClose(theoretical, numerical, rtol=tol, atol=tol)
theoretical, numerical = gradient_checker_v2.compute_gradient(
lambda x: math_ops.matmul(effective_a_np, x, **kwargs_),
[effective_b_np],
delta=delta)
self.assertAllClose(theoretical, numerical, rtol=tol, atol=tol)
return Test
try:
# @ operator supported since python 3.5.
infix_matmul = operator.matmul
except AttributeError:
# For earlier versions of python, emulate regular behavior.
# Useful to build and test for 3.5+ on earlier versions.
def infix_matmul(x, y): # pylint: disable=invalid-name
try:
r = type(x).__matmul__(x, y)
except AttributeError:
r = NotImplemented
if r is NotImplemented and type(x) is not type(y):
try:
r = type(y).__rmatmul__(y, x)
except AttributeError:
r = NotImplemented
if r is NotImplemented:
raise TypeError("unsupported operand type(s) for @: '{}' and '{}'"
.format(type(x).__name__, type(y).__name__))
return r
@test_util.with_eager_op_as_function
| MatMulGradientTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-array-hopping-score-i.py | {
"start": 50,
"end": 369
} | class ____(object):
def maxScore(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = mx = 0
for i in reversed(xrange(1, len(nums))):
mx = max(mx, nums[i])
result += mx
return result
# Time: O(n^2)
# Space: O(n)
# dp
| Solution |
python | Textualize__textual | docs/examples/app/question_title02.py | {
"start": 126,
"end": 800
} | class ____(App[str]):
CSS_PATH = "question02.tcss"
TITLE = "A Question App"
SUB_TITLE = "The most important question"
def compose(self) -> ComposeResult:
yield Header()
yield Label("Do you love Textual?", id="question")
yield Button("Yes", id="yes", variant="primary")
yield Button("No", id="no", variant="error")
def on_button_pressed(self, event: Button.Pressed) -> None:
self.exit(event.button.id)
def on_key(self, event: Key):
self.title = event.key
self.sub_title = f"You just pressed {event.key}!"
if __name__ == "__main__":
app = MyApp()
reply = app.run()
print(reply)
| MyApp |
python | ray-project__ray | python/ray/_common/usage/usage_lib.py | {
"start": 2697,
"end": 2933
} | class ____:
total_num_cpus: Optional[int] = None
total_num_gpus: Optional[int] = None
total_memory_gb: Optional[float] = None
total_object_store_memory_gb: Optional[float] = None
@dataclass(init=True)
| ClusterStatusToReport |
python | huggingface__transformers | src/transformers/models/gemma2/modular_gemma2.py | {
"start": 13907,
"end": 16603
} | class ____(GemmaAttention):
def __init__(self, config: Gemma2Config, layer_idx: int):
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
super().__init__(config, layer_idx)
self.attn_logit_softcapping = self.config.attn_logit_softcapping
self.attention_dropout = self.config.attention_dropout
self.is_causal = not getattr(config, "use_bidirectional_attention", False)
self.scaling = config.query_pre_attn_scalar**-0.5
self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=self.attention_dropout if self.training else 0.0,
scaling=self.scaling,
sliding_window=self.sliding_window,
softcap=self.attn_logit_softcapping,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
| Gemma2Attention |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingLiteralMember1.py | {
"start": 388,
"end": 459
} | class ____:
kind: str
kind_class: str
c: int
is_a: bool
| C |
python | walkccc__LeetCode | solutions/1632. Rank Transform of a Matrix/1632.py | {
"start": 575,
"end": 1570
} | class ____:
def matrixRankTransform(self, matrix: list[list[int]]) -> list[list[int]]:
m = len(matrix)
n = len(matrix[0])
ans = [[0] * n for _ in range(m)]
# {val: [(i, j)]}
valToGrids = collections.defaultdict(list)
# rank[i] := the maximum rank of the row or column so far
maxRankSoFar = [0] * (m + n)
for i, row in enumerate(matrix):
for j, val in enumerate(row):
valToGrids[val].append((i, j))
for _, grids in sorted(valToGrids.items()):
uf = UnionFind()
for i, j in grids:
# Union i-th row with j-th col.
uf.union(i, j + m)
for values in uf.getGroupIdToValues().values():
# Get the maximum rank of all the included rows and columns.
maxRank = max(maxRankSoFar[i] for i in values)
for i in values:
# Update all the rows and columns to maxRank + 1.
maxRankSoFar[i] = maxRank + 1
for i, j in grids:
ans[i][j] = maxRankSoFar[i]
return ans
| Solution |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 37685,
"end": 73064
} | class ____(UserDefinedVariable):
"""
Mostly objects of defined type. Catch-all for something where we only know the type.
"""
_nonvar_fields = {
"value",
"value_type",
"attrs_directly_modifed_on_dict",
*UserDefinedVariable._nonvar_fields,
}
def __init__(
self,
value,
*,
value_type=None,
cls_source=None,
base_cls_vt=None,
init_args=None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.value = value
self.value_type = value_type or type(value)
assert type(value) is self.value_type
# This is used with __new__, when the new object is sourceless but the user class can be sourceful.
self.cls_source = cls_source
if cls_source is None and self.source is not None:
self.cls_source = TypeSource(self.source)
# These attributes are used to reconstruct the user defined object. The
# pseudo code looks like this. Builtin C __new__ do not support kwargs,
# so init_args is sufficient.
# obj = base_cls.__new__(user_cls, *args)
self.base_cls_vt = base_cls_vt
self.init_args = init_args
# This records names of the attributes that were modified via instance
# `__dict__` directly, rather than the normal setattr path.
#
# TODO consider emulating `obj.__dict__` as a `ConstDictVariable` to get
# rid of these workarounds here and in `GetAttrVariable`.
self.attrs_directly_modifed_on_dict = set()
import torch.utils._pytree as pytree
self.is_pytree_constant_class = pytree.is_constant_class(self.value_type)
if pytree.is_constant_class(self.value_type) and self.source:
install_guard(self.source.make_guard(GuardBuilder.EQUALS_MATCH))
def __str__(self) -> str:
inner = self.value_type.__name__
if inner in [
"builtin_function_or_method",
"getset_descriptor",
"method_descriptor",
"method",
]:
inner = str(getattr(self.value, "__name__", None))
return f"{self.__class__.__name__}({inner})"
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.value_type.__name__})"
def is_underlying_vt_modified(self, side_effects):
return False
def python_type(self):
return self.value_type
def as_python_constant(self):
if self.is_pytree_constant_class and self.source:
# NOTE pytree constants created in the torch.compile region will
# NOT be guarded (even though they have a source set)
return self.value
# TODO else try reconstructing the object by, e.g., leveraging side
# effects and `as_python_constant`.
return super().as_python_constant()
def guard_as_python_constant(self):
if self.source:
install_guard(self.source.make_guard(GuardBuilder.ID_MATCH))
return self.value
return super().guard_as_python_constant()
def torch_function_check(self):
assert has_torch_function(self), (
f"calling torch function on object without __torch_function__ {self}"
)
def get_torch_fn(self, tx):
self.torch_function_check()
from .torch_function import get_torch_function_fn
return get_torch_function_fn(tx, self)
def call_torch_function(self, tx: "InstructionTranslator", fn, types, args, kwargs):
self.torch_function_check()
from .torch_function import call_torch_function
return call_torch_function(
tx,
self.get_torch_fn(tx),
fn,
types,
args,
kwargs,
)
@staticmethod
@functools.cache
def _supported_random_functions():
fns = {
random.random,
random.randint,
random.randrange,
random.uniform,
}
return fns
def _maybe_get_baseclass_method(self, name):
if name not in getattr(self.value, "__dict__", {}):
try:
return inspect.getattr_static(type(self.value), name)
except AttributeError:
pass
return None
def call_method(
self,
tx,
name,
args: "list[VariableTracker]",
kwargs: "dict[str, VariableTracker]",
) -> "VariableTracker":
from . import ConstantVariable, UserMethodVariable
method = self._maybe_get_baseclass_method(name)
if method is not None:
if method is object.__init__:
return ConstantVariable.create(None)
if is_standard_setattr(method) or isinstance(self.value, threading.local):
return self.method_setattr_standard(tx, *args, **kwargs)
if is_standard_delattr(method):
return self.method_setattr_standard(
tx, args[0], variables.DeletedVariable()
)
if method is object.__eq__ and len(args) == 1 and not kwargs:
other = args[0]
if not isinstance(other, UserDefinedObjectVariable):
return variables.ConstantVariable.create(NotImplemented)
# TODO(anijain2305) - Identity checking should already be a part
# of the cmp_eq polyfill function.
return ConstantVariable.create(self.value is other.value)
if torch._dynamo.config.enable_faithful_generator_behavior and isinstance(
self.value, types.GeneratorType
):
unimplemented(
gb_type="call_method on generator",
context=f"object={self.value}, method={name}, args={args}, kwargs={kwargs}",
explanation="Detected a method call to a user-defined generator object. "
"This is not fully supported.",
hints=[
"Set `torch._dynamo.config.enable_faithful_generator_behavior = False`. Note that this "
"may cause silent incorrectness, since we will eagerly unpack generators instead of lazily "
"evaluating them.",
],
)
# check for methods implemented in C++
if isinstance(method, types.FunctionType):
source = self.source
source_fn = None
if source:
source_fn = self.get_source_by_walking_mro(name)
# TODO(jansel): add a guard to check for monkey patching?
from ..mutation_guard import unpatched_nn_module_init
if method is torch.nn.Module.__init__:
method = unpatched_nn_module_init
return UserMethodVariable(
method, self, source_fn=source_fn, source=source
).call_function(tx, args, kwargs)
if method is list.__len__ and self.source and not (args or kwargs):
install_guard(self.source.make_guard(GuardBuilder.SEQUENCE_LENGTH))
return ConstantVariable(len(self.value))
return super().call_method(tx, name, args, kwargs)
def method_setattr_standard(
self, tx: "InstructionTranslator", name, value, directly_update_dict=False
):
try:
name = name.as_python_constant()
except NotImplementedError:
unimplemented(
gb_type="non-const setattr name on user-defined object",
context=f"object={self}, name={name}, value={value}",
explanation="Detected a call to `setattr` of a user-defined object with a non-constant name.",
hints=["Ensure that the name is a string."],
)
assert tx.output.side_effects.is_attribute_mutation(self), (
"Attempted setattr on a user-defined object that does not have "
"an AttributeMutation mutation_type"
)
if directly_update_dict:
self.attrs_directly_modifed_on_dict.add(name)
else:
tmp = self.try_get_descritor_and_setter_py_func(name)
if tmp:
descriptor, setter = tmp
# Emulate
# https://github.com/python/cpython/blob/3.11/Objects/object.c#L1371-L1452
desc_source = None
func_source = None
if self.cls_source:
desc_source = self.get_source_by_walking_mro(name)
# use `type(...)` to ignore instance attrs.
func_source = AttrSource(TypeSource(desc_source), "__set__")
desc_var = VariableTracker.build(tx, descriptor, desc_source)
func_var = VariableTracker.build(tx, setter, func_source)
args = [desc_var, self, value]
return func_var.call_function(tx, args, {})
# NOTE: else we assume the descriptor (if any) has a
# side-effect-free `__set__` as far as Dynamo tracing is concerned.
# Emulate the standard setattr on instance dict.
tx.output.side_effects.store_attr(self, name, value)
return variables.ConstantVariable(None)
def needs_slow_setattr(self):
return not is_standard_setattr(
inspect.getattr_static(self.value, "__setattr__", None)
) and not isinstance(self.value, threading.local)
def unpack_var_sequence(self, tx):
if (
self.source
and self._maybe_get_baseclass_method("__iter__") is list.__iter__
and self._maybe_get_baseclass_method("__len__") is list.__len__
and self._maybe_get_baseclass_method("__getitem__") is list.__getitem__
):
install_guard(self.source.make_guard(GuardBuilder.SEQUENCE_LENGTH))
return [
variables.LazyVariableTracker.create(
self.value[k],
source=GetItemSource(self.source, k),
)
for k in range(len(self.value))
]
return super().unpack_var_sequence(tx)
def has_force_unpack_var_sequence(self, tx: "InstructionTranslator") -> bool:
try:
variables.BuiltinVariable(iter).call_function(tx, [self], {})
return True
except ObservedTypeError:
handle_observed_exception(tx)
return False
def force_unpack_var_sequence(self, tx):
result = []
iter_ = variables.BuiltinVariable(iter).call_function(tx, [self], {})
while True:
try:
r = iter_.next_variable(tx)
result.append(r)
except ObservedUserStopIteration:
handle_observed_exception(tx)
break
return result
def next_variable(self, tx):
return self.call_method(tx, "__next__", [], {})
def is_supported_random(self):
try:
return self.value in self._supported_random_functions()
except TypeError:
# TypeError: unhashable type
return False
def call_function(
self,
tx: "InstructionTranslator",
args: "list[VariableTracker]",
kwargs: "dict[str, VariableTracker]",
) -> "VariableTracker":
if (
self.is_supported_random()
and all(k.is_python_constant() for k in args)
and all(v.is_python_constant() for v in kwargs.values())
):
return call_random_fn(tx, self.value, args, kwargs)
elif istype(self.value, types.MethodType):
func = self.value.__func__
obj = self.value.__self__
if (
func is torch.utils._contextlib._DecoratorContextManager.clone
and variables.TorchCtxManagerClassVariable.is_matching_cls(
obj.__class__
)
and not (args or kwargs)
):
return variables.TorchCtxManagerClassVariable(
obj.__class__
).call_function(tx, args, kwargs)
if (
func is torch.autograd.grad_mode.inference_mode.clone
and obj.__class__ is torch.autograd.grad_mode.inference_mode
):
# simulate the inference_mode.clone implementation
var = variables.ConstantVariable(obj.mode)
return variables.TorchCtxManagerClassVariable(
obj.__class__
).call_function(tx, [var], kwargs)
if self.source is None:
unimplemented(
gb_type="attempted to call sourceless user-defined object as a method",
context=f"object={self.value}, function={func}, args={args}, kwargs={kwargs}",
explanation="Dynamo does not support this.",
hints=[
f"Ensure the user-defined object {self.value} is constructed outside the compiled region.",
],
)
func_src = AttrSource(self.source, "__func__")
func_var = VariableTracker.build(tx, func, func_src)
obj_src = AttrSource(self.source, "__self__")
obj_var = VariableTracker.build(tx, obj, obj_src)
return func_var.call_function(tx, [obj_var] + args, kwargs)
elif callable(self.value):
if self.source:
source = AttrSource(self.cls_source, "__call__")
install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH))
return self.call_method(tx, "__call__", args, kwargs)
return super().call_function(tx, args, kwargs)
def _check_for_getattr(self):
return get_custom_getattr(self.value)
def _is_c_defined_property(self, subobj):
if not isinstance(subobj, property):
return False
# pybind def_readwrite is implemented via PyCFunction. At the python level, it is visible as a property whose
# fget is an instancemethod wrapper - https://docs.python.org/3/c-api/method.html#c.PyInstanceMethod_Check
# If we have a PyCFunction, we make an assumption that there is no side effect.
return isinstance(
subobj.fget, types.BuiltinFunctionType
) or torch._C._dynamo.utils.is_instancemethod(subobj.fget)
def _getattr_static(self, name):
subobj = inspect.getattr_static(self.value, name, NO_SUCH_SUBOBJ)
# In some cases, we have to do dynamic lookup because getattr_static is not enough. For example, threading.local
# has side-effect free __getattribute__ and the attribute is not visible without a dynamic lookup.
# NOTE we assume the following descriptors are side-effect-free as far
# as Dynamo tracing is concerned.
if not object_has_getattribute(self.value) and (
subobj is NO_SUCH_SUBOBJ # e.g., threading.local
or inspect.ismemberdescriptor(subobj) # e.g., __slots__
or inspect.isgetsetdescriptor(subobj) # e.g., __dict__
or self._is_c_defined_property(subobj)
):
# Call __getattribute__, we have already checked that this is not overridden and side-effect free. We don't
# want to call getattr because it can be user-overridden.
subobj = type(self.value).__getattribute__(self.value, name)
elif object_has_getattribute(self.value) and subobj is NO_SUCH_SUBOBJ:
# If the object has an overridden getattribute method, Dynamo has
# already tried tracing it, and encountered an AttributeError. We
# call getattr_static only when the __getattribute__ tracing fails
# (check var_getattr impl). So, it is safe here to raise the
# AttributeError.
raise AttributeError
return subobj
def should_skip_descriptor_setter(self, attr_name):
# Check if `attr_name` corresponds to a descriptor.
descriptor = inspect.getattr_static(type(self.value), attr_name, None)
setter = inspect.getattr_static(type(descriptor), "__set__", None)
if setter:
# Skip if `__set__` was traceable (no need to redo the side effect).
if inspect.isfunction(setter):
return True
# For untraceable `__set__` we should still skip if the attribute
# was mutated via instance `__dict__`.
elif attr_name in self.attrs_directly_modifed_on_dict:
return True
return False
def try_get_descritor_and_setter_py_func(self, attr_name):
descriptor = inspect.getattr_static(type(self.value), attr_name, None)
setter = inspect.getattr_static(type(descriptor), "__set__", None)
if inspect.isfunction(setter):
return (descriptor, setter)
return None
def has_key_in_generic_dict(self, tx: "InstructionTranslator", key):
if tx.output.side_effects.has_pending_mutation_of_attr(self, key):
mutated_attr = tx.output.side_effects.load_attr(self, key, deleted_ok=True)
return not isinstance(mutated_attr, variables.DeletedVariable)
return key in self.value.__dict__
def get_source_by_walking_mro(self, name):
assert self.cls_source is not None
for idx, klass in enumerate(type(self.value).__mro__):
if name in klass.__dict__:
if idx != 0:
mro_source = TypeMROSource(self.cls_source)
klass_source = GetItemSource(mro_source, idx)
else:
klass_source = self.cls_source
dict_source = TypeDictSource(klass_source)
out_source = DictGetItemSource(dict_source, name)
for absent_idx in range(1, idx):
# Insert a guard that the name is not present in the mro hierarchy
mro_source = TypeMROSource(self.cls_source)
klass_source = GetItemSource(mro_source, absent_idx)
dict_source = TypeDictSource(klass_source)
install_guard(
dict_source.make_guard(
functools.partial(
GuardBuilder.DICT_CONTAINS, key=name, invert=True
)
)
)
# Insert a guard that the name is not present in the object __dict__
if (
self.source
and hasattr(self.value, "__dict__")
and name not in self.value.__dict__
):
install_guard(
self.source.make_guard(
functools.partial(
GuardBuilder.NOT_PRESENT_IN_GENERIC_DICT, attr=name
)
)
)
return out_source
unimplemented(
gb_type="could not find name in object's mro",
context=f"name={name}, object type={type(self.value)}, mro={type(self.value).__mro__}",
explanation=f"Could not find name `{name}` in mro {type(self.value).__mro__}",
hints=[
f"Ensure the name `{name}` is defined somewhere in {self.value}'s type hierarchy.",
*graph_break_hints.USER_ERROR,
],
)
def var_getattr(self, tx: "InstructionTranslator", name):
from . import ConstantVariable
source = AttrSource(self.source, name) if self.source else None
if object_has_getattribute(self.value):
getattribute_fn = inspect.getattr_static(
type(self.value), "__getattribute__"
)
if self.source:
new_source = AttrSource(self.source, "__getattribute__")
try:
return variables.UserMethodVariable(
getattribute_fn, self, source=new_source
).call_function(tx, [ConstantVariable.create(name)], {})
except ObservedAttributeError:
# Pass through to __getattr__ if __getattribute__ fails
handle_observed_exception(tx)
if tx.output.side_effects.has_pending_mutation_of_attr(self, name):
result = tx.output.side_effects.load_attr(self, name, deleted_ok=True)
if isinstance(result, variables.DeletedVariable):
raise_observed_exception(
AttributeError,
tx,
msg=f"'{type(self.value).__name__}' object has no attribute '{name}'",
)
return result
if name == "__dict__":
options = {"source": source}
return variables.GetAttrVariable(self, name, **options)
# TODO(anijain2305) - Investigate if we need specialization for more
# dunder attrs. inspect.getattr_static does not return correct value for
# them.
if name == "__class__":
cls_source = source
if cls_source is None:
cls_source = self.cls_source
options = {"source": cls_source}
return UserDefinedClassVariable(type(self.value), **options)
try:
subobj = self._getattr_static(name)
except AttributeError:
subobj = NO_SUCH_SUBOBJ
getattr_fn = self._check_for_getattr()
if isinstance(getattr_fn, types.FunctionType):
# Dynamo is going to trace the __getattr__ function with
# args=name. Set the source accordingly.
if (
getattr_fn is unpatched_nn_module_getattr
and isinstance(self, variables.UnspecializedNNModuleVariable)
# prevent against overwriting of params/buffers/submodules
and istype(self.value._parameters, dict)
and istype(self.value._buffers, dict)
and istype(self.value._modules, dict)
):
# Manually trace out the nn module __getattr__ to avoid large compilation latency.
out = self.manually_trace_nn_module_getattr(tx, name)
else:
new_source = None
if self.source:
new_source = AttrSource(self.source, "__getattr__")
out = variables.UserMethodVariable(
getattr_fn, self, source=new_source
).call_function(tx, [ConstantVariable.create(name)], {})
if self.source and getattr_fn is torch.nn.Module.__getattr__:
if isinstance(
out,
(
variables.UnspecializedNNModuleVariable,
variables.NNModuleVariable,
),
):
# nn_module_stack source is BC surface area. Ensure that
# mod._modules["linear"] is reflected as mod.linear for
# nn_module_stack.
out.set_nn_module_stack_source(
AttrSource(self.get_nn_module_stack_source(), name)
)
return out
elif getattr_fn is not None:
unimplemented(
gb_type="User-defined object with non-function __getattr__",
context=f"object={self.value}, name={name}, getattr_fn={getattr_fn}",
explanation=f"Found a non-function __getattr__ {getattr_fn} from a user-defined object {self.value} "
f" when attempting to getattr `{name}`",
hints=[
"Ensure the object's __getattr__ is a function type.",
],
)
from ..mutation_guard import unpatched_nn_module_init
if subobj is torch.nn.Module.__init__:
subobj = unpatched_nn_module_init
subobj_from_class = inspect.getattr_static(
self.value.__class__, name, NO_SUCH_SUBOBJ
)
is_accessible_from_type_mro = (
subobj_from_class is subobj
and self.cls_source is not None
and self.source is not None
and hasattr(self.value, "__dict__")
and name not in self.value.__dict__
)
if isinstance(subobj, property):
if self.source:
# Read the class attribute to reach the property
source = self.get_source_by_walking_mro(name)
# Get the getter function
source = AttrSource(source, "fget")
fget_vt = VariableTracker.build(tx, subobj.fget, source=source)
return fget_vt.call_function(tx, [self], {})
elif isinstance(subobj, _collections._tuplegetter):
# namedtuple fields are represented by _tuplegetter, and here we
# emulate its `__get__`, which is implemented in C.
_, (idx, _) = subobj.__reduce__()
# Don't go through the `__getitem__` method anymore, see
# https://github.com/python/cpython/blob/470941782f74288823b445120f6383914b659f23/Modules/_collectionsmodule.c#L2690
assert isinstance(self, UserDefinedTupleVariable)
return self._tuple_vt.items[idx]
elif isinstance(subobj, staticmethod):
# Safe because `staticmethod.__get__` basically won't trigger user
# code and just returns the underlying `__func__`:
# https://github.com/python/cpython/blob/3.11/Objects/funcobject.c#L1088-L1100
if is_accessible_from_type_mro:
# Accessing from __dict__ does not resolve the descriptor, it
# returns a staticmethod object, so access the __func__
# attribute to get to the actual function.
source = AttrSource(self.get_source_by_walking_mro(name), "__func__")
func = subobj.__get__(self.value)
return VariableTracker.build(tx, func, source)
elif isinstance(subobj, classmethod):
source_fn = None
if is_accessible_from_type_mro:
# Accessing from __dict__ does not resolve the descriptor, it
# returns a classmethod object, so access the __func__
# attribute to get to the actual function.
source_fn = AttrSource(self.get_source_by_walking_mro(name), "__func__")
return variables.UserMethodVariable(
subobj.__func__,
self.var_getattr(tx, "__class__"),
source_fn=source_fn,
source=source,
)
elif isinstance(subobj, types.ClassMethodDescriptorType):
# e.g.: inspect.getattr_static({}, "fromkeys")
func = subobj.__get__(self.value, None)
return VariableTracker.build(tx, func, source)
elif is_lru_cache_wrapped_function(subobj):
# getattr_static returns the lru_wrapped function, and we cannot
# extract the underlying method from the wrapped function. To handle
# it, manually create a wrapped user method vt.
return variables.WrapperUserMethodVariable(
subobj, "__wrapped__", self, source=source
)
elif inspect.getattr_static(
type(subobj), "__get__", NO_SUCH_SUBOBJ
) is not NO_SUCH_SUBOBJ and not is_wrapper_or_member_descriptor(
type(subobj).__get__
):
# Emulate https://github.com/python/cpython/blob/3.11/Objects/object.c#L1271-L1285
#
# Attribute has a __get__ method. Create a user defined object vt
# for the subobj, and then trace the __get__ method.
descriptor_source = None
descriptor_get_source = None
if self.cls_source:
# To access the method descriptor from the udf object w/o using
# inspect.getattr_static, we can look into the class mro
descriptor_source = self.get_source_by_walking_mro(name)
descriptor_get_source = AttrSource(
TypeSource(descriptor_source), "__get__"
)
descriptor_var = VariableTracker.build(tx, subobj, descriptor_source)
else:
# Sourceless Builder does not support user defined objects
descriptor_var = UserDefinedObjectVariable(subobj)
# The arguments of the __get__ function are (self, instance, owner)
# self - descriptor_var
# instance - instance of the class, represented by self here
# owner - class object
owner_var = UserDefinedClassVariable(type(self.value))
return variables.UserMethodVariable(
subobj.__get__.__func__, descriptor_var, source=descriptor_get_source
).call_function(tx, [self, owner_var], {})
elif isinstance(subobj, types.FunctionType) or (
isinstance(subobj, types.MethodType)
and isinstance(self.value, torch.nn.Module)
):
# Since we get subobj via self._getattr_static, which may not trigger dynamic lookup.
# Static lookup can't tell us it's a method or function correctly,
# so we trigger dynamic lookup here to get the correct type.
dynamic_subobj = getattr(self.value, name)
while dynamic_subobj is subobj and hasattr(subobj, "_torchdynamo_inline"):
subobj = subobj._torchdynamo_inline
dynamic_subobj = subobj
source = AttrSource(source, "_torchdynamo_inline") if source else None
if isinstance(subobj, types.MethodType):
if dynamic_subobj.__self__ is not self.value:
if not isinstance(dynamic_subobj.__func__, types.FunctionType):
unimplemented(
gb_type="User-defined object method with non-function __func__",
context=f"object={self.value}, name={name}, method={dynamic_subobj}, "
f"method.__self__={dynamic_subobj.__self__}, method.__func__={dynamic_subobj.__func__}",
explanation=f"Method {dynamic_subobj} (name={name}) of user-defined object {self.value} has a "
f"__func__ ({dynamic_subobj.__func__}) that is not a function type.",
hints=[
"Ensure that the method's __func__ is a function type.",
],
)
# Use the __self__ attribute of the method to find the
# source of the new self object.
self_source = None
if source is not None:
self_source = AttrSource(source, "__self__")
object_vt = VariableTracker.build(
tx, dynamic_subobj.__self__, self_source
)
return variables.UserMethodVariable(
dynamic_subobj.__func__, object_vt
)
func = subobj.__func__
else:
assert isinstance(subobj, types.FunctionType)
func = subobj
if inspect.ismethod(dynamic_subobj):
source_fn = None
if is_accessible_from_type_mro:
source_fn = self.get_source_by_walking_mro(name)
return variables.UserMethodVariable(
func, self, source_fn=source_fn, source=source
)
elif inspect.isfunction(dynamic_subobj):
return VariableTracker.build(tx, func, source)
if (
# wrap the source only if inline_inbuilt_nn_modules is set or fsdp modules. This is a temporary solution to
# keep Dynamo behavior compatible with no inlining, as there will be some delay to turn on the flag in
# fbcode.
(
torch._dynamo.config.inline_inbuilt_nn_modules
or isinstance(self, variables.FSDPManagedNNModuleVariable)
)
and source
and isinstance(self, variables.UnspecializedNNModuleVariable)
# export has some awkwardness around specialized and unspecialized modules. Skip wrapping source for export
# usecase for now.
and (not tx.output.export or torch._dynamo.config.install_free_tensors)
):
# Recalculate source for params/buffers
if name in ("_buffers", "_parameters"):
source = UnspecializedParamBufferSource(self.source, name)
source = self._wrap_source(source)
if subobj is not NO_SUCH_SUBOBJ:
if (
is_wrapper_or_member_descriptor(subobj)
or torch._C._dynamo.utils.is_instancemethod(subobj)
or is_cython_function(subobj)
):
options = {"source": source}
return variables.GetAttrVariable(self, name, **options)
if source:
if is_accessible_from_type_mro:
source = self.get_source_by_walking_mro(name)
return variables.LazyVariableTracker.create(subobj, source)
else:
# Check if the subobj is accessible from the class itself. If the class source is known, we can create a
# sourceful variable tracker.
if self.cls_source is not None:
subobj_from_class = inspect.getattr_static(
self.value.__class__, name, NO_SUCH_SUBOBJ
)
if subobj_from_class is subobj:
src_from_class = AttrSource(self.cls_source, name)
return variables.LazyVariableTracker.create(
subobj_from_class, src_from_class
)
return VariableTracker.build(tx, subobj)
# Earlier we were returning GetAttrVariable but its incorrect. In absence of attr, Python raises AttributeError.
raise_observed_exception(
AttributeError,
tx,
msg=f"'{type(self.value).__name__}' object has no attribute '{name}'",
)
def call_obj_hasattr(
self, tx: "InstructionTranslator", name: str
) -> "VariableTracker":
if self.source:
install_guard(
AttrSource(self.source, name).make_guard(GuardBuilder.HASATTR)
)
try:
var_vt = self.var_getattr(tx, name)
return variables.ConstantVariable.create(
not isinstance(var_vt, variables.DeletedVariable)
)
except ObservedAttributeError:
handle_observed_exception(tx)
return variables.ConstantVariable.create(False)
| UserDefinedObjectVariable |
python | redis__redis-py | redis/asyncio/cluster.py | {
"start": 67252,
"end": 72263
} | class ____(AbstractRedis, AbstractRedisCluster, AsyncRedisClusterCommands):
"""
Create a new ClusterPipeline object.
Usage::
result = await (
rc.pipeline()
.set("A", 1)
.get("A")
.hset("K", "F", "V")
.hgetall("K")
.mset_nonatomic({"A": 2, "B": 3})
.get("A")
.get("B")
.delete("A", "B", "K")
.execute()
)
# result = [True, "1", 1, {"F": "V"}, True, True, "2", "3", 1, 1, 1]
Note: For commands `DELETE`, `EXISTS`, `TOUCH`, `UNLINK`, `mset_nonatomic`, which
are split across multiple nodes, you'll get multiple results for them in the array.
Retryable errors:
- :class:`~.ClusterDownError`
- :class:`~.ConnectionError`
- :class:`~.TimeoutError`
Redirection errors:
- :class:`~.TryAgainError`
- :class:`~.MovedError`
- :class:`~.AskError`
:param client:
| Existing :class:`~.RedisCluster` client
"""
__slots__ = ("cluster_client", "_transaction", "_execution_strategy")
def __init__(
self, client: RedisCluster, transaction: Optional[bool] = None
) -> None:
self.cluster_client = client
self._transaction = transaction
self._execution_strategy: ExecutionStrategy = (
PipelineStrategy(self)
if not self._transaction
else TransactionStrategy(self)
)
async def initialize(self) -> "ClusterPipeline":
await self._execution_strategy.initialize()
return self
async def __aenter__(self) -> "ClusterPipeline":
return await self.initialize()
async def __aexit__(self, exc_type: None, exc_value: None, traceback: None) -> None:
await self.reset()
def __await__(self) -> Generator[Any, None, "ClusterPipeline"]:
return self.initialize().__await__()
def __bool__(self) -> bool:
"Pipeline instances should always evaluate to True on Python 3+"
return True
def __len__(self) -> int:
return len(self._execution_strategy)
def execute_command(
self, *args: Union[KeyT, EncodableT], **kwargs: Any
) -> "ClusterPipeline":
"""
Append a raw command to the pipeline.
:param args:
| Raw command args
:param kwargs:
- target_nodes: :attr:`NODE_FLAGS` or :class:`~.ClusterNode`
or List[:class:`~.ClusterNode`] or Dict[Any, :class:`~.ClusterNode`]
- Rest of the kwargs are passed to the Redis connection
"""
return self._execution_strategy.execute_command(*args, **kwargs)
async def execute(
self, raise_on_error: bool = True, allow_redirections: bool = True
) -> List[Any]:
"""
Execute the pipeline.
It will retry the commands as specified by retries specified in :attr:`retry`
& then raise an exception.
:param raise_on_error:
| Raise the first error if there are any errors
:param allow_redirections:
| Whether to retry each failed command individually in case of redirection
errors
:raises RedisClusterException: if target_nodes is not provided & the command
can't be mapped to a slot
"""
try:
return await self._execution_strategy.execute(
raise_on_error, allow_redirections
)
finally:
await self.reset()
def _split_command_across_slots(
self, command: str, *keys: KeyT
) -> "ClusterPipeline":
for slot_keys in self.cluster_client._partition_keys_by_slot(keys).values():
self.execute_command(command, *slot_keys)
return self
async def reset(self):
"""
Reset back to empty pipeline.
"""
await self._execution_strategy.reset()
def multi(self):
"""
Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`.
"""
self._execution_strategy.multi()
async def discard(self):
""" """
await self._execution_strategy.discard()
async def watch(self, *names):
"""Watches the values at keys ``names``"""
await self._execution_strategy.watch(*names)
async def unwatch(self):
"""Unwatches all previously specified keys"""
await self._execution_strategy.unwatch()
async def unlink(self, *names):
await self._execution_strategy.unlink(*names)
def mset_nonatomic(
self, mapping: Mapping[AnyKeyT, EncodableT]
) -> "ClusterPipeline":
return self._execution_strategy.mset_nonatomic(mapping)
for command in PIPELINE_BLOCKED_COMMANDS:
command = command.replace(" ", "_").lower()
if command == "mset_nonatomic":
continue
setattr(ClusterPipeline, command, block_pipeline_command(command))
| ClusterPipeline |
python | walkccc__LeetCode | solutions/401. Binary Watch/401-2.py | {
"start": 0,
"end": 244
} | class ____:
def readBinaryWatch(self, turnedOn: int) -> list[str]:
ans = []
for h in range(12):
for m in range(60):
if h.bit_count() + m.bit_count() == turnedOn:
ans.append(f'{h}:{m:02d}')
return ans
| Solution |
python | ansible__ansible | lib/ansible/_internal/_templating/_access.py | {
"start": 174,
"end": 1199
} | class ____(metaclass=abc.ABCMeta):
"""Base class for a context manager that, when active, receives notification of managed access for types/tags in which it has registered an interest."""
_type_interest: t.FrozenSet[type] = frozenset()
"""Set of types (including tag types) for which this context will be notified upon access."""
_mask: t.ClassVar[bool] = False
"""When true, only the innermost (most recently created) context of this type will be notified."""
def __enter__(self):
# noinspection PyProtectedMember
AnsibleAccessContext.current()._register_interest(self)
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
# noinspection PyProtectedMember
AnsibleAccessContext.current()._unregister_interest(self)
return None
@abc.abstractmethod
def _notify(self, o: t.Any) -> t.Any:
"""Derived classes implement custom notification behavior when a registered type or tag is accessed."""
| NotifiableAccessContextBase |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 64176,
"end": 65115
} | class ____(TestCase):
def setUp(self):
self.poll = PollWithExcludedFieldsWithDefaults.objects.create(
question="what's up?", pub_date=today, max_questions=12
)
self.historical = self.poll.history.order_by("pk")[0]
self.poll.delete()
def test_restore_deleted_poll_exclude_fields(self):
original = self.historical.instance
# pub_date don't have default value so it will be None
self.assertIsNone(original.pub_date)
# same for max_questions
self.assertIsNone(original.max_questions)
def test_restore_deleted_poll_exclude_fields_with_defaults(self):
poll = self.poll
original = self.historical.instance
self.assertEqual(original.expiration_time, poll.expiration_time)
self.assertEqual(original.place, poll.place)
self.assertEqual(original.min_questions, poll.min_questions)
| ExcludeFieldsForDeletedObjectTest |
python | davidhalter__parso | parso/python/tokenize.py | {
"start": 1385,
"end": 8263
} | class ____(NamedTuple):
pseudo_token: Pattern
single_quoted: Set[str]
triple_quoted: Set[str]
endpats: Dict[str, Pattern]
whitespace: Pattern
fstring_pattern_map: Dict[str, str]
always_break_tokens: Tuple[str]
BOM_UTF8_STRING = BOM_UTF8.decode('utf-8')
_token_collection_cache: Dict[PythonVersionInfo, TokenCollection] = {}
def group(*choices, capture=False, **kwargs):
assert not kwargs
start = '('
if not capture:
start += '?:'
return start + '|'.join(choices) + ')'
def maybe(*choices):
return group(*choices) + '?'
# Return the empty string, plus all of the valid string prefixes.
def _all_string_prefixes(*, include_fstring=False, only_fstring=False):
def different_case_versions(prefix):
for s in _itertools.product(*[(c, c.upper()) for c in prefix]):
yield ''.join(s)
# The valid string prefixes. Only contain the lower case versions,
# and don't contain any permuations (include 'fr', but not
# 'rf'). The various permutations will be generated.
valid_string_prefixes = ['b', 'r', 'u', 'br']
result = {''}
if include_fstring:
f = ['f', 'fr']
if only_fstring:
valid_string_prefixes = f
result = set()
else:
valid_string_prefixes += f
elif only_fstring:
return set()
# if we add binary f-strings, add: ['fb', 'fbr']
for prefix in valid_string_prefixes:
for t in _itertools.permutations(prefix):
# create a list with upper and lower versions of each
# character
result.update(different_case_versions(t))
return result
def _compile(expr):
return re.compile(expr, re.UNICODE)
def _get_token_collection(version_info):
try:
return _token_collection_cache[tuple(version_info)]
except KeyError:
_token_collection_cache[tuple(version_info)] = result = \
_create_token_collection(version_info)
return result
unicode_character_name = r'[A-Za-z0-9\-]+(?: [A-Za-z0-9\-]+)*'
fstring_string_single_line = _compile(
r'(?:\{\{|\}\}|\\N\{' + unicode_character_name
+ r'\}|\\(?:\r\n?|\n)|\\[^\r\nN]|[^{}\r\n\\])+'
)
fstring_string_multi_line = _compile(
r'(?:\{\{|\}\}|\\N\{' + unicode_character_name + r'\}|\\[^N]|[^{}\\])+'
)
fstring_format_spec_single_line = _compile(r'(?:\\(?:\r\n?|\n)|[^{}\r\n])+')
fstring_format_spec_multi_line = _compile(r'[^{}]+')
def _create_token_collection(version_info):
# Note: we use unicode matching for names ("\w") but ascii matching for
# number literals.
Whitespace = r'[ \f\t]*'
whitespace = _compile(Whitespace)
Comment = r'#[^\r\n]*'
Name = '([A-Za-z_0-9\u0080-' + MAX_UNICODE + ']+)'
Hexnumber = r'0[xX](?:_?[0-9a-fA-F])+'
Binnumber = r'0[bB](?:_?[01])+'
Octnumber = r'0[oO](?:_?[0-7])+'
Decnumber = r'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)'
Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
Exponent = r'[eE][-+]?[0-9](?:_?[0-9])*'
Pointfloat = group(r'[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?',
r'\.[0-9](?:_?[0-9])*') + maybe(Exponent)
Expfloat = r'[0-9](?:_?[0-9])*' + Exponent
Floatnumber = group(Pointfloat, Expfloat)
Imagnumber = group(r'[0-9](?:_?[0-9])*[jJ]', Floatnumber + r'[jJ]')
Number = group(Imagnumber, Floatnumber, Intnumber)
# Note that since _all_string_prefixes includes the empty string,
# StringPrefix can be the empty string (making it optional).
possible_prefixes = _all_string_prefixes()
StringPrefix = group(*possible_prefixes)
StringPrefixWithF = group(*_all_string_prefixes(include_fstring=True))
fstring_prefixes = _all_string_prefixes(include_fstring=True, only_fstring=True)
FStringStart = group(*fstring_prefixes)
# Tail end of ' string.
Single = r"(?:\\.|[^'\\])*'"
# Tail end of " string.
Double = r'(?:\\.|[^"\\])*"'
# Tail end of ''' string.
Single3 = r"(?:\\.|'(?!'')|[^'\\])*'''"
# Tail end of """ string.
Double3 = r'(?:\\.|"(?!"")|[^"\\])*"""'
Triple = group(StringPrefixWithF + "'''", StringPrefixWithF + '"""')
# Because of leftmost-then-longest match semantics, be sure to put the
# longest operators first (e.g., if = came before ==, == would get
# recognized as two instances of =).
Operator = group(r"\*\*=?", r">>=?", r"<<=?",
r"//=?", r"->",
r"[+\-*/%&@`|^!=<>]=?",
r"~")
Bracket = '[][(){}]'
special_args = [r'\.\.\.', r'\r\n?', r'\n', r'[;.,@]']
if version_info >= (3, 8):
special_args.insert(0, ":=?")
else:
special_args.insert(0, ":")
Special = group(*special_args)
Funny = group(Operator, Bracket, Special)
# First (or only) line of ' or " string.
ContStr = group(StringPrefix + r"'[^\r\n'\\]*(?:\\.[^\r\n'\\]*)*"
+ group("'", r'\\(?:\r\n?|\n)'),
StringPrefix + r'"[^\r\n"\\]*(?:\\.[^\r\n"\\]*)*'
+ group('"', r'\\(?:\r\n?|\n)'))
pseudo_extra_pool = [Comment, Triple]
all_quotes = '"', "'", '"""', "'''"
if fstring_prefixes:
pseudo_extra_pool.append(FStringStart + group(*all_quotes))
PseudoExtras = group(r'\\(?:\r\n?|\n)|\Z', *pseudo_extra_pool)
PseudoToken = group(Whitespace, capture=True) + \
group(PseudoExtras, Number, Funny, ContStr, Name, capture=True)
# For a given string prefix plus quotes, endpats maps it to a regex
# to match the remainder of that string. _prefix can be empty, for
# a normal single or triple quoted string (with no prefix).
endpats = {}
for _prefix in possible_prefixes:
endpats[_prefix + "'"] = _compile(Single)
endpats[_prefix + '"'] = _compile(Double)
endpats[_prefix + "'''"] = _compile(Single3)
endpats[_prefix + '"""'] = _compile(Double3)
# A set of all of the single and triple quoted string prefixes,
# including the opening quotes.
single_quoted = set()
triple_quoted = set()
fstring_pattern_map = {}
for t in possible_prefixes:
for quote in '"', "'":
single_quoted.add(t + quote)
for quote in '"""', "'''":
triple_quoted.add(t + quote)
for t in fstring_prefixes:
for quote in all_quotes:
fstring_pattern_map[t + quote] = quote
ALWAYS_BREAK_TOKENS = (';', 'import', 'class', 'def', 'try', 'except',
'finally', 'while', 'with', 'return', 'continue',
'break', 'del', 'pass', 'global', 'assert', 'nonlocal')
pseudo_token_compiled = _compile(PseudoToken)
return TokenCollection(
pseudo_token_compiled, single_quoted, triple_quoted, endpats,
whitespace, fstring_pattern_map, set(ALWAYS_BREAK_TOKENS)
)
| TokenCollection |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 243616,
"end": 245695
} | class ____(Request):
"""
Get the list of task configurations
:param tasks: Task IDs
:type tasks: Sequence[str]
:param names: Names of the configuration items to retreive. If not passed or
empty then all the configurations will be retreived.
:type names: Sequence[str]
"""
_service = "tasks"
_action = "get_configurations"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {
"names": {
"description": "Names of the configuration items to retreive. If not passed or empty then all the configurations will be retreived.",
"items": {"type": "string"},
"type": "array",
},
"tasks": {
"description": "Task IDs",
"items": {"type": "string"},
"type": "array",
},
},
"required": ["tasks"],
"type": "object",
}
def __init__(self, tasks: List[str], names: Optional[List[str]] = None, **kwargs: Any) -> None:
super(GetConfigurationsRequest, self).__init__(**kwargs)
self.tasks = tasks
self.names = names
@schema_property("tasks")
def tasks(self) -> List[str]:
return self._property_tasks
@tasks.setter
def tasks(self, value: List[str]) -> None:
if value is None:
self._property_tasks = None
return
self.assert_isinstance(value, "tasks", (list, tuple))
self.assert_isinstance(value, "tasks", six.string_types, is_array=True)
self._property_tasks = value
@schema_property("names")
def names(self) -> Optional[List[str]]:
return self._property_names
@names.setter
def names(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_names = None
return
self.assert_isinstance(value, "names", (list, tuple))
self.assert_isinstance(value, "names", six.string_types, is_array=True)
self._property_names = value
| GetConfigurationsRequest |
python | openai__openai-python | tests/api_resources/beta/threads/test_messages.py | {
"start": 508,
"end": 12498
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@parametrize
def test_method_create(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.create(
thread_id="thread_id",
content="string",
role="user",
)
assert_matches_type(Message, message, path=["response"])
@parametrize
def test_method_create_with_all_params(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.create(
thread_id="thread_id",
content="string",
role="user",
attachments=[
{
"file_id": "file_id",
"tools": [{"type": "code_interpreter"}],
}
],
metadata={"foo": "string"},
)
assert_matches_type(Message, message, path=["response"])
@parametrize
def test_raw_response_create(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.messages.with_raw_response.create(
thread_id="thread_id",
content="string",
role="user",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(Message, message, path=["response"])
@parametrize
def test_streaming_response_create(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.messages.with_streaming_response.create(
thread_id="thread_id",
content="string",
role="user",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(Message, message, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_create(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.messages.with_raw_response.create(
thread_id="",
content="string",
role="user",
)
@parametrize
def test_method_retrieve(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.retrieve(
message_id="message_id",
thread_id="thread_id",
)
assert_matches_type(Message, message, path=["response"])
@parametrize
def test_raw_response_retrieve(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.messages.with_raw_response.retrieve(
message_id="message_id",
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(Message, message, path=["response"])
@parametrize
def test_streaming_response_retrieve(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.messages.with_streaming_response.retrieve(
message_id="message_id",
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(Message, message, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_retrieve(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.messages.with_raw_response.retrieve(
message_id="message_id",
thread_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"):
client.beta.threads.messages.with_raw_response.retrieve(
message_id="",
thread_id="thread_id",
)
@parametrize
def test_method_update(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.update(
message_id="message_id",
thread_id="thread_id",
)
assert_matches_type(Message, message, path=["response"])
@parametrize
def test_method_update_with_all_params(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.update(
message_id="message_id",
thread_id="thread_id",
metadata={"foo": "string"},
)
assert_matches_type(Message, message, path=["response"])
@parametrize
def test_raw_response_update(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.messages.with_raw_response.update(
message_id="message_id",
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(Message, message, path=["response"])
@parametrize
def test_streaming_response_update(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.messages.with_streaming_response.update(
message_id="message_id",
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(Message, message, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_update(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.messages.with_raw_response.update(
message_id="message_id",
thread_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"):
client.beta.threads.messages.with_raw_response.update(
message_id="",
thread_id="thread_id",
)
@parametrize
def test_method_list(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.list(
thread_id="thread_id",
)
assert_matches_type(SyncCursorPage[Message], message, path=["response"])
@parametrize
def test_method_list_with_all_params(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.list(
thread_id="thread_id",
after="after",
before="before",
limit=0,
order="asc",
run_id="run_id",
)
assert_matches_type(SyncCursorPage[Message], message, path=["response"])
@parametrize
def test_raw_response_list(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.messages.with_raw_response.list(
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(SyncCursorPage[Message], message, path=["response"])
@parametrize
def test_streaming_response_list(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.messages.with_streaming_response.list(
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(SyncCursorPage[Message], message, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_list(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.messages.with_raw_response.list(
thread_id="",
)
@parametrize
def test_method_delete(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
message = client.beta.threads.messages.delete(
message_id="message_id",
thread_id="thread_id",
)
assert_matches_type(MessageDeleted, message, path=["response"])
@parametrize
def test_raw_response_delete(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
response = client.beta.threads.messages.with_raw_response.delete(
message_id="message_id",
thread_id="thread_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(MessageDeleted, message, path=["response"])
@parametrize
def test_streaming_response_delete(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with client.beta.threads.messages.with_streaming_response.delete(
message_id="message_id",
thread_id="thread_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
message = response.parse()
assert_matches_type(MessageDeleted, message, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_delete(self, client: OpenAI) -> None:
with pytest.warns(DeprecationWarning):
with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"):
client.beta.threads.messages.with_raw_response.delete(
message_id="message_id",
thread_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"):
client.beta.threads.messages.with_raw_response.delete(
message_id="",
thread_id="thread_id",
)
| TestMessages |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 22545,
"end": 24307
} | class ____:
def test_basic(self, xp):
xp_assert_close(windows.kaiser(6, 0.5, xp=xp),
xp.asarray([0.9403061933191572, 0.9782962393705389,
0.9975765035372042, 0.9975765035372042,
0.9782962393705389, 0.9403061933191572],
dtype=xp.float64))
xp_assert_close(windows.kaiser(7, 0.5, xp=xp),
xp.asarray([0.9403061933191572, 0.9732402256999829,
0.9932754654413773, 1.0, 0.9932754654413773,
0.9732402256999829, 0.9403061933191572],
dtype=xp.float64))
xp_assert_close(windows.kaiser(6, 2.7, xp=xp),
xp.asarray([0.2603047507678832, 0.6648106293528054,
0.9582099802511439, 0.9582099802511439,
0.6648106293528054, 0.2603047507678832],
dtype=xp.float64))
xp_assert_close(windows.kaiser(7, 2.7, xp=xp),
xp.asarray([0.2603047507678832, 0.5985765418119844,
0.8868495172060835, 1.0, 0.8868495172060835,
0.5985765418119844, 0.2603047507678832],
dtype=xp.float64))
xp_assert_close(windows.kaiser(6, 2.7, False, xp=xp),
xp.asarray([0.2603047507678832, 0.5985765418119844,
0.8868495172060835, 1.0, 0.8868495172060835,
0.5985765418119844], dtype=xp.float64))
@make_xp_test_case(windows.kaiser_bessel_derived)
| TestKaiser |
python | huggingface__transformers | src/transformers/integrations/tensor_parallel.py | {
"start": 30072,
"end": 31339
} | class ____(ColwiseParallel):
def shard_tensor(
self,
param,
param_type=None,
param_casting_dtype=None,
to_contiguous=None,
rank=None,
device_mesh=None,
tensor_idx=None,
):
device_mesh = device_mesh or self.device_mesh
empty_param = self.empty_param
rank = rank if rank is not None else self.rank
return get_packed_weights(param, empty_param, device_mesh, rank, -2).to(param_casting_dtype), [Shard(-2)]
def partition_tensor(self, param, empty_param, param_type, param_casting_dtype, to_contiguous, rank, device_mesh):
# colwise shard weight/bias to Shard(0), weight be Shard(-2) (0 if you have 1 dim only)
# means Colwise as Linear is input * weight^T + bias, where
# weight would become Shard(1)
parameter = get_packed_weights(param, empty_param, device_mesh, rank, -2)
parameter = parameter.to(param_casting_dtype)
if to_contiguous:
parameter = parameter.contiguous()
if self.use_dtensor:
parameter = DTensor.from_local(parameter, device_mesh, [Shard(-2)], run_check=False)
return nn.Parameter(parameter, requires_grad=parameter.is_floating_point())
| PackedColwiseParallel |
python | cookiecutter__cookiecutter | cookiecutter/exceptions.py | {
"start": 2494,
"end": 2709
} | class ____(CookiecutterException):
"""
Exception for incompatible modes.
Raised when cookiecutter is called with both `no_input==True` and
`replay==True` at the same time.
"""
| InvalidModeException |
python | spack__spack | lib/spack/spack/traverse.py | {
"start": 1095,
"end": 1883
} | class ____:
"""A simple visitor that accepts all edges unconditionally and follows all
edges to dependencies of a given ``deptype``."""
def __init__(self, depflag: dt.DepFlag = dt.ALL):
self.depflag = depflag
def accept(self, item):
"""
Arguments:
item (EdgeAndDepth): Provides the depth and the edge through which the
node was discovered
Returns:
bool: Returns ``True`` if the node is accepted. When ``False``, this
indicates that the node won't be yielded by iterators and dependencies
are not followed.
"""
return True
def neighbors(self, item):
return sort_edges(item.edge.spec.edges_to_dependencies(depflag=self.depflag))
| BaseVisitor |
python | allegroai__clearml | clearml/storage/helper.py | {
"start": 2385,
"end": 5739
} | class ____(metaclass=ABCMeta):
_certs_cache_context = "certs"
_file_server_hosts = None
@classmethod
def get_logger(cls) -> logging.Logger:
return get_logger("storage")
@abstractmethod
def get_container(
self,
container_name: str,
config: Optional[Any] = None,
**kwargs: Any,
) -> Any:
pass
@abstractmethod
def test_upload(self, test_path: str, config: Any, **kwargs: Any) -> bool:
pass
@abstractmethod
def upload_object_via_stream(
self,
iterator: Any,
container: Any,
object_name: str,
extra: dict,
**kwargs: Any,
) -> Any:
pass
@abstractmethod
def list_container_objects(
self,
container: Any,
ex_prefix: Optional[str] = None,
**kwargs: Any,
) -> Any:
pass
@abstractmethod
def get_direct_access(self, remote_path: str, **kwargs: Any) -> Optional[str]:
pass
@abstractmethod
def download_object(
self,
obj: Any,
local_path: str,
overwrite_existing: bool,
delete_on_failure: bool,
callback: Any,
**kwargs: Any,
) -> bool:
pass
@abstractmethod
def download_object_as_stream(self, obj: Any, chunk_size: int, **kwargs: Any) -> GeneratorType:
pass
@abstractmethod
def delete_object(self, obj: Any, **kwargs: Any) -> bool:
pass
@abstractmethod
def upload_object(
self,
file_path: str,
container: Any,
object_name: str,
extra: dict,
**kwargs: Any,
) -> Any:
pass
@abstractmethod
def get_object(self, container_name: str, object_name: str, **kwargs: Any) -> Any:
pass
@abstractmethod
def exists_file(self, container_name: str, object_name: str) -> bool:
pass
@classmethod
def get_file_server_hosts(cls) -> List[str]:
if cls._file_server_hosts is None:
hosts = [Session.get_files_server_host()] + (Session.legacy_file_servers or [])
for host in hosts[:]:
substituted = _StorageHelper._apply_url_substitutions(host)
if substituted not in hosts:
hosts.append(substituted)
cls._file_server_hosts = hosts
return cls._file_server_hosts
@classmethod
def download_cert(cls, cert_url: str) -> str:
# import here to avoid circular imports
from .manager import StorageManager
cls.get_logger().info("Attempting to download remote certificate '{}'".format(cert_url))
potential_exception = None
downloaded_verify = None
try:
downloaded_verify = StorageManager.get_local_copy(cert_url, cache_context=cls._certs_cache_context)
except Exception as e:
potential_exception = e
if not downloaded_verify:
cls.get_logger().error(
"Failed downloading remote certificate '{}'{}".format(
cert_url,
"Error is: {}".format(potential_exception) if potential_exception else "",
)
)
else:
cls.get_logger().info("Successfully downloaded remote certificate '{}'".format(cert_url))
return downloaded_verify
| _Driver |
python | aimacode__aima-python | gui/tsp.py | {
"start": 170,
"end": 1429
} | class ____(Problem):
"""subclass of Problem to define various functions"""
def two_opt(self, state):
"""Neighbour generating function for Traveling Salesman Problem"""
neighbour_state = state[:]
left = random.randint(0, len(neighbour_state) - 1)
right = random.randint(0, len(neighbour_state) - 1)
if left > right:
left, right = right, left
neighbour_state[left: right + 1] = reversed(neighbour_state[left: right + 1])
return neighbour_state
def actions(self, state):
"""action that can be executed in given state"""
return [self.two_opt]
def result(self, state, action):
"""result after applying the given action on the given state"""
return action(state)
def path_cost(self, c, state1, action, state2):
"""total distance for the Traveling Salesman to be covered if in state2"""
cost = 0
for i in range(len(state2) - 1):
cost += distances[state2[i]][state2[i + 1]]
cost += distances[state2[0]][state2[-1]]
return cost
def value(self, state):
"""value of path cost given negative for the given state"""
return -1 * self.path_cost(None, None, None, state)
| TSProblem |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_clip_grad_norm_.py | {
"start": 3888,
"end": 4937
} | class ____(_TestClipGradNormBase):
@property
def world_size(self) -> int:
return min(torch.get_device_module(device_type).device_count(), 2)
@skip_if_lt_x_gpu(2)
def test_clip_grad_norm_1d(self):
for norm_type in (2, 1, float("inf")):
torch.manual_seed(42)
model_args = ModelArgs(dropout_p=0.0)
model = Transformer(model_args)
ref_model = replicate(copy.deepcopy(model).to(device_type))
ref_optim = torch.optim.Adam(ref_model.parameters(), lr=1e-2)
for module in model.modules():
if isinstance(module, TransformerBlock):
fully_shard(module)
fully_shard(model)
optim = torch.optim.Adam(model.parameters(), lr=1e-2)
inp = torch.randint(
0, model.model_args.vocab_size, (3, 16), device=device_type
)
self._test_clip_grad_norm(
1, norm_type, ref_model, ref_optim, model, optim, inp
)
| TestClipGradNormWorldSize2 |
python | mlflow__mlflow | examples/tensorflow/train.py | {
"start": 561,
"end": 1196
} | class ____(tf.Module):
"""Linear Regression model class"""
def __init__(self):
self.built = False
@tf.function
def __call__(self, x):
# Initialize the model parameters on the first call
if not self.built:
# Randomly generate the weight vector and bias term
rand_w = tf.random.uniform(shape=[x.shape[-1], 1])
rand_b = tf.random.uniform(shape=[])
self.w = tf.Variable(rand_w)
self.b = tf.Variable(rand_b)
self.built = True
y = tf.add(tf.matmul(x, self.w), self.b)
return tf.squeeze(y, axis=1)
| LinearRegression |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 123974,
"end": 124437
} | class ____(IterDataPipe):
def __init__(self, dp):
self.dp = dp
self.num_of_instances = 1
self.instance_id = 0
def apply_sharding(self, num_of_instances, instance_id):
self.num_of_instances = num_of_instances
self.instance_id = instance_id
def __iter__(self):
for i, d in enumerate(self.dp):
if i % self.num_of_instances == self.instance_id:
yield d
| CustomShardingIterDataPipe |
python | zarr-developers__zarr-python | src/zarr/core/dtype/npy/int.py | {
"start": 6676,
"end": 11289
} | class ____(BaseInt[np.dtypes.Int8DType, np.int8]):
"""
A Zarr data type for arrays containing 8-bit signed integers.
Wraps the [`np.dtypes.Int8DType`][numpy.dtypes.Int8DType] data type. Scalars for this data type are
instances of [`np.int8`][numpy.int8].
Attributes
----------
dtype_cls : np.dtypes.Int8DType
The class of the underlying NumPy dtype.
References
----------
This class implements the 8-bit signed integer data type defined in Zarr V2 and V3.
See the [Zarr V2](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding) and [Zarr V3](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v3/data-types/index.rst) specification documents for details.
"""
dtype_cls = np.dtypes.Int8DType
_zarr_v3_name: ClassVar[Literal["int8"]] = "int8"
_zarr_v2_names: ClassVar[tuple[Literal["|i1"]]] = ("|i1",)
@classmethod
def from_native_dtype(cls, dtype: TBaseDType) -> Self:
"""
Create an Int8 from a np.dtype('int8') instance.
Parameters
----------
dtype : TBaseDType
The np.dtype('int8') instance.
Returns
-------
Self
An instance of this data type.
Raises
------
DataTypeValidationError
If the input data type is not a valid representation of this class Int8.
"""
if cls._check_native_dtype(dtype):
return cls()
raise DataTypeValidationError(
f"Invalid data type: {dtype}. Expected an instance of {cls.dtype_cls}"
)
def to_native_dtype(self: Self) -> np.dtypes.Int8DType:
"""
Convert the Int8 instance to a np.dtype('int8') instance.
Returns
-------
np.dtypes.Int8DType
The np.dtype('int8') instance.
"""
return self.dtype_cls()
@classmethod
def _from_json_v2(cls, data: DTypeJSON) -> Self:
"""
Create an Int8 from Zarr V2-flavored JSON.
Parameters
----------
data : DTypeJSON
The JSON data.
Returns
-------
Self
An instance of this data type.
Raises
------
DataTypeValidationError
If the input JSON is not a valid representation of this class Int8.
"""
if cls._check_json_v2(data):
return cls()
msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v2_names[0]!r}"
raise DataTypeValidationError(msg)
@classmethod
def _from_json_v3(cls, data: DTypeJSON) -> Self:
"""
Create an Int8 from Zarr V3-flavored JSON.
Parameters
----------
data : DTypeJSON
The JSON data.
Returns
-------
Self
An instance of this data type.
Raises
------
DataTypeValidationError
If the input JSON is not a valid representation of this class Int8.
"""
if cls._check_json_v3(data):
return cls()
msg = f"Invalid JSON representation of {cls.__name__}. Got {data!r}, expected the string {cls._zarr_v3_name!r}"
raise DataTypeValidationError(msg)
@overload
def to_json(self, zarr_format: Literal[2]) -> DTypeConfig_V2[Literal["|i1"], None]: ...
@overload
def to_json(self, zarr_format: Literal[3]) -> Literal["int8"]: ...
def to_json(
self, zarr_format: ZarrFormat
) -> DTypeConfig_V2[Literal["|i1"], None] | Literal["int8"]:
"""
Convert the data type to a JSON-serializable form.
Parameters
----------
zarr_format : ZarrFormat
The Zarr format version.
Returns
-------
``DTypeConfig_V2[Literal["|i1"], None] | Literal["int8"]``
The JSON-serializable representation of the data type.
Raises
------
ValueError
If the zarr_format is not 2 or 3.
"""
if zarr_format == 2:
return {"name": self._zarr_v2_names[0], "object_codec_id": None}
elif zarr_format == 3:
return self._zarr_v3_name
raise ValueError(f"zarr_format must be 2 or 3, got {zarr_format}") # pragma: no cover
@property
def item_size(self) -> int:
"""
The size of a single scalar in bytes.
Returns
-------
int
The size of a single scalar in bytes.
"""
return 1
@dataclass(frozen=True, kw_only=True)
| Int8 |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/filter.py | {
"start": 111,
"end": 1242
} | class ____:
"""Filters the set of Airflow objects to fetch.
Args:
dag_id_ilike (Optional[str]): A pattern used to match the set of dag_ids to retrieve. Uses the sql ILIKE operator Airflow-side.
airflow_tags (Optional[Sequence[str]]): Filters down to the set of Airflow DAGs whcih contain the particular tags provided.
retrieve_datasets (bool): Whether to retrieve datasets from Airflow. Defaults to True.
dataset_uri_ilike (Optional[str]): A pattern used to match the set of datasets to retrieve. Uses the sql ILIKE operator Airflow-side.
"""
dag_id_ilike: Optional[str] = None
airflow_tags: Optional[Sequence[str]] = None
retrieve_datasets: bool = True
dataset_uri_ilike: Optional[str] = None
def augment_request_params(self, request_params: dict) -> dict:
new_request_params = request_params.copy()
if self.dag_id_ilike is not None:
new_request_params["dag_id_pattern"] = self.dag_id_ilike
if self.airflow_tags is not None:
new_request_params["tags"] = self.airflow_tags
return new_request_params
| AirflowFilter |
python | pytoolz__toolz | toolz/tests/test_dicttoolz.py | {
"start": 6046,
"end": 6267
} | class ____(_defaultdict):
def __eq__(self, other):
return (super().__eq__(other) and
isinstance(other, _defaultdict) and
self.default_factory == other.default_factory)
| defaultdict |
python | getsentry__sentry | tests/sentry/sentry_apps/tasks/test_sentry_apps.py | {
"start": 55524,
"end": 58837
} | class ____(TestCase):
def setUp(self) -> None:
self.project = self.create_project()
self.user = self.create_user()
self.rpc_user = user_service.get_user(user_id=self.user.id)
self.sentry_app = self.create_sentry_app(organization=self.project.organization)
self.install = self.create_sentry_app_installation(
organization=self.project.organization, slug=self.sentry_app.slug
)
@responses.activate
@patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_sends_installation_notification(self, mock_record: MagicMock) -> None:
responses.add(responses.POST, "https://example.com/webhook")
installation_webhook(self.install.id, self.user.id)
response_body = json.loads(responses.calls[0].request.body)
assert response_body.get("installation").get("uuid") == self.install.uuid
assert response_body.get("action") == "created"
assert self.rpc_user, "User should exist in test to test installation webhook unless noted"
assert response_body.get("actor")["id"] == self.rpc_user.id
# SLO assertions
assert_success_metric(mock_record)
# PREPARE_WEBHOOK (success) -> SEND_WEBHOOK (success) x 1
assert_count_of_metric(
mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=2
)
assert_count_of_metric(
mock_record=mock_record, outcome=EventLifecycleOutcome.SUCCESS, outcome_count=2
)
@responses.activate
@patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_gracefully_handles_missing_install(self, mock_record: MagicMock) -> None:
responses.add(responses.POST, "https://example.com/webhook")
installation_webhook(999, self.user.id)
assert len(responses.calls) == 0
# SLO assertions
assert_failure_metric(
mock_record,
SentryAppSentryError(message=SentryAppWebhookFailureReason.MISSING_INSTALLATION),
)
# PREPARE_WEBHOOK (failure)
assert_count_of_metric(
mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=1
)
assert_count_of_metric(
mock_record=mock_record, outcome=EventLifecycleOutcome.FAILURE, outcome_count=1
)
@responses.activate
@patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_gracefully_handles_missing_user(self, mock_record: MagicMock) -> None:
responses.add(responses.POST, "https://example.com/webhook")
installation_webhook(self.install.id, 999)
assert len(responses.calls) == 0
# SLO assertions
assert_failure_metric(
mock_record,
SentryAppSentryError(message=SentryAppWebhookFailureReason.MISSING_USER),
)
# PREPARE_WEBHOOK (failure)
assert_count_of_metric(
mock_record=mock_record, outcome=EventLifecycleOutcome.STARTED, outcome_count=1
)
assert_count_of_metric(
mock_record=mock_record, outcome=EventLifecycleOutcome.FAILURE, outcome_count=1
)
@patch("sentry.utils.sentry_apps.webhooks.safe_urlopen", return_value=MockResponseInstance)
| TestInstallationWebhook |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/interactive.py | {
"start": 170,
"end": 259
} | class ____:
"""Sentinel value for detecting parameters with unset values"""
| PARAM_UNSET |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 27557,
"end": 30542
} | class ____:
"""
Decomposes inductor ops
"""
@staticmethod
def identity(value: OpVarT) -> OpVarT:
# used to trigger cse
return value
@staticmethod
def reciprocal(x: OpVarT) -> OpVarT:
return ops.truediv(ops.constant(1, torch.int32), x)
@staticmethod
def square(x: OpVarT) -> OpVarT:
return ops.mul(x, x)
@staticmethod
def erfc(x: OpVarT) -> OpVarT:
return ops.sub(ops.constant(1, torch.float32), ops.erf(x))
@staticmethod
def erfcx(x: OpVarT) -> OpVarT:
return ops.mul(ops.exp(ops.square(x)), ops.erfc(x))
@staticmethod
def expm1(x: OpVarT) -> OpVarT:
return ops.sub(ops.exp(x), ops.constant(1, torch.float32))
@staticmethod
def log10(x: OpVarT) -> OpVarT:
return ops.mul(ops.log(x), ops.constant(1 / math.log(10), torch.float32))
@staticmethod
def log2(x: OpVarT) -> OpVarT:
return ops.mul(ops.log(x), ops.constant(1 / math.log(2), torch.float32))
@staticmethod
def exp2(x: OpVarT) -> OpVarT:
return ops.exp(ops.mul(x, ops.constant(math.log(2), torch.float32)))
@staticmethod
def log1p(x: OpVarT) -> OpVarT:
return ops.log(ops.add(x, ops.constant(1, torch.int32)))
@staticmethod
def sigmoid(x: OpVarT) -> OpVarT:
one = ops.constant(1, torch.int32)
return ops.truediv(one, ops.add(one, ops.exp(ops.neg(x))))
@staticmethod
def relu(x: OpVarT) -> OpVarT:
return ops.maximum(x, ops.constant(0, torch.int32))
@staticmethod
def fma(x: OpVarT, y: OpVarT, z: OpVarT) -> OpVarT:
# for backends that don't override this (halide)
return ops.add(ops.mul(x, y), z)
@staticmethod
def floor_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT:
return ops.to_dtype(ops.floor(a), dtype)
@staticmethod
def ceil_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT:
return ops.to_dtype(ops.ceil(a), dtype)
@staticmethod
def trunc_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT:
return ops.to_dtype(ops.trunc(a), dtype)
@staticmethod
def remainder(a: OpVarT, b: OpVarT) -> OpVarT:
r = ops.mod(a, b)
cond = ops.and_(
ops.ne(r, ops.constant(0, torch.int32)),
ops.ne(ops.signbit(r), ops.signbit(b)),
)
return ops.where(cond, ops.add(r, b), r)
@staticmethod
def round_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT:
return ops.to_dtype(ops.round(a), dtype)
_RE_PAREN_NOT_NEEDED = re.compile(r"[a-z0-9_.]+|\([^)]*\)|", flags=re.IGNORECASE)
def _all_in_parens(string: str) -> bool:
if string[0] != "(" or len(string) < 2:
return False
count = 1
for i, char in enumerate(string[1:]):
if char == "(":
count += 1
elif char == ")":
count -= 1
if count == 0 and i != len(string) - 2:
return False
assert count == 0
return True
| OpDecompositions |
python | pytorch__pytorch | torch/_dynamo/variables/misc.py | {
"start": 37852,
"end": 42949
} | class ____(UserDefinedObjectVariable):
"""
Tracks an autograd.Function() context using mutation tracking in side_effects.py
"""
_nonvar_fields = {
"proxy",
"inference",
"saved_tensors",
*UserDefinedObjectVariable._nonvar_fields,
}
def __init__(
self,
value,
value_type=None,
inference=False,
saved_tensors=None,
needs_input_grad=None,
non_differentiable=None,
**kwargs,
) -> None:
super().__init__(value=value, value_type=value_type, **kwargs)
self.inference = inference
self.saved_tensors = saved_tensors
self.needs_input_grad = needs_input_grad
self.non_differentiable = non_differentiable
@staticmethod
def create(tx: "InstructionTranslator", args=None, kwargs=None):
needs_input_grad = None
if args and not kwargs:
needs_input_grad = tuple(
isinstance(x, variables.TensorVariable) and x.requires_grad
for x in args
)
out = tx.output.side_effects.track_object_new(
None,
torch.autograd.function.FunctionCtx,
functools.partial(
AutogradFunctionContextVariable,
inference=True,
saved_tensors=SavedTensorBox(),
needs_input_grad=needs_input_grad,
),
{},
)
return out
def as_proxy(self):
if self.proxy is None:
unimplemented(
gb_type="proxy not set",
context=f"as_proxy {self}",
explanation="Dynamo requires the autograd.Function context "
"to be initialized with a proxy.",
hints=[*graph_break_hints.DYNAMO_BUG],
)
return self.proxy
def call_method(
self,
tx: "InstructionTranslator",
name,
args: "list[VariableTracker]",
kwargs: "dict[str, VariableTracker]",
) -> "VariableTracker":
if name == "__setattr__":
return super().call_method(tx, name, args, kwargs)
elif name == "mark_non_differentiable":
if kwargs:
raise_args_mismatch(tx, name, "0 kwargs", f"{len(kwargs)} kwargs")
self.non_differentiable = proxy_args_kwargs(args, {})[0]
return variables.ConstantVariable.create(None)
if name != "save_for_backward":
unimplemented(
gb_type="Unsupported autograd.Function context method",
context=f"call_method {self} {name}",
explanation="Dynamo does not support calling the method "
f"`{name}` on `autograd.Function` context objects. Supported "
"methods are `__setattr__`, `save_for_backward` and "
"`mark_non_differentiable`.",
hints=[*graph_break_hints.SUPPORTABLE],
)
if self.saved_tensors is None:
unimplemented(
gb_type="Unsupported autograd.Function context `save_for_backward`",
context=f"call_method {self} {name}",
explanation="Dynamo requires the `saved_tensors` attribute "
"to be initialized on the `autograd.Function` context object.",
hints=[
"Ensure that the `saved_tensors` attribute is properly "
"initialized before calling `save_for_backward`. "
"`save_for_backward` only supported on a newly constructed `torch.autograd.function.FunctionCtx`.",
],
)
if not self.inference:
if kwargs or not self.source:
raise_type_error_exc(
tx, "save_for_backward() requires a source and no keyword arguments"
)
tx.output.side_effects.track_save_for_backward(self, args)
# In eager mode, multiple calls to .save_for_backward() will overwrite previous calls.
if len(self.saved_tensors.tensors) > 0:
self.saved_tensors.tensors = []
for arg in args:
self.saved_tensors.tensors.append(arg)
return variables.ConstantVariable.create(None)
def var_getattr(self, tx: "InstructionTranslator", name):
if name in ["save_for_backward", "mark_non_differentiable"]:
return LambdaVariable(
lambda *args, **kwargs: self.call_method(tx, name, args, kwargs)
)
if name == "saved_tensors" and self.saved_tensors is not None:
return variables.TupleVariable(list(self.saved_tensors.tensors))
if name == "needs_input_grad":
if self.needs_input_grad is not None:
return variables.ConstantVariable.create(self.needs_input_grad)
if self.source:
source = AttrSource(self.source, "needs_input_grad")
return VariableTracker.build(tx, self.value.needs_input_grad, source)
return super().var_getattr(tx, name)
| AutogradFunctionContextVariable |
python | django__django | django/db/migrations/exceptions.py | {
"start": 140,
"end": 252
} | class ____(Exception):
"""There's a bad migration (unreadable/bad format/etc.)."""
pass
| BadMigrationError |
python | PyCQA__pylint | tests/functional/ext/typing/typing_deprecated_alias.py | {
"start": 2035,
"end": 2227
} | class ____(typing.NamedTuple):
my_var: List[int] # [deprecated-typing-alias]
CustomTypedDict1 = TypedDict("CustomTypedDict1", my_var=List[int]) # [deprecated-typing-alias]
| CustomNamedTuple |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/lexers/pygments.py | {
"start": 896,
"end": 1672
} | class ____(metaclass=ABCMeta):
"""
Syntax synchronizer. This is a tool that finds a start position for the
lexer. This is especially important when editing big documents; we don't
want to start the highlighting by running the lexer from the beginning of
the file. That is very slow when editing.
"""
@abstractmethod
def get_sync_start_position(
self, document: Document, lineno: int
) -> tuple[int, int]:
"""
Return the position from where we can start lexing as a (row, column)
tuple.
:param document: `Document` instance that contains all the lines.
:param lineno: The line that we want to highlight. (We need to return
this line, or an earlier position.)
"""
| SyntaxSync |
python | kamyu104__LeetCode-Solutions | Python/super-egg-drop.py | {
"start": 33,
"end": 1991
} | class ____(object):
def superEggDrop(self, K, N):
"""
:type K: int
:type N: int
:rtype: int
"""
def check(n, K, N):
# let f(n, K) be the max number of floors could be solved by n moves and K eggs,
# we want to do binary search to find min of n, s.t. f(n, K) >= N,
# if we use one move to drop egg with X floors
# 1. if it breaks, we can search new X in the range [X-f(n-1, K-1), X-1]
# 2. if it doesn't break, we can search new X in the range [X+1, X+f(n-1, K)]
# => f(n, K) = (X+f(n-1, K))-(X-f(n-1, K-1))+1 = f(n-1, K)+f(n-1, K-1)+1
# => (1) f(n, K) = f(n-1, K) +1+f(n-1, K-1)
# (2) f(n, K-1) = f(n-1, K-1)+1+f(n-1, K-2)
# let g(n, K) = f(n, K)-f(n, K-1), and we subtract (1) by (2)
# => g(n, K) = g(n-1, K)+g(n-1, K-1), obviously, it is binomial coefficient
# => C(n, K) = g(n, K) = f(n, K)-f(n, K-1),
# which also implies if we have one more egg with n moves and x-1 eggs, we can have more C(n, x) floors solvable
# => f(n, K) = C(n, K)+f(n, K-1) = C(n, K) + C(n, K-1) + ... + C(n, 1) + f(n, 0) = sum(C(n, k) for k in [1, K])
# => all we have to do is to check sum(C(n, k) for k in [1, K]) >= N,
# if true, there must exist a 1-to-1 mapping from each F in [1, N] to each success and failure sequence of every C(n, k) combinations for k in [1, K]
total, c = 0, 1
for k in xrange(1, K+1):
c *= n-k+1
c //= k
total += c
if total >= N:
return True
return False
left, right = 1, N
while left <= right:
mid = left + (right-left)//2
if check(mid, K, N):
right = mid-1
else:
left = mid+1
return left
| Solution |
python | huggingface__transformers | src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | {
"start": 43214,
"end": 44296
} | class ____(nn.Module):
def __init__(self, config: SeamlessM4Tv2Config, ffn_dim: int):
super().__init__()
self.fc1 = nn.Linear(config.hidden_size, ffn_dim)
self.fc2 = nn.Linear(ffn_dim, config.hidden_size)
self.dropout = nn.Dropout(config.activation_dropout)
self.act = ACT2FN[config.activation_function]
def forward(self, hidden_states: torch.Tensor):
hidden_states = self.fc1(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.dropout(hidden_states)
if (
isinstance(self.fc2.weight, torch.Tensor)
and hidden_states.dtype != self.fc2.weight.dtype
and (self.fc2.weight.dtype != torch.int8 and self.fc2.weight.dtype != torch.uint8)
):
hidden_states = hidden_states.to(self.fc2.weight.dtype)
hidden_states = self.fc2(hidden_states)
return hidden_states
# Copied from transformers.models.seamless_m4t.modeling_seamless_m4t.SeamlessM4TEncoderLayer with SeamlessM4T->SeamlessM4Tv2
| SeamlessM4Tv2FeedForwardNetwork |
python | doocs__leetcode | solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/Solution.py | {
"start": 705,
"end": 1427
} | class ____:
def maxXor(self, n: int, edges: List[List[int]], values: List[int]) -> int:
def dfs1(i, fa):
t = values[i]
for j in g[i]:
if j != fa:
t += dfs1(j, i)
s[i] = t
return t
def dfs2(i, fa):
nonlocal ans
ans = max(ans, tree.search(s[i]))
for j in g[i]:
if j != fa:
dfs2(j, i)
tree.insert(s[i])
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
s = [0] * n
dfs1(0, -1)
ans = 0
tree = Trie()
dfs2(0, -1)
return ans
| Solution |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 12210,
"end": 13533
} | class ____(IntegrationBase, unittest.TestCase):
package = 'tests.pkgs.staticpermapp'
root_factory = 'tests.pkgs.staticpermapp:RootFactory'
def test_allowed(self):
result = self.testapp.get('/allowed/index.html', status=200)
_assertBody(
result.body, os.path.join(here, 'fixtures/static/index.html')
)
def test_denied_via_acl_global_root_factory(self):
self.testapp.extra_environ = {'REMOTE_USER': 'bob'}
self.testapp.get('/protected/index.html', status=403)
def test_allowed_via_acl_global_root_factory(self):
self.testapp.extra_environ = {'REMOTE_USER': 'fred'}
result = self.testapp.get('/protected/index.html', status=200)
_assertBody(
result.body, os.path.join(here, 'fixtures/static/index.html')
)
def test_denied_via_acl_local_root_factory(self):
self.testapp.extra_environ = {'REMOTE_USER': 'fred'}
self.testapp.get('/factory_protected/index.html', status=403)
def test_allowed_via_acl_local_root_factory(self):
self.testapp.extra_environ = {'REMOTE_USER': 'bob'}
result = self.testapp.get('/factory_protected/index.html', status=200)
_assertBody(
result.body, os.path.join(here, 'fixtures/static/index.html')
)
| TestStaticPermApp |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-klaviyo/components.py | {
"start": 13555,
"end": 15001
} | class ____(StateMigration):
"""
Transforms the input state for per-partitioned streams from the legacy format to the low-code format.
The cursor field and partition ID fields are automatically extracted from the stream's DatetimebasedCursor and SubstreamPartitionRouter.
Example input state:
{
"partition": {"event_id": "13506132"},
"cursor": {"datetime": "2120-10-10 00:00:00+00:00"}
}
Example output state:
{
"datetime": "2120-10-10 00:00:00+00:00"
}
"""
declarative_stream: DeclarativeStreamModel
config: Config
def __init__(self, declarative_stream: DeclarativeStreamModel, config: Config):
self._config = config
self.declarative_stream = declarative_stream
self._cursor = declarative_stream.incremental_sync
self._parameters = declarative_stream.parameters
self._cursor_field = InterpolatedString.create(self._cursor.cursor_field, parameters=self._parameters).eval(self._config)
def should_migrate(self, stream_state: Mapping[str, Any]) -> bool:
return "states" in stream_state
def migrate(self, stream_state: Mapping[str, Any]) -> Mapping[str, Any]:
if not self.should_migrate(stream_state):
return stream_state
min_state = min(stream_state.get("states"), key=lambda state: state["cursor"][self._cursor_field])
return min_state.get("cursor")
| PerPartitionToSingleStateMigration |
python | RaRe-Technologies__gensim | gensim/test/test_datatype.py | {
"start": 356,
"end": 1965
} | class ____(unittest.TestCase):
def load_model(self, datatype):
path = datapath('high_precision.kv.txt')
kv = KeyedVectors.load_word2vec_format(path, binary=False,
datatype=datatype)
return kv
def test_high_precision(self):
kv = self.load_model(np.float64)
self.assertAlmostEqual(kv['horse.n.01'][0], -0.0008546282343595379)
self.assertEqual(kv['horse.n.01'][0].dtype, np.float64)
def test_medium_precision(self):
kv = self.load_model(np.float32)
self.assertAlmostEqual(kv['horse.n.01'][0], -0.00085462822)
self.assertEqual(kv['horse.n.01'][0].dtype, np.float32)
def test_low_precision(self):
kv = self.load_model(np.float16)
self.assertAlmostEqual(kv['horse.n.01'][0], -0.00085449)
self.assertEqual(kv['horse.n.01'][0].dtype, np.float16)
def test_type_conversion(self):
path = datapath('high_precision.kv.txt')
binary_path = datapath('high_precision.kv.bin')
model1 = KeyedVectors.load_word2vec_format(path, datatype=np.float16)
model1.save_word2vec_format(binary_path, binary=True)
model2 = KeyedVectors.load_word2vec_format(binary_path, datatype=np.float64, binary=True)
self.assertAlmostEqual(model1["horse.n.01"][0], np.float16(model2["horse.n.01"][0]))
self.assertEqual(model1["horse.n.01"][0].dtype, np.float16)
self.assertEqual(model2["horse.n.01"][0].dtype, np.float64)
if __name__ == '__main__':
logging.root.setLevel(logging.WARNING)
unittest.main()
| TestDataType |
python | gevent__gevent | src/greentest/3.14/test_urllib.py | {
"start": 51282,
"end": 59133
} | class ____(unittest.TestCase):
"""Tests for urlencode()"""
def help_inputtype(self, given, test_type):
"""Helper method for testing different input types.
'given' must lead to only the pairs:
* 1st, 1
* 2nd, 2
* 3rd, 3
Test cannot assume anything about order. Docs make no guarantee and
have possible dictionary input.
"""
expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
result = urllib.parse.urlencode(given)
for expected in expect_somewhere:
self.assertIn(expected, result,
"testing %s: %s not found in %s" %
(test_type, expected, result))
self.assertEqual(result.count('&'), 2,
"testing %s: expected 2 '&'s; got %s" %
(test_type, result.count('&')))
amp_location = result.index('&')
on_amp_left = result[amp_location - 1]
on_amp_right = result[amp_location + 1]
self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
"testing %s: '&' not located in proper place in %s" %
(test_type, result))
self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
"testing %s: "
"unexpected number of characters: %s != %s" %
(test_type, len(result), (5 * 3) + 2))
def test_using_mapping(self):
# Test passing in a mapping object as an argument.
self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
"using dict as input type")
def test_using_sequence(self):
# Test passing in a sequence of two-item sequences as an argument.
self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
"using sequence of two-item tuples as input")
def test_quoting(self):
# Make sure keys and values are quoted using quote_plus()
given = {"&":"="}
expect = "%s=%s" % (hexescape('&'), hexescape('='))
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
given = {"key name":"A bunch of pluses"}
expect = "key+name=A+bunch+of+pluses"
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
def test_doseq(self):
# Test that passing True for 'doseq' parameter works correctly
given = {'sequence':['1', '2', '3']}
expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3']))
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
result = urllib.parse.urlencode(given, True)
for value in given["sequence"]:
expect = "sequence=%s" % value
self.assertIn(expect, result)
self.assertEqual(result.count('&'), 2,
"Expected 2 '&'s, got %s" % result.count('&'))
def test_empty_sequence(self):
self.assertEqual("", urllib.parse.urlencode({}))
self.assertEqual("", urllib.parse.urlencode([]))
def test_nonstring_values(self):
self.assertEqual("a=1", urllib.parse.urlencode({"a": 1}))
self.assertEqual("a=None", urllib.parse.urlencode({"a": None}))
def test_nonstring_seq_values(self):
self.assertEqual("a=1&a=2", urllib.parse.urlencode({"a": [1, 2]}, True))
self.assertEqual("a=None&a=a",
urllib.parse.urlencode({"a": [None, "a"]}, True))
data = collections.OrderedDict([("a", 1), ("b", 1)])
self.assertEqual("a=a&a=b",
urllib.parse.urlencode({"a": data}, True))
def test_urlencode_encoding(self):
# ASCII encoding. Expect %3F with errors="replace'
given = (('\u00a0', '\u00c1'),)
expect = '%3F=%3F'
result = urllib.parse.urlencode(given, encoding="ASCII", errors="replace")
self.assertEqual(expect, result)
# Default is UTF-8 encoding.
given = (('\u00a0', '\u00c1'),)
expect = '%C2%A0=%C3%81'
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
# Latin-1 encoding.
given = (('\u00a0', '\u00c1'),)
expect = '%A0=%C1'
result = urllib.parse.urlencode(given, encoding="latin-1")
self.assertEqual(expect, result)
def test_urlencode_encoding_doseq(self):
# ASCII Encoding. Expect %3F with errors="replace'
given = (('\u00a0', '\u00c1'),)
expect = '%3F=%3F'
result = urllib.parse.urlencode(given, doseq=True,
encoding="ASCII", errors="replace")
self.assertEqual(expect, result)
# ASCII Encoding. On a sequence of values.
given = (("\u00a0", (1, "\u00c1")),)
expect = '%3F=1&%3F=%3F'
result = urllib.parse.urlencode(given, True,
encoding="ASCII", errors="replace")
self.assertEqual(expect, result)
# Utf-8
given = (("\u00a0", "\u00c1"),)
expect = '%C2%A0=%C3%81'
result = urllib.parse.urlencode(given, True)
self.assertEqual(expect, result)
given = (("\u00a0", (42, "\u00c1")),)
expect = '%C2%A0=42&%C2%A0=%C3%81'
result = urllib.parse.urlencode(given, True)
self.assertEqual(expect, result)
# latin-1
given = (("\u00a0", "\u00c1"),)
expect = '%A0=%C1'
result = urllib.parse.urlencode(given, True, encoding="latin-1")
self.assertEqual(expect, result)
given = (("\u00a0", (42, "\u00c1")),)
expect = '%A0=42&%A0=%C1'
result = urllib.parse.urlencode(given, True, encoding="latin-1")
self.assertEqual(expect, result)
def test_urlencode_bytes(self):
given = ((b'\xa0\x24', b'\xc1\x24'),)
expect = '%A0%24=%C1%24'
result = urllib.parse.urlencode(given)
self.assertEqual(expect, result)
result = urllib.parse.urlencode(given, True)
self.assertEqual(expect, result)
# Sequence of values
given = ((b'\xa0\x24', (42, b'\xc1\x24')),)
expect = '%A0%24=42&%A0%24=%C1%24'
result = urllib.parse.urlencode(given, True)
self.assertEqual(expect, result)
def test_urlencode_encoding_safe_parameter(self):
# Send '$' (\x24) as safe character
# Default utf-8 encoding
given = ((b'\xa0\x24', b'\xc1\x24'),)
result = urllib.parse.urlencode(given, safe=":$")
expect = '%A0$=%C1$'
self.assertEqual(expect, result)
given = ((b'\xa0\x24', b'\xc1\x24'),)
result = urllib.parse.urlencode(given, doseq=True, safe=":$")
expect = '%A0$=%C1$'
self.assertEqual(expect, result)
# Safe parameter in sequence
given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
expect = '%A0$=%C1$&%A0$=13&%A0$=42'
result = urllib.parse.urlencode(given, True, safe=":$")
self.assertEqual(expect, result)
# Test all above in latin-1 encoding
given = ((b'\xa0\x24', b'\xc1\x24'),)
result = urllib.parse.urlencode(given, safe=":$",
encoding="latin-1")
expect = '%A0$=%C1$'
self.assertEqual(expect, result)
given = ((b'\xa0\x24', b'\xc1\x24'),)
expect = '%A0$=%C1$'
result = urllib.parse.urlencode(given, doseq=True, safe=":$",
encoding="latin-1")
given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
expect = '%A0$=%C1$&%A0$=13&%A0$=42'
result = urllib.parse.urlencode(given, True, safe=":$",
encoding="latin-1")
self.assertEqual(expect, result)
| urlencode_Tests |
python | mlflow__mlflow | mlflow/bedrock/stream.py | {
"start": 433,
"end": 2583
} | class ____:
"""
A wrapper class for a event stream to record events and accumulated response
in an MLflow span if possible.
A span should be ended when the stream is exhausted rather than when it is created.
Args:
stream: The original event stream to wrap.
span: The span to record events and response in.
inputs: The inputs to the converse API.
"""
def __init__(
self,
stream: EventStream,
span: LiveSpan,
inputs: dict[str, Any] | None = None,
):
self._stream = stream
self._span = span
self._inputs = inputs
def __iter__(self):
for event in self._stream:
self._handle_event(self._span, event)
yield event
# End the span when the stream is exhausted
self._close()
def __getattr__(self, attr):
"""Delegate all other attributes to the original stream."""
return getattr(self._stream, attr)
def _handle_event(self, span, event):
"""Process a single event from the stream."""
raise NotImplementedError
def _close(self):
"""End the span and run any finalization logic."""
raise NotImplementedError
@capture_exception("Failed to handle event for the stream")
def _end_span(self):
"""End the span."""
self._span.end()
def _extract_token_usage_from_chunk(chunk: dict[str, Any]) -> dict[str, int] | None:
"""Extract partial token usage from streaming chunk.
Args:
chunk: A single streaming chunk from Bedrock API.
Returns:
Token usage dictionary with standardized keys, or None if no usage found.
"""
try:
usage = (
chunk.get("message", {}).get("usage")
if chunk.get("type") == "message_start"
else chunk.get("usage")
)
if isinstance(usage, dict):
return parse_partial_token_usage_from_response(usage)
return None
except (KeyError, TypeError, AttributeError) as e:
_logger.debug(f"Failed to extract token usage from chunk: {e}")
return None
| BaseEventStreamWrapper |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 29060,
"end": 30227
} | class ____(Response):
"""
Response of queues.delete endpoint.
:param deleted: Number of queues deleted (0 or 1)
:type deleted: int
"""
_service = "queues"
_action = "delete"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"deleted": {
"description": "Number of queues deleted (0 or 1)",
"enum": [0, 1],
"type": ["integer", "null"],
}
},
"type": "object",
}
def __init__(self, deleted: Optional[int] = None, **kwargs: Any) -> None:
super(DeleteResponse, self).__init__(**kwargs)
self.deleted = deleted
@schema_property("deleted")
def deleted(self) -> Optional[int]:
return self._property_deleted
@deleted.setter
def deleted(self, value: Optional[int]) -> None:
if value is None:
self._property_deleted = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "deleted", six.integer_types)
self._property_deleted = value
| DeleteResponse |
python | Delgan__loguru | tests/conftest.py | {
"start": 4137,
"end": 4209
} | class ____(io.StringIO):
def fileno(self):
return 1
| StubStream |
python | getsentry__sentry | src/sentry/utils/time_window.py | {
"start": 88,
"end": 2424
} | class ____:
# Timestamps are in seconds
start: float
end: float
def as_tuple(self) -> tuple[float, float]:
return (self.start, self.end)
@property
def duration_ms(self) -> float:
return (self.end - self.start) * 1000
def __add__(self, other: "TimeWindow") -> tuple[Optional["TimeWindow"], "TimeWindow"]:
if self.start < other.start:
if self.end < other.start:
return self, other
return None, TimeWindow(start=self.start, end=max(self.end, other.end))
else:
if self.start > other.end:
return other, self
return None, TimeWindow(start=other.start, end=max(self.end, other.end))
def __sub__(self, other: "TimeWindow") -> tuple[Optional["TimeWindow"], "TimeWindow"]:
if self.start < other.start:
if self.end > other.end:
return (
TimeWindow(start=self.start, end=other.start),
TimeWindow(start=other.end, end=self.end),
)
return None, TimeWindow(start=self.start, end=min(self.end, other.start))
else:
if self.end < other.end:
return None, TimeWindow(start=self.end, end=self.end)
return None, TimeWindow(start=max(self.start, other.end), end=self.end)
def union_time_windows(time_windows: list[TimeWindow]) -> list[TimeWindow]:
if not time_windows:
return []
previous, *time_windows = sorted(time_windows, key=lambda window: window.as_tuple())
unioned: list[TimeWindow] = []
for current in time_windows:
window, previous = previous + current
if window:
unioned.append(window)
unioned.append(previous)
return unioned
def remove_time_windows(source: TimeWindow, time_windows: list[TimeWindow]) -> list[TimeWindow]:
if not time_windows:
return [source]
removed: list[TimeWindow] = []
for current in time_windows:
window, source = source - current
if window:
removed.append(window)
removed.append(source)
# After subtracting time windows, we may end up with 0 width time_windows.
# remove them from the results.
return [time_window for time_window in removed if time_window.start != time_window.end]
| TimeWindow |
python | etianen__django-reversion | tests/test_app/tests/test_api.py | {
"start": 9316,
"end": 9801
} | class ____(UserMixin, TestBase):
def testGetUser(self):
with reversion.create_revision():
reversion.set_user(self.user)
self.assertEqual(reversion.get_user(), self.user)
def testGetUserDefault(self):
with reversion.create_revision():
self.assertEqual(reversion.get_user(), None)
def testGetUserNoBlock(self):
with self.assertRaises(reversion.RevisionManagementError):
reversion.get_user()
| GetUserTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/bigquery.py | {
"start": 63907,
"end": 81547
} | class ____(BigQueryBaseCursor):
"""
A very basic BigQuery PEP 249 cursor implementation.
The PyHive PEP 249 implementation was used as a reference:
https://github.com/dropbox/PyHive/blob/master/pyhive/presto.py
https://github.com/dropbox/PyHive/blob/master/pyhive/common.py
"""
def __init__(
self,
service: Any,
project_id: str,
hook: BigQueryHook,
use_legacy_sql: bool = True,
location: str | None = None,
num_retries: int = 5,
) -> None:
super().__init__(
service=service,
project_id=project_id,
hook=hook,
use_legacy_sql=use_legacy_sql,
location=location,
num_retries=num_retries,
)
self.buffersize: int | None = None
self.page_token: str | None = None
self.job_id: str | None = None
self.buffer: list = []
self.all_pages_loaded: bool = False
self._description: list = []
@property
def description(self) -> list:
"""Return the cursor description."""
return self._description
@description.setter
def description(self, value):
self._description = value
def close(self) -> None:
"""By default, do nothing."""
@property
def rowcount(self) -> int:
"""By default, return -1 to indicate that this is not supported."""
return -1
def execute(self, operation: str, parameters: dict | None = None) -> None:
"""
Execute a BigQuery query, and update the BigQueryCursor description.
:param operation: The query to execute.
:param parameters: Parameters to substitute into the query.
"""
sql = _bind_parameters(operation, parameters) if parameters else operation
self.flush_results()
job = self._run_query(sql)
self.job_id = job.job_id
self.location = self.location or job.location
query_results = self._get_query_result()
if "schema" in query_results:
self.description = _format_schema_for_description(query_results["schema"])
else:
self.description = []
def executemany(self, operation: str, seq_of_parameters: list) -> None:
"""
Execute a BigQuery query multiple times with different parameters.
:param operation: The query to execute.
:param seq_of_parameters: List of dictionary parameters to substitute into the
query.
"""
for parameters in seq_of_parameters:
self.execute(operation, parameters)
def flush_results(self) -> None:
"""Flush results related cursor attributes."""
self.page_token = None
self.job_id = None
self.all_pages_loaded = False
self.buffer = []
def fetchone(self) -> list | None:
"""Fetch the next row of a query result set."""
return self.next()
def next(self) -> list | None:
"""
Return the next row from a buffer.
Helper method for ``fetchone``.
If the buffer is empty, attempts to paginate through the result set for
the next page, and load it into the buffer.
"""
if not self.job_id:
return None
if not self.buffer:
if self.all_pages_loaded:
return None
query_results = self._get_query_result()
if rows := query_results.get("rows"):
self.page_token = query_results.get("pageToken")
fields = query_results["schema"]["fields"]
col_types = [field["type"] for field in fields]
for dict_row in rows:
typed_row = [bq_cast(vs["v"], col_types[idx]) for idx, vs in enumerate(dict_row["f"])]
self.buffer.append(typed_row)
if not self.page_token:
self.all_pages_loaded = True
else:
# Reset all state since we've exhausted the results.
self.flush_results()
return None
return self.buffer.pop(0)
def fetchmany(self, size: int | None = None) -> list:
"""
Fetch the next set of rows of a query result.
This returns a sequence of sequences (e.g. a list of tuples). An empty
sequence is returned when no more rows are available.
The number of rows to fetch per call is specified by the parameter. If
it is not given, the cursor's arraysize determines the number of rows to
be fetched.
This method tries to fetch as many rows as indicated by the size
parameter. If this is not possible due to the specified number of rows
not being available, fewer rows may be returned.
An :py:class:`~pyhive.exc.Error` (or subclass) exception is raised if
the previous call to :py:meth:`execute` did not produce any result set,
or no call was issued yet.
"""
if size is None:
size = self.arraysize
result = []
for _ in range(size):
one = self.fetchone()
if one is None:
break
result.append(one)
return result
def fetchall(self) -> list[list]:
"""
Fetch all (remaining) rows of a query result.
A sequence of sequences (e.g. a list of tuples) is returned.
"""
result = list(iter(self.fetchone, None))
return result
def get_arraysize(self) -> int:
"""
Get number of rows to fetch at a time.
.. seealso:: :func:`.fetchmany()`
"""
return self.buffersize or 1
def set_arraysize(self, arraysize: int) -> None:
"""
Set the number of rows to fetch at a time.
.. seealso:: :func:`.fetchmany()`
"""
self.buffersize = arraysize
arraysize = property(get_arraysize, set_arraysize)
def setinputsizes(self, sizes: Any) -> None:
"""Do nothing by default."""
def setoutputsize(self, size: Any, column: Any = None) -> None:
"""Do nothing by default."""
def _get_query_result(self) -> dict:
"""Get job query results; data, schema, job type, etc."""
query_results = (
self.service.jobs()
.getQueryResults(
projectId=self.project_id,
jobId=self.job_id,
location=self.location,
pageToken=self.page_token,
)
.execute(num_retries=self.num_retries)
)
return query_results
def _run_query(
self,
sql,
location: str | None = None,
) -> BigQueryJob:
"""Run a job query and return the job instance."""
if not self.project_id:
raise ValueError("The project_id should be set")
configuration = self._prepare_query_configuration(sql)
job = self.hook.insert_job(configuration=configuration, project_id=self.project_id, location=location)
return job
def _prepare_query_configuration(
self,
sql,
destination_dataset_table: str | None = None,
write_disposition: str = "WRITE_EMPTY",
allow_large_results: bool = False,
flatten_results: bool | None = None,
udf_config: list | None = None,
use_legacy_sql: bool | None = None,
maximum_billing_tier: int | None = None,
maximum_bytes_billed: float | None = None,
create_disposition: str = "CREATE_IF_NEEDED",
query_params: list | None = None,
labels: dict | None = None,
schema_update_options: Iterable | None = None,
priority: str | None = None,
time_partitioning: dict | None = None,
range_partitioning: dict | None = None,
api_resource_configs: dict | None = None,
cluster_fields: list[str] | None = None,
encryption_configuration: dict | None = None,
):
"""Prepare configuration for query."""
labels = labels or self.hook.labels
schema_update_options = list(schema_update_options or [])
priority = priority or self.hook.priority
if time_partitioning is None:
time_partitioning = {}
if range_partitioning is None:
range_partitioning = {}
if time_partitioning and range_partitioning:
raise ValueError("Only one of time_partitioning or range_partitioning can be set.")
if not api_resource_configs:
api_resource_configs = self.hook.api_resource_configs
else:
_validate_value("api_resource_configs", api_resource_configs, dict)
configuration = deepcopy(api_resource_configs)
if "query" not in configuration:
configuration["query"] = {}
else:
_validate_value("api_resource_configs['query']", configuration["query"], dict)
if sql is None and not configuration["query"].get("query", None):
raise TypeError("`BigQueryBaseCursor.run_query` missing 1 required positional argument: `sql`")
# BigQuery also allows you to define how you want a table's schema to change
# as a side effect of a query job
# for more details:
# https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.schemaUpdateOptions
allowed_schema_update_options = ["ALLOW_FIELD_ADDITION", "ALLOW_FIELD_RELAXATION"]
if not set(allowed_schema_update_options).issuperset(set(schema_update_options)):
raise ValueError(
f"{schema_update_options} contains invalid schema update options."
f" Please only use one or more of the following options: {allowed_schema_update_options}"
)
if destination_dataset_table:
destination_project, destination_dataset, destination_table = self.hook.split_tablename(
table_input=destination_dataset_table, default_project_id=self.project_id
)
destination_dataset_table = { # type: ignore
"projectId": destination_project,
"datasetId": destination_dataset,
"tableId": destination_table,
}
if cluster_fields:
cluster_fields = {"fields": cluster_fields} # type: ignore
query_param_list: list[tuple[Any, str, str | bool | None | dict, type | tuple[type]]] = [
(sql, "query", None, (str,)),
(priority, "priority", priority, (str,)),
(use_legacy_sql, "useLegacySql", self.use_legacy_sql, bool),
(query_params, "queryParameters", None, list),
(udf_config, "userDefinedFunctionResources", None, list),
(maximum_billing_tier, "maximumBillingTier", None, int),
(maximum_bytes_billed, "maximumBytesBilled", None, float),
(time_partitioning, "timePartitioning", {}, dict),
(range_partitioning, "rangePartitioning", {}, dict),
(schema_update_options, "schemaUpdateOptions", None, list),
(destination_dataset_table, "destinationTable", None, dict),
(cluster_fields, "clustering", None, dict),
]
for param_raw, param_name, param_default, param_type in query_param_list:
param: Any
if param_name not in configuration["query"] and param_raw in [None, {}, ()]:
if param_name == "timePartitioning":
param = _cleanse_time_partitioning(destination_dataset_table, time_partitioning)
else:
param = param_default
else:
param = param_raw
if param in [None, {}, ()]:
continue
_api_resource_configs_duplication_check(param_name, param, configuration["query"])
configuration["query"][param_name] = param
# check valid type of provided param,
# it last step because we can get param from 2 sources,
# and first of all need to find it
_validate_value(param_name, configuration["query"][param_name], param_type)
if param_name == "schemaUpdateOptions" and param:
self.log.info("Adding experimental 'schemaUpdateOptions': %s", schema_update_options)
if param_name == "destinationTable":
for key in ["projectId", "datasetId", "tableId"]:
if key not in configuration["query"]["destinationTable"]:
raise ValueError(
"Not correct 'destinationTable' in "
"api_resource_configs. 'destinationTable' "
"must be a dict with {'projectId':'', "
"'datasetId':'', 'tableId':''}"
)
configuration["query"].update(
{
"allowLargeResults": allow_large_results,
"flattenResults": flatten_results,
"writeDisposition": write_disposition,
"createDisposition": create_disposition,
}
)
if (
"useLegacySql" in configuration["query"]
and configuration["query"]["useLegacySql"]
and "queryParameters" in configuration["query"]
):
raise ValueError("Query parameters are not allowed when using legacy SQL")
if labels:
_api_resource_configs_duplication_check("labels", labels, configuration)
configuration["labels"] = labels
if encryption_configuration:
configuration["query"]["destinationEncryptionConfiguration"] = encryption_configuration
return configuration
def _bind_parameters(operation: str, parameters: dict) -> str:
"""Bind parameters to a SQL query."""
# inspired by MySQL Python Connector (conversion.py)
string_parameters = {} # type dict[str, str]
for name, value in parameters.items():
if value is None:
string_parameters[name] = "NULL"
elif isinstance(value, str):
string_parameters[name] = "'" + _escape(value) + "'"
else:
string_parameters[name] = str(value)
return operation % string_parameters
def _escape(s: str) -> str:
"""Escape special characters in a SQL query string."""
e = s
e = e.replace("\\", "\\\\")
e = e.replace("\n", "\\n")
e = e.replace("\r", "\\r")
e = e.replace("'", "\\'")
e = e.replace('"', '\\"')
return e
def _cleanse_time_partitioning(
destination_dataset_table: str | None, time_partitioning_in: dict | None
) -> dict: # if it is a partitioned table ($ is in the table name) add partition load option
if time_partitioning_in is None:
time_partitioning_in = {}
time_partitioning_out = {}
if destination_dataset_table and "$" in destination_dataset_table:
time_partitioning_out["type"] = "DAY"
time_partitioning_out.update(time_partitioning_in)
return time_partitioning_out
def _validate_value(key: Any, value: Any, expected_type: type | tuple[type]) -> None:
"""Check expected type and raise error if type is not correct."""
if not isinstance(value, expected_type):
raise TypeError(f"{key} argument must have a type {expected_type} not {type(value)}")
def _api_resource_configs_duplication_check(
key: Any, value: Any, config_dict: dict, config_dict_name="api_resource_configs"
) -> None:
if key in config_dict and value != config_dict[key]:
raise ValueError(
f"Values of {key} param are duplicated. "
f"{config_dict_name} contained {key} param "
f"in `query` config and {key} was also provided "
"with arg to run_query() method. Please remove duplicates."
)
def _validate_src_fmt_configs(
source_format: str,
src_fmt_configs: dict,
valid_configs: list[str],
backward_compatibility_configs: dict | None = None,
) -> dict:
"""
Validate ``src_fmt_configs`` against a valid config for the source format.
Adds the backward compatibility config to ``src_fmt_configs``.
:param source_format: File format to export.
:param src_fmt_configs: Configure optional fields specific to the source format.
:param valid_configs: Valid configuration specific to the source format
:param backward_compatibility_configs: The top-level params for backward-compatibility
"""
if backward_compatibility_configs is None:
backward_compatibility_configs = {}
for k, v in backward_compatibility_configs.items():
if k not in src_fmt_configs and k in valid_configs:
src_fmt_configs[k] = v
for k in src_fmt_configs:
if k not in valid_configs:
raise ValueError(f"{k} is not a valid src_fmt_configs for type {source_format}.")
return src_fmt_configs
def _format_schema_for_description(schema: dict) -> list:
"""
Reformat the schema to match cursor description standard.
The description should be a tuple of 7 elemenbts: name, type, display_size,
internal_size, precision, scale, null_ok.
"""
description = []
for field in schema["fields"]:
mode = field.get("mode", "NULLABLE")
field_description = (
field["name"],
field["type"],
None,
None,
None,
None,
mode == "NULLABLE",
)
description.append(field_description)
return description
| BigQueryCursor |
python | huggingface__transformers | src/transformers/models/esm/modeling_esmfold.py | {
"start": 59636,
"end": 60235
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layers = nn.ModuleList()
for _ in range(config.num_transition_layers):
l = EsmFoldStructureModuleTransitionLayer(config)
self.layers.append(l)
self.dropout = nn.Dropout(config.dropout_rate)
self.layer_norm = LayerNorm(config.sequence_dim)
def forward(self, s):
for l in self.layers:
s = l(s)
s = self.dropout(s)
s = self.layer_norm(s)
return s
| EsmFoldStructureModuleTransition |
python | bokeh__bokeh | src/bokeh/models/formatters.py | {
"start": 4237,
"end": 5660
} | class ____(BasicTickFormatter):
''' A ``TickFormatter`` for values in WebMercator units.
Some map plot types internally use WebMercator to describe coordinates,
plot bounds, etc. These units are not very human-friendly. This tick
formatter will convert WebMercator units into Latitude and Longitude
for display on axes.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
dimension = Nullable(Enum(LatLon), help="""
Specify whether to format ticks for Latitude or Longitude.
Projected coordinates are not separable, computing Latitude and Longitude
tick labels from Web Mercator requires considering coordinates from both
dimensions together. Use this property to specify which result should be
used for display.
Typically, if the formatter is for an x-axis, then dimension should be
``"lon"`` and if the formatter is for a y-axis, then the dimension
should be `"lat"``.
In order to prevent hard to debug errors, there is no default value for
dimension. Using an un-configured ``MercatorTickFormatter`` will result in
a validation error and a JavaScript console error.
""")
@error(MISSING_MERCATOR_DIMENSION)
def _check_missing_dimension(self):
if self.dimension is None:
return str(self)
| MercatorTickFormatter |
python | numba__numba | numba/core/pythonapi.py | {
"start": 2062,
"end": 2692
} | class ____(namedtuple("_ReflectContext",
("context", "builder", "pyapi", "env_manager",
"is_error"))):
"""
The facilities required by reflection implementations.
"""
__slots__ = ()
# XXX the error bit is currently unused by consumers (e.g. PyCallWrapper)
def set_error(self):
self.builder.store(self.is_error, cgutils.true_bit)
def box(self, typ, val):
return self.pyapi.from_native_value(typ, val, self.env_manager)
def reflect(self, typ, val):
return self.pyapi.reflect_native_value(typ, val, self.env_manager)
| _ReflectContext |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 15826,
"end": 15913
} | class ____(IterableExportStreamAdjustableRange):
data_field = "emailClick"
| EmailClick |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 25647,
"end": 25891
} | class ____(MixinUnsafeUrl, TestRefererMiddleware):
settings = {
"REFERRER_POLICY": "scrapy.spidermiddlewares.referer.OriginWhenCrossOriginPolicy"
}
req_meta = {"referrer_policy": POLICY_UNSAFE_URL}
| TestRequestMetaPrecedence003 |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/users/main.py | {
"start": 1413,
"end": 1886
} | class ____(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
if users.is_current_user_admin():
self.response.write("You are an administrator.")
else:
self.response.write("You are not an administrator.")
else:
self.response.write("You are not logged in.")
app = webapp2.WSGIApplication([("/", MainPage), ("/admin", AdminPage)], debug=True)
| AdminPage |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py | {
"start": 467,
"end": 643
} | class ____:
def __index__(self):
print("ruff") # [invalid-index-return]
# TODO: Once Ruff has better type checking
def return_index():
return "3"
| IndexNoReturn |
python | jina-ai__jina | tests/integration/deployments/test_deployment.py | {
"start": 10064,
"end": 11600
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
for doc in docs:
if doc.text == 'slow':
time.sleep(1.0)
def _create_regular_deployment(
port,
name='',
executor=None,
uses_before=False,
uses_after=False,
polling=PollingType.ANY,
shards=None,
replicas=None,
):
args = set_deployment_parser().parse_args(['--port', str(port)])
args.name = name
if shards:
args.shards = shards
if replicas:
args.replicas = replicas
args.polling = polling
if executor:
args.uses = executor if executor else 'NameChangeExecutor'
if uses_after:
args.uses_after = executor if executor else 'NameChangeExecutor'
if uses_before:
args.uses_before = executor if executor else 'NameChangeExecutor'
return Deployment(args, include_gateway=False)
def _create_gateway_deployment(
graph_description, deployments_addresses, deployments_metadata, port
):
return Deployment(
set_gateway_parser().parse_args(
[
'--graph-description',
graph_description,
'--deployments-addresses',
deployments_addresses,
'--deployments-metadata',
deployments_metadata,
'--port',
str(port),
]
),
include_gateway=False,
)
async def async_inputs():
for _ in range(20):
yield Document(text='client0-Request')
| FastSlowExecutor |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/data_utils.py | {
"start": 11662,
"end": 12884
} | class ____(object):
"""Wrap an iterator with a lock and propagate exceptions to all threads."""
def __init__(self, it):
self.it = it
self.lock = threading.Lock()
# After a generator throws an exception all subsequent next() calls raise a
# StopIteration Exception. This, however, presents an issue when mixing
# generators and threading because it means the order of retrieval need not
# match the order in which the generator was called. This can make it appear
# that a generator exited normally when in fact the terminating exception is
# just in a different thread. In order to provide thread safety, once
# self.it has thrown an exception we continue to throw the same exception.
self._exception = None
def __iter__(self):
return self
def next(self):
return self.__next__()
def __next__(self):
with self.lock:
if self._exception:
raise self._exception # pylint: disable=raising-bad-type
try:
return next(self.it)
except Exception as e:
self._exception = e
raise
def threadsafe_generator(f):
@functools.wraps(f)
def g(*a, **kw):
return ThreadsafeIter(f(*a, **kw))
return g
| ThreadsafeIter |
python | tensorflow__tensorflow | tensorflow/compiler/tests/ensure_shape_op_test.py | {
"start": 1003,
"end": 1861
} | class ____(xla_test.XLATestCase):
def testEnsureShape(self):
with self.session() as sess:
p = array_ops.placeholder(dtypes.int32)
with self.test_scope():
op = check_ops.ensure_shape(p, (None, 3))
expected_out = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
self.assertAllEqual(expected_out,
sess.run(op, {p: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]}))
def testInvalidEnsureShape(self):
with self.session() as sess:
p = array_ops.placeholder(dtypes.int32)
with self.test_scope():
op = check_ops.ensure_shape(p, (None, 3, 3))
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
"is not compatible with expected shape"):
sess.run(op, {p: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]})
if __name__ == "__main__":
test.main()
| EnsureShapeOpTest |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 164239,
"end": 164478
} | class ____(RecvmsgTests, SendrecvmsgUDP6TestBase):
pass
@requireAttrs(socket.socket, "recvmsg_into")
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.')
@requireSocket("AF_INET6", "SOCK_DGRAM")
| RecvmsgUDP6Test |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 24307,
"end": 24686
} | class ____(CompressionTestMixin):
"""Specialization of CompressionTestMixin when we expect no compression."""
def verify_wire_bytes(self, bytes_in, bytes_out):
# Bytes out includes the 4-byte mask key per message.
self.assertEqual(bytes_out, 3 * (len(self.MESSAGE) + 6))
self.assertEqual(bytes_in, 3 * (len(self.MESSAGE) + 2))
| UncompressedTestMixin |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_3des.py | {
"start": 1773,
"end": 2793
} | class ____:
test_kat = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "OFB"),
[
"TOFBpermop.rsp",
"TOFBsubtab.rsp",
"TOFBvarkey.rsp",
"TOFBvartext.rsp",
"TOFBinvperm.rsp",
],
lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)),
lambda iv, **kwargs: OFB(binascii.unhexlify(iv)),
)
test_mmt = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "3DES", "OFB"),
["TOFBMMT1.rsp", "TOFBMMT2.rsp", "TOFBMMT3.rsp"],
lambda key1, key2, key3, **kwargs: algorithms.TripleDES(
binascii.unhexlify(key1 + key2 + key3)
),
lambda iv, **kwargs: OFB(binascii.unhexlify(iv)),
)
@pytest.mark.supported(
only_if=lambda backend: backend.cipher_supported(
algorithms.TripleDES(b"\x00" * 8), CFB(b"\x00" * 8)
),
skip_message="Does not support TripleDES CFB",
)
| TestTripleDESModeOFB |
python | dagster-io__dagster | python_modules/dagster/dagster/components/testing/deprecated/utils.py | {
"start": 810,
"end": 12346
} | class ____:
project_root: Path
defs_folder_path: Path
component_path: Path
project_name: str
component_format: ScaffoldFormatOptions
@contextmanager
def swap_defs_file(self, defs_path: Path, component_body: Optional[dict[str, Any]]):
check.invariant(
defs_path.suffix == ".yaml",
"Attributes are only supported for yaml components",
)
check.invariant(defs_path.exists(), "defs.yaml must exist")
# no need to override there is no component body
if component_body is None:
yield
return
temp_dir = Path(tempfile.mkdtemp())
temp_path = temp_dir / defs_path.name
try:
shutil.copy2(defs_path, temp_path)
defs_path.write_text(yaml.safe_dump(component_body))
yield
finally:
if temp_path.exists():
defs_path.unlink(missing_ok=True)
shutil.copy2(temp_path, defs_path)
shutil.rmtree(temp_dir)
@contextmanager
def load(
self, component_body: Optional[dict[str, Any]] = None
) -> Iterator[tuple["Component", "Definitions"]]:
defs_path = self.defs_folder_path / "defs.yaml"
with self.swap_defs_file(defs_path, component_body):
with self.load_instance(0) as (component, defs):
yield component, defs
@contextmanager
def load_instance(
self, instance_key: Union[int, str]
) -> Iterator[tuple[Component, Definitions]]:
assert isinstance(instance_key, int) # only int for now
with self.load_all() as components:
yield components[instance_key][0], components[instance_key][1]
@contextmanager
def load_all(self) -> Iterator[list[tuple[Component, Definitions]]]:
with alter_sys_path(to_add=[str(self.project_root / "src")], to_remove=[]):
module_path = get_module_path(
defs_module_name=f"{self.project_name}.defs", component_path=self.component_path
)
try:
yield get_all_components_defs_from_defs_path(
project_root=self.project_root,
module_path=module_path,
)
finally:
modules_to_remove = [name for name in sys.modules if name.startswith(module_path)]
for name in modules_to_remove:
del sys.modules[name]
@deprecated(
additional_warn_text="Use dagster.components.testing.create_defs_folder_sandbox instead.",
breaking_version="2.0.0",
)
@contextmanager
def scaffold_defs_sandbox(
*,
component_cls: type,
component_path: Optional[Union[Path, str]] = None,
scaffold_params: Optional[dict[str, Any]] = None,
scaffold_format: ScaffoldFormatOptions = "yaml",
project_name: Optional[str] = None,
) -> Iterator[DefsPathSandbox]:
"""Create a lightweight sandbox to scaffold and instantiate a component. Useful
for those authoring component types.
Scaffold defs sandbox creates a temporary project that mimics the defs folder portion
of a real dagster project.
It then invokes the scaffolder on the component class that produces. After
scaffold_defs_sandbox yields a DefsPathSandbox object.
DefsPathSandbox has a few properties useful for different types of tests:
* defs_folder_path: The absolute path to the defs folder where the component
is scaffolded. The user can inspect and load files that the scaffolder has produced.
e.g. (defs_folder_path / "defs.yaml").exists()
* component_path: The relative path to the component within the defs folder. If not
provided, a random name is generated.
* project_name: If not provided, a random name is generated.
Once the sandbox is created the user has the option to load the definitions produced
by the component using the load method on DefsPathSandbox.
By default it will produce the component based on the persisted `defs.yaml` file. You
can also supply a component body to the load method to override the defs.yaml file with
an in-memory component body.
This sandbox does not provide complete environmental isolation, but does provide some isolation guarantees
to do its best to isolate the test from and restore the environment after the test.
* A file structure like this is created: <<temp folder>> / src / <<project_name>> / defs / <<component_path>>
* <<temp folder>> / src is placed in sys.path during the loading process
* The last element of the component path is loaded as a namespace package
* Any modules loaded during the process that descend from defs module are evicted from sys.modules on cleanup.
Args:
component_cls: The component class to scaffold
component_path: Optional path where the component should be scaffolded. It is relative to the defs folder. Defaults to a random name at the root of the defs folder.
scaffold_params: Optional parameters to pass to the scaffolder in dictionary form. E.g. if you scaffold a component with dg scaffold defs MyComponent --param-one value-one the scaffold_params should be {"param_one": "value-one"}.
scaffold_format: Format to use for scaffolding (default: "yaml"). Can also be "python".
project_name: Optional name for the project (default: random name).
Returns:
Iterator[DefsPathSandbox]: A context manager that yields a DefsPathSandbox
Example:
.. code-block:: python
with scaffold_defs_sandbox(component_cls=MyComponent) as sandbox:
assert (sandbox.defs_folder_path / "defs.yaml").exists()
assert (sandbox.defs_folder_path / "my_component_config_file.yaml").exists() # produced by MyComponentScaffolder
with scaffold_defs_sandbox(component_cls=MyComponent, scaffold_params={"asset_key": "my_asset"}) as sandbox:
with sandbox.load() as (component, defs):
assert isinstance(component, MyComponent)
assert defs.get_asset_def("my_asset").key == AssetKey("my_asset")
with scaffold_defs_sandbox(component_cls=MyComponent) as sandbox:
with sandbox.load(defs_yaml_contents={"type": "MyComponent", "attributes": {"asset_key": "different_asset_key"}}) as (component, defs):
assert isinstance(component, MyComponent)
assert defs.get_asset_def("different_asset_key").key == AssetKey("different_asset_key")
"""
from dagster.components.testing.utils import get_original_module_name, random_importable_name
project_name = project_name or random_importable_name()
component_path = component_path or random_importable_name()
typename = get_original_module_name(component_cls)
with tempfile.TemporaryDirectory() as project_root_str:
project_root = Path(project_root_str)
defs_folder_path = project_root / "src" / project_name / "defs" / component_path
defs_folder_path.mkdir(parents=True, exist_ok=True)
scaffold_object(
path=defs_folder_path,
# obj=component_cls,
typename=typename,
json_params=json.dumps(scaffold_params) if scaffold_params else None,
scaffold_format=scaffold_format,
project_root=project_root,
)
yield DefsPathSandbox(
project_root=project_root,
defs_folder_path=defs_folder_path,
project_name=project_name,
component_path=Path(component_path),
component_format=scaffold_format,
)
@deprecated(
breaking_version="2.0.0",
)
def get_module_path(defs_module_name: str, component_path: Path):
component_module_path = str(component_path).replace("/", ".")
return f"{defs_module_name}.{component_module_path}"
def flatten_components(parent_component: Optional[Component]) -> list[Component]:
if isinstance(parent_component, CompositeYamlComponent):
return list(parent_component.components)
elif isinstance(parent_component, Component):
return [parent_component]
else:
return []
@deprecated(
breaking_version="2.0.0",
additional_warn_text="Use dagster.ComponentTree.for_project instead.",
)
def get_component_defs_within_project(
*,
project_root: Union[str, Path],
component_path: Union[str, Path],
instance_key: int = 0,
) -> tuple[Component, Definitions]:
"""Get the component defs for a component within a project. This only works if dagster_dg_core is installed.
Args:
project_root: The root of the project.
component_path: The path to the component.
Returns:
A tuple of the component and its definitions.
"""
all_component_defs = get_all_components_defs_within_project(
project_root=project_root, component_path=component_path
)
return all_component_defs[instance_key][0], all_component_defs[instance_key][1]
@deprecated(
breaking_version="2.0.0",
additional_warn_text="Use dagster.ComponentTree.for_project instead.",
)
def get_all_components_defs_within_project(
*,
project_root: Union[str, Path],
component_path: Union[str, Path],
) -> list[tuple[Component, Definitions]]:
"""Get all the component defs for a component within a project. This only works if dagster_dg_core is installed.
Args:
project_root: The root of the project.
component_path: The path to the component.
Returns:
A list of tuples of the component and its definitions.
"""
try:
from dagster_dg_core.config import discover_config_file
from dagster_dg_core.context import DgContext
except ImportError:
raise Exception(
"dagster_dg_core is not installed. Please install it to use default project_name and defs module from pyproject.toml or dg.toml."
)
project_root = Path(project_root)
component_path = Path(component_path)
dg_context = DgContext.from_file_discovery_and_command_line_config(
path=check.not_none(discover_config_file(project_root), "No project config file found."),
command_line_config={},
)
return get_all_components_defs_from_defs_path(
module_path=get_module_path(dg_context.defs_module_name, component_path),
project_root=project_root,
)
@deprecated(
breaking_version="2.0.0",
additional_warn_text="Use dagster.ComponentTree.for_project instead.",
)
def get_all_components_defs_from_defs_path(
*,
module_path: str,
project_root: Union[str, Path],
) -> list[tuple[Component, Definitions]]:
module = importlib.import_module(module_path)
context = ComponentTree(
defs_module=module,
project_root=Path(project_root),
).load_context
components = flatten_components(get_component(context))
return [(component, component.build_defs(context)) for component in components]
@deprecated(
breaking_version="2.0.0",
additional_warn_text="Use dagster.ComponentTree.for_project instead.",
)
def get_component_defs_from_defs_path(
*, module_path: str, project_root: Union[str, Path]
) -> tuple[Component, Definitions]:
components = get_all_components_defs_from_defs_path(
project_root=project_root,
module_path=module_path,
)
check.invariant(
len(components) == 1,
"Only one component is supported. To get all components use get_all_components_defs_from_defs_path.",
)
return components[0]
| DefsPathSandbox |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/static_analysis/type_inference.py | {
"start": 18706,
"end": 19810
} | class ____(transformer.Base):
"""AST visitor that applies type inference to each function separately."""
def __init__(self, source_info, graphs, resolver):
super(FunctionVisitor, self).__init__(source_info)
self.graphs = graphs
self.resolver = resolver
def visit_FunctionDef(self, node):
subgraph = self.graphs[node]
scope = anno.getanno(node, annos.NodeAnno.ARGS_AND_BODY_SCOPE)
closure_types = anno.getanno(node, anno.Static.CLOSURE_TYPES, {})
analyzer = Analyzer(subgraph, self.resolver, self.ctx.info.namespace, scope,
closure_types)
analyzer.visit_forward()
# Recursively process any remaining subfunctions.
node.body = self.visit_block(node.body)
return node
def resolve(node, source_info, graphs, resolver):
"""Performs type inference.
Args:
node: ast.AST
source_info: transformer.SourceInfo
graphs: Dict[ast.FunctionDef, cfg.Graph]
resolver: Resolver
Returns:
ast.AST
"""
visitor = FunctionVisitor(source_info, graphs, resolver)
node = visitor.visit(node)
return node
| FunctionVisitor |
python | django__django | tests/admin_views/models.py | {
"start": 29895,
"end": 30050
} | class ____(models.Model):
interesting_name = models.CharField(max_length=100)
def __str__(self):
return self.interesting_name
| CamelCaseModel |
python | pyinstaller__pyinstaller | PyInstaller/depend/dylib.py | {
"start": 8200,
"end": 13220
} | class ____:
def __init__(self, entries):
self._regex = re.compile('|'.join(entries), re.I) if entries else None
def check_library(self, libname):
if self._regex:
return self._regex.match(os.path.basename(libname))
return False
if compat.is_darwin:
import macholib.util
class MacExcludeList(MatchList):
def __init__(self, entries):
super().__init__(entries)
def check_library(self, libname):
# Try the global exclude list.
result = super().check_library(libname)
if result:
return result
# Exclude libraries in standard system locations.
return macholib.util.in_system_path(libname)
exclude_list = MacExcludeList(_excludes)
include_list = MatchList(_includes)
elif compat.is_win:
from PyInstaller.utils.win32 import winutils
class WinExcludeList(MatchList):
def __init__(self, entries):
super().__init__(entries)
self._windows_dir = pathlib.Path(winutils.get_windows_dir()).resolve()
# When running as SYSTEM user, the home directory is `%WINDIR%\system32\config\systemprofile`.
self._home_dir = pathlib.Path.home().resolve()
self._system_home = self._windows_dir in self._home_dir.parents
def check_library(self, libname):
# Try the global exclude list. The global exclude list contains lower-cased names, so lower-case the input
# for case-normalized comparison.
result = super().check_library(libname.lower())
if result:
return result
# Exclude everything from the Windows directory by default; but allow contents of user's gome directory if
# that happens to be rooted under Windows directory (e.g., when running PyInstaller as SYSTEM user).
lib_fullpath = pathlib.Path(libname).resolve()
exclude = self._windows_dir in lib_fullpath.parents
if exclude and self._system_home and self._home_dir in lib_fullpath.parents:
exclude = False
return exclude
exclude_list = WinExcludeList(_excludes)
include_list = MatchList(_includes)
else:
exclude_list = MatchList(_excludes)
include_list = MatchList(_includes)
_seen_wine_dlls = set() # Used for warning tracking in include_library()
def include_library(libname):
"""
Check if the dynamic library should be included with application or not.
"""
if exclude_list.check_library(libname) and not include_list.check_library(libname):
# Library is excluded and is not overridden by include list. It should be excluded.
return False
# If we are running under Wine and the library is a Wine built-in DLL, ensure that it is always excluded. Typically,
# excluding a DLL leads to an incomplete bundle and run-time errors when the said DLL is not installed on the target
# system. However, having Wine built-in DLLs collected is even more detrimental, as they usually provide Wine's
# implementation of low-level functionality, and therefore cannot be used on actual Windows (i.e., system libraries
# from the C:\Windows\system32 directory that might end up collected due to ``_win_includes`` list; a prominent
# example are VC runtime DLLs, for which Wine provides their own implementation, unless user explicitly installs
# Microsoft's VC redistributable package in their Wine environment). Therefore, excluding the Wine built-in DLLs
# actually improves the chances of the bundle running on Windows, or at least makes the issue easier to debug by
# turning it into the "standard" missing DLL problem. Exclusion should not affect the bundle's ability to run under
# Wine itself, as the excluded DLLs are available there.
if compat.is_win_wine and compat.is_wine_dll(libname):
# Display warning message only once per DLL. Note that it is also displayed only if the DLL were to be included
# in the first place.
if libname not in _seen_wine_dlls:
logger.warning("Excluding Wine built-in DLL: %s", libname)
_seen_wine_dlls.add(libname)
return False
return True
# Patterns for suppressing warnings about missing dynamically linked libraries
_warning_suppressions = []
# On some systems (e.g., openwrt), libc.so might point to ldd. Suppress warnings about it.
if compat.is_linux:
_warning_suppressions.append(r'ldd')
# Suppress warnings about unresolvable UCRT DLLs (see issue #1566) on Windows 10 and 11.
if compat.is_win_10 or compat.is_win_11:
_warning_suppressions.append(r'api-ms-win-.*\.dll')
missing_lib_warning_suppression_list = MatchList(_warning_suppressions)
def warn_missing_lib(libname):
"""
Check if a missing-library warning should be displayed for the given library name (or full path).
"""
return not missing_lib_warning_suppression_list.check_library(libname)
| MatchList |
python | ApeWorX__ape | src/ape/managers/_contractscache.py | {
"start": 3077,
"end": 37704
} | class ____(BaseManager):
"""
A collection of cached contracts. Contracts can be cached in two ways:
1. An in-memory cache of locally deployed contracts
2. A cache of contracts per network (only permanent networks are stored this way)
When retrieving a contract, if a :class:`~ape.api.explorers.ExplorerAPI` is used,
it will be cached to disk for faster look-up next time.
"""
# ecosystem_name -> network_name -> cache_name -> cache
_caches: dict[str, dict[str, dict[str, ApeDataCache]]] = {}
# chain_id -> address -> custom_err
# Cached to prevent calling `new_class` multiple times with conflicts.
_custom_error_types: dict[int, dict[AddressType, set[type[CustomError]]]] = {}
@property
def contract_types(self) -> ApeDataCache[ContractType]:
return self._get_data_cache("contract_types", ContractType)
@property
def proxy_infos(self) -> ApeDataCache[ProxyInfoAPI]:
return self._get_data_cache("proxy_info", ProxyInfoAPI)
@property
def blueprints(self) -> ApeDataCache[ContractType]:
return self._get_data_cache("blueprints", ContractType)
@property
def contract_creations(self) -> ApeDataCache[ContractCreation]:
return self._get_data_cache("contract_creation", ContractCreation)
def _get_data_cache(
self,
key: str,
model_type: type,
ecosystem_key: Optional[str] = None,
network_key: Optional[str] = None,
):
ecosystem_name = ecosystem_key or self.provider.network.ecosystem.name
network_name = network_key or self.provider.network.name.replace("-fork", "")
self._caches.setdefault(ecosystem_name, {})
self._caches[ecosystem_name].setdefault(network_name, {})
if cache := self._caches[ecosystem_name][network_name].get(key):
return cache
self._caches[ecosystem_name][network_name][key] = ApeDataCache(
self.config_manager.DATA_FOLDER, ecosystem_name, network_name, key, model_type
)
return self._caches[ecosystem_name][network_name][key]
@cached_property
def deployments(self) -> DeploymentDiskCache:
"""A manager for contract deployments across networks."""
return DeploymentDiskCache()
def __setitem__(
self, address: AddressType, item: Union[ContractType, ProxyInfoAPI, ContractCreation]
):
"""
Cache the given contract type. Contracts are cached in memory per session.
In live networks, contracts also get cached to disk at
``.ape/{ecosystem_name}/{network_name}/contract_types/{address}.json``
for faster look-up next time.
Args:
address (AddressType): The on-chain address of the contract.
item (ContractType | ProxyInfoAPI | ContractCreation): The contract's type, proxy info,
or creation metadata.
"""
# Note: Can't cache blueprints this way.
address = self.provider.network.ecosystem.decode_address(int(address, 16))
if isinstance(item, ContractType):
self.cache_contract_type(address, item)
elif isinstance(item, ProxyInfoAPI):
self.cache_proxy_info(address, item)
elif isinstance(item, ContractCreation):
self.cache_contract_creation(address, item)
elif contract_type := getattr(item, "contract_type", None):
self.cache_contract_type(address, contract_type)
else:
raise TypeError(item)
def cache_contract_type(
self,
address: AddressType,
contract_type: ContractType,
ecosystem_key: Optional[str] = None,
network_key: Optional[str] = None,
):
"""
Cache a contract type at the given address for the given network.
If not connected, you must provider both ``ecosystem_key:`` and
``network_key::``.
Args:
address (AddressType): The address key.
contract_type (ContractType): The contract type to cache.
ecosystem_key (str | None): The ecosystem key. Defaults to
the connected ecosystem's name.
network_key (str | None): The network key. Defaults to the
connected network's name.
"""
# Get the cache in a way that doesn't require an active connection.
cache = self._get_data_cache(
"contract_types", ContractType, ecosystem_key=ecosystem_key, network_key=network_key
)
cache[address] = contract_type
# NOTE: The txn_hash is not included when caching this way.
if name := contract_type.name:
self.deployments.cache_deployment(
address, name, ecosystem_key=ecosystem_key, network_key=network_key
)
def cache_contract_creation(
self,
address: AddressType,
contract_creation: ContractCreation,
ecosystem_key: Optional[str] = None,
network_key: Optional[str] = None,
):
"""
Cache a contract creation object.
Args:
address (AddressType): The address of the contract.
contract_creation (ContractCreation): The object to cache.
ecosystem_key (str | None): The ecosystem key. Defaults to
the connected ecosystem's name.
network_key (str | None): The network key. Defaults to the
connected network's name.
"""
# Get the cache in a way that doesn't require an active connection.
cache = self._get_data_cache(
"contract_creation",
ContractCreation,
ecosystem_key=ecosystem_key,
network_key=network_key,
)
cache[address] = contract_creation
def __delitem__(self, address: AddressType):
"""
Delete a cached contract.
If using a live network, it will also delete the file-cache for the contract.
Args:
address (AddressType): The address to remove from the cache.
"""
del self.contract_types[address]
self._delete_proxy(address)
del self.contract_creations[address]
@contextmanager
def use_temporary_caches(self):
"""
Create temporary context where there are no cached items.
Useful for testing.
"""
caches = self._caches
self._caches = {}
with self.deployments.use_temporary_cache():
yield
self._caches = caches
def _delete_proxy(self, address: AddressType):
if info := self.proxy_infos[address]:
target = info.target
del self.proxy_infos[target]
del self.contract_types[target]
def __contains__(self, address: AddressType) -> bool:
return self.get(address) is not None
def cache_deployment(
self,
contract_instance: ContractInstance,
proxy_info: Optional[ProxyInfoAPI] = None,
detect_proxy: bool = True,
):
"""
Cache the given contract instance's type and deployment information.
Args:
contract_instance (:class:`~ape.contracts.base.ContractInstance`): The contract
to cache.
proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to
avoid the potentially expensive look-up.
detect_proxy (bool): Set to ``False`` to avoid detecting if the contract is a
proxy.
"""
address = contract_instance.address
contract_type = contract_instance.contract_type # may be a proxy
# Cache contract type in memory before proxy check,
# in case it is needed somewhere. It may get overridden.
self.contract_types.memory[address] = contract_type
if proxy_info:
# Was given proxy info.
self._cache_proxy_contract(address, proxy_info, contract_type, contract_instance)
elif detect_proxy:
# Proxy info was not provided. Use the connected ecosystem to figure it out.
if proxy_info := self.provider.network.ecosystem.get_proxy_info(address):
# The user is caching a deployment of a proxy with the target already set.
self._cache_proxy_contract(address, proxy_info, contract_type, contract_instance)
else:
# Cache as normal.
self.contract_types[address] = contract_type
else:
# Cache as normal; do not do expensive proxy detection.
self.contract_types[address] = contract_type
# Cache the deployment now.
txn_hash = contract_instance.txn_hash
if contract_name := contract_type.name:
self.deployments.cache_deployment(address, contract_name, transaction_hash=txn_hash)
return contract_type
def _cache_proxy_contract(
self,
address: AddressType,
proxy_info: ProxyInfoAPI,
contract_type: ContractType,
contract_instance: ContractInstance,
):
self.cache_proxy_info(address, proxy_info)
if implementation_contract := self.get(proxy_info.target):
updated_proxy_contract = _get_combined_contract_type(
contract_type, proxy_info, implementation_contract
)
self.contract_types[address] = updated_proxy_contract
# Use this contract type in the user's contract instance.
contract_instance.contract_type = updated_proxy_contract
else:
# No implementation yet. Just cache proxy.
self.contract_types[address] = contract_type
def cache_proxy_info(self, address: AddressType, proxy_info: ProxyInfoAPI):
"""
Cache proxy info for a particular address, useful for plugins adding already
deployed proxies. When you deploy a proxy locally, it will also call this method.
Args:
address (AddressType): The address of the proxy contract.
proxy_info (:class:`~ape.api.networks.ProxyInfo`): The proxy info class
to cache.
"""
self.proxy_infos[address] = proxy_info
def cache_blueprint(self, blueprint_id: str, contract_type: ContractType):
"""
Cache a contract blueprint.
Args:
blueprint_id (``str``): The ID of the blueprint. For example, in EIP-5202,
it would be the address of the deployed blueprint. For Starknet, it would
be the class identifier.
contract_type (``ContractType``): The contract type associated with the blueprint.
"""
self.blueprints[blueprint_id] = contract_type
def get_proxy_info(self, address: AddressType) -> Optional[ProxyInfoAPI]:
"""
Get proxy information about a contract using its address,
either from a local cache, a disk cache, or the provider.
Args:
address (AddressType): The address of the proxy contract.
Returns:
Optional[:class:`~ape.api.networks.ProxyInfoAPI`]
"""
return self.proxy_infos[address]
def get_creation_metadata(self, address: AddressType) -> Optional[ContractCreation]:
"""
Get contract creation metadata containing txn_hash, deployer, factory, block.
Args:
address (AddressType): The address of the contract.
Returns:
Optional[:class:`~ape.api.query.ContractCreation`]
"""
if creation := self.contract_creations[address]:
return creation
# Query and cache.
query = ContractCreationQuery(columns=["*"], contract=address)
get_creation = self.query_manager.query(query)
try:
if not (creation := next(get_creation, None)): # type: ignore[arg-type]
return None
except ApeException:
return None
self.contract_creations[address] = creation
return creation
def get_blueprint(self, blueprint_id: str) -> Optional[ContractType]:
"""
Get a cached blueprint contract type.
Args:
blueprint_id (``str``): The unique identifier used when caching
the blueprint.
Returns:
``ContractType``
"""
return self.blueprints[blueprint_id]
def _get_errors(
self, address: AddressType, chain_id: Optional[int] = None
) -> set[type[CustomError]]:
if chain_id is None and self.network_manager.active_provider is not None:
chain_id = self.chain_manager.chain_id
elif chain_id is None:
return set()
if chain_id not in self._custom_error_types:
return set()
errors = self._custom_error_types[chain_id]
if address in errors:
return errors[address]
return set()
def _cache_error(
self, address: AddressType, error: type[CustomError], chain_id: Optional[int] = None
):
if chain_id is None and self.network_manager.active_provider is not None:
chain_id = self.chain_manager.chain_id
elif chain_id is None:
return
if chain_id not in self._custom_error_types:
self._custom_error_types[chain_id] = {address: set()}
elif address not in self._custom_error_types[chain_id]:
self._custom_error_types[chain_id][address] = set()
self._custom_error_types[chain_id][address].add(error)
def __getitem__(self, address: AddressType) -> ContractType:
contract_type = self.get(address)
if not contract_type:
# Create error message from custom exception cls.
err = ContractNotFoundError(
address, self.provider.network.explorer is not None, self.provider.network_choice
)
# Must raise KeyError.
raise KeyError(str(err))
return contract_type
def get_multiple(
self, addresses: Collection[AddressType], concurrency: Optional[int] = None
) -> dict[AddressType, ContractType]:
"""
Get contract types for all given addresses.
Args:
addresses (list[AddressType): A list of addresses to get contract types for.
concurrency (Optional[int]): The number of threads to use. Defaults to
``min(4, len(addresses))``.
Returns:
dict[AddressType, ContractType]: A mapping of addresses to their respective
contract types.
"""
if not addresses:
logger.warning("No addresses provided.")
return {}
def get_contract_type(addr: AddressType):
addr = self.conversion_manager.convert(addr, AddressType)
ct = self.get(addr)
if not ct:
logger.warning(f"Failed to locate contract at '{addr}'.")
return addr, None
else:
return addr, ct
converted_addresses: list[AddressType] = []
for address in converted_addresses:
if not self.conversion_manager.is_type(address, AddressType):
converted_address = self.conversion_manager.convert(address, AddressType)
converted_addresses.append(converted_address)
else:
converted_addresses.append(address)
contract_types = {}
default_max_threads = 4
max_threads = (
concurrency
if concurrency is not None
else min(len(addresses), default_max_threads) or default_max_threads
)
with ThreadPoolExecutor(max_workers=max_threads) as pool:
for address, contract_type in pool.map(get_contract_type, addresses):
if contract_type is None:
continue
contract_types[address] = contract_type
return contract_types
@nonreentrant(key_fn=lambda *args, **kwargs: args[1])
def get(
self,
address: AddressType,
default: Optional[ContractType] = None,
fetch_from_explorer: bool = True,
proxy_info: Optional[ProxyInfoAPI] = None,
detect_proxy: bool = True,
) -> Optional[ContractType]:
"""
Get a contract type by address.
If the contract is cached, it will return the contract from the cache.
Otherwise, if on a live network, it fetches it from the
:class:`~ape.api.explorers.ExplorerAPI`.
Args:
address (AddressType): The address of the contract.
default (Optional[ContractType]): A default contract when none is found.
Defaults to ``None``.
fetch_from_explorer (bool): Set to ``False`` to avoid fetching from an
explorer. Defaults to ``True``. Only fetches if it needs to (uses disk
& memory caching otherwise).
proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known,
to avoid the potentially expensive look-up.
detect_proxy (bool): Set to ``False`` to avoid detecting if it is a proxy.
Returns:
Optional[ContractType]: The contract type if it was able to get one,
otherwise the default parameter.
"""
try:
address_key: AddressType = self.conversion_manager.convert(address, AddressType)
except ConversionError:
if not address.startswith("0x"):
# Still raise conversion errors for ENS and such.
raise
# In this case, it at least _looked_ like an address.
return None
if contract_type := self.contract_types[address_key]:
# The ContractType was previously cached.
if default and default != contract_type:
# The given default ContractType is different than the cached one.
# Merge the two and cache the merged result.
combined_contract_type = _merge_contract_types(contract_type, default)
self.contract_types[address_key] = combined_contract_type
return combined_contract_type
return contract_type
# Contract is not cached yet. Check broader sources, such as an explorer.
if not proxy_info and detect_proxy:
# Proxy info not provided. Attempt to detect.
if not (proxy_info := self.proxy_infos[address_key]):
if proxy_info := self.provider.network.ecosystem.get_proxy_info(address_key):
self.proxy_infos[address_key] = proxy_info
if proxy_info:
if proxy_contract_type := self._get_proxy_contract_type(
address_key,
proxy_info,
fetch_from_explorer=fetch_from_explorer,
default=default,
):
# `proxy_contract_type` is one of the following:
# 1. A ContractType with the combined proxy and implementation ABIs
# 2. Implementation-only ABI ContractType (like forwarder proxies)
# 3. Proxy only ABI (e.g. unverified implementation ContractType)
return proxy_contract_type
# Also gets cached to disk for faster lookup next time.
if fetch_from_explorer:
contract_type = self._get_contract_type_from_explorer(address_key)
# Cache locally for faster in-session look-up.
if contract_type:
self.contract_types[address_key] = contract_type
elif default:
self.contract_types[address_key] = default
return default
return contract_type
def _get_proxy_contract_type(
self,
address: AddressType,
proxy_info: ProxyInfoAPI,
fetch_from_explorer: bool = True,
default: Optional[ContractType] = None,
) -> Optional[ContractType]:
"""
Combines the discoverable ABIs from the proxy contract and its implementation.
"""
implementation_contract_type = self._get_contract_type(
proxy_info.target,
fetch_from_explorer=fetch_from_explorer,
default=default,
)
proxy_contract_type = self._get_contract_type(
address, fetch_from_explorer=fetch_from_explorer
)
if proxy_contract_type is not None and implementation_contract_type is not None:
combined_contract = _get_combined_contract_type(
proxy_contract_type, proxy_info, implementation_contract_type
)
self.contract_types[address] = combined_contract
return combined_contract
elif implementation_contract_type is not None:
contract_type_to_cache = implementation_contract_type
self.contract_types[address] = implementation_contract_type
return contract_type_to_cache
elif proxy_contract_type is not None:
# In this case, the implementation ContactType was not discovered.
# However, we were able to discover the ContractType of the proxy.
# Proceed with caching the proxy; the user can update the type later
# when the implementation is discoverable.
self.contract_types[address] = proxy_contract_type
return proxy_contract_type
logger.warning(f"Unable to determine the ContractType for the proxy at '{address}'.")
return None
def _get_contract_type(
self,
address: AddressType,
fetch_from_explorer: bool = True,
default: Optional[ContractType] = None,
) -> Optional[ContractType]:
"""
Get the _exact_ ContractType for a given address. For proxy contracts, returns
the proxy ABIs if there are any and not the implementation ABIs.
"""
if contract_type := self.contract_types[address]:
return contract_type
elif fetch_from_explorer:
return self._get_contract_type_from_explorer(address)
return default
@classmethod
def get_container(cls, contract_type: ContractType) -> ContractContainer:
"""
Get a contract container for the given contract type.
Args:
contract_type (ContractType): The contract type to wrap.
Returns:
ContractContainer: A container object you can deploy.
"""
return ContractContainer(contract_type)
def instance_at(
self,
address: Union[str, AddressType],
contract_type: Optional[ContractType] = None,
txn_hash: Optional[Union[str, "HexBytes"]] = None,
abi: Optional[Union[list[ABI], dict, str, Path]] = None,
fetch_from_explorer: bool = True,
proxy_info: Optional[ProxyInfoAPI] = None,
detect_proxy: bool = True,
) -> ContractInstance:
"""
Get a contract at the given address. If the contract type of the contract is known,
either from a local deploy or a :class:`~ape.api.explorers.ExplorerAPI`, it will use that
contract type. You can also provide the contract type from which it will cache and use
next time.
Raises:
TypeError: When passing an invalid type for the `contract_type` arguments
(expects `ContractType`).
:class:`~ape.exceptions.ContractNotFoundError`: When the contract type is not found.
Args:
address (Union[str, AddressType]): The address of the plugin. If you are using the ENS
plugin, you can also provide an ENS domain name.
contract_type (Optional[``ContractType``]): Optionally provide the contract type
in case it is not already known.
txn_hash (Optional[Union[str, HexBytes]]): The hash of the transaction responsible for
deploying the contract, if known. Useful for publishing. Defaults to ``None``.
abi (Optional[Union[list[ABI], dict, str, Path]]): Use an ABI str, dict, path,
or ethpm models to create a contract instance class.
fetch_from_explorer (bool): Set to ``False`` to avoid fetching from the explorer.
Defaults to ``True``. Won't fetch unless it needs to (uses disk & memory caching
first).
proxy_info (Optional[ProxyInfoAPI]): Pass in the proxy info, if it is known, to avoid
the potentially expensive look-up.
detect_proxy (bool): Set to ``False`` to avoid detecting if the contract is a proxy.
Returns:
:class:`~ape.contracts.base.ContractInstance`
"""
if contract_type and not isinstance(contract_type, ContractType):
prefix = f"Expected type '{ContractType.__name__}' for argument 'contract_type'"
try:
suffix = f"; Given '{type(contract_type).__name__}'."
except Exception:
suffix = "."
raise TypeError(f"{prefix}{suffix}")
try:
contract_address = self.conversion_manager.convert(address, AddressType)
except ConversionError:
# Attempt as str.
raise ValueError(f"Unknown address value '{address}'.")
try:
# Always attempt to get an existing contract type to update caches
contract_type = self.get(
contract_address,
default=contract_type,
fetch_from_explorer=fetch_from_explorer,
proxy_info=proxy_info,
detect_proxy=detect_proxy,
)
except Exception as err:
if contract_type or abi:
# If a default contract type was provided, don't error and use it.
logger.error(str(err))
else:
raise # Current exception
if abi:
# if the ABI is a str then convert it to a JSON dictionary.
if isinstance(abi, Path) or (
isinstance(abi, str) and "{" not in abi and Path(abi).is_file()
):
# Handle both absolute and relative paths
abi_path = Path(abi)
if not abi_path.is_absolute():
abi_path = self.local_project.path / abi
try:
abi = json.loads(abi_path.read_text())
except Exception as err:
if contract_type:
# If a default contract type was provided, don't error and use it.
logger.error(str(err))
else:
raise # Current exception
elif isinstance(abi, str):
# JSON str
try:
abi = json.loads(abi)
except Exception as err:
if contract_type:
# If a default contract type was provided, don't error and use it.
logger.error(str(err))
else:
raise # Current exception
# If the ABI was a str, it should be a list now.
if isinstance(abi, (ABIList, list)):
contract_type = ContractType(abi=abi)
# Ensure we cache the contract-types from ABI!
self[contract_address] = contract_type
else:
raise TypeError(
f"Invalid ABI type '{type(abi)}', expecting str, list[ABI] or a JSON file."
)
if not contract_type:
raise ContractNotFoundError(
contract_address,
self.provider.network.explorer is not None,
self.provider.network_choice,
)
if not txn_hash:
# Check for txn_hash in deployments.
contract_name = getattr(contract_type, "name", f"{contract_type}") or ""
deployments = self.deployments[contract_name]
for deployment in deployments[::-1]:
if deployment.address == contract_address and deployment.transaction_hash:
txn_hash = deployment.transaction_hash
break
return ContractInstance(contract_address, contract_type, txn_hash=txn_hash)
@classmethod
def instance_from_receipt(
cls, receipt: "ReceiptAPI", contract_type: ContractType
) -> ContractInstance:
"""
A convenience method for creating instances from receipts.
Args:
receipt (:class:`~ape.api.transactions.ReceiptAPI`): The receipt.
contract_type (ContractType): The deployed contract type.
Returns:
:class:`~ape.contracts.base.ContractInstance`
"""
# NOTE: Mostly just needed this method to avoid a local import.
return ContractInstance.from_receipt(receipt, contract_type)
def get_deployments(self, contract_container: ContractContainer) -> list[ContractInstance]:
"""
Retrieves previous deployments of a contract container or contract type.
Locally deployed contracts are saved for the duration of the script and read from
``_local_deployments_mapping``, while those deployed on a live network are written to
disk in ``deployments_map.json``.
Args:
contract_container (:class:`~ape.contracts.ContractContainer`): The
``ContractContainer`` with deployments.
Returns:
list[:class:`~ape.contracts.ContractInstance`]: Returns a list of contracts that
have been deployed.
"""
contract_type = contract_container.contract_type
if not (contract_name := contract_type.name or ""):
return []
config_deployments = self._get_config_deployments(contract_name)
if not (deployments := [*config_deployments, *self.deployments[contract_name]]):
return []
instances: list[ContractInstance] = []
for deployment in deployments:
instance = ContractInstance(
deployment.address, contract_type, txn_hash=deployment.transaction_hash
)
instances.append(instance)
return instances
def _get_config_deployments(self, contract_name: str) -> list[Deployment]:
if not self.network_manager.connected:
return []
ecosystem_name = self.provider.network.ecosystem.name
network_name = self.provider.network.name
all_config_deployments = (
self.config_manager.deployments if self.config_manager.deployments else {}
)
ecosystem_deployments = all_config_deployments.get(ecosystem_name, {})
network_deployments = ecosystem_deployments.get(network_name, {})
return [
Deployment(address=c["address"], transaction_hash=c.get("transaction_hash"))
for c in network_deployments
if c["contract_type"] == contract_name
]
def clear_local_caches(self):
"""
Reset local caches to a blank state.
"""
if self.network_manager.connected:
for cache in (
self.contract_types,
self.proxy_infos,
self.contract_creations,
self.blueprints,
):
cache.memory = {}
self.deployments.clear_local()
def _get_contract_type_from_explorer(self, address: AddressType) -> Optional[ContractType]:
if not self.provider.network.explorer:
return None
try:
contract_type = self.provider.network.explorer.get_contract_type(address)
except Exception as err:
explorer_name = self.provider.network.explorer.name
if "rate limit" in str(err).lower():
# Don't show any additional error message during rate limit errors,
# if it can be helped, as it may scare users into thinking their
# contracts are not verified.
message = str(err)
else:
# Carefully word this message in a way that doesn't hint at
# any one specific reason, such as un-verified source code,
# which is potentially a scare for users.
message = (
f"Attempted to retrieve contract type from explorer '{explorer_name}' "
f"from address '{address}' but encountered an exception: {err}\n"
)
logger.error(message)
return None
if contract_type:
# Cache contract so faster look-up next time.
if not isinstance(contract_type, ContractType):
explorer_name = self.provider.network.explorer.name
wrong_type = type(contract_type)
wrong_type_str = getattr(wrong_type, "__name__", f"{wrong_type}")
logger.warning(
f"Explorer '{explorer_name}' returned unexpected "
f"type '{wrong_type_str}' ContractType."
)
return None
self.contract_types[address] = contract_type
return contract_type
def _get_combined_contract_type(
proxy_contract_type: ContractType,
proxy_info: ProxyInfoAPI,
implementation_contract_type: ContractType,
) -> ContractType:
proxy_abis = _get_relevant_additive_abis(proxy_contract_type)
# Include "hidden" ABIs, such as Safe's `masterCopy()`.
if proxy_info.abi and proxy_info.abi.signature not in [
abi.signature for abi in implementation_contract_type.abi
]:
proxy_abis.append(proxy_info.abi)
return _merge_abis(implementation_contract_type, proxy_abis)
def _get_relevant_additive_abis(contract_type: ContractType) -> list[ABI]:
# Get ABIs you would want to add to a base contract as extra,
# such as unique ABIs from proxies.
return [abi for abi in contract_type.abi if abi.type in ("error", "event", "function")]
def _merge_abis(base_contract: ContractType, extra_abis: list[ABI]) -> ContractType:
contract_type = base_contract.model_copy(deep=True)
contract_type.abi.extend(extra_abis)
return contract_type
def _merge_contract_types(
base_contract_type: ContractType, additive_contract_type: ContractType
) -> ContractType:
existing_methods = set(_get_relevant_additive_abis(base_contract_type))
relevant_abis = _get_relevant_additive_abis(additive_contract_type)
return _merge_abis(
base_contract_type,
[abi for abi in relevant_abis if abi not in existing_methods],
)
| ContractCache |
python | davidhalter__parso | parso/python/diff.py | {
"start": 8743,
"end": 19937
} | class ____:
"""
An advanced form of parsing a file faster. Unfortunately comes with huge
side effects. It changes the given module.
"""
def __init__(self, pgen_grammar, tokenizer, module):
self._pgen_grammar = pgen_grammar
self._tokenizer = tokenizer
self._module = module
def _reset(self):
self._copy_count = 0
self._parser_count = 0
self._nodes_tree = _NodesTree(self._module)
def update(self, old_lines, new_lines):
'''
The algorithm works as follows:
Equal:
- Assure that the start is a newline, otherwise parse until we get
one.
- Copy from parsed_until_line + 1 to max(i2 + 1)
- Make sure that the indentation is correct (e.g. add DEDENT)
- Add old and change positions
Insert:
- Parse from parsed_until_line + 1 to min(j2 + 1), hopefully not
much more.
Returns the new module node.
'''
LOG.debug('diff parser start')
# Reset the used names cache so they get regenerated.
self._module._used_names = None
self._parser_lines_new = new_lines
self._reset()
line_length = len(new_lines)
sm = difflib.SequenceMatcher(None, old_lines, self._parser_lines_new)
opcodes = sm.get_opcodes()
LOG.debug('line_lengths old: %s; new: %s' % (len(old_lines), line_length))
for operation, i1, i2, j1, j2 in opcodes:
LOG.debug('-> code[%s] old[%s:%s] new[%s:%s]',
operation, i1 + 1, i2, j1 + 1, j2)
if j2 == line_length and new_lines[-1] == '':
# The empty part after the last newline is not relevant.
j2 -= 1
if operation == 'equal':
line_offset = j1 - i1
self._copy_from_old_parser(line_offset, i1 + 1, i2, j2)
elif operation == 'replace':
self._parse(until_line=j2)
elif operation == 'insert':
self._parse(until_line=j2)
else:
assert operation == 'delete'
# With this action all change will finally be applied and we have a
# changed module.
self._nodes_tree.close()
if DEBUG_DIFF_PARSER:
# If there is reasonable suspicion that the diff parser is not
# behaving well, this should be enabled.
try:
code = ''.join(new_lines)
assert self._module.get_code() == code
_assert_valid_graph(self._module)
without_diff_parser_module = Parser(
self._pgen_grammar,
error_recovery=True
).parse(self._tokenizer(new_lines))
_assert_nodes_are_equal(self._module, without_diff_parser_module)
except AssertionError:
print(_get_debug_error_message(self._module, old_lines, new_lines))
raise
last_pos = self._module.end_pos[0]
if last_pos != line_length:
raise Exception(
('(%s != %s) ' % (last_pos, line_length))
+ _get_debug_error_message(self._module, old_lines, new_lines)
)
LOG.debug('diff parser end')
return self._module
def _enabled_debugging(self, old_lines, lines_new):
if self._module.get_code() != ''.join(lines_new):
LOG.warning('parser issue:\n%s\n%s', ''.join(old_lines), ''.join(lines_new))
def _copy_from_old_parser(self, line_offset, start_line_old, until_line_old, until_line_new):
last_until_line = -1
while until_line_new > self._nodes_tree.parsed_until_line:
parsed_until_line_old = self._nodes_tree.parsed_until_line - line_offset
line_stmt = self._get_old_line_stmt(parsed_until_line_old + 1)
if line_stmt is None:
# Parse 1 line at least. We don't need more, because we just
# want to get into a state where the old parser has statements
# again that can be copied (e.g. not lines within parentheses).
self._parse(self._nodes_tree.parsed_until_line + 1)
else:
p_children = line_stmt.parent.children
index = p_children.index(line_stmt)
if start_line_old == 1 \
and p_children[0].get_first_leaf().prefix.startswith(BOM_UTF8_STRING):
# If there's a BOM in the beginning, just reparse. It's too
# complicated to account for it otherwise.
copied_nodes = []
else:
from_ = self._nodes_tree.parsed_until_line + 1
copied_nodes = self._nodes_tree.copy_nodes(
p_children[index:],
until_line_old,
line_offset
)
# Match all the nodes that are in the wanted range.
if copied_nodes:
self._copy_count += 1
to = self._nodes_tree.parsed_until_line
LOG.debug('copy old[%s:%s] new[%s:%s]',
copied_nodes[0].start_pos[0],
copied_nodes[-1].end_pos[0] - 1, from_, to)
else:
# We have copied as much as possible (but definitely not too
# much). Therefore we just parse a bit more.
self._parse(self._nodes_tree.parsed_until_line + 1)
# Since there are potential bugs that might loop here endlessly, we
# just stop here.
assert last_until_line != self._nodes_tree.parsed_until_line, last_until_line
last_until_line = self._nodes_tree.parsed_until_line
def _get_old_line_stmt(self, old_line):
leaf = self._module.get_leaf_for_position((old_line, 0), include_prefixes=True)
if _ends_with_newline(leaf):
leaf = leaf.get_next_leaf()
if leaf.get_start_pos_of_prefix()[0] == old_line:
node = leaf
while node.parent.type not in ('file_input', 'suite'):
node = node.parent
# Make sure that if only the `else:` line of an if statement is
# copied that not the whole thing is going to be copied.
if node.start_pos[0] >= old_line:
return node
# Must be on the same line. Otherwise we need to parse that bit.
return None
def _parse(self, until_line):
"""
Parses at least until the given line, but might just parse more until a
valid state is reached.
"""
last_until_line = 0
while until_line > self._nodes_tree.parsed_until_line:
node = self._try_parse_part(until_line)
nodes = node.children
self._nodes_tree.add_parsed_nodes(nodes, self._keyword_token_indents)
if self._replace_tos_indent is not None:
self._nodes_tree.indents[-1] = self._replace_tos_indent
LOG.debug(
'parse_part from %s to %s (to %s in part parser)',
nodes[0].get_start_pos_of_prefix()[0],
self._nodes_tree.parsed_until_line,
node.end_pos[0] - 1
)
# Since the tokenizer sometimes has bugs, we cannot be sure that
# this loop terminates. Therefore assert that there's always a
# change.
assert last_until_line != self._nodes_tree.parsed_until_line, last_until_line
last_until_line = self._nodes_tree.parsed_until_line
def _try_parse_part(self, until_line):
"""
Sets up a normal parser that uses a spezialized tokenizer to only parse
until a certain position (or a bit longer if the statement hasn't
ended.
"""
self._parser_count += 1
# TODO speed up, shouldn't copy the whole list all the time.
# memoryview?
parsed_until_line = self._nodes_tree.parsed_until_line
lines_after = self._parser_lines_new[parsed_until_line:]
tokens = self._diff_tokenize(
lines_after,
until_line,
line_offset=parsed_until_line
)
self._active_parser = Parser(
self._pgen_grammar,
error_recovery=True
)
return self._active_parser.parse(tokens=tokens)
def _diff_tokenize(self, lines, until_line, line_offset=0):
was_newline = False
indents = self._nodes_tree.indents
initial_indentation_count = len(indents)
tokens = self._tokenizer(
lines,
start_pos=(line_offset + 1, 0),
indents=indents,
is_first_token=line_offset == 0,
)
stack = self._active_parser.stack
self._replace_tos_indent = None
self._keyword_token_indents = {}
# print('start', line_offset + 1, indents)
for token in tokens:
# print(token, indents)
typ = token.type
if typ == DEDENT:
if len(indents) < initial_indentation_count:
# We are done here, only thing that can come now is an
# endmarker or another dedented code block.
while True:
typ, string, start_pos, prefix = token = next(tokens)
if typ in (DEDENT, ERROR_DEDENT):
if typ == ERROR_DEDENT:
# We want to force an error dedent in the next
# parser/pass. To make this possible we just
# increase the location by one.
self._replace_tos_indent = start_pos[1] + 1
pass
else:
break
if '\n' in prefix or '\r' in prefix:
prefix = re.sub(r'[^\n\r]+\Z', '', prefix)
else:
assert start_pos[1] >= len(prefix), repr(prefix)
if start_pos[1] - len(prefix) == 0:
prefix = ''
yield PythonToken(
ENDMARKER, '',
start_pos,
prefix
)
break
elif typ == NEWLINE and token.start_pos[0] >= until_line:
was_newline = True
elif was_newline:
was_newline = False
if len(indents) == initial_indentation_count:
# Check if the parser is actually in a valid suite state.
if _suite_or_file_input_is_valid(self._pgen_grammar, stack):
yield PythonToken(ENDMARKER, '', token.start_pos, '')
break
if typ == NAME and token.string in ('class', 'def'):
self._keyword_token_indents[token.start_pos] = list(indents)
yield token
| DiffParser |
python | allegroai__clearml | clearml/utilities/pyhocon/config_parser.py | {
"start": 1257,
"end": 1795
} | class ____(object):
pass
def period(period_value, period_unit):
try:
from dateutil.relativedelta import relativedelta as period_impl
except Exception:
from datetime import timedelta as period_impl
if period_unit == 'nanoseconds':
period_unit = 'microseconds'
period_value = int(period_value / 1000)
arguments = dict(zip((period_unit,), (period_value,)))
if period_unit == 'milliseconds':
return timedelta(**arguments)
return period_impl(**arguments)
| STR_SUBSTITUTION |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 33532,
"end": 37974
} | class ____(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
need paper, generalized to work on images.
"""
def __init__(
self, num_pos_feats: int = 64, temperature: int = 10000, normalize: bool = False, scale: Optional[float] = None
):
super().__init__()
if scale is not None and normalize is False:
raise ValueError("normalize should be True if scale is passed")
self.num_pos_feats = num_pos_feats
self.temperature = temperature
self.normalize = normalize
self.scale = 2 * math.pi if scale is None else scale
def encode_1d_positions(self, x: torch.Tensor, y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""
Encode 1D coordinate pairs using sine/cosine positional embeddings.
Args:
x: 1D tensor of x coordinates (flattened)
y: 1D tensor of y coordinates (flattened)
Returns:
Tuple of (pos_x, pos_y) positional embeddings
"""
x_embed = x * self.scale
y_embed = y * self.scale
dim_t = torch.arange(self.num_pos_feats, dtype=torch.int64, device=x.device).to(x.dtype)
dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
pos_x = x_embed[:, None] / dim_t
pos_y = y_embed[:, None] / dim_t
pos_x = torch.stack((pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2).flatten(1)
pos_y = torch.stack((pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2).flatten(1)
return pos_x, pos_y
def encode_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
"""
Encode 4D box coordinates (x, y, w, h) for decoder conditioning using sine/cosine embeddings.
Args:
boxes: Box coordinates [batch_size, num_queries, 4] in (x, y, w, h) format
Returns:
Position embeddings [batch_size, num_queries, num_pos_feats*4]
"""
assert boxes.size(-1) == 4, f"Expected 4D box coordinates (x, y, w, h), got shape {boxes.shape}"
dim_t = torch.arange(self.num_pos_feats, dtype=torch.int64, device=boxes.device).to(boxes.dtype)
dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.num_pos_feats)
x_embed = boxes[:, :, 0] * self.scale
y_embed = boxes[:, :, 1] * self.scale
w_embed = boxes[:, :, 2] * self.scale
h_embed = boxes[:, :, 3] * self.scale
pos_x = x_embed[:, :, None] / dim_t
pos_y = y_embed[:, :, None] / dim_t
pos_w = w_embed[:, :, None] / dim_t
pos_h = h_embed[:, :, None] / dim_t
pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2)
pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2)
pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2)
pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2)
pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2)
return pos
@compile_compatible_method_lru_cache(maxsize=4)
def forward(
self,
shape: torch.Size,
device: Union[torch.device, str],
dtype: torch.dtype,
mask: Optional[Tensor] = None,
) -> Tensor:
if mask is None:
mask = torch.zeros((shape[0], shape[2], shape[3]), device=device, dtype=torch.bool)
not_mask = (~mask).to(dtype)
y_embed = not_mask.cumsum(1)
x_embed = not_mask.cumsum(2)
if self.normalize:
eps = 1e-6
y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
dim_t = torch.arange(self.num_pos_feats, dtype=torch.int64, device=device).to(dtype)
dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.num_pos_feats)
pos_x = x_embed[:, :, :, None] / dim_t
pos_y = y_embed[:, :, :, None] / dim_t
pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
return pos
| Sam3SinePositionEmbedding |
python | doocs__leetcode | solution/1200-1299/1256.Encode Number/Solution.py | {
"start": 0,
"end": 87
} | class ____:
def encode(self, num: int) -> str:
return bin(num + 1)[3:]
| Solution |
python | etianen__django-reversion | tests/test_app/tests/test_admin.py | {
"start": 4606,
"end": 7243
} | class ____(LoginMixin, AdminMixin, TestBase):
"""Test that Django model signals are muted during GET requests to revision views."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.signal_fired = None
def signal_receiver(self, sender, **kwargs):
"""Receiver that tracks which signal was fired."""
self.signal_fired = sender
raise RuntimeError(f"Django signal was fired for {sender}!")
def setUp(self):
super().setUp()
with reversion.create_revision():
self.obj = TestModelParent.objects.create()
# Connect all the model signals that should be muted
self.signals_to_test = [pre_save, post_save, pre_delete, post_delete, m2m_changed]
for signal in self.signals_to_test:
signal.connect(receiver=self.signal_receiver, sender=TestModelParent)
def tearDown(self):
# Disconnect all signals
for signal in self.signals_to_test:
signal.disconnect(receiver=self.signal_receiver, sender=TestModelParent)
super().tearDown()
def testGetForRevisionViewDoesntFireDjangoSignals(self):
"""Test that viewing a revision (GET request) doesn't fire Django model signals."""
self.signal_fired = None
# This should NOT fire any signals since it's a GET request
response = self.client.get(resolve_url(
"admin:test_app_testmodelparent_revision",
self.obj.pk,
Version.objects.get_for_object(self.obj)[0].pk,
))
# The request should succeed (no signal should have been fired)
self.assertEqual(response.status_code, 200)
self.assertIsNone(self.signal_fired, "No signals should fire during GET request")
def testPostForRevisionViewFiresDjangoSignals(self):
"""Test that reverting a revision (POST request) properly fires Django model signals."""
self.signal_fired = None
# This SHOULD fire signals since it's a POST request (actual revert)
with self.assertRaises(RuntimeError) as cm:
self.client.post(resolve_url(
"admin:test_app_testmodelparent_revision",
self.obj.pk,
Version.objects.get_for_object(self.obj)[0].pk,
), {
"name": "v1",
"parent_name": "parent v1",
})
# Verify that signals were indeed fired during POST
self.assertIn("Django signal was fired", str(cm.exception))
self.assertIsNotNone(self.signal_fired, "Signals should fire during POST request")
| AdminRevisionViewSignalsTest |
python | keras-team__keras | keras/src/backend/common/variables_test.py | {
"start": 47067,
"end": 47516
} | class ____(test_case.TestCase):
def test_standardize_shape_with_tensor_size(self):
import tensorflow as tf
shape = (3, tf.constant(4, dtype=tf.int64), 5)
standardized_shape = standardize_shape(shape)
self.assertEqual(standardized_shape, (3, 4, 5))
self.assertIs(type(standardized_shape), tuple)
for d in standardized_shape:
self.assertIsInstance(d, int)
| TestStandardizeShapeWithTensorflow |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/_utils.py | {
"start": 6268,
"end": 7319
} | class ____:
command: list[str]
@property
def is_installed(self) -> bool:
"""Returns whether formatter is available"""
if not hasattr(self, "_is_installed"):
self._is_installed = self._is_available_via_cli()
return self._is_installed
def format(self, code: str, line_length: int) -> str:
"""Formats code"""
return subprocess.check_output(
[
sys.executable,
"-m",
*self.command,
"--line-length",
str(line_length),
"-",
],
input=code,
text=True,
).strip()
def _is_available_via_cli(self) -> bool:
try:
subprocess.check_output(
[
sys.executable,
"-m",
*self.command,
"--help",
],
)
return True
except subprocess.CalledProcessError:
return False
| Formatter |
python | pytorch__pytorch | test/test_opaque_obj.py | {
"start": 520,
"end": 1520
} | class ____:
def __init__(self, queue: list[torch.Tensor], init_tensor_: torch.Tensor) -> None:
super().__init__()
self.queue = queue
self.init_tensor_ = init_tensor_
# For testing purposes
self._push_counter = 0
self._pop_counter = 0
self._size_counter = 0
def push(self, tensor: torch.Tensor) -> None:
self._push_counter += 1
self.queue.append(tensor)
def pop(self) -> torch.Tensor:
self._pop_counter += 1
if len(self.queue) > 0:
return self.queue.pop(0)
return self.init_tensor_
def size(self) -> int:
self._size_counter += 1
return len(self.queue)
def __eq__(self, other):
if len(self.queue) != len(other.queue):
return False
for q1, q2 in zip(self.queue, other.queue):
if not torch.allclose(q1, q2):
return False
return torch.allclose(self.init_tensor_, other.init_tensor_)
| OpaqueQueue |
python | getsentry__sentry | src/sentry/middleware/integrations/classifications.py | {
"start": 653,
"end": 1236
} | class ____(abc.ABC):
def __init__(self, response_handler: ResponseHandler) -> None:
self.response_handler = response_handler
def should_operate(self, request: HttpRequest) -> bool:
"""
Determines whether the classification should act on request.
Middleware will return self.get_response() if this function returns True.
"""
raise NotImplementedError
def get_response(self, request: HttpRequest) -> HttpResponseBase:
"""Parse the request and return a response."""
raise NotImplementedError
| BaseClassification |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_s3.py | {
"start": 1061,
"end": 7360
} | class ____:
def test_serialization(self):
"""
Asserts that the TaskStateTrigger correctly serializes its arguments
and classpath.
"""
trigger = S3KeyTrigger(
bucket_key="s3://test_bucket/file",
bucket_name="test_bucket",
wildcard_match=True,
metadata_keys=["Size", "LastModified"],
)
classpath, kwargs = trigger.serialize()
assert classpath == "airflow.providers.amazon.aws.triggers.s3.S3KeyTrigger"
assert kwargs == {
"bucket_name": "test_bucket",
"bucket_key": "s3://test_bucket/file",
"wildcard_match": True,
"aws_conn_id": "aws_default",
"hook_params": {},
"poke_interval": 5.0,
"should_check_fn": False,
"use_regex": False,
"verify": None,
"region_name": None,
"botocore_config": None,
"metadata_keys": ["Size", "LastModified"],
}
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.get_async_conn")
async def test_run_success(self, mock_client):
"""
Test if the task is run is in triggerr successfully.
"""
mock_client.return_value.return_value.check_key.return_value = True
trigger = S3KeyTrigger(bucket_key="test_bucket/file", bucket_name="test_bucket")
task = asyncio.create_task(trigger.run().__anext__())
await asyncio.sleep(0.5)
assert task.done() is True
result = await task
assert result == TriggerEvent({"status": "success"})
asyncio.get_event_loop().stop()
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.check_key_async")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.get_async_conn")
async def test_run_pending(self, mock_client, mock_check_key_async):
"""
Test if the task is run is in trigger successfully and set check_key to return false.
"""
mock_check_key_async.return_value = False
trigger = S3KeyTrigger(bucket_key="test_bucket/file", bucket_name="test_bucket")
task = asyncio.create_task(trigger.run().__anext__())
await asyncio.sleep(0.5)
assert task.done() is False
asyncio.get_event_loop().stop()
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.get_files_async")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.get_head_object_async")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.check_key_async")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.get_async_conn")
async def test_run_with_metadata(
self,
mock_get_async_conn,
mock_check_key_async,
mock_get_head_object_async,
mock_get_files_async,
):
"""Test if the task retrieves metadata correctly when should_check_fn is True."""
mock_check_key_async.return_value = True
mock_get_files_async.return_value = ["file1.txt", "file2.txt"]
async def fake_get_head_object_async(*args, **kwargs):
key = kwargs.get("key")
if key == "file1.txt":
return {"ContentLength": 1024, "LastModified": "2023-10-01T12:00:00Z"}
if key == "file2.txt":
return {"ContentLength": 2048, "LastModified": "2023-10-02T12:00:00Z"}
mock_get_head_object_async.side_effect = fake_get_head_object_async
mock_get_async_conn.return_value.__aenter__.return_value = async_mock.AsyncMock()
trigger = S3KeyTrigger(
bucket_key="test_bucket/file",
bucket_name="test_bucket",
should_check_fn=True,
metadata_keys=["Size", "LastModified"],
poke_interval=0.1, # reduce waiting time
)
result = await asyncio.wait_for(trigger.run().__anext__(), timeout=2)
expected = TriggerEvent(
{
"status": "running",
"files": [
{"Size": 1024, "LastModified": "2023-10-01T12:00:00Z", "Key": "file1.txt"},
{"Size": 2048, "LastModified": "2023-10-02T12:00:00Z", "Key": "file2.txt"},
],
}
)
assert result == expected
@pytest.mark.asyncio
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.get_files_async")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.get_head_object_async")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.check_key_async")
@async_mock.patch("airflow.providers.amazon.aws.triggers.s3.S3Hook.get_async_conn")
async def test_run_with_all_metadata(
self, mock_get_async_conn, mock_check_key_async, mock_get_head_object_async, mock_get_files_async
):
"""
Test if the task retrieves all metadata when metadata_keys contains '*'.
"""
mock_check_key_async.return_value = True
mock_get_files_async.return_value = ["file1.txt"]
async def fake_get_head_object_async(*args, **kwargs):
return {
"ContentLength": 1024,
"LastModified": "2023-10-01T12:00:00Z",
"ETag": "abc123",
}
mock_get_head_object_async.side_effect = fake_get_head_object_async
mock_get_async_conn.return_value.__aenter__.return_value = async_mock.AsyncMock()
trigger = S3KeyTrigger(
bucket_key="test_bucket/file",
bucket_name="test_bucket",
should_check_fn=True,
metadata_keys=["*"],
poke_interval=0.1,
)
result = await asyncio.wait_for(trigger.run().__anext__(), timeout=2)
expected = TriggerEvent(
{
"status": "running",
"files": [
{
"ContentLength": 1024,
"LastModified": "2023-10-01T12:00:00Z",
"ETag": "abc123",
"Key": "file1.txt",
}
],
}
)
assert result == expected
| TestS3KeyTrigger |
python | openai__openai-python | src/openai/types/fine_tuning/alpha/grader_run_params.py | {
"start": 593,
"end": 1414
} | class ____(TypedDict, total=False):
grader: Required[Grader]
"""The grader used for the fine-tuning job."""
model_sample: Required[str]
"""The model sample to be evaluated.
This value will be used to populate the `sample` namespace. See
[the guide](https://platform.openai.com/docs/guides/graders) for more details.
The `output_json` variable will be populated if the model sample is a valid JSON
string.
"""
item: object
"""The dataset item provided to the grader.
This will be used to populate the `item` namespace. See
[the guide](https://platform.openai.com/docs/guides/graders) for more details.
"""
Grader: TypeAlias = Union[
StringCheckGraderParam, TextSimilarityGraderParam, PythonGraderParam, ScoreModelGraderParam, MultiGraderParam
]
| GraderRunParams |
python | plotly__plotly.py | plotly/graph_objs/waterfall/_hoverlabel.py | {
"start": 233,
"end": 11255
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "waterfall"
_path_str = "waterfall.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc",
"showarrow",
}
@property
def align(self):
"""
Sets the horizontal alignment of the text content within hover
label box. Has an effect only if the hover label text spans
more two or more lines
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'right', 'auto']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["align"]
@align.setter
def align(self, val):
self["align"] = val
@property
def alignsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `align`.
The 'alignsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["alignsrc"]
@alignsrc.setter
def alignsrc(self, val):
self["alignsrc"] = val
@property
def bgcolor(self):
"""
Sets the background color of the hover labels for this trace
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def bgcolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `bgcolor`.
The 'bgcolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bgcolorsrc"]
@bgcolorsrc.setter
def bgcolorsrc(self, val):
self["bgcolorsrc"] = val
@property
def bordercolor(self):
"""
Sets the border color of the hover labels for this trace.
The 'bordercolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["bordercolor"]
@bordercolor.setter
def bordercolor(self, val):
self["bordercolor"] = val
@property
def bordercolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
The 'bordercolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bordercolorsrc"]
@bordercolorsrc.setter
def bordercolorsrc(self, val):
self["bordercolorsrc"] = val
@property
def font(self):
"""
Sets the font used in hover labels.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.waterfall.hoverlabel.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.waterfall.hoverlabel.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def namelength(self):
"""
Sets the default length (in number of characters) of the trace
name in the hover labels for all traces. -1 shows the whole
name regardless of length. 0-3 shows the first 0-3 characters,
and an integer >3 will show the whole name if it is less than
that many characters, but if it is longer, will truncate to
`namelength - 3` characters and add an ellipsis.
The 'namelength' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [-1, 9223372036854775807]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["namelength"]
@namelength.setter
def namelength(self, val):
self["namelength"] = val
@property
def namelengthsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`namelength`.
The 'namelengthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["namelengthsrc"]
@namelengthsrc.setter
def namelengthsrc(self, val):
self["namelengthsrc"] = val
@property
def showarrow(self):
"""
Sets whether or not to show the hover label arrow/triangle
pointing to the data point.
The 'showarrow' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showarrow"]
@showarrow.setter
def showarrow(self, val):
self["showarrow"] = val
@property
def _prop_descriptions(self):
return """\
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
`bgcolor`.
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
`namelength`.
showarrow
Sets whether or not to show the hover label
arrow/triangle pointing to the data point.
"""
def __init__(
self,
arg=None,
align=None,
alignsrc=None,
bgcolor=None,
bgcolorsrc=None,
bordercolor=None,
bordercolorsrc=None,
font=None,
namelength=None,
namelengthsrc=None,
showarrow=None,
**kwargs,
):
"""
Construct a new Hoverlabel object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.waterfall.Hoverlabel`
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
`bgcolor`.
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
`namelength`.
showarrow
Sets whether or not to show the hover label
arrow/triangle pointing to the data point.
Returns
-------
Hoverlabel
"""
super().__init__("hoverlabel")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.waterfall.Hoverlabel
constructor must be a dict or
an instance of :class:`plotly.graph_objs.waterfall.Hoverlabel`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("align", arg, align)
self._set_property("alignsrc", arg, alignsrc)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("bgcolorsrc", arg, bgcolorsrc)
self._set_property("bordercolor", arg, bordercolor)
self._set_property("bordercolorsrc", arg, bordercolorsrc)
self._set_property("font", arg, font)
self._set_property("namelength", arg, namelength)
self._set_property("namelengthsrc", arg, namelengthsrc)
self._set_property("showarrow", arg, showarrow)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Hoverlabel |
python | mwaskom__seaborn | tests/_core/test_plot.py | {
"start": 44127,
"end": 49835
} | class ____:
@pytest.fixture(scope="class", params=["row", "col"])
def dim(self, request):
return request.param
@pytest.fixture(scope="class", params=["reverse", "subset", "expand"])
def reorder(self, request):
return {
"reverse": lambda x: x[::-1],
"subset": lambda x: x[:-1],
"expand": lambda x: x + ["z"],
}[request.param]
def check_facet_results_1d(self, p, df, dim, key, order=None):
p = p.plot()
order = categorical_order(df[key], order)
assert len(p._figure.axes) == len(order)
other_dim = {"row": "col", "col": "row"}[dim]
for subplot, level in zip(p._subplots, order):
assert subplot[dim] == level
assert subplot[other_dim] is None
assert subplot["ax"].get_title() == f"{level}"
assert_gridspec_shape(subplot["ax"], **{f"n{dim}s": len(order)})
def test_1d(self, long_df, dim):
key = "a"
p = Plot(long_df).facet(**{dim: key})
self.check_facet_results_1d(p, long_df, dim, key)
def test_1d_as_vector(self, long_df, dim):
key = "a"
p = Plot(long_df).facet(**{dim: long_df[key]})
self.check_facet_results_1d(p, long_df, dim, key)
def test_1d_with_order(self, long_df, dim, reorder):
key = "a"
order = reorder(categorical_order(long_df[key]))
p = Plot(long_df).facet(**{dim: key, "order": order})
self.check_facet_results_1d(p, long_df, dim, key, order)
def check_facet_results_2d(self, p, df, variables, order=None):
p = p.plot()
if order is None:
order = {dim: categorical_order(df[key]) for dim, key in variables.items()}
levels = itertools.product(*[order[dim] for dim in ["row", "col"]])
assert len(p._subplots) == len(list(levels))
for subplot, (row_level, col_level) in zip(p._subplots, levels):
assert subplot["row"] == row_level
assert subplot["col"] == col_level
assert subplot["axes"].get_title() == (
f"{col_level} | {row_level}"
)
assert_gridspec_shape(
subplot["axes"], len(levels["row"]), len(levels["col"])
)
def test_2d(self, long_df):
variables = {"row": "a", "col": "c"}
p = Plot(long_df).facet(**variables)
self.check_facet_results_2d(p, long_df, variables)
def test_2d_with_order(self, long_df, reorder):
variables = {"row": "a", "col": "c"}
order = {
dim: reorder(categorical_order(long_df[key]))
for dim, key in variables.items()
}
p = Plot(long_df).facet(**variables, order=order)
self.check_facet_results_2d(p, long_df, variables, order)
@pytest.mark.parametrize("algo", ["tight", "constrained"])
def test_layout_algo(self, algo):
p = Plot().facet(["a", "b"]).limit(x=(.1, .9))
p1 = p.layout(engine=algo).plot()
p2 = p.layout(engine="none").plot()
# Force a draw (we probably need a method for this)
p1.save(io.BytesIO())
p2.save(io.BytesIO())
bb11, bb12 = [ax.get_position() for ax in p1._figure.axes]
bb21, bb22 = [ax.get_position() for ax in p2._figure.axes]
sep1 = bb12.corners()[0, 0] - bb11.corners()[2, 0]
sep2 = bb22.corners()[0, 0] - bb21.corners()[2, 0]
assert sep1 <= sep2
def test_axis_sharing(self, long_df):
variables = {"row": "a", "col": "c"}
p = Plot(long_df).facet(**variables)
p1 = p.plot()
root, *other = p1._figure.axes
for axis in "xy":
shareset = getattr(root, f"get_shared_{axis}_axes")()
assert all(shareset.joined(root, ax) for ax in other)
p2 = p.share(x=False, y=False).plot()
root, *other = p2._figure.axes
for axis in "xy":
shareset = getattr(root, f"get_shared_{axis}_axes")()
assert not any(shareset.joined(root, ax) for ax in other)
p3 = p.share(x="col", y="row").plot()
shape = (
len(categorical_order(long_df[variables["row"]])),
len(categorical_order(long_df[variables["col"]])),
)
axes_matrix = np.reshape(p3._figure.axes, shape)
for (shared, unshared), vectors in zip(
["yx", "xy"], [axes_matrix, axes_matrix.T]
):
for root, *other in vectors:
shareset = {
axis: getattr(root, f"get_shared_{axis}_axes")() for axis in "xy"
}
assert all(shareset[shared].joined(root, ax) for ax in other)
assert not any(shareset[unshared].joined(root, ax) for ax in other)
def test_unshared_spacing(self):
x = [1, 2, 10, 20]
y = [1, 2, 3, 4]
col = [1, 1, 2, 2]
m = MockMark()
Plot(x, y).facet(col).add(m).share(x=False).plot()
assert_array_almost_equal(m.passed_data[0]["width"], [0.8, 0.8])
assert_array_equal(m.passed_data[1]["width"], [8, 8])
def test_col_wrapping(self):
cols = list("abcd")
wrap = 3
p = Plot().facet(col=cols, wrap=wrap).plot()
assert len(p._figure.axes) == 4
assert_gridspec_shape(p._figure.axes[0], len(cols) // wrap + 1, wrap)
# TODO test axis labels and titles
def test_row_wrapping(self):
rows = list("abcd")
wrap = 3
p = Plot().facet(row=rows, wrap=wrap).plot()
assert_gridspec_shape(p._figure.axes[0], wrap, len(rows) // wrap + 1)
assert len(p._figure.axes) == 4
# TODO test axis labels and titles
| TestFacetInterface |
python | tensorflow__tensorflow | tensorflow/python/trackable/base.py | {
"start": 3105,
"end": 4036
} | class ____(object):
"""A callable object that returns a CheckpointInitialValue.
See CheckpointInitialValue for more information.
"""
def __init__(self, checkpoint_position):
self._checkpoint_position = checkpoint_position
@property
def checkpoint_position(self):
return self._checkpoint_position
def __call__(self, shape=None, dtype=None, shard_info=None):
# Note that the signature here is for compatibility with normal callable
# initializers which take shape and dtype. Although dtype isn't used, it
# will get passed in by a functool.partial_wrapper in places like
# base_layer_utils.py's make_variable.
return CheckpointInitialValue(
self._checkpoint_position, shape, shard_info=shard_info)
@property
def restore_uid(self):
return self._checkpoint_position.restore_uid
@tf_export("__internal__.tracking.CheckpointInitialValue", v1=[])
| CheckpointInitialValueCallable |
python | huggingface__transformers | src/transformers/models/pvt/configuration_pvt.py | {
"start": 946,
"end": 6377
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PvtModel`]. It is used to instantiate an Pvt
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the Pvt
[Xrenya/pvt-tiny-224](https://huggingface.co/Xrenya/pvt-tiny-224) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
image_size (`int`, *optional*, defaults to 224):
The input image size
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
num_encoder_blocks (`int`, *optional*, defaults to 4):
The number of encoder blocks (i.e. stages in the Mix Transformer encoder).
depths (`list[int]`, *optional*, defaults to `[2, 2, 2, 2]`):
The number of layers in each encoder block.
sequence_reduction_ratios (`list[int]`, *optional*, defaults to `[8, 4, 2, 1]`):
Sequence reduction ratios in each encoder block.
hidden_sizes (`list[int]`, *optional*, defaults to `[64, 128, 320, 512]`):
Dimension of each of the encoder blocks.
patch_sizes (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
Patch size before each encoder block.
strides (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
Stride before each encoder block.
num_attention_heads (`list[int]`, *optional*, defaults to `[1, 2, 5, 8]`):
Number of attention heads for each attention layer in each block of the Transformer encoder.
mlp_ratios (`list[int]`, *optional*, defaults to `[8, 8, 4, 4]`):
Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
encoder blocks.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
drop_path_rate (`float`, *optional*, defaults to 0.0):
The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the layer normalization layers.
qkv_bias (`bool`, *optional*, defaults to `True`):
Whether or not a learnable bias should be added to the queries, keys and values.
num_labels ('int', *optional*, defaults to 1000):
The number of classes.
Example:
```python
>>> from transformers import PvtModel, PvtConfig
>>> # Initializing a PVT Xrenya/pvt-tiny-224 style configuration
>>> configuration = PvtConfig()
>>> # Initializing a model from the Xrenya/pvt-tiny-224 style configuration
>>> model = PvtModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "pvt"
def __init__(
self,
image_size: int = 224,
num_channels: int = 3,
num_encoder_blocks: int = 4,
depths: list[int] = [2, 2, 2, 2],
sequence_reduction_ratios: list[int] = [8, 4, 2, 1],
hidden_sizes: list[int] = [64, 128, 320, 512],
patch_sizes: list[int] = [4, 2, 2, 2],
strides: list[int] = [4, 2, 2, 2],
num_attention_heads: list[int] = [1, 2, 5, 8],
mlp_ratios: list[int] = [8, 8, 4, 4],
hidden_act: Mapping[str, Callable] = "gelu",
hidden_dropout_prob: float = 0.0,
attention_probs_dropout_prob: float = 0.0,
initializer_range: float = 0.02,
drop_path_rate: float = 0.0,
layer_norm_eps: float = 1e-6,
qkv_bias: bool = True,
num_labels: int = 1000,
**kwargs,
):
super().__init__(**kwargs)
self.image_size = image_size
self.num_channels = num_channels
self.num_encoder_blocks = num_encoder_blocks
self.depths = depths
self.sequence_reduction_ratios = sequence_reduction_ratios
self.hidden_sizes = hidden_sizes
self.patch_sizes = patch_sizes
self.strides = strides
self.mlp_ratios = mlp_ratios
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.drop_path_rate = drop_path_rate
self.layer_norm_eps = layer_norm_eps
self.num_labels = num_labels
self.qkv_bias = qkv_bias
__all__ = ["PvtConfig"]
| PvtConfig |
python | spack__spack | lib/spack/spack/tengine.py | {
"start": 314,
"end": 1703
} | class ____(type):
"""Meta class for Context. It helps reducing the boilerplate in
client code.
"""
#: Keeps track of the context properties that have been added
#: by the class that is being defined
_new_context_properties: List[str] = []
def __new__(cls, name, bases, attr_dict):
# Merge all the context properties that are coming from base classes
# into a list without duplicates.
context_properties = list(cls._new_context_properties)
for x in bases:
try:
context_properties.extend(x.context_properties)
except AttributeError:
pass
context_properties = list(spack.llnl.util.lang.dedupe(context_properties))
# Flush the list
cls._new_context_properties = []
# Attach the list to the class being created
attr_dict["context_properties"] = context_properties
return super(ContextMeta, cls).__new__(cls, name, bases, attr_dict)
@classmethod
def context_property(cls, func):
"""Decorator that adds a function name to the list of new context
properties, and then returns a property.
"""
name = func.__name__
cls._new_context_properties.append(name)
return property(func)
#: A saner way to use the decorator
context_property = ContextMeta.context_property
| ContextMeta |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_grayscale_test.py | {
"start": 229,
"end": 4500
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_layer(self):
self.run_layer_test(
layers.RandomGrayscale,
init_kwargs={
"factor": 0.5,
"data_format": "channels_last",
},
input_shape=(1, 2, 2, 3),
supports_masking=False,
expected_output_shape=(1, 2, 2, 3),
)
self.run_layer_test(
layers.RandomGrayscale,
init_kwargs={
"factor": 0.5,
"data_format": "channels_first",
},
input_shape=(1, 3, 2, 2),
supports_masking=False,
expected_output_shape=(1, 3, 2, 2),
)
@parameterized.named_parameters(
("channels_last", "channels_last"), ("channels_first", "channels_first")
)
def test_grayscale_conversion(self, data_format):
if data_format == "channels_last":
xs = np.random.uniform(0, 255, size=(2, 4, 4, 3)).astype(np.float32)
layer = layers.RandomGrayscale(factor=1.0, data_format=data_format)
transformed = ops.convert_to_numpy(layer(xs))
self.assertEqual(transformed.shape[-1], 3)
for img in transformed:
r, g, b = img[:, :, 0], img[:, :, 1], img[:, :, 2]
self.assertTrue(np.allclose(r, g) and np.allclose(g, b))
else:
xs = np.random.uniform(0, 255, size=(2, 3, 4, 4)).astype(np.float32)
layer = layers.RandomGrayscale(factor=1.0, data_format=data_format)
transformed = ops.convert_to_numpy(layer(xs))
self.assertEqual(transformed.shape[1], 3)
for img in transformed:
r, g, b = img[0], img[1], img[2]
self.assertTrue(np.allclose(r, g) and np.allclose(g, b))
def test_invalid_factor(self):
with self.assertRaises(ValueError):
layers.RandomGrayscale(factor=-0.1)
with self.assertRaises(ValueError):
layers.RandomGrayscale(factor=1.1)
def test_tf_data_compatibility(self):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
input_data = np.random.random((2, 8, 8, 3)) * 255
else:
input_data = np.random.random((2, 3, 8, 8)) * 255
layer = layers.RandomGrayscale(factor=0.5, data_format=data_format)
ds = tf_data.Dataset.from_tensor_slices(input_data).batch(2).map(layer)
for output in ds.take(1):
output_array = output.numpy()
self.assertEqual(output_array.shape, input_data.shape)
def test_grayscale_with_single_color_image(self):
test_cases = [
# batched inputs
(np.full((1, 4, 4, 3), 128, dtype=np.float32), "channels_last"),
(np.full((1, 3, 4, 4), 128, dtype=np.float32), "channels_first"),
# unbatched inputs
(np.full((4, 4, 3), 128, dtype=np.float32), "channels_last"),
(np.full((3, 4, 4), 128, dtype=np.float32), "channels_first"),
]
for xs, data_format in test_cases:
layer = layers.RandomGrayscale(factor=1.0, data_format=data_format)
transformed = ops.convert_to_numpy(layer(xs))
# Determine if the input was batched
is_batched = len(xs.shape) == 4
# If batched, select the first image from the batch for inspection.
# Otherwise, use the transformed image directly.
# `image_to_inspect` will always be a 3D tensor.
if is_batched:
image_to_inspect = transformed[0]
else:
image_to_inspect = transformed
if data_format == "channels_last":
# image_to_inspect has shape (H, W, C),
# get the first channel [:, :, 0]
channel_data = image_to_inspect[:, :, 0]
else: # data_format == "channels_first"
# image_to_inspect has shape (C, H, W),
# get the first channel [0, :, :]
channel_data = image_to_inspect[0, :, :]
unique_vals = np.unique(channel_data)
self.assertEqual(len(unique_vals), 1)
| RandomGrayscaleTest |
python | weaviate__weaviate-python-client | weaviate/collections/batch/grpc_batch_delete.py | {
"start": 559,
"end": 2661
} | class ____(_BaseGRPC):
"""This class is used to delete multiple objects from Weaviate using the gRPC API."""
def __init__(
self,
weaviate_version: _ServerVersion,
consistency_level: Optional[ConsistencyLevel],
):
super().__init__(weaviate_version, consistency_level, False)
def batch_delete(
self,
connection: Connection,
*,
name: str,
filters: _Filters,
verbose: bool,
dry_run: bool,
tenant: Optional[str],
) -> executor.Result[Union[DeleteManyReturn[List[DeleteManyObject]], DeleteManyReturn[None]]]:
def resp(
res: batch_delete_pb2.BatchDeleteReply,
) -> Union[DeleteManyReturn[List[DeleteManyObject]], DeleteManyReturn[None]]:
if verbose:
objects: List[DeleteManyObject] = [
DeleteManyObject(
uuid=_WeaviateUUIDInt(int.from_bytes(obj.uuid, byteorder="big")),
successful=obj.successful,
error=obj.error if obj.error != "" else None,
)
for obj in res.objects
]
return DeleteManyReturn(
failed=res.failed,
successful=res.successful,
matches=res.matches,
objects=objects,
)
else:
return DeleteManyReturn(
failed=res.failed,
successful=res.successful,
matches=res.matches,
objects=None,
)
request = batch_delete_pb2.BatchDeleteRequest(
collection=name,
consistency_level=self._consistency_level,
verbose=verbose,
dry_run=dry_run,
tenant=tenant,
filters=_FilterToGRPC.convert(filters),
)
return executor.execute(
response_callback=resp,
method=connection.grpc_batch_delete,
request=request,
)
| _BatchDeleteGRPC |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.