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 | tensorflow__tensorflow | tensorflow/python/autograph/utils/type_registry.py | {
"start": 767,
"end": 1955
} | class ____(object):
"""Provides a type registry for the python registry pattern.
Contains mappings between types and type specific objects, to implement the
registry pattern.
Some example uses of this would be to register different functions depending
on the type of object.
"""
def __init__(self):
self._registry = {}
def register(self, obj, value):
"""Registers a Python object within the registry.
Args:
obj: The object to add to the registry.
value: The stored value for the 'obj' type.
Raises:
KeyError: If the same obj is used twice.
"""
if obj in self._registry:
raise KeyError(f"{type(obj)} has already been registered.")
self._registry[obj] = value
def lookup(self, obj):
"""Looks up 'obj'.
Args:
obj: The object to lookup within the registry.
Returns:
Value for 'obj' in the registry if found.
Raises:
LookupError: if 'obj' has not been registered.
"""
for registered in self._registry:
if isinstance(
obj, registered
):
return self._registry[registered]
raise LookupError(f"{type(obj)} has not been registered.")
| TypeRegistry |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py | {
"start": 1274,
"end": 1428
} | class ____(BaseInfoResponse):
"""DagProcessor info serializer for responses."""
latest_dag_processor_heartbeat: str | None
| DagProcessorInfoResponse |
python | encode__django-rest-framework | tests/test_relations_pk.py | {
"start": 1198,
"end": 1445
} | class ____(serializers.ModelSerializer):
first_source = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = ForeignKeyTarget
fields = ('id', 'name', 'first_source')
| ForeignKeyTargetPropertySourceSerializer |
python | PrefectHQ__prefect | src/prefect/server/schemas/sorting.py | {
"start": 3221,
"end": 3756
} | class ____(AutoEnum):
"""Defines log sorting options."""
TIMESTAMP_ASC = AutoEnum.auto()
TIMESTAMP_DESC = AutoEnum.auto()
@db_injector
def as_sql_sort(self, db: "PrefectDBInterface") -> Iterable[sa.ColumnElement[Any]]:
"""Return an expression used to sort task runs"""
sort_mapping: dict[str, Iterable[sa.ColumnElement[Any]]] = {
"TIMESTAMP_ASC": [db.Log.timestamp.asc()],
"TIMESTAMP_DESC": [db.Log.timestamp.desc()],
}
return sort_mapping[self.value]
| LogSort |
python | langchain-ai__langchain | libs/partners/ollama/tests/unit_tests/test_auth.py | {
"start": 3687,
"end": 5881
} | class ____:
"""Test URL authentication integration with ChatOllama."""
@patch("langchain_ollama.chat_models.Client")
@patch("langchain_ollama.chat_models.AsyncClient")
def test_chat_ollama_url_auth_integration(
self, mock_async_client: MagicMock, mock_client: MagicMock
) -> None:
"""Test that ChatOllama properly handles URL authentication."""
url_with_auth = "https://user:password@ollama.example.com:11434"
ChatOllama(
model=MODEL_NAME,
base_url=url_with_auth,
)
# Verify the clients were called with cleaned URL and auth headers
expected_url = "https://ollama.example.com:11434"
expected_credentials = base64.b64encode(b"user:password").decode()
expected_headers = {"Authorization": f"Basic {expected_credentials}"}
mock_client.assert_called_once_with(host=expected_url, headers=expected_headers)
mock_async_client.assert_called_once_with(
host=expected_url, headers=expected_headers
)
@patch("langchain_ollama.chat_models.Client")
@patch("langchain_ollama.chat_models.AsyncClient")
def test_chat_ollama_url_auth_with_existing_headers(
self, mock_async_client: MagicMock, mock_client: MagicMock
) -> None:
"""Test that URL auth headers merge with existing headers."""
url_with_auth = "https://user:password@ollama.example.com:11434"
existing_headers = {"User-Agent": "test-agent", "X-Custom": "value"}
ChatOllama(
model=MODEL_NAME,
base_url=url_with_auth,
client_kwargs={"headers": existing_headers},
)
# Verify headers are merged
expected_url = "https://ollama.example.com:11434"
expected_credentials = base64.b64encode(b"user:password").decode()
expected_headers = {
**existing_headers,
"Authorization": f"Basic {expected_credentials}",
}
mock_client.assert_called_once_with(host=expected_url, headers=expected_headers)
mock_async_client.assert_called_once_with(
host=expected_url, headers=expected_headers
)
| TestChatOllamaUrlAuth |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 31417,
"end": 31695
} | class ____(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the resource is locked.
code: 423, title: Locked
"""
# Note: from WebDAV
code = 423
title = 'Locked'
explanation = 'The resource is locked'
| HTTPLocked |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_requests/posts_request_builder.py | {
"start": 302,
"end": 1660
} | class ____(ZendeskSupportBaseRequestBuilder):
@classmethod
def posts_endpoint(cls, authenticator: Authenticator) -> "PostsRequestBuilder":
return cls("d3v-airbyte", "community/posts").with_authenticator(authenticator)
def __init__(self, subdomain: str, resource: str) -> None:
super().__init__(subdomain, resource)
self._start_time: Optional[int] = None
self._page_size: Optional[int] = None
self._after_cursor: Optional[str] = None
@property
def query_params(self):
params = super().query_params or {}
if self._start_time is not None:
params["start_time"] = self._start_time
if self._page_size is not None:
params["page[size]"] = self._page_size
if self._after_cursor is not None:
params["page[after]"] = self._after_cursor
return params
def with_start_time(self, start_time: str) -> "PostsRequestBuilder":
self._start_time: int = calendar.timegm(ab_datetime_parse(start_time).utctimetuple())
return self
def with_page_size(self, page_size: int) -> "PostsRequestBuilder":
self._page_size: int = page_size
return self
def with_after_cursor(self, after_cursor: str) -> "PostsRequestBuilder":
self._after_cursor: str = after_cursor
return self
| PostsRequestBuilder |
python | networkx__networkx | networkx/generators/tests/test_intersection.py | {
"start": 39,
"end": 819
} | class ____:
def test_random_intersection_graph(self):
G = nx.uniform_random_intersection_graph(10, 5, 0.5)
assert len(G) == 10
def test_k_random_intersection_graph(self):
G = nx.k_random_intersection_graph(10, 5, 2)
assert len(G) == 10
def test_k_random_intersection_graph_seeded(self):
G = nx.k_random_intersection_graph(10, 5, 2, seed=1234)
assert len(G) == 10
def test_general_random_intersection_graph(self):
G = nx.general_random_intersection_graph(10, 5, [0.1, 0.2, 0.2, 0.1, 0.1])
assert len(G) == 10
pytest.raises(
ValueError,
nx.general_random_intersection_graph,
10,
5,
[0.1, 0.2, 0.2, 0.1],
)
| TestIntersectionGraph |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 60409,
"end": 63945
} | class ____(GeneratedAirbyteDestination):
class Unencrypted:
@public
def __init__(
self,
):
self.encryption_method = "unencrypted"
class NativeNetworkEncryptionNNE:
@public
def __init__(self, encryption_algorithm: Optional[str] = None):
self.encryption_method = "client_nne"
self.encryption_algorithm = check.opt_str_param(
encryption_algorithm, "encryption_algorithm"
)
class TLSEncryptedVerifyCertificate:
@public
def __init__(self, ssl_certificate: str):
self.encryption_method = "encrypted_verify_certificate"
self.ssl_certificate = check.str_param(ssl_certificate, "ssl_certificate")
@public
def __init__(
self,
name: str,
host: str,
port: int,
sid: str,
username: str,
encryption: Union[
"OracleDestination.Unencrypted",
"OracleDestination.NativeNetworkEncryptionNNE",
"OracleDestination.TLSEncryptedVerifyCertificate",
],
password: Optional[str] = None,
jdbc_url_params: Optional[str] = None,
schema: Optional[str] = None,
):
"""Airbyte Destination for Oracle.
Documentation can be found at https://docs.airbyte.com/integrations/destinations/oracle
Args:
name (str): The name of the destination.
host (str): The hostname of the database.
port (int): The port of the database.
sid (str): The System Identifier uniquely distinguishes the instance from any other instance on the same computer.
username (str): The username to access the database. This user must have CREATE USER privileges in the database.
password (Optional[str]): The password associated with the username.
jdbc_url_params (Optional[str]): Additional properties to pass to the JDBC URL string when connecting to the database formatted as 'key=value' pairs separated by the symbol '&'. (example: key1=value1&key2=value2&key3=value3).
schema (Optional[str]): The default schema is used as the target schema for all statements issued from the connection that do not explicitly specify a schema name. The usual value for this field is "airbyte". In Oracle, schemas and users are the same thing, so the "user" parameter is used as the login credentials and this is used for the default Airbyte message schema.
encryption (Union[OracleDestination.Unencrypted, OracleDestination.NativeNetworkEncryptionNNE, OracleDestination.TLSEncryptedVerifyCertificate]): The encryption method which is used when communicating with the database.
"""
self.host = check.str_param(host, "host")
self.port = check.int_param(port, "port")
self.sid = check.str_param(sid, "sid")
self.username = check.str_param(username, "username")
self.password = check.opt_str_param(password, "password")
self.jdbc_url_params = check.opt_str_param(jdbc_url_params, "jdbc_url_params")
self.schema = check.opt_str_param(schema, "schema")
self.encryption = check.inst_param(
encryption,
"encryption",
(
OracleDestination.Unencrypted,
OracleDestination.NativeNetworkEncryptionNNE,
OracleDestination.TLSEncryptedVerifyCertificate,
),
)
super().__init__("Oracle", name)
| OracleDestination |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/integrations/looker/customize-looker-assets.py | {
"start": 386,
"end": 1330
} | class ____(DagsterLookerApiTranslator):
def get_asset_spec(
self, looker_structure: LookerApiTranslatorStructureData
) -> dg.AssetSpec:
# We create the default asset spec using super()
default_spec = super().get_asset_spec(looker_structure)
# We customize the team owner tag for all assets,
# and we customize the asset key prefix only for dashboards.
return default_spec.replace_attributes(
key=(
default_spec.key.with_prefix("looker")
if looker_structure.structure_type == LookerStructureType.DASHBOARD
else default_spec.key
),
owners=["team:my_team"],
)
looker_specs = load_looker_asset_specs(
looker_resource, dagster_looker_translator=CustomDagsterLookerApiTranslator()
)
defs = dg.Definitions(assets=[*looker_specs], resources={"looker": looker_resource})
| CustomDagsterLookerApiTranslator |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type_test.py | {
"start": 39945,
"end": 47257
} | class ____(
test_util.TensorFlowTestCase, parameterized.TestCase
):
def testSpecConstructor(self):
values_spec = tensor.TensorSpec([4], dtypes.float32)
mask_spec = tensor.TensorSpec([4], dtypes.bool)
mt_spec = MaskedTensorV1.Spec(values_spec, mask_spec)
self.assertEqual(mt_spec.values, values_spec)
self.assertEqual(mt_spec.mask, mask_spec)
mt = MaskedTensorV1([1.0, 2.0, 3.0, 4.0], [True, True, False, True])
self.assertEqual(mt._type_spec, mt_spec)
def testSpecConstructorSignature(self):
class MyType(extension_type.ExtensionType):
x: tensor.Tensor
y: tensor.Tensor
z: typing.Tuple[typing.Union[int, str], ...] = [1, 'two', 3]
expected_parameters = [
tf_inspect.Parameter('self', POSITIONAL_OR_KEYWORD),
tf_inspect.Parameter('x', POSITIONAL_OR_KEYWORD),
tf_inspect.Parameter('y', POSITIONAL_OR_KEYWORD),
tf_inspect.Parameter('z', POSITIONAL_OR_KEYWORD),
]
expected_sig = tf_inspect.Signature(
expected_parameters, return_annotation=MyType.Spec
)
self.assertEqual(expected_sig, tf_inspect.signature(MyType.Spec.__init__))
def testSpecAttributesAreImmutable(self):
mt = MaskedTensorV1([1, 2, 3, 4], [True, True, False, True])
mt_spec = MaskedTensorV1.Spec.from_value(mt)
with self.assertRaisesRegex(
AttributeError,
'Cannot mutate attribute `score` '
'outside the custom constructor of ExtensionTypeSpec',
):
mt_spec.score = 12
with self.assertRaisesRegex(
AttributeError,
'Cannot mutate attribute `values` '
'outside the custom constructor of ExtensionTypeSpec',
):
mt_spec.values = constant_op.constant([4, 3, 2, 1])
with self.assertRaisesRegex(
AttributeError,
'Cannot mutate attribute `values` '
'outside the custom constructor of ExtensionTypeSpec',
):
del mt_spec.values
def testSpecFromValue(self):
mt = MaskedTensorV1([1.0, 2.0, 3.0, 4.0], [True, True, False, True])
mt_spec = MaskedTensorV1.Spec.from_value(mt)
expected_values_spec = tensor.TensorSpec([4], dtypes.float32)
expected_mask_spec = tensor.TensorSpec([4], dtypes.bool)
self.assertEqual(mt_spec.values, expected_values_spec)
self.assertEqual(mt_spec.mask, expected_mask_spec)
def testSpecSerialize(self):
class Zoo(extension_type.ExtensionType):
zookeepers: typing.Tuple[str, ...]
animals: typing.Mapping[str, typing.Mapping[str, tensor.Tensor]]
featurespec = {
'size': tensor.TensorSpec([3]),
'weight': tensor.TensorSpec([]),
}
zoo_spec = Zoo.Spec(
zookeepers=['Zoey', 'Zack'],
animals={'tiger': featurespec, 'elephant': featurespec},
)
serialized = zoo_spec._serialize()
self.assertEqual(
serialized,
(
('zookeepers', ('Zoey', 'Zack')),
('animals', {'tiger': featurespec, 'elephant': featurespec}),
),
)
restored = Zoo.Spec._deserialize(serialized)
self.assertEqual(zoo_spec, restored)
# ImmutableDict is used for the field, but dict for the serialization:
self.assertIsInstance(zoo_spec.animals, immutable_dict.ImmutableDict)
serialized_field_name, serialized_field_value = serialized[1]
self.assertEqual(serialized_field_name, 'animals')
self.assertIsInstance(serialized_field_value, dict)
def testSpecComponents(self):
class Zoo(extension_type.ExtensionType):
zookeepers: typing.Tuple[str, ...]
animals: typing.Mapping[str, typing.Mapping[str, tensor.Tensor]]
zoo = Zoo(
['Zoey', 'Zack'],
{
'elephant': {'size': [25, 30, 20], 'weight': 2000.0},
'tiger': {'hunger': 3.2, 'size': [3, 8, 2], 'weight': 87.3},
},
)
zoo_spec = Zoo.Spec.from_value(zoo)
components = zoo_spec._to_components(zoo)
self.assertLen(components, 5)
self.assertAllClose(components[0], [25, 30, 20])
self.assertAllClose(components[1], 2000.0)
self.assertAllClose(components[2], 3.2)
self.assertAllClose(components[3], [3, 8, 2])
self.assertAllClose(components[4], 87.3)
restored = zoo_spec._from_components(components)
self.assertAllEqual(zoo == restored, True)
self.assertEqual(
zoo_spec._component_specs,
(
tensor.TensorSpec([3], dtypes.int32),
tensor.TensorSpec([], dtypes.float32),
tensor.TensorSpec([], dtypes.float32),
tensor.TensorSpec([3], dtypes.int32),
tensor.TensorSpec([], dtypes.float32),
),
)
def testCopyAndPickle(self):
values_spec = tensor.TensorSpec([4], dtypes.float32)
mask_spec = tensor.TensorSpec([4], dtypes.bool)
mt_spec = MaskedTensorV1.Spec(values_spec, mask_spec)
self.assertEqual(copy.copy(mt_spec), mt_spec)
self.assertEqual(copy.deepcopy(mt_spec), mt_spec)
self.assertEqual(pickle.loads(pickle.dumps(mt_spec)), mt_spec)
def testCustomizeSpecTest(self):
class WeightedTensor(extension_type.ExtensionType):
"""ExtensionType with a customized TypeSpec.
* Custom constructor.
* Custom __validate__.
* Add properties (shape, dtype, weight_dtype).
* Add method (with_shape).
"""
values: tensor.Tensor
weight: tensor.Tensor # scalar
shape = property(lambda self: self.shape)
dtype = property(lambda self: self.dtype)
weight_dtype = property(lambda self: self.weight.dtype)
def __validate__(self):
self.weight.shape.assert_has_rank(0)
class Spec:
def __init__(self, shape, dtype, weight_dtype=dtypes.float32):
self.values = tensor.TensorSpec(shape, dtype)
self.weight = tensor.TensorSpec([], weight_dtype)
def __validate__(self):
self.weight.shape.assert_has_rank(0)
shape = property(lambda self: self.values.shape)
dtype = property(lambda self: self.values.dtype)
weight_dtype = property(lambda self: self.weight.dtype)
def with_shape(self, shape):
return WeightedTensor.Spec(shape, self.dtype, self.weight_dtype)
wt = WeightedTensor([1, 2], 0.3)
wt_spec = WeightedTensor.Spec.from_value(wt)
self.assertEqual(wt_spec.shape, tensor_shape.TensorShape([2]))
self.assertEqual(wt_spec.dtype, dtypes.int32)
self.assertEqual(wt_spec, WeightedTensor.Spec([2], dtypes.int32))
wt2 = WeightedTensor([[1, 2], [3, 4]], 0.5)
wt2_spec = WeightedTensor.Spec.from_value(wt2)
self.assertEqual(wt_spec.with_shape([2, 2]), wt2_spec)
def testNestedSpecMustBeAClass(self):
with self.assertRaisesRegex(
ValueError, r'BrokenExtensionType\.Spec must be a nested class; got 12.'
):
class BrokenExtensionType(extension_type.ExtensionType):
Spec = 12 # pylint: disable=invalid-name
del BrokenExtensionType
def testNestedSpecMayNotHaveBaseClasses(self):
with self.assertRaisesRegex(
ValueError,
r'BrokenExtensionType\.Spec must be directly subclassed '
'from tf.TypeSpec.',
):
class BrokenExtensionType(extension_type.ExtensionType):
class Spec(type_spec.BatchableTypeSpec):
pass
del BrokenExtensionType
@test_util.run_all_in_graph_and_eager_modes
| ExtensionTypeSpecTest |
python | walkccc__LeetCode | solutions/1786. Number of Restricted Paths From First to Last Node/1786.py | {
"start": 0,
"end": 992
} | class ____:
def countRestrictedPaths(self, n: int, edges: list[list[int]]) -> int:
graph = [[] for _ in range(n)]
for u, v, w in edges:
graph[u - 1].append((v - 1, w))
graph[v - 1].append((u - 1, w))
return self._dijkstra(graph, 0, n - 1)
def _dijkstra(
self,
graph: list[list[tuple[int, int]]],
src: int,
dst: int,
) -> int:
MOD = 10**9 + 7
# ways[i] := the number of restricted path from i to n
ways = [0] * len(graph)
# dist[i] := the distance to the last node of i
dist = [math.inf] * len(graph)
ways[dst] = 1
dist[dst] = 0
minHeap = [(dist[dst], dst)] # (d, u)
while minHeap:
d, u = heapq.heappop(minHeap)
if d > dist[u]:
continue
for v, w in graph[u]:
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(minHeap, (dist[v], v))
if dist[v] < dist[u]:
ways[u] += ways[v]
ways[u] %= MOD
return ways[src]
| Solution |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/runtime_wrappers.py | {
"start": 41930,
"end": 66474
} | class ____(CompilerWrapper):
# Currently, the only reason we need to plumb this bool is because
# the synthetic base code prohibits more cases in the autograd case than the inference case.
trace_joint: bool # TODO: refactor trace_joint
needs_post_compile: bool = True
aliased_arg_idx_with_metadata_mutations: list[int] = field(default_factory=list)
def pre_compile(
self,
flat_fn: TraceFn,
flat_args: list[FxValue],
flat_args_descs: list[AOTInput],
aot_config: AOTConfig,
*,
fw_metadata: ViewAndMutationMeta,
) -> tuple[Callable, list[FxValue], list[AOTInput], ViewAndMutationMeta]:
is_inference = not self.trace_joint
(
flat_args_with_synthetic_bases,
flat_args_descs_with_synthetic_bases,
synthetic_base_info,
) = merge_view_inputs(
aot_config,
flat_args,
flat_args_descs,
fw_metadata.input_info,
is_inference=is_inference,
)
# Happy path: we don't need synthetic bases
if synthetic_base_info is None:
self.needs_post_compile = False
return flat_fn, flat_args, flat_args_descs, fw_metadata
# export path: ban synthetic bases for now, add later if requested.
if requires_subclass_dispatch(flat_args, fw_metadata):
raise RuntimeError(
"""\
Encountered aliased inputs that are mutated in the graph, but at least one input/output
to the graph is a tensor subclass. This is not supported today. You can try to
remove the aliasing yourself as a workaround, or otherwise file an issue on github."""
)
if aot_config.is_export:
raise RuntimeError(
f"""\
Encountered aliased inputs that are mutated in the graph you are trying to export.
This functionality is currently not supported. If needed, please file a github issue.
synthetic_base_info={str(synthetic_base_info)}
fw_metadata={str(fw_metadata)}
"""
)
assert len(fw_metadata.input_info) == len(synthetic_base_info)
# Update our forward metadata to take synthetic bases into account
(
fw_metadata_updated,
aliased_arg_idx_with_metadata_mutations,
) = create_synthetic_base_metadata(
fw_metadata,
synthetic_base_info,
flat_args,
flat_args_with_synthetic_bases,
flat_args_descs_with_synthetic_bases,
)
# Save old input args for post-compile
self.old_input_info = fw_metadata.input_info
self.aliased_arg_idx_with_metadata_mutations = (
aliased_arg_idx_with_metadata_mutations
)
replay_views = config.view_replay_for_aliased_outputs
def _unpack_synthetic_bases(primals: tuple[Any, ...]) -> list[Any]:
f_args_inner = []
# pyrefly: ignore [not-iterable]
for inner_idx_or_tuple in synthetic_base_info:
if isinstance(inner_idx_or_tuple, int):
f_args_inner.append(primals[inner_idx_or_tuple])
else:
inner_base_idx, view_tensor = inner_idx_or_tuple
base = primals[inner_base_idx]
view_arg = gen_alias_from_base(
base,
view_tensor,
view_tensor.requires_grad,
replay_views=replay_views,
)
f_args_inner.append(view_arg)
return f_args_inner
@simple_wraps(flat_fn)
def wrapped_flat_fn(*args):
unpacked_args = _unpack_synthetic_bases(args)
# This is a bit subtle. The goal of this entire function (aot_dispatch_synthetic_bases)
# is to relieve the downstream logic from having to reason about mutations on inputs that alias
# each other, by replacing aliased inputs with a synthetic base.
# One area where this breaks down a bit however is if one of those aliased inputs
# experienced a metadata mutation.
# We are now obligated to reapply the metadata mutation directly to the user's input;
# it isn't enough to apply mutations back to the synthetic base in the downstream logic.
#
# The way we handle this is by pretending that those aliased inputs that experience metadata mutations
# are additional outputs in the user's forward function.
# The downstream logic will just treat these as "user outputs that alias inputs".
# However, we will manually grab them at runtime here, use them to reapply the metadata mutation
# to the user inputs, and not return them to the user.
aliased_args_with_metadata_mutations = [
x
for i, x in enumerate(unpacked_args)
if i in self.aliased_arg_idx_with_metadata_mutations
]
out, out_descs = call_and_expect_output_descs(flat_fn, unpacked_args)
if len(aliased_args_with_metadata_mutations) > 0:
# TODO: record more detailed desc information here
return (*out, *aliased_args_with_metadata_mutations), (
*out_descs,
*(
[
MetadataMutationAOTOutput(i)
for i in range(
len(self.aliased_arg_idx_with_metadata_mutations)
)
]
),
)
else:
return out, out_descs
if config.debug_assert:
ref_fw_metadata = run_functionalized_fw_and_collect_metadata(
without_output_descs(wrapped_flat_fn),
flat_args_descs=flat_args_descs_with_synthetic_bases,
static_input_indices=aot_config.static_input_indices,
keep_input_mutations=fw_metadata.keep_input_mutations,
is_train=fw_metadata.is_train,
)(*flat_args_with_synthetic_bases)
assert ref_fw_metadata == fw_metadata_updated, (
f"ref_metadata={pprint.pformat(partial_flatten_asdict(ref_fw_metadata))}, "
f"\nactual_metadata={pprint.pformat(partial_flatten_asdict(fw_metadata_updated))}"
)
return (
wrapped_flat_fn,
flat_args_with_synthetic_bases,
flat_args_descs_with_synthetic_bases,
fw_metadata_updated,
)
def post_compile(
self,
compiled_fn,
aot_config: AOTConfig,
*,
runtime_metadata: ViewAndMutationMeta,
):
if not self.needs_post_compile:
return compiled_fn
is_inference = not self.trace_joint
@wraps(compiled_fn)
def wrapped_compiled_fn(args):
# TODO: this sure seems expensive to run at runtime (which
# post_compile seems to imply it does?!)
args_with_synthetic_bases, _, synthetic_base_info = merge_view_inputs(
aot_config, args, None, self.old_input_info, is_inference=is_inference
)
assert synthetic_base_info is not None
aliased_args_w_metadata_mutations = [
args[i] for i in self.aliased_arg_idx_with_metadata_mutations
]
num_aliased_args_with_metadata_mutations = len(
aliased_args_w_metadata_mutations
)
args.clear()
outs = compiled_fn(args_with_synthetic_bases)
if num_aliased_args_with_metadata_mutations > 0:
# This code does not handle **all** input metadata mutations.
# Instead, it only handles metadata mutations on inputs that were converted into synthetic bases
# (which only happens if at least one aliased input experienced a data mutation).
# e.g:
# def f(a, b):
# a.mul_(2)
# b.t_(1, 0)
# f(x.view(2, 2), x.view(2, 2))
mutated_metadata_inps = outs[-num_aliased_args_with_metadata_mutations:]
user_outs = outs[:-num_aliased_args_with_metadata_mutations]
for inp, mutated_inp in zip(
aliased_args_w_metadata_mutations, mutated_metadata_inps
):
inp.as_strided_(
mutated_inp.size(),
mutated_inp.stride(),
mutated_inp.storage_offset(),
)
return user_outs
return outs
return wrapped_compiled_fn
# Note [Handling mutations on an input that aliases other inputs]
# The easiest example to show-case this edge case is here:
#
# def f(a, b):
# a.mul_(2)
# out = a + b
# return out
# b = torch.ones(...)
# a = b.view(-1)
# f(a, b)
#
# In this situation, if a and b happened to be aliased, we need to trace something different!
# Suppose we had b = a.view(-1)
# (In this case, that means that `a._base is b`)
#
# We need to ensure that the aliasing relationship between a and b is preserved.
# We do that detecting the specific situation above (mutate an input that aliases another input),
# and when we do that, we create a synthetic base argument. Then inside of the traced forward,
# we regenerate a and b off of that base.
# The complete example of the transformed function looks like this:
#
# // The traced forward takes in a synthetic base, and regenerates the aliased inputs as views
# // We could consider getting view-replay support here to minimize as_strided_scatter ops in the graph
# def traced_forward(base):
# a = base.as_strided(...)
# b = base.as_strided(...)
# a_updated = a.mul(2)
# base_updated = torch.as_strided_scatter(base, a_updated, ...)
# b_updated = base_updated.as_strided(...)
# out = a_updated + b_updated
# return a_updated, out
#
# def compiled_fn(a, b):
# // we detect that a is the "differentiable base" here
# base = a
# // In other situations, we might do either:
# // (1) a and b are both views off of some larger differentiable base
# // assert a._base is b._base and a._base is not None
# // base = a._base
# // (2) a and b both don't require gradients. Create a base from the storage
# // assert a._base is None and b._base is None
# // base = torch.Tensor(a.storage())
# a_updated, out = traced_forward(base)
# a.copy_(a_updated)
# return out
#
# This function:
# (1) Merges input views into a synthetic base argument, when any of those input views are mutated
# (2) Returns metadata telling the autograd.Function how to modify their arguments properly,
# to respect the new calling convention.
#
# The calling convention is as follows.
# Any inputs that were originally views of one another get yanked, and replaced with a synthetic base.
# The argument list ordering goes [base1, ..., baseN], [arg1, ..., argN],
# Where the ordering of the bases is determined from the ordering of the original view args.
# baseA will come before baseB if the earliest original argument coming from baseA
# showed up earlier in the argument list than the earliest original argument coming from baseB.
#
# Example, given some tensors a, b, c, d
# call site:
# f(a, c.view(-1), b.view(-1), b, c, d)
# Modified argument list:
# c_base comes first because the first c view came earlier in arg list than the first b view
# a and d still show up in the modified arg list, but b and c don't- they're regenerated from their bases
# b_base = torch.Tensor(b.storage())
# c_base = torch.Tensor(c.storage())
# f(c_base, b_base, a, d)
def merge_view_inputs(
aot_config: AOTConfig,
fwd_inputs: list[Any],
# This is None when called at runtime from post_compile closure
fwd_inputs_descs: Optional[list[AOTInput]],
mutated_input_info: list[InputAliasInfo],
*,
# The autograd case currently has more restrictions than the inference case.
is_inference: bool,
) -> tuple[
list[Any], list[AOTInput], Optional[list[Union[int, tuple[int, torch.Tensor]]]]
]:
if fwd_inputs_descs is None:
fwd_inputs_descs = [DummyAOTInput(i) for i in range(len(fwd_inputs))]
def _are_differentiable_views(view1, view2):
if view1 is view2:
return True
if view1._base is None and view2._base is None:
return False
if view1._base is view2._base or view1._base is view2 or view1 is view2._base:
return True
return False
def _same_dtype_views(view1, view2):
if view1.dtype != view2.dtype:
return False
if view1._base is not None and view1.dtype != view1._base.dtype:
return False
if view2._base is not None and view2.dtype != view2._base.dtype:
return False
return True
assert len(fwd_inputs) == len(mutated_input_info)
if not [info for info in mutated_input_info if info.mutates_data]:
# Return early when there are no mutations.
return fwd_inputs, fwd_inputs_descs, None
storage_ref_to_idx: dict[StorageWeakRef, list[int]] = collections.defaultdict(list)
base_args = []
other_args = []
base_args_descs = []
other_args_descs = []
for i, (inpt, source) in enumerate(zip(fwd_inputs, fwd_inputs_descs)):
if isinstance(inpt, Tensor):
storage_ref = StorageWeakRef(inpt.untyped_storage())
storage_ref_to_idx[storage_ref].append(i)
else:
other_args.append(inpt)
other_args_descs.append(source)
# Note [Synthetic Base Info Metadata]
# This list contains metadata that tells you what the i'th argument in the inner calling convention should be.
# It's either:
# - another int (corresponding to the index in the argument list of the element from the outer calling convention)
# - idx, view_tensor, where we can generate the new output with view_tensor._view_func(old_args[idx])
# idx corresponds to which synthetic base from the outer calling context to view
inner_calling_convention_meta: dict[int, Union[int, tuple[int, torch.Tensor]]] = {}
for aliased_input_indices in storage_ref_to_idx.values():
if len(aliased_input_indices) <= 1 or not any(
# We only care about mutations that affect all aliases,
# so metadata mutations on an input doesn't require us to do synthetic base handling.
mutated_input_info[inpt_idx].mutates_data
for inpt_idx in aliased_input_indices
):
other_args.extend(
fwd_inputs[curr_idx] for curr_idx in aliased_input_indices
)
other_args_descs.extend(
fwd_inputs_descs[curr_idx] for curr_idx in aliased_input_indices
)
continue
# Here, we attempt to do a more complicated check to detect false aliasing
# (e.g. if all the tensors have the same storage, but don't actually overlap)
# In theory, we could have a large group of tensors that all share storages, where only *some* of them
# have overlapping memory.
# I don't bother with that case for now: here, we only bail out earlier if we detect that **every** pair
# of tensors in the current group that shares a storage is non-overlapping.
aliased_input_indices_no_false_sharing = compute_overlapping_inputs(
aot_config, fwd_inputs, aliased_input_indices
)
if len(aliased_input_indices_no_false_sharing) <= 1:
other_args.extend(
fwd_inputs[curr_idx] for curr_idx in aliased_input_indices
)
other_args_descs.extend(
fwd_inputs_descs[curr_idx] for curr_idx in aliased_input_indices
)
continue
# We detected an input that was mutated, AND aliases with another input.
# we need to replace this set of aliased inputs with a single synthetic base.
# For now, I'm banning a bunch of cases. We expect dynamo to properly detect these cases
# and error out. We can fix them later.
# These checks are transitive, so we don't need to check every pair.
for idx1, idx2 in zip(
aliased_input_indices, aliased_input_indices[1:], strict=False
):
view1 = fwd_inputs[idx1]
view2 = fwd_inputs[idx2]
# The "inputs that are aliased but have different differentiable bases" case
# is more complicated and hopefully pretty rare. Not currently handled.
if not is_inference:
assert _are_differentiable_views(view1, view2), (
"aot_autograd() does not yet handle non-differentiable view input mutations."
)
# Regenerating views when reinterpreting complex / real tensors seems non-trivial,
# not handling for now
assert _same_dtype_views(view1, view2), (
"aot_autograd() does not yet handle input mutations on views with different dtypes."
)
non_none_bases = [
(i, fwd_inputs[i]._base)
for i in aliased_input_indices
if fwd_inputs[i]._base is not None
]
aliases_with_none_bases = [
fwd_inputs[i] for i in aliased_input_indices if fwd_inputs[i]._base is None
]
synthetic_base_desc: AOTInput
if len(non_none_bases) == 0:
# Case where none of the aliases have a ._base
# we generate a synthetic base without gradients, and generate views off of it
# We hit this case when we have input tensors to the graph that share a storage,
# but do not have a ._base field.
# Wondering when we hit this case?
# The _base field simply says that autograd knows about the aliasing relationship,
# but sometimes we create tensors which are aliased out of the same storage but guaranteed
# to be disjoint. In these cases, we will skip setting up the _base relationship
# for performance reasons (because the fact that the tensors share the same storage
# is unobservable unless you (1) do naughty things with resize_/as_strided
# or (2) look at the storage--as we are doing here.)
# One particular example of this is optimizer steps on the LSTM module:
# LSTM parameters are packed into a contiguous storage for efficiency reasons when
# calling cuDNN kernels, so when these parameters get passed to the optimizer we will
# find they share the same storage, but do not have _base set since they are all disjoint.
#
# NOTE: There is one case where this is unsafe:
# torch.Tensor(storage) will ALWAYS create a 1D tensor, which is not necessarily
# the same shape as the "actual" base that the tensor came from.
# For the most part this is fine, because we always use as_strided()
# to generate the original aliased inputs again.
# If we were to use view-replay though, this could cause the aliased views
# to have incorrect sizes.
example_idx = aliased_input_indices[0]
example_alias = fwd_inputs[example_idx]
# Note that this function is reused at both trace time and runtime.
# At trace time, we're under a FakeMode so synthetic_base becomes a FakeTensor.
synthetic_base = torch.empty(
(0,), dtype=example_alias.dtype, device=example_alias.device
)
# We don't actually have a convenient way of going from storage -> tensor,
# So using set_() here (we suffer some minor overhead, but this case is rare).
synthetic_base.set_(example_alias.untyped_storage())
synthetic_base_desc = SyntheticBaseAOTInput(fwd_inputs_descs[example_idx])
else:
# Case where all of the aliases require gradients, and have the same _base.
i, synthetic_base = non_none_bases[0]
synthetic_base_desc = ViewBaseAOTInput(fwd_inputs_descs[i])
for _, other_base in non_none_bases[1:]:
assert other_base is synthetic_base, (
"aot_autograd() does not yet handle non-differentiable view input mutations."
)
for alias in aliases_with_none_bases:
assert alias is synthetic_base, (
"aot_autograd() does not yet handle non-differentiable view input mutations."
)
base_args.append(synthetic_base)
base_args_descs.append(synthetic_base_desc)
for curr_view_idx in aliased_input_indices:
curr_view = fwd_inputs[curr_view_idx]
base_idx = len(base_args) - 1
# We store just enough info here so that we can regenerate the view later.
# Regeneration: curr_view._view_func(args[base_idx])
inner_calling_convention_meta[curr_view_idx] = (base_idx, curr_view)
if len(base_args) == 0:
assert len(other_args) == len(fwd_inputs)
# If no synthetic bases are necessary, just return the original inputs.
return fwd_inputs, fwd_inputs_descs, None
else:
from torch.fx.experimental.symbolic_shapes import SymIntEqByExpr
def make_hashable(arg):
if isinstance(arg, torch.SymInt):
# Since only nested SymInt objects can be hashed, we wrap them with
# SymIntEqByExpr, which is a hashable wrapper of SymInts.
return SymIntEqByExpr(arg)
return arg
# Otherwise, return:
# (1) The new args according to the updated calling convention: (synthetic_bases, other_args)
# (2) Metadata telling functionalization how to generate the inner argument list given the outer calling convention.
# We post-process it into a list, where meta[i] tells you info about the i'th argument in the inner calling convention.
args_to_functionalization = base_args + other_args
args_to_functionalization_descs = base_args_descs + other_args_descs
# Map each argument into its old index.
# There may be some repeated arguments, so we collect their indices in a list.
arg_to_old_idx_map = collections.defaultdict(list)
for i, arg in enumerate(fwd_inputs):
arg_to_old_idx_map[make_hashable(arg)].append(i)
# Reverse the list of each argument, so that we can easily pop them one-after-the-other in order.
for hashable_arg in arg_to_old_idx_map:
arg_to_old_idx_map[hashable_arg] = list(
reversed(arg_to_old_idx_map[hashable_arg])
)
for i, other_arg in enumerate(other_args):
new_idx = len(base_args) + i
old_idx = arg_to_old_idx_map[make_hashable(other_arg)].pop()
inner_calling_convention_meta[old_idx] = new_idx
# post process into a list
post_processed_calling_convention_meta: list[
Union[int, tuple[int, torch.Tensor]]
] = [-1 for _ in range(len(inner_calling_convention_meta))]
for k, v in inner_calling_convention_meta.items():
post_processed_calling_convention_meta[k] = v
# Quick assert: every argument in the inner calling convention should be accounted for.
for x in post_processed_calling_convention_meta:
assert x != -1
return (
args_to_functionalization,
args_to_functionalization_descs,
post_processed_calling_convention_meta,
)
# Note: [Backward graph lazy lowering]
# After AOTDispatch traces the backward for graphs requiring autograd, we will lower the graph lazily,
# unless we suspect that inductor might specialize and insert additional guards. When we do lazy
# lowering, we stash the AOT backward graph (bw_module) in this class.
#
# Lowering passes are performed on a deepcopy of this bw_module due to compatibility
# with compiled autograd. See: https://github.com/pytorch/pytorch/pull/149229#discussion_r2002122645.
@dataclass
| AOTSyntheticBaseWrapper |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/processors.py | {
"start": 18980,
"end": 19813
} | class ____(Processor):
"""
Append the auto suggestion to the input.
(The user can then press the right arrow the insert the suggestion.)
"""
def __init__(self, style: str = "class:auto-suggestion") -> None:
self.style = style
def apply_transformation(self, ti: TransformationInput) -> Transformation:
# Insert fragments after the last line.
if ti.lineno == ti.document.line_count - 1:
buffer = ti.buffer_control.buffer
if buffer.suggestion and ti.document.is_cursor_at_the_end:
suggestion = buffer.suggestion.text
else:
suggestion = ""
return Transformation(fragments=ti.fragments + [(self.style, suggestion)])
else:
return Transformation(fragments=ti.fragments)
| AppendAutoSuggestion |
python | sqlalchemy__sqlalchemy | test/orm/test_subquery_relations.py | {
"start": 96577,
"end": 103674
} | class ____(
fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL
):
__dialect__ = "default"
run_inserts = "once"
run_deletes = None
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class Director(Base):
__tablename__ = "director"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=True
)
name = Column(String(50))
class DirectorPhoto(Base):
__tablename__ = "director_photo"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=True
)
path = Column(String(255))
director_id = Column(Integer, ForeignKey("director.id"))
director = relationship(
Director, backref=backref("photos", order_by=id)
)
class Movie(Base):
__tablename__ = "movie"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=True
)
director_id = Column(Integer, ForeignKey("director.id"))
director = relationship(Director, backref="movies")
title = Column(String(50))
credits = relationship("Credit", backref="movie")
class Credit(Base):
__tablename__ = "credit"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=True
)
movie_id = Column(Integer, ForeignKey("movie.id"))
@classmethod
def insert_data(cls, connection):
Movie = cls.classes.Movie
Director = cls.classes.Director
DirectorPhoto = cls.classes.DirectorPhoto
Credit = cls.classes.Credit
d = Director(name="Woody Allen")
d.photos = [DirectorPhoto(path="/1.jpg"), DirectorPhoto(path="/2.jpg")]
d.movies = [
Movie(title="Manhattan", credits=[Credit(), Credit()]),
Movie(title="Sweet and Lowdown", credits=[Credit()]),
]
sess = Session(connection)
sess.add_all([d])
sess.flush()
def test_distinct_strategy_opt_m2o(self):
self._run_test_m2o(True, None)
self._run_test_m2o(False, None)
def test_distinct_unrelated_opt_m2o(self):
self._run_test_m2o(None, True)
self._run_test_m2o(None, False)
def _run_test_m2o(self, director_strategy_level, photo_strategy_level):
# test where the innermost is m2o, e.g.
# Movie->director
Movie = self.classes.Movie
Director = self.classes.Director
Movie.director.property.distinct_target_key = director_strategy_level
Director.photos.property.distinct_target_key = photo_strategy_level
# the DISTINCT is controlled by
# only the Movie->director relationship, *not* the
# Director.photos
expect_distinct = director_strategy_level in (True, None)
s = fixture_session()
with self.sql_execution_asserter(testing.db) as asserter:
result = (
s.query(Movie)
.options(
subqueryload(Movie.director).subqueryload(Director.photos)
)
.all()
)
asserter.assert_(
CompiledSQL(
"SELECT movie.id AS movie_id, movie.director_id "
"AS movie_director_id, movie.title AS movie_title FROM movie"
),
CompiledSQL(
"SELECT director.id AS director_id, "
"director.name AS director_name, "
"anon_1.movie_director_id AS anon_1_movie_director_id "
"FROM (SELECT%s movie.director_id AS movie_director_id "
"FROM movie) AS anon_1 "
"JOIN director ON director.id = anon_1.movie_director_id"
% (" DISTINCT" if expect_distinct else ""),
),
CompiledSQL(
"SELECT director_photo.id AS director_photo_id, "
"director_photo.path AS director_photo_path, "
"director_photo.director_id AS director_photo_director_id, "
"director_1.id AS director_1_id "
"FROM (SELECT%s movie.director_id AS movie_director_id "
"FROM movie) AS anon_1 "
"JOIN director AS director_1 "
"ON director_1.id = anon_1.movie_director_id "
"JOIN director_photo "
"ON director_1.id = director_photo.director_id "
"ORDER BY director_photo.id"
% (" DISTINCT" if expect_distinct else ""),
),
)
eq_(
[
(
movie.title,
movie.director.name,
[photo.path for photo in movie.director.photos],
)
for movie in result
],
[
("Manhattan", "Woody Allen", ["/1.jpg", "/2.jpg"]),
("Sweet and Lowdown", "Woody Allen", ["/1.jpg", "/2.jpg"]),
],
)
# check number of persistent objects in session
eq_(len(list(s)), 5)
def test_cant_do_distinct_in_joins(self):
"""the DISTINCT feature here works when the m2o is in the innermost
mapper, but when we are just joining along relationships outside
of that, we can still have dupes, and there's no solution to that.
"""
Movie = self.classes.Movie
Credit = self.classes.Credit
s = fixture_session()
with self.sql_execution_asserter(testing.db) as asserter:
result = (
s.query(Credit)
.options(
subqueryload(Credit.movie).subqueryload(Movie.director)
)
.all()
)
asserter.assert_(
CompiledSQL(
"SELECT credit.id AS credit_id, credit.movie_id AS "
"credit_movie_id FROM credit"
),
CompiledSQL(
"SELECT movie.id AS movie_id, movie.director_id "
"AS movie_director_id, movie.title AS movie_title, "
"anon_1.credit_movie_id AS anon_1_credit_movie_id "
"FROM (SELECT DISTINCT credit.movie_id AS credit_movie_id "
"FROM credit) AS anon_1 JOIN movie ON movie.id = "
"anon_1.credit_movie_id"
),
CompiledSQL(
"SELECT director.id AS director_id, director.name "
"AS director_name, movie_1.director_id AS movie_1_director_id "
"FROM (SELECT DISTINCT credit.movie_id AS credit_movie_id "
"FROM credit) AS anon_1 JOIN movie AS movie_1 ON "
"movie_1.id = anon_1.credit_movie_id JOIN director "
"ON director.id = movie_1.director_id"
),
)
eq_(
[credit.movie.director.name for credit in result],
["Woody Allen", "Woody Allen", "Woody Allen"],
)
| SubqueryloadDistinctTest |
python | django__django | tests/decorators/test_gzip.py | {
"start": 188,
"end": 1605
} | class ____(SimpleTestCase):
# Gzip ignores content that is too short.
content = "Content " * 100
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = gzip_page(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_async_function_is_coroutine_function(self):
async def async_view(request):
return HttpResponse()
wrapped_view = gzip_page(async_view)
self.assertIs(iscoroutinefunction(wrapped_view), True)
def test_gzip_page_decorator(self):
@gzip_page
def sync_view(request):
return HttpResponse(content=self.content)
request = HttpRequest()
request.META["HTTP_ACCEPT_ENCODING"] = "gzip"
response = sync_view(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get("Content-Encoding"), "gzip")
async def test_gzip_page_decorator_async_view(self):
@gzip_page
async def async_view(request):
return HttpResponse(content=self.content)
request = HttpRequest()
request.META["HTTP_ACCEPT_ENCODING"] = "gzip"
response = await async_view(request)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.get("Content-Encoding"), "gzip")
| GzipPageTests |
python | scipy__scipy | benchmarks/benchmarks/spatial.py | {
"start": 15527,
"end": 16562
} | class ____(Benchmark):
params = (['euclidean', 'minkowski', 'cityblock', 'sqeuclidean', 'cosine',
'correlation', 'hamming', 'jaccard', 'chebyshev', 'canberra',
'braycurtis', 'yule', 'dice', 'rogerstanimoto',
'russellrao', 'sokalsneath', 'minkowski-P3'])
param_names = ['metric']
def setup(self, metric):
rng = np.random.default_rng(123)
self.points = rng.random((2, 3))
self.metric = metric
if metric == 'minkowski-P3':
# p=2 is just the euclidean metric, try another p value as well
self.kwargs = {'p': 3.0, 'w': np.ones(3)}
self.metric = 'minkowski'
else:
self.kwargs = {'w': np.ones(3)}
def time_dist_weighted(self, metric):
"""Time weighted distance metrics individually (without batching
with cdist or pdist).
"""
getattr(distance, self.metric)(self.points[0], self.points[1],
**self.kwargs)
| SingleDistWeighted |
python | kamyu104__LeetCode-Solutions | Python/minimum-incompatibility.py | {
"start": 6348,
"end": 10052
} | class ____(object):
P_NUMERATOR, P_DENOMINATOR = 1, 2 # P = 1/4 in redis implementation
MAX_LEVEL = 32 # enough for 2^32 elements
def __init__(self, end=float("inf"), can_duplicated=False, cmp=lambda x, y: x < y):
seed(0)
self.__head = SkipNode()
self.__len = 0
self.__can_duplicated = can_duplicated
self.__cmp = cmp
self.add(end)
self.__end = self.find(end)
def begin(self):
return self.__head.nexts[0]
def end(self):
return self.__end
def lower_bound(self, target):
return self.__lower_bound(target, self.__find_prev_nodes(target))
def find(self, target):
return self.__find(target, self.__find_prev_nodes(target))
def add(self, val):
if not self.__can_duplicated and self.find(val):
return self.find(val), False
node = SkipNode(self.__random_level(), val)
if len(self.__head.nexts) < len(node.nexts):
self.__head.nexts.extend([None]*(len(node.nexts)-len(self.__head.nexts)))
prevs = self.__find_prev_nodes(val)
for i in xrange(len(node.nexts)):
node.nexts[i] = prevs[i].nexts[i]
if prevs[i].nexts[i]:
prevs[i].nexts[i].prevs[i] = node
prevs[i].nexts[i] = node
node.prevs[i] = prevs[i]
self.__len += 1
return node if self.__can_duplicated else (node, True)
def remove(self, it):
prevs = it.prevs
curr = self.__find(it.val, prevs)
if not curr:
return self.__end
self.__len -= 1
for i in reversed(xrange(len(curr.nexts))):
prevs[i].nexts[i] = curr.nexts[i]
if curr.nexts[i]:
curr.nexts[i].prevs[i] = prevs[i]
if not self.__head.nexts[i]:
self.__head.nexts.pop()
return curr.nexts[0]
def __lower_bound(self, val, prevs):
if prevs:
candidate = prevs[0].nexts[0]
if candidate:
return candidate
return None
def __find(self, val, prevs):
candidate = self.__lower_bound(val, prevs)
if candidate and candidate.val == val:
return candidate
return None
def __find_prev_nodes(self, val):
prevs = [None]*len(self.__head.nexts)
curr = self.__head
for i in reversed(xrange(len(self.__head.nexts))):
while curr.nexts[i] and self.__cmp(curr.nexts[i].val, val):
curr = curr.nexts[i]
prevs[i] = curr
return prevs
def __random_level(self):
level = 1
while randint(1, SkipList.P_DENOMINATOR) <= SkipList.P_NUMERATOR and \
level < SkipList.MAX_LEVEL:
level += 1
return level
def __iter__(self):
it = self.begin()
while it != self.end():
yield it.val
it = it.nexts[0]
def __len__(self):
return self.__len-1 # excluding end node
def __str__(self):
result = []
for i in reversed(xrange(len(self.__head.nexts))):
result.append([])
curr = self.__head.nexts[i]
while curr:
result[-1].append(str(curr.val))
curr = curr.nexts[i]
return "\n".join(map(lambda x: "->".join(x), result))
# wrong with greedy solution
# nums = [15, 9, 7, 10, 15, 14, 12, 2, 10, 8, 10, 13, 4, 11, 2]
# k = 5
# greedy => [[2, 4, 7], [2, 8, 9], [10, 11, 12], [10, 13, 15], [10, 14, 15]] => 24
# correct => [[2, 4, 7], [2, 8, 10], [9, 10, 11], [10, 12, 15], [13, 14, 15]] => 22
# optimized from Solution_Wrong_Greedy, using SkipList
| SkipList |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofworkv2.py | {
"start": 100684,
"end": 113195
} | class ____(
testing.AssertsExecutionResults, fixtures.TestBase
):
__sparse_driver_backend__ = True
@variation_fixture("eager_defaults", ["unspecified", "auto", True, False])
def eager_defaults_variations(self, request):
yield request.param
@variation_fixture("implicit_returning", [True, False])
def implicit_returning_variations(self, request):
yield request.param
@testing.fixture
def define_tables(
self, metadata, connection, implicit_returning_variations
):
implicit_returning = bool(implicit_returning_variations)
t = Table(
"test",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column(
"foo",
Integer,
server_default="3",
),
Column("bar", Integer, server_onupdate=FetchedValue()),
implicit_returning=implicit_returning,
)
metadata.create_all(connection)
return t
@testing.fixture
def setup_mappers(
self, define_tables, eager_defaults_variations, registry
):
class Thing:
pass
if eager_defaults_variations.unspecified:
registry.map_imperatively(Thing, define_tables)
else:
eager_defaults = (
"auto"
if eager_defaults_variations.auto
else bool(eager_defaults_variations)
)
registry.map_imperatively(
Thing, define_tables, eager_defaults=eager_defaults
)
return Thing
def test_eager_default_setting_inserts(
self,
setup_mappers,
eager_defaults_variations,
implicit_returning_variations,
connection,
):
Thing = setup_mappers
s = Session(connection)
t1, t2 = (Thing(id=1, bar=6), Thing(id=2, bar=6))
s.add_all([t1, t2])
expected_eager_defaults = eager_defaults_variations.eager_defaults or (
(
eager_defaults_variations.auto
or eager_defaults_variations.unspecified
)
and connection.dialect.insert_executemany_returning
and bool(implicit_returning_variations)
)
expect_returning = (
expected_eager_defaults
and connection.dialect.insert_returning
and bool(implicit_returning_variations)
)
with self.sql_execution_asserter(connection) as asserter:
s.flush()
asserter.assert_(
Conditional(
expect_returning,
[
Conditional(
connection.dialect.insert_executemany_returning,
[
CompiledSQL(
"INSERT INTO test (id, bar) "
"VALUES (:id, :bar) "
"RETURNING test.foo",
[
{"id": 1, "bar": 6},
{"id": 2, "bar": 6},
],
)
],
[
CompiledSQL(
"INSERT INTO test (id, bar) "
"VALUES (:id, :bar) "
"RETURNING test.foo",
{"id": 1, "bar": 6},
),
CompiledSQL(
"INSERT INTO test (id, bar) "
"VALUES (:id, :bar) "
"RETURNING test.foo",
{"id": 2, "bar": 6},
),
],
),
],
[
CompiledSQL(
"INSERT INTO test (id, bar) VALUES (:id, :bar)",
[
{"id": 1, "bar": 6},
{"id": 2, "bar": 6},
],
),
Conditional(
expected_eager_defaults and not expect_returning,
[
CompiledSQL(
"SELECT test.foo "
"FROM test WHERE test.id = :pk_1",
[{"pk_1": 1}],
),
CompiledSQL(
"SELECT test.foo "
"FROM test WHERE test.id = :pk_1",
[{"pk_1": 2}],
),
],
[],
),
],
)
)
def test_eager_default_setting_inserts_no_pks(
self,
setup_mappers,
eager_defaults_variations,
implicit_returning_variations,
connection,
):
"""test for #10453.
This is essentially a variation from test_eager_default_setting,
as a separate test because there are too many new conditions by
introducing this variant.
"""
Thing = setup_mappers
s = Session(connection)
t1, t2 = (Thing(bar=6), Thing(bar=6))
s.add_all([t1, t2])
expected_eager_defaults = eager_defaults_variations.eager_defaults or (
(
eager_defaults_variations.auto
or eager_defaults_variations.unspecified
)
and connection.dialect.insert_executemany_returning
and bool(implicit_returning_variations)
)
expect_returning = connection.dialect.insert_returning and bool(
implicit_returning_variations
)
with self.sql_execution_asserter(connection) as asserter:
s.flush()
asserter.assert_(
Conditional(
expect_returning,
[
Conditional(
connection.dialect.insert_executemany_returning,
[
Conditional(
expected_eager_defaults,
[
CompiledSQL(
"INSERT INTO test (bar) "
"VALUES (:bar) "
"RETURNING test.id, test.foo",
[
{"bar": 6},
{"bar": 6},
],
)
],
[
CompiledSQL(
"INSERT INTO test (bar) "
"VALUES (:bar) "
"RETURNING test.id",
[
{"bar": 6},
{"bar": 6},
],
)
],
)
],
[
CompiledSQL(
"INSERT INTO test (bar) "
"VALUES (:bar) "
"RETURNING test.id, test.foo",
{"bar": 6},
),
CompiledSQL(
"INSERT INTO test (bar) "
"VALUES (:bar) "
"RETURNING test.id, test.foo",
{"bar": 6},
),
],
),
],
[
CompiledSQL(
"INSERT INTO test (bar) VALUES (:bar)",
[
{"bar": 6},
],
enable_returning=False,
),
CompiledSQL(
"INSERT INTO test (bar) VALUES (:bar)",
[
{"bar": 6},
],
enable_returning=False,
),
Conditional(
expected_eager_defaults and not expect_returning,
[
CompiledSQL(
"SELECT test.foo "
"FROM test WHERE test.id = :pk_1",
[{"pk_1": 1}],
),
CompiledSQL(
"SELECT test.foo "
"FROM test WHERE test.id = :pk_1",
[{"pk_1": 2}],
),
],
[],
),
],
)
)
def test_eager_default_setting_updates(
self,
setup_mappers,
eager_defaults_variations,
implicit_returning_variations,
connection,
):
Thing = setup_mappers
s = Session(connection)
t1, t2 = (Thing(id=1, foo=5), Thing(id=2, foo=5))
s.add_all([t1, t2])
s.flush()
expected_eager_defaults = eager_defaults_variations.eager_defaults
expect_returning = (
expected_eager_defaults
and connection.dialect.update_returning
and bool(implicit_returning_variations)
)
t1.foo = 7
t2.foo = 12
with self.sql_execution_asserter(connection) as asserter:
s.flush()
asserter.assert_(
Conditional(
expect_returning,
[
CompiledSQL(
"UPDATE test SET foo=:foo WHERE test.id = :test_id "
"RETURNING test.bar",
[
{"test_id": 1, "foo": 7},
],
),
CompiledSQL(
"UPDATE test SET foo=:foo WHERE test.id = :test_id "
"RETURNING test.bar",
[
{"test_id": 2, "foo": 12},
],
),
],
[
Conditional(
expected_eager_defaults and not expect_returning,
[
CompiledSQL(
"UPDATE test SET foo=:foo "
"WHERE test.id = :test_id",
[
{"test_id": 1, "foo": 7},
{"test_id": 2, "foo": 12},
],
),
CompiledSQL(
"SELECT test.bar "
"FROM test WHERE test.id = :pk_1",
[{"pk_1": 1}],
),
CompiledSQL(
"SELECT test.bar "
"FROM test WHERE test.id = :pk_1",
[{"pk_1": 2}],
),
],
[
CompiledSQL(
"UPDATE test SET foo=:foo "
"WHERE test.id = :test_id",
[
{"test_id": 1, "foo": 7},
{"test_id": 2, "foo": 12},
],
),
],
),
],
)
)
| EagerDefaultsSettingTest |
python | numpy__numpy | numpy/f2py/tests/test_semicolon_split.py | {
"start": 329,
"end": 1056
} | class ____(util.F2PyTest):
suffix = ".pyf"
module_name = "multiline"
code = f"""
python module {module_name}
usercode '''
void foo(int* x) {{
char dummy = ';';
*x = 42;
}}
'''
interface
subroutine foo(x)
intent(c) foo
integer intent(out) :: x
end subroutine foo
end interface
end python module {module_name}
"""
def test_multiline(self):
assert self.module.foo() == 42
@pytest.mark.skipif(
platform.system() == "Darwin",
reason="Prone to error when run with numpy/f2py/tests on mac os, "
"but not when run in isolation",
)
@pytest.mark.skipif(
not IS_64BIT, reason="32-bit builds are buggy"
)
@pytest.mark.slow
| TestMultiline |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 19186,
"end": 19579
} | class ____(IntEnum):
COMPILING = 0
"""statement is present, compilation phase in progress"""
STRING_APPLIED = 1
"""statement is present, string form of the statement has been applied.
Additional processors by subclasses may still be pending.
"""
NO_STATEMENT = 2
"""compiler does not have a statement to compile, is used
for method access"""
| CompilerState |
python | sympy__sympy | sympy/logic/algorithms/lra_theory.py | {
"start": 4813,
"end": 5129
} | class ____(Exception):
"""
Raised while creating an LRASolver if non-linearity
or non-rational numbers are present.
"""
# predicates that LRASolver understands and makes use of
ALLOWED_PRED = {Q.eq, Q.gt, Q.lt, Q.le, Q.ge}
# if true ~Q.gt(x, y) implies Q.le(x, y)
HANDLE_NEGATION = True
| UnhandledInput |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 39261,
"end": 39445
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ALL", "DAY", "MONTH", "WEEK")
| SponsorsActivityPeriod |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/query.py | {
"start": 120161,
"end": 120321
} | class ____(Query[Row[Unpack[_Ts]]]):
if TYPE_CHECKING:
def tuples(self) -> Query[Tuple[Unpack[_Ts]]]: # type: ignore
...
| RowReturningQuery |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/deprecated2.py | {
"start": 406,
"end": 1283
} | class ____:
@deprecated("Don't temp me")
def method1(self) -> None: ...
@overload
@deprecated("Int is no longer supported")
def method2(self, a: int) -> None: ...
@overload
def method2(self, a: None = None) -> None: ...
def method2(self, a: int | None = None) -> None: ...
c1 = ClassC()
# This should generate an error if reportDeprecated is enabled.
c1.method1()
c1.method2()
# This should generate an error if reportDeprecated is enabled.
c1.method2(2)
@deprecated("Test")
def func1() -> None: ...
# This should generate an error if reportDeprecated is enabled.
func1()
@overload
def func2(a: str) -> None: ...
@overload
@deprecated("int no longer supported")
def func2(a: int) -> int: ...
def func2(a: str | int) -> int | None: ...
func2("hi")
# This should generate an error if reportDeprecated is enabled.
func2(3)
| ClassC |
python | neetcode-gh__leetcode | python/1299-replace-elements-with-greatest-element-on-right-side.py | {
"start": 0,
"end": 265
} | class ____:
def replaceElements(self, arr: List[int]) -> List[int]:
rightMax = -1
for i in range(len(arr) -1, -1, -1):
newMax = max(rightMax, arr[i])
arr[i] = rightMax
rightMax = newMax
return arr
| Solution |
python | python-openxml__python-docx | src/docx/styles/style.py | {
"start": 736,
"end": 5131
} | class ____(ElementProxy):
"""Base class for the various types of style object, paragraph, character, table,
and numbering.
These properties and methods are inherited by all style objects.
"""
def __init__(self, style_elm: CT_Style):
super().__init__(style_elm)
self._style_elm = style_elm
@property
def builtin(self):
"""Read-only.
|True| if this style is a built-in style. |False| indicates it is a custom
(user-defined) style. Note this value is based on the presence of a
`customStyle` attribute in the XML, not on specific knowledge of which styles
are built into Word.
"""
return not self._element.customStyle
def delete(self):
"""Remove this style definition from the document.
Note that calling this method does not remove or change the style applied to any
document content. Content items having the deleted style will be rendered using
the default style, as is any content with a style not defined in the document.
"""
self._element.delete()
self._element = None
@property
def hidden(self):
"""|True| if display of this style in the style gallery and list of recommended
styles is suppressed.
|False| otherwise. In order to be shown in the style gallery, this value must be
|False| and :attr:`.quick_style` must be |True|.
"""
return self._element.semiHidden_val
@hidden.setter
def hidden(self, value):
self._element.semiHidden_val = value
@property
def locked(self):
"""Read/write Boolean.
|True| if this style is locked. A locked style does not appear in the styles
panel or the style gallery and cannot be applied to document content. This
behavior is only active when formatting protection is turned on for the document
(via the Developer menu).
"""
return self._element.locked_val
@locked.setter
def locked(self, value):
self._element.locked_val = value
@property
def name(self):
"""The UI name of this style."""
name = self._element.name_val
if name is None:
return None
return BabelFish.internal2ui(name)
@name.setter
def name(self, value):
self._element.name_val = value
@property
def priority(self):
"""The integer sort key governing display sequence of this style in the Word UI.
|None| indicates no setting is defined, causing Word to use the default value of
0. Style name is used as a secondary sort key to resolve ordering of styles
having the same priority value.
"""
return self._element.uiPriority_val
@priority.setter
def priority(self, value):
self._element.uiPriority_val = value
@property
def quick_style(self):
"""|True| if this style should be displayed in the style gallery when
:attr:`.hidden` is |False|.
Read/write Boolean.
"""
return self._element.qFormat_val
@quick_style.setter
def quick_style(self, value):
self._element.qFormat_val = value
@property
def style_id(self) -> str:
"""The unique key name (string) for this style.
This value is subject to rewriting by Word and should generally not be changed
unless you are familiar with the internals involved.
"""
return self._style_elm.styleId
@style_id.setter
def style_id(self, value):
self._element.styleId = value
@property
def type(self):
"""Member of :ref:`WdStyleType` corresponding to the type of this style, e.g.
``WD_STYLE_TYPE.PARAGRAPH``."""
type = self._style_elm.type
if type is None:
return WD_STYLE_TYPE.PARAGRAPH
return type
@property
def unhide_when_used(self):
"""|True| if an application should make this style visible the next time it is
applied to content.
False otherwise. Note that |docx| does not automatically unhide a style having
|True| for this attribute when it is applied to content.
"""
return self._element.unhideWhenUsed_val
@unhide_when_used.setter
def unhide_when_used(self, value):
self._element.unhideWhenUsed_val = value
| BaseStyle |
python | scrapy__scrapy | tests/test_utils_defer.py | {
"start": 11398,
"end": 12434
} | class ____:
@deferred_f_from_coro_f
async def test_deferred(self):
d = Deferred()
result = maybe_deferred_to_future(d)
assert isinstance(result, Future)
d.callback(42)
future_result = await result
assert future_result == 42
@deferred_f_from_coro_f
async def test_wrapped_coroutine(self):
async def c_f() -> int:
return 42
d = deferred_from_coro(c_f())
result = maybe_deferred_to_future(d)
assert isinstance(result, Future)
future_result = await result
assert future_result == 42
@deferred_f_from_coro_f
async def test_wrapped_coroutine_asyncio(self):
async def c_f() -> int:
await asyncio.sleep(0.01)
return 42
d = deferred_from_coro(c_f())
result = maybe_deferred_to_future(d)
assert isinstance(result, Future)
future_result = await result
assert future_result == 42
@pytest.mark.only_not_asyncio
| TestMaybeDeferredToFutureAsyncio |
python | pytorch__pytorch | tools/linter/adapters/_linter/file_linter.py | {
"start": 614,
"end": 6459
} | class ____:
"""The base class that all token-based linters inherit from"""
description: str
linter_name: str
epilog: str | None = None
is_fixer: bool = True
report_column_numbers: bool = False
@abstractmethod
def _lint(self, python_file: PythonFile) -> Iterator[LintResult]:
raise NotImplementedError
def __init__(self, argv: Sequence[str] | None = None) -> None:
self.argv = argv
self.parser = ArgumentParser(
is_fixer=self.is_fixer,
description=self.description,
epilog=self.epilog,
)
self.result_shown = False
@classmethod
def run(cls) -> Never:
sys.exit(not cls().lint_all())
def lint_all(self) -> bool:
if self.args.fix and self.args.lintrunner:
raise ValueError("--fix and --lintrunner are incompatible")
success = True
for p in self.paths:
success = self._lint_file(p) and success
return self.args.lintrunner or success
@classmethod
def make_file(cls, pc: Path | str | None = None) -> PythonFile:
return PythonFile.make(cls.linter_name, pc)
@cached_property
def args(self) -> Namespace:
args = self.parser.parse_args(self.argv)
return args
@cached_property
def code(self) -> str:
return self.linter_name.upper()
@cached_property
def paths(self) -> list[Path]:
files = []
file_parts = (f for fp in self.args.files for f in fp.split(":"))
for f in file_parts:
if f.startswith("@"):
files.extend(Path(f[1:]).read_text().splitlines())
elif f != "--":
files.append(f)
return sorted(Path(f) for f in files)
def _lint_file(self, p: Path) -> bool:
if self.args.verbose:
print(p, "Reading", file=sys.stderr)
pf = self.make_file(p)
replacement, results = self._replace(pf)
if display := list(self._display(pf, results)):
print(*display, sep="\n")
if results and self.args.fix and pf.path and pf.contents != replacement:
pf.path.write_text(replacement)
return not results or self.args.fix and all(r.is_edit for r in results)
def _error(self, pf: PythonFile, result: LintResult) -> None:
"""Called on files that are unparsable"""
def _replace(self, pf: PythonFile) -> tuple[str, list[LintResult]]:
# Because of recursive replacements, we need to repeat replacing and reparsing
# from the inside out until all possible replacements are complete
previous_result_count = float("inf")
first_results = None
original = replacement = pf.contents
# pyrefly: ignore [bad-assignment]
while True:
try:
results = sorted(self._lint(pf), key=LintResult.sort_key)
except IndentationError as e:
error, (_name, lineno, column, _line) = e.args
results = [LintResult(error, lineno, column)]
self._error(pf, *results)
except ParseError as e:
results = [LintResult(str(e), *e.token.start)]
self._error(pf, *results)
for i, ri in enumerate(results):
if not ri.is_recursive:
for rj in results[i + 1 :]:
if ri.contains(rj):
rj.is_recursive = True
else:
break
first_results = first_results or results
if not results or len(results) >= previous_result_count:
break
previous_result_count = len(results)
lines = pf.lines[:]
for r in reversed(results):
if r.is_edit and not r.is_recursive:
r.apply(lines)
replacement = "".join(lines)
if not any(r.is_recursive for r in results):
break
pf = pf.with_contents(replacement)
if first_results and self.args.lintrunner:
name = f"Suggested fixes for {self.linter_name}"
msg = LintResult(name=name, original=original, replacement=replacement)
first_results.append(msg)
return replacement, first_results
def _display(self, pf: PythonFile, results: list[LintResult]) -> Iterator[str]:
"""Emit a series of human-readable strings representing the results"""
for r in results:
if self.args.lintrunner:
msg = r.as_message(code=self.code, path=str(pf.path))
yield json.dumps(msg.asdict(), sort_keys=True)
else:
if self.result_shown:
yield ""
else:
self.result_shown = True
if r.line is None:
yield f"{pf.path}: {r.name}"
else:
yield from (i.rstrip() for i in self._display_window(pf, r))
def _display_window(self, pf: PythonFile, r: LintResult) -> Iterator[str]:
"""Display a window onto the code with an error"""
if r.char is None or not self.report_column_numbers:
yield f"{pf.path}:{r.line}: {r.name}"
else:
yield f"{pf.path}:{r.line}:{r.char + 1}: {r.name}"
begin = max((r.line or 0) - ErrorLines.BEFORE, 1)
end = min(begin + ErrorLines.WINDOW, 1 + len(pf.lines))
for lineno in range(begin, end):
source_line = pf.lines[lineno - 1].rstrip()
yield f"{lineno:5} | {source_line}"
if lineno == r.line:
spaces = 8 + (r.char or 0)
carets = len(source_line) if r.char is None else (r.length or 1)
yield spaces * " " + carets * "^"
| FileLinter |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_dataprep.py | {
"start": 25093,
"end": 35182
} | class ____:
_url = "https://api.clouddataprep.com/v4/flows"
def setup_method(self):
self._flow_id = 1234567
self._create_flow_body_request = {
"name": "test_name",
"description": "Test description",
}
self._expected_copy_flow_hook_data = json.dumps(
{
"name": "",
"description": "",
"copyDatasources": False,
}
)
self._expected_run_flow_hook_data = json.dumps({})
self._expected_create_flow_hook_data = json.dumps(
{
"name": "test_name",
"description": "Test description",
}
)
with mock.patch(f"{BASEHOOK_PATCH_PATH}.get_connection") as conn:
conn.return_value.extra_dejson = EXTRA
self.hook = GoogleDataprepHook(dataprep_conn_id="dataprep_default")
@patch("airflow.providers.google.cloud.hooks.dataprep.requests.post")
def test_create_flow_should_be_called_once_with_params(self, mock_post_request):
self.hook.create_flow(body_request=self._create_flow_body_request)
mock_post_request.assert_called_once_with(
self._url,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {TOKEN}",
},
data=self._expected_create_flow_hook_data,
)
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[HTTPError(), mock.MagicMock()],
)
def test_create_flow_should_pass_after_retry(self, mock_post_request):
self.hook.create_flow(body_request=self._create_flow_body_request)
assert mock_post_request.call_count == 2
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[mock.MagicMock(), HTTPError()],
)
def test_create_flow_should_not_retry_after_success(self, mock_post_request):
self.hook.create_flow.retry.sleep = mock.Mock()
self.hook.create_flow(body_request=self._create_flow_body_request)
assert mock_post_request.call_count == 1
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[
HTTPError(),
HTTPError(),
HTTPError(),
HTTPError(),
mock.MagicMock(),
],
)
def test_create_flow_should_retry_after_four_errors(self, mock_post_request):
self.hook.create_flow.retry.sleep = mock.Mock()
self.hook.create_flow(body_request=self._create_flow_body_request)
assert mock_post_request.call_count == 5
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[HTTPError(), HTTPError(), HTTPError(), HTTPError(), HTTPError()],
)
def test_create_flow_raise_error_after_five_calls(self, mock_post_request):
self.hook.create_flow.retry.sleep = mock.Mock()
with pytest.raises(RetryError) as ctx:
self.hook.create_flow(body_request=self._create_flow_body_request)
assert "HTTPError" in str(ctx.value)
assert mock_post_request.call_count == 5
@patch("airflow.providers.google.cloud.hooks.dataprep.requests.post")
def test_copy_flow_should_be_called_once_with_params(self, mock_get_request):
self.hook.copy_flow(
flow_id=self._flow_id,
)
mock_get_request.assert_called_once_with(
f"{self._url}/{self._flow_id}/copy",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {TOKEN}",
},
data=self._expected_copy_flow_hook_data,
)
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[HTTPError(), mock.MagicMock()],
)
def test_copy_flow_should_pass_after_retry(self, mock_get_request):
self.hook.copy_flow(flow_id=self._flow_id)
assert mock_get_request.call_count == 2
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[mock.MagicMock(), HTTPError()],
)
def test_copy_flow_should_not_retry_after_success(self, mock_get_request):
self.hook.copy_flow.retry.sleep = mock.Mock()
self.hook.copy_flow(flow_id=self._flow_id)
assert mock_get_request.call_count == 1
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[
HTTPError(),
HTTPError(),
HTTPError(),
HTTPError(),
mock.MagicMock(),
],
)
def test_copy_flow_should_retry_after_four_errors(self, mock_get_request):
self.hook.copy_flow.retry.sleep = mock.Mock()
self.hook.copy_flow(flow_id=self._flow_id)
assert mock_get_request.call_count == 5
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[HTTPError(), HTTPError(), HTTPError(), HTTPError(), HTTPError()],
)
def test_copy_flow_raise_error_after_five_calls(self, mock_get_request):
self.hook.copy_flow.retry.sleep = mock.Mock()
with pytest.raises(RetryError) as ctx:
self.hook.copy_flow(flow_id=self._flow_id)
assert "HTTPError" in str(ctx.value)
assert mock_get_request.call_count == 5
@patch("airflow.providers.google.cloud.hooks.dataprep.requests.delete")
def test_delete_flow_should_be_called_once_with_params(self, mock_get_request):
self.hook.delete_flow(
flow_id=self._flow_id,
)
mock_get_request.assert_called_once_with(
f"{self._url}/{self._flow_id}",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {TOKEN}",
},
)
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.delete",
side_effect=[HTTPError(), mock.MagicMock()],
)
def test_delete_flow_should_pass_after_retry(self, mock_get_request):
self.hook.delete_flow(flow_id=self._flow_id)
assert mock_get_request.call_count == 2
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.delete",
side_effect=[mock.MagicMock(), HTTPError()],
)
def test_delete_flow_should_not_retry_after_success(self, mock_get_request):
self.hook.delete_flow.retry.sleep = mock.Mock()
self.hook.delete_flow(flow_id=self._flow_id)
assert mock_get_request.call_count == 1
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.delete",
side_effect=[
HTTPError(),
HTTPError(),
HTTPError(),
HTTPError(),
mock.MagicMock(),
],
)
def test_delete_flow_should_retry_after_four_errors(self, mock_get_request):
self.hook.delete_flow.retry.sleep = mock.Mock()
self.hook.delete_flow(flow_id=self._flow_id)
assert mock_get_request.call_count == 5
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.delete",
side_effect=[HTTPError(), HTTPError(), HTTPError(), HTTPError(), HTTPError()],
)
def test_delete_flow_raise_error_after_five_calls(self, mock_get_request):
self.hook.delete_flow.retry.sleep = mock.Mock()
with pytest.raises(RetryError) as ctx:
self.hook.delete_flow(flow_id=self._flow_id)
assert "HTTPError" in str(ctx.value)
assert mock_get_request.call_count == 5
@patch("airflow.providers.google.cloud.hooks.dataprep.requests.post")
def test_run_flow_should_be_called_once_with_params(self, mock_get_request):
self.hook.run_flow(
flow_id=self._flow_id,
body_request={},
)
mock_get_request.assert_called_once_with(
f"{self._url}/{self._flow_id}/run",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {TOKEN}",
},
data=self._expected_run_flow_hook_data,
)
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[HTTPError(), mock.MagicMock()],
)
def test_run_flow_should_pass_after_retry(self, mock_get_request):
self.hook.run_flow(
flow_id=self._flow_id,
body_request={},
)
assert mock_get_request.call_count == 2
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[mock.MagicMock(), HTTPError()],
)
def test_run_flow_should_not_retry_after_success(self, mock_get_request):
self.hook.run_flow.retry.sleep = mock.Mock()
self.hook.run_flow(
flow_id=self._flow_id,
body_request={},
)
assert mock_get_request.call_count == 1
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[
HTTPError(),
HTTPError(),
HTTPError(),
HTTPError(),
mock.MagicMock(),
],
)
def test_run_flow_should_retry_after_four_errors(self, mock_get_request):
self.hook.run_flow.retry.sleep = mock.Mock()
self.hook.run_flow(
flow_id=self._flow_id,
body_request={},
)
assert mock_get_request.call_count == 5
@patch(
"airflow.providers.google.cloud.hooks.dataprep.requests.post",
side_effect=[HTTPError(), HTTPError(), HTTPError(), HTTPError(), HTTPError()],
)
def test_run_flow_raise_error_after_five_calls(self, mock_get_request):
self.hook.run_flow.retry.sleep = mock.Mock()
with pytest.raises(RetryError) as ctx:
self.hook.run_flow(
flow_id=self._flow_id,
body_request={},
)
assert "HTTPError" in str(ctx.value)
assert mock_get_request.call_count == 5
| TestGoogleDataprepFlowPathHooks |
python | django-haystack__django-haystack | test_haystack/mocks.py | {
"start": 3844,
"end": 4666
} | class ____(MockSearchBackend):
@log_query
def search(self, query_string, **kwargs):
if kwargs.get("end_offset") and kwargs["end_offset"] > 30:
kwargs["end_offset"] = 30
result_info = super().search(query_string, **kwargs)
result_info["hits"] = 30
# Remove search results from other models.
temp_results = []
for result in result_info["results"]:
if not int(result.pk) in (9, 13, 14):
# MockSearchResult('core', 'AnotherMockModel', 9, .1)
# MockSearchResult('core', 'AnotherMockModel', 13, .1)
# MockSearchResult('core', 'NonexistentMockModel', 14, .1)
temp_results.append(result)
result_info["results"] = temp_results
return result_info
| MixedMockSearchBackend |
python | kamyu104__LeetCode-Solutions | Python/range-sum-query-immutable.py | {
"start": 60,
"end": 527
} | class ____(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.accu = [0]
for num in nums:
self.accu.append(self.accu[-1] + num),
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.accu[j + 1] - self.accu[i]
| NumArray |
python | tensorflow__tensorflow | tensorflow/python/framework/constant_op_test.py | {
"start": 1295,
"end": 4853
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.parameters(
dtypes.bfloat16,
dtypes.complex128,
dtypes.complex64,
dtypes.double,
dtypes.float16,
dtypes.float32,
dtypes.float64,
dtypes.half,
dtypes.int16,
dtypes.int32,
dtypes.int64,
dtypes.int8,
dtypes.qint16,
dtypes.qint32,
dtypes.qint8,
dtypes.quint16,
dtypes.quint8,
dtypes.uint16,
dtypes.uint32,
dtypes.uint64,
dtypes.uint8,
)
def test_convert_string_to_number(self, dtype):
with self.assertRaises(TypeError):
constant_op.constant("hello", dtype)
def _make_graph_def(self, text):
ret = graph_pb2.GraphDef()
text_format.Parse(text, ret)
return ret
def test_eager_const_xla(self):
@def_function.function(jit_compile=True)
def f_using_eagerconst(x):
graph_def = self._make_graph_def("""
node { name: 'x' op: 'Const'
attr { key: 'dtype' value { type: DT_FLOAT } }
attr { key: 'value' value { tensor {
dtype: DT_FLOAT tensor_shape {} float_val: NaN } } } }
node { name: 'const' op: '_EagerConst' input: 'x:0'
attr { key: 'T' value { type: DT_FLOAT } }}""")
x_id = importer.import_graph_def(
graph_def,
input_map={"x:0": x},
return_elements=["const"],
name="import")[0].outputs[0]
return x_id
self.assertAllClose(3.14, f_using_eagerconst(constant_op.constant(3.14)))
def test_np_array_memory_not_shared(self):
# An arbitrarily large loop number to test memory sharing
for _ in range(10000):
x = np.arange(10)
xt = constant_op.constant(x)
x[3] = 42
# Changing the input array after `xt` is created should not affect `xt`
self.assertEqual(xt.numpy()[3], 3)
def test_eager_const_grad_error(self):
@def_function.function
def f_using_eagerconst():
x = constant_op.constant(1.)
graph_def = self._make_graph_def("""
node { name: 'x' op: 'Placeholder'
attr { key: 'dtype' value { type: DT_FLOAT } }}
node { name: 'const' op: '_EagerConst' input: 'x:0'
attr { key: 'T' value { type: DT_FLOAT } }}""")
x_id = importer.import_graph_def(
graph_def,
input_map={"x:0": x},
return_elements=["const"],
name="import")[0].outputs[0]
gradients_impl.gradients(x_id, x)
return x_id
with self.assertRaisesRegex(AssertionError, "Please file a bug"):
f_using_eagerconst()
def test_eager_const_pfor(self):
@def_function.function
def f_using_eagerconst():
def vec_fn(x):
graph_def = self._make_graph_def("""
node { name: 'x' op: 'Const'
attr { key: 'dtype' value { type: DT_FLOAT } }
attr { key: 'value' value { tensor {
dtype: DT_FLOAT tensor_shape {} float_val: 3.14 } } } }
node { name: 'const' op: '_EagerConst' input: 'x:0'
attr { key: 'T' value { type: DT_FLOAT } }}""")
return importer.import_graph_def(
graph_def,
input_map={"x:0": x},
return_elements=["const"],
name="import")[0].outputs[0]
return control_flow_ops.vectorized_map(
vec_fn, constant_op.constant([1., 2.]), fallback_to_while_loop=False)
self.assertAllClose([1., 2.], f_using_eagerconst())
if __name__ == "__main__":
ops.enable_eager_execution()
test.main()
| ConstantOpTest |
python | astropy__astropy | astropy/table/row.py | {
"start": 236,
"end": 7181
} | class ____:
"""A class to represent one row of a Table object.
A Row object is returned when a Table object is indexed with an integer
or when iterating over a table::
>>> from astropy.table import Table
>>> table = Table([(1, 2), (3, 4)], names=('a', 'b'),
... dtype=('int32', 'int32'))
>>> row = table[1]
>>> row
<Row index=1>
a b
int32 int32
----- -----
2 4
>>> row['a']
np.int32(2)
>>> row[1]
np.int32(4)
"""
def __init__(self, table, index):
# Ensure that the row index is a valid index (int)
index = operator_index(index)
n = len(table)
if index < -n or index >= n:
raise IndexError(
f"index {index} out of range for table with length {len(table)}"
)
# Finally, ensure the index is positive [#8422] and set Row attributes
self._index = index % n
self._table = table
def __getitem__(self, item):
try:
# Try the most common use case of accessing a single column in the Row.
# Bypass the TableColumns __getitem__ since that does more testing
# and allows a list of tuple or str, which is not the right thing here.
out = OrderedDict.__getitem__(self._table.columns, item)[self._index]
except (KeyError, TypeError):
if self._table._is_list_or_tuple_of_str(item):
cols = [self._table[name] for name in item]
out = self._table.__class__(cols, copy=False)[self._index]
elif isinstance(item, slice):
# https://github.com/astropy/astropy/issues/14007
out = tuple(self.values())[item]
else:
# This is only to raise an exception
out = self._table.columns[item][self._index]
return out
def __setitem__(self, item, val):
if self._table._is_list_or_tuple_of_str(item):
self._table._set_row(self._index, colnames=item, vals=val)
else:
self._table.columns[item][self._index] = val
def _ipython_key_completions_(self):
return self.colnames
def __eq__(self, other):
if self._table.masked:
# Sent bug report to numpy-discussion group on 2012-Oct-21, subject:
# "Comparing rows in a structured masked array raises exception"
# No response, so this is still unresolved.
raise ValueError(
"Unable to compare rows for masked table due to numpy.ma bug"
)
return self.as_void() == other
def __ne__(self, other):
if self._table.masked:
raise ValueError(
"Unable to compare rows for masked table due to numpy.ma bug"
)
return self.as_void() != other
def __array__(self, dtype=None, copy=COPY_IF_NEEDED):
"""Support converting Row to np.array via np.array(table).
Coercion to a different dtype via np.array(table, dtype) is not
supported and will raise a ValueError.
If the parent table is masked then the mask information is dropped.
"""
if dtype is not None:
raise ValueError("Datatype coercion is not allowed")
return np.array(self.as_void(), copy=copy)
def __len__(self):
return len(self._table.columns)
def __iter__(self):
index = self._index
for col in self._table.columns.values():
yield col[index]
def get(self, key, default=None, /):
"""Return the value for key if key is in the columns, else default.
Parameters
----------
key : `str`, positional-only
The name of the column to look for.
default : `object`, optional, positional-only
The value to return if the ``key`` is not among the columns.
Returns
-------
`object`
The value in the ``key`` column of the row if present,
``default`` otherwise.
Examples
--------
>>> from astropy.table import Table
>>> t = Table({"a": [2., 3., 5.], "b": [7., 11., 13.]})
>>> t[0].get("a")
np.float64(2.0)
>>> t[1].get("b", 0.)
np.float64(11.0)
>>> t[2].get("c", 0.)
0.0
"""
return self[key] if key in self._table.columns else default
def keys(self):
return self._table.columns.keys()
def values(self):
return self.__iter__()
@property
def table(self):
return self._table
@property
def index(self):
return self._index
def as_void(self):
"""
Returns a *read-only* copy of the row values in the form of np.void or
np.ma.mvoid objects. This corresponds to the object types returned for
row indexing of a pure numpy structured array or masked array. This
method is slow and its use is discouraged when possible.
Returns
-------
void_row : ``numpy.void`` or ``numpy.ma.mvoid``
Copy of row values.
``numpy.void`` if unmasked, ``numpy.ma.mvoid`` else.
"""
index = self._index
cols = self._table.columns.values()
vals = tuple(np.asarray(col)[index] for col in cols)
if self._table.masked:
mask = tuple(
col.mask[index] if hasattr(col, "mask") else False for col in cols
)
void_row = np.ma.array([vals], mask=[mask], dtype=self.dtype)[0]
else:
void_row = np.array([vals], dtype=self.dtype)[0]
return void_row
@property
def meta(self):
return self._table.meta
@property
def columns(self):
return self._table.columns
@property
def colnames(self):
return self._table.colnames
@property
def dtype(self):
return self._table.dtype
def _base_repr_(self, html=False):
"""
Display row as a single-line table but with appropriate header line.
"""
index = self.index if (self.index >= 0) else self.index + len(self._table)
table = self._table[index : index + 1]
descr_vals = [self.__class__.__name__, f"index={self.index}"]
if table.masked:
descr_vals.append("masked=True")
return table._base_repr_(
html, descr_vals, max_width=-1, tableid=f"table{id(self._table)}"
)
def _repr_html_(self):
return self._base_repr_(html=True)
def __repr__(self):
return self._base_repr_(html=False)
def __str__(self):
index = self.index if (self.index >= 0) else self.index + len(self._table)
return "\n".join(self.table[index : index + 1].pformat(max_width=-1))
def __bytes__(self):
return str(self).encode("utf-8")
collections.abc.Sequence.register(Row)
| Row |
python | GoogleCloudPlatform__python-docs-samples | appengine/flexible/django_cloudsql/polls/test_polls.py | {
"start": 632,
"end": 832
} | class ____(TestCase):
def test_index_view(self):
response = self.client.get("/")
assert response.status_code == 200
assert "Hello, world" in str(response.content)
| PollViewTests |
python | keras-team__keras | keras/src/layers/pooling/max_pooling2d.py | {
"start": 181,
"end": 4128
} | class ____(BasePooling):
"""Max pooling operation for 2D spatial data.
Downsamples the input along its spatial dimensions (height and width)
by taking the maximum value over an input window
(of size defined by `pool_size`) for each channel of the input.
The window is shifted by `strides` along each dimension.
The resulting output when using the `"valid"` padding option has a spatial
shape (number of rows or columns) of:
`output_shape = math.floor((input_shape - pool_size) / strides) + 1`
(when `input_shape >= pool_size`)
The resulting output shape when using the `"same"` padding option is:
`output_shape = math.floor((input_shape - 1) / strides) + 1`
Args:
pool_size: int or tuple of 2 integers, factors by which to downscale
(dim1, dim2). If only one integer is specified, the same
window length will be used for all dimensions.
strides: int or tuple of 2 integers, or None. Strides values. If None,
it will default to `pool_size`. If only one int is specified, the
same stride size will be used for all dimensions.
padding: string, either `"valid"` or `"same"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding evenly to
the left/right or up/down of the input such that output has the same
height/width dimension as the input.
data_format: string, either `"channels_last"` or `"channels_first"`.
The ordering of the dimensions in the inputs. `"channels_last"`
corresponds to inputs with shape `(batch, height, width, channels)`
while `"channels_first"` corresponds to inputs with shape
`(batch, channels, height, width)`. It defaults to the
`image_data_format` value found in your Keras config file at
`~/.keras/keras.json`. If you never set it, then it will be
`"channels_last"`.
Input shape:
- If `data_format="channels_last"`:
4D tensor with shape `(batch_size, height, width, channels)`.
- If `data_format="channels_first"`:
4D tensor with shape `(batch_size, channels, height, width)`.
Output shape:
- If `data_format="channels_last"`:
4D tensor with shape
`(batch_size, pooled_height, pooled_width, channels)`.
- If `data_format="channels_first"`:
4D tensor with shape
`(batch_size, channels, pooled_height, pooled_width)`.
Examples:
`strides=(1, 1)` and `padding="valid"`:
>>> x = np.array([[1., 2., 3.],
... [4., 5., 6.],
... [7., 8., 9.]])
>>> x = np.reshape(x, [1, 3, 3, 1])
>>> max_pool_2d = keras.layers.MaxPooling2D(pool_size=(2, 2),
... strides=(1, 1), padding="valid")
>>> max_pool_2d(x)
`strides=(2, 2)` and `padding="valid"`:
>>> x = np.array([[1., 2., 3., 4.],
... [5., 6., 7., 8.],
... [9., 10., 11., 12.]])
>>> x = np.reshape(x, [1, 3, 4, 1])
>>> max_pool_2d = keras.layers.MaxPooling2D(pool_size=(2, 2),
... strides=(2, 2), padding="valid")
>>> max_pool_2d(x)
`stride=(1, 1)` and `padding="same"`:
>>> x = np.array([[1., 2., 3.],
... [4., 5., 6.],
... [7., 8., 9.]])
>>> x = np.reshape(x, [1, 3, 3, 1])
>>> max_pool_2d = keras.layers.MaxPooling2D(pool_size=(2, 2),
... strides=(1, 1), padding="same")
>>> max_pool_2d(x)
"""
def __init__(
self,
pool_size=(2, 2),
strides=None,
padding="valid",
data_format=None,
name=None,
**kwargs,
):
super().__init__(
pool_size,
strides,
pool_dimensions=2,
pool_mode="max",
padding=padding,
data_format=data_format,
name=name,
**kwargs,
)
| MaxPooling2D |
python | requests__requests-oauthlib | tests/examples/base.py | {
"start": 2985,
"end": 4708
} | class ____():
def setUp(self):
super().setUp()
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
self.driver = webdriver.Chrome(options=options)
self.user_username = os.environ.get("AUTH0_USERNAME")
self.user_password = os.environ.get("AUTH0_PASSWORD")
if not self.user_username or not self.user_password:
self.skipTest("auth0 is not configured properly")
def tearDown(self):
super().tearDown()
self.driver.quit()
def authorize_auth0(self, authorize_url, expected_redirect_uri):
"""
Start browser based on an Auth0 authorize url, and log user with user and password.
Returns once login journey ends with a redirection to ``expected_redirect_uri``.
Note this is for Auth0 login dialog specifically.
:param authorize_url: Full Authorize URL of Identity Provider
:type authorize_url: string
:param expected_redirect_uri: Expected ``redirect_uri``. Used only to check end of the authorize journey.
:type expected_redirect_uri: string
"""
self.driver.get(authorize_url)
username = self.driver.find_element(By.ID, "username")
password = self.driver.find_element(By.ID, "password")
wait = WebDriverWait(self.driver, timeout=2)
wait.until(lambda d : username.is_displayed())
wait.until(lambda d : password.is_displayed())
username.clear()
username.send_keys(self.user_username)
password.send_keys(self.user_password)
username.send_keys(Keys.RETURN)
wait.until(EC.url_contains(expected_redirect_uri))
return self.driver.current_url
| Browser |
python | tensorflow__tensorflow | tensorflow/core/function/transform/transform_test.py | {
"start": 2398,
"end": 15837
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
dict(
testcase_name="transform",
transform_fn=add_to_multiply,
mlir_pipeline=None),
dict(
testcase_name="mlir_pipeline",
transform_fn=None,
mlir_pipeline="test-pass"),
dict(
testcase_name="transform_and_mlir_pipeline",
transform_fn=add_to_multiply,
mlir_pipeline="test-pass"),
dict(
testcase_name="transform_list",
transform_fn=[add_to_multiply],
mlir_pipeline=None),
dict(
testcase_name="mlir_pipeline_list",
transform_fn=None,
mlir_pipeline=["test-pass"]),
dict(
testcase_name="transform_list_and_mlir_pipeline_list",
transform_fn=[add_to_multiply],
mlir_pipeline=["test-pass"]),
)
@test_util.run_v2_only
def test_concrete_function_with(self, transform_fn, mlir_pipeline):
@def_function.function(input_signature=[
tensor_spec.TensorSpec((), dtype=dtypes.float32),
tensor_spec.TensorSpec((), dtype=dtypes.float32)
])
def f(x, y):
return math_ops.add(x, y, name="x_plus_y")
# transfrom f(x, y): x + y -> f(x, y): x * y
f = transform.transform_function(
f, transform_fn=transform_fn, mlir_pipeline=mlir_pipeline)
one = constant_op.constant(1.0)
self.assertEqual(f(one, one), 1.0)
@def_function.function
def f2(x, y):
z = f(x, y)
return math_ops.add(z, 10.0)
self.assertEqual(f2(one, one), 11.0)
@def_function.function
def f_g(x, y):
z = f(x, y)
dz_dx, dz_dy = gradients_impl.gradients(z, [x, y])
return math_ops.add(dz_dx, dz_dy)
self.assertEqual(
f_g(constant_op.constant(2.0), constant_op.constant(3.0)), 5.0)
@test_util.run_v2_only
def test_transform_with_keywords(self):
@def_function.function
def f(x, y):
return math_ops.add(x, y, name="x_plus_y")
one = constant_op.constant(1.0)
# transfrom f(x, y): x + y -> f(x, y): x * y
g = transform.transform_function(
f,
inputs=[one],
kw_inputs={"y": one},
transform_fn=add_to_multiply,
mlir_pipeline="test-pass")
self.assertEqual(g(one, one), 1.0)
self.assertEqual(g(one, y=one), 1.0)
self.assertEqual(g(x=one, y=one), 1.0)
@test_util.run_v2_only
def test_transform_with_keywords_only(self):
@def_function.function
def f(x, y):
return math_ops.add(x, y, name="x_plus_y")
one = constant_op.constant(1.0)
# transfrom f(x, y): x + y -> f(x, y): x * y
g = transform.transform_function(
f,
inputs=None,
kw_inputs={"x": one, "y": one},
transform_fn=add_to_multiply,
mlir_pipeline="test-pass")
self.assertEqual(g(one, one), 1.0)
self.assertEqual(g(one, y=one), 1.0)
self.assertEqual(g(x=one, y=one), 1.0)
@test_util.run_v2_only
def test_function_spec(self):
@def_function.function
def f(x, y):
return math_ops.add(x, y, name="x_plus_y")
args = [1, 1]
self.assertEqual(f(*args), 2)
updated_f = transform.transform_function(
f, inputs=args, transform_fn=add_to_multiply)
self.assertEqual(updated_f(*args), 1)
self.assertSequenceAlmostEqual(
f.get_concrete_function(
*args).pretty_printed_signature().split("\n")[1:],
updated_f.pretty_printed_signature().split("\n")[1:])
@test_util.run_v2_only
def test_transform_with_custom_gradients(self):
@custom_gradient.custom_gradient
def add(x, y):
e = math_ops.add(x, y, name="x_plus_y")
# custom gradient that returns gradients of x * y instead of x + y
def grad(upstream):
dz_dx = y
dz_dy = x
return upstream * dz_dx, upstream * dz_dy
return e, grad
@def_function.function
def f(x, y):
return add(x, y)
one = constant_op.constant(1.0)
f = transform.transform_function(
f, inputs=[one, one], transform_fn=add_to_multiply)
self.assertEqual(f(one, one), 1.0)
@def_function.function
def f_g(x, y):
z = f(x, y)
dz_dx, dz_dy = gradients_impl.gradients(z, [x, y])
return math_ops.add(dz_dx, dz_dy)
self.assertEqual(
f_g(constant_op.constant(2.0), constant_op.constant(3.0)), 5.0)
@test_util.run_v2_only
def test_transform_with_nested_function(self):
@def_function.function
def f(x, z):
@def_function.function
def add():
i = constant_op.constant(1.0)
c = lambda i: math_ops.less(i, 3.0)
b = lambda i: (math_ops.add(i, z, name="x_plus_y"))
i = while_loop.while_loop_v2(c, b, [i])
return i
y = add()
return math_ops.add(x, y, name="x_plus_y")
one = constant_op.constant(1.0)
two = constant_op.constant(2.0)
inputs = [one, two]
# By default only `f` is transformed.
updated_f = transform.transform_function(
f, inputs=inputs, transform_fn=add_to_multiply)
self.assertEqual(updated_f(*inputs), 3.0) # 1 x (1 + 2) = 3
# Extract all the functions in `f`'s library that we want to transform.
nested_transforms = {}
gdef = f.get_concrete_function(*inputs).graph.as_graph_def()
for fdef in gdef.library.function:
nested_transforms[fdef.signature.name] = add_to_multiply
# Transform `f` and all of its library functions.
updated_f = transform.transform_function(
f,
inputs=inputs,
transform_fn=add_to_multiply,
nested_fn_transforms=nested_transforms)
self.assertEqual(updated_f(*inputs), 4.0) # 1 x (1 x 2 x 2) = 4
@parameterized.named_parameters(
dict(
testcase_name="fn",
transform_fn=add_to_multiply),
dict(
testcase_name="mlir",
mlir_pipeline="test-pass"),
dict(
testcase_name="fn_and_mlir",
transform_fn=add_to_multiply,
mlir_pipeline="test-pass"),
)
@test_util.run_v2_only
def test_nested_python_function_transform_with(self,
transform_fn=None,
mlir_pipeline=None):
@def_function.function
def f(x, y):
def inner_add():
return math_ops.add(x, y, name="x_plus_y")
return inner_add()
inputs = [1.0, 2.0]
self.assertEqual(f(*inputs), 3.0) # 1 + 2 = 3
# Transform `f`.
updated_f = transform.transform_function(
f,
inputs=inputs,
transform_fn=transform_fn,
mlir_pipeline=mlir_pipeline)
# Nested Python functions should be transformed.
self.assertEqual(updated_f(*inputs), 2.0) # 1 x 2 = 2
@parameterized.named_parameters(
dict(
testcase_name="fn_and_nested_fn",
transform_fn=add_to_multiply,
nested_fn=True),
dict(
testcase_name="fn_and_nested_mlir",
transform_fn=add_to_multiply,
nested_mlir=True),
dict(
testcase_name="mlir_and_nested_fn",
mlir_pipeline="test-pass",
nested_fn=True),
dict(
testcase_name="mlir_and_nested_mlir",
mlir_pipeline="test-pass",
nested_mlir=True),
dict(
testcase_name="mlir_fn_and_nested_mlir_fn",
transform_fn=add_to_multiply,
mlir_pipeline="test-pass",
nested_fn=True,
nested_mlir=True),
)
@test_util.run_v2_only
def test_nested_transform_with(self,
transform_fn=None,
mlir_pipeline=None,
nested_fn=False,
nested_mlir=False):
@def_function.function
def f(x, y, z):
@def_function.function
def inner_add():
return math_ops.add(y, z, name="x_plus_y")
return math_ops.add(x, inner_add(), name="x_plus_y")
# 1, 2, 4 are picked so the following combinations create different results.
# 1 + (2 + 4) = 7
# 1 + (2 * 4) = 9
# 1 * (2 + 4) = 6
# 1 * (2 * 4) = 8
inputs = [1.0, 2.0, 4.0]
self.assertEqual(f(*inputs), 7.0) # 1 + (2 + 4) = 7
# Extract all the functions in `f`'s library that we want to transform.
nested_fn_transforms = {}
nested_mlir_transforms = {}
cf = f.get_concrete_function(*inputs)
gdef = cf.graph.as_graph_def()
for fdef in gdef.library.function:
fdef_name = fdef.signature.name
if nested_fn:
nested_fn_transforms[fdef_name] = add_to_multiply
if nested_mlir:
nested_mlir_transforms[fdef_name] = "test-pass"
# Transform `f` and all of its library functions.
updated_f = transform.transform_function(
f,
inputs=inputs,
transform_fn=transform_fn,
mlir_pipeline=mlir_pipeline,
nested_fn_transforms=nested_fn_transforms,
nested_mlir_transforms=nested_mlir_transforms)
self.assertEqual(updated_f(*inputs), 8.0) # 1 x (2 x 4) = 8
@parameterized.named_parameters(
dict(
testcase_name="fn_and_nested_fn",
transform_fn=add_to_multiply,
nested_fn=True),
dict(
testcase_name="fn_and_nested_mlir",
transform_fn=add_to_multiply,
nested_mlir=True),
dict(
testcase_name="mlir_and_nested_fn",
mlir_pipeline="test-pass",
nested_fn=True),
dict(
testcase_name="mlir_and_nested_mlir",
mlir_pipeline="test-pass",
nested_mlir=True),
dict(
testcase_name="mlir_fn_and_nested_mlir_fn",
transform_fn=add_to_multiply,
mlir_pipeline="test-pass",
nested_fn=True,
nested_mlir=True),
)
@test_util.run_v2_only
def test_nested_transform_in_tf_function_with(self,
transform_fn=None,
mlir_pipeline=None,
nested_fn=False,
nested_mlir=False):
@def_function.function
def g(x, y, z):
@def_function.function
def f(x, y, z):
@def_function.function
def inner_add():
return math_ops.add(y, z, name="x_plus_y")
return math_ops.add(x, inner_add(), name="x_plus_y")
nested_fn_transforms = {}
nested_mlir_transforms = {}
cf = f.get_concrete_function(*inputs)
gdef = cf.graph.as_graph_def()
for fdef in gdef.library.function:
fdef_name = fdef.signature.name
if nested_fn:
nested_fn_transforms[fdef_name] = add_to_multiply
if nested_mlir:
nested_mlir_transforms[fdef_name] = "test-pass"
updated_f = transform.transform_function(
f,
inputs=inputs,
transform_fn=transform_fn,
mlir_pipeline=mlir_pipeline,
nested_fn_transforms=nested_fn_transforms,
nested_mlir_transforms=nested_mlir_transforms)
return updated_f(x, y, z)
inputs = [1.0, 2.0, 4.0]
graph_def = g.get_concrete_function(*inputs).graph.as_graph_def()
# Confirm all "AddV2" nodes in the library functions of graph_def are
# transformed to "Mul".
ops = collections.Counter()
for fdef in graph_def.library.function:
for node in fdef.node_def:
ops[node.op] += 1
self.assertNotIn("AddV2", ops)
self.assertEqual(ops["Mul"], 2)
@test_util.run_v2_only
def test_save_transform_for_all_signatures(self):
m = Model()
# Originally f does addition
self.assertEqual(
m.f(
constant_op.constant(1, dtypes.int32),
constant_op.constant(2, dtypes.int32),
constant_op.constant(False, dtypes.bool)), 3)
self.assertEqual(
m.f(
constant_op.constant(1, dtypes.int32),
constant_op.constant(2, dtypes.int32),
constant_op.constant(True, dtypes.bool)), 5)
# Transform every input signature of f to a multiply
m.f = apply_transform(m.f, add_to_multiply)
# Validate arbitrary signatures.
self.assertEqual(
m.f(
constant_op.constant(1, dtypes.int32),
constant_op.constant(2, dtypes.int32),
constant_op.constant(False, dtypes.bool)), 2)
self.assertEqual(
m.f(
constant_op.constant(1, dtypes.int32),
constant_op.constant(2, dtypes.int32),
constant_op.constant(True, dtypes.bool)), 4)
self.assertEqual(
m.f(
constant_op.constant(1.0, dtypes.float32),
constant_op.constant(2.0, dtypes.float32),
constant_op.constant(False, dtypes.bool)), (2.0))
# Save and restore the model.
save_lib.save(m, "/tmp/testing_model")
m_loaded = load_lib.load("/tmp/testing_model")
# Validate the restored model.
self.assertEqual(
m_loaded.f(
constant_op.constant(1, dtypes.int32),
constant_op.constant(2, dtypes.int32),
constant_op.constant(False, dtypes.bool)), 2)
self.assertEqual(
m_loaded.f(
constant_op.constant(1.1, dtypes.float32),
constant_op.constant(2.0, dtypes.float32),
constant_op.constant(True, dtypes.bool)), (4.2))
if __name__ == "__main__":
test_pass.RegisterTestPass()
test.main()
| TransformTest |
python | PrefectHQ__prefect | src/prefect/settings/profiles.py | {
"start": 1448,
"end": 3378
} | class ____(BaseModel):
"""A user profile containing settings."""
model_config: ClassVar[ConfigDict] = ConfigDict(
extra="ignore", arbitrary_types_allowed=True
)
name: str
settings: Annotated[dict[Setting, Any], BeforeValidator(_cast_settings)] = Field(
default_factory=dict
)
source: Optional[Path] = None
def to_environment_variables(self) -> dict[str, str]:
"""Convert the profile settings to a dictionary of environment variables."""
return {
setting.name: str(value)
for setting, value in self.settings.items()
if value is not None
}
def validate_settings(self) -> None:
"""
Validate all settings in this profile by creating a partial Settings object
with the nested structure properly constructed using accessor paths.
"""
if not self.settings:
return
nested_settings: dict[str, Any] = {}
for setting, value in self.settings.items():
set_in_dict(nested_settings, setting.accessor, value)
try:
Settings.model_validate(nested_settings)
except ValidationError as e:
errors: list[tuple[Setting, ValidationError]] = []
for error in e.errors():
error_path = ".".join(str(loc) for loc in error["loc"])
for setting in self.settings.keys():
if setting.accessor == error_path:
errors.append(
(
setting,
ValidationError.from_exception_data(
"ValidationError", [error]
),
)
)
break
if errors:
raise ProfileSettingsValidationError(errors)
| Profile |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 15026,
"end": 16242
} | class ____(nn.Module):
def __init__(self, config, layer_idx=None, is_cross_attention=False):
super().__init__()
self.self = EvollaSaProtSelfAttention(config, layer_idx=layer_idx, is_cross_attention=is_cross_attention)
self.output = EvollaSaProtSelfOutput(config)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(
self,
hidden_states,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
**kwargs: Unpack[TransformersKwargs],
):
hidden_states_ln = self.LayerNorm(hidden_states)
attn_output, _ = self.self(
hidden_states_ln,
attention_mask=attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
**kwargs,
)
attn_output = self.output(attn_output, hidden_states)
return attn_output
def gelu(x):
"""
This is the gelu implementation from the original EVOLLA_SA_PROT repo. Using F.gelu yields subtly wrong results.
"""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
| EvollaSaProtAttention |
python | astropy__astropy | astropy/io/ascii/fastbasic.py | {
"start": 10381,
"end": 12634
} | class ____(FastBasic):
"""
A faster version of the :class:`CommentedHeader` reader, which looks for
column names in a commented line. ``header_start`` denotes the index of
the header line among all commented lines and is 0 by default.
"""
_format_name = "fast_commented_header"
_description = "Columns name in a commented line using the fast C engine"
_fast = True
def __init__(self, **kwargs):
super().__init__({}, **kwargs)
# Mimic CommentedHeader's behavior in which data_start
# is relative to header_start if unspecified; see #2692
if "data_start" not in kwargs:
self.data_start = 0
def make_table(self, data, comments):
"""
Actually make the output table give the data and comments. This is
slightly different from the base FastBasic method in the way comments
are handled.
"""
meta = {}
if comments:
idx = self.header_start
if idx < 0:
idx = len(comments) + idx
meta["comments"] = comments[:idx] + comments[idx + 1 :]
if not meta["comments"]:
del meta["comments"]
names = core._deduplicate_names(self.engine.get_names())
return Table(data, names=names, meta=meta)
def _read_header(self):
tmp = self.engine.source
commented_lines = []
for line in tmp.splitlines():
line = line.lstrip()
if line and line[0] == self.comment: # line begins with a comment
commented_lines.append(line[1:])
if len(commented_lines) == self.header_start + 1:
break
if len(commented_lines) <= self.header_start:
raise cparser.CParserError("not enough commented lines")
self.engine.setup_tokenizer([commented_lines[self.header_start]])
self.engine.header_start = 0
self.engine.read_header()
self.engine.setup_tokenizer(tmp)
def write(self, table, output):
"""
Override the default writing behavior in `FastBasic` so
that column names are commented.
"""
self._write(table, output, {}, header_output="comment")
| FastCommentedHeader |
python | tensorflow__tensorflow | tensorflow/compiler/tests/sparse_to_dense_op_test.py | {
"start": 1533,
"end": 4615
} | class ____(xla_test.XLATestCase):
def testInt(self):
with self.session(), self.test_scope():
tf_ans = _SparseToDense([1, 3], [5], 1, 0)
np_ans = np.array([0, 1, 0, 1, 0]).astype(np.int32)
self.assertAllClose(np_ans, tf_ans)
def testFloat(self):
with self.session(), self.test_scope():
tf_ans = _SparseToDense([1, 3], [5], 1.0, 0.0)
np_ans = np.array([0, 1, 0, 1, 0]).astype(np.float32)
self.assertAllClose(np_ans, tf_ans)
def testSetValue(self):
with self.session(), self.test_scope():
tf_ans = _SparseToDense([1, 3], [5], [1, 2], -1)
np_ans = np.array([-1, 1, -1, 2, -1]).astype(np.int32)
self.assertAllClose(np_ans, tf_ans)
def testSetSingleValue(self):
with self.session(), self.test_scope():
tf_ans = _SparseToDense([1, 3], [5], 1, -1)
np_ans = np.array([-1, 1, -1, 1, -1]).astype(np.int32)
self.assertAllClose(np_ans, tf_ans)
def test2d(self):
# pylint: disable=bad-whitespace
with self.session(), self.test_scope():
tf_ans = _SparseToDense([[1, 3], [2, 0]], [3, 4], 1, -1)
np_ans = np.array([[-1, -1, -1, -1],
[-1, -1, -1, 1],
[ 1, -1, -1, -1]]).astype(np.int32)
self.assertAllClose(np_ans, tf_ans)
def testZeroDefault(self):
with self.session():
x = sparse_ops.sparse_to_dense(2, [4], 7).eval()
self.assertAllEqual(x, [0, 0, 7, 0])
def test3d(self):
with self.session(), self.test_scope():
tf_ans = _SparseToDense([[1, 3, 0], [2, 0, 1]], [3, 4, 2], 1, -1)
np_ans = np.ones((3, 4, 2), dtype=np.int32) * -1
np_ans[1, 3, 0] = 1
np_ans[2, 0, 1] = 1
self.assertAllClose(np_ans, tf_ans)
def testDegenerateIndexMatrix(self):
with self.session(), self.test_scope():
tf_ans = _SparseToDense([[2], [3], [4], [5], [6], [7], [8], [9]], [10],
[1, 2, 3, 4, 5, 6, 7, 8], -1)
self.assertAllClose([-1, -1, 1, 2, 3, 4, 5, 6, 7, 8], tf_ans)
def testBadShape(self):
with self.session(), self.test_scope():
with self.assertRaisesWithPredicateMatch(ValueError, "must be rank 1"):
_SparseToDense([1, 3], [[5], [3]], 1, -1)
@test_util.disable_mlir_bridge("Error handling")
def testBadValue(self):
with self.session(), self.test_scope():
with self.assertRaisesOpError(
r"sparse_values has incorrect shape \[2,1\], "
r"should be \[\] or \[2\]"):
_SparseToDense([1, 3], [5], [[5], [3]], -1)
@test_util.disable_mlir_bridge("Error handling")
def testBadNumValues(self):
with self.session(), self.test_scope():
with self.assertRaisesOpError(
r"sparse_values has incorrect shape \[3\], should be \[\] or \[2\]"):
_SparseToDense([1, 3], [5], [1, 2, 3], -1)
@test_util.disable_mlir_bridge("Error handling")
def testBadDefault(self):
with self.session(), self.test_scope():
with self.assertRaisesOpError("default_value should be a scalar"):
_SparseToDense([1, 3], [5], [1, 2], [0])
if __name__ == "__main__":
test.main()
| SparseToDenseTest |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 139227,
"end": 140500
} | class ____(Response):
"""
Response of events.next_debug_image_sample endpoint.
"""
_service = "events"
_action = "next_debug_image_sample"
_version = "2.20"
_schema = {
"$ref": "#/definitions/debug_image_sample_response",
"definitions": {
"debug_image_sample_response": {
"properties": {
"event": {
"description": "Debug image event",
"type": ["object", "null"],
},
"max_iteration": {
"description": "maximal valid iteration for the variant",
"type": ["integer", "null"],
},
"min_iteration": {
"description": "minimal valid iteration for the variant",
"type": ["integer", "null"],
},
"scroll_id": {
"description": "Scroll ID to pass to the next calls to get_debug_image_sample or next_debug_image_sample",
"type": ["string", "null"],
},
},
"type": "object",
}
},
}
| NextDebugImageSampleResponse |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_bitcoin_address.py | {
"start": 1921,
"end": 4681
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid Bitcoin addresses."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_valid": [
"1BoatSLRHtKNngkdXEeobR76b53LETtpyT",
"n2nzi7xDTrMVK9stGpbK3BtrpBCJfH7LRQ",
"3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC",
"bc1qxneu85dnhx33asv8da45x55qyeu44ek9h3vngx",
],
"some_other": [
"1BoatSLRHtKNngkdXEeobR76b53LETtpyT",
"n2nzi7xDTrMVK9stGpbK3BtrpBCJfH7LRQ",
"3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC",
"bc1qxneu85dnhx33asv8da45x55qyeu44ek9h3vngxdsare",
],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "all_valid"},
"out": {
"success": True,
},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "some_other", "mostly": 1},
"out": {
"success": False,
},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_bitcoin_address"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental",
"tags": [
"hackathon-22",
"experimental",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@szecsip", # Don't forget to add your github handle here!
],
"requirements": ["coinaddrvalidator"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidBitcoinAddress().print_diagnostic_checklist()
| ExpectColumnValuesToBeValidBitcoinAddress |
python | Textualize__textual | docs/examples/widgets/data_table_sort.py | {
"start": 862,
"end": 3234
} | class ____(App):
BINDINGS = [
("a", "sort_by_average_time", "Sort By Average Time"),
("n", "sort_by_last_name", "Sort By Last Name"),
("c", "sort_by_country", "Sort By Country"),
("d", "sort_by_columns", "Sort By Columns (Only)"),
]
current_sorts: set = set()
def compose(self) -> ComposeResult:
yield DataTable()
yield Footer()
def on_mount(self) -> None:
table = self.query_one(DataTable)
for col in ROWS[0]:
table.add_column(col, key=col)
table.add_rows(ROWS[1:])
def sort_reverse(self, sort_type: str):
"""Determine if `sort_type` is ascending or descending."""
reverse = sort_type in self.current_sorts
if reverse:
self.current_sorts.remove(sort_type)
else:
self.current_sorts.add(sort_type)
return reverse
def action_sort_by_average_time(self) -> None:
"""Sort DataTable by average of times (via a function) and
passing of column data through positional arguments."""
def sort_by_average_time_then_last_name(row_data):
name, *scores = row_data
return (sum(scores) / len(scores), name.split()[-1])
table = self.query_one(DataTable)
table.sort(
"swimmer",
"time 1",
"time 2",
key=sort_by_average_time_then_last_name,
reverse=self.sort_reverse("time"),
)
def action_sort_by_last_name(self) -> None:
"""Sort DataTable by last name of swimmer (via a lambda)."""
table = self.query_one(DataTable)
table.sort(
"swimmer",
key=lambda swimmer: swimmer.split()[-1],
reverse=self.sort_reverse("swimmer"),
)
def action_sort_by_country(self) -> None:
"""Sort DataTable by country which is a `Rich.Text` object."""
table = self.query_one(DataTable)
table.sort(
"country",
key=lambda country: country.plain,
reverse=self.sort_reverse("country"),
)
def action_sort_by_columns(self) -> None:
"""Sort DataTable without a key."""
table = self.query_one(DataTable)
table.sort("swimmer", "lane", reverse=self.sort_reverse("columns"))
app = TableApp()
if __name__ == "__main__":
app.run()
| TableApp |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 6703,
"end": 7765
} | class ____(BiffRecord):
"""
Offset Size Contents
0 2 Version, contains 0600H for BIFF8 and BIFF8X
2 2 Type of the following data:
0005H = Workbook globals
0006H = Visual Basic module
0010H = Worksheet
0020H = Chart
0040H = Macro sheet
0100H = Workspace file
4 2 Build identifier
6 2 Build year
8 4 File history flags
12 4 Lowest Excel version that can read all records in this file
"""
_REC_ID = 0x0809
# stream types
BOOK_GLOBAL = 0x0005
VB_MODULE = 0x0006
WORKSHEET = 0x0010
CHART = 0x0020
MACROSHEET = 0x0040
WORKSPACE = 0x0100
def __init__(self, rec_type):
version = 0x0600
build = 0x0DBB
year = 0x07CC
file_hist_flags = 0x00
ver_can_read = 0x06
self._rec_data = pack('<4H2I', version, rec_type, build, year, file_hist_flags, ver_can_read)
| Biff8BOFRecord |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/compute.py | {
"start": 1872,
"end": 40483
} | class ____(GoogleBaseHook):
"""
Hook for Google Compute Engine APIs.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
"""
def __init__(
self,
api_version: str = "v1",
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(
gcp_conn_id=gcp_conn_id,
impersonation_chain=impersonation_chain,
**kwargs,
)
self.api_version = api_version
_conn: Any | None = None
def get_conn(self):
"""
Retrieve connection to Google Compute Engine.
:return: Google Compute Engine services object
:rtype: dict
"""
if not self._conn:
http_authorized = self._authorize()
self._conn = build("compute", self.api_version, http=http_authorized, cache_discovery=False)
return self._conn
def get_compute_instance_template_client(self):
"""Return Compute Engine Instance Template Client."""
return InstanceTemplatesClient(credentials=self.get_credentials(), client_info=CLIENT_INFO)
def get_compute_instance_client(self):
"""Return Compute Engine Instance Client."""
return InstancesClient(credentials=self.get_credentials(), client_info=CLIENT_INFO)
def get_compute_instance_group_managers_client(self):
"""Return Compute Engine Instance Group Managers Client."""
return InstanceGroupManagersClient(credentials=self.get_credentials(), client_info=CLIENT_INFO)
@GoogleBaseHook.fallback_to_default_project_id
def insert_instance_template(
self,
body: dict,
request_id: str | None = None,
project_id: str = PROVIDE_PROJECT_ID,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> None:
"""
Create Instance Template using body specified.
Must be called with keyword arguments rather than positional.
:param body: Instance Template representation as an object.
:param request_id: Unique request_id that you might add to achieve
full idempotence (for example when client call times out repeating the request
with the same request id will not create a new instance template again)
It should be in UUID format as defined in RFC 4122
:param project_id: Google Cloud project ID where the Compute Engine Instance Template exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
"""
client = self.get_compute_instance_template_client()
operation = client.insert(
# Calling method insert() on client to create Instance Template.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.InsertInstanceTemplateRequest, dict] to construct a request
# message.
# The request object should be represented using arguments:
# instance_template_resource (google.cloud.compute_v1.types.InstanceTemplate):
# The body resource for this request.
# request_id (str):
# An optional request ID to identify requests.
# project (str):
# Project ID for this request.
request={
"instance_template_resource": body,
"request_id": request_id,
"project": project_id,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
self._wait_for_operation_to_complete(operation_name=operation.name, project_id=project_id)
@GoogleBaseHook.fallback_to_default_project_id
def delete_instance_template(
self,
resource_id: str,
request_id: str | None = None,
project_id: str = PROVIDE_PROJECT_ID,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> None:
"""
Delete Instance Template.
Deleting an Instance Template is permanent and cannot be undone. It is not
possible to delete templates that are already in use by a managed instance
group. Must be called with keyword arguments rather than positional.
:param resource_id: Name of the Compute Engine Instance Template resource.
:param request_id: Unique request_id that you might add to achieve
full idempotence (for example when client call times out repeating the request
with the same request id will not create a new instance template again)
It should be in UUID format as defined in RFC 4122
:param project_id: Google Cloud project ID where the Compute Engine Instance Template exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
"""
client = self.get_compute_instance_template_client()
operation = client.delete(
# Calling method delete() on client to delete Instance Template.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.DeleteInstanceTemplateRequest, dict] to
# construct a request message.
# The request object should be represented using arguments:
# instance_template (str):
# The name of the Instance Template to delete.
# project (str):
# Project ID for this request.
# request_id (str):
# An optional request ID to identify requests.
request={
"instance_template": resource_id,
"project": project_id,
"request_id": request_id,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
self._wait_for_operation_to_complete(operation_name=operation.name, project_id=project_id)
@GoogleBaseHook.fallback_to_default_project_id
def get_instance_template(
self,
resource_id: str,
project_id: str = PROVIDE_PROJECT_ID,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> InstanceTemplate:
"""
Retrieve Instance Template by project_id and resource_id.
Must be called with keyword arguments rather than positional.
:param resource_id: Name of the Instance Template.
:param project_id: Google Cloud project ID where the Compute Engine Instance Template exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
:return: Instance Template representation as object according to
https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates
:rtype: object
"""
client = self.get_compute_instance_template_client()
instance_template = client.get(
# Calling method get() on client to get the specified Instance Template.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.GetInstanceTemplateRequest, dict] to construct a request
# message.
# The request object should be represented using arguments:
# instance_template (str):
# The name of the Instance Template.
# project (str):
# Project ID for this request.
request={
"instance_template": resource_id,
"project": project_id,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
return instance_template
@GoogleBaseHook.fallback_to_default_project_id
def insert_instance(
self,
body: dict,
zone: str,
project_id: str = PROVIDE_PROJECT_ID,
request_id: str | None = None,
source_instance_template: str | None = None,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> None:
"""
Create Instance using body specified.
Must be called with keyword arguments rather than positional.
:param body: Instance representation as an object. Should at least include 'name', 'machine_type',
'disks' and 'network_interfaces' fields but doesn't include 'zone' field, as it will be specified
in 'zone' parameter.
Full or partial URL and can be represented as examples below:
1. "machine_type": "projects/your-project-name/zones/your-zone/machineTypes/your-machine-type"
2. "source_image": "projects/your-project-name/zones/your-zone/diskTypes/your-disk-type"
3. "subnetwork": "projects/your-project-name/regions/your-region/subnetworks/your-subnetwork"
:param zone: Google Cloud zone where the Instance exists
:param project_id: Google Cloud project ID where the Compute Engine Instance Template exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param source_instance_template: Existing Instance Template that will be used as a base while
creating new Instance.
When specified, only name of new Instance should be provided as input arguments in 'body'
parameter when creating new Instance. All other parameters, will be passed to Instance as they
are specified in the Instance Template.
Full or partial URL and can be represented as examples below:
1. "https://www.googleapis.com/compute/v1/projects/your-project/global/instanceTemplates/temp"
2. "projects/your-project/global/instanceTemplates/temp"
3. "global/instanceTemplates/temp"
:param request_id: Unique request_id that you might add to achieve
full idempotence (for example when client call times out repeating the request
with the same request id will not create a new instance template again)
It should be in UUID format as defined in RFC 4122
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
"""
client = self.get_compute_instance_client()
operation = client.insert(
# Calling method insert() on client to create Instance.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.InsertInstanceRequest, dict] to construct a request
# message.
# The request object should be represented using arguments:
# instance_resource (google.cloud.compute_v1.types.Instance):
# The body resource for this request.
# request_id (str):
# Optional, request ID to identify requests.
# project (str):
# Project ID for this request.
# zone (str):
# The name of the zone for this request.
# source_instance_template (str):
# Optional, link to Instance Template, that can be used to create new Instance.
request={
"instance_resource": body,
"request_id": request_id,
"project": project_id,
"zone": zone,
"source_instance_template": source_instance_template,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation.name, zone=zone)
@GoogleBaseHook.fallback_to_default_project_id
def get_instance(
self,
resource_id: str,
zone: str,
project_id: str = PROVIDE_PROJECT_ID,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> Instance:
"""
Retrieve Instance by project_id and resource_id.
Must be called with keyword arguments rather than positional.
:param resource_id: Name of the Instance
:param zone: Google Cloud zone where the Instance exists
:param project_id: Google Cloud project ID where the Compute Engine Instance exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
:return: Instance representation as object according to
https://cloud.google.com/compute/docs/reference/rest/v1/instances
:rtype: object
"""
client = self.get_compute_instance_client()
instance = client.get(
# Calling method get() on client to get the specified Instance.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.GetInstanceRequest, dict] to construct a request
# message.
# The request object should be represented using arguments:
# instance (str):
# The name of the Instance.
# project (str):
# Project ID for this request.
# zone (str):
# The name of the zone for this request.
request={
"instance": resource_id,
"project": project_id,
"zone": zone,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
return instance
@GoogleBaseHook.fallback_to_default_project_id
def delete_instance(
self,
resource_id: str,
zone: str,
project_id: str = PROVIDE_PROJECT_ID,
request_id: str | None = None,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> None:
"""
Permanently and irrevocably deletes an Instance.
It is not possible to delete Instances that are already in use by a managed instance group.
Must be called with keyword arguments rather than positional.
:param resource_id: Name of the Compute Engine Instance Template resource.
:param request_id: Unique request_id that you might add to achieve
full idempotence (for example when client call times out repeating the request
with the same request id will not create a new instance template again)
It should be in UUID format as defined in RFC 4122
:param project_id: Google Cloud project ID where the Compute Engine Instance Template exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param zone: Google Cloud zone where the Instance exists
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
"""
client = self.get_compute_instance_client()
operation = client.delete(
# Calling method delete() on client to delete Instance.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.DeleteInstanceRequest, dict] to construct a request
# message.
# The request object should be represented using arguments:
# instance (str):
# Name of the Instance resource to delete.
# project (str):
# Project ID for this request.
# request_id (str):
# An optional request ID to identify requests.
# zone (str):
# The name of the zone for this request.
request={
"instance": resource_id,
"project": project_id,
"request_id": request_id,
"zone": zone,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation.name, zone=zone)
@GoogleBaseHook.fallback_to_default_project_id
def start_instance(self, zone: str, resource_id: str, project_id: str) -> None:
"""
Start an existing instance defined by project_id, zone and resource_id.
Must be called with keyword arguments rather than positional.
:param zone: Google Cloud zone where the instance exists
:param resource_id: Name of the Compute Engine instance resource
:param project_id: Optional, Google Cloud project ID where the
Compute Engine Instance exists. If set to None or missing,
the default project_id from the Google Cloud connection is used.
:return: None
"""
response = (
self.get_conn()
.instances()
.start(project=project_id, zone=zone, instance=resource_id)
.execute(num_retries=self.num_retries)
)
try:
operation_name = response["name"]
except KeyError:
raise AirflowException(f"Wrong response '{response}' returned - it should contain 'name' field")
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation_name, zone=zone)
@GoogleBaseHook.fallback_to_default_project_id
def stop_instance(self, zone: str, resource_id: str, project_id: str) -> None:
"""
Stop an instance defined by project_id, zone and resource_id.
Must be called with keyword arguments rather than positional.
:param zone: Google Cloud zone where the instance exists
:param resource_id: Name of the Compute Engine instance resource
:param project_id: Optional, Google Cloud project ID where the
Compute Engine Instance exists. If set to None or missing,
the default project_id from the Google Cloud connection is used.
:return: None
"""
response = (
self.get_conn()
.instances()
.stop(project=project_id, zone=zone, instance=resource_id)
.execute(num_retries=self.num_retries)
)
try:
operation_name = response["name"]
except KeyError:
raise AirflowException(f"Wrong response '{response}' returned - it should contain 'name' field")
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation_name, zone=zone)
@GoogleBaseHook.fallback_to_default_project_id
def set_machine_type(self, zone: str, resource_id: str, body: dict, project_id: str) -> None:
"""
Set machine type of an instance defined by project_id, zone and resource_id.
Must be called with keyword arguments rather than positional.
:param zone: Google Cloud zone where the instance exists.
:param resource_id: Name of the Compute Engine instance resource
:param body: Body required by the Compute Engine setMachineType API,
as described in
https://cloud.google.com/compute/docs/reference/rest/v1/instances/setMachineType
:param project_id: Optional, Google Cloud project ID where the
Compute Engine Instance exists. If set to None or missing,
the default project_id from the Google Cloud connection is used.
:return: None
"""
response = self._execute_set_machine_type(zone, resource_id, body, project_id)
try:
operation_name = response["name"]
except KeyError:
raise AirflowException(f"Wrong response '{response}' returned - it should contain 'name' field")
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation_name, zone=zone)
def _execute_set_machine_type(self, zone: str, resource_id: str, body: dict, project_id: str) -> dict:
return (
self.get_conn()
.instances()
.setMachineType(project=project_id, zone=zone, instance=resource_id, body=body)
.execute(num_retries=self.num_retries)
)
@GoogleBaseHook.fallback_to_default_project_id
def insert_instance_group_manager(
self,
body: dict,
zone: str,
project_id: str = PROVIDE_PROJECT_ID,
request_id: str | None = None,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> None:
"""
Create an Instance Group Managers using the body specified.
After the group is created, instances in the group are created using the specified Instance Template.
Must be called with keyword arguments rather than positional.
:param body: Instance Group Manager representation as an object.
:param request_id: Unique request_id that you might add to achieve
full idempotence (for example when client call times out repeating the request
with the same request id will not create a new Instance Group Managers again)
It should be in UUID format as defined in RFC 4122
:param project_id: Google Cloud project ID where the Compute Engine Instance Group Managers exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param zone: Google Cloud zone where the Instance exists
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
"""
client = self.get_compute_instance_group_managers_client()
operation = client.insert(
# Calling method insert() on client to create the specified Instance Group Managers.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.InsertInstanceGroupManagerRequest, dict] to construct
# a request message.
# The request object should be represented using arguments:
# instance_group_manager_resource (google.cloud.compute_v1.types.InstanceGroupManager):
# The body resource for this request.
# project (str):
# Project ID for this request.
# zone (str):
# The name of the zone where you want to create the managed instance group.
# request_id (str):
# An optional request ID to identify requests.
request={
"instance_group_manager_resource": body,
"project": project_id,
"zone": zone,
"request_id": request_id,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation.name, zone=zone)
@GoogleBaseHook.fallback_to_default_project_id
def get_instance_group_manager(
self,
resource_id: str,
zone: str,
project_id: str = PROVIDE_PROJECT_ID,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> InstanceGroupManager:
"""
Retrieve Instance Group Manager by project_id, zone and resource_id.
Must be called with keyword arguments rather than positional.
:param resource_id: The name of the Managed Instance Group
:param zone: Google Cloud zone where the Instance Group Managers exists
:param project_id: Google Cloud project ID where the Compute Engine Instance Group Managers exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
:return: Instance Group Managers representation as object according to
https://cloud.google.com/compute/docs/reference/rest/v1/instanceGroupManagers
:rtype: object
"""
client = self.get_compute_instance_group_managers_client()
instance_group_manager = client.get(
# Calling method get() on client to get the specified Instance Group Manager.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.GetInstanceGroupManagerRequest, dict] to construct a
# request message.
# The request object should be represented using arguments:
# instance_group_manager (str):
# The name of the Managed Instance Group.
# project (str):
# Project ID for this request.
# zone (str):
# The name of the zone for this request.
request={
"instance_group_manager": resource_id,
"project": project_id,
"zone": zone,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
return instance_group_manager
@GoogleBaseHook.fallback_to_default_project_id
def delete_instance_group_manager(
self,
resource_id: str,
zone: str,
project_id: str = PROVIDE_PROJECT_ID,
request_id: str | None = None,
retry: Retry | None = None,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> None:
"""
Permanently and irrevocably deletes Instance Group Managers.
Must be called with keyword arguments rather than positional.
:param resource_id: Name of the Compute Engine Instance Group Managers resource.
:param request_id: Unique request_id that you might add to achieve
full idempotence (for example when client call times out repeating the request
with the same request id will not create a new instance template again)
It should be in UUID format as defined in RFC 4122
:param project_id: Google Cloud project ID where the Compute Engine Instance Group Managers exists.
If set to None or missing, the default project_id from the Google Cloud connection is used.
:param zone: Google Cloud zone where the Instance Group Managers exists
:param retry: A retry object used to retry requests. If `None` is specified, requests
will not be retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete.
Note that if `retry` is specified, the timeout applies to each individual attempt.
:param metadata: Additional metadata that is provided to the method.
"""
client = self.get_compute_instance_group_managers_client()
operation = client.delete(
# Calling method delete() on client to delete Instance Group Managers.
# This method accepts request object as an argument and should be of type
# Union[google.cloud.compute_v1.types.DeleteInstanceGroupManagerRequest, dict] to construct a
# request message.
# The request object should be represented using arguments:
# instance_group_manager (str):
# Name of the Instance resource to delete.
# project (str):
# Project ID for this request.
# request_id (str):
# An optional request ID to identify requests.
# zone (str):
# The name of the zone for this request.
request={
"instance_group_manager": resource_id,
"project": project_id,
"request_id": request_id,
"zone": zone,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation.name, zone=zone)
@GoogleBaseHook.fallback_to_default_project_id
def patch_instance_group_manager(
self,
zone: str,
resource_id: str,
body: dict,
project_id: str,
request_id: str | None = None,
) -> None:
"""
Patches Instance Group Manager with the specified body.
Must be called with keyword arguments rather than positional.
:param zone: Google Cloud zone where the Instance Group Manager exists
:param resource_id: Name of the Instance Group Manager
:param body: Instance Group Manager representation as json-merge-patch object
according to
https://cloud.google.com/compute/docs/reference/rest/beta/instanceTemplates/patch
:param request_id: Optional, unique request_id that you might add to achieve
full idempotence (for example when client call times out repeating the request
with the same request id will not create a new instance template again).
It should be in UUID format as defined in RFC 4122
:param project_id: Optional, Google Cloud project ID where the
Compute Engine Instance exists. If set to None or missing,
the default project_id from the Google Cloud connection is used.
:return: None
"""
response = (
self.get_conn()
.instanceGroupManagers()
.patch(
project=project_id,
zone=zone,
instanceGroupManager=resource_id,
body=body,
requestId=request_id,
)
.execute(num_retries=self.num_retries)
)
try:
operation_name = response["name"]
except KeyError:
raise AirflowException(f"Wrong response '{response}' returned - it should contain 'name' field")
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation_name, zone=zone)
def _wait_for_operation_to_complete(
self, project_id: str, operation_name: str, zone: str | None = None
) -> None:
"""
Wait for the named operation to complete - checks status of the async call.
:param operation_name: name of the operation
:param zone: optional region of the request (might be None for global operations)
:param project_id: Google Cloud project ID where the Compute Engine Instance exists.
:return: None
"""
service = self.get_conn()
while True:
self.log.info("Waiting for Operation to complete...")
if zone is None:
operation_response = self._check_global_operation_status(
service=service,
operation_name=operation_name,
project_id=project_id,
num_retries=self.num_retries,
)
else:
operation_response = self._check_zone_operation_status(
service, operation_name, project_id, zone, self.num_retries
)
if operation_response.get("status") == GceOperationStatus.DONE:
error = operation_response.get("error")
if error:
code = operation_response.get("httpErrorStatusCode")
msg = operation_response.get("httpErrorMessage")
# Extracting the errors list as string and trimming square braces
error_msg = str(error.get("errors"))[1:-1]
raise AirflowException(f"{code} {msg}: " + error_msg)
break
time.sleep(TIME_TO_SLEEP_IN_SECONDS)
@staticmethod
def _check_zone_operation_status(
service: Any, operation_name: str, project_id: str, zone: str, num_retries: int
) -> dict:
return (
service.zoneOperations()
.get(project=project_id, zone=zone, operation=operation_name)
.execute(num_retries=num_retries)
)
@staticmethod
def _check_global_operation_status(
service: Any, operation_name: str, project_id: str, num_retries: int
) -> dict:
return (
service.globalOperations()
.get(project=project_id, operation=operation_name)
.execute(num_retries=num_retries)
)
@GoogleBaseHook.fallback_to_default_project_id
def get_instance_info(self, zone: str, resource_id: str, project_id: str) -> dict[str, Any]:
"""
Get instance information.
:param zone: Google Cloud zone where the Instance Group Manager exists
:param resource_id: Name of the Instance Group Manager
:param project_id: Optional, Google Cloud project ID where the
Compute Engine Instance exists. If set to None or missing,
the default project_id from the Google Cloud connection is used.
"""
instance_info = (
self.get_conn()
.instances()
.get(project=project_id, instance=resource_id, zone=zone)
.execute(num_retries=self.num_retries)
)
return instance_info
@GoogleBaseHook.fallback_to_default_project_id
def get_instance_address(
self, zone: str, resource_id: str, project_id: str = PROVIDE_PROJECT_ID, use_internal_ip: bool = False
) -> str:
"""
Return network address associated to instance.
:param zone: Google Cloud zone where the Instance Group Manager exists
:param resource_id: Name of the Instance Group Manager
:param project_id: Optional, Google Cloud project ID where the
Compute Engine Instance exists. If set to None or missing,
the default project_id from the Google Cloud connection is used.
:param use_internal_ip: If true, return private IP address.
"""
instance_info = self.get_instance_info(project_id=project_id, resource_id=resource_id, zone=zone)
if use_internal_ip:
return instance_info["networkInterfaces"][0].get("networkIP")
access_config = instance_info["networkInterfaces"][0].get("accessConfigs")
if access_config:
return access_config[0].get("natIP")
raise AirflowException("The target instance does not have external IP")
@GoogleBaseHook.fallback_to_default_project_id
def set_instance_metadata(
self, zone: str, resource_id: str, metadata: dict[str, str], project_id: str
) -> None:
"""
Set instance metadata.
:param zone: Google Cloud zone where the Instance Group Manager exists
:param resource_id: Name of the Instance Group Manager
:param metadata: The new instance metadata.
:param project_id: Optional, Google Cloud project ID where the
Compute Engine Instance exists. If set to None or missing,
the default project_id from the Google Cloud connection is used.
"""
response = (
self.get_conn()
.instances()
.setMetadata(project=project_id, zone=zone, instance=resource_id, body=metadata)
.execute(num_retries=self.num_retries)
)
operation_name = response["name"]
self._wait_for_operation_to_complete(project_id=project_id, operation_name=operation_name, zone=zone)
| ComputeEngineHook |
python | fastapi__sqlmodel | docs_src/tutorial/one/tutorial009_py310.py | {
"start": 63,
"end": 1506
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with Session(engine) as session:
hero = session.get(Hero, 9001)
print("Hero:", hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | getsentry__sentry | src/sentry/integrations/github/integration.py | {
"start": 9203,
"end": 32582
} | class ____(
RepositoryIntegration,
GitHubIssuesSpec,
IssueSyncIntegration,
CommitContextIntegration,
RepoTreesIntegration,
):
integration_name = IntegrationProviderSlug.GITHUB
# IssueSyncIntegration configuration keys
comment_key = "sync_comments"
outbound_status_key = "sync_status_forward"
inbound_status_key = "sync_status_reverse"
outbound_assignee_key = "sync_forward_assignment"
inbound_assignee_key = "sync_reverse_assignment"
resolution_strategy_key = "resolution_strategy"
codeowners_locations = ["CODEOWNERS", ".github/CODEOWNERS", "docs/CODEOWNERS"]
def get_client(self) -> GitHubBaseClient:
if not self.org_integration:
raise IntegrationError("Organization Integration does not exist")
return GitHubApiClient(integration=self.model, org_integration_id=self.org_integration.id)
# IntegrationInstallation methods
def is_rate_limited_error(self, exc: ApiError) -> bool:
if exc.json and RATE_LIMITED_MESSAGE in exc.json.get("message", ""):
metrics.incr("github.link_all_repos.rate_limited_error")
return True
return False
def message_from_error(self, exc: Exception) -> str:
if not isinstance(exc, ApiError):
return ERR_INTERNAL
if not exc.code:
message = ""
else:
message = API_ERRORS.get(exc.code, "")
if exc.code == 404 and exc.url and re.search(r"/repos/.*/(compare|commits)", exc.url):
message += (
" Please also confirm that the commits associated with "
f"the following URL have been pushed to GitHub: {exc.url}"
)
if not message:
message = exc.json.get("message", "unknown error") if exc.json else "unknown error"
return f"Error Communicating with GitHub (HTTP {exc.code}): {message}"
# RepositoryIntegration methods
def source_url_matches(self, url: str) -> bool:
return url.startswith("https://{}".format(self.model.metadata["domain_name"]))
def format_source_url(self, repo: Repository, filepath: str, branch: str | None) -> str:
# Must format the url ourselves since `check_file` is a head request
# "https://github.com/octokit/octokit.rb/blob/master/README.md"
return f"https://github.com/{repo.name}/blob/{branch}/{filepath}"
def extract_branch_from_source_url(self, repo: Repository, url: str) -> str:
if not repo.url:
return ""
branch, _ = parse_github_blob_url(repo.url, url)
return branch
def extract_source_path_from_source_url(self, repo: Repository, url: str) -> str:
if not repo.url:
return ""
_, source_path = parse_github_blob_url(repo.url, url)
return source_path
def get_repositories(
self, query: str | None = None, page_number_limit: int | None = None
) -> list[dict[str, Any]]:
"""
args:
* query - a query to filter the repositories by
This fetches all repositories accessible to the Github App
https://docs.github.com/en/rest/apps/installations#list-repositories-accessible-to-the-app-installation
"""
if not query:
all_repos = self.get_client().get_repos(page_number_limit=page_number_limit)
return [
{
"name": i["name"],
"identifier": i["full_name"],
"default_branch": i.get("default_branch"),
}
for i in all_repos
if not i.get("archived")
]
full_query = build_repository_query(self.model.metadata, self.model.name, query)
response = self.get_client().search_repositories(full_query)
return [
{
"name": i["name"],
"identifier": i["full_name"],
"default_branch": i.get("default_branch"),
}
for i in response.get("items", [])
]
def get_unmigratable_repositories(self) -> list[RpcRepository]:
accessible_repos = self.get_repositories()
accessible_repo_names = [r["identifier"] for r in accessible_repos]
existing_repos = repository_service.get_repositories(
organization_id=self.organization_id, providers=[IntegrationProviderSlug.GITHUB.value]
)
return [repo for repo in existing_repos if repo.name not in accessible_repo_names]
def has_repo_access(self, repo: RpcRepository) -> bool:
client = self.get_client()
try:
# make sure installation has access to this specific repo
# use hooks endpoint since we explicitly ask for those permissions
# when installing the app (commits can be accessed for public repos)
# https://docs.github.com/en/rest/webhooks/repo-config#list-hooks
client.repo_hooks(repo.config["name"])
except ApiError:
return False
return True
def search_issues(self, query: str | None, **kwargs) -> dict[str, Any]:
if query is None:
query = ""
resp = self.get_client().search_issues(query)
assert isinstance(resp, dict)
return resp
def get_account_id(self):
installation_metadata = self.model.metadata
github_account_id = installation_metadata.get("account_id")
# Attempt to backfill the id if it does not exist
if github_account_id is None:
client: GitHubBaseClient = self.get_client()
installation_id = self.model.external_id
updated_installation_info: Mapping[str, Any] = client.get_installation_info(
installation_id
)
github_account_id = updated_installation_info["account"]["id"]
installation_metadata["account_id"] = github_account_id
integration_service.update_integration(
integration_id=self.model.id, metadata=installation_metadata
)
return github_account_id
# CommitContextIntegration methods
def on_create_or_update_comment_error(self, api_error: ApiError, metrics_base: str) -> bool:
if api_error.json:
if ISSUE_LOCKED_ERROR_MESSAGE in api_error.json.get("message", ""):
metrics.incr(
metrics_base.format(integration=self.integration_name, key="error"),
tags={"type": "issue_locked_error"},
)
return True
elif RATE_LIMITED_MESSAGE in api_error.json.get("message", ""):
metrics.incr(
metrics_base.format(integration=self.integration_name, key="error"),
tags={"type": "rate_limited_error"},
)
return True
return False
# IssueSyncIntegration methods
def split_external_issue_key(
self, external_issue_key: str
) -> tuple[str, str] | tuple[None, None]:
"""
Split the external issue key into repo and issue number.
"""
# Parse the external issue key to get repo and issue number
# Format is "{repo_full_name}#{issue_number}"
try:
repo_id, issue_num = external_issue_key.split("#")
return repo_id, issue_num
except ValueError:
logger.exception(
"github.assignee-outbound.invalid-key",
extra={
"external_issue_key": external_issue_key,
},
)
return None, None
def sync_assignee_outbound(
self,
external_issue: ExternalIssue,
user: RpcUser | None,
assign: bool = True,
**kwargs: Any,
) -> None:
"""
Propagate a sentry issue's assignee to a linked GitHub issue's assignee.
If assign=True, we're assigning the issue. Otherwise, deassign.
"""
client = self.get_client()
repo_id, issue_num = self.split_external_issue_key(external_issue.key)
if not repo_id or not issue_num:
logger.error(
"github.assignee-outbound.invalid-key",
extra={
"integration_id": external_issue.integration_id,
"external_issue_key": external_issue.key,
"external_issue_id": external_issue.id,
},
)
return
github_username = None
# If we're assigning and have a user, find their GitHub username
if user and assign:
# Check if user has a GitHub identity linked
external_actor = ExternalActor.objects.filter(
provider=ExternalProviders.GITHUB.value,
user_id=user.id,
integration_id=external_issue.integration_id,
organization=external_issue.organization,
).first()
if not external_actor:
logger.info(
"github.assignee-outbound.external-actor-not-found",
extra={
"integration_id": external_issue.integration_id,
"user_id": user.id,
},
)
return
# Strip the @ from the username
github_username = external_actor.external_name.lstrip("@")
# lowercase the username
github_username = github_username.lower()
# Only update GitHub if we have a username to assign or if we're explicitly deassigning
if github_username or not assign:
try:
client.update_issue_assignees(
repo_id, issue_num, [github_username] if github_username else []
)
except Exception as e:
self.raise_error(e)
def sync_status_outbound(
self, external_issue: ExternalIssue, is_resolved: bool, project_id: int
) -> None:
"""
Propagate a sentry issue's status to a linked GitHub issue's status.
For GitHub, we only support open/closed states.
"""
client = self.get_client()
repo_id, issue_num = self.split_external_issue_key(external_issue.key)
if not repo_id or not issue_num:
logger.error(
"github.status-outbound.invalid-key",
extra={
"external_issue_key": external_issue.key,
},
)
return
# Get the project mapping to determine what status to use
external_project = integration_service.get_integration_external_project(
organization_id=external_issue.organization_id,
integration_id=external_issue.integration_id,
external_id=repo_id,
)
log_context = {
"integration_id": external_issue.integration_id,
"is_resolved": is_resolved,
"issue_key": external_issue.key,
"repo_id": repo_id,
}
if not external_project:
logger.info("github.external-project-not-found", extra=log_context)
return
desired_state = (
external_project.resolved_status if is_resolved else external_project.unresolved_status
)
try:
issue_data = client.get_issue(repo_id, issue_num)
except ApiError as e:
self.raise_error(e)
current_state = issue_data.get("state")
# Don't update if it's already in the desired state
if current_state == desired_state:
logger.info(
"github.sync_status_outbound.unchanged",
extra={
**log_context,
"current_state": current_state,
"desired_state": desired_state,
},
)
return
# Update the issue state
try:
client.update_issue_status(repo_id, issue_num, desired_state)
logger.info(
"github.sync_status_outbound.success",
extra={
**log_context,
"old_state": current_state,
"new_state": desired_state,
},
)
except ApiError as e:
self.raise_error(e)
def get_resolve_sync_action(self, data: Mapping[str, Any]) -> ResolveSyncAction:
"""
Given webhook data, check whether the GitHub issue status changed.
GitHub issues only have open/closed state.
"""
if not features.has(
"organizations:integrations-github-project-management", self.organization
):
return ResolveSyncAction.NOOP
if data.get("action") == IssueEvenntWebhookActionType.CLOSED.value:
return ResolveSyncAction.RESOLVE
elif data.get("action") == IssueEvenntWebhookActionType.REOPENED.value:
return ResolveSyncAction.UNRESOLVE
return ResolveSyncAction.NOOP
def get_config_data(self):
config = self.org_integration.config
project_mappings = IntegrationExternalProject.objects.filter(
organization_integration_id=self.org_integration.id
)
sync_status_forward = {}
for pm in project_mappings:
sync_status_forward[pm.external_id] = {
"on_unresolve": pm.unresolved_status,
"on_resolve": pm.resolved_status,
}
config["sync_status_forward"] = sync_status_forward
return config
def _get_organization_config_default_values(self) -> list[dict[str, Any]]:
"""
Return configuration options for the GitHub integration.
"""
config: list[dict[str, Any]] = []
if features.has("organizations:integrations-github-project-management", self.organization):
config.extend(
[
{
"name": self.inbound_status_key,
"type": "boolean",
"label": _("Sync GitHub Status to Sentry"),
"help": _(
"When a GitHub issue is marked closed, resolve its linked issue in Sentry. "
"When a GitHub issue is reopened, unresolve its linked Sentry issue."
),
"default": False,
},
{
"name": self.inbound_assignee_key,
"type": "boolean",
"label": _("Sync Github Assignment to Sentry"),
"help": _(
"When an issue is assigned in GitHub, assign its linked Sentry issue to the same user."
),
"default": False,
},
{
"name": self.outbound_assignee_key,
"type": "boolean",
"label": _("Sync Sentry Assignment to GitHub"),
"help": _(
"When an issue is assigned in Sentry, assign its linked GitHub issue to the same user."
),
"default": False,
},
{
"name": self.resolution_strategy_key,
"label": "Resolve",
"type": "select",
"placeholder": "Resolve",
"choices": [
("resolve", "Resolve"),
("resolve_current_release", "Resolve in Current Release"),
("resolve_next_release", "Resolve in Next Release"),
],
"help": _(
"Select what action to take on Sentry Issue when GitHub ticket is marked Closed."
),
},
{
"name": self.comment_key,
"type": "boolean",
"label": _("Sync Sentry Comments to GitHub"),
"help": _("Post comments from Sentry issues to linked GitHub issues"),
},
]
)
return config
def get_organization_config(self) -> list[dict[str, Any]]:
"""
Return configuration options for the GitHub integration.
"""
config = self._get_organization_config_default_values()
if features.has("organizations:integrations-github-project-management", self.organization):
config.insert(
0,
{
"name": self.outbound_status_key,
"type": "choice_mapper",
"label": _("Sync Sentry Status to Github"),
"help": _(
"When a Sentry issue changes status, change the status of the linked ticket in Github."
),
"addButtonText": _("Add Github Project"),
"addDropdown": {
"emptyMessage": _("All projects configured"),
"noResultsMessage": _("Could not find Github project"),
"items": [], # Populated with projects
},
"mappedSelectors": {},
"columnLabels": {
"on_resolve": _("When resolved"),
"on_unresolve": _("When unresolved"),
},
"mappedColumnLabel": _("Github Project"),
"formatMessageValue": False,
},
)
try:
# Fetch all repositories and add them to the config
repositories = self.get_client().get_repos()
# Format repositories for the dropdown
formatted_repos = [
{"value": repository["full_name"], "label": repository["name"]}
for repository in repositories
if not repository.get("archived")
]
config[0]["addDropdown"]["items"] = formatted_repos
status_choices = GitHubIssueStatus.get_choices()
# Add mappedSelectors for each repository with GitHub status choices
config[0]["mappedSelectors"] = {
"on_resolve": {"choices": status_choices},
"on_unresolve": {"choices": status_choices},
}
except ApiError:
config[0]["disabled"] = True
config[0]["disabledReason"] = _(
"Unable to communicate with the GitHub instance. You may need to reinstall the integration."
)
context = organization_service.get_organization_by_id(
id=self.organization_id, include_projects=False, include_teams=False
)
assert context, "organizationcontext must exist to get org"
organization = context.organization
has_issue_sync = features.has("organizations:integrations-issue-sync", organization)
if not has_issue_sync:
for field in config:
field["disabled"] = True
field["disabledReason"] = _(
"Your organization does not have access to this feature"
)
return config
def update_organization_config(self, data: MutableMapping[str, Any]) -> None:
"""
Update the configuration field for an organization integration.
"""
if not self.org_integration:
return
config = self.org_integration.config
# Handle status sync configuration
if "sync_status_forward" in data:
project_mappings = data.pop("sync_status_forward")
if any(
not mapping["on_unresolve"] or not mapping["on_resolve"]
for mapping in project_mappings.values()
):
raise IntegrationError("Resolve and unresolve status are required.")
data["sync_status_forward"] = bool(project_mappings)
IntegrationExternalProject.objects.filter(
organization_integration_id=self.org_integration.id
).delete()
for repo_id, statuses in project_mappings.items():
# For GitHub, we only support open/closed states
# Validate that the statuses are valid GitHub states
if statuses["on_resolve"] not in [
GitHubIssueStatus.OPEN.value,
GitHubIssueStatus.CLOSED.value,
]:
raise IntegrationError(
f"Invalid resolve status: {statuses['on_resolve']}. Must be 'open' or 'closed'."
)
if statuses["on_unresolve"] not in ["open", "closed"]:
raise IntegrationError(
f"Invalid unresolve status: {statuses['on_unresolve']}. Must be 'open' or 'closed'."
)
IntegrationExternalProject.objects.create(
organization_integration_id=self.org_integration.id,
external_id=repo_id,
resolved_status=statuses["on_resolve"],
unresolved_status=statuses["on_unresolve"],
)
config.update(data)
org_integration = integration_service.update_organization_integration(
org_integration_id=self.org_integration.id,
config=config,
)
if org_integration is not None:
self.org_integration = org_integration
def get_pr_comment_workflow(self) -> PRCommentWorkflow:
return GitHubPRCommentWorkflow(integration=self)
def create_comment_attribution(self, user_id, comment_text):
user = user_service.get_user(user_id)
username = "Unknown User" if user is None else user.name
attribution = f"**{username}** wrote:\n\n"
# GitHub uses markdown blockquotes
quoted_text = "\n".join(f"> {line}" for line in comment_text.split("\n"))
return f"{attribution}{quoted_text}"
def update_comment(self, issue_id, user_id, group_note):
quoted_comment = self.create_comment_attribution(user_id, group_note.data["text"])
repo, issue_number = issue_id.rsplit("#", 1)
return self.get_client().update_comment(
repo, issue_number, group_note.data["external_id"], {"body": quoted_comment}
)
def create_comment(self, issue_id, user_id, group_note):
# GitHub uses markdown syntax directly without needing special formatting
comment = group_note.data["text"]
quoted_comment = self.create_comment_attribution(user_id, comment)
repo, issue_number = issue_id.rsplit("#", 1)
return self.get_client().create_comment(repo, issue_number, {"body": quoted_comment})
MERGED_PR_COMMENT_BODY_TEMPLATE = """\
## Issues attributed to commits in this pull request
This pull request was merged and Sentry observed the following issues:
{issue_list}""".rstrip()
| GitHubIntegration |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_select.py | {
"start": 57754,
"end": 59371
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
__requires__ = ("supports_is_distinct_from",)
@classmethod
def define_tables(cls, metadata):
Table(
"is_distinct_test",
metadata,
Column("id", Integer, primary_key=True),
Column("col_a", Integer, nullable=True),
Column("col_b", Integer, nullable=True),
)
@testing.combinations(
("both_int_different", 0, 1, 1),
("both_int_same", 1, 1, 0),
("one_null_first", None, 1, 1),
("one_null_second", 0, None, 1),
("both_null", None, None, 0),
id_="iaaa",
argnames="col_a_value, col_b_value, expected_row_count_for_is",
)
def test_is_or_is_not_distinct_from(
self, col_a_value, col_b_value, expected_row_count_for_is, connection
):
tbl = self.tables.is_distinct_test
connection.execute(
tbl.insert(),
[{"id": 1, "col_a": col_a_value, "col_b": col_b_value}],
)
result = connection.execute(
tbl.select().where(tbl.c.col_a.is_distinct_from(tbl.c.col_b))
).fetchall()
eq_(
len(result),
expected_row_count_for_is,
)
expected_row_count_for_is_not = (
1 if expected_row_count_for_is == 0 else 0
)
result = connection.execute(
tbl.select().where(tbl.c.col_a.is_not_distinct_from(tbl.c.col_b))
).fetchall()
eq_(
len(result),
expected_row_count_for_is_not,
)
| IsOrIsNotDistinctFromTest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 440810,
"end": 441087
} | class ____(VegaLiteSchema):
"""
Geometry schema wrapper.
Geometry object. https://tools.ietf.org/html/rfc7946#section-3
"""
_schema = {"$ref": "#/definitions/Geometry"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| Geometry |
python | ray-project__ray | python/ray/tests/test_actor_retry_1.py | {
"start": 40,
"end": 89
} | class ____(Exception):
pass
@ray.remote
| MyError |
python | numba__numba | numba/core/controlflow.py | {
"start": 2651,
"end": 23385
} | class ____(object):
"""
Generic (almost) implementation of a Control Flow Graph.
"""
def __init__(self):
self._nodes = set()
self._preds = _DictOfContainers(set)
self._succs = _DictOfContainers(set)
self._edge_data = {}
self._entry_point = None
def add_node(self, node):
"""
Add *node* to the graph. This is necessary before adding any
edges from/to the node. *node* can be any hashable object.
"""
self._nodes.add(node)
def add_edge(self, src, dest, data=None):
"""
Add an edge from node *src* to node *dest*, with optional
per-edge *data*.
If such an edge already exists, it is replaced (duplicate edges
are not possible).
"""
if src not in self._nodes:
raise ValueError("Cannot add edge as src node %s not in nodes %s" %
(src, self._nodes))
if dest not in self._nodes:
raise ValueError("Cannot add edge as dest node %s not in nodes %s" %
(dest, self._nodes))
self._add_edge(src, dest, data)
def successors(self, src):
"""
Yield (node, data) pairs representing the successors of node *src*.
(*data* will be None if no data was specified when adding the edge)
"""
for dest in self._succs[src]:
yield dest, self._edge_data[src, dest]
def predecessors(self, dest):
"""
Yield (node, data) pairs representing the predecessors of node *dest*.
(*data* will be None if no data was specified when adding the edge)
"""
for src in self._preds[dest]:
yield src, self._edge_data[src, dest]
def set_entry_point(self, node):
"""
Set the entry point of the graph to *node*.
"""
assert node in self._nodes
self._entry_point = node
def process(self):
"""
Compute essential properties of the control flow graph. The graph
must have been fully populated, and its entry point specified. Other
graph properties are computed on-demand.
"""
if self._entry_point is None:
raise RuntimeError("no entry point defined!")
self._eliminate_dead_blocks()
def dominators(self):
"""
Return a dictionary of {node -> set(nodes)} mapping each node to
the nodes dominating it.
A node D dominates a node N when any path leading to N must go through D
"""
return self._doms
def post_dominators(self):
"""
Return a dictionary of {node -> set(nodes)} mapping each node to
the nodes post-dominating it.
A node P post-dominates a node N when any path starting from N must go
through P.
"""
return self._post_doms
def immediate_dominators(self):
"""
Return a dictionary of {node -> node} mapping each node to its
immediate dominator (idom).
The idom(B) is the closest strict dominator of V
"""
return self._idom
def dominance_frontier(self):
"""
Return a dictionary of {node -> set(nodes)} mapping each node to
the nodes in its dominance frontier.
The dominance frontier _df(N) is the set of all nodes that are
immediate successors to blocks dominated by N but which aren't
strictly dominated by N
"""
return self._df
def dominator_tree(self):
"""
return a dictionary of {node -> set(nodes)} mapping each node to
the set of nodes it immediately dominates
The domtree(B) is the closest strict set of nodes that B dominates
"""
return self._domtree
@functools.cached_property
def _exit_points(self):
return self._find_exit_points()
@functools.cached_property
def _doms(self):
return self._find_dominators()
@functools.cached_property
def _back_edges(self):
return self._find_back_edges()
@functools.cached_property
def _topo_order(self):
return self._find_topo_order()
@functools.cached_property
def _descs(self):
return self._find_descendents()
@functools.cached_property
def _loops(self):
return self._find_loops()
@functools.cached_property
def _in_loops(self):
return self._find_in_loops()
@functools.cached_property
def _post_doms(self):
return self._find_post_dominators()
@functools.cached_property
def _idom(self):
return self._find_immediate_dominators()
@functools.cached_property
def _df(self):
return self._find_dominance_frontier()
@functools.cached_property
def _domtree(self):
return self._find_dominator_tree()
def descendents(self, node):
"""
Return the set of descendents of the given *node*, in topological
order (ignoring back edges).
"""
return self._descs[node]
def entry_point(self):
"""
Return the entry point node.
"""
assert self._entry_point is not None
return self._entry_point
def exit_points(self):
"""
Return the computed set of exit nodes (may be empty).
"""
return self._exit_points
def backbone(self):
"""
Return the set of nodes constituting the graph's backbone.
(i.e. the nodes that every path starting from the entry point
must go through). By construction, it is non-empty: it contains
at least the entry point.
"""
return self._post_doms[self._entry_point]
def loops(self):
"""
Return a dictionary of {node -> loop} mapping each loop header
to the loop (a Loop instance) starting with it.
"""
return self._loops
def in_loops(self, node):
"""
Return the list of Loop objects the *node* belongs to,
from innermost to outermost.
"""
return [self._loops[x] for x in self._in_loops.get(node, ())]
def dead_nodes(self):
"""
Return the set of dead nodes (eliminated from the graph).
"""
return self._dead_nodes
def nodes(self):
"""
Return the set of live nodes.
"""
return self._nodes
def topo_order(self):
"""
Return the sequence of nodes in topological order (ignoring back
edges).
"""
return self._topo_order
def topo_sort(self, nodes, reverse=False):
"""
Iterate over the *nodes* in topological order (ignoring back edges).
The sort isn't guaranteed to be stable.
"""
nodes = set(nodes)
it = self._topo_order
if reverse:
it = reversed(it)
for n in it:
if n in nodes:
yield n
def dump(self, file=None):
"""
Dump extensive debug information.
"""
import pprint
file = file or sys.stdout
if 1:
print("CFG adjacency lists:", file=file)
self._dump_adj_lists(file)
print("CFG dominators:", file=file)
pprint.pprint(self._doms, stream=file)
print("CFG post-dominators:", file=file)
pprint.pprint(self._post_doms, stream=file)
print("CFG back edges:", sorted(self._back_edges), file=file)
print("CFG loops:", file=file)
pprint.pprint(self._loops, stream=file)
print("CFG node-to-loops:", file=file)
pprint.pprint(self._in_loops, stream=file)
print("CFG backbone:", file=file)
pprint.pprint(self.backbone(), stream=file)
def render_dot(self, filename="numba_cfg.dot"):
"""Render the controlflow graph with GraphViz DOT via the
``graphviz`` python binding.
Returns
-------
g : graphviz.Digraph
Use `g.view()` to open the graph in the default PDF application.
"""
try:
import graphviz as gv
except ImportError:
raise ImportError(
"The feature requires `graphviz` but it is not available. "
"Please install with `pip install graphviz`"
)
g = gv.Digraph(filename=filename)
# Populate the nodes
for n in self._nodes:
g.node(str(n))
# Populate the edges
for n in self._nodes:
for edge in self._succs[n]:
g.edge(str(n), str(edge))
return g
# Internal APIs
def _add_edge(self, from_, to, data=None):
# This internal version allows adding edges to/from unregistered
# (ghost) nodes.
self._preds[to].add(from_)
self._succs[from_].add(to)
self._edge_data[from_, to] = data
def _remove_node_edges(self, node):
for succ in self._succs.pop(node, ()):
self._preds[succ].remove(node)
del self._edge_data[node, succ]
for pred in self._preds.pop(node, ()):
self._succs[pred].remove(node)
del self._edge_data[pred, node]
def _dfs(self, entries=None):
if entries is None:
entries = (self._entry_point,)
seen = set()
stack = list(entries)
while stack:
node = stack.pop()
if node not in seen:
yield node
seen.add(node)
for succ in self._succs[node]:
stack.append(succ)
def _eliminate_dead_blocks(self):
"""
Eliminate all blocks not reachable from the entry point, and
stash them into self._dead_nodes.
"""
live = set()
for node in self._dfs():
live.add(node)
self._dead_nodes = self._nodes - live
self._nodes = live
# Remove all edges leading from dead nodes
for dead in self._dead_nodes:
self._remove_node_edges(dead)
def _find_exit_points(self):
"""
Compute the graph's exit points.
"""
exit_points = set()
for n in self._nodes:
if not self._succs.get(n):
exit_points.add(n)
return exit_points
def _find_postorder(self):
succs = self._succs
back_edges = self._back_edges
post_order = []
seen = set()
post_order = []
# DFS
def dfs_rec(node):
if node not in seen:
seen.add(node)
stack.append((post_order.append, node))
for dest in succs[node]:
if (node, dest) not in back_edges:
stack.append((dfs_rec, dest))
stack = [(dfs_rec, self._entry_point)]
while stack:
cb, data = stack.pop()
cb(data)
return post_order
def _find_immediate_dominators(self):
# The algorithm implemented computes the immediate dominator
# for each node in the CFG which is equivalent to build a dominator tree
# Based on the implementation from NetworkX
# library - nx.immediate_dominators
# https://github.com/networkx/networkx/blob/858e7cb183541a78969fed0cbcd02346f5866c02/networkx/algorithms/dominance.py # noqa: E501
# References:
# Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy
# A Simple, Fast Dominance Algorithm
# https://www.cs.rice.edu/~keith/EMBED/dom.pdf
def intersect(u, v):
while u != v:
while idx[u] < idx[v]:
u = idom[u]
while idx[u] > idx[v]:
v = idom[v]
return u
entry = self._entry_point
preds_table = self._preds
order = self._find_postorder()
idx = {e: i for i, e in enumerate(order)} # index of each node
idom = {entry : entry}
order.pop()
order.reverse()
changed = True
while changed:
changed = False
for u in order:
new_idom = functools.reduce(intersect,
(v for v in preds_table[u]
if v in idom))
if u not in idom or idom[u] != new_idom:
idom[u] = new_idom
changed = True
return idom
def _find_dominator_tree(self):
idom = self._idom
domtree = _DictOfContainers(set)
for u, v in idom.items():
# v dominates u
if u not in domtree:
domtree[u] = set()
if u != v:
domtree[v].add(u)
return domtree
def _find_dominance_frontier(self):
idom = self._idom
preds_table = self._preds
df = {u: set() for u in idom}
for u in idom:
if len(preds_table[u]) < 2:
continue
for v in preds_table[u]:
while v != idom[u]:
df[v].add(u)
v = idom[v]
return df
def _find_dominators_internal(self, post=False):
# See theoretical description in
# http://en.wikipedia.org/wiki/Dominator_%28graph_theory%29
# The algorithm implemented here uses a todo-list as described
# in http://pages.cs.wisc.edu/~fischer/cs701.f08/finding.loops.html
if post:
entries = set(self._exit_points)
preds_table = self._succs
succs_table = self._preds
else:
entries = set([self._entry_point])
preds_table = self._preds
succs_table = self._succs
if not entries:
raise RuntimeError("no entry points: dominator algorithm "
"cannot be seeded")
doms = {}
for e in entries:
doms[e] = set([e])
todo = []
for n in self._nodes:
if n not in entries:
doms[n] = set(self._nodes)
todo.append(n)
while todo:
n = todo.pop()
if n in entries:
continue
new_doms = set([n])
preds = preds_table[n]
if preds:
new_doms |= functools.reduce(set.intersection,
[doms[p] for p in preds])
if new_doms != doms[n]:
assert len(new_doms) < len(doms[n])
doms[n] = new_doms
todo.extend(succs_table[n])
return doms
def _find_dominators(self):
return self._find_dominators_internal(post=False)
def _find_post_dominators(self):
# To handle infinite loops correctly, we need to add a dummy
# exit point, and link members of infinite loops to it.
dummy_exit = object()
self._exit_points.add(dummy_exit)
for loop in self._loops.values():
if not loop.exits:
for b in loop.body:
self._add_edge(b, dummy_exit)
pdoms = self._find_dominators_internal(post=True)
# Fix the _post_doms table to make no reference to the dummy exit
del pdoms[dummy_exit]
for doms in pdoms.values():
doms.discard(dummy_exit)
self._remove_node_edges(dummy_exit)
self._exit_points.remove(dummy_exit)
return pdoms
# Finding loops and back edges: see
# http://pages.cs.wisc.edu/~fischer/cs701.f08/finding.loops.html
def _find_back_edges(self, stats=None):
"""
Find back edges. An edge (src, dest) is a back edge if and
only if *dest* dominates *src*.
"""
# Prepare stats to capture execution information
if stats is not None:
if not isinstance(stats, dict):
raise TypeError(f"*stats* must be a dict; got {type(stats)}")
stats.setdefault('iteration_count', 0)
# Uses a simple DFS to find back-edges.
# The new algorithm is faster than the previous dominator based
# algorithm.
back_edges = set()
# stack: keeps track of the traversal path
stack = []
# succs_state: keep track of unvisited successors of a node
succs_state = {}
entry_point = self.entry_point()
checked = set()
def push_state(node):
stack.append(node)
succs_state[node] = [dest for dest in self._succs[node]]
push_state(entry_point)
# Keep track for iteration count for debugging
iter_ct = 0
while stack:
iter_ct += 1
tos = stack[-1]
tos_succs = succs_state[tos]
# Are there successors not checked?
if tos_succs:
# Check the next successor
cur_node = tos_succs.pop()
# Is it in our traversal path?
if cur_node in stack:
# Yes, it's a backedge
back_edges.add((tos, cur_node))
elif cur_node not in checked:
# Push
push_state(cur_node)
else:
# Checked all successors. Pop
stack.pop()
checked.add(tos)
if stats is not None:
stats['iteration_count'] += iter_ct
return back_edges
def _find_topo_order(self):
succs = self._succs
back_edges = self._back_edges
post_order = []
seen = set()
def _dfs_rec(node):
if node not in seen:
seen.add(node)
for dest in succs[node]:
if (node, dest) not in back_edges:
_dfs_rec(dest)
post_order.append(node)
_dfs_rec(self._entry_point)
post_order.reverse()
return post_order
def _find_descendents(self):
descs = {}
for node in reversed(self._topo_order):
descs[node] = node_descs = set()
for succ in self._succs[node]:
if (node, succ) not in self._back_edges:
node_descs.add(succ)
node_descs.update(descs[succ])
return descs
def _find_loops(self):
"""
Find the loops defined by the graph's back edges.
"""
bodies = {}
for src, dest in self._back_edges:
# The destination of the back edge is the loop header
header = dest
# Build up the loop body from the back edge's source node,
# up to the source header.
body = set([header])
queue = [src]
while queue:
n = queue.pop()
if n not in body:
body.add(n)
queue.extend(self._preds[n])
# There can be several back edges to a given loop header;
# if so, merge the resulting body fragments.
if header in bodies:
bodies[header].update(body)
else:
bodies[header] = body
# Create a Loop object for each header.
loops = {}
for header, body in bodies.items():
entries = set()
exits = set()
for n in body:
entries.update(self._preds[n] - body)
exits.update(self._succs[n] - body)
loop = Loop(header=header, body=body, entries=entries, exits=exits)
loops[header] = loop
return loops
def _find_in_loops(self):
loops = self._loops
# Compute the loops to which each node belongs.
in_loops = dict((n, []) for n in self._nodes)
# Sort loops from longest to shortest
# This ensures that outer loops will come before inner loops
for loop in sorted(loops.values(), key=lambda loop: len(loop.body)):
for n in loop.body:
in_loops[n].append(loop.header)
return in_loops
def _dump_adj_lists(self, file):
adj_lists = dict((src, sorted(list(dests)))
for src, dests in self._succs.items())
import pprint
pprint.pprint(adj_lists, stream=file)
def __eq__(self, other):
if not isinstance(other, CFGraph):
return NotImplemented
for x in ['_nodes', '_edge_data', '_entry_point', '_preds', '_succs']:
this = getattr(self, x, None)
that = getattr(other, x, None)
if this != that:
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
| CFGraph |
python | kamyu104__LeetCode-Solutions | Python/shortest-string-that-contains-three-strings.py | {
"start": 81,
"end": 1521
} | class ____(object):
def minimumString(self, a, b, c):
"""
:type a: str
:type b: str
:type c: str
:rtype: str
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j != -1 and pattern[j+1] != pattern[i]:
j = prefix[j]
if pattern[j+1] == pattern[i]:
j += 1
prefix[i] = j
return prefix
def KMP(text, pattern):
prefix = getPrefix(pattern)
j = -1
for i in xrange(len(text)):
while j != -1 and pattern[j+1] != text[i]:
j = prefix[j]
if pattern[j+1] == text[i]:
j += 1
if j+1 == len(pattern):
return i-j
return -1
def merge(a, b):
if KMP(b, a) != -1:
return b
prefix = getPrefix(b+'#'+a)
l = prefix[-1]+1 # longest prefix suffix length
return a+b[l:]
result = [merge(a, merge(b, c)), merge(a, merge(c, b)),
merge(b, merge(a, c)), merge(b, merge(c, a)),
merge(c, merge(a, b)), merge(c, merge(b, a))]
return min(result, key=lambda x: (len(x), x))
# Time: O(l^2)
# Space: O(l)
# brute force
| Solution |
python | bokeh__bokeh | src/bokeh/util/callback_manager.py | {
"start": 2324,
"end": 4349
} | class ____:
''' A mixin class to provide an interface for registering and
triggering event callbacks on the Python side.
'''
document: Document | None
id: ID
subscribed_events: set[str]
_event_callbacks: dict[str, list[EventCallback]]
def __init__(self, *args: Any, **kw: Any) -> None:
super().__init__(*args, **kw)
self._event_callbacks = defaultdict(list)
def on_event(self, event: str | type[Event], *callbacks: EventCallback) -> None:
''' Run callbacks when the specified event occurs on this Model
Not all Events are supported for all Models.
See specific Events in :ref:`bokeh.events` for more information on
which Models are able to trigger them.
'''
if not isinstance(event, str) and issubclass(event, Event):
event = event.event_name
for callback in callbacks:
if _nargs(callback) != 0:
_check_callback(callback, ('event',), what='Event callback')
self._event_callbacks[event].append(callback)
self.subscribed_events.add(event)
def _trigger_event(self, event: ModelEvent) -> None:
def invoke() -> None:
for callback in self._event_callbacks.get(event.event_name, []):
if event.model is not None and self.id == event.model.id:
if _nargs(callback) == 0:
cast(EventCallbackWithoutEvent, callback)()
else:
cast(EventCallbackWithEvent, callback)(event)
if self.document is not None:
from ..model import Model
self.document.callbacks.notify_event(cast(Model, self), event, invoke)
else:
invoke()
def _update_event_callbacks(self) -> None:
if self.document is None:
return
for key in self._event_callbacks:
from ..model import Model
self.document.callbacks.subscribe(key, cast(Model, self))
| EventCallbackManager |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 45353,
"end": 48969
} | class ____(base_classes.Table):
def __init__(self, parent, key):
self._parent = parent
self.xl = parent.xl.list_objects[key]
@property
def parent(self):
return self._parent
@property
def api(self):
return self.xl
@property
def name(self):
return self.xl.name.get()
@name.setter
def name(self, value):
self.xl.name.set(value)
self.xl = self.parent.xl.list_objects[value]
@property
def data_body_range(self):
if self.xl.cell_table.get() == kw.missing_value:
return
else:
return Range(self.parent, self.xl.cell_table.get_address())
@property
def display_name(self):
return self.xl.display_name.get()
@display_name.setter
def display_name(self, value):
# Changing the display_name also changes the name
self.xl.display_name.set(value)
self.xl = self.parent.xl.list_objects[value]
@property
def header_row_range(self):
if self.xl.header_row.get() == kw.missing_value:
return
else:
return Range(self.parent, self.xl.header_row.get_address())
@property
def insert_row_range(self):
if self.xl.insert_row.get() == kw.missing_value:
return
else:
return Range(self.parent, self.xl.insert_row.get_address())
@property
def range(self):
return Range(self.parent, self.xl.range_object.get_address())
@property
def show_autofilter(self):
return self.xl.show_autofilter.get()
@show_autofilter.setter
def show_autofilter(self, value):
self.xl.show_autofilter.set(value)
@property
def show_headers(self):
return self.xl.show_headers.get()
@show_headers.setter
def show_headers(self, value):
self.xl.show_headers.set(value)
@property
def show_table_style_column_stripes(self):
return self.xl.show_table_style_column_stripes.get()
@show_table_style_column_stripes.setter
def show_table_style_column_stripes(self, value):
self.xl.show_table_style_column_stripes.set(value)
@property
def show_table_style_first_column(self):
return self.xl.show_table_style_first_column.get()
@show_table_style_first_column.setter
def show_table_style_first_column(self, value):
self.xl.show_table_style_first_column.set(value)
@property
def show_table_style_last_column(self):
return self.xl.show_table_style_last_column.get()
@show_table_style_last_column.setter
def show_table_style_last_column(self, value):
self.xl.show_table_style_last_column.set(value)
@property
def show_table_style_row_stripes(self):
return self.xl.show_table_style_row_stripes.get()
@show_table_style_row_stripes.setter
def show_table_style_row_stripes(self, value):
self.xl.show_table_style_row_stripes.set(value)
@property
def show_totals(self):
return self.xl.total.get()
@show_totals.setter
def show_totals(self, value):
self.xl.total.set(value)
@property
def table_style(self):
return self.xl.table_style.properties().get(kw.name)
@table_style.setter
def table_style(self, value):
self.xl.table_style.set(value)
@property
def totals_row_range(self):
if self.xl.total_row.get() == kw.missing_value:
return
else:
return Range(self.parent, self.xl.total_row.get_address())
def resize(self, range):
self.xl.resize(range=range.api)
| Table |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py | {
"start": 11965,
"end": 12431
} | class ____(PreTrainedModel):
config: Qwen2_5_VLConfig
base_model_prefix = "model"
input_modalities = ("image", "video", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen2_5_VLDecoderLayer", "Qwen2_5_VLVisionBlock"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_sdpa = True
_can_compile_fullgraph = True
_supports_attention_backend = True
| Qwen2_5_VLPreTrainedModel |
python | doocs__leetcode | solution/0400-0499/0429.N-ary Tree Level Order Traversal/Solution.py | {
"start": 152,
"end": 545
} | class ____:
def levelOrder(self, root: 'Node') -> List[List[int]]:
ans = []
if root is None:
return ans
q = deque([root])
while q:
t = []
for _ in range(len(q)):
root = q.popleft()
t.append(root.val)
q.extend(root.children)
ans.append(t)
return ans
| Solution |
python | getsentry__sentry | src/sentry/models/files/fileblobowner.py | {
"start": 246,
"end": 537
} | class ____(AbstractFileBlobOwner):
__relocation_scope__ = RelocationScope.Excluded
blob = FlexibleForeignKey("sentry.FileBlob")
class Meta:
app_label = "sentry"
db_table = "sentry_fileblobowner"
unique_together = (("blob", "organization_id"),)
| FileBlobOwner |
python | sanic-org__sanic | sanic/logging/formatter.py | {
"start": 732,
"end": 3989
} | class ____(logging.Formatter):
"""
Automatically sets up the formatter based on the environment.
It will switch between the Debug and Production formatters based upon
how the environment is set up. Additionally, it will automatically
detect if the output is a TTY and colorize the output accordingly.
"""
SETUP = False
ATTY = is_atty()
NO_COLOR = os.environ.get("SANIC_NO_COLOR", "false").lower() == "true"
LOG_EXTRA = os.environ.get("SANIC_LOG_EXTRA", "true").lower() == "true"
IDENT = os.environ.get("SANIC_WORKER_IDENTIFIER", "Main ") or "Main "
DATE_FORMAT = "%Y-%m-%d %H:%M:%S %z"
IDENT_LIMIT = 5
MESSAGE_START = 42
PREFIX_FORMAT = (
f"{c.GREY}%(ident)s{{limit}} %(asctime)s {c.END}"
"%(levelname)s: {start}"
)
MESSAGE_FORMAT = "%(message)s"
def __init__(self, *args) -> None:
args_list = list(args)
if not args:
args_list.append(self._make_format())
elif args and not args[0]:
args_list[0] = self._make_format()
if len(args_list) < 2:
args_list.append(self.DATE_FORMAT)
elif not args[1]:
args_list[1] = self.DATE_FORMAT
super().__init__(*args_list)
def format(self, record: logging.LogRecord) -> str:
record.ident = self.IDENT
self._set_levelname(record)
output = super().format(record)
if self.LOG_EXTRA:
output += self._log_extra(record)
return output
def _set_levelname(self, record: logging.LogRecord) -> None:
if (
self.ATTY
and not self.NO_COLOR
and (color := LEVEL_COLORS.get(record.levelno))
):
record.levelname = f"{color}{record.levelname}{c.END}"
def _make_format(self) -> str:
limit = CONTROL_LIMIT_IDENT.format(limit=self.IDENT_LIMIT)
start = CONTROL_LIMIT_START.format(start=self.MESSAGE_START)
base_format = self.PREFIX_FORMAT + self.MESSAGE_FORMAT
fmt = base_format.format(limit=limit, start=start)
if not self.ATTY or self.NO_COLOR:
return CONTROL_RE.sub("", fmt)
return fmt
def _log_extra(self, record: logging.LogRecord, indent: int = 0) -> str:
extra_lines = [""]
for key, value in record.__dict__.items():
if key not in DEFAULT_FIELDS:
extra_lines.append(self._format_key_value(key, value, indent))
return "\n".join(extra_lines)
def _format_key_value(self, key, value, indent):
indentation = " " * indent
template = (
f"{indentation} {{c.YELLOW}}{{key}}{{c.END}}={{value}}"
if self.ATTY and not self.NO_COLOR
else f"{indentation}{{key}}={{value}}"
)
if isinstance(value, dict):
nested_lines = [template.format(c=c, key=key, value="")]
for nested_key, nested_value in value.items():
nested_lines.append(
self._format_key_value(
nested_key, nested_value, indent + 2
)
)
return "\n".join(nested_lines)
else:
return template.format(c=c, key=key, value=value)
| AutoFormatter |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_types07.py | {
"start": 315,
"end": 1937
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("types07.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels",
]
def test_write_nan_and_inf(self):
"""Test writing special numbers."""
workbook = Workbook(self.got_filename, {"nan_inf_to_errors": True})
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, float("nan"))
worksheet.write(1, 0, float("inf"))
worksheet.write(2, 0, float("-inf"))
workbook.close()
self.assertExcelEqual()
def test_write_nan_and_inf_write_number(self):
"""Test writing special numbers."""
workbook = Workbook(self.got_filename, {"nan_inf_to_errors": True})
worksheet = workbook.add_worksheet()
worksheet.write_number(0, 0, float("nan"))
worksheet.write_number(1, 0, float("inf"))
worksheet.write_number(2, 0, float("-inf"))
workbook.close()
self.assertExcelEqual()
def test_write_nan_and_inf_write_as_string(self):
"""Test writing special numbers."""
workbook = Workbook(
self.got_filename, {"nan_inf_to_errors": True, "strings_to_numbers": True}
)
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, "nan")
worksheet.write(1, 0, "inf")
worksheet.write(2, 0, "-inf")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | scikit-learn__scikit-learn | doc/sphinxext/allow_nan_estimators.py | {
"start": 270,
"end": 2187
} | class ____(Directive):
@staticmethod
def make_paragraph_for_estimator_type(estimator_type):
intro = nodes.list_item()
intro += nodes.strong(text="Estimators that allow NaN values for type ")
intro += nodes.literal(text=f"{estimator_type}")
intro += nodes.strong(text=":\n")
exists = False
lst = nodes.bullet_list()
for name, est_class in all_estimators(type_filter=estimator_type):
with suppress(SkipTest):
# Here we generate the text only for one instance. This directive
# should not be used for meta-estimators where tags depend on the
# sub-estimator.
est = next(_construct_instances(est_class))
if est.__sklearn_tags__().input_tags.allow_nan:
module_name = ".".join(est_class.__module__.split(".")[:2])
class_title = f"{est_class.__name__}"
class_url = f"./generated/{module_name}.{class_title}.html"
item = nodes.list_item()
para = nodes.paragraph()
para += nodes.reference(
class_title, text=class_title, internal=False, refuri=class_url
)
exists = True
item += para
lst += item
intro += lst
return [intro] if exists else None
def run(self):
lst = nodes.bullet_list()
for i in ["cluster", "regressor", "classifier", "transformer"]:
item = self.make_paragraph_for_estimator_type(i)
if item is not None:
lst += item
return [lst]
def setup(app):
app.add_directive("allow_nan_estimators", AllowNanEstimators)
return {
"version": "0.1",
"parallel_read_safe": True,
"parallel_write_safe": True,
}
| AllowNanEstimators |
python | doocs__leetcode | solution/1900-1999/1960.Maximum Product of the Length of Two Palindromic Substrings/Solution.py | {
"start": 0,
"end": 1124
} | class ____:
def maxProduct(self, s: str) -> int:
n = len(s)
hlen = [0] * n
center = right = 0
for i in range(n):
if i < right:
hlen[i] = min(right - i, hlen[2 * center - i])
while (
0 <= i - 1 - hlen[i]
and i + 1 + hlen[i] < len(s)
and s[i - 1 - hlen[i]] == s[i + 1 + hlen[i]]
):
hlen[i] += 1
if right < i + hlen[i]:
center, right = i, i + hlen[i]
prefix = [0] * n
suffix = [0] * n
for i in range(n):
prefix[i + hlen[i]] = max(prefix[i + hlen[i]], 2 * hlen[i] + 1)
suffix[i - hlen[i]] = max(suffix[i - hlen[i]], 2 * hlen[i] + 1)
for i in range(1, n):
prefix[~i] = max(prefix[~i], prefix[~i + 1] - 2)
suffix[i] = max(suffix[i], suffix[i - 1] - 2)
for i in range(1, n):
prefix[i] = max(prefix[i - 1], prefix[i])
suffix[~i] = max(suffix[~i], suffix[~i + 1])
return max(prefix[i - 1] * suffix[i] for i in range(1, n))
| Solution |
python | mlflow__mlflow | mlflow/genai/scorers/builtin_scorers.py | {
"start": 9300,
"end": 12023
} | class ____(Judge):
"""
Abstract base class for built-in scorers that share a common implementation.
All built-in scorers should inherit from this class.
"""
name: str
required_columns: set[str] = set()
@property
@abstractmethod
def instructions(self) -> str:
"""
Get the instructions of what this scorer evaluates.
"""
def model_dump(self, **kwargs) -> dict[str, Any]:
"""Override model_dump to handle builtin scorer serialization."""
pydantic_model_data = pydantic.BaseModel.model_dump(self, mode="json", **kwargs)
pydantic_model_data["instructions"] = self.instructions
serialized = SerializedScorer(
name=self.name,
description=self.description,
aggregations=self.aggregations,
mlflow_version=mlflow.__version__,
serialization_version=_SERIALIZATION_VERSION,
builtin_scorer_class=self.__class__.__name__,
builtin_scorer_pydantic_data=pydantic_model_data,
)
return asdict(serialized)
@classmethod
def model_validate(cls, obj: SerializedScorer | dict[str, Any]) -> "BuiltInScorer":
"""Override model_validate to handle builtin scorer deserialization."""
from mlflow.genai.scorers import builtin_scorers
if isinstance(obj, SerializedScorer):
serialized = obj
else:
if not isinstance(obj, dict) or "builtin_scorer_class" not in obj:
raise MlflowException.invalid_parameter_value(
f"Invalid builtin scorer data: expected a dictionary with "
f"'builtin_scorer_class' field, got {type(obj).__name__}."
)
try:
serialized = SerializedScorer(**obj)
except Exception as e:
raise MlflowException.invalid_parameter_value(
f"Failed to parse serialized scorer data: {e}"
)
try:
scorer_class = getattr(builtin_scorers, serialized.builtin_scorer_class)
except AttributeError:
raise MlflowException.invalid_parameter_value(
f"Unknown builtin scorer class: {serialized.builtin_scorer_class}"
)
constructor_args = serialized.builtin_scorer_pydantic_data or {}
return scorer_class(**constructor_args)
def validate_columns(self, columns: set[str]) -> None:
if missing_columns := self.required_columns - columns:
raise MissingColumnsException(self.name, missing_columns)
@property
def kind(self) -> ScorerKind:
return ScorerKind.BUILTIN
@format_docstring(_MODEL_API_DOC)
| BuiltInScorer |
python | dateutil__dateutil | src/dateutil/rrule.py | {
"start": 50715,
"end": 54400
} | class ____(rrulebase):
""" The rruleset type allows more complex recurrence setups, mixing
multiple rules, dates, exclusion rules, and exclusion dates. The type
constructor takes the following keyword arguments:
:param cache: If True, caching of results will be enabled, improving
performance of multiple queries considerably. """
class _genitem(object):
def __init__(self, genlist, gen):
try:
self.dt = advance_iterator(gen)
genlist.append(self)
except StopIteration:
pass
self.genlist = genlist
self.gen = gen
def __next__(self):
try:
self.dt = advance_iterator(self.gen)
except StopIteration:
if self.genlist[0] is self:
heapq.heappop(self.genlist)
else:
self.genlist.remove(self)
heapq.heapify(self.genlist)
next = __next__
def __lt__(self, other):
return self.dt < other.dt
def __gt__(self, other):
return self.dt > other.dt
def __eq__(self, other):
return self.dt == other.dt
def __ne__(self, other):
return self.dt != other.dt
def __init__(self, cache=False):
super(rruleset, self).__init__(cache)
self._rrule = []
self._rdate = []
self._exrule = []
self._exdate = []
@_invalidates_cache
def rrule(self, rrule):
""" Include the given :py:class:`rrule` instance in the recurrence set
generation. """
self._rrule.append(rrule)
@_invalidates_cache
def rdate(self, rdate):
""" Include the given :py:class:`datetime` instance in the recurrence
set generation. """
self._rdate.append(rdate)
@_invalidates_cache
def exrule(self, exrule):
""" Include the given rrule instance in the recurrence set exclusion
list. Dates which are part of the given recurrence rules will not
be generated, even if some inclusive rrule or rdate matches them.
"""
self._exrule.append(exrule)
@_invalidates_cache
def exdate(self, exdate):
""" Include the given datetime instance in the recurrence set
exclusion list. Dates included that way will not be generated,
even if some inclusive rrule or rdate matches them. """
self._exdate.append(exdate)
def _iter(self):
rlist = []
self._rdate.sort()
self._genitem(rlist, iter(self._rdate))
for gen in [iter(x) for x in self._rrule]:
self._genitem(rlist, gen)
exlist = []
self._exdate.sort()
self._genitem(exlist, iter(self._exdate))
for gen in [iter(x) for x in self._exrule]:
self._genitem(exlist, gen)
lastdt = None
total = 0
heapq.heapify(rlist)
heapq.heapify(exlist)
while rlist:
ritem = rlist[0]
if not lastdt or lastdt != ritem.dt:
while exlist and exlist[0] < ritem:
exitem = exlist[0]
advance_iterator(exitem)
if exlist and exlist[0] is exitem:
heapq.heapreplace(exlist, exitem)
if not exlist or ritem != exlist[0]:
total += 1
yield ritem.dt
lastdt = ritem.dt
advance_iterator(ritem)
if rlist and rlist[0] is ritem:
heapq.heapreplace(rlist, ritem)
self._len = total
| rruleset |
python | ray-project__ray | python/ray/train/v2/_internal/execution/worker_group/poll.py | {
"start": 3866,
"end": 4111
} | class ____:
"""Represents a poll task for a worker.
Attributes:
start_time: The time when the poll task was started.
task: The ObjectRef representing the poll task.
"""
start_time: float
task: ObjectRef
| PollTask |
python | scrapy__scrapy | tests/mockserver/ftp.py | {
"start": 377,
"end": 1638
} | class ____:
"""Creates an FTP server on port 2121 with a default passwordless user
(anonymous) and a temporary root path that you can read from the
:attr:`path` attribute."""
def __enter__(self):
self.path = Path(mkdtemp())
self.proc = Popen(
[sys.executable, "-u", "-m", "tests.mockserver.ftp", "-d", str(self.path)],
stderr=PIPE,
env=get_script_run_env(),
)
for line in self.proc.stderr:
if b"starting FTP server" in line:
break
return self
def __exit__(self, exc_type, exc_value, traceback):
rmtree(str(self.path))
self.proc.kill()
self.proc.communicate()
def url(self, path):
return "ftp://127.0.0.1:2121/" + path
def main() -> None:
parser = ArgumentParser()
parser.add_argument("-d", "--directory")
args = parser.parse_args()
authorizer = DummyAuthorizer()
full_permissions = "elradfmwMT"
authorizer.add_anonymous(args.directory, perm=full_permissions)
handler = FTPHandler
handler.authorizer = authorizer
address = ("127.0.0.1", 2121)
server = FTPServer(address, handler)
server.serve_forever()
if __name__ == "__main__":
main()
| MockFTPServer |
python | ansible__ansible | lib/ansible/module_utils/urls.py | {
"start": 10513,
"end": 10824
} | class ____(urllib.request.HTTPHandler):
"""Handler for Unix urls"""
def __init__(self, unix_socket, **kwargs):
super().__init__(**kwargs)
self._unix_socket = unix_socket
def http_open(self, req):
return self.do_open(UnixHTTPConnection(self._unix_socket), req)
| UnixHTTPHandler |
python | huggingface__transformers | src/transformers/models/regnet/modeling_regnet.py | {
"start": 9341,
"end": 10435
} | class ____(PreTrainedModel):
config: RegNetConfig
base_model_prefix = "regnet"
main_input_name = "pixel_values"
_no_split_modules = ["RegNetYLayer"]
@torch.no_grad()
def _init_weights(self, module):
if isinstance(module, nn.Conv2d):
init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
# copied from the `reset_parameters` method of `class Linear(Module)` in `torch`.
elif isinstance(module, nn.Linear):
init.kaiming_uniform_(module.weight, a=math.sqrt(5))
if module.bias is not None:
fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(module.weight)
bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
init.uniform_(module.bias, -bound, bound)
elif isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)):
init.constant_(module.weight, 1)
init.constant_(module.bias, 0)
@auto_docstring
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
| RegNetPreTrainedModel |
python | joblib__joblib | joblib/externals/loky/backend/process.py | {
"start": 1683,
"end": 2018
} | class ____(bytes):
def __reduce__(self):
try:
assert_spawning(self)
except RuntimeError:
raise TypeError(
"Pickling an AuthenticationKey object is "
"disallowed for security reasons"
)
return AuthenticationKey, (bytes(self),)
| AuthenticationKey |
python | walkccc__LeetCode | solutions/144. Binary Tree Preorder Traversal/144-2.py | {
"start": 0,
"end": 341
} | class ____:
def preorderTraversal(self, root: TreeNode | None) -> list[int]:
if not root:
return []
ans = []
stack = [root]
while stack:
node = stack.pop()
ans.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return ans
| Solution |
python | pytorch__pytorch | test/distributed/checkpoint/test_dtensor_resharding.py | {
"start": 6060,
"end": 12716
} | class ____(DTensorTestBase):
"""
Test DCP reshard for DTensor with placements changes and mesh_tensor change.
"""
@with_comms
@with_temp_dir
@skip_if_lt_x_gpu(2)
def test_1d_to_2d_reshard_mesh_change(self) -> None:
CHECKPOINT_DIR = self.temp_dir
for placements_1d in ONE_D_PLACEMENTS:
global_tensor = torch.arange(16, dtype=torch.float).view(4, 4)
mesh_shape = (self.world_size,)
mesh_1d = init_device_mesh(self.device_type, mesh_shape)
dtensor = distribute_tensor(
global_tensor, mesh_1d, placements=placements_1d
)
state_dict_to_save = {"dtensor": dtensor}
dist_cp.save(
state_dict=state_dict_to_save,
storage_writer=dist_cp.FileSystemWriter(path=CHECKPOINT_DIR),
planner=dist_cp.DefaultSavePlanner(),
)
for placements_2d in TWO_D_PLACEMENTS:
mesh_shape = (2, self.world_size // 2)
mesh_2d = init_device_mesh(self.device_type, mesh_shape)
zero_dtensor = zeros(
[4, 4], device_mesh=mesh_2d, placements=placements_2d
)
state_dict_to_load = {"dtensor": zero_dtensor}
dist_cp.load(
state_dict=state_dict_to_load,
storage_reader=dist_cp.FileSystemReader(CHECKPOINT_DIR),
planner=dist_cp.DefaultLoadPlanner(),
)
# materialzie the whole tensor to compare with the original global_tensor
state_dict_to_load["dtensor"] = state_dict_to_load[
"dtensor"
].redistribute(
mesh_2d,
placements=[Replicate(), Replicate()],
)
self.assertEqual(
global_tensor, state_dict_to_load["dtensor"].to_local()
)
@with_comms
@with_temp_dir
@skip_if_lt_x_gpu(4)
def test_2d_to_1d_reshard_mesh_change(self) -> None:
CHECKPOINT_DIR = self.temp_dir
for placements_2d in TWO_D_PLACEMENTS:
global_tensor = torch.arange(16, dtype=torch.float).view(4, 4)
mesh_shape = (2, self.world_size // 2)
mesh_2d = init_device_mesh(self.device_type, mesh_shape)
dtensor = distribute_tensor(
global_tensor, mesh_2d, placements=placements_2d
)
state_dict_to_save = {"dtensor": dtensor}
dist_cp.save(
state_dict=state_dict_to_save,
storage_writer=dist_cp.FileSystemWriter(path=CHECKPOINT_DIR),
planner=dist_cp.DefaultSavePlanner(),
)
for placements_1d in ONE_D_PLACEMENTS:
mesh_shape = (self.world_size,)
mesh_1d = init_device_mesh(self.device_type, mesh_shape)
zero_dtensor = zeros(
[4, 4], device_mesh=mesh_1d, placements=placements_1d
)
state_dict_to_load = {"dtensor": zero_dtensor}
dist_cp.load(
state_dict=state_dict_to_load,
storage_reader=dist_cp.FileSystemReader(CHECKPOINT_DIR),
planner=dist_cp.DefaultLoadPlanner(),
)
# materialzie the whole tensor to compare with the original global_tensor
state_dict_to_load["dtensor"] = state_dict_to_load[
"dtensor"
].redistribute(
mesh_1d,
placements=[Replicate()],
)
self.assertEqual(
global_tensor, state_dict_to_load["dtensor"].to_local()
)
@with_comms
@with_temp_dir
@skip_if_lt_x_gpu(2)
def test_dtensor_checkpoint_resharding_with_empty_shard(self):
"""
Test dtensor checkpoint resharding with dtensor containing empty shards.
"""
tensor = torch.rand(1).to(self.device_type)
mesh = init_device_mesh(self.device_type, (self.world_size,))
dtensor = distribute_tensor(tensor, mesh, [Shard(0)])
ref_state_dict = {"dtensor": dtensor}
dist_cp.save(
state_dict=ref_state_dict,
storage_writer=dist_cp.FileSystemWriter(path=self.temp_dir),
)
tensor = torch.rand(1).to(self.device_type)
mesh_2 = init_device_mesh(self.device_type, (2, self.world_size // 2))
dtensor = distribute_tensor(tensor, mesh_2, [Shard(0), Shard(0)])
state_dict = {"dtensor": dtensor}
dist_cp.load(
state_dict=state_dict,
storage_reader=dist_cp.FileSystemReader(self.temp_dir),
)
@with_comms
@with_temp_dir
@skip_if_lt_x_gpu(4)
def test_dtensor_checkpoint_with_uneven_shards(self) -> None:
"""
Saving a dtensor with uneven shards.
rank 0 -> [[0], [1], [2], [3]]
rank 1 -> [[4], [5], [6], [7]]
rank 2 -> [[8], [9], [10], [11]]
rank 3 -> [[12], [13]]
"""
CHECKPOINT_DIR = self.temp_dir
mesh_shape = (self.world_size,)
mesh_1 = init_device_mesh(self.device_type, mesh_shape)
my_rank = dist.get_rank()
# Make the last shard uneven
if my_rank == self.world_size - 1:
local_tensor = torch.arange(
start=my_rank * 4, end=(my_rank * 4) + 2, dtype=torch.float
).view(2, 1)
else:
local_tensor = torch.arange(
start=my_rank * 4, end=(my_rank + 1) * 4, dtype=torch.float
).view(4, 1)
dtensor = DTensor.from_local(
local_tensor,
mesh_1,
[Shard(0)],
run_check=True,
shape=torch.Size([14, 1]),
stride=torch.Size([1, 1]),
)
state_dict_to_save = {"uneven_sharded_dtensor": dtensor}
dist_cp.save(
state_dict=state_dict_to_save,
storage_writer=dist_cp.FileSystemWriter(path=CHECKPOINT_DIR),
planner=dist_cp.DefaultSavePlanner(),
)
loading_full_tensor = torch.rand([14, 1], dtype=torch.float, device="cpu")
print(f"rank {my_rank} loading_dtensor for load :\n {loading_full_tensor}")
state_dict_to_load = {
"uneven_sharded_dtensor": loading_full_tensor
} # re-sharding load.
dist_cp.load(
state_dict=state_dict_to_load,
storage_reader=dist_cp.FileSystemReader(self.temp_dir),
)
| TestDTensorReshardMeshChange |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 20912,
"end": 21151
} | class ____:
@classmethod
def _type_fixture(cls):
return MutableSet
def teardown_test(self):
# clear out mapper events
Mapper.dispatch._clear()
ClassManager.dispatch._clear()
| _MutableSetTestFixture |
python | facebook__pyre-check | tools/incremental_test/runner.py | {
"start": 6937,
"end": 7330
} | class ____:
full_check_output: List[PyreError]
incremental_check_output: List[PyreError]
def to_json(self) -> Dict[str, Any]:
return {
"full_check_output": [asdict(e) for e in self.full_check_output],
"incremental_check_output": [
asdict(e) for e in self.incremental_check_output
],
}
@dataclass
| InconsistentOutput |
python | jina-ai__jina | jina/serve/executors/__init__.py | {
"start": 3404,
"end": 5047
} | class ____(type(JAMLCompatible), type):
"""The class of Executor type, which is the metaclass of :class:`BaseExecutor`."""
def __new__(cls, *args, **kwargs):
"""
# noqa: DAR101
# noqa: DAR102
:return: Executor class
"""
_cls = super().__new__(cls, *args, **kwargs)
# this needs to be here, in the case where Executors inherited do not define new `requests`
_init_requests_by_class(_cls)
return cls.register_class(_cls)
@staticmethod
def register_class(cls):
"""
Register a class and wrap update, train, aggregate functions.
:param cls: The class.
:return: The class, after being registered.
"""
reg_cls_set = getattr(cls, '_registered_class', set())
cls_id = f'{cls.__module__}.{cls.__name__}'
if cls_id not in reg_cls_set:
arg_spec = inspect.getfullargspec(cls.__init__)
if not arg_spec.varkw and not __args_executor_init__.issubset(
arg_spec.args
):
raise TypeError(
f'{cls.__init__} does not follow the full signature of `Executor.__init__`, '
f'please add `**kwargs` to your __init__ function'
)
taboo = get_executor_taboo()
wrap_func(cls, ['__init__'], store_init_kwargs, taboo=taboo)
wrap_func(cls, ['__init__'], avoid_concurrent_lock_cls(cls))
reg_cls_set.add(cls_id)
setattr(cls, '_registered_class', reg_cls_set)
return cls
T = TypeVar('T', bound='_FunctionWithSchema')
| ExecutorType |
python | walkccc__LeetCode | solutions/400. Nth Digit/400.py | {
"start": 0,
"end": 528
} | class ____:
def findNthDigit(self, n: int) -> int:
def getDigit(num: int, pos: int, digitSize: int):
if pos == 0:
return num % 10
for _ in range(digitSize - pos):
num //= 10
return num % 10
digitSize = 1
startNum = 1
count = 9
while digitSize * count < n:
n -= digitSize * count
digitSize += 1
startNum *= 10
count *= 10
targetNum = startNum + (n - 1) // digitSize
pos = n % digitSize
return getDigit(targetNum, pos, digitSize)
| Solution |
python | pytorch__pytorch | test/inductor/test_compile_worker.py | {
"start": 3646,
"end": 4826
} | class ____(TestCase):
def test_basics(self):
done = Event()
def doit():
done.set()
t = Timer(0.1, doit)
t.sleep_time = 0.1
t.record_call()
self.assertTrue(done.wait(4))
t.quit()
def test_repeated_calls(self):
done = Event()
def doit():
done.set()
t = Timer(0.1, doit)
t.sleep_time = 0.1
for _ in range(10):
t.record_call()
self.assertTrue(done.wait(4))
done.clear()
t.quit()
def test_never_fires(self):
done = Event()
def doit():
done.set()
t = Timer(999, doit)
t.sleep_time = 0.1
t.record_call()
self.assertFalse(done.wait(4))
t.quit()
def test_spammy_calls(self):
done = Event()
def doit():
done.set()
t = Timer(1, doit)
t.sleep_time = 0.1
for _ in range(400):
t.record_call()
self.assertTrue(done.wait(4))
t.quit()
if __name__ == "__main__":
from torch._inductor.test_case import run_tests
if HAS_CPU:
run_tests()
| TestTimer |
python | chardet__chardet | chardet/chardistribution.py | {
"start": 5429,
"end": 6195
} | class ____(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER
self._table_size = EUCKR_TABLE_SIZE
self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, bytearray]) -> int: # type: ignore[reportIncompatibleMethodOverride]
# for euc-KR encoding, we are interested
# first byte range: 0xb0 -- 0xfe
# second byte range: 0xa1 -- 0xfe
# no validation needed here. State machine has done that
first_char = byte_str[0]
if first_char >= 0xB0:
return 94 * (first_char - 0xB0) + byte_str[1] - 0xA1
return -1
| EUCKRDistributionAnalysis |
python | realpython__materials | python-built-in-functions/shapes.py | {
"start": 247,
"end": 345
} | class ____(Rectangle):
def __init__(self, length):
super().__init__(length, length)
| Square |
python | faif__python-patterns | patterns/structural/flyweight_with_metaclass.py | {
"start": 17,
"end": 1117
} | class ____(type):
def __new__(mcs, name, parents, dct):
"""
Set up object pool
:param name: class name
:param parents: class parents
:param dct: dict: includes class attributes, class methods,
static methods, etc
:return: new class
"""
dct["pool"] = weakref.WeakValueDictionary()
return super().__new__(mcs, name, parents, dct)
@staticmethod
def _serialize_params(cls, *args, **kwargs):
"""
Serialize input parameters to a key.
Simple implementation is just to serialize it as a string
"""
args_list = list(map(str, args))
args_list.extend([str(kwargs), cls.__name__])
key = "".join(args_list)
return key
def __call__(cls, *args, **kwargs):
key = FlyweightMeta._serialize_params(cls, *args, **kwargs)
pool = getattr(cls, "pool", {})
instance = pool.get(key)
if instance is None:
instance = super().__call__(*args, **kwargs)
pool[key] = instance
return instance
| FlyweightMeta |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 193662,
"end": 196349
} | class ____(rv_continuous):
r"""A Levy continuous random variable.
%(before_notes)s
See Also
--------
levy_stable, levy_l
Notes
-----
The probability density function for `levy` is:
.. math::
f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp\left(-\frac{1}{2x}\right)
for :math:`x > 0`.
This is the same as the Levy-stable distribution with :math:`a=1/2` and
:math:`b=1`.
%(after_notes)s
Examples
--------
>>> import numpy as np
>>> from scipy.stats import levy
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)
Calculate the first four moments:
>>> mean, var, skew, kurt = levy.stats(moments='mvsk')
Display the probability density function (``pdf``):
>>> # `levy` is very heavy-tailed.
>>> # To show a nice plot, let's cut off the upper 40 percent.
>>> a, b = levy.ppf(0), levy.ppf(0.6)
>>> x = np.linspace(a, b, 100)
>>> ax.plot(x, levy.pdf(x),
... 'r-', lw=5, alpha=0.6, label='levy pdf')
Alternatively, the distribution object can be called (as a function)
to fix the shape, location and scale parameters. This returns a "frozen"
RV object holding the given parameters fixed.
Freeze the distribution and display the frozen ``pdf``:
>>> rv = levy()
>>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
Check accuracy of ``cdf`` and ``ppf``:
>>> vals = levy.ppf([0.001, 0.5, 0.999])
>>> np.allclose([0.001, 0.5, 0.999], levy.cdf(vals))
True
Generate random numbers:
>>> r = levy.rvs(size=1000)
And compare the histogram:
>>> # manual binning to ignore the tail
>>> bins = np.concatenate((np.linspace(a, b, 20), [np.max(r)]))
>>> ax.hist(r, bins=bins, density=True, histtype='stepfilled', alpha=0.2)
>>> ax.set_xlim([x[0], x[-1]])
>>> ax.legend(loc='best', frameon=False)
>>> plt.show()
"""
_support_mask = rv_continuous._open_support_mask
def _shape_info(self):
return []
def _pdf(self, x):
# levy.pdf(x) = 1 / (x * sqrt(2*pi*x)) * exp(-1/(2*x))
return 1 / np.sqrt(2*np.pi*x) / x * np.exp(-1/(2*x))
def _cdf(self, x):
# Equivalent to 2*norm.sf(np.sqrt(1/x))
return sc.erfc(np.sqrt(0.5 / x))
def _sf(self, x):
return sc.erf(np.sqrt(0.5 / x))
def _ppf(self, q):
# Equivalent to 1.0/(norm.isf(q/2)**2) or 0.5/(erfcinv(q)**2)
val = _norm_isf(q/2)
return 1.0 / (val * val)
def _isf(self, p):
return 1/(2*sc.erfinv(p)**2)
def _stats(self):
return np.inf, np.inf, np.nan, np.nan
levy = levy_gen(a=0.0, name="levy")
| levy_gen |
python | pennersr__django-allauth | allauth/headless/account/views.py | {
"start": 9796,
"end": 10423
} | class ____(APIView):
input_class = RequestPasswordResetInput
def post(self, request, *args, **kwargs):
r429 = ratelimit.consume_or_429(
self.request,
action="reset_password",
key=self.input.cleaned_data["email"].lower(),
)
if r429:
return r429
self.input.save(request)
if account_settings.PASSWORD_RESET_BY_CODE_ENABLED:
return AuthenticationResponse(request)
return response.RequestPasswordResponse(request)
@method_decorator(rate_limit(action="reset_password_from_key"), name="handle")
| RequestPasswordResetView |
python | python-poetry__poetry | src/poetry/puzzle/solver.py | {
"start": 10160,
"end": 20289
} | class ____(DFSNode):
def __init__(
self,
package: Package,
packages: list[Package],
previous: PackageNode | None = None,
dep: Dependency | None = None,
marker: BaseMarker | None = None,
) -> None:
self.package = package
self.packages = packages
self.dep = dep
self.marker = marker or AnyMarker()
self.depth = -1
if not previous:
self.groups: frozenset[NormalizedName] = frozenset()
self.optional = True
elif dep:
self.groups = dep.groups
self.optional = dep.is_optional()
else:
raise ValueError("Both previous and dep must be passed")
package_repr = repr(package)
super().__init__(
(package_repr, self.groups, self.optional),
package_repr,
package.name,
)
def reachable(self) -> Sequence[PackageNode]:
children: list[PackageNode] = []
for dependency in self.package.all_requires:
for pkg in self.packages:
if pkg.complete_name == dependency.complete_name and pkg.satisfies(
dependency
):
marker = dependency.marker
if self.package.is_root() and dependency.in_extras:
marker = marker.intersect(
parse_marker(
" or ".join(
f'extra == "{extra}"'
for extra in dependency.in_extras
)
)
)
children.append(
PackageNode(
pkg,
self.packages,
self,
self.dep or dependency,
marker,
)
)
return children
def visit(self, parents: list[PackageNode]) -> None:
# The root package, which has no parents, is defined as having depth -1
# So that the root package's top-level dependencies have depth 0.
self.depth = 1 + max(
[
parent.depth if parent.base_name != self.base_name else parent.depth - 1
for parent in parents
]
+ [-2]
)
def aggregate_package_nodes(
nodes: list[PackageNode],
) -> tuple[Package, TransitivePackageInfo]:
package = nodes[0].package
depth = max(node.depth for node in nodes)
groups: set[NormalizedName] = set()
for node in nodes:
groups.update(node.groups)
optional = all(node.optional for node in nodes)
for node in nodes:
node.depth = depth
node.optional = optional
package.optional = optional
# TransitivePackageInfo.markers is updated later,
# because the nodes of all packages have to be aggregated first.
return package, TransitivePackageInfo(depth, groups, {})
def calculate_markers(
packages: dict[Package, TransitivePackageInfo], markers: MarkerOriginDict
) -> None:
# group packages by depth
packages_by_depth: dict[int, list[Package]] = defaultdict(list)
max_depth = -1
for package, info in packages.items():
max_depth = max(max_depth, info.depth)
packages_by_depth[info.depth].append(package)
# calculate markers from lowest to highest depth
# (start with depth 0 because the root package has depth -1)
has_incomplete_markers = True
while has_incomplete_markers:
has_incomplete_markers = False
for depth in range(max_depth + 1):
for package in packages_by_depth[depth]:
transitive_info = packages[package]
transitive_marker: dict[NormalizedName, BaseMarker] = {
group: EmptyMarker() for group in transitive_info.groups
}
for parent, group_markers in markers[package].items():
parent_info = packages[parent]
if parent_info.groups:
# If parent has groups, we need to intersect its per-group
# markers with each edge marker and union into child's groups.
if parent_info.groups != set(parent_info.markers):
# there is a cycle -> we need one more iteration
has_incomplete_markers = True
continue
for group in parent_info.groups:
for edge_marker in group_markers.values():
transitive_marker[group] = transitive_marker[
group
].union(
parent_info.markers[group].intersect(edge_marker)
)
else:
# Parent is the root (no groups). Edge markers specify which
# dependency groups the edge belongs to. We should only add
# the edge marker to the corresponding child groups.
for groups, edge_marker in group_markers.items():
assert groups, (
f"Package {package.name} at depth {depth} has no groups."
f" All dependencies except for the root package at depth -1 must have groups"
)
for group in transitive_info.groups:
if group in groups:
transitive_marker[group] = transitive_marker[
group
].union(edge_marker)
transitive_info.markers = transitive_marker
def merge_override_packages(
override_packages: list[
tuple[
dict[Package, dict[str, Dependency]], dict[Package, TransitivePackageInfo]
]
],
python_constraint: VersionConstraint,
) -> dict[Package, TransitivePackageInfo]:
result: dict[Package, TransitivePackageInfo] = {}
all_packages: dict[
Package, list[tuple[Package, TransitivePackageInfo, BaseMarker]]
] = {}
for override, o_packages in override_packages:
override_marker: BaseMarker = AnyMarker()
for deps in override.values():
for dep in deps.values():
override_marker = override_marker.intersect(dep.marker.without_extras())
override_marker = simplify_marker(override_marker, python_constraint)
for package, info in o_packages.items():
for group, marker in info.markers.items():
# `override_marker` is often a SingleMarker or a MultiMarker,
# `marker` often is a MultiMarker that contains `override_marker`.
# We can "remove" `override_marker` from `marker`
# because we will do an intersection later anyway.
# By removing it now, it is more likely that we hit
# the performance shortcut instead of the fallback algorithm.
info.markers[group] = remove_other_from_marker(marker, override_marker)
all_packages.setdefault(package, []).append(
(package, info, override_marker)
)
for package_duplicates in all_packages.values():
base = package_duplicates[0]
remaining = package_duplicates[1:]
package = base[0]
package_info = base[1]
first_override_marker = base[2]
result[package] = package_info
package_info.depth = max(info.depth for _, info, _ in package_duplicates)
package_info.groups = {
g for _, info, _ in package_duplicates for g in info.groups
}
if all(info.markers == package_info.markers for _, info, _ in remaining):
# performance shortcut:
# if markers are the same for all overrides,
# we can use less expensive marker operations
override_marker = EmptyMarker()
for _, _, marker in package_duplicates:
override_marker = override_marker.union(marker)
package_info.markers = {
group: override_marker.intersect(marker)
for group, marker in package_info.markers.items()
}
else:
# fallback / general algorithm with performance issues
for group, marker in package_info.markers.items():
package_info.markers[group] = first_override_marker.intersect(marker)
for _, info, override_marker in remaining:
for group, marker in info.markers.items():
package_info.markers[group] = package_info.markers.get(
group, EmptyMarker()
).union(override_marker.intersect(marker))
for duplicate_package, _, _ in remaining:
for dep in duplicate_package.requires:
if dep not in package.requires:
package.add_dependency(dep)
return result
def remove_other_from_marker(marker: BaseMarker, other: BaseMarker) -> BaseMarker:
if isinstance(other, SingleMarker):
other_markers: set[BaseMarker] = {other}
elif isinstance(other, MultiMarker):
other_markers = set(other.markers)
else:
return marker
if isinstance(marker, MultiMarker) and other_markers.issubset(marker.markers):
return MultiMarker.of(*(m for m in marker.markers if m not in other_markers))
return marker
@functools.cache
def simplify_marker(
marker: BaseMarker, python_constraint: VersionConstraint
) -> BaseMarker:
"""
Remove constraints from markers that are covered by the projects Python constraint.
Use cache because we call this function often for the same markers.
"""
return marker.reduce_by_python_constraint(python_constraint)
| PackageNode |
python | tensorflow__tensorflow | tensorflow/python/autograph/tests/cond_basic_test.py | {
"start": 3491,
"end": 8321
} | class ____(reference_test_base.TestCase, parameterized.TestCase):
@parameterized.parameters(*itertools.product(
(
if_no_vars,
if_else_no_vars,
),
(
True,
False,
),
(
bool,
tf.constant,
),
))
def test_no_vars(self, target, c, type_):
c = type_(c)
self.assertFunctionMatchesEager(target, c, tf.Variable(0))
@parameterized.parameters(*itertools.product(
(
if_one_var,
if_else_one_var,
if_two_vars,
if_else_two_vars,
),
(
0,
1,
),
(
int,
tf.constant,
),
))
def test_several_vars(self, target, n, type_):
n = type_(n)
self.assertFunctionMatchesEager(target, n)
def test_var_lifetime_imbalanced_legal(self):
self.assertFunctionMatchesEager(if_creates_var, True)
self.assertFunctionMatchesEager(else_creates_var, False)
self.assertFunctionMatchesEager(if_destroys_var, False)
self.assertFunctionMatchesEager(else_destroys_var, True)
@parameterized.parameters(*itertools.product(
(
True,
False,
),
(
int,
tf.constant,
),
))
def test_if_else_var_lifetime(self, c, type_):
c = type_(c)
self.assertFunctionMatchesEager(if_else_creates_var, c)
if type_ is int:
with self.assertRaisesRegex(UnboundLocalError, "'i'"):
tf.function(if_else_destroys_var)(c)
else:
with self.assertRaisesRegex(ValueError, "'i' must also be initialized"):
tf.function(if_else_destroys_var)(c)
@parameterized.parameters(
(if_creates_var, False, bool, UnboundLocalError,
"'i' is used before assignment"),
(if_creates_var, True, tf.constant, ValueError,
"'i' must also be initialized in the else branch"),
(if_creates_var, False, tf.constant, ValueError,
"'i' must also be initialized in the else branch"),
(else_creates_var, True, bool, UnboundLocalError,
"'i' is used before assignment"),
(else_creates_var, True, tf.constant, ValueError,
"'i' must also be initialized in the main branch"),
(else_creates_var, False, tf.constant, ValueError,
"'i' must also be initialized in the main branch"),
)
def test_creates_var_imbalanced_illegal(self, target, c, type_, exc_type,
exc_regex):
c = type_(c)
with self.assertRaisesRegex(exc_type, exc_regex):
tf.function(target)(c)
def test_returns_none_legal(self):
self.assertFunctionMatchesEager(if_returns_none, True)
self.assertFunctionMatchesEager(if_else_returns_none, False)
self.assertFunctionMatchesEager(else_returns_none, False)
@parameterized.parameters(
(if_returns_none, True),
(if_returns_none, False),
(else_returns_none, True),
(else_returns_none, False),
(if_else_returns_none, True),
(if_else_returns_none, False),
)
def test_returns_none_illegal(self, target, c):
c = tf.constant(c)
with self.assertRaisesRegex(ValueError, re.compile("'i' is None",
re.DOTALL)):
tf.function(target)(c)
@parameterized.parameters(*itertools.product(
(
if_local_var,
if_else_local_var,
if_locally_modified_var,
),
(
True,
False,
),
(
bool,
tf.constant,
),
))
def test_local_vars(self, target, c, type_):
c = type_(c)
self.assertFunctionMatchesEager(target, c)
@parameterized.parameters(*itertools.product(
(True, False),
(True, False),
))
def test_nested_if_temporarily_undefined_return_legal(self, c1, c2):
self.assertFunctionMatchesEager(
nested_if_temporarily_undefined_return, c1, c2)
@parameterized.parameters(*itertools.product(
(True, False),
(True, False),
))
def test_nested_if_temporarily_undefined_return_illegal(self, c1, c2):
c1 = tf.constant(c1)
c2 = tf.constant(c2)
with self.assertRaisesRegex(ValueError, "must also have a return"):
tf.function(nested_if_temporarily_undefined_return)(c1, c2)
@parameterized.parameters(*itertools.product(
(
successive_ifs,
successive_if_elses,
nested_ifs,
nested_if_elses,
),
(
0,
1,
),
(
bool,
tf.constant,
),
(
0,
1,
),
(
bool,
tf.constant,
),
))
def test_composition(self, target, n1, n1_type, n2, n2_type):
n1 = n1_type(n1)
n2 = n2_type(n2)
self.assertFunctionMatchesEager(target, n1, n2)
if __name__ == "__main__":
tf.test.main()
| ReferenceTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/image_ops/draw_bounding_box_op_test.py | {
"start": 1214,
"end": 6369
} | class ____(test.TestCase):
def _fillBorder(self, image, color):
"""Fill the border of the image.
Args:
image: Numpy array of shape [height, width, depth].
color: Numpy color of shape [depth] and either contents RGB/RGBA.
Returns:
image of original shape with border filled with "color".
Raises:
ValueError: Depths of image and color don"t match.
"""
height, width, depth = image.shape
if depth != color.shape[0]:
raise ValueError("Image (%d) and color (%d) depths must match." %
(depth, color.shape[0]))
image[0:height, 0, 0:depth] = color
image[0:height, width - 1, 0:depth] = color
image[0, 0:width, 0:depth] = color
image[height - 1, 0:width, 0:depth] = color
return image
def _testDrawBoundingBoxColorCycling(self,
img,
dtype=dtypes.float32,
colors=None):
"""Tests if cycling works appropriately.
Args:
img: 3-D numpy image on which to draw.
dtype: image dtype (float, half).
colors: color table.
"""
color_table = colors
if colors is None:
# THIS TABLE MUST MATCH draw_bounding_box_op.cc
color_table = np.asarray([[1, 1, 0, 1], [0, 0, 1, 1], [1, 0, 0, 1],
[0, 1, 0, 1], [0.5, 0, 0.5,
1], [0.5, 0.5, 0, 1],
[0.5, 0, 0, 1], [0, 0, 0.5, 1], [0, 1, 1, 1],
[1, 0, 1, 1]])
assert len(img.shape) == 3
depth = img.shape[2]
assert depth <= color_table.shape[1]
assert depth == 1 or depth == 3 or depth == 4
## Set red channel to 1 if image is GRY.
if depth == 1:
color_table[:, 0] = 1
num_colors = color_table.shape[0]
for num_boxes in range(1, num_colors + 2):
# Generate draw_bounding_box_op drawn image
image = np.copy(img)
color = color_table[(num_boxes - 1) % num_colors, 0:depth]
test_drawn_image = self._fillBorder(image, color)
bboxes = np.asarray([0, 0, 1, 1])
bboxes = np.vstack([bboxes for _ in range(num_boxes)])
bboxes = math_ops.cast(bboxes, dtypes.float32)
bboxes = array_ops.expand_dims(bboxes, 0)
image = ops.convert_to_tensor(image)
image = image_ops_impl.convert_image_dtype(image, dtype)
image = array_ops.expand_dims(image, 0)
image = image_ops.draw_bounding_boxes(image, bboxes, colors=colors)
with self.cached_session(use_gpu=False) as sess:
op_drawn_image = np.squeeze(sess.run(image), 0)
self.assertAllEqual(test_drawn_image, op_drawn_image)
def testDrawBoundingBoxRGBColorCycling(self):
"""Test if RGB color cycling works correctly."""
image = np.zeros([10, 10, 3], "float32")
self._testDrawBoundingBoxColorCycling(image)
def testDrawBoundingBoxRGBAColorCycling(self):
"""Test if RGBA color cycling works correctly."""
image = np.zeros([10, 10, 4], "float32")
self._testDrawBoundingBoxColorCycling(image)
def testDrawBoundingBoxGRY(self):
"""Test if drawing bounding box on a GRY image works."""
image = np.zeros([4, 4, 1], "float32")
self._testDrawBoundingBoxColorCycling(image)
def testDrawBoundingBoxRGBColorCyclingWithColors(self):
"""Test if RGB color cycling works correctly with provided colors."""
image = np.zeros([10, 10, 3], "float32")
colors = np.asarray([[1, 1, 0, 1], [0, 0, 1, 1], [0.5, 0, 0.5, 1],
[0.5, 0.5, 0, 1], [0, 1, 1, 1], [1, 0, 1, 1]])
self._testDrawBoundingBoxColorCycling(image, colors=colors)
def testDrawBoundingBoxRGBAColorCyclingWithColors(self):
"""Test if RGBA color cycling works correctly with provided colors."""
image = np.zeros([10, 10, 4], "float32")
colors = np.asarray([[0.5, 0, 0.5, 1], [0.5, 0.5, 0, 1], [0.5, 0, 0, 1],
[0, 0, 0.5, 1]])
self._testDrawBoundingBoxColorCycling(image, colors=colors)
def testDrawBoundingBoxHalf(self):
"""Test if RGBA color cycling works correctly with provided colors."""
image = np.zeros([10, 10, 4], "float32")
colors = np.asarray([[0.5, 0, 0.5, 1], [0.5, 0.5, 0, 1], [0.5, 0, 0, 1],
[0, 0, 0.5, 1]])
self._testDrawBoundingBoxColorCycling(
image, dtype=dtypes.half, colors=colors)
# generate_bound_box_proposals is only available on GPU.
@test_util.run_gpu_only
def testGenerateBoundingBoxProposals(self):
# Op only exists on GPU.
with self.cached_session(use_gpu=True):
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
"must be rank 4"):
scores = constant_op.constant(
value=[[[[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]]]])
self.evaluate(
image_ops.generate_bounding_box_proposals(
scores=scores,
bbox_deltas=[],
image_info=[],
anchors=[],
pre_nms_topn=1))
if __name__ == "__main__":
test.main()
| DrawBoundingBoxOpTest |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 11417,
"end": 11561
} | class ____(desc_sig_element, _sig_element=True):
"""Node for a numeric literal in a signature."""
classes = ['m']
| desc_sig_literal_number |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 11011,
"end": 11142
} | class ____:
fqn: Annotated[str, 10]
signature: Annotated[Optional[ModuleCallSignature], 30] = None
@dataclass
| ModuleCallEntry |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_test.py | {
"start": 3033,
"end": 4039
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_deprecated_v1
def testBuildGraph(self):
with self.cached_session():
pt = test_ops.stub_resource_handle_op(container="a", shared_name="b")
test_ops.resource_create_op(pt).run()
@test_util.run_deprecated_v1
def testInitialize(self):
with self.cached_session():
handle = test_ops.stub_resource_handle_op(container="a", shared_name="b")
resources.register_resource(
handle=handle,
create_op=test_ops.resource_create_op(handle),
is_initialized_op=test_ops.resource_initialized_op(handle))
self.assertEqual(
len(
resources.report_uninitialized_resources(
resources.shared_resources()).eval()), 1)
resources.initialize_resources(resources.shared_resources()).run()
self.assertEqual(
len(
resources.report_uninitialized_resources(
resources.shared_resources()).eval()), 0)
| ResourceTest |
python | kamyu104__LeetCode-Solutions | Python/shortest-distance-from-all-buildings.py | {
"start": 75,
"end": 1625
} | class ____(object):
def shortestDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def bfs(grid, dists, cnts, x, y):
dist, m, n = 0, len(grid), len(grid[0])
visited = [[False for _ in xrange(n)] for _ in xrange(m)]
pre_level = [(x, y)]
visited[x][y] = True
while pre_level:
dist += 1
cur_level = []
for i, j in pre_level:
for dir in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
I, J = i+dir[0], j+dir[1]
if 0 <= I < m and 0 <= J < n and grid[I][J] == 0 and not visited[I][J]:
cnts[I][J] += 1
dists[I][J] += dist
cur_level.append((I, J))
visited[I][J] = True
pre_level = cur_level
m, n, cnt = len(grid), len(grid[0]), 0
dists = [[0 for _ in xrange(n)] for _ in xrange(m)]
cnts = [[0 for _ in xrange(n)] for _ in xrange(m)]
for i in xrange(m):
for j in xrange(n):
if grid[i][j] == 1:
cnt += 1
bfs(grid, dists, cnts, i, j)
shortest = float("inf")
for i in xrange(m):
for j in xrange(n):
if dists[i][j] < shortest and cnts[i][j] == cnt:
shortest = dists[i][j]
return shortest if shortest != float("inf") else -1
| Solution |
python | python__mypy | mypy/nodes.py | {
"start": 77304,
"end": 78332
} | class ____(Expression):
"""Comparison expression (e.g. a < b > c < d)."""
__slots__ = ("operators", "operands", "method_types")
__match_args__ = ("operands", "operators")
operators: list[str]
operands: list[Expression]
# Inferred type for the operator methods (when relevant; None for 'is').
method_types: list[mypy.types.Type | None]
def __init__(self, operators: list[str], operands: list[Expression]) -> None:
super().__init__()
self.operators = operators
self.operands = operands
self.method_types = []
def pairwise(self) -> Iterator[tuple[str, Expression, Expression]]:
"""If this comparison expr is "a < b is c == d", yields the sequence
("<", a, b), ("is", b, c), ("==", c, d)
"""
for i, operator in enumerate(self.operators):
yield operator, self.operands[i], self.operands[i + 1]
def accept(self, visitor: ExpressionVisitor[T]) -> T:
return visitor.visit_comparison_expr(self)
| ComparisonExpr |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 579819,
"end": 580394
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("admin", "client_mutation_id", "enterprise", "message", "viewer")
admin = sgqlc.types.Field("User", graphql_name="admin")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
enterprise = sgqlc.types.Field("Enterprise", graphql_name="enterprise")
message = sgqlc.types.Field(String, graphql_name="message")
viewer = sgqlc.types.Field("User", graphql_name="viewer")
| RemoveEnterpriseAdminPayload |
python | virgili0__Virgilio | Tools/regex-bin/regexPrinter.py | {
"start": 1346,
"end": 1607
} | class ____(object):
def __init__(self, token, value, next_node):
self.token = token
self.value = value
self.next_node = next_node
def print(self):
raise NotImplementedError("This should be overriden in subclasses")
| TreeNode |
python | django__django | django/contrib/gis/db/models/lookups.py | {
"start": 7104,
"end": 7202
} | class ____(GISLookup):
lookup_name = "disjoint"
@BaseSpatialField.register_lookup
| DisjointLookup |
python | optuna__optuna | tests/terminator_tests/test_terminator.py | {
"start": 419,
"end": 2325
} | class ____(BaseImprovementEvaluator):
def __init__(self, constant: float) -> None:
super().__init__()
self._constant = constant
def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float:
return self._constant
def test_init() -> None:
# Test that a positive `min_n_trials` does not raise any error.
Terminator(min_n_trials=1)
with pytest.raises(ValueError):
# Test that a non-positive `min_n_trials` raises ValueError.
Terminator(min_n_trials=0)
Terminator(BestValueStagnationEvaluator(), min_n_trials=1)
def test_should_terminate() -> None:
study = create_study()
# Add dummy trial because Terminator needs at least one trial.
trial = study.ask()
study.tell(trial, 0.0)
# Improvement is greater than error.
terminator = Terminator(
improvement_evaluator=_StaticImprovementEvaluator(3),
error_evaluator=StaticErrorEvaluator(0),
min_n_trials=1,
)
assert not terminator.should_terminate(study)
# Improvement is less than error.
terminator = Terminator(
improvement_evaluator=_StaticImprovementEvaluator(-1),
error_evaluator=StaticErrorEvaluator(0),
min_n_trials=1,
)
assert terminator.should_terminate(study)
# Improvement is less than error. However, the number of trials is less than `min_n_trials`.
terminator = Terminator(
improvement_evaluator=_StaticImprovementEvaluator(-1),
error_evaluator=StaticErrorEvaluator(0),
min_n_trials=2,
)
assert not terminator.should_terminate(study)
# Improvement is equal to error.
terminator = Terminator(
improvement_evaluator=_StaticImprovementEvaluator(0),
error_evaluator=StaticErrorEvaluator(0),
min_n_trials=1,
)
assert not terminator.should_terminate(study)
| _StaticImprovementEvaluator |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 42350,
"end": 43143
} | class ____(BaseAsyncRealtimeConnectionResource):
async def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None:
"""**WebRTC Only:** Emit to cut off the current audio response.
This will trigger the server to
stop generating audio and emit a `output_audio_buffer.cleared` event. This
event should be preceded by a `response.cancel` client event to stop the
generation of the current response.
[Learn more](https://platform.openai.com/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).
"""
await self._connection.send(
cast(RealtimeClientEventParam, strip_not_given({"type": "output_audio_buffer.clear", "event_id": event_id}))
)
| AsyncRealtimeOutputAudioBufferResource |
python | mahmoud__boltons | boltons/queueutils.py | {
"start": 3293,
"end": 6774
} | class ____:
"""The abstract base class for the other PriorityQueues in this
module. Override the ``_backend_type`` class attribute, as well as
the :meth:`_push_entry` and :meth:`_pop_entry` staticmethods for
custom subclass behavior. (Don't forget to use
:func:`staticmethod`).
Args:
priority_key (callable): A function that takes *priority* as
passed in by :meth:`add` and returns a real number
representing the effective priority.
"""
# negating priority means larger numbers = higher priority
_default_priority_key = staticmethod(lambda p: -float(p or 0))
_backend_type = list
def __init__(self, **kw):
self._pq = self._backend_type()
self._entry_map = {}
self._counter = itertools.count()
self._get_priority = kw.pop('priority_key', self._default_priority_key)
if kw:
raise TypeError('unexpected keyword arguments: %r' % kw.keys())
@staticmethod
def _push_entry(backend, entry):
pass # abstract
@staticmethod
def _pop_entry(backend):
pass # abstract
def add(self, task, priority=None):
"""
Add a task to the queue, or change the *task*'s priority if *task*
is already in the queue. *task* can be any hashable object,
and *priority* defaults to ``0``. Higher values representing
higher priority, but this behavior can be controlled by
setting *priority_key* in the constructor.
"""
priority = self._get_priority(priority)
if task in self._entry_map:
self.remove(task)
count = next(self._counter)
entry = [priority, count, task]
self._entry_map[task] = entry
self._push_entry(self._pq, entry)
def remove(self, task):
"""Remove a task from the priority queue. Raises :exc:`KeyError` if
the *task* is absent.
"""
entry = self._entry_map.pop(task)
entry[-1] = _REMOVED
def _cull(self, raise_exc=True):
"Remove entries marked as removed by previous :meth:`remove` calls."
while self._pq:
priority, count, task = self._pq[0]
if task is _REMOVED:
self._pop_entry(self._pq)
continue
return
if raise_exc:
raise IndexError('empty priority queue')
def peek(self, default=_REMOVED):
"""Read the next value in the queue without removing it. Returns
*default* on an empty queue, or raises :exc:`KeyError` if
*default* is not set.
"""
try:
self._cull()
_, _, task = self._pq[0]
except IndexError:
if default is not _REMOVED:
return default
raise IndexError('peek on empty queue')
return task
def pop(self, default=_REMOVED):
"""Remove and return the next value in the queue. Returns *default* on
an empty queue, or raises :exc:`KeyError` if *default* is not
set.
"""
try:
self._cull()
_, _, task = self._pop_entry(self._pq)
del self._entry_map[task]
except IndexError:
if default is not _REMOVED:
return default
raise IndexError('pop on empty queue')
return task
def __len__(self):
"Return the number of tasks in the queue."
return len(self._entry_map)
| BasePriorityQueue |
python | numpy__numpy | numpy/ma/tests/test_core.py | {
"start": 2684,
"end": 40852
} | class ____:
# Base test class for MaskedArrays.
# message for warning filters
def _create_data(self):
# Base data definition.
x = np.array([1., 1., 1., -2., pi / 2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
a10 = 10.
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
xm = masked_array(x, mask=m1)
ym = masked_array(y, mask=m2)
z = np.array([-.5, 0., .5, .8])
zm = masked_array(z, mask=[0, 1, 0, 0])
xf = np.where(m1, 1e+20, x)
xm.set_fill_value(1e+20)
return x, y, a10, m1, m2, xm, ym, z, zm, xf
def test_basicattributes(self):
# Tests some basic array attributes.
a = array([1, 3, 2])
b = array([1, 3, 2], mask=[1, 0, 1])
assert_equal(a.ndim, 1)
assert_equal(b.ndim, 1)
assert_equal(a.size, 3)
assert_equal(b.size, 3)
assert_equal(a.shape, (3,))
assert_equal(b.shape, (3,))
def test_basic0d(self):
# Checks masking a scalar
x = masked_array(0)
assert_equal(str(x), '0')
x = masked_array(0, mask=True)
assert_equal(str(x), str(masked_print_option))
x = masked_array(0, mask=False)
assert_equal(str(x), '0')
x = array(0, mask=1)
assert_(x.filled().dtype is x._data.dtype)
def test_basic1d(self):
# Test of basic array creation and properties in 1 dimension.
x, _, _, m1, _, xm, ym, z, zm, xf = self._create_data()
assert_(not isMaskedArray(x))
assert_(isMaskedArray(xm))
assert_((xm - ym).filled(0).any())
fail_if_equal(xm.mask.astype(int), ym.mask.astype(int))
s = x.shape
assert_equal(np.shape(xm), s)
assert_equal(xm.shape, s)
assert_equal(xm.dtype, x.dtype)
assert_equal(zm.dtype, z.dtype)
assert_equal(xm.size, reduce(lambda x, y: x * y, s))
assert_equal(count(xm), len(m1) - reduce(lambda x, y: x + y, m1))
assert_array_equal(xm, xf)
assert_array_equal(filled(xm, 1.e20), xf)
assert_array_equal(x, xm)
def test_basic2d(self):
# Test of basic array creation and properties in 2 dimensions.
x, y, _, m1, _, xm, ym, _, _, xf = self._create_data()
for s in [(4, 3), (6, 2)]:
x = x.reshape(s)
y = y.reshape(s)
xm = xm.reshape(s)
ym = ym.reshape(s)
xf = xf.reshape(s)
assert_(not isMaskedArray(x))
assert_(isMaskedArray(xm))
assert_equal(shape(xm), s)
assert_equal(xm.shape, s)
assert_equal(xm.size, reduce(lambda x, y: x * y, s))
assert_equal(count(xm), len(m1) - reduce(lambda x, y: x + y, m1))
assert_equal(xm, xf)
assert_equal(filled(xm, 1.e20), xf)
assert_equal(x, xm)
def test_concatenate_basic(self):
# Tests concatenations.
x, y, _, _, _, xm, ym, _, _, _ = self._create_data()
# basic concatenation
assert_equal(np.concatenate((x, y)), concatenate((xm, ym)))
assert_equal(np.concatenate((x, y)), concatenate((x, y)))
assert_equal(np.concatenate((x, y)), concatenate((xm, y)))
assert_equal(np.concatenate((x, y, x)), concatenate((x, ym, x)))
def test_concatenate_alongaxis(self):
# Tests concatenations.
x, y, _, m1, m2, xm, ym, z, _, xf = self._create_data()
# Concatenation along an axis
s = (3, 4)
x = x.reshape(s)
y = y.reshape(s)
xm = xm.reshape(s)
ym = ym.reshape(s)
xf = xf.reshape(s)
assert_equal(xm.mask, np.reshape(m1, s))
assert_equal(ym.mask, np.reshape(m2, s))
xmym = concatenate((xm, ym), 1)
assert_equal(np.concatenate((x, y), 1), xmym)
assert_equal(np.concatenate((xm.mask, ym.mask), 1), xmym._mask)
x = zeros(2)
y = array(ones(2), mask=[False, True])
z = concatenate((x, y))
assert_array_equal(z, [0, 0, 1, 1])
assert_array_equal(z.mask, [False, False, False, True])
z = concatenate((y, x))
assert_array_equal(z, [1, 1, 0, 0])
assert_array_equal(z.mask, [False, True, False, False])
def test_concatenate_flexible(self):
# Tests the concatenation on flexible arrays.
data = masked_array(list(zip(np.random.rand(10),
np.arange(10))),
dtype=[('a', float), ('b', int)])
test = concatenate([data[:5], data[5:]])
assert_equal_records(test, data)
def test_creation_ndmin(self):
# Check the use of ndmin
x = array([1, 2, 3], mask=[1, 0, 0], ndmin=2)
assert_equal(x.shape, (1, 3))
assert_equal(x._data, [[1, 2, 3]])
assert_equal(x._mask, [[1, 0, 0]])
def test_creation_ndmin_from_maskedarray(self):
# Make sure we're not losing the original mask w/ ndmin
x = array([1, 2, 3])
x[-1] = masked
xx = array(x, ndmin=2, dtype=float)
assert_equal(x.shape, x._mask.shape)
assert_equal(xx.shape, xx._mask.shape)
def test_creation_maskcreation(self):
# Tests how masks are initialized at the creation of Maskedarrays.
data = arange(24, dtype=float)
data[[3, 6, 15]] = masked
dma_1 = MaskedArray(data)
assert_equal(dma_1.mask, data.mask)
dma_2 = MaskedArray(dma_1)
assert_equal(dma_2.mask, dma_1.mask)
dma_3 = MaskedArray(dma_1, mask=[1, 0, 0, 0] * 6)
fail_if_equal(dma_3.mask, dma_1.mask)
x = array([1, 2, 3], mask=True)
assert_equal(x._mask, [True, True, True])
x = array([1, 2, 3], mask=False)
assert_equal(x._mask, [False, False, False])
y = array([1, 2, 3], mask=x._mask, copy=False)
assert_(np.may_share_memory(x.mask, y.mask))
y = array([1, 2, 3], mask=x._mask, copy=True)
assert_(not np.may_share_memory(x.mask, y.mask))
x = array([1, 2, 3], mask=None)
assert_equal(x._mask, [False, False, False])
def test_masked_singleton_array_creation_warns(self):
# The first works, but should not (ideally), there may be no way
# to solve this, however, as long as `np.ma.masked` is an ndarray.
np.array(np.ma.masked)
with pytest.warns(UserWarning):
# Tries to create a float array, using `float(np.ma.masked)`.
# We may want to define this is invalid behaviour in the future!
# (requiring np.ma.masked to be a known NumPy scalar probably
# with a DType.)
np.array([3., np.ma.masked])
def test_creation_with_list_of_maskedarrays(self):
# Tests creating a masked array from a list of masked arrays.
x = array(np.arange(5), mask=[1, 0, 0, 0, 0])
data = array((x, x[::-1]))
assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
assert_equal(data._mask, [[1, 0, 0, 0, 0], [0, 0, 0, 0, 1]])
x.mask = nomask
data = array((x, x[::-1]))
assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
assert_(data.mask is nomask)
def test_creation_with_list_of_maskedarrays_no_bool_cast(self):
# Tests the regression in gh-18551
masked_str = np.ma.masked_array(['a', 'b'], mask=[True, False])
normal_int = np.arange(2)
res = np.ma.asarray([masked_str, normal_int], dtype="U21")
assert_array_equal(res.mask, [[True, False], [False, False]])
# The above only failed due a long chain of oddity, try also with
# an object array that cannot be converted to bool always:
class NotBool:
def __bool__(self):
raise ValueError("not a bool!")
masked_obj = np.ma.masked_array([NotBool(), 'b'], mask=[True, False])
# Check that the NotBool actually fails like we would expect:
with pytest.raises(ValueError, match="not a bool!"):
np.asarray([masked_obj], dtype=bool)
res = np.ma.asarray([masked_obj, normal_int])
assert_array_equal(res.mask, [[True, False], [False, False]])
def test_creation_from_ndarray_with_padding(self):
x = np.array([('A', 0)], dtype={'names': ['f0', 'f1'],
'formats': ['S4', 'i8'],
'offsets': [0, 8]})
array(x) # used to fail due to 'V' padding field in x.dtype.descr
def test_unknown_keyword_parameter(self):
with pytest.raises(TypeError, match="unexpected keyword argument"):
MaskedArray([1, 2, 3], maks=[0, 1, 0]) # `mask` is misspelled.
def test_asarray(self):
xm = self._create_data()[5]
xm.fill_value = -9999
xm._hardmask = True
xmm = asarray(xm)
assert_equal(xmm._data, xm._data)
assert_equal(xmm._mask, xm._mask)
assert_equal(xmm.fill_value, xm.fill_value)
assert_equal(xmm._hardmask, xm._hardmask)
def test_asarray_default_order(self):
# See Issue #6646
m = np.eye(3).T
assert_(not m.flags.c_contiguous)
new_m = asarray(m)
assert_(new_m.flags.c_contiguous)
def test_asarray_enforce_order(self):
# See Issue #6646
m = np.eye(3).T
assert_(not m.flags.c_contiguous)
new_m = asarray(m, order='C')
assert_(new_m.flags.c_contiguous)
def test_fix_invalid(self):
# Checks fix_invalid.
with np.errstate(invalid='ignore'):
data = masked_array([np.nan, 0., 1.], mask=[0, 0, 1])
data_fixed = fix_invalid(data)
assert_equal(data_fixed._data, [data.fill_value, 0., 1.])
assert_equal(data_fixed._mask, [1., 0., 1.])
def test_maskedelement(self):
# Test of masked element
x = arange(6)
x[1] = masked
assert_(str(masked) == '--')
assert_(x[1] is masked)
assert_equal(filled(x[1], 0), 0)
def test_set_element_as_object(self):
# Tests setting elements with object
a = empty(1, dtype=object)
x = (1, 2, 3, 4, 5)
a[0] = x
assert_equal(a[0], x)
assert_(a[0] is x)
import datetime
dt = datetime.datetime.now()
a[0] = dt
assert_(a[0] is dt)
def test_indexing(self):
# Tests conversions and indexing
x1 = np.array([1, 2, 4, 3])
x2 = array(x1, mask=[1, 0, 0, 0])
x3 = array(x1, mask=[0, 1, 0, 1])
x4 = array(x1)
# test conversion to strings
str(x2) # raises?
repr(x2) # raises?
assert_equal(np.sort(x1), sort(x2, endwith=False))
# tests of indexing
assert_(type(x2[1]) is type(x1[1]))
assert_(x1[1] == x2[1])
assert_(x2[0] is masked)
assert_equal(x1[2], x2[2])
assert_equal(x1[2:5], x2[2:5])
assert_equal(x1[:], x2[:])
assert_equal(x1[1:], x3[1:])
x1[2] = 9
x2[2] = 9
assert_equal(x1, x2)
x1[1:3] = 99
x2[1:3] = 99
assert_equal(x1, x2)
x2[1] = masked
assert_equal(x1, x2)
x2[1:3] = masked
assert_equal(x1, x2)
x2[:] = x1
x2[1] = masked
assert_(allequal(getmask(x2), array([0, 1, 0, 0])))
x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
assert_(allequal(getmask(x3), array([0, 1, 1, 0])))
x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
assert_(allequal(getmask(x4), array([0, 1, 1, 0])))
assert_(allequal(x4, array([1, 2, 3, 4])))
x1 = np.arange(5) * 1.0
x2 = masked_values(x1, 3.0)
assert_equal(x1, x2)
assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
assert_equal(3.0, x2.fill_value)
x1 = array([1, 'hello', 2, 3], object)
x2 = np.array([1, 'hello', 2, 3], object)
s1 = x1[1]
s2 = x2[1]
assert_equal(type(s2), str)
assert_equal(type(s1), str)
assert_equal(s1, s2)
assert_(x1[1:1].shape == (0,))
def test_setitem_no_warning(self):
# Setitem shouldn't warn, because the assignment might be masked
# and warning for a masked assignment is weird (see gh-23000)
# (When the value is masked, otherwise a warning would be acceptable
# but is not given currently.)
x = np.ma.arange(60).reshape((6, 10))
index = (slice(1, 5, 2), [7, 5])
value = np.ma.masked_all((2, 2))
value._data[...] = np.inf # not a valid integer...
x[index] = value
# The masked scalar is special cased, but test anyway (it's NaN):
x[...] = np.ma.masked
# Finally, a large value that cannot be cast to the float32 `x`
x = np.ma.arange(3., dtype=np.float32)
value = np.ma.array([2e234, 1, 1], mask=[True, False, False])
x[...] = value
x[[0, 1, 2]] = value
@pytest.mark.filterwarnings(WARNING_MARK_SPEC)
def test_copy(self):
# Tests of some subtle points of copying and sizing.
n = [0, 0, 1, 0, 0]
m = make_mask(n)
m2 = make_mask(m)
assert_(m is m2)
m3 = make_mask(m, copy=True)
assert_(m is not m3)
x1 = np.arange(5)
y1 = array(x1, mask=m)
assert_equal(y1._data.__array_interface__, x1.__array_interface__)
assert_(allequal(x1, y1.data))
assert_equal(y1._mask.__array_interface__, m.__array_interface__)
y1a = array(y1)
# Default for masked array is not to copy; see gh-10318.
assert_(y1a._data.__array_interface__ ==
y1._data.__array_interface__)
assert_(y1a._mask.__array_interface__ ==
y1._mask.__array_interface__)
y2 = array(x1, mask=m3)
assert_(y2._data.__array_interface__ == x1.__array_interface__)
assert_(y2._mask.__array_interface__ == m3.__array_interface__)
assert_(y2[2] is masked)
y2[2] = 9
assert_(y2[2] is not masked)
assert_(y2._mask.__array_interface__ == m3.__array_interface__)
assert_(allequal(y2.mask, 0))
y2a = array(x1, mask=m, copy=1)
assert_(y2a._data.__array_interface__ != x1.__array_interface__)
#assert_( y2a._mask is not m)
assert_(y2a._mask.__array_interface__ != m.__array_interface__)
assert_(y2a[2] is masked)
y2a[2] = 9
assert_(y2a[2] is not masked)
#assert_( y2a._mask is not m)
assert_(y2a._mask.__array_interface__ != m.__array_interface__)
assert_(allequal(y2a.mask, 0))
y3 = array(x1 * 1.0, mask=m)
assert_(filled(y3).dtype is (x1 * 1.0).dtype)
x4 = arange(4)
x4[2] = masked
y4 = resize(x4, (8,))
assert_equal(concatenate([x4, x4]), y4)
assert_equal(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])
y5 = repeat(x4, (2, 2, 2, 2), axis=0)
assert_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3])
y6 = repeat(x4, 2, axis=0)
assert_equal(y5, y6)
y7 = x4.repeat((2, 2, 2, 2), axis=0)
assert_equal(y5, y7)
y8 = x4.repeat(2, 0)
assert_equal(y5, y8)
y9 = x4.copy()
assert_equal(y9._data, x4._data)
assert_equal(y9._mask, x4._mask)
x = masked_array([1, 2, 3], mask=[0, 1, 0])
# Copy is False by default
y = masked_array(x)
assert_equal(y._data.ctypes.data, x._data.ctypes.data)
assert_equal(y._mask.ctypes.data, x._mask.ctypes.data)
y = masked_array(x, copy=True)
assert_not_equal(y._data.ctypes.data, x._data.ctypes.data)
assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data)
def test_copy_0d(self):
# gh-9430
x = np.ma.array(43, mask=True)
xc = x.copy()
assert_equal(xc.mask, True)
def test_copy_on_python_builtins(self):
# Tests copy works on python builtins (issue#8019)
assert_(isMaskedArray(np.ma.copy([1, 2, 3])))
assert_(isMaskedArray(np.ma.copy((1, 2, 3))))
def test_copy_immutable(self):
# Tests that the copy method is immutable, GitHub issue #5247
a = np.ma.array([1, 2, 3])
b = np.ma.array([4, 5, 6])
a_copy_method = a.copy
b.copy
assert_equal(a_copy_method(), [1, 2, 3])
def test_deepcopy(self):
from copy import deepcopy
a = array([0, 1, 2], mask=[False, True, False])
copied = deepcopy(a)
assert_equal(copied.mask, a.mask)
assert_not_equal(id(a._mask), id(copied._mask))
copied[1] = 1
assert_equal(copied.mask, [0, 0, 0])
assert_equal(a.mask, [0, 1, 0])
copied = deepcopy(a)
assert_equal(copied.mask, a.mask)
copied.mask[1] = False
assert_equal(copied.mask, [0, 0, 0])
assert_equal(a.mask, [0, 1, 0])
def test_format(self):
a = array([0, 1, 2], mask=[False, True, False])
assert_equal(format(a), "[0 -- 2]")
assert_equal(format(masked), "--")
assert_equal(format(masked, ""), "--")
# Postponed from PR #15410, perhaps address in the future.
# assert_equal(format(masked, " >5"), " --")
# assert_equal(format(masked, " <5"), "-- ")
# Expect a FutureWarning for using format_spec with MaskedElement
with pytest.warns(FutureWarning):
with_format_string = format(masked, " >5")
assert_equal(with_format_string, "--")
def test_str_repr(self):
a = array([0, 1, 2], mask=[False, True, False])
assert_equal(str(a), '[0 -- 2]')
assert_equal(
repr(a),
textwrap.dedent('''\
masked_array(data=[0, --, 2],
mask=[False, True, False],
fill_value=999999)''')
)
# arrays with a continuation
a = np.ma.arange(2000)
a[1:50] = np.ma.masked
assert_equal(
repr(a),
textwrap.dedent('''\
masked_array(data=[0, --, --, ..., 1997, 1998, 1999],
mask=[False, True, True, ..., False, False, False],
fill_value=999999)''')
)
# line-wrapped 1d arrays are correctly aligned
a = np.ma.arange(20)
assert_equal(
repr(a),
textwrap.dedent('''\
masked_array(data=[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19],
mask=False,
fill_value=999999)''')
)
# 2d arrays cause wrapping
a = array([[1, 2, 3], [4, 5, 6]], dtype=np.int8)
a[1, 1] = np.ma.masked
assert_equal(
repr(a),
textwrap.dedent(f'''\
masked_array(
data=[[1, 2, 3],
[4, --, 6]],
mask=[[False, False, False],
[False, True, False]],
fill_value={np.array(999999)[()]!r},
dtype=int8)''')
)
# but not it they're a row vector
assert_equal(
repr(a[:1]),
textwrap.dedent(f'''\
masked_array(data=[[1, 2, 3]],
mask=[[False, False, False]],
fill_value={np.array(999999)[()]!r},
dtype=int8)''')
)
# dtype=int is implied, so not shown
assert_equal(
repr(a.astype(int)),
textwrap.dedent('''\
masked_array(
data=[[1, 2, 3],
[4, --, 6]],
mask=[[False, False, False],
[False, True, False]],
fill_value=999999)''')
)
def test_str_repr_legacy(self):
oldopts = np.get_printoptions()
np.set_printoptions(legacy='1.13')
try:
a = array([0, 1, 2], mask=[False, True, False])
assert_equal(str(a), '[0 -- 2]')
assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
' mask = [False True False],\n'
' fill_value = 999999)\n')
a = np.ma.arange(2000)
a[1:50] = np.ma.masked
assert_equal(
repr(a),
'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
' mask = [False True True ..., False False False],\n'
' fill_value = 999999)\n'
)
finally:
np.set_printoptions(**oldopts)
def test_0d_unicode(self):
u = 'caf\xe9'
utype = type(u)
arr_nomask = np.ma.array(u)
arr_masked = np.ma.array(u, mask=True)
assert_equal(utype(arr_nomask), u)
assert_equal(utype(arr_masked), '--')
def test_pickling(self):
# Tests pickling
for dtype in (int, float, str, object):
a = arange(10).astype(dtype)
a.fill_value = 999
masks = ([0, 0, 0, 1, 0, 1, 0, 1, 0, 1], # partially masked
True, # Fully masked
False) # Fully unmasked
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
for mask in masks:
a.mask = mask
a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
assert_equal(a_pickled._mask, a._mask)
assert_equal(a_pickled._data, a._data)
if dtype in (object, int):
assert_equal(a_pickled.fill_value, 999)
else:
assert_equal(a_pickled.fill_value, dtype(999))
assert_array_equal(a_pickled.mask, mask)
def test_pickling_subbaseclass(self):
# Test pickling w/ a subclass of ndarray
x = np.array([(1.0, 2), (3.0, 4)],
dtype=[('x', float), ('y', int)]).view(np.recarray)
a = masked_array(x, mask=[(True, False), (False, True)])
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
assert_equal(a_pickled._mask, a._mask)
assert_equal(a_pickled, a)
assert_(isinstance(a_pickled._data, np.recarray))
def test_pickling_maskedconstant(self):
# Test pickling MaskedConstant
mc = np.ma.masked
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
mc_pickled = pickle.loads(pickle.dumps(mc, protocol=proto))
assert_equal(mc_pickled._baseclass, mc._baseclass)
assert_equal(mc_pickled._mask, mc._mask)
assert_equal(mc_pickled._data, mc._data)
def test_pickling_wstructured(self):
# Tests pickling w/ structured array
a = array([(1, 1.), (2, 2.)], mask=[(0, 0), (0, 1)],
dtype=[('a', int), ('b', float)])
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
assert_equal(a_pickled._mask, a._mask)
assert_equal(a_pickled, a)
def test_pickling_keepalignment(self):
# Tests pickling w/ F_CONTIGUOUS arrays
a = arange(10).reshape( (-1, 2))
b = a.T
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
test = pickle.loads(pickle.dumps(b, protocol=proto))
assert_equal(test, b)
def test_single_element_subscript(self):
# Tests single element subscripts of Maskedarrays.
a = array([1, 3, 2])
b = array([1, 3, 2], mask=[1, 0, 1])
assert_equal(a[0].shape, ())
assert_equal(b[0].shape, ())
assert_equal(b[1].shape, ())
def test_topython(self):
# Tests some communication issues with Python.
assert_equal(1, int(array(1)))
assert_equal(1.0, float(array(1)))
assert_equal(1, int(array([[[1]]])))
assert_equal(1.0, float(array([[1]])))
assert_raises(TypeError, float, array([1, 1]))
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore', 'Warning: converting a masked element', UserWarning)
assert_(np.isnan(float(array([1], mask=[1]))))
a = array([1, 2, 3], mask=[1, 0, 0])
assert_raises(TypeError, lambda: float(a))
assert_equal(float(a[-1]), 3.)
assert_(np.isnan(float(a[0])))
assert_raises(TypeError, int, a)
assert_equal(int(a[-1]), 3)
assert_raises(MAError, lambda: int(a[0]))
def test_oddfeatures_1(self):
# Test of other odd features
x = arange(20)
x = x.reshape(4, 5)
x.flat[5] = 12
assert_(x[1, 0] == 12)
z = x + 10j * x
assert_equal(z.real, x)
assert_equal(z.imag, 10 * x)
assert_equal((z * conjugate(z)).real, 101 * x * x)
z.imag[...] = 0.0
x = arange(10)
x[3] = masked
assert_(str(x[3]) == str(masked))
c = x >= 8
assert_(count(where(c, masked, masked)) == 0)
assert_(shape(where(c, masked, masked)) == c.shape)
z = masked_where(c, x)
assert_(z.dtype is x.dtype)
assert_(z[3] is masked)
assert_(z[4] is not masked)
assert_(z[7] is not masked)
assert_(z[8] is masked)
assert_(z[9] is masked)
assert_equal(x, z)
def test_oddfeatures_2(self):
# Tests some more features.
x = array([1., 2., 3., 4., 5.])
c = array([1, 1, 1, 0, 0])
x[2] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
c[0] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
assert_(z[0] is masked)
assert_(z[1] is not masked)
assert_(z[2] is masked)
def test_oddfeatures_3(self):
msg = "setting an item on a masked array which has a shared mask will not copy"
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore', msg, numpy.ma.core.MaskedArrayFutureWarning)
# Tests some generic features
atest = array([10], mask=True)
btest = array([20])
idx = atest.mask
atest[idx] = btest[idx]
assert_equal(atest, [20])
def test_filled_with_object_dtype(self):
a = np.ma.masked_all(1, dtype='O')
assert_equal(a.filled('x')[0], 'x')
def test_filled_with_flexible_dtype(self):
# Test filled w/ flexible dtype
flexi = array([(1, 1, 1)],
dtype=[('i', int), ('s', '|S8'), ('f', float)])
flexi[0] = masked
assert_equal(flexi.filled(),
np.array([(default_fill_value(0),
default_fill_value('0'),
default_fill_value(0.),)], dtype=flexi.dtype))
flexi[0] = masked
assert_equal(flexi.filled(1),
np.array([(1, '1', 1.)], dtype=flexi.dtype))
def test_filled_with_mvoid(self):
# Test filled w/ mvoid
ndtype = [('a', int), ('b', float)]
a = mvoid((1, 2.), mask=[(0, 1)], dtype=ndtype)
# Filled using default
test = a.filled()
assert_equal(tuple(test), (1, default_fill_value(1.)))
# Explicit fill_value
test = a.filled((-1, -1))
assert_equal(tuple(test), (1, -1))
# Using predefined filling values
a.fill_value = (-999, -999)
assert_equal(tuple(a.filled()), (1, -999))
def test_filled_with_nested_dtype(self):
# Test filled w/ nested dtype
ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])]
a = array([(1, (1, 1)), (2, (2, 2))],
mask=[(0, (1, 0)), (0, (0, 1))], dtype=ndtype)
test = a.filled(0)
control = np.array([(1, (0, 1)), (2, (2, 0))], dtype=ndtype)
assert_equal(test, control)
test = a['B'].filled(0)
control = np.array([(0, 1), (2, 0)], dtype=a['B'].dtype)
assert_equal(test, control)
# test if mask gets set correctly (see #6760)
Z = numpy.ma.zeros(2, numpy.dtype([("A", "(2,2)i1,(2,2)i1", (2, 2))]))
assert_equal(Z.data.dtype, numpy.dtype([('A', [('f0', 'i1', (2, 2)),
('f1', 'i1', (2, 2))], (2, 2))]))
assert_equal(Z.mask.dtype, numpy.dtype([('A', [('f0', '?', (2, 2)),
('f1', '?', (2, 2))], (2, 2))]))
def test_filled_with_f_order(self):
# Test filled w/ F-contiguous array
a = array(np.array([(0, 1, 2), (4, 5, 6)], order='F'),
mask=np.array([(0, 0, 1), (1, 0, 0)], order='F'),
order='F') # this is currently ignored
assert_(a.flags['F_CONTIGUOUS'])
assert_(a.filled(0).flags['F_CONTIGUOUS'])
def test_optinfo_propagation(self):
# Checks that _optinfo dictionary isn't back-propagated
x = array([1, 2, 3, ], dtype=float)
x._optinfo['info'] = '???'
y = x.copy()
assert_equal(y._optinfo['info'], '???')
y._optinfo['info'] = '!!!'
assert_equal(x._optinfo['info'], '???')
def test_optinfo_forward_propagation(self):
a = array([1, 2, 2, 4])
a._optinfo["key"] = "value"
assert_equal(a._optinfo["key"], (a == 2)._optinfo["key"])
assert_equal(a._optinfo["key"], (a != 2)._optinfo["key"])
assert_equal(a._optinfo["key"], (a > 2)._optinfo["key"])
assert_equal(a._optinfo["key"], (a >= 2)._optinfo["key"])
assert_equal(a._optinfo["key"], (a <= 2)._optinfo["key"])
assert_equal(a._optinfo["key"], (a + 2)._optinfo["key"])
assert_equal(a._optinfo["key"], (a - 2)._optinfo["key"])
assert_equal(a._optinfo["key"], (a * 2)._optinfo["key"])
assert_equal(a._optinfo["key"], (a / 2)._optinfo["key"])
assert_equal(a._optinfo["key"], a[:2]._optinfo["key"])
assert_equal(a._optinfo["key"], a[[0, 0, 2]]._optinfo["key"])
assert_equal(a._optinfo["key"], np.exp(a)._optinfo["key"])
assert_equal(a._optinfo["key"], np.abs(a)._optinfo["key"])
assert_equal(a._optinfo["key"], array(a, copy=True)._optinfo["key"])
assert_equal(a._optinfo["key"], np.zeros_like(a)._optinfo["key"])
def test_fancy_printoptions(self):
# Test printing a masked array w/ fancy dtype.
fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
test = array([(1, (2, 3.0)), (4, (5, 6.0))],
mask=[(1, (0, 1)), (0, (1, 0))],
dtype=fancydtype)
control = "[(--, (2, --)) (4, (--, 6.0))]"
assert_equal(str(test), control)
# Test 0-d array with multi-dimensional dtype
t_2d0 = masked_array(data=(0, [[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0]],
0.0),
mask=(False, [[True, False, True],
[False, False, True]],
False),
dtype="int, (2,3)float, float")
control = "(0, [[--, 0.0, --], [0.0, 0.0, --]], 0.0)"
assert_equal(str(t_2d0), control)
def test_flatten_structured_array(self):
# Test flatten_structured_array on arrays
# On ndarray
ndtype = [('a', int), ('b', float)]
a = np.array([(1, 1), (2, 2)], dtype=ndtype)
test = flatten_structured_array(a)
control = np.array([[1., 1.], [2., 2.]], dtype=float)
assert_equal(test, control)
assert_equal(test.dtype, control.dtype)
# On masked_array
a = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
test = flatten_structured_array(a)
control = array([[1., 1.], [2., 2.]],
mask=[[0, 1], [1, 0]], dtype=float)
assert_equal(test, control)
assert_equal(test.dtype, control.dtype)
assert_equal(test.mask, control.mask)
# On masked array with nested structure
ndtype = [('a', int), ('b', [('ba', int), ('bb', float)])]
a = array([(1, (1, 1.1)), (2, (2, 2.2))],
mask=[(0, (1, 0)), (1, (0, 1))], dtype=ndtype)
test = flatten_structured_array(a)
control = array([[1., 1., 1.1], [2., 2., 2.2]],
mask=[[0, 1, 0], [1, 0, 1]], dtype=float)
assert_equal(test, control)
assert_equal(test.dtype, control.dtype)
assert_equal(test.mask, control.mask)
# Keeping the initial shape
ndtype = [('a', int), ('b', float)]
a = np.array([[(1, 1), ], [(2, 2), ]], dtype=ndtype)
test = flatten_structured_array(a)
control = np.array([[[1., 1.], ], [[2., 2.], ]], dtype=float)
assert_equal(test, control)
assert_equal(test.dtype, control.dtype)
def test_void0d(self):
# Test creating a mvoid object
ndtype = [('a', int), ('b', int)]
a = np.array([(1, 2,)], dtype=ndtype)[0]
f = mvoid(a)
assert_(isinstance(f, mvoid))
a = masked_array([(1, 2)], mask=[(1, 0)], dtype=ndtype)[0]
assert_(isinstance(a, mvoid))
a = masked_array([(1, 2), (1, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
f = mvoid(a._data[0], a._mask[0])
assert_(isinstance(f, mvoid))
def test_mvoid_getitem(self):
# Test mvoid.__getitem__
ndtype = [('a', int), ('b', int)]
a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)],
dtype=ndtype)
# w/o mask
f = a[0]
assert_(isinstance(f, mvoid))
assert_equal((f[0], f['a']), (1, 1))
assert_equal(f['b'], 2)
# w/ mask
f = a[1]
assert_(isinstance(f, mvoid))
assert_(f[0] is masked)
assert_(f['a'] is masked)
assert_equal(f[1], 4)
# exotic dtype
A = masked_array(data=[([0, 1],)],
mask=[([True, False],)],
dtype=[("A", ">i2", (2,))])
assert_equal(A[0]["A"], A["A"][0])
assert_equal(A[0]["A"], masked_array(data=[0, 1],
mask=[True, False], dtype=">i2"))
def test_mvoid_iter(self):
# Test iteration on __getitem__
ndtype = [('a', int), ('b', int)]
a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)],
dtype=ndtype)
# w/o mask
assert_equal(list(a[0]), [1, 2])
# w/ mask
assert_equal(list(a[1]), [masked, 4])
@pytest.mark.thread_unsafe(reason="masked_print_option.set_display global state")
def test_mvoid_print(self):
# Test printing a mvoid
mx = array([(1, 1), (2, 2)], dtype=[('a', int), ('b', int)])
assert_equal(str(mx[0]), "(1, 1)")
mx['b'][0] = masked
ini_display = masked_print_option._display
masked_print_option.set_display("-X-")
try:
assert_equal(str(mx[0]), "(1, -X-)")
assert_equal(repr(mx[0]), "(1, -X-)")
finally:
masked_print_option.set_display(ini_display)
# also check if there are object datatypes (see gh-7493)
mx = array([(1,), (2,)], dtype=[('a', 'O')])
assert_equal(str(mx[0]), "(1,)")
@pytest.mark.thread_unsafe(reason="masked_print_option global state")
def test_mvoid_multidim_print(self):
# regression test for gh-6019
t_ma = masked_array(data=[([1, 2, 3],)],
mask=[([False, True, False],)],
fill_value=([999999, 999999, 999999],),
dtype=[('a', '<i4', (3,))])
assert_(str(t_ma[0]) == "([1, --, 3],)")
assert_(repr(t_ma[0]) == "([1, --, 3],)")
# additional tests with structured arrays
t_2d = masked_array(data=[([[1, 2], [3, 4]],)],
mask=[([[False, True], [True, False]],)],
dtype=[('a', '<i4', (2, 2))])
assert_(str(t_2d[0]) == "([[1, --], [--, 4]],)")
assert_(repr(t_2d[0]) == "([[1, --], [--, 4]],)")
t_0d = masked_array(data=[(1, 2)],
mask=[(True, False)],
dtype=[('a', '<i4'), ('b', '<i4')])
assert_(str(t_0d[0]) == "(--, 2)")
assert_(repr(t_0d[0]) == "(--, 2)")
t_2d = masked_array(data=[([[1, 2], [3, 4]], 1)],
mask=[([[False, True], [True, False]], False)],
dtype=[('a', '<i4', (2, 2)), ('b', float)])
assert_(str(t_2d[0]) == "([[1, --], [--, 4]], 1.0)")
assert_(repr(t_2d[0]) == "([[1, --], [--, 4]], 1.0)")
t_ne = masked_array(data=[(1, (1, 1))],
mask=[(True, (True, False))],
dtype=[('a', '<i4'), ('b', 'i4,i4')])
assert_(str(t_ne[0]) == "(--, (--, 1))")
assert_(repr(t_ne[0]) == "(--, (--, 1))")
def test_object_with_array(self):
mx1 = masked_array([1.], mask=[True])
mx2 = masked_array([1., 2.])
mx = masked_array([mx1, mx2], mask=[False, True], dtype=object)
assert_(mx[0] is mx1)
assert_(mx[1] is not mx2)
assert_(np.all(mx[1].data == mx2.data))
assert_(np.all(mx[1].mask))
# check that we return a view.
mx[1].data[0] = 0.
assert_(mx2[0] == 0.)
def test_maskedarray_tofile_raises_notimplementederror(self):
xm = masked_array([1, 2, 3], mask=[False, True, False])
# Test case to check the NotImplementedError.
# It is not implemented at this point of time. We can change this in future
with temppath(suffix='.npy') as path:
with pytest.raises(NotImplementedError):
np.save(path, xm)
| TestMaskedArray |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_test.py | {
"start": 72975,
"end": 76452
} | class ____(parameterized.TestCase, test_lib.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_increasing_and_decreasing(self):
x = constant_op.constant([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]],
dtype=dtypes.float64)
y, segments = nn_ops.isotonic_regression(x, decreasing=False)
self.assertAllClose(y, x)
self.assertAllClose(segments, [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]])
y, segments = nn_ops.isotonic_regression(x, decreasing=True)
self.assertAllClose(
y,
[
[2, 2, 2, 2, 2], # Average of the inputs.
[7, 7, 7, 7, 7]
])
self.assertAllClose(segments, array_ops.zeros((2, 5)))
# pylint: disable=invalid-unary-operand-type
y, segments = nn_ops.isotonic_regression(-x, decreasing=True)
self.assertAllClose(segments, [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]])
self.assertAllClose(y, -x)
y, segments = nn_ops.isotonic_regression(-x, decreasing=False)
self.assertAllClose(
-y,
[
[2, 2, 2, 2, 2], # Average of the inputs.
[7, 7, 7, 7, 7]
])
self.assertAllClose(segments, array_ops.zeros((2, 5)))
@test_util.run_in_graph_and_eager_modes
def test_different_axis(self):
x = constant_op.constant([[0, 6, 2, 8, 4], [5, 1, 7, 3, 9]],
dtype=dtypes.float64)
y, segments = nn_ops.isotonic_regression(x, decreasing=True, axis=0)
self.assertAllClose(
y,
[
[2.5, 6, 4.5, 8, 6.5], # Either identity or average.
[2.5, 1, 4.5, 3, 6.5]
])
self.assertAllClose(segments, [[0, 0, 0, 0, 0], [0, 1, 0, 1, 0]])
@test_util.run_v2_only
def testGradientV2(self, dtype=np.float64, batch_size=30, dimensions=50):
@def_function.function
def ComputeIsotonicFn(x):
y, _ = nn_ops.isotonic_regression(x) # No gradient wrt segments.
return y
np.random.seed(0)
x_init = np.random.randn(batch_size, dimensions).astype(dtype)
grad_theoretical, grad_numerical = gradient_checker_v2.compute_gradient(
ComputeIsotonicFn, [x_init], delta=1e-5)
self.assertAllClose(grad_theoretical, grad_numerical)
@test_util.run_v1_only("compute_gradient_error is v1 only")
def testGradientV1(self, dtype=np.float64, batch_size=30, dimensions=50):
np.random.seed(0)
x_init = np.random.randn(batch_size, dimensions).astype(dtype)
with self.cached_session():
x = array_ops.placeholder(dtype, (batch_size, dimensions))
y, _ = nn_ops.isotonic_regression(x) # Segments have no gradient.
max_error = gradient_checker.compute_gradient_error(
x, (batch_size, dimensions), y, (batch_size, dimensions), x_init)
self.assertAllClose(max_error, 0.)
@parameterized.parameters([[dtypes.half, dtypes.half],
[dtypes.bfloat16, dtypes.bfloat16],
[dtypes.float32, dtypes.float32],
[dtypes.float64, dtypes.float64],
[dtypes.int32, dtypes.float64],
[dtypes.int16, dtypes.float32]])
def testTypePromotion(self, dtype_in, expected_dtype_out):
x = constant_op.constant([[0, 6, 2, 8, 4], [5, 1, 7, 3, 9]], dtype=dtype_in)
y, segments = nn_ops.isotonic_regression(x)
self.assertEqual(y.dtype, expected_dtype_out)
self.assertEqual(segments.dtype, dtypes.int32)
if __name__ == "__main__":
test_lib.main()
| IsotonicTest |
python | tornadoweb__tornado | tornado/httpserver.py | {
"start": 14927,
"end": 16131
} | class ____(httputil.HTTPMessageDelegate):
def __init__(
self,
delegate: httputil.HTTPMessageDelegate,
request_conn: httputil.HTTPConnection,
) -> None:
self.connection = request_conn
self.delegate = delegate
def headers_received(
self,
start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
headers: httputil.HTTPHeaders,
) -> Optional[Awaitable[None]]:
# TODO: either make context an official part of the
# HTTPConnection interface or figure out some other way to do this.
self.connection.context._apply_xheaders(headers) # type: ignore
return self.delegate.headers_received(start_line, headers)
def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
return self.delegate.data_received(chunk)
def finish(self) -> None:
self.delegate.finish()
self._cleanup()
def on_connection_close(self) -> None:
self.delegate.on_connection_close()
self._cleanup()
def _cleanup(self) -> None:
self.connection.context._unapply_xheaders() # type: ignore
HTTPRequest = httputil.HTTPServerRequest
| _ProxyAdapter |
python | huggingface__transformers | tests/models/bloom/test_modeling_bloom.py | {
"start": 1069,
"end": 7232
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = BloomModel
def create_and_check_bloom_model_past(self, config, *args):
input_ids, _, input_mask, _, _, _ = args
model = BloomModel(config=config)
model.to(torch_device)
model.eval()
# first forward pass
outputs = model(input_ids, attention_mask=torch.ones_like(input_ids), use_cache=True)
outputs_use_cache_conf = model(input_ids, attention_mask=torch.ones_like(input_ids))
outputs_no_past = model(input_ids, use_cache=False, attention_mask=torch.ones_like(input_ids))
self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
past = outputs["past_key_values"]
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
# append to next input_ids and token_type_ids
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
output_from_no_past = model(next_input_ids)["last_hidden_state"]
output_from_past = model(next_tokens, past_key_values=past)["last_hidden_state"]
# select random slice
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
def create_and_check_bloom_model_attention_mask_past(self, config, *args):
input_ids, _, input_mask, _, _, _ = args
model = BloomModel(config=config)
model.to(torch_device)
model.eval()
# create attention mask
attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
half_seq_length = self.seq_length // 2
attn_mask[:, half_seq_length:] = 0
# first forward pass
output, past = model(input_ids, attention_mask=attn_mask).to_tuple()
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
# change a random masked slice from input_ids
random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
# append to next input_ids and attn_mask
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
attn_mask = torch.cat(
[attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
dim=1,
)
# get two different outputs
output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"]
# select random slice
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
def create_and_check_bloom_model_past_large_inputs(self, config, *args):
input_ids, _, input_mask, _, _, _ = args
model = BloomModel(config=config)
model.to(torch_device)
model.eval()
# first forward pass
outputs = model(input_ids, attention_mask=input_mask, use_cache=True)
output, past = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
# append to next input_ids and token_type_ids
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past)[
"last_hidden_state"
]
self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1])
# select random slice
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
def create_and_check_lm_head_model(self, config, *args):
input_ids, _, input_mask, _, _, _ = args
model = BloomForCausalLM(config)
model.to(torch_device)
model.eval()
result = model(input_ids, labels=input_ids)
self.parent.assertEqual(result.loss.shape, ())
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
def create_and_check_bloom_weight_initialization(self, config, *args):
model = BloomModel(config)
model_std = model.config.initializer_range / math.sqrt(2 * model.config.n_layer)
for key in model.state_dict():
if "c_proj" in key and "weight" in key:
self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std), 0.001)
self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0), 0.01)
@require_torch
| BloomModelTester |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.