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
django-extensions__django-extensions
tests/test_templatetags.py
{ "start": 240, "end": 631 }
class ____(TestCase): def test_widont(self): self.assertEqual(widont("Test Value"), "Test Value") self.assertEqual(widont(str("Test Value")), str("Test Value")) def test_widont_html(self): self.assertEqual(widont_html("Test Value"), "Test Value") self.assertEqual(widont_html(str("Test Value")), str("Test Value"))
TemplateTagsTests
python
getsentry__sentry
src/sentry/api/serializers/models/dashboard.py
{ "start": 1433, "end": 1513 }
class ____(TypedDict): field: str dashboardId: int
LinkedDashboardResponse
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 52473, "end": 52759 }
class ____(BaseModel): """ See source code for the fields' description. An arbitrary object where the object key is a configuration property name and the value is a configuration property value. """ model_config = ConfigDict(extra="allow", frozen=True)
SparkConfPair
python
scipy__scipy
scipy/spatial/tests/test_kdtree.py
{ "start": 19006, "end": 21880 }
class ____: def distance(self, a, b, p): return minkowski_distance(a, b, p) def test_consistency_with_neighbors(self): M = self.T1.sparse_distance_matrix(self.T2, self.r) r = self.T1.query_ball_tree(self.T2, self.r) for i, l in enumerate(r): for j in l: assert_almost_equal( M[i, j], self.distance(self.T1.data[i], self.T2.data[j], self.p), decimal=14 ) for ((i, j), d) in M.items(): assert_(j in r[i]) def test_zero_distance(self): # raises an exception for bug 870 (FIXME: Does it?) self.T1.sparse_distance_matrix(self.T1, self.r) def test_consistency(self): # Test consistency with a distance_matrix M1 = self.T1.sparse_distance_matrix(self.T2, self.r) expected = distance_matrix(self.T1.data, self.T2.data) expected[expected > self.r] = 0 assert_array_almost_equal(M1.toarray(), expected, decimal=14) def test_against_logic_error_regression(self): # regression test for gh-5077 logic error np.random.seed(0) too_many = np.array(np.random.randn(18, 2), dtype=int) tree = self.kdtree_type( too_many, balanced_tree=False, compact_nodes=False) d = tree.sparse_distance_matrix(tree, 3).toarray() assert_array_almost_equal(d, d.T, decimal=14) def test_ckdtree_return_types(self): # brute-force reference ref = np.zeros((self.n, self.n)) for i in range(self.n): for j in range(self.n): v = self.data1[i, :] - self.data2[j, :] ref[i, j] = np.dot(v, v) ref = np.sqrt(ref) ref[ref > self.r] = 0. # test return type 'dict' dist = np.zeros((self.n, self.n)) r = self.T1.sparse_distance_matrix(self.T2, self.r, output_type='dict') for i, j in r.keys(): dist[i, j] = r[(i, j)] assert_array_almost_equal(ref, dist, decimal=14) # test return type 'ndarray' dist = np.zeros((self.n, self.n)) r = self.T1.sparse_distance_matrix(self.T2, self.r, output_type='ndarray') for k in range(r.shape[0]): i = r['i'][k] j = r['j'][k] v = r['v'][k] dist[i, j] = v assert_array_almost_equal(ref, dist, decimal=14) # test return type 'dok_matrix' r = self.T1.sparse_distance_matrix(self.T2, self.r, output_type='dok_matrix') assert_array_almost_equal(ref, r.toarray(), decimal=14) # test return type 'coo_matrix' r = self.T1.sparse_distance_matrix(self.T2, self.r, output_type='coo_matrix') assert_array_almost_equal(ref, r.toarray(), decimal=14) @KDTreeTest
sparse_distance_matrix_consistency
python
ray-project__ray
python/ray/_private/runtime_env/protocol.py
{ "start": 58, "end": 9516 }
class ____: _MISSING_DEPENDENCIES_WARNING = ( "Note that these must be preinstalled " "on all nodes in the Ray cluster; it is not " "sufficient to install them in the runtime_env." ) @classmethod def get_protocols(cls): return { # For packages dynamically uploaded and managed by the GCS. "gcs", # For conda environments installed locally on each node. "conda", # For pip environments installed locally on each node. "pip", # For uv environments install locally on each node. "uv", # Remote https path, assumes everything packed in one zip file. "https", # Remote s3 path, assumes everything packed in one zip file. "s3", # Remote google storage path, assumes everything packed in one zip file. "gs", # Remote azure blob storage path, assumes everything packed in one zip file. "azure", # Remote Azure Blob File System Secure path, assumes everything packed in one zip file. "abfss", # File storage path, assumes everything packed in one zip file. "file", } @classmethod def get_remote_protocols(cls): return {"https", "s3", "gs", "azure", "abfss", "file"} @classmethod def _handle_s3_protocol(cls): """Set up S3 protocol handling. Returns: tuple: (open_file function, transport_params) Raises: ImportError: If required dependencies are not installed. """ try: import boto3 from smart_open import open as open_file except ImportError: raise ImportError( "You must `pip install smart_open[s3]` " "to fetch URIs in s3 bucket. " + cls._MISSING_DEPENDENCIES_WARNING ) # Create S3 client, falling back to unsigned for public buckets session = boto3.Session() # session.get_credentials() will return None if no credentials can be found. if session.get_credentials(): # If credentials are found, use a standard signed client. s3_client = session.client("s3") else: # No credentials found, fall back to an unsigned client for public buckets. from botocore import UNSIGNED from botocore.config import Config s3_client = boto3.client("s3", config=Config(signature_version=UNSIGNED)) transport_params = {"client": s3_client} return open_file, transport_params @classmethod def _handle_gs_protocol(cls): """Set up Google Cloud Storage protocol handling. Returns: tuple: (open_file function, transport_params) Raises: ImportError: If required dependencies are not installed. """ try: from google.cloud import storage # noqa: F401 from smart_open import open as open_file except ImportError: raise ImportError( "You must `pip install smart_open[gcs]` " "to fetch URIs in Google Cloud Storage bucket." + cls._MISSING_DEPENDENCIES_WARNING ) return open_file, None @classmethod def _handle_azure_protocol(cls): """Set up Azure blob storage protocol handling. Returns: tuple: (open_file function, transport_params) Raises: ImportError: If required dependencies are not installed. ValueError: If required environment variables are not set. """ try: from azure.identity import DefaultAzureCredential from azure.storage.blob import BlobServiceClient # noqa: F401 from smart_open import open as open_file except ImportError: raise ImportError( "You must `pip install azure-storage-blob azure-identity smart_open[azure]` " "to fetch URIs in Azure Blob Storage. " + cls._MISSING_DEPENDENCIES_WARNING ) # Define authentication variable azure_storage_account_name = os.getenv("AZURE_STORAGE_ACCOUNT") if not azure_storage_account_name: raise ValueError( "Azure Blob Storage authentication requires " "AZURE_STORAGE_ACCOUNT environment variable to be set." ) account_url = f"https://{azure_storage_account_name}.blob.core.windows.net/" transport_params = { "client": BlobServiceClient( account_url=account_url, credential=DefaultAzureCredential() ) } return open_file, transport_params @classmethod def _handle_abfss_protocol(cls): """Set up Azure Blob File System Secure (ABFSS) protocol handling. Returns: tuple: (open_file function, transport_params) Raises: ImportError: If required dependencies are not installed. ValueError: If the ABFSS URI format is invalid. """ try: import adlfs from azure.identity import DefaultAzureCredential except ImportError: raise ImportError( "You must `pip install adlfs azure-identity` " "to fetch URIs in Azure Blob File System Secure. " + cls._MISSING_DEPENDENCIES_WARNING ) def open_file(uri, mode, *, transport_params=None): # Parse and validate the ABFSS URI parsed = urlparse(uri) # Validate ABFSS URI format: abfss://container@account.dfs.core.windows.net/path if not parsed.netloc or "@" not in parsed.netloc: raise ValueError( f"Invalid ABFSS URI format - missing container@account: {uri}" ) container_part, hostname_part = parsed.netloc.split("@", 1) # Validate container name (must be non-empty) if not container_part: raise ValueError( f"Invalid ABFSS URI format - empty container name: {uri}" ) # Validate hostname format if not hostname_part or not hostname_part.endswith(".dfs.core.windows.net"): raise ValueError( f"Invalid ABFSS URI format - invalid hostname (must end with .dfs.core.windows.net): {uri}" ) # Extract and validate account name azure_storage_account_name = hostname_part.split(".")[0] if not azure_storage_account_name: raise ValueError( f"Invalid ABFSS URI format - empty account name: {uri}" ) # Handle ABFSS URI with adlfs filesystem = adlfs.AzureBlobFileSystem( account_name=azure_storage_account_name, credential=DefaultAzureCredential(), ) return filesystem.open(uri, mode) return open_file, None @classmethod def download_remote_uri(cls, protocol: str, source_uri: str, dest_file: str): """Download file from remote URI to destination file. Args: protocol: The protocol to use for downloading (e.g., 's3', 'https'). source_uri: The source URI to download from. dest_file: The destination file path to save to. Raises: ImportError: If required dependencies for the protocol are not installed. """ assert protocol in cls.get_remote_protocols() tp = None open_file = None if protocol == "file": source_uri = source_uri[len("file://") :] def open_file(uri, mode, *, transport_params=None): return open(uri, mode) elif protocol == "s3": open_file, tp = cls._handle_s3_protocol() elif protocol == "gs": open_file, tp = cls._handle_gs_protocol() elif protocol == "azure": open_file, tp = cls._handle_azure_protocol() elif protocol == "abfss": open_file, tp = cls._handle_abfss_protocol() else: try: from smart_open import open as open_file except ImportError: raise ImportError( "You must `pip install smart_open` " f"to fetch {protocol.upper()} URIs. " + cls._MISSING_DEPENDENCIES_WARNING ) with open_file(source_uri, "rb", transport_params=tp) as fin: with open(dest_file, "wb") as fout: fout.write(fin.read()) Protocol = enum.Enum( "Protocol", {protocol.upper(): protocol for protocol in ProtocolsProvider.get_protocols()}, ) @classmethod def _remote_protocols(cls): # Returns a list of protocols that support remote storage # These protocols should only be used with paths that end in ".zip" or ".whl" return [ cls[protocol.upper()] for protocol in ProtocolsProvider.get_remote_protocols() ] Protocol.remote_protocols = _remote_protocols def _download_remote_uri(self, source_uri, dest_file): return ProtocolsProvider.download_remote_uri(self.value, source_uri, dest_file) Protocol.download_remote_uri = _download_remote_uri
ProtocolsProvider
python
facelessuser__pymdown-extensions
pymdownx/tilde.py
{ "start": 5060, "end": 5260 }
class ____(util.PatternSequenceProcessor): """Just subscript processor.""" PATTERNS = [ util.PatSeqItem(re.compile(SUB, re.DOTALL | re.UNICODE), 'single', 'sub') ]
TildeSubProcessor
python
sympy__sympy
sympy/codegen/approximations.py
{ "start": 3428, "end": 6448 }
class ____(Optimization): """ Approximates functions by expanding them as a series. Parameters ========== bounds : dict Mapping expressions to length 2 tuple of bounds (low, high). reltol : number Threshold for when to ignore a term. Taken relative to the largest lower bound among bounds. max_order : int Largest order to include in series expansion n_point_checks : int (even) The validity of an expansion (with respect to reltol) is checked at discrete points (linearly spaced over the bounds of the variable). The number of points used in this numerical check is given by this number. Examples ======== >>> from sympy import sin, pi >>> from sympy.abc import x, y >>> from sympy.codegen.rewriting import optimize >>> from sympy.codegen.approximations import SeriesApprox >>> bounds = {x: (-.1, .1), y: (pi-1, pi+1)} >>> series_approx2 = SeriesApprox(bounds, reltol=1e-2) >>> series_approx3 = SeriesApprox(bounds, reltol=1e-3) >>> series_approx8 = SeriesApprox(bounds, reltol=1e-8) >>> expr = sin(x)*sin(y) >>> optimize(expr, [series_approx2]) x*(-y + (y - pi)**3/6 + pi) >>> optimize(expr, [series_approx3]) (-x**3/6 + x)*sin(y) >>> optimize(expr, [series_approx8]) sin(x)*sin(y) """ def __init__(self, bounds, reltol, max_order=4, n_point_checks=4, **kwargs): super().__init__(**kwargs) self.bounds = bounds self.reltol = reltol self.max_order = max_order if n_point_checks % 2 == 1: raise ValueError("Checking the solution at expansion point is not helpful") self.n_point_checks = n_point_checks self._prec = math.ceil(-math.log10(self.reltol)) def __call__(self, expr): return expr.factor().replace(self.query, lambda arg: self.value(arg)) def query(self, expr): return (expr.is_Function and not isinstance(expr, UndefinedFunction) and len(expr.args) == 1) def value(self, fexpr): free_symbols = fexpr.free_symbols if len(free_symbols) != 1: return fexpr symb, = free_symbols if symb not in self.bounds: return fexpr lo, hi = self.bounds[symb] x0 = (lo + hi)/2 cheapest = None for n in range(self.max_order+1, 0, -1): fseri = fexpr.series(symb, x0=x0, n=n).removeO() n_ok = True for idx in range(self.n_point_checks): x = lo + idx*(hi - lo)/(self.n_point_checks - 1) val = fseri.xreplace({symb: x}) ref = fexpr.xreplace({symb: x}) if abs((1 - val/ref).evalf(self._prec)) > self.reltol: n_ok = False break if n_ok: cheapest = fseri else: break if cheapest is None: return fexpr else: return cheapest
SeriesApprox
python
PrefectHQ__prefect
src/prefect/server/orchestration/core_policy.py
{ "start": 41397, "end": 42349 }
class ____(GenericOrchestrationRule): """ Name the states if they have run more than once. In the special case where the initial state is an "AwaitingRetry" scheduled state, the proposed state will be renamed to "Retrying" instead. """ FROM_STATES = ALL_ORCHESTRATION_STATES TO_STATES = {StateType.RUNNING} async def before_transition( self, initial_state: states.State[Any] | None, proposed_state: states.State[Any] | None, context: OrchestrationContext[ orm_models.Run, core.TaskRunPolicy | core.FlowRunPolicy ], ) -> None: if initial_state is None or proposed_state is None: return run_count = context.run.run_count if run_count > 0: if initial_state.name == "AwaitingRetry": await self.rename_state("Retrying") else: await self.rename_state("Rerunning")
RenameReruns
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py
{ "start": 50885, "end": 51765 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testPlaceholder(self): foo = array_ops.sparse_placeholder(dtypes.float32, shape=(10, 47)) self.assertAllEqual([10, 47], foo.get_shape()) self.assertAllEqual([None, 2], foo.indices.get_shape().as_list()) @test_util.run_deprecated_v1 def testPartialShapePlaceholder(self): foo = array_ops.sparse_placeholder(dtypes.float32, shape=(None, 47)) self.assertAllEqual([None, 47], foo.get_shape().as_list()) self.assertAllEqual([None, 2], foo.indices.get_shape().as_list()) @test_util.run_deprecated_v1 def testNoShapePlaceholder(self): foo = array_ops.sparse_placeholder(dtypes.float32, shape=None) self.assertAllEqual(None, foo.get_shape()) self.assertAllEqual([None, None], foo.indices.get_shape().as_list()) if __name__ == "__main__": googletest.main()
SparsePlaceholderTest
python
numba__numba
numba/tests/npyufunc/ufuncbuilding_usecases.py
{ "start": 976, "end": 1061 }
class ____(Exception): pass def guerror(a, b, c): raise MyException
MyException
python
getsentry__sentry
src/sentry/integrations/base.py
{ "start": 12097, "end": 19304 }
class ____(abc.ABC): """ An IntegrationInstallation represents an installed integration and manages the core functionality of the integration. """ logger = logging.getLogger("sentry.integrations") def __init__(self, model: RpcIntegration | Integration, organization_id: int) -> None: self.model = model self.organization_id = organization_id @cached_property def org_integration(self) -> RpcOrganizationIntegration: from sentry.integrations.services.integration import integration_service integration = integration_service.get_organization_integration( integration_id=self.model.id, organization_id=self.organization_id, ) if integration is None: sentry_sdk.set_tag("integration_id", self.model.id) sentry_sdk.set_tag("organization_id", self.organization_id) raise OrganizationIntegrationNotFound("missing org_integration") return integration @cached_property def organization(self) -> RpcOrganization: organization = organization_service.get(id=self.organization_id) if organization is None: raise NotFound("organization_id not found") return organization def get_organization_config(self) -> Sequence[Any]: """ Returns a list of JSONForm configuration object descriptors used to configure the integration per-organization. This simply represents the configuration structure. See the JSONForm react component for structure details. """ return [] def update_organization_config(self, data: MutableMapping[str, Any]) -> None: """ Update the configuration field for an organization integration. """ from sentry.integrations.services.integration import integration_service if not self.org_integration: return config = self.org_integration.config 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_config_data(self) -> Mapping[str, Any]: if not self.org_integration: return {} return self.org_integration.config def get_dynamic_display_information(self) -> Mapping[str, Any] | None: return None @abc.abstractmethod def get_client(self) -> Any: """ Return an API client for the integration provider Use this method if the integration uses a single API key for all configurations and usage of the integration. """ raise NotImplementedError def get_keyring_client(self, keyid: int | str) -> Any: """ Return an API client with a scoped key based on the key_name. Use this method if your integration supports a 'keyring' of keys like opsgenie or pagerduty. """ raise NotImplementedError @cached_property def default_identity(self) -> RpcIdentity: """For Integrations that rely solely on user auth for authentication.""" try: org_integration = self.org_integration except OrganizationIntegrationNotFound: raise Identity.DoesNotExist else: if org_integration.default_auth_id is None: raise Identity.DoesNotExist identity = identity_service.get_identity(filter={"id": org_integration.default_auth_id}) if identity is None: scope = sentry_sdk.get_isolation_scope() scope.set_tag("integration_provider", self.model.get_provider().name) scope.set_tag("org_integration_id", org_integration.id) scope.set_tag("default_auth_id", org_integration.default_auth_id) raise Identity.DoesNotExist return identity def error_message_from_json(self, data: Mapping[str, Any]) -> Any: return data.get("message", "unknown error") def error_fields_from_json(self, data: Mapping[str, Any]) -> Any | None: """ If we can determine error fields from the response JSON this should format and return them, allowing an IntegrationFormError to be raised. Return None if no form errors are present. Error fields should be in the format: {field: [message]} """ return None def message_from_error(self, exc: Exception) -> str: if isinstance(exc, ApiUnauthorized): return ERR_UNAUTHORIZED elif isinstance(exc, ApiHostError): return exc.text elif isinstance(exc, UnsupportedResponseType): return ERR_UNSUPPORTED_RESPONSE_TYPE.format(content_type=exc.content_type) elif isinstance(exc, ApiError): if exc.json: msg = self.error_message_from_json(exc.json) or "unknown error" else: msg = "unknown error" return f"Error Communicating with {self.model.get_provider().name} (HTTP {exc.code}): {msg}" else: return ERR_INTERNAL def raise_error(self, exc: Exception, identity: Identity | None = None) -> NoReturn: if isinstance(exc, ApiUnauthorized): raise InvalidIdentity(self.message_from_error(exc), identity=identity).with_traceback( sys.exc_info()[2] ) elif isinstance(exc, ApiInvalidRequestError): if exc.json: error_fields = self.error_fields_from_json(exc.json) if error_fields is not None: raise IntegrationFormError(error_fields).with_traceback(sys.exc_info()[2]) raise IntegrationError(self.message_from_error(exc)).with_traceback(sys.exc_info()[2]) elif isinstance(exc, IntegrationError): raise else: raise IntegrationError(self.message_from_error(exc)).with_traceback(sys.exc_info()[2]) def is_rate_limited_error(self, exc: ApiError) -> bool: raise NotImplementedError @property def metadata(self) -> dict[str, Any]: return self.model.metadata def uninstall(self) -> None: """ For integrations that need additional steps for uninstalling that are not covered by the deletion task for OrganizationIntegration task. """ # NotifyBasicMixin noops def notify_remove_external_team(self, external_team: ExternalActor, team: Team) -> None: pass def is_response_success(resp: Any) -> bool: if resp.status_code and resp.status_code < 300: return True return False def is_response_error(resp: Any) -> bool: if not resp.status_code: return False return resp.status_code >= 400 and resp.status_code != 429 and resp.status_code < 500 def get_integration_types(provider: str) -> list[IntegrationDomain]: types = [] for integration_type, providers in INTEGRATION_TYPE_TO_PROVIDER.items(): if provider in providers: types.append(integration_type) return types
IntegrationInstallation
python
encode__django-rest-framework
rest_framework/viewsets.py
{ "start": 1580, "end": 8218 }
class ____: """ This is the magic. Overrides `.as_view()` so that it takes an `actions` keyword that performs the binding of HTTP methods to actions on the Resource. For example, to create a concrete view binding the 'GET' and 'POST' methods to the 'list' and 'create' actions... view = MyViewSet.as_view({'get': 'list', 'post': 'create'}) """ @classonlymethod def as_view(cls, actions=None, **initkwargs): """ Because of the way class based views create a closure around the instantiated view, we need to totally reimplement `.as_view`, and slightly modify the view function that is created and returned. """ # The name and description initkwargs may be explicitly overridden for # certain route configurations. eg, names of extra actions. cls.name = None cls.description = None # The suffix initkwarg is reserved for displaying the viewset type. # This initkwarg should have no effect if the name is provided. # eg. 'List' or 'Instance'. cls.suffix = None # The detail initkwarg is reserved for introspecting the viewset type. cls.detail = None # Setting a basename allows a view to reverse its action urls. This # value is provided by the router through the initkwargs. cls.basename = None # actions must not be empty if not actions: raise TypeError("The `actions` argument must be provided when " "calling `.as_view()` on a ViewSet. For example " "`.as_view({'get': 'list'})`") # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r" % ( cls.__name__, key)) # name and suffix are mutually exclusive if 'name' in initkwargs and 'suffix' in initkwargs: raise TypeError("%s() received both `name` and `suffix`, which are " "mutually exclusive arguments." % (cls.__name__)) def view(request, *args, **kwargs): self = cls(**initkwargs) if 'get' in actions and 'head' not in actions: actions['head'] = actions['get'] # We also store the mapping of request methods to actions, # so that we can later set the action attribute. # eg. `self.action = 'list'` on an incoming GET request. self.action_map = actions # Bind methods to actions # This is the bit that's different to a standard view for method, action in actions.items(): handler = getattr(self, action) setattr(self, method, handler) self.request = request self.args = args self.kwargs = kwargs # And continue as usual return self.dispatch(request, *args, **kwargs) # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) # We need to set these on the view function, so that breadcrumb # generation can pick out these bits of information from a # resolved URL. view.cls = cls view.initkwargs = initkwargs view.actions = actions # Exempt from Django's LoginRequiredMiddleware. Users should set # DEFAULT_PERMISSION_CLASSES to 'rest_framework.permissions.IsAuthenticated' instead if DJANGO_VERSION >= (5, 1): view.login_required = False return csrf_exempt(view) def initialize_request(self, request, *args, **kwargs): """ Set the `.action` attribute on the view, depending on the request method. """ request = super().initialize_request(request, *args, **kwargs) method = request.method.lower() if method == 'options': # This is a special case as we always provide handling for the # options method in the base `View` class. # Unlike the other explicitly defined actions, 'metadata' is implicit. self.action = 'metadata' else: self.action = self.action_map.get(method) return request def reverse_action(self, url_name, *args, **kwargs): """ Reverse the action for the given `url_name`. """ url_name = '%s-%s' % (self.basename, url_name) namespace = None if self.request and self.request.resolver_match: namespace = self.request.resolver_match.namespace if namespace: url_name = namespace + ':' + url_name kwargs.setdefault('request', self.request) return reverse(url_name, *args, **kwargs) @classmethod def get_extra_actions(cls): """ Get the methods that are marked as an extra ViewSet `@action`. """ return [_check_attr_name(method, name) for name, method in getmembers(cls, _is_extra_action)] def get_extra_action_url_map(self): """ Build a map of {names: urls} for the extra actions. This method will noop if `detail` was not provided as a view initkwarg. """ action_urls = {} # exit early if `detail` has not been provided if self.detail is None: return action_urls # filter for the relevant extra actions actions = [ action for action in self.get_extra_actions() if action.detail == self.detail ] for action in actions: try: url_name = '%s-%s' % (self.basename, action.url_name) namespace = self.request.resolver_match.namespace if namespace: url_name = '%s:%s' % (namespace, url_name) url = reverse(url_name, self.args, self.kwargs, request=self.request) view = self.__class__(**action.kwargs) action_urls[view.get_view_name()] = url except NoReverseMatch: pass # URL requires additional arguments, ignore return action_urls
ViewSetMixin
python
wandb__wandb
wandb/apis/paginator.py
{ "start": 3467, "end": 4197 }
class ____(Paginator[_WandbT], Sized, ABC): """A Paginator for objects with a known total count.""" @property def length(self) -> int | None: wandb.termwarn( ( "`.length` is deprecated and will be removed in a future version. " "Use `len(...)` instead." ), repeat=False, ) return len(self) def __len__(self) -> int: if self._length is None: self._load_page() if self._length is None: raise ValueError("Object doesn't provide length") return self._length @property @abstractmethod def _length(self) -> int | None: raise NotImplementedError
SizedPaginator
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-oci-data-science/llama_index/embeddings/oci_data_science/client.py
{ "start": 7052, "end": 11550 }
class ____(ABC): """ Abstract base class for HTTP clients invoking models with retry logic. This class provides common functionality for synchronous and asynchronous clients, including request preparation, authentication, and retry handling. Attributes: endpoint (str): The URL endpoint to send the request. auth (httpx.Auth): The authentication signer for the requests. retries (int): The number of retry attempts for the request. backoff_factor (float): The factor to determine the delay between retries. timeout (Union[float, Tuple[float, float]]): The timeout setting for the HTTP request. kwargs (Dict[str, Any]): Additional keyword arguments. """ def __init__( self, endpoint: str, auth: Optional[Any] = None, retries: Optional[int] = DEFAULT_RETRIES, backoff_factor: Optional[float] = DEFAULT_BACKOFF_FACTOR, timeout: Optional[Union[float, Tuple[float, float]]] = None, **kwargs: Any, ) -> None: """ Initialize the BaseClient. Args: endpoint (str): The URL endpoint to send the request. auth (Optional[Any]): The authentication signer for the requests. If None, the default signer is used. retries (Optional[int]): The number of retry attempts for the request. Defaults to DEFAULT_RETRIES. backoff_factor (Optional[float]): The factor to determine the delay between retries. Defaults to DEFAULT_BACKOFF_FACTOR. timeout (Optional[Union[float, Tuple[float, float]]]): The timeout setting for the HTTP request in seconds. Can be a single float for total timeout, or a tuple (connect_timeout, read_timeout). Defaults to TIMEOUT. **kwargs: Additional keyword arguments. """ self.endpoint = endpoint self.retries = retries or DEFAULT_RETRIES self.backoff_factor = backoff_factor or DEFAULT_BACKOFF_FACTOR self.timeout = timeout or TIMEOUT self.kwargs = kwargs # Use default signer from ADS if `auth` if auth not provided if not auth: try: from ads.common import auth as authutil auth = auth or authutil.default_signer() except ImportError as ex: raise ImportError( "The authentication signer for the requests was not provided. " "Use `auth` attribute to provide the signer. " "The authentication methods supported for LlamaIndex are equivalent to those " "used with other OCI services and follow the standard SDK authentication methods, " "specifically API Key, session token, instance principal, and resource principal. " "For more details, refer to the documentation: " "`https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html`. " "Alternatively you can use the `oracle-ads` package. " "Please install it with `pip install oracle-ads` and follow the example provided here: " "`https://accelerated-data-science.readthedocs.io/en/latest/user_guide/cli/authentication.html#authentication`." ) from ex # Validate auth object if not callable(auth.get("signer")): raise ValueError("Auth object must have a 'signer' callable attribute.") self.auth = OCIAuth(auth["signer"]) logger.debug( f"Initialized {self.__class__.__name__} with endpoint={self.endpoint}, " f"retries={self.retries}, backoff_factor={self.backoff_factor}, timeout={self.timeout}" ) def _prepare_headers( self, headers: Optional[Dict[str, str]] = None ) -> Dict[str, str]: """ Construct and return the headers for a request. This method merges any provided headers with the default headers. Args: headers (Optional[Dict[str, str]]): HTTP headers to include in the request. Returns: Dict[str, str]: The prepared headers. """ default_headers = { "Content-Type": "application/json", "Accept": "application/json", } if headers: default_headers.update(headers) logger.debug(f"Prepared headers: {default_headers}") return default_headers
BaseClient
python
huggingface__transformers
src/transformers/models/blip_2/processing_blip_2.py
{ "start": 1473, "end": 6676 }
class ____(ProcessorMixin): r""" Constructs a BLIP-2 processor which wraps a BLIP image processor and an OPT/T5 tokenizer into a single processor. [`BlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`AutoTokenizer`]. See the docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information. Args: image_processor (`BlipImageProcessor`): An instance of [`BlipImageProcessor`]. The image processor is a required input. tokenizer (`AutoTokenizer`): An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input. num_query_tokens (`int`, *optional*): Number of tokens used by the Qformer as queries, should be same as in model's config. """ def __init__(self, image_processor, tokenizer, num_query_tokens=None, **kwargs): tokenizer.return_token_type_ids = False if not hasattr(tokenizer, "image_token"): self.image_token = AddedToken("<image>", normalized=False, special=True) tokenizer.add_tokens([self.image_token], special_tokens=True) else: self.image_token = tokenizer.image_token self.num_query_tokens = num_query_tokens super().__init__(image_processor, tokenizer) def __call__( self, images: Optional[ImageInput] = None, text: Optional[Union[str, list[str], TextInput, PreTokenizedInput]] = None, **kwargs: Unpack[Blip2ProcessorKwargs], ) -> BatchEncoding: """ This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and [`BertTokenizerFast.__call__`] to prepare text for the model. Please refer to the docstring of the above two methods for more information. Args: images (`ImageInput`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. Both channels-first and channels-last formats are supported. text (`TextInput`, `PreTokenizedInput`, `list[TextInput]`, `list[PreTokenizedInput]`): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. """ if images is None and text is None: raise ValueError("You have to specify either images or text.") output_kwargs = self._merge_kwargs( Blip2ProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs, ) # BC for explicit return_tensors return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None) max_length = output_kwargs["text_kwargs"].pop("max_length", None) if max_length is not None: output_kwargs["text_kwargs"]["max_length"] = max_length - self.num_query_tokens encoding = BatchFeature(tensor_type=return_tensors) if text is not None: if isinstance(text, str): text = [text] elif not isinstance(text, list) and not isinstance(text[0], str): raise ValueError("Invalid input text. Please provide a string, or a list of strings") # We need this hacky manipulation because BLIP expects image tokens to be at the beginning even before BOS token text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"]) if images is not None and self.num_query_tokens is not None: # Image tokens should not be padded/truncated or prepended with special BOS token image_tokens = self.image_token.content * self.num_query_tokens output_kwargs["text_kwargs"]["add_special_tokens"] = False output_kwargs["text_kwargs"]["padding"] = False output_kwargs["text_kwargs"]["truncation"] = False image_text_encoding = self.tokenizer(image_tokens, **output_kwargs["text_kwargs"]) for k in text_encoding: text_encoding[k] = [image_text_encoding[k] + sample for sample in text_encoding[k]] encoding.update(text_encoding) # Now add pixel_values encoding. If we also have text_encoding, update image encoding and return it. # else, return the text encoding. if images is not None: image_encoding = self.image_processor(images, **output_kwargs["images_kwargs"]) encoding.update(image_encoding) # Cast to desired return tensors type encoding = BatchFeature(encoding, tensor_type=return_tensors) return encoding __all__ = ["Blip2Processor"]
Blip2Processor
python
sqlalchemy__sqlalchemy
test/orm/test_unitofwork.py
{ "start": 86420, "end": 88657 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "t1_t", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(30)), Column("value", sa.Boolean), ) def test_boolean(self): t1_t = self.tables.t1_t # use the regular mapper class T(ComparableEntity): pass self.mapper_registry.map_imperatively(T, t1_t) sess = fixture_session() t1 = T(value=True, name="t1") t2 = T(value=False, name="t2") t3 = T(value=True, name="t3") sess.add_all((t1, t2, t3)) sess.flush() for clear in (False, True): if clear: sess.expunge_all() eq_( sess.query(T).order_by(T.id).all(), [ T(value=True, name="t1"), T(value=False, name="t2"), T(value=True, name="t3"), ], ) if clear: sess.expunge_all() eq_( sess.query(T) .filter(T.value == True) # noqa .order_by(T.id) .all(), [T(value=True, name="t1"), T(value=True, name="t3")], ) if clear: sess.expunge_all() eq_( sess.query(T) .filter(T.value == False) # noqa .order_by(T.id) .all(), [T(value=False, name="t2")], ) t2 = sess.get(T, t2.id) t2.value = True sess.flush() eq_( sess.query(T).filter(T.value == True).order_by(T.id).all(), # noqa [ T(value=True, name="t1"), T(value=True, name="t2"), T(value=True, name="t3"), ], ) t2.value = False sess.flush() eq_( sess.query(T).filter(T.value == True).order_by(T.id).all(), # noqa [T(value=True, name="t1"), T(value=True, name="t3")], )
BooleanColTest
python
python-markdown__markdown
tests/test_syntax/blocks/test_paragraphs.py
{ "start": 781, "end": 7958 }
class ____(TestCase): def test_simple_paragraph(self): self.assertMarkdownRenders( 'A simple paragraph.', '<p>A simple paragraph.</p>' ) def test_blank_line_before_paragraph(self): self.assertMarkdownRenders( '\nA paragraph preceded by a blank line.', '<p>A paragraph preceded by a blank line.</p>' ) def test_multiline_paragraph(self): self.assertMarkdownRenders( self.dedent( """ This is a paragraph on multiple lines with hard returns. """ ), self.dedent( """ <p>This is a paragraph on multiple lines with hard returns.</p> """ ) ) def test_paragraph_long_line(self): self.assertMarkdownRenders( 'A very long long long long long long long long long long long long long long long long long long long ' 'long long long long long long long long long long long long long paragraph on 1 line.', '<p>A very long long long long long long long long long long long long long long long long long long ' 'long long long long long long long long long long long long long long paragraph on 1 line.</p>' ) def test_2_paragraphs_long_line(self): self.assertMarkdownRenders( 'A very long long long long long long long long long long long long long long long long long long long ' 'long long long long long long long long long long long long long paragraph on 1 line.\n\n' 'A new long long long long long long long long long long long long long long long ' 'long paragraph on 1 line.', '<p>A very long long long long long long long long long long long long long long long long long long ' 'long long long long long long long long long long long long long long paragraph on 1 line.</p>\n' '<p>A new long long long long long long long long long long long long long long long ' 'long paragraph on 1 line.</p>' ) def test_consecutive_paragraphs(self): self.assertMarkdownRenders( self.dedent( """ Paragraph 1. Paragraph 2. """ ), self.dedent( """ <p>Paragraph 1.</p> <p>Paragraph 2.</p> """ ) ) def test_consecutive_paragraphs_tab(self): self.assertMarkdownRenders( self.dedent( """ Paragraph followed by a line with a tab only. \t Paragraph after a line with a tab only. """ ), self.dedent( """ <p>Paragraph followed by a line with a tab only.</p> <p>Paragraph after a line with a tab only.</p> """ ) ) def test_consecutive_paragraphs_space(self): self.assertMarkdownRenders( self.dedent( """ Paragraph followed by a line with a space only. Paragraph after a line with a space only. """ ), self.dedent( """ <p>Paragraph followed by a line with a space only.</p> <p>Paragraph after a line with a space only.</p> """ ) ) def test_consecutive_multiline_paragraphs(self): self.assertMarkdownRenders( self.dedent( """ Paragraph 1, line 1. Paragraph 1, line 2. Paragraph 2, line 1. Paragraph 2, line 2. """ ), self.dedent( """ <p>Paragraph 1, line 1. Paragraph 1, line 2.</p> <p>Paragraph 2, line 1. Paragraph 2, line 2.</p> """ ) ) def test_paragraph_leading_space(self): self.assertMarkdownRenders( ' A paragraph with 1 leading space.', '<p>A paragraph with 1 leading space.</p>' ) def test_paragraph_2_leading_spaces(self): self.assertMarkdownRenders( ' A paragraph with 2 leading spaces.', '<p>A paragraph with 2 leading spaces.</p>' ) def test_paragraph_3_leading_spaces(self): self.assertMarkdownRenders( ' A paragraph with 3 leading spaces.', '<p>A paragraph with 3 leading spaces.</p>' ) def test_paragraph_trailing_leading_space(self): self.assertMarkdownRenders( ' A paragraph with 1 trailing and 1 leading space. ', '<p>A paragraph with 1 trailing and 1 leading space. </p>' ) def test_paragraph_trailing_tab(self): self.assertMarkdownRenders( 'A paragraph with 1 trailing tab.\t', '<p>A paragraph with 1 trailing tab. </p>' ) def test_paragraphs_CR(self): self.assertMarkdownRenders( 'Paragraph 1, line 1.\rParagraph 1, line 2.\r\rParagraph 2, line 1.\rParagraph 2, line 2.\r', self.dedent( """ <p>Paragraph 1, line 1. Paragraph 1, line 2.</p> <p>Paragraph 2, line 1. Paragraph 2, line 2.</p> """ ) ) def test_paragraphs_LF(self): self.assertMarkdownRenders( 'Paragraph 1, line 1.\nParagraph 1, line 2.\n\nParagraph 2, line 1.\nParagraph 2, line 2.\n', self.dedent( """ <p>Paragraph 1, line 1. Paragraph 1, line 2.</p> <p>Paragraph 2, line 1. Paragraph 2, line 2.</p> """ ) ) def test_paragraphs_CR_LF(self): self.assertMarkdownRenders( 'Paragraph 1, line 1.\r\nParagraph 1, line 2.\r\n\r\nParagraph 2, line 1.\r\nParagraph 2, line 2.\r\n', self.dedent( """ <p>Paragraph 1, line 1. Paragraph 1, line 2.</p> <p>Paragraph 2, line 1. Paragraph 2, line 2.</p> """ ) ) def test_paragraphs_no_list(self): self.assertMarkdownRenders( self.dedent( """ Paragraph: * no list Paragraph * no list Paragraph: * no list Paragraph: * no list """ ), '<p>Paragraph:\n' '* no list</p>\n' '<p>Paragraph\n' ' * no list</p>\n' '<p>Paragraph:\n' ' * no list</p>\n' '<p>Paragraph:\n' ' * no list</p>', )
TestParagraphBlocks
python
fastai__fastai
fastai/vision/augment.py
{ "start": 1246, "end": 2792 }
class ____(DisplayedTransform): "A transform that before_call its state at each `__call__`" do,nm,supports,split_idx = True,None,[],0 def __init__(self, p:float=1., # Probability of applying Transform nm:str=None, before_call:Callable=None, # Optional batchwise preprocessing function **kwargs ): store_attr('p') super().__init__(**kwargs) self.before_call = ifnone(before_call,self.before_call) def before_call(self, b, split_idx:int, # Index of the train/valid dataset ): "This function can be overridden. Set `self.do` based on `self.p`" self.do = self.p==1. or random.random() < self.p def __call__(self, b, split_idx:int=None, # Index of the train/valid dataset **kwargs ): self.before_call(b, split_idx=split_idx) return super().__call__(b, split_idx=split_idx, **kwargs) if self.do else b # %% ../../nbs/09_vision.augment.ipynb 14 def _neg_axis(x, axis): x[...,axis] = -x[...,axis] return x TensorTypes = (TensorImage,TensorMask,TensorPoint,TensorBBox) # %% ../../nbs/09_vision.augment.ipynb 15 @patch def flip_lr(x:Image.Image): return x.transpose(Image.FLIP_LEFT_RIGHT) @patch def flip_lr(x:TensorImageBase): return x.flip(-1) @patch def flip_lr(x:TensorPoint): return TensorPoint(_neg_axis(x.clone(), 0)) @patch def flip_lr(x:TensorBBox): return TensorBBox(TensorPoint(x.view(-1,2)).flip_lr().view(-1,4)) # %% ../../nbs/09_vision.augment.ipynb 18
RandTransform
python
sympy__sympy
sympy/functions/elementary/integers.py
{ "start": 16094, "end": 22316 }
class ____(DefinedFunction): r"""Represents the fractional part of x For real numbers it is defined [1]_ as .. math:: x - \left\lfloor{x}\right\rfloor Examples ======== >>> from sympy import Symbol, frac, Rational, floor, I >>> frac(Rational(4, 3)) 1/3 >>> frac(-Rational(4, 3)) 2/3 returns zero for integer arguments >>> n = Symbol('n', integer=True) >>> frac(n) 0 rewrite as floor >>> x = Symbol('x') >>> frac(x).rewrite(floor) x - floor(x) for complex arguments >>> r = Symbol('r', real=True) >>> t = Symbol('t', real=True) >>> frac(t + I*r) I*frac(r) + frac(t) See Also ======== sympy.functions.elementary.integers.floor sympy.functions.elementary.integers.ceiling References =========== .. [1] https://en.wikipedia.org/wiki/Fractional_part .. [2] https://mathworld.wolfram.com/FractionalPart.html """ @classmethod def eval(cls, arg): from sympy.calculus.accumulationbounds import AccumBounds def _eval(arg): if arg in (S.Infinity, S.NegativeInfinity): return AccumBounds(0, 1) if arg.is_integer: return S.Zero if arg.is_number: if arg is S.NaN or arg is S.ComplexInfinity: return S.NaN return arg - floor(arg) return cls(arg, evaluate=False) real, imag = S.Zero, S.Zero for t in Add.make_args(arg): # Two checks are needed for complex arguments # see issue-7649 for details if t.is_imaginary or (S.ImaginaryUnit*t).is_real: i = im(t) if not i.has(S.ImaginaryUnit): imag += i else: real += t else: real += t real = _eval(real) imag = _eval(imag) return real + S.ImaginaryUnit*imag def _eval_rewrite_as_floor(self, arg, **kwargs): return arg - floor(arg) def _eval_rewrite_as_ceiling(self, arg, **kwargs): return arg + ceiling(-arg) def _eval_is_finite(self): return True def _eval_is_real(self): return self.args[0].is_extended_real def _eval_is_imaginary(self): return self.args[0].is_imaginary def _eval_is_integer(self): return self.args[0].is_integer def _eval_is_zero(self): return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer]) def _eval_is_negative(self): return False def __ge__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other <= 0 if other.is_extended_nonpositive: return S.true # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return not(res) return Ge(self, other, evaluate=False) def __gt__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other < 0 res = self._value_one_or_more(other) if res is not None: return not(res) # Check if other >= 1 if other.is_extended_negative: return S.true return Gt(self, other, evaluate=False) def __le__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other < 0 if other.is_extended_negative: return S.false # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return res return Le(self, other, evaluate=False) def __lt__(self, other): if self.is_extended_real: other = _sympify(other) # Check if other <= 0 if other.is_extended_nonpositive: return S.false # Check if other >= 1 res = self._value_one_or_more(other) if res is not None: return res return Lt(self, other, evaluate=False) def _value_one_or_more(self, other): if other.is_extended_real: if other.is_number: res = other >= 1 if res and not isinstance(res, Relational): return S.true if other.is_integer and other.is_positive: return S.true def _eval_as_leading_term(self, x, logx, cdir): from sympy.calculus.accumulationbounds import AccumBounds arg = self.args[0] arg0 = arg.subs(x, 0) r = self.subs(x, 0) if arg0.is_finite: if r.is_zero: ndir = arg.dir(x, cdir=cdir) if ndir.is_negative: return S.One return (arg - arg0).as_leading_term(x, logx=logx, cdir=cdir) else: return r elif arg0 in (S.ComplexInfinity, S.Infinity, S.NegativeInfinity): return AccumBounds(0, 1) return arg.as_leading_term(x, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir=0): from sympy.series.order import Order arg = self.args[0] arg0 = arg.subs(x, 0) r = self.subs(x, 0) if arg0.is_infinite: from sympy.calculus.accumulationbounds import AccumBounds o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1) + Order(x**n, (x, 0)) return o else: res = (arg - arg0)._eval_nseries(x, n, logx=logx, cdir=cdir) if r.is_zero: ndir = arg.dir(x, cdir=cdir) res += S.One if ndir.is_negative else S.Zero else: res += r return res @dispatch(frac, Basic) # type:ignore def _eval_is_eq(lhs, rhs): # noqa:F811 if (lhs.rewrite(floor) == rhs) or \ (lhs.rewrite(ceiling) == rhs): return True # Check if other < 0 if rhs.is_extended_negative: return False # Check if other >= 1 res = lhs._value_one_or_more(rhs) if res is not None: return False
frac
python
cython__cython
Cython/Compiler/TypeSlots.py
{ "start": 36912, "end": 49669 }
class ____: def __init__(self, old_binops): # The following dictionary maps __xxx__ method names to slot descriptors. method_name_to_slot = {} self._get_slot_by_method_name = method_name_to_slot.get self.substructures = [] # List of all SuiteSlot instances bf = binaryfunc if old_binops else ibinaryfunc ptf = powternaryfunc if old_binops else ipowternaryfunc # Descriptor tables for the slots of the various type object # substructures, in the order they appear in the structure. self.PyNumberMethods = ( BinopSlot(bf, "nb_add", "__add__", method_name_to_slot), BinopSlot(bf, "nb_subtract", "__sub__", method_name_to_slot), BinopSlot(bf, "nb_multiply", "__mul__", method_name_to_slot), BinopSlot(bf, "nb_remainder", "__mod__", method_name_to_slot), BinopSlot(bf, "nb_divmod", "__divmod__", method_name_to_slot), BinopSlot(ptf, "nb_power", "__pow__", method_name_to_slot), MethodSlot(unaryfunc, "nb_negative", "__neg__", method_name_to_slot), MethodSlot(unaryfunc, "nb_positive", "__pos__", method_name_to_slot), MethodSlot(unaryfunc, "nb_absolute", "__abs__", method_name_to_slot), MethodSlot(inquiry, "nb_bool", "__bool__", method_name_to_slot, fallback="__nonzero__"), MethodSlot(unaryfunc, "nb_invert", "__invert__", method_name_to_slot), BinopSlot(bf, "nb_lshift", "__lshift__", method_name_to_slot), BinopSlot(bf, "nb_rshift", "__rshift__", method_name_to_slot), BinopSlot(bf, "nb_and", "__and__", method_name_to_slot), BinopSlot(bf, "nb_xor", "__xor__", method_name_to_slot), BinopSlot(bf, "nb_or", "__or__", method_name_to_slot), MethodSlot(unaryfunc, "nb_int", "__int__", method_name_to_slot, fallback="__long__"), EmptySlot("nb_long (reserved)"), MethodSlot(unaryfunc, "nb_float", "__float__", method_name_to_slot), # Added in release 2.0 MethodSlot(ibinaryfunc, "nb_inplace_add", "__iadd__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_subtract", "__isub__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_multiply", "__imul__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_remainder", "__imod__", method_name_to_slot), MethodSlot(ptf, "nb_inplace_power", "__ipow__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_lshift", "__ilshift__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_rshift", "__irshift__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_and", "__iand__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_xor", "__ixor__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_or", "__ior__", method_name_to_slot), # Added in release 2.2 # The following require the Py_TPFLAGS_HAVE_CLASS flag BinopSlot(bf, "nb_floor_divide", "__floordiv__", method_name_to_slot), BinopSlot(bf, "nb_true_divide", "__truediv__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_floor_divide", "__ifloordiv__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_true_divide", "__itruediv__", method_name_to_slot), # Added in release 2.5 MethodSlot(unaryfunc, "nb_index", "__index__", method_name_to_slot), # Added in release 3.5 BinopSlot(bf, "nb_matrix_multiply", "__matmul__", method_name_to_slot), MethodSlot(ibinaryfunc, "nb_inplace_matrix_multiply", "__imatmul__", method_name_to_slot), ) self.PySequenceMethods = ( MethodSlot(lenfunc, "sq_length", "__len__", method_name_to_slot), EmptySlot("sq_concat"), # nb_add used instead EmptySlot("sq_repeat"), # nb_multiply used instead SyntheticSlot("sq_item", ["__getitem__"], "0"), #EmptySlot("sq_item"), # mp_subscript used instead EmptySlot("sq_slice"), EmptySlot("sq_ass_item"), # mp_ass_subscript used instead EmptySlot("sq_ass_slice"), MethodSlot(cmpfunc, "sq_contains", "__contains__", method_name_to_slot), EmptySlot("sq_inplace_concat"), # nb_inplace_add used instead EmptySlot("sq_inplace_repeat"), # nb_inplace_multiply used instead ) self.PyMappingMethods = ( MethodSlot(lenfunc, "mp_length", "__len__", method_name_to_slot), MethodSlot(objargfunc, "mp_subscript", "__getitem__", method_name_to_slot), SyntheticSlot("mp_ass_subscript", ["__setitem__", "__delitem__"], "0"), ) self.PyBufferProcs = ( MethodSlot(getbufferproc, "bf_getbuffer", "__getbuffer__", method_name_to_slot), MethodSlot(releasebufferproc, "bf_releasebuffer", "__releasebuffer__", method_name_to_slot) ) self.PyAsyncMethods = ( MethodSlot(unaryfunc, "am_await", "__await__", method_name_to_slot), MethodSlot(unaryfunc, "am_aiter", "__aiter__", method_name_to_slot), MethodSlot(unaryfunc, "am_anext", "__anext__", method_name_to_slot), # We should not map arbitrary .send() methods to an async slot. #MethodSlot(sendfunc, "am_send", "send", method_name_to_slot), EmptySlot("am_send"), ) self.slot_table = ( ConstructorSlot("tp_dealloc", '__dealloc__'), EmptySlot("tp_vectorcall_offset"), EmptySlot("tp_getattr"), EmptySlot("tp_setattr"), SuiteSlot(self. PyAsyncMethods, "__Pyx_PyAsyncMethodsStruct", "tp_as_async", self.substructures, cast_cname="PyAsyncMethods"), MethodSlot(reprfunc, "tp_repr", "__repr__", method_name_to_slot), SuiteSlot(self.PyNumberMethods, "PyNumberMethods", "tp_as_number", self.substructures), SuiteSlot(self.PySequenceMethods, "PySequenceMethods", "tp_as_sequence", self.substructures), SuiteSlot(self.PyMappingMethods, "PyMappingMethods", "tp_as_mapping", self.substructures), MethodSlot(hashfunc, "tp_hash", "__hash__", method_name_to_slot, inherited=False), # Py3 checks for __richcmp__ MethodSlot(callfunc, "tp_call", "__call__", method_name_to_slot), MethodSlot(reprfunc, "tp_str", "__str__", method_name_to_slot), SyntheticSlot("tp_getattro", ["__getattr__","__getattribute__"], "0"), #"PyObject_GenericGetAttr"), SyntheticSlot("tp_setattro", ["__setattr__", "__delattr__"], "0"), #"PyObject_GenericSetAttr"), SuiteSlot(self.PyBufferProcs, "PyBufferProcs", "tp_as_buffer", self.substructures), TypeFlagsSlot("tp_flags"), DocStringSlot("tp_doc"), GCDependentSlot("tp_traverse"), GCClearReferencesSlot("tp_clear"), RichcmpSlot(richcmpfunc, "tp_richcompare", "__richcmp__", method_name_to_slot, inherited=False), # Py3 checks for __hash__ EmptySlot("tp_weaklistoffset"), MethodSlot(getiterfunc, "tp_iter", "__iter__", method_name_to_slot), MethodSlot(iternextfunc, "tp_iternext", "__next__", method_name_to_slot), MethodTableSlot("tp_methods"), MemberTableSlot("tp_members"), GetSetSlot("tp_getset"), BaseClassSlot("tp_base"), #EmptySlot("tp_base"), EmptySlot("tp_dict"), SyntheticSlot("tp_descr_get", ["__get__"], "0"), SyntheticSlot("tp_descr_set", ["__set__", "__delete__"], "0"), DictOffsetSlot("tp_dictoffset", ifdef="!CYTHON_USE_TYPE_SPECS"), # otherwise set via "__dictoffset__" member MethodSlot(initproc, "tp_init", "__init__", method_name_to_slot), EmptySlot("tp_alloc"), #FixedSlot("tp_alloc", "PyType_GenericAlloc"), ConstructorSlot("tp_new", "__cinit__"), EmptySlot("tp_free"), EmptySlot("tp_is_gc"), EmptySlot("tp_bases"), EmptySlot("tp_mro"), EmptySlot("tp_cache"), EmptySlot("tp_subclasses"), EmptySlot("tp_weaklist"), EmptySlot("tp_del"), EmptySlot("tp_version_tag"), SyntheticSlot("tp_finalize", ["__del__"], "0", used_ifdef="CYTHON_USE_TP_FINALIZE"), EmptySlot("tp_vectorcall", ifdef="!CYTHON_COMPILING_IN_PYPY || PYPY_VERSION_NUM >= 0x07030800"), EmptySlot("tp_print", ifdef="__PYX_NEED_TP_PRINT_SLOT == 1"), EmptySlot("tp_watched", ifdef="PY_VERSION_HEX >= 0x030C0000"), EmptySlot("tp_versions_used", ifdef="PY_VERSION_HEX >= 0x030d00A4"), # PyPy specific extension - only here to avoid C compiler warnings. EmptySlot("tp_pypy_flags", ifdef="CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x030a0000"), ) #------------------------------------------------------------------------------------------ # # Descriptors for special methods which don't appear directly # in the type object or its substructures. These methods are # called from slot functions synthesized by Cython. # #------------------------------------------------------------------------------------------ MethodSlot(initproc, "", "__cinit__", method_name_to_slot) MethodSlot(destructor, "", "__dealloc__", method_name_to_slot) MethodSlot(destructor, "", "__del__", method_name_to_slot) MethodSlot(objobjargproc, "", "__setitem__", method_name_to_slot) MethodSlot(objargproc, "", "__delitem__", method_name_to_slot) MethodSlot(ssizessizeobjargproc, "", "__setslice__", method_name_to_slot) MethodSlot(ssizessizeargproc, "", "__delslice__", method_name_to_slot) MethodSlot(getattrofunc, "", "__getattr__", method_name_to_slot) MethodSlot(getattrofunc, "", "__getattribute__", method_name_to_slot) MethodSlot(setattrofunc, "", "__setattr__", method_name_to_slot) MethodSlot(delattrofunc, "", "__delattr__", method_name_to_slot) MethodSlot(descrgetfunc, "", "__get__", method_name_to_slot) MethodSlot(descrsetfunc, "", "__set__", method_name_to_slot) MethodSlot(descrdelfunc, "", "__delete__", method_name_to_slot) #------------------------------------------------------------------------- # # Legacy "fallback" Py2 slots. Don't appear in the generated slot table, # but match the "fallback" argument of a slot that does # #------------------------------------------------------------------------- MethodSlot(inquiry, "", "__nonzero__", method_name_to_slot) MethodSlot(unaryfunc, "", "__long__", method_name_to_slot) def get_special_method_signature(self, name): # Given a method name, if it is a special method, # return its signature, else return None. slot = self._get_slot_by_method_name(name) if slot: return slot.signature elif name in richcmp_special_methods: return ibinaryfunc else: return None def get_slot_by_method_name(self, method_name): # For now, only search the type struct, no referenced sub-structs. return self._get_slot_by_method_name(method_name) def __iter__(self): # make it easier to iterate over all the slots return iter(self.slot_table) _slot_table_dict = {} def get_slot_table(compiler_directives): if not compiler_directives: # fetch default directives here since the builtin type classes don't have # directives set from .Options import get_directive_defaults compiler_directives = get_directive_defaults() old_binops = compiler_directives['c_api_binop_methods'] key = (old_binops,) if key not in _slot_table_dict: _slot_table_dict[key] = SlotTable(old_binops=old_binops) return _slot_table_dict[key] # Populate "special_method_names" based on the default directives (so it can always be accessed quickly). special_method_names = set(get_slot_table(compiler_directives=None)) # Method flags for python-exposed methods. method_noargs = "METH_NOARGS" method_onearg = "METH_O" method_varargs = "METH_VARARGS" method_fastcall = "__Pyx_METH_FASTCALL" # Actually VARARGS on versions < 3.7 method_keywords = "METH_KEYWORDS" method_coexist = "METH_COEXIST"
SlotTable
python
astropy__astropy
astropy/table/sorted_array.py
{ "start": 823, "end": 10128 }
class ____: """ Implements a sorted array container using a list of numpy arrays. Parameters ---------- data : Table Sorted columns of the original table row_index : Column object Row numbers corresponding to data columns unique : bool Whether the values of the index must be unique. Defaults to False. """ def __init__(self, data: "Table", row_index: "Column", unique: bool = False): self.data = data self.row_index = row_index self.num_cols = len(getattr(data, "colnames", [])) self.unique = unique @property def cols(self) -> list["Column"]: return list(self.data.columns.values()) def add(self, key: tuple, row: int) -> None: """ Add a new entry to the sorted array. Parameters ---------- key : tuple Column values at the given row row : int Row number """ pos = self.find_pos(key, row) # first >= key if ( self.unique and 0 <= pos < len(self.row_index) and all(self.data[pos][i] == key[i] for i in range(len(key))) ): # already exists raise ValueError(f'Cannot add duplicate value "{key}" in a unique index') self.data.insert_row(pos, key) self.row_index = self.row_index.insert(pos, row) def _get_key_slice(self, i, begin, end): """ Retrieve the ith slice of the sorted array from begin to end. """ if i < self.num_cols: return self.cols[i][begin:end] else: return self.row_index[begin:end] def find_pos(self, key, data, exact=False): """ Return the index of the largest key in data greater than or equal to the given key, data pair. Parameters ---------- key : tuple Column key data : int Row number exact : bool If True, return the index of the given key in data or -1 if the key is not present. """ begin = 0 end = len(self.row_index) num_cols = self.num_cols if not self.unique: # consider the row value as well key = key + (data,) num_cols += 1 # search through keys in lexicographic order for i in range(num_cols): key_slice = self._get_key_slice(i, begin, end) t = _searchsorted(key_slice, key[i]) # t is the smallest index >= key[i] if exact and (t == len(key_slice) or key_slice[t] != key[i]): # no match return -1 elif t == len(key_slice) or ( t == 0 and len(key_slice) > 0 and key[i] < key_slice[0] ): # too small or too large return begin + t end = begin + _searchsorted(key_slice, key[i], side="right") begin += t if begin >= len(self.row_index): # greater than all keys return begin return begin def find(self, key: tuple) -> Sequence[Integral]: """ Find all rows matching the given key. Parameters ---------- key : tuple Column values Returns ------- matching_rows : list List of rows matching the input key """ begin = 0 end = len(self.row_index) # search through keys in lexicographic order for i in range(self.num_cols): key_slice = self._get_key_slice(i, begin, end) t = _searchsorted(key_slice, key[i]) # t is the smallest index >= key[i] if t == len(key_slice) or key_slice[t] != key[i]: # no match return [] elif t == 0 and len(key_slice) > 0 and key[i] < key_slice[0]: # too small or too large return [] end = begin + _searchsorted(key_slice, key[i], side="right") begin += t if begin >= len(self.row_index): # greater than all keys return [] return self.row_index[begin:end] def range( self, lower: tuple[Hashable, ...] | None, upper: tuple[Hashable, ...] | None, bounds: tuple[bool, bool], ) -> list[int]: """ Find values in the given range. Parameters ---------- lower : tuple, None Lower search bound (no lower bound if None) upper : tuple, None Upper search bound (no upper bound if None) bounds : (2,) tuple of bool Indicates whether the search should be inclusive or exclusive with respect to the endpoints. The first argument corresponds to an inclusive lower bound, and the second argument to an inclusive upper bound. """ # Find initial positions for lower and upper bounds. Just like a slice object, # None values for `lower` or `upper` correspond to no bound in that direction. lower_pos = 0 if lower is None else self.find_pos(lower, 0) upper_pos = len(self.row_index) if upper is None else self.find_pos(upper, 0) if lower_pos == len(self.row_index): return [] lower_bound = tuple(col[lower_pos] for col in self.cols) if not bounds[0] and lower_bound == lower: lower_pos += 1 # data[lower_pos] > lower # data[lower_pos] >= lower # data[upper_pos] >= upper if upper_pos < len(self.row_index): upper_bound = tuple(col[upper_pos] for col in self.cols) if not bounds[1] and upper_bound == upper: upper_pos -= 1 # data[upper_pos] < upper elif upper_bound > upper: upper_pos -= 1 # data[upper_pos] <= upper return self.row_index[lower_pos : upper_pos + 1] def remove(self, key: tuple, data: int) -> bool: """ Remove the given entry from the sorted array. Parameters ---------- key : tuple Column values data : int Row number Returns ------- successful : bool Whether the entry was successfully removed """ pos = self.find_pos(key, data, exact=True) if pos == -1: # key not found return False self.data.remove_row(pos) keep_mask = np.ones(len(self.row_index), dtype=bool) keep_mask[pos] = False self.row_index = self.row_index[keep_mask] return True def shift_left(self, row: int) -> None: """ Decrement all row numbers greater than the input row. Parameters ---------- row : int Input row number """ self.row_index[self.row_index > row] -= 1 def shift_right(self, row: int) -> None: """ Increment all row numbers greater than or equal to the input row. Parameters ---------- row : int Input row number """ self.row_index[self.row_index >= row] += 1 def replace_rows(self, row_map: "Mapping[int, int]") -> None: """ Replace all rows with the values they map to in the given dictionary. Any rows not present as keys in the dictionary will have their entries deleted. Parameters ---------- row_map : dict Mapping of row numbers to new row numbers """ num_rows = len(row_map) keep_rows = np.zeros(len(self.row_index), dtype=bool) tagged = 0 for i, row in enumerate(self.row_index): if row in row_map: keep_rows[i] = True tagged += 1 if tagged == num_rows: break self.data = self.data[keep_rows] self.row_index = np.array([row_map[x] for x in self.row_index[keep_rows]]) def items(self) -> list[tuple[Hashable, list[Integral]]]: """ Retrieve all array items as a list of pairs of the form [(key, [row 1, row 2, ...]), ...]. """ array = [] last_key = None for i, key in enumerate(zip(*self.data.columns.values())): row = self.row_index[i] if key == last_key: array[-1][1].append(row) else: last_key = key array.append((key, [row])) return array def sort(self) -> None: """ Make row order align with key order. """ self.row_index = np.arange(len(self.row_index)) def sorted_data(self) -> None: """ Return rows in sorted order. """ return self.row_index def __getitem__(self, item): """ Return a sliced reference to this sorted array. Parameters ---------- item : slice Slice to use for referencing """ return SortedArray(self.data[item], self.row_index[item]) def __repr__(self): t = self.data.copy() t["rows"] = self.row_index return f"<{self.__class__.__name__} length={len(t)}>\n{t}"
SortedArray
python
mitmproxy__pdoc
pdoc/__init__.py
{ "start": 10493, "end": 10568 }
class ____(BaseModel): a: int = Field(description="Docs for field a.")
Foo
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 25278, "end": 25810 }
class ____(models.Model): """ Historic table foreign key to non-historic table. In this case it should simply behave like ForeignKey because the origin model (this one) can be historic but the target model is not, so foreign key lookups are always "current". """ name = models.CharField(max_length=15, unique=True) organization = HistoricForeignKey( TestOrganization, on_delete=CASCADE, related_name="participants" ) history = HistoricalRecords()
TestHistoricParticipantToOrganization
python
charliermarsh__ruff
python/ruff-ecosystem/ruff_ecosystem/main.py
{ "start": 534, "end": 4571 }
class ____(Enum): markdown = "markdown" json = "json" async def main( command: RuffCommand, baseline_executable: Path, comparison_executable: Path, targets: list[Project], project_dir: Path, format: OutputFormat, format_comparison: FormatComparison | None, max_parallelism: int = 50, raise_on_failure: bool = False, ) -> None: logger.debug("Using command %s", command.value) logger.debug("Using baseline executable at %s", baseline_executable) logger.debug("Using comparison executable at %s", comparison_executable) logger.debug("Using checkout_dir directory %s", project_dir) if format_comparison: logger.debug("Using format comparison type %s", format_comparison.value) logger.debug("Checking %s targets", len(targets)) # Limit parallelism to avoid high memory consumption semaphore = asyncio.Semaphore(max_parallelism) async def limited_parallelism(coroutine: Awaitable[T]) -> T: async with semaphore: return await coroutine comparisons: list[BaseException | Comparison] = await asyncio.gather( *[ limited_parallelism( clone_and_compare( command, baseline_executable, comparison_executable, target, project_dir, format_comparison, ) ) for target in targets ], return_exceptions=not raise_on_failure, ) comparisons_by_target = dict(zip(targets, comparisons, strict=True)) # Split comparisons into errored / completed errored: list[tuple[Project, BaseException]] = [] completed: list[tuple[Project, Comparison]] = [] for target, comparison in comparisons_by_target.items(): if isinstance(comparison, BaseException): errored.append((target, comparison)) else: completed.append((target, comparison)) result = Result(completed=completed, errored=errored) match format: case OutputFormat.json: print(json.dumps(result, indent=4, cls=JSONEncoder)) case OutputFormat.markdown: match command: case RuffCommand.check: print(markdown_check_result(result)) case RuffCommand.format: print(markdown_format_result(result)) case _: raise ValueError(f"Unknown target Ruff command {command}") case _: raise ValueError(f"Unknown output format {format}") return None async def clone_and_compare( command: RuffCommand, baseline_executable: Path, comparison_executable: Path, target: Project, project_dir: Path, format_comparison: FormatComparison | None, ) -> Comparison: """Check a specific repository against two versions of ruff.""" assert ":" not in target.repo.owner assert ":" not in target.repo.name match command: case RuffCommand.check: compare, options, overrides, kwargs = ( compare_check, target.check_options, target.config_overrides, {}, ) case RuffCommand.format: compare, options, overrides, kwargs = ( compare_format, target.format_options, target.config_overrides, {"format_comparison": format_comparison}, ) case _: raise ValueError(f"Unknown target Ruff command {command}") checkout_dir = project_dir.joinpath(f"{target.repo.owner}:{target.repo.name}") cloned_repo = await target.repo.clone(checkout_dir) try: return await compare( baseline_executable, comparison_executable, options, overrides, cloned_repo, **kwargs, ) except ExceptionGroup as e: raise e.exceptions[0] from e
OutputFormat
python
tornadoweb__tornado
tornado/test/websocket_test.py
{ "start": 4145, "end": 4604 }
class ____(TestWebSocketHandler): def initialize(self, **kwargs): # type: ignore[override] super().initialize(**kwargs) self.sleeping = 0 @gen.coroutine def on_message(self, message): if self.sleeping > 0: self.write_message("another coroutine is already sleeping") self.sleeping += 1 yield gen.sleep(0.01) self.sleeping -= 1 self.write_message(message)
CoroutineOnMessageHandler
python
MTrajK__coding-problems
Arrays/top_k_frequent_elements.py
{ "start": 1497, "end": 1676 }
class ____: def __init__(self, el): self.frequency, self.val = el def __lt__(self, other): return self.frequency < other.frequency # priority queue
PQElement
python
getsentry__sentry
tests/sentry/models/test_projectredirect.py
{ "start": 104, "end": 865 }
class ____(TestCase): def test_record(self) -> None: org = self.create_organization() project = self.create_project(organization=org) ProjectRedirect.record(project, "old_slug") assert ProjectRedirect.objects.filter(redirect_slug="old_slug", project=project).exists() # Recording the same historic slug on a different project updates the # project pointer. project2 = self.create_project(organization=org) ProjectRedirect.record(project2, "old_slug") assert not ProjectRedirect.objects.filter( redirect_slug="old_slug", project=project ).exists() assert ProjectRedirect.objects.filter(redirect_slug="old_slug", project=project2).exists()
ProjectRedirectTest
python
kamyu104__LeetCode-Solutions
Python/coloring-a-border.py
{ "start": 58, "end": 1122 }
class ____(object): def colorBorder(self, grid, r0, c0, color): """ :type grid: List[List[int]] :type r0: int :type c0: int :type color: int :rtype: List[List[int]] """ directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] lookup, q, borders = set([(r0, c0)]), collections.deque([(r0, c0)]), [] while q: r, c = q.popleft() is_border = False for direction in directions: nr, nc = r+direction[0], c+direction[1] if not ((0 <= nr < len(grid)) and \ (0 <= nc < len(grid[0])) and \ grid[nr][nc] == grid[r][c]): is_border = True continue if (nr, nc) in lookup: continue lookup.add((nr, nc)) q.append((nr, nc)) if is_border: borders.append((r, c)) for r, c in borders: grid[r][c] = color return grid
Solution
python
lazyprogrammer__machine_learning_examples
cnn_class2/tf_resnet.py
{ "start": 1781, "end": 2014 }
class ____: def forward(self, X): return tf.contrib.layers.flatten(X) def get_params(self): return [] def custom_softmax(x): m = tf.reduce_max(x, 1) x = x - m e = tf.exp(x) return e / tf.reduce_sum(e, -1)
Flatten
python
PyCQA__pylint
tests/checkers/unittest_misc.py
{ "start": 387, "end": 4182 }
class ____(CheckerTestCase): CHECKER_CLASS = misc.EncodingChecker def test_fixme_with_message(self) -> None: code = """a = 1 # FIXME message """ with self.assertAddsMessages( MessageTest(msg_id="fixme", line=2, args="FIXME message", col_offset=17) ): self.checker.process_tokens(_tokenize_str(code)) def test_todo_without_message(self) -> None: code = """a = 1 # TODO """ with self.assertAddsMessages( MessageTest(msg_id="fixme", line=2, args="TODO", col_offset=17) ): self.checker.process_tokens(_tokenize_str(code)) def test_xxx_without_space(self) -> None: code = """a = 1 #XXX """ with self.assertAddsMessages( MessageTest(msg_id="fixme", line=2, args="XXX", col_offset=17) ): self.checker.process_tokens(_tokenize_str(code)) def test_xxx_middle(self) -> None: code = """a = 1 # middle XXX """ with self.assertNoMessages(): self.checker.process_tokens(_tokenize_str(code)) def test_without_space_fixme(self) -> None: code = """a = 1 #FIXME """ with self.assertAddsMessages( MessageTest(msg_id="fixme", line=2, args="FIXME", col_offset=17) ): self.checker.process_tokens(_tokenize_str(code)) @set_config(notes=["???"]) def test_non_alphanumeric_codetag(self) -> None: code = """a = 1 #??? """ with self.assertAddsMessages( MessageTest(msg_id="fixme", line=2, args="???", col_offset=17) ): self.checker.process_tokens(_tokenize_str(code)) @set_config(notes=[]) def test_absent_codetag(self) -> None: code = """a = 1 # FIXME # FIXME # TODO # TODO # XXX # XXX """ with self.assertNoMessages(): self.checker.process_tokens(_tokenize_str(code)) @set_config(notes=["CODETAG"]) def test_other_present_codetag(self) -> None: code = """a = 1 # CODETAG # FIXME """ with self.assertAddsMessages( MessageTest(msg_id="fixme", line=2, args="CODETAG", col_offset=17) ): self.checker.process_tokens(_tokenize_str(code)) def test_issue_2321_should_not_trigger(self) -> None: code = 'print("# TODO this should not trigger a fixme")' with self.assertNoMessages(): self.checker.process_tokens(_tokenize_str(code)) def test_issue_2321_should_trigger(self) -> None: code = "# TODO this should not trigger a fixme" with self.assertAddsMessages( MessageTest( msg_id="fixme", line=1, args="TODO this should not trigger a fixme", col_offset=1, ) ): self.checker.process_tokens(_tokenize_str(code)) def test_dont_trigger_on_todoist(self) -> None: code = """ # Todoist API: What is this task about? # Todoist API: Look up a task's due date # Todoist API: Look up a Project/Label/Task ID # Todoist API: Fetch all labels # Todoist API: "Name" value # Todoist API: Get a task's priority # Todoist API: Look up the Project ID a Task belongs to # Todoist API: Fetch all Projects # Todoist API: Fetch all Tasks """ with self.assertNoMessages(): self.checker.process_tokens(_tokenize_str(code))
TestFixme
python
doocs__leetcode
solution/0300-0399/0311.Sparse Matrix Multiplication/Solution.py
{ "start": 0, "end": 363 }
class ____: def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: m, n = len(mat1), len(mat2[0]) ans = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): for k in range(len(mat2)): ans[i][j] += mat1[i][k] * mat2[k][j] return ans
Solution
python
getsentry__sentry-python
sentry_sdk/integrations/launchdarkly.py
{ "start": 1337, "end": 1934 }
class ____(Hook): @property def metadata(self): # type: () -> Metadata return Metadata(name="sentry-flag-auditor") def after_evaluation(self, series_context, data, detail): # type: (EvaluationSeriesContext, dict[Any, Any], EvaluationDetail) -> dict[Any, Any] if isinstance(detail.value, bool): add_feature_flag(series_context.key, detail.value) return data def before_evaluation(self, series_context, data): # type: (EvaluationSeriesContext, dict[Any, Any]) -> dict[Any, Any] return data # No-op.
LaunchDarklyHook
python
huggingface__transformers
src/transformers/models/qwen3_vl/modeling_qwen3_vl.py
{ "start": 34338, "end": 39779 }
class ____(Qwen3VLPreTrainedModel): config: Qwen3VLTextConfig _no_split_modules = ["Qwen3VLTextDecoderLayer"] def __init__(self, config: Qwen3VLTextConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [Qwen3VLTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = Qwen3VLTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = Qwen3VLTextRotaryEmbedding(config=config) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() @check_model_inputs() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, # args for deepstack visual_pos_masks: Optional[torch.Tensor] = None, deepstack_visual_embeds: Optional[list[torch.Tensor]] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> Union[tuple, BaseModelOutputWithPast]: r""" visual_pos_masks (`torch.Tensor` of shape `(batch_size, seqlen)`, *optional*): The mask of the visual positions. deepstack_visual_embeds (`list[torch.Tensor]`, *optional*): The deepstack visual embeddings. The shape is (num_layers, visual_seqlen, embed_dim). The feature is extracted from the different visual encoder layers, and fed to the decoder hidden states. It's from the paper DeepStack(https://arxiv.org/abs/2406.04334). """ if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") # torch.jit.trace() doesn't support cache objects in the output if use_cache and past_key_values is None and not torch.jit.is_tracing(): past_key_values = DynamicCache(config=self.config) if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) # the hard coded `3` is for temporal, height and width. if position_ids is None: position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1) elif position_ids.ndim == 2: position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) if position_ids.ndim == 3 and position_ids.shape[0] == 4: text_position_ids = position_ids[0] position_ids = position_ids[1:] else: text_position_ids = position_ids[0] attention_mask = create_causal_mask( config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, position_ids=text_position_ids, ) hidden_states = inputs_embeds # create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids) # decoder layers for layer_idx, decoder_layer in enumerate(self.layers): layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=text_position_ids, past_key_values=past_key_values, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = layer_outputs # add visual features to the hidden states of first several layers if deepstack_visual_embeds is not None and layer_idx in range(len(deepstack_visual_embeds)): hidden_states = self._deepstack_process( hidden_states, visual_pos_masks, deepstack_visual_embeds[layer_idx], ) hidden_states = self.norm(hidden_states) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values, ) def _deepstack_process( self, hidden_states: torch.Tensor, visual_pos_masks: torch.Tensor, visual_embeds: torch.Tensor ): visual_pos_masks = visual_pos_masks.to(hidden_states.device) visual_embeds = visual_embeds.to(hidden_states.device, hidden_states.dtype) hidden_states = hidden_states.clone() local_this = hidden_states[visual_pos_masks, :] + visual_embeds hidden_states[visual_pos_masks, :] = local_this return hidden_states @auto_docstring
Qwen3VLTextModel
python
airbytehq__airbyte
airbyte-integrations/connectors/source-braintree/source_braintree/schemas/merchant_account.py
{ "start": 601, "end": 810 }
class ____(CatalogModel): business_details: BussinessDetails currency_iso_code: str funding_details: FundingDetails id: str individual_details: IndividualDetails status: str
MerchantAccount
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solver24.py
{ "start": 752, "end": 789 }
class ____(Generic[AnyStr]): ...
ClassC
python
readthedocs__readthedocs.org
readthedocs/redirects/tests/test_views.py
{ "start": 9979, "end": 10182 }
class ____(TestViews): def setUp(self): super().setUp() self.organization = get( Organization, projects=[self.project], owners=[self.user] )
TestViewsWithOrganizations
python
doocs__leetcode
solution/3200-3299/3238.Find the Number of Winning Players/Solution.py
{ "start": 0, "end": 279 }
class ____: def winningPlayerCount(self, n: int, pick: List[List[int]]) -> int: cnt = [[0] * 11 for _ in range(n)] s = set() for x, y in pick: cnt[x][y] += 1 if cnt[x][y] > x: s.add(x) return len(s)
Solution
python
Textualize__textual
docs/examples/guide/reactivity/refresh02.py
{ "start": 321, "end": 661 }
class ____(App): CSS_PATH = "refresh02.tcss" def compose(self) -> ComposeResult: yield Input(placeholder="Enter your name") yield Name() def on_input_changed(self, event: Input.Changed) -> None: self.query_one(Name).who = event.value if __name__ == "__main__": app = WatchApp() app.run()
WatchApp
python
automl__auto-sklearn
autosklearn/pipeline/components/feature_preprocessing/kernel_pca.py
{ "start": 542, "end": 4046 }
class ____(AutoSklearnPreprocessingAlgorithm): def __init__( self, n_components, kernel, degree=3, gamma=0.25, coef0=0.0, random_state=None ): self.n_components = n_components self.kernel = kernel self.degree = degree self.gamma = gamma self.coef0 = coef0 self.random_state = random_state def fit(self, X, Y=None): import scipy.sparse import sklearn.decomposition self.n_components = int(self.n_components) self.degree = int(self.degree) self.gamma = float(self.gamma) self.coef0 = float(self.coef0) self.preprocessor = sklearn.decomposition.KernelPCA( n_components=self.n_components, kernel=self.kernel, degree=self.degree, gamma=self.gamma, coef0=self.coef0, remove_zero_eig=True, random_state=self.random_state, ) if scipy.sparse.issparse(X): X = X.astype(np.float64) with warnings.catch_warnings(): warnings.filterwarnings("error") self.preprocessor.fit(X) # Raise an informative error message, equation is based ~line 249 in # kernel_pca.py in scikit-learn if len(self.preprocessor.alphas_ / self.preprocessor.lambdas_) == 0: raise ValueError("KernelPCA removed all features!") return self def transform(self, X): if self.preprocessor is None: raise NotImplementedError() with warnings.catch_warnings(): warnings.filterwarnings("error") X_new = self.preprocessor.transform(X) # TODO write a unittest for this case if X_new.shape[1] == 0: raise ValueError("KernelPCA removed all features!") return X_new @staticmethod def get_properties(dataset_properties=None): return { "shortname": "KernelPCA", "name": "Kernel Principal Component Analysis", "handles_regression": True, "handles_classification": True, "handles_multiclass": True, "handles_multilabel": True, "handles_multioutput": True, "is_deterministic": False, "input": (DENSE, SPARSE, UNSIGNED_DATA), "output": (DENSE, UNSIGNED_DATA), } @staticmethod def get_hyperparameter_search_space( feat_type: Optional[FEAT_TYPE_TYPE] = None, dataset_properties=None ): n_components = UniformIntegerHyperparameter( "n_components", 10, 2000, default_value=100 ) kernel = CategoricalHyperparameter( "kernel", ["poly", "rbf", "sigmoid", "cosine"], "rbf" ) gamma = UniformFloatHyperparameter( "gamma", 3.0517578125e-05, 8, log=True, default_value=0.01, ) degree = UniformIntegerHyperparameter("degree", 2, 5, 3) coef0 = UniformFloatHyperparameter("coef0", -1, 1, default_value=0) cs = ConfigurationSpace() cs.add_hyperparameters([n_components, kernel, degree, gamma, coef0]) degree_depends_on_poly = EqualsCondition(degree, kernel, "poly") coef0_condition = InCondition(coef0, kernel, ["poly", "sigmoid"]) gamma_condition = InCondition(gamma, kernel, ["poly", "rbf"]) cs.add_conditions([degree_depends_on_poly, coef0_condition, gamma_condition]) return cs
KernelPCA
python
tensorflow__tensorflow
tensorflow/python/ops/clustering_ops_test.py
{ "start": 2670, "end": 3375 }
class ____(test.TestCase): def setUp(self): self._distances = np.zeros(1001) self._distances[500] = 100.0 self._distances[1000] = 50.0 def testBasic(self): with self.cached_session(): counts = {} seed = 0 for i in range(50): sample = self.evaluate( clustering_ops.kmc2_chain_initialization(self._distances, seed + i)) counts[sample] = counts.get(sample, 0) + 1 self.assertEqual(len(counts), 2) self.assertTrue(500 in counts) self.assertTrue(1000 in counts) self.assertGreaterEqual(counts[500], 5) self.assertGreaterEqual(counts[1000], 5) @test_util.run_all_in_graph_and_eager_modes
KMC2InitializationLargeTest
python
pyinstaller__pyinstaller
PyInstaller/exceptions.py
{ "start": 1448, "end": 1651 }
class ____(SystemExit): def __init__(self, message): super().__init__(f"ERROR: Support for external executable manifest was removed in PyInstaller v6.0. {message}")
RemovedExternalManifestError
python
ansible__ansible
test/units/_internal/templating/test_templar.py
{ "start": 15140, "end": 48910 }
class ____(BaseTemplar, unittest.TestCase): def _context(self, variables=None): variables = variables or {} env = AnsibleEnvironment() context = AnsibleContext(env, parent={}, name='some_context', blocks={}) for key, value in variables.items(): context.vars[key] = value return context def test(self): context = self._context() self.assertIsInstance(context, AnsibleContext) self.assertIsInstance(context, Context) def test_resolve_unsafe(self): context = self._context(variables={'some_unsafe_key': 'some_unsafe_string'}) res = context.resolve('some_unsafe_key') assert not TrustedAsTemplate.is_tagged_on(res) def test_resolve_unsafe_list(self): context = self._context(variables={'some_unsafe_key': ['some unsafe string 1']}) res = context.resolve('some_unsafe_key') assert not TrustedAsTemplate.is_tagged_on(res[0]) assert not TrustedAsTemplate.is_tagged_on(res) def test_resolve_unsafe_dict(self): context = self._context(variables={'some_unsafe_key': {'an_unsafe_dict': 'some unsafe string 1'} }) res = context.resolve('some_unsafe_key') assert not TrustedAsTemplate.is_tagged_on(res['an_unsafe_dict']) def test_resolve(self): context = self._context(variables={'some_key': 'some_string'}) res = context.resolve('some_key') self.assertEqual(res, 'some_string') def test_resolve_none(self): context = self._context(variables={'some_key': None}) res = context.resolve('some_key') self.assertEqual(res, None) def test_unsafe_lookup(): res = TemplateEngine( None, variables={ 'var0': TrustedAsTemplate().tag('{{ var1 }}'), 'var1': ['unsafe'], } ).template(TrustedAsTemplate().tag('{{ lookup("list", var0) }}')) assert not TrustedAsTemplate.is_tagged_on(res[0]) def test_unsafe_lookup_no_conversion(): res = TemplateEngine( None, variables={ 'var0': TrustedAsTemplate().tag('{{ var1 }}'), 'var1': ['unsafe'], } ).template( TrustedAsTemplate().tag('{{ lookup("list", var0) }}'), ) assert not TrustedAsTemplate.is_tagged_on(res) @pytest.mark.parametrize("tagged", ( False, True, )) def test_dict_template(tagged: bool) -> None: """Verify that templar.template can round-trip both tagged and untagged values in a dict.""" key1 = "key1" val1 = "val1" if tagged: key1 = origin.tag(key1) val1 = origin.tag(val1) test1 = { key1: val1, } variables = dict( test1=test1, ) templar = TemplateEngine(variables=variables) result = templar.template(TrustedAsTemplate().tag('{{test1}}')) assert result == test1 assert AnsibleTagHelper.tags(result) == AnsibleTagHelper.tags(test1) @pytest.mark.parametrize("expr,expected,variables", [ ("'constant'", "constant", None), ("a - b", 42, dict(a=100, b=58)), ]) def test_evaluate_expression(expr: str, expected: t.Any, variables: dict[str, t.Any] | None): assert TemplateEngine(variables=variables).evaluate_expression(TRUST.tag(expr)) == expected @pytest.mark.parametrize("expr,error_type", [ ("fhdgsfk#$76&@#$&", AnsibleTemplateSyntaxError), ("bogusvar", AnsibleUndefinedVariable), ("untrusted expression", TemplateTrustCheckFailedError), (dict(hi="{{'mom'}}"), TypeError), ]) def test_evaluate_expression_errors(expr: str, error_type: type[Exception]): if error_type is not TemplateTrustCheckFailedError: expr = TRUST.tag(expr) with pytest.raises(error_type): TemplateEngine().evaluate_expression(expr) @pytest.mark.parametrize("conditional,expected,variables", [ ("1 == 2", False, None), ("test2_name | default(True)", True, None), # DTFIX5: more success cases? ]) def test_evaluate_conditional(conditional: str, expected: t.Any, variables: dict[str, t.Any] | None): assert TemplateEngine().evaluate_conditional(TRUST.tag(conditional)) == expected @pytest.mark.parametrize("conditional,error_type", [ ("fkjhs$#@^%$*& ldfkjds", AnsibleTemplateSyntaxError), ("#jinja2:variable_start_string:2\n{{blah}}", AnsibleTemplateSyntaxError), ("#jinja2:bogus_key:'val'\n{{blah}}", AnsibleTemplateSyntaxError), ("bogusvar", AnsibleUndefinedVariable), ("not trusted", TemplateTrustCheckFailedError), ]) def test_evaluate_conditional_errors(conditional: t.Any, error_type: type[Exception], mocker: pytest_mock.MockerFixture): mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since a number of cases need it if error_type is not TemplateTrustCheckFailedError: conditional = TRUST.tag(conditional) with pytest.raises(error_type): TemplateEngine().evaluate_conditional(conditional) @pytest.mark.parametrize("value", ( '{{ foo }}', '{% foo %}', '{# foo #}', '{# {{ foo }} #}', '{# {{ nothing }} {# #}', '{# {{ nothing }} {# #} #}', '{% raw %}{{ foo }}{% endraw %}', # in 2.16 and earlier these were not considered templates due to syntax errors # now syntax errors in templates are still reported as templates, since is_template no longer compiles the template '{{ foo', '{% foo', '{# foo', '{{ foo %}', '{{ foo #}', '{% foo }}', '{% foo #}', '{# foo %}', '{# foo }}', '{{ foo {{', '{% raw %}{% foo %}', )) def test_is_template_true(value: str) -> None: assert TemplateEngine().is_template(TRUST.tag(value)) @pytest.mark.parametrize("value", ( 'foo', )) def test_is_template_false(value: str) -> None: assert not TemplateEngine().is_template(TRUST.tag(value)) @pytest.mark.parametrize("value", ( '{{ foo }}', '{% foo %}', '{# foo #}', '{# {{ foo }} #}', '{# {{ nothing }} {# #}', '{# {{ nothing }} {# #} #}', '{% raw %}{{ foo }}{% endraw %}', '{{', '{%', '{#', '{% raw', )) def test_is_possibly_template_true(value: str) -> None: assert is_possibly_template(value) @pytest.mark.parametrize("value", ( '{', '%', '#', 'foo', '}}', '%}', 'raw %}', '#}', )) def test_is_possibly_template_false(value: str) -> None: assert not is_possibly_template(value) def test_stop_on_container() -> None: # DTFIX5: add more test cases assert TemplateEngine().resolve_to_container(TRUST.tag('{{ [ 1 ] }}')) == [1] @pytest.mark.parametrize("value", [True, False]) def test_stripped_conditionals(value: bool, mocker: pytest_mock.MockerFixture) -> None: mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since this case needs it assert TemplateEngine().evaluate_conditional(TRUST.tag(f"""\n \r\n \t{{{{ {value} }}}} \n\n \t \t\t """)) == value @pytest.mark.parametrize("template, variables, error", ( ("{{ undefined_var.undefined_attribute }}", {}, "'undefined_var' is undefined >>"), ("{{ some_dict['undefined_key'] }}", dict(some_dict={}), "object of type 'dict' has no attribute 'undefined_key' >>"), ("{{ some_dict.undefined_key }}", dict(some_dict={}), "object of type 'dict' has no attribute 'undefined_key' >>"), ("{{ m1 }} {{ m2 }} here", {}, "<< error 1 - 'm1' is undefined >> << error 2 - 'm2' is undefined >> here"), ("before {{ m1 + m2 }} after", {}, "before << error 1 - 'm1' is undefined >><< error 2 - template potentially truncated >>"), )) def test_jinja_sourced_undefined(template: str, variables: dict[str, t.Any], error: str) -> None: """ Ensure when Jinja encounters a `Marker` and raises `MarkerError`, that we turn it back into the original `Marker` so marker_behavior can handle it during finalization. """ assert error in TemplateEngine(variables=variables, marker_behavior=ReplacingMarkerBehavior()).template(TRUST.tag(template)) def test_omit_concat() -> None: assert TemplateEngine().template(TRUST.tag("{{ omit }}hi{{ omit }} mom")) == 'hi mom' @pytest.mark.parametrize("conditional", ( # Jinja plugins "'join' is filter", "'join' is not test", "'eq' is test", "'eq' is not filter", # Ansible plugins "'comment' is filter", "'comment' is not test", "'version' is test", "'version' is not filter", # plugin not found "'nope' is not filter", "'nope' is not test", )) def test_plugin_found_not_found(conditional: str) -> None: assert TemplateEngine().evaluate_conditional(TRUST.tag(conditional)) @pytest.mark.parametrize("value, expected", ( ("{{ {'a': 1}.items() }}", [['a', 1]]), ("{{ {'a': 1}.keys() }}", ['a']), ("{{ {'a': 1}.values() }}", [1]), ("{{ yielder(2) }}", [0, 1]), ("{% set y = yielder(2) %}{{ y | list }} | {{ y | list }}", "[0, 1] | [0, 1]"), ), ids=str) def test_finalize_generator(value: t.Any, expected: t.Any) -> None: def yielder(count: int) -> t.Generator[int, None, None]: yield from range(count) templar = TemplateEngine(variables=dict( yielder=yielder, )) # DTFIX5: we still need to deal with the "Encountered unsupported" warnings these generate assert templar.template(TRUST.tag(value)) == expected @pytest.mark.parametrize("template", ( "{{ lookup('my_lookup', some_var) }}", "{{ some_var | my_filter }}", "{{ some_var is my_test }}", )) def test_eager_trip_undefined(template: str, mocker: pytest_mock.MockerFixture) -> None: """Verify that eager tripping of Marker works for template plugins which only perform isinstance checks on undefined values.""" from ansible.plugins.lookup import LookupBase class MyLookup(LookupBase): def run(self, terms, variables=None, **kwargs): return [isinstance(value, bool) for value in itertools.chain(*terms)] def my_filter(values): return [isinstance(value, bool) for value in values] def my_test(values): return all(isinstance(value, bool) for value in values) def mock_lookup_get(*_args, **_kwargs) -> t.Any: return MyLookup() mock_lookup_loader = mocker.MagicMock() mock_lookup_loader.get = mock_lookup_get mocker.patch.object(_jinja_plugins, 'lookup_loader', mock_lookup_loader) def get_templar(variables: dict[str, t.Any]) -> TemplateEngine: new_templar = TemplateEngine(variables=variables) new_templar.environment.filters['my_filter'] = my_filter new_templar.environment.tests['my_test'] = my_test return new_templar template = TRUST.tag(template) # verify the template works when some_var is defined templar = get_templar(dict(some_var=[True])) result = templar.template(template) assert result is True or result == [True] # verify the template raises AnsibleUndefinedVariable when some_var contains a template that references an undefined variable templar = get_templar(dict(some_var=[TRUST.tag("{{ nope }}")])) with pytest.raises(AnsibleUndefinedVariable) as ex: templar.template(template) assert ex.value.message == "'nope' is undefined" def as_template(value: str) -> str: return f"{{{{ {value} }}}}" TEMPLATED_LOOKUP_NAME_TEST_VALUES = [ ("""lookup('{{ "pipe" }}', 'echo hi')""", "hi"), ("""query('{{ "pipe" }}', 'echo hi')""", ["hi"]), ] @pytest.mark.parametrize("value", [v[0] for v in TEMPLATED_LOOKUP_NAME_TEST_VALUES]) def test_lookup_query_name_is_not_templated_non_conditional(value: str) -> None: with pytest.raises(AnsibleTemplatePluginNotFoundError): TemplateEngine().template(TRUST.tag(as_template(value))) @pytest.mark.parametrize("value", [v[0] for v in TEMPLATED_LOOKUP_NAME_TEST_VALUES]) def test_lookup_query_name_is_not_templated_conditional_nested_template(value: str, mocker: pytest_mock.MockerFixture) -> None: mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since a number of cases need it with pytest.raises(AnsibleTemplatePluginNotFoundError): TemplateEngine().evaluate_conditional(TRUST.tag(as_template(value))) @pytest.mark.parametrize("value, expected_result", TEMPLATED_LOOKUP_NAME_TEST_VALUES) def test_lookup_query_name_is_not_templated_conditional_expression(value: str, expected_result: t.Any, mocker: pytest_mock.MockerFixture) -> None: mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since a number of cases need it with emits_warnings(warning_pattern="should not contain embedded templates"): assert TemplateEngine().evaluate_conditional(TRUST.tag(f'{value} == {expected_result!r}')) @pytest.mark.parametrize("value", [ "foo(", "'a' == {{ 'b' }}", ]) def test_conditional_syntax_error(value: str) -> None: with pytest.raises(AnsibleTemplateSyntaxError): TemplateEngine().evaluate_conditional(TRUST.tag(value)) BROKEN_CONDITIONAL_VALUES = [ (None, True), # stupid backward-compat ("", True), # stupid backward-compat ("''", False), ("0", False), ("0.0", False), ("1", True), ("1.1", True), ("'abc'", True), ("{{ '' }}", True), ("{{ None }}", True), ("{{ 0 }}", False), ("{{ 0.0 }}", False), ("{{ [] }}", False), ("{{ {} }}", False), ([], False), ([TRUST.tag("{{ omit }}")], False), ({}, False), (dict(a=TRUST.tag("{{ omit }}")), False), (["abc", TRUST.tag("{{ omit }}")], True), (dict(a="b", omitted=TRUST.tag("{{ omit }}")), True), (0, False), (0.0, False), (1, True), (1.1, True), ] @pytest.mark.parametrize("value", [v[0] for v in BROKEN_CONDITIONAL_VALUES], ids=repr) def test_broken_conditionals_disabled(value: t.Any, mocker: pytest_mock.MockerFixture) -> None: mocker.patch.object(_TemplateConfig, 'allow_broken_conditionals', False) with pytest.raises(AnsibleBrokenConditionalError): TemplateEngine().evaluate_conditional(TRUST.tag(value)) @pytest.mark.parametrize("value, expected_result", BROKEN_CONDITIONAL_VALUES, ids=repr) def test_broken_conditionals_enabled(value: t.Any, expected_result: bool, mocker: pytest_mock.MockerFixture) -> None: mocker.patch.object(_TemplateConfig, 'allow_broken_conditionals', True) mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) # force this on since a number of cases need it deprecation_matches = [] if isinstance(value, str) and is_possibly_all_template(value): deprecation_matches.append("should not be surrounded") if value in (None, '', "{{ '' }}", "{{ None }}"): deprecation_matches.append("Empty conditional") else: deprecation_matches.append("must have a boolean result") with emits_warnings(deprecation_pattern=deprecation_matches): assert TemplateEngine().evaluate_conditional(TRUST.tag(value)) == expected_result @pytest.mark.parametrize("template, expected", ( ("1 == '{{ 1 }}'", False), ("lookup('items', '{{ [1, 2, 3] }}') == [1, 2, 3]", False), ("query('items', '{{ [1, 2, 3] }}') == [1, 2, 3]", False), )) def test_embedded_templates_disabled(template: str, expected: t.Any, mocker: pytest_mock.MockerFixture) -> None: mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', False) with emits_warnings(warning_pattern=[]): assert TemplateEngine().evaluate_conditional(TRUST.tag(template)) == expected @pytest.mark.parametrize("template, expected", ( ("1 == '{{ 1 }}'", True), ("lookup('items', '{{ [1, 2, 3] }}') == [1, 2, 3]", True), ("query('items', '{{ [1, 2, 3] }}') == [1, 2, 3]", True), )) def test_embedded_templates_enabled(template: str, expected: t.Any, mocker: pytest_mock.MockerFixture) -> None: mocker.patch.object(_TemplateConfig, 'allow_embedded_templates', True) templar = TemplateEngine() with emits_warnings(warning_pattern="should not contain embedded templates"): assert templar.evaluate_conditional(TRUST.tag(template)) == expected # only lookup/query args support embedded templates in an actual template (not a naked expression) if 'lookup' in template or 'query' in template: with emits_warnings(warning_pattern="should not contain embedded templates"): assert templar.evaluate_conditional(TRUST.tag(as_template(template))) == expected def test_available_vars_smuggling(): """ Jinja Template.render() and TemplateExpression.__call__() flatten their args/kwargs via splatting to dict(), which is an unnecessary copy as well as causing top-level templated variables to be rendered prematurely. We have some arg smuggling code to prevent this, which this test validates. """ class ExplodingDict(dict): """A dict subclass that explodes when copied or iterated via `dict()`.""" def __iter__(self): raise NotImplementedError() def keys(self): raise NotImplementedError() template_vars = ExplodingDict() # ensure our tripwire dict subclass fails when used as the source for a dict copy with pytest.raises(NotImplementedError): dict(template_vars) # if Jinja copies our input dict, it should blow up; assert that it doesn't and that the template renders as expected assert TemplateEngine(variables=template_vars).template(TRUST.tag("{{ 1 }}")) == 1 def test_template_var_isolation(): """ Ensure that plugin mutations to lazy-wrapped container variables do not persist outside templating. Direct mutation via Templar.available_variables is not currently protected (and is generally a bad idea). """ orig_dict_value = dict(one="one") orig_list_value = [1, 2, 3] available_vars = dict(dict_value=orig_dict_value, list_value=orig_list_value) def mutate_my_vars(dict_value: dict, list_value: list) -> dict[str, t.Any]: dict_value["added"] = "added" list_value.append("added") return dict(dict_value=dict_value, list_value=list_value) res = TemplateEngine(variables=available_vars).evaluate_expression( TRUST.tag("mutate_my_vars(dict_value, list_value)"), local_variables=dict(mutate_my_vars=mutate_my_vars) ) # ensure the plugin returned the mutated copies as expected assert res == dict(dict_value=dict(one="one", added="added"), list_value=[1, 2, 3, "added"]) # ensure the original input variables are the same unmodified instances assert available_vars == dict(dict_value=dict(one="one"), list_value=[1, 2, 3]) assert available_vars['dict_value'] is orig_dict_value assert available_vars['list_value'] is orig_list_value @pytest.mark.parametrize('fixture, plugin_type, plugin_name, expected', ( ('no_collections', 'filter', 'invalid/name.does_not_matter.also_does_not_matter', AnsibleTemplateSyntaxError), # plugin is None ('no_collections', 'lookup', 'invalid/name.does_not_matter.also_does_not_matter', AnsibleTemplatePluginNotFoundError), ('no_collections', 'filter', 'missing_namespace_name.does_not_matter.also_does_not_matter', AnsibleTemplateSyntaxError), # KeyError ('no_collections', 'lookup', 'missing_namespace_name.does_not_matter.also_does_not_matter', AnsibleTemplatePluginNotFoundError), ('valid_collection', 'filter', 'valid.invalid/name.does_not_matter', AnsibleTemplateSyntaxError), # KeyError ('valid_collection', 'lookup', 'valid.invalid/name.does_not_matter', AnsibleTemplatePluginNotFoundError), ('valid_collection', 'filter', 'valid.missing_collection.does_not_matter', AnsibleTemplateSyntaxError), # KeyError ('valid_collection', 'lookup', 'valid.missing_collection.does_not_matter', AnsibleTemplatePluginNotFoundError), ('valid_collection', 'filter', 'valid.also_valid.invalid/name', AnsibleTemplateSyntaxError), # plugin is None ('valid_collection', 'lookup', 'valid.also_valid.invalid/name', AnsibleTemplatePluginNotFoundError), ('valid_collection', 'filter', 'valid.also_valid.missing_plugin', AnsibleTemplateSyntaxError), # plugin is None ('valid_collection', 'lookup', 'valid.also_valid.missing_plugin', AnsibleTemplatePluginNotFoundError), ('valid_collection', 'filter', 'valid.also_valid.also_also_valid', []), ('valid_collection', 'lookup', 'valid.also_valid.also_also_valid', []), ('valid_collection', 'filter', 'valid.also_valid.runtime_error', AnsibleTemplatePluginRuntimeError), ('valid_collection', 'lookup', 'valid.also_valid.runtime_error', AnsibleTemplatePluginRuntimeError), ('valid_collection', 'filter', 'valid.also_valid.load_error', AnsibleTemplatePluginLoadError), # AnsibleError ('valid_collection', 'lookup', 'valid.also_valid.load_error', AnsibleTemplatePluginLoadError), ('valid_collection', 'template', '{% if false %}{{ 123 | valid.also_valid.load_error }}{% else %}Success{% endif %}', AnsibleTemplatePluginLoadError), ('no_collections', 'filter', 'ansible.invalid/name.does_not_matter', AnsibleTemplateSyntaxError), # KeyError ('no_collections', 'lookup', 'ansible.invalid/name.does_not_matter', AnsibleTemplatePluginNotFoundError), ('no_collections', 'filter', 'ansible.missing_collection.does_not_matter', AnsibleTemplateSyntaxError), # KeyError ('no_collections', 'lookup', 'ansible.missing_collection.does_not_matter', AnsibleTemplatePluginNotFoundError), ('no_collections', 'filter', 'ansible.builtin.invalid/name', AnsibleTemplateSyntaxError), # plugin is None ('no_collections', 'lookup', 'ansible.builtin.invalid/name', AnsibleTemplatePluginNotFoundError), ('no_collections', 'filter', 'ansible.builtin.missing_plugin', AnsibleTemplateSyntaxError), # plugin is None ('no_collections', 'lookup', 'ansible.builtin.missing_plugin', AnsibleTemplatePluginNotFoundError), ('no_collections', 'filter', 'ansible.builtin.quote', 'foo'), ('no_collections', 'lookup', 'ansible.builtin.env', []), ('no_collections', 'template', '{% if false %}{{ 123 | ansible.builtin.missing_plugin }}{% else %}Success{% endif %}', 'Success'), ('no_collections', 'filter', 'invalid/name', AnsibleTemplateSyntaxError), # plugin is None ('no_collections', 'lookup', 'invalid/name', AnsibleTemplatePluginNotFoundError), ('no_collections', 'filter', 'missing_plugin', AnsibleTemplateSyntaxError), # plugin is None ('no_collections', 'lookup', 'missing_plugin', AnsibleTemplatePluginNotFoundError), ('no_collections', 'filter', 'quote', 'foo'), ('no_collections', 'lookup', 'env', []), ), ids=str) def test_jinja2_loader_plugin(fixture: str, plugin_type: str, plugin_name: str, expected: t.Any) -> None: if plugin_type == 'filter': expression = f'{{{{ "foo" | {plugin_name} }}}}' elif plugin_type == 'template': expression = plugin_name # abusing plugin_type and plugin_name to allow for testing arbitrary expressions else: expression = f'{{{{ lookup("{plugin_name}") }}}}' # HACK: this test should really be using a shared collection loader fixture, but this fixes an "inherited" dummy collection loader from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder try: _AnsibleCollectionFinder._remove() nuke_module_prefix('ansible_collections') except Exception: pass _AnsibleCollectionFinder(paths=[str(pathlib.Path(__file__).parent / 'fixtures' / fixture)])._install() try: if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected): TemplateEngine().template(TRUST.tag(expression)) else: assert TemplateEngine().template(TRUST.tag(expression)) == expected finally: _AnsibleCollectionFinder._remove() nuke_module_prefix('ansible_collections') def test_variable_name_as_template_success() -> None: name = origin.tag("blar") res = TemplateEngine().variable_name_as_template(name) assert res.replace(' ', '') == "{{blar}}" required_tags: frozenset[AnsibleDatatagBase] = frozenset({origin, TrustedAsTemplate()}) assert required_tags - AnsibleTagHelper.tags(res) == set() # there might be others, that's fine def test_variable_name_as_template_invalid() -> None: invalid_name = origin.tag(" invalid[var*name") with pytest.raises(AnsibleError) as err: TemplateEngine().variable_name_as_template(invalid_name) assert err.value.obj is invalid_name @pytest.mark.parametrize("expression, expected", ( ("dictthing.subdict1.subdict2", "hi mom"), ("dictthing.sublist1[0]", 1), ("dictthing[keys.sublist1][0]", 1), ("123", 123), )) def test_resolve_variable_expression_success(expression: str, expected: t.Any) -> None: templar = TemplateEngine() local_variables = dict( dictthing=dict(sublist1=[1, 2, 3], subdict1=dict(subdict2="hi mom")), keys=dict(sublist1="sublist1") ) assert templar.resolve_variable_expression(expression, local_variables=local_variables) == expected @pytest.mark.parametrize("expression", ( "'text'", "dictthing['subdict1']", "q('env')", )) def test_resolve_variable_expression_invalid(expression: str) -> None: templar = TemplateEngine() with pytest.raises(AnsibleError) as err: templar.resolve_variable_expression(expression, local_variables=dict(dictthing=dict(subdict1=1))) assert err.value.obj is expression def test_resolve_variable_expression_missing() -> None: templar = TemplateEngine() expr = origin.tag("missing_variable") with pytest.raises(AnsibleUndefinedVariable) as err: templar.resolve_variable_expression(expr) assert err.value.obj == expr # may not be the same instance, since it was tagged TrustedAsTemplate internally required_tags: frozenset[AnsibleDatatagBase] = frozenset({origin, TrustedAsTemplate()}) assert required_tags - AnsibleTagHelper.tags(err.value.obj) == set() # there might be others, that's fine def test_error_invalid_non_string_template(): """Ensure errors on non-string template inputs include type information.""" with pytest.raises(AnsibleTemplateError) as err: TemplateEngine().template(...) assert f"Type {type(...).__name__!r} is unsupported for variable storage." in err.value.message def nuke_module_prefix(prefix): for module_to_nuke in [m for m in sys.modules if m.startswith(prefix)]: sys.modules.pop(module_to_nuke) def test_template_transform_limit_exceeded(mocker: pytest_mock.MockerFixture) -> None: """ Verify that template transforms cannot trigger an infinite loop. This currently requires injecting bogus transforms to trigger the condition, but the logic is present to catch future coding errors. """ class One: def __init__(self, *args, **kwargs): pass class Two: def __init__(self, *args, **kwargs): pass mocker.patch.dict(_transform._type_transform_mapping, {One: Two, Two: One}) with pytest.raises(AnsibleTemplateTransformLimitError): TemplateEngine(variables=dict(limit=One())).template(TRUST.tag("{{ limit }}")) def test_transform_transform_limit_exceeded(mocker: pytest_mock.MockerFixture) -> None: """ Verify that standalone recursive transforms cannot trigger an infinite loop. This currently requires injecting bogus transforms to trigger the condition, but the logic is present to catch future coding errors. """ class One: def __init__(self, *args, **kwargs): pass class Two: def __init__(self, *args, **kwargs): pass mocker.patch.dict(_transform._type_transform_mapping, {One: Two, Two: One}) with pytest.raises(AnsibleTemplateTransformLimitError): TemplateEngine().transform(One()) def test_deprecated_dedupe_and_source(): """Validate dedupe and source context behavior for deprecated item access and associated warning behavior.""" # unique tag instances that share the same contents (can be tracked independently by the audit context) deprecated_string = Deprecated(msg="deprecated").tag("deprecated string") deprecated_list = Deprecated(msg="deprecated").tag([42]) deprecated_dict = Deprecated(msg="deprecated").tag(dict(key="value")) # a shared tag instance (cannot be tracked independently by the audit context) shared_tag_instance = Deprecated(msg="shared tag") d1 = shared_tag_instance.tag("d1") d2 = shared_tag_instance.tag("d2") variables = dict( indirect1=TRUST.tag('{{ indirect2 }}'), indirect2=TRUST.tag('{{ deprecated_string }}'), deprecated_string=deprecated_string, deprecated_list=deprecated_list, deprecated_dict=deprecated_dict, d1=d1, d2=d2, ansible_deprecation_warnings=True, ) templar = TemplateEngine(variables=variables) with _display_utils.DeferredWarningContext(variables=variables) as dwc: # The indirect access summary occurs first. # The two following direct access summaries get deduped to a single one by the warning context (but unique template value keeps distinct from indirect). # The accesses with the shared tag instance values are internally deduped by the audit context. templar.evaluate_expression(TRUST.tag("indirect1 and deprecated_list and deprecated_dict and d1 and d2")) dep_warnings = dwc.get_deprecation_warnings() assert len(dep_warnings) == 3 assert 'deprecated_string' in _event_utils.format_event_brief_message(dep_warnings[0].event) assert 'indirect1 and deprecated_list and deprecated_dict' in _event_utils.format_event_brief_message(dep_warnings[1].event) assert 'd1 and d2' in _event_utils.format_event_brief_message(dep_warnings[2].event) def test_jinja_const_template_leak(template_context: TemplateContext) -> None: """Verify that _JinjaConstTemplate is present during internal templating.""" with _display_utils.DeferredWarningContext(variables={}): # suppress warning from usage of embedded template with unittest.mock.patch.object(_TemplateConfig, 'allow_embedded_templates', True): assert _JinjaConstTemplate.is_tagged_on(TemplateEngine().template(TRUST.tag("{{ '{{ 1 }}' }}"))) def test_jinja_const_template_finalized() -> None: """Verify that _JinjaConstTemplate is not present in finalized template results.""" with _display_utils.DeferredWarningContext(variables={}): # suppress warning from usage of embedded template with unittest.mock.patch.object(_TemplateConfig, 'allow_embedded_templates', True): assert not _JinjaConstTemplate.is_tagged_on(TemplateEngine().template(TRUST.tag("{{ '{{ 1 }}' }}"))) @pytest.mark.parametrize("template,expected", ( ("{{ (-1).__abs__() }}", 1), )) def test_unsafe_attr_access(template: str, expected: object) -> None: """Verify that unsafe attribute access fails by default and works when explicitly configured.""" assert _TemplateConfig.sandbox_mode == _SandboxMode.DEFAULT with pytest.raises(AnsibleUndefinedVariable): TemplateEngine().template(TRUST.tag(template)) with unittest.mock.patch.object(_TemplateConfig, 'sandbox_mode', _SandboxMode.ALLOW_UNSAFE_ATTRIBUTES): assert TemplateEngine().template(TRUST.tag(template)) == expected def test_marker_from_test_plugin() -> None: """Verify test plugins can raise MarkerError to return a Marker, and that no warnings or deprecations are emitted.""" with emits_warnings(deprecation_pattern=[], warning_pattern=[]): assert TemplateEngine(variables=dict(something=TRUST.tag("{{ nope }}"))).template(TRUST.tag("{{ (something is eq {}) is undefined }}")) @pytest.mark.parametrize("template,expected", ( ("{{ none }}", None), # concat sees one node, NoneType result is preserved ("{% if False %}{% endif %}", None), # concat sees one node, NoneType result is preserved ("{{''}}{% if False %}{% endif %}", ""), # multiple blocks with an embedded None result, concat is in play, the result is an empty string ("hey {{ none }}", "hey "), # composite template, the result is an empty string ("{% import 'importme' as imported %}{{ imported }}", "imported template result"), )) def test_none_concat(template: str, expected: object) -> None: """Validate that None values are omitted from composite template concat.""" te = TemplateEngine() # set up an importable template to exercise TemplateModule code paths te.environment.loader = DictLoader(dict(importme=TRUST.tag("{{ none }}{{ 'imported template result' }}{{ none }}"))) assert te.template(TRUST.tag(template)) == expected def test_filter_generator() -> None: """Verify that filters which return a generator are converted to a list while under the filter's JinjaCallContext.""" variables = dict( foo=[ dict(x=1, optional_var=0), dict(x=2), ], bar=TRUST.tag("{{ foo | selectattr('optional_var', 'defined') }}"), ) te = TemplateEngine(variables=variables) te.template(TRUST.tag("{{ bar }}")) te.template(TRUST.tag("{{ lookup('vars', 'bar') }}")) def test_call_context_reset() -> None: """Ensure that new template invocations do not inherit trip behavior from running Jinja plugins.""" templar = TemplateEngine(variables=dict( somevar=TRUST.tag("{{ somedict.somekey | default('ok') }}"), somedict=dict( somekey=TRUST.tag("{{ not_here }}"), ) )) assert templar.template(TRUST.tag("{{ lookup('vars', 'somevar') }}")) == 'ok'
TestAnsibleContext
python
readthedocs__readthedocs.org
readthedocs/core/forms.py
{ "start": 5784, "end": 6916 }
class ____: """ Data class for rich content dropdowns. Instead of just value and text, :py:class:`RichSelect` displays multiple attributes in each item content display. Choices can be passed as an array, however with the default :py:class:`django.forms.fields.ChoiceField` you should still pass in a tuple of ``(value, RichChoice(...))`` as the tuple values are used in field validation: choices = [ RichChoice(name="Foo", value="foo", ...), RichChoice(name="Bar", value="bar", ...), ] field = forms.ChoiceField( ..., widget=RichSelect(), choices=[(choice.value, choice) for choice in choices], ) """ #: Choice verbose text display text: str #: Choice input value value: str #: Right floated content for dropdown item description: str #: Optional image URL for item image_url: str = None #: Optional image alt text image_alt: str = None #: Error string to display next to text error: str = None #: Is choice disabled? disabled: bool = False
RichChoice
python
python-excel__xlwt
xlwt/Cell.py
{ "start": 5306, "end": 8525 }
class ____(object): __slots__ = ["rowx", "colx", "xf_idx", "frmla", "calc_flags"] def __init__(self, rowx, colx, xf_idx, frmla, calc_flags=0): self.rowx = rowx self.colx = colx self.xf_idx = xf_idx self.frmla = frmla self.calc_flags = calc_flags def get_biff_data(self): return BIFFRecords.FormulaRecord(self.rowx, self.colx, self.xf_idx, self.frmla.rpn(), self.calc_flags).get() # module-level function for *internal* use by the Row module def _get_cells_biff_data_mul(rowx, cell_items): # Return the BIFF data for all cell records in the row. # Adjacent BLANK|RK records are combined into MUL(BLANK|RK) records. pieces = [] nitems = len(cell_items) i = 0 while i < nitems: icolx, icell = cell_items[i] if isinstance(icell, NumberCell): isRK, value = icell.get_encoded_data() if not isRK: pieces.append(value) # pre-packed NUMBER record i += 1 continue muldata = [(value, icell.xf_idx)] target = NumberCell elif isinstance(icell, BlankCell): muldata = [icell.xf_idx] target = BlankCell else: pieces.append(icell.get_biff_data()) i += 1 continue lastcolx = icolx j = i packed_record = '' for j in range(i+1, nitems): jcolx, jcell = cell_items[j] if jcolx != lastcolx + 1: nexti = j break if not isinstance(jcell, target): nexti = j break if target == NumberCell: isRK, value = jcell.get_encoded_data() if not isRK: packed_record = value nexti = j + 1 break muldata.append((value, jcell.xf_idx)) else: muldata.append(jcell.xf_idx) lastcolx = jcolx else: nexti = j + 1 if target == NumberCell: if lastcolx == icolx: # RK record value, xf_idx = muldata[0] pieces.append(pack('<5Hi', 0x027E, 10, rowx, icolx, xf_idx, value)) else: # MULRK record nc = lastcolx - icolx + 1 pieces.append(pack('<4H', 0x00BD, 6 * nc + 6, rowx, icolx)) pieces.append(b''.join(pack('<Hi', xf_idx, value) for value, xf_idx in muldata)) pieces.append(pack('<H', lastcolx)) else: if lastcolx == icolx: # BLANK record xf_idx = muldata[0] pieces.append(pack('<5H', 0x0201, 6, rowx, icolx, xf_idx)) else: # MULBLANK record nc = lastcolx - icolx + 1 pieces.append(pack('<4H', 0x00BE, 2 * nc + 6, rowx, icolx)) pieces.append(b''.join(pack('<H', xf_idx) for xf_idx in muldata)) pieces.append(pack('<H', lastcolx)) if packed_record: pieces.append(packed_record) i = nexti return b''.join(pieces)
FormulaCell
python
sympy__sympy
sympy/matrices/utilities.py
{ "start": 279, "end": 2523 }
class ____(local): def __init__(self): self.state = None _dotprodsimp_state = DotProdSimpState() @contextmanager def dotprodsimp(x): old = _dotprodsimp_state.state try: _dotprodsimp_state.state = x yield finally: _dotprodsimp_state.state = old @overload def _dotprodsimp(expr: Expr, withsimp: Literal[False] = False) -> Expr: ... @overload def _dotprodsimp(expr: Expr, withsimp: Literal[True]) -> tuple[Expr, bool]: ... def _dotprodsimp(expr: Expr, withsimp: bool = False) -> Expr | tuple[Expr, bool]: """Wrapper for simplify.dotprodsimp to avoid circular imports.""" from sympy.simplify.simplify import dotprodsimp as dps return dps(expr, withsimp=withsimp) def _get_intermediate_simp(deffunc=lambda x: x, offfunc=lambda x: x, onfunc=_dotprodsimp, dotprodsimp=None): """Support function for controlling intermediate simplification. Returns a simplification function according to the global setting of dotprodsimp operation. ``deffunc`` - Function to be used by default. ``offfunc`` - Function to be used if dotprodsimp has been turned off. ``onfunc`` - Function to be used if dotprodsimp has been turned on. ``dotprodsimp`` - True, False or None. Will be overridden by global _dotprodsimp_state.state if that is not None. """ if dotprodsimp is False or _dotprodsimp_state.state is False: return offfunc if dotprodsimp is True or _dotprodsimp_state.state is True: return onfunc return deffunc # None, None def _get_intermediate_simp_bool(default=False, dotprodsimp=None): """Same as ``_get_intermediate_simp`` but returns bools instead of functions by default.""" return _get_intermediate_simp(default, False, True, dotprodsimp) def _iszero(x: Expr) -> bool | None: """Returns True if x is zero.""" return getattr(x, 'is_zero', None) def _is_zero_after_expand_mul(x): """Tests by expand_mul only, suitable for polynomials and rational functions.""" return expand_mul(x) == 0 def _simplify(expr): """ Wrapper to avoid circular imports. """ from sympy.simplify.simplify import simplify return simplify(expr)
DotProdSimpState
python
astropy__astropy
astropy/modeling/spline.py
{ "start": 18161, "end": 19820 }
class ____(_SplineFitter): """ Fit an interpolating spline. """ def __call__(self, model, x, y, **kwargs): """ Fit an interpolating spline to data. Parameters ---------- model : `Spline1D` The spline model to fit. x : array-like The x data values. y : array-like The y data values. **kwargs : dict, optional Additional keyword arguments: - ``weights`` : array-like, optional Weights for the data points. - ``bbox`` : array-like, optional The bounding box limits as ``[xmin, xmax]``. Default is ``[None, None]``. Returns ------- fitted_model : `Spline1D` A copy of the input model with fitted parameters. """ return super().__call__(model, x, y, **kwargs) def _fit_method(self, model, x, y, **kwargs): weights = kwargs.pop("weights", None) bbox = kwargs.pop("bbox", [None, None]) if model.user_knots: warnings.warn( "The user-specified knots from the input model " "will be ignored for interpolating data.", AstropyUserWarning, ) model.user_knots = False if bbox != [None, None]: model.bounding_box = bbox from scipy.interpolate import InterpolatedUnivariateSpline spline = InterpolatedUnivariateSpline( x, y, w=weights, bbox=bbox, k=model.degree ) model.tck = spline._eval_args return spline
SplineInterpolateFitter
python
davidhalter__jedi
test/test_api/test_full_name.py
{ "start": 452, "end": 1061 }
class ____(object): operation = None @pytest.fixture(autouse=True) def init(self, Script, environment): self.Script = Script self.environment = environment def check(self, source, desired): script = self.Script(textwrap.dedent(source)) definitions = getattr(script, self.operation)() for d in definitions: self.assertEqual(d.full_name, desired) def test_os_path_join(self): self.check('import os; os.path.join', 'os.path.join') def test_builtin(self): self.check('TypeError', 'builtins.TypeError')
MixinTestFullName
python
google__pytype
pytype/overlays/attr_overlay.py
{ "start": 9376, "end": 9899 }
class ____(AttrsBase): """Implements the @attr.s decorator.""" @classmethod def make(cls, ctx, module="attr"): return super().make("s", ctx, module) @classmethod def make_dataclass(cls, ctx, module): ret = super().make("s", ctx, module) ret.partial_args["auto_attribs"] = True return ret @classmethod def from_metadata(cls, ctx, metadata): kwargs = {k: metadata[k] for k in ("init", "kw_only", "auto_attribs")} ret = cls.make(ctx) ret.set_current_args(kwargs) return ret
Attrs
python
apache__airflow
airflow-core/tests/unit/listeners/class_listener.py
{ "start": 926, "end": 2211 }
class ____: def __init__(self): self.started_component = None self.stopped_component = None self.state = [] @hookimpl def on_starting(self, component): self.started_component = component self.state.append(DagRunState.RUNNING) @hookimpl def before_stopping(self, component): global stopped_component stopped_component = component self.state.append(DagRunState.SUCCESS) @hookimpl def on_task_instance_running(self, previous_state, task_instance): self.state.append(TaskInstanceState.RUNNING) @hookimpl def on_task_instance_success(self, previous_state, task_instance): self.state.append(TaskInstanceState.SUCCESS) @hookimpl def on_task_instance_failed(self, previous_state, task_instance, error: None | str | BaseException): self.state.append(TaskInstanceState.FAILED) @hookimpl def on_dag_run_running(self, dag_run, msg: str): self.state.append(DagRunState.RUNNING) @hookimpl def on_dag_run_success(self, dag_run, msg: str): self.state.append(DagRunState.SUCCESS) @hookimpl def on_dag_run_failed(self, dag_run, msg: str): self.state.append(DagRunState.FAILED) def clear(): pass
ClassBasedListener
python
catalyst-team__catalyst
examples/catalyst_rl/ddpg.py
{ "start": 562, "end": 1198 }
class ____(gym.ActionWrapper): def action(self, action: float) -> float: low_bound = self.action_space.low upper_bound = self.action_space.high action = low_bound + (action + 1.0) * 0.5 * (upper_bound - low_bound) action = np.clip(action, low_bound, upper_bound) return action def _reverse_action(self, action: float) -> float: low_bound = self.action_space.low upper_bound = self.action_space.high action = 2 * (action - low_bound) / (upper_bound - low_bound) - 1 action = np.clip(action, low_bound, upper_bound) return action
NormalizedActions
python
django-guardian__django-guardian
benchmarks/models.py
{ "start": 189, "end": 319 }
class ____(UserObjectPermissionBase): content_object = models.ForeignKey("TestDirectModel", on_delete=models.CASCADE)
DirectUser
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_legacy_tests.py
{ "start": 1371, "end": 2602 }
class ____(TestCase): def test_empty(self): class Schema: option = c.OptionallyRequired() conf = self.get_config(Schema, {'option': None}) self.assertEqual(conf['option'], None) self.assertEqual(Schema.option.required, False) def test_required(self): class Schema: option = c.OptionallyRequired(required=True) with self.expect_error(option="Required configuration not provided."): self.get_config(Schema, {'option': None}) self.assertEqual(Schema.option.required, True) def test_required_no_default(self): class Schema: option = c.OptionallyRequired(required=True) conf = self.get_config(Schema, {'option': 2}) self.assertEqual(conf['option'], 2) def test_default(self): class Schema: option = c.OptionallyRequired(default=1) conf = self.get_config(Schema, {'option': None}) self.assertEqual(conf['option'], 1) def test_replace_default(self): class Schema: option = c.OptionallyRequired(default=1) conf = self.get_config(Schema, {'option': 2}) self.assertEqual(conf['option'], 2)
OptionallyRequiredTest
python
celery__celery
t/unit/utils/test_threads.py
{ "start": 707, "end": 1092 }
class ____: def test_iter(self): x = Local() x.foo = 'bar' ident = x.__ident_func__() assert (ident, {'foo': 'bar'}) in list(iter(x)) delattr(x, 'foo') assert (ident, {'foo': 'bar'}) not in list(iter(x)) with pytest.raises(AttributeError): delattr(x, 'foo') assert x(lambda: 'foo') is not None
test_Local
python
PyCQA__pylint
tests/functional/s/super/super_with_arguments.py
{ "start": 195, "end": 273 }
class ____(Foo): def __init__(self): super(Bar, self).__init__()
Qux
python
matplotlib__matplotlib
galleries/examples/misc/demo_ribbon_box.py
{ "start": 279, "end": 1148 }
class ____: original_image = plt.imread( cbook.get_sample_data("Minduka_Present_Blue_Pack.png")) cut_location = 70 b_and_h = original_image[:, :, 2:3] color = original_image[:, :, 2:3] - original_image[:, :, 0:1] alpha = original_image[:, :, 3:4] nx = original_image.shape[1] def __init__(self, color): rgb = mcolors.to_rgb(color) self.im = np.dstack( [self.b_and_h - self.color * (1 - np.array(rgb)), self.alpha]) def get_stretched_image(self, stretch_factor): stretch_factor = max(stretch_factor, 1) ny, nx, nch = self.im.shape ny2 = int(ny*stretch_factor) return np.vstack( [self.im[:self.cut_location], np.broadcast_to( self.im[self.cut_location], (ny2 - ny, nx, nch)), self.im[self.cut_location:]])
RibbonBox
python
ray-project__ray
python/ray/air/integrations/keras.py
{ "start": 3127, "end": 6522 }
class ____(_Callback): """Keras callback for Ray Train reporting and checkpointing. .. note:: Metrics are always reported with checkpoints, even if the event isn't specified in ``report_metrics_on``. Example: .. code-block:: python ############# Using it in TrainSession ############### from ray.air.integrations.keras import ReportCheckpointCallback def train_loop_per_worker(): strategy = tf.distribute.MultiWorkerMirroredStrategy() with strategy.scope(): model = build_model() model.fit(dataset_shard, callbacks=[ReportCheckpointCallback()]) Args: metrics: Metrics to report. If this is a list, each item describes the metric key reported to Keras, and it's reported under the same name. If this is a dict, each key is the name reported and the respective value is the metric key reported to Keras. If this is None, all Keras logs are reported. report_metrics_on: When to report metrics. Must be one of the Keras event hooks (less the ``on_``), e.g. "train_start" or "predict_end". Defaults to "epoch_end". checkpoint_on: When to save checkpoints. Must be one of the Keras event hooks (less the ``on_``), e.g. "train_start" or "predict_end". Defaults to "epoch_end". """ def __init__( self, checkpoint_on: Union[str, List[str]] = "epoch_end", report_metrics_on: Union[str, List[str]] = "epoch_end", metrics: Optional[Union[str, List[str], Dict[str, str]]] = None, ): if isinstance(checkpoint_on, str): checkpoint_on = [checkpoint_on] if isinstance(report_metrics_on, str): report_metrics_on = [report_metrics_on] on = list(set(checkpoint_on + report_metrics_on)) super().__init__(on=on) self._checkpoint_on: List[str] = checkpoint_on self._report_metrics_on: List[str] = report_metrics_on self._metrics = metrics def _handle(self, logs: Dict, when: str): assert when in self._checkpoint_on or when in self._report_metrics_on metrics = self._get_reported_metrics(logs) should_checkpoint = when in self._checkpoint_on if should_checkpoint: checkpoint = TensorflowCheckpoint.from_model(self.model) ray.train.report(metrics, checkpoint=checkpoint) # Clean up temporary checkpoint shutil.rmtree(checkpoint.path, ignore_errors=True) else: ray.train.report(metrics, checkpoint=None) def _get_reported_metrics(self, logs: Dict) -> Dict: assert isinstance(self._metrics, (type(None), str, list, dict)) if self._metrics is None: reported_metrics = logs elif isinstance(self._metrics, str): reported_metrics = {self._metrics: logs[self._metrics]} elif isinstance(self._metrics, list): reported_metrics = {metric: logs[metric] for metric in self._metrics} elif isinstance(self._metrics, dict): reported_metrics = { key: logs[metric] for key, metric in self._metrics.items() } assert isinstance(reported_metrics, dict) return reported_metrics
ReportCheckpointCallback
python
apache__airflow
providers/apache/kafka/tests/integration/apache/kafka/hooks/test_consumer.py
{ "start": 1335, "end": 2277 }
class ____: """ Test consumer hook. """ @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id="kafka_d", conn_type="kafka", extra=json.dumps(config), ) ) def test_consume_messages(self): """test initialization of AdminClientHook""" # Standard Init p = Producer(**{"bootstrap.servers": "broker:29092"}) p.produce(TOPIC, "test_message") assert len(p) == 1 x = p.flush() assert x == 0 c = KafkaConsumerHook([TOPIC], kafka_config_id="kafka_d") consumer = c.get_consumer() msg = consumer.consume() assert msg[0].value() == b"test_message" hook = KafkaAdminClientHook(kafka_config_id="kafka_d") hook.delete_topic(topics=[TOPIC])
TestConsumerHook
python
openai__gym
gym/envs/mujoco/walker2d_v4.py
{ "start": 247, "end": 16500 }
class ____(MujocoEnv, utils.EzPickle): """ ### Description This environment builds on the hopper environment based on the work done by Erez, Tassa, and Todorov in ["Infinite Horizon Model Predictive Control for Nonlinear Periodic Tasks"](http://www.roboticsproceedings.org/rss07/p10.pdf) by adding another set of legs making it possible for the robot to walker forward instead of hop. Like other Mujoco environments, this environment aims to increase the number of independent state and control variables as compared to the classic control environments. The walker is a two-dimensional two-legged figure that consist of four main body parts - a single torso at the top (with the two legs splitting after the torso), two thighs in the middle below the torso, two legs in the bottom below the thighs, and two feet attached to the legs on which the entire body rests. The goal is to make coordinate both sets of feet, legs, and thighs to move in the forward (right) direction by applying torques on the six hinges connecting the six body parts. ### Action Space The action space is a `Box(-1, 1, (6,), float32)`. An action represents the torques applied at the hinge joints. | Num | Action | Control Min | Control Max | Name (in corresponding XML file) | Joint | Unit | |-----|----------------------------------------|-------------|-------------|----------------------------------|-------|--------------| | 0 | Torque applied on the thigh rotor | -1 | 1 | thigh_joint | hinge | torque (N m) | | 1 | Torque applied on the leg rotor | -1 | 1 | leg_joint | hinge | torque (N m) | | 2 | Torque applied on the foot rotor | -1 | 1 | foot_joint | hinge | torque (N m) | | 3 | Torque applied on the left thigh rotor | -1 | 1 | thigh_left_joint | hinge | torque (N m) | | 4 | Torque applied on the left leg rotor | -1 | 1 | leg_left_joint | hinge | torque (N m) | | 5 | Torque applied on the left foot rotor | -1 | 1 | foot_left_joint | hinge | torque (N m) | ### Observation Space Observations consist of positional values of different body parts of the walker, followed by the velocities of those individual parts (their derivatives) with all the positions ordered before all the velocities. By default, observations do not include the x-coordinate of the top. It may be included by passing `exclude_current_positions_from_observation=False` during construction. In that case, the observation space will have 18 dimensions where the first dimension represent the x-coordinates of the top of the walker. Regardless of whether `exclude_current_positions_from_observation` was set to true or false, the x-coordinate of the top will be returned in `info` with key `"x_position"`. By default, observation is a `ndarray` with shape `(17,)` where the elements correspond to the following: | Num | Observation | Min | Max | Name (in corresponding XML file) | Joint | Unit | | --- | ------------------------------------------------ | ---- | --- | -------------------------------- | ----- | ------------------------ | | 0 | z-coordinate of the top (height of hopper) | -Inf | Inf | rootz (torso) | slide | position (m) | | 1 | angle of the top | -Inf | Inf | rooty (torso) | hinge | angle (rad) | | 2 | angle of the thigh joint | -Inf | Inf | thigh_joint | hinge | angle (rad) | | 3 | angle of the leg joint | -Inf | Inf | leg_joint | hinge | angle (rad) | | 4 | angle of the foot joint | -Inf | Inf | foot_joint | hinge | angle (rad) | | 5 | angle of the left thigh joint | -Inf | Inf | thigh_left_joint | hinge | angle (rad) | | 6 | angle of the left leg joint | -Inf | Inf | leg_left_joint | hinge | angle (rad) | | 7 | angle of the left foot joint | -Inf | Inf | foot_left_joint | hinge | angle (rad) | | 8 | velocity of the x-coordinate of the top | -Inf | Inf | rootx | slide | velocity (m/s) | | 9 | velocity of the z-coordinate (height) of the top | -Inf | Inf | rootz | slide | velocity (m/s) | | 10 | angular velocity of the angle of the top | -Inf | Inf | rooty | hinge | angular velocity (rad/s) | | 11 | angular velocity of the thigh hinge | -Inf | Inf | thigh_joint | hinge | angular velocity (rad/s) | | 12 | angular velocity of the leg hinge | -Inf | Inf | leg_joint | hinge | angular velocity (rad/s) | | 13 | angular velocity of the foot hinge | -Inf | Inf | foot_joint | hinge | angular velocity (rad/s) | | 14 | angular velocity of the thigh hinge | -Inf | Inf | thigh_left_joint | hinge | angular velocity (rad/s) | | 15 | angular velocity of the leg hinge | -Inf | Inf | leg_left_joint | hinge | angular velocity (rad/s) | | 16 | angular velocity of the foot hinge | -Inf | Inf | foot_left_joint | hinge | angular velocity (rad/s) | ### Rewards The reward consists of three parts: - *healthy_reward*: Every timestep that the walker is alive, it receives a fixed reward of value `healthy_reward`, - *forward_reward*: A reward of walking forward which is measured as *`forward_reward_weight` * (x-coordinate before action - x-coordinate after action)/dt*. *dt* is the time between actions and is dependeent on the frame_skip parameter (default is 4), where the frametime is 0.002 - making the default *dt = 4 * 0.002 = 0.008*. This reward would be positive if the walker walks forward (right) desired. - *ctrl_cost*: A cost for penalising the walker if it takes actions that are too large. It is measured as *`ctrl_cost_weight` * sum(action<sup>2</sup>)* where *`ctrl_cost_weight`* is a parameter set for the control and has a default value of 0.001 The total reward returned is ***reward*** *=* *healthy_reward bonus + forward_reward - ctrl_cost* and `info` will also contain the individual reward terms ### Starting State All observations start in state (0.0, 1.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) with a uniform noise in the range of [-`reset_noise_scale`, `reset_noise_scale`] added to the values for stochasticity. ### Episode End The walker is said to be unhealthy if any of the following happens: 1. Any of the state space values is no longer finite 2. The height of the walker is ***not*** in the closed interval specified by `healthy_z_range` 3. The absolute value of the angle (`observation[1]` if `exclude_current_positions_from_observation=False`, else `observation[2]`) is ***not*** in the closed interval specified by `healthy_angle_range` If `terminate_when_unhealthy=True` is passed during construction (which is the default), the episode ends when any of the following happens: 1. Truncation: The episode duration reaches a 1000 timesteps 2. Termination: The walker is unhealthy If `terminate_when_unhealthy=False` is passed, the episode is ended only when 1000 timesteps are exceeded. ### Arguments No additional arguments are currently supported in v2 and lower. ``` env = gym.make('Walker2d-v4') ``` v3 and beyond take gym.make kwargs such as xml_file, ctrl_cost_weight, reset_noise_scale etc. ``` env = gym.make('Walker2d-v4', ctrl_cost_weight=0.1, ....) ``` | Parameter | Type | Default | Description | | -------------------------------------------- | --------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `xml_file` | **str** | `"walker2d.xml"` | Path to a MuJoCo model | | `forward_reward_weight` | **float** | `1.0` | Weight for _forward_reward_ term (see section on reward) | | `ctrl_cost_weight` | **float** | `1e-3` | Weight for _ctr_cost_ term (see section on reward) | | `healthy_reward` | **float** | `1.0` | Constant reward given if the ant is "healthy" after timestep | | `terminate_when_unhealthy` | **bool** | `True` | If true, issue a done signal if the z-coordinate of the walker is no longer healthy | | `healthy_z_range` | **tuple** | `(0.8, 2)` | The z-coordinate of the top of the walker must be in this range to be considered healthy | | `healthy_angle_range` | **tuple** | `(-1, 1)` | The angle must be in this range to be considered healthy | | `reset_noise_scale` | **float** | `5e-3` | Scale of random perturbations of initial position and velocity (see section on Starting State) | | `exclude_current_positions_from_observation` | **bool** | `True` | Whether or not to omit the x-coordinate from observations. Excluding the position can serve as an inductive bias to induce position-agnostic behavior in policies | ### Version History * v4: all mujoco environments now use the mujoco bindings in mujoco>=2.1.3 * v3: support for gym.make kwargs such as xml_file, ctrl_cost_weight, reset_noise_scale etc. rgb rendering comes from tracking camera (so agent does not run away from screen) * v2: All continuous control environments now use mujoco_py >= 1.50 * v1: max_time_steps raised to 1000 for robot based tasks. Added reward_threshold to environments. * v0: Initial versions release (1.0.0) """ metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 125, } def __init__( self, forward_reward_weight=1.0, ctrl_cost_weight=1e-3, healthy_reward=1.0, terminate_when_unhealthy=True, healthy_z_range=(0.8, 2.0), healthy_angle_range=(-1.0, 1.0), reset_noise_scale=5e-3, exclude_current_positions_from_observation=True, **kwargs ): utils.EzPickle.__init__( self, forward_reward_weight, ctrl_cost_weight, healthy_reward, terminate_when_unhealthy, healthy_z_range, healthy_angle_range, reset_noise_scale, exclude_current_positions_from_observation, **kwargs ) self._forward_reward_weight = forward_reward_weight self._ctrl_cost_weight = ctrl_cost_weight self._healthy_reward = healthy_reward self._terminate_when_unhealthy = terminate_when_unhealthy self._healthy_z_range = healthy_z_range self._healthy_angle_range = healthy_angle_range self._reset_noise_scale = reset_noise_scale self._exclude_current_positions_from_observation = ( exclude_current_positions_from_observation ) if exclude_current_positions_from_observation: observation_space = Box( low=-np.inf, high=np.inf, shape=(17,), dtype=np.float64 ) else: observation_space = Box( low=-np.inf, high=np.inf, shape=(18,), dtype=np.float64 ) MujocoEnv.__init__( self, "walker2d.xml", 4, observation_space=observation_space, **kwargs ) @property def healthy_reward(self): return ( float(self.is_healthy or self._terminate_when_unhealthy) * self._healthy_reward ) def control_cost(self, action): control_cost = self._ctrl_cost_weight * np.sum(np.square(action)) return control_cost @property def is_healthy(self): z, angle = self.data.qpos[1:3] min_z, max_z = self._healthy_z_range min_angle, max_angle = self._healthy_angle_range healthy_z = min_z < z < max_z healthy_angle = min_angle < angle < max_angle is_healthy = healthy_z and healthy_angle return is_healthy @property def terminated(self): terminated = not self.is_healthy if self._terminate_when_unhealthy else False return terminated def _get_obs(self): position = self.data.qpos.flat.copy() velocity = np.clip(self.data.qvel.flat.copy(), -10, 10) if self._exclude_current_positions_from_observation: position = position[1:] observation = np.concatenate((position, velocity)).ravel() return observation def step(self, action): x_position_before = self.data.qpos[0] self.do_simulation(action, self.frame_skip) x_position_after = self.data.qpos[0] x_velocity = (x_position_after - x_position_before) / self.dt ctrl_cost = self.control_cost(action) forward_reward = self._forward_reward_weight * x_velocity healthy_reward = self.healthy_reward rewards = forward_reward + healthy_reward costs = ctrl_cost observation = self._get_obs() reward = rewards - costs terminated = self.terminated info = { "x_position": x_position_after, "x_velocity": x_velocity, } if self.render_mode == "human": self.render() return observation, reward, terminated, False, info def reset_model(self): noise_low = -self._reset_noise_scale noise_high = self._reset_noise_scale qpos = self.init_qpos + self.np_random.uniform( low=noise_low, high=noise_high, size=self.model.nq ) qvel = self.init_qvel + self.np_random.uniform( low=noise_low, high=noise_high, size=self.model.nv ) self.set_state(qpos, qvel) observation = self._get_obs() return observation def viewer_setup(self): assert self.viewer is not None for key, value in DEFAULT_CAMERA_CONFIG.items(): if isinstance(value, np.ndarray): getattr(self.viewer.cam, key)[:] = value else: setattr(self.viewer.cam, key, value)
Walker2dEnv
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/event_attribute_handler.py
{ "start": 579, "end": 3930 }
class ____(DataConditionHandler[WorkflowEventData]): group = DataConditionHandler.Group.ACTION_FILTER subgroup = DataConditionHandler.Subgroup.EVENT_ATTRIBUTES comparison_json_schema = { "type": "object", "properties": { "attribute": {"type": "string", "enum": list(ATTR_CHOICES.keys())}, "match": { "type": "string", "enum": [*MatchType], }, "value": { "type": "string", "optional": True, }, }, "oneOf": [ { "properties": { "attribute": {"type": "string", "enum": list(ATTR_CHOICES.keys())}, "match": {"enum": [MatchType.IS_SET, MatchType.NOT_SET]}, }, "required": ["attribute", "match"], "not": {"required": ["value"]}, }, { "properties": { "attribute": {"type": "string", "enum": list(ATTR_CHOICES.keys())}, "match": { "not": {"enum": [MatchType.IS_SET, MatchType.NOT_SET]}, }, "value": {"type": "string"}, }, "required": ["attribute", "match", "value"], }, ], "additionalProperties": False, } @staticmethod def get_attribute_values(event: GroupEvent, attribute: str) -> list[str]: path = attribute.split(".") first_attribute = path[0] try: attribute_handler = attribute_registry.get(first_attribute) except NoRegistrationExistsError: attribute_handler = None if not attribute_handler: attribute_values = [] else: try: attribute_values = attribute_handler.handle(path, event) except KeyError as e: attribute_values = [] sentry_sdk.capture_exception(e) attribute_values = [str(value).lower() for value in attribute_values if value is not None] return attribute_values @staticmethod def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool: event = event_data.event if not isinstance(event, GroupEvent): # cannot evaluate event attributes on non-GroupEvent types return False attribute = comparison.get("attribute", "") attribute_values = EventAttributeConditionHandler.get_attribute_values(event, attribute) match = comparison.get("match") desired_value = comparison.get("value") if not (match and desired_value) and not (match in (MatchType.IS_SET, MatchType.NOT_SET)): return False desired_value = str(desired_value).lower() # NOTE: IS_SET condition differs btw tagged_event and event_attribute so not handled by match_values # For event_attribute we need to check that the value of the attribute is not None if match == MatchType.IS_SET: return bool(attribute_values) elif match == MatchType.NOT_SET: return not attribute_values return match_values( group_values=attribute_values, match_value=desired_value, match_type=match )
EventAttributeConditionHandler
python
huggingface__transformers
src/transformers/models/bert_japanese/tokenization_bert_japanese.py
{ "start": 31008, "end": 32900 }
class ____: """Runs WordPiece tokenization.""" def __init__(self, vocab, unk_token, max_input_chars_per_word=100): self.vocab = vocab self.unk_token = unk_token self.max_input_chars_per_word = max_input_chars_per_word def tokenize(self, text): """ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`. Args: text: A single token or whitespace separated tokens. This should have already been passed through *BasicTokenizer*. Returns: A list of wordpiece tokens. """ output_tokens = [] for token in whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.unk_token) continue is_bad = False start = 0 sub_tokens = [] while start < len(chars): end = len(chars) cur_substr = None while start < end: substr = "".join(chars[start:end]) if start > 0: substr = "##" + substr if substr in self.vocab: cur_substr = substr break end -= 1 if cur_substr is None: is_bad = True break sub_tokens.append(cur_substr) start = end if is_bad: output_tokens.append(self.unk_token) else: output_tokens.extend(sub_tokens) return output_tokens
WordpieceTokenizer
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 25047, "end": 25303 }
class ____(WebHookMixin, UpdateView): success_message = _("Webhook updated") def get_success_url(self): return reverse( "projects_webhooks_edit", args=[self.get_project().slug, self.object.pk], )
WebHookUpdate
python
getsentry__sentry
src/sentry/tsdb/base.py
{ "start": 4105, "end": 24381 }
class ____(Service): __read_methods__ = frozenset( [ "get_range", "get_sums", "get_timeseries_sums", "get_distinct_counts_series", "get_distinct_counts_totals", "get_frequency_series", ] ) __write_methods__ = frozenset( [ "incr", "incr_multi", "merge", "delete", "record", "record_multi", "merge_distinct_counts", "delete_distinct_counts", "record_frequency_multi", "merge_frequencies", "delete_frequencies", "flush", ] ) __all__ = ( frozenset( [ "get_earliest_timestamp", "get_optimal_rollup", "get_optimal_rollup_series", "get_rollups", "make_series", "models_with_environment_support", "normalize_to_epoch", "rollup", ] ) | __write_methods__ | __read_methods__ ) models_with_environment_support = frozenset( [ TSDBModel.project, TSDBModel.group, TSDBModel.release, TSDBModel.users_affected_by_group, TSDBModel.users_affected_by_project, ] ) def __init__( self, rollups: Iterable[tuple[int, int]] | None = None, legacy_rollups: dict[int, int] | None = None, **options: object, ): if rollups is None: rollups = settings.SENTRY_TSDB_ROLLUPS self.rollups: dict[int, int] = dict(rollups) # The ``SENTRY_TSDB_LEGACY_ROLLUPS`` setting should be used to store # previous rollup configuration values after they are modified in # ``SENTRY_TSDB_ROLLUPS``. The values can be removed after the new # rollup period is full of new data. if legacy_rollups is None: legacy_rollups = getattr(settings, "SENTRY_TSDB_LEGACY_ROLLUPS", {}) self.__legacy_rollups = legacy_rollups def validate_arguments( self, models: Sequence[TSDBModel], environment_ids: Iterable[int | None] ) -> None: if any(e is not None for e in environment_ids): unsupported_models = set(models) - self.models_with_environment_support if unsupported_models: raise ValueError("not all models support environment parameters") def get_rollups(self) -> dict[int, int]: return self.rollups def normalize_to_epoch(self, timestamp: datetime, seconds: int) -> int: """ Given a ``timestamp`` (datetime object) normalize to an epoch timestamp. i.e. if the rollup is minutes, the resulting timestamp would have the seconds and microseconds rounded down. """ epoch = int(timestamp.timestamp()) return epoch - (epoch % seconds) def normalize_ts_to_epoch(self, epoch: float, seconds: int) -> float: """ Given a ``epoch`` normalize to an epoch rollup. """ return epoch - (epoch % seconds) def normalize_to_rollup(self, timestamp: datetime | float, seconds: int) -> int: """ Given a ``timestamp`` (datetime object) normalize to an epoch rollup. """ if isinstance(timestamp, datetime): epoch = int(timestamp.timestamp()) else: epoch = int(timestamp) return int(epoch / seconds) def normalize_ts_to_rollup(self, epoch: float, seconds: int) -> int: """ Given a ``epoch`` normalize to an epoch rollup. """ return int(epoch / seconds) def get_optimal_rollup(self, start_timestamp: datetime, end_timestamp: datetime) -> int: """ Identify the lowest granularity rollup available within the given time range. """ num_seconds = int(end_timestamp.timestamp()) - int(start_timestamp.timestamp()) # This loop attempts to find the smallest possible rollup that will # contain both the start and end timestamps. ``self.rollups`` is # ordered from the highest resolution (smallest interval) to lowest # resolution (largest interval.) # XXX: There is a bug here, since this function assumes that the end # timestamp is always equal to or greater than the current time. If the # time range is shifted far enough into the past (e.g. a 30 second # window, retrieved several days after it's occurrence), this can # return a rollup that has already been evicted due to TTL, even if a # lower resolution representation of the range exists. for rollup, samples in self.rollups.items(): if rollup * samples >= num_seconds: return rollup # If nothing actually matches the requested range, just return the # lowest resolution interval. return list(self.rollups)[-1] def get_optimal_rollup_series( self, start: datetime, end: datetime | None = None, rollup: int | None = None ) -> tuple[int, list[int]]: if end is None: end = timezone.now() if rollup is None: rollup = self.get_optimal_rollup(start, end) # This attempts to create a range with a duration as close as possible # to the requested interval using the requested (or inferred) rollup # resolution. This result always includes the ``end`` timestamp, but # may not include the ``start`` timestamp. series = [] timestamp = end while timestamp >= start: series.append(self.normalize_to_epoch(timestamp, rollup)) timestamp = timestamp - timedelta(seconds=rollup) return rollup, series[::-1] def get_active_series( self, start: datetime | None = None, end: datetime | None = None, timestamp: datetime | None = None, ) -> dict[int, list[datetime]]: rollups: dict[int, list[datetime]] = {} for rollup, samples in self.rollups.items(): _, series = self.get_optimal_rollup_series( ( start if start is not None else to_datetime(self.get_earliest_timestamp(rollup, timestamp=timestamp)) ), end, rollup=rollup, ) rollups[rollup] = [to_datetime(item) for item in series] return rollups def make_series( self, default, start: datetime, end: datetime | None = None, rollup: int | None = None ) -> list[tuple[int, int]]: f = default if callable(default) else lambda timestamp: default return [ (timestamp, f(timestamp)) for timestamp in self.get_optimal_rollup_series(start, end, rollup)[1] ] def calculate_expiry(self, rollup: int, samples: int, timestamp: datetime) -> int: """ Calculate the expiration time for a rollup. :param rollup: rollup interval (in seconds) :param samples: number of samples to maintain :param timestamp: datetime used to calculate the rollup epoch """ epoch = self.normalize_to_epoch(timestamp, rollup) return epoch + (rollup * samples) def get_earliest_timestamp(self, rollup: int, timestamp: datetime | None = None) -> int: """ Calculate the earliest available timestamp for a rollup. """ if timestamp is None: timestamp = timezone.now() samples = self.__legacy_rollups.get(rollup) if samples is None: samples = self.rollups[rollup] seconds = rollup * (samples - 1) lifespan = timedelta(seconds=seconds) return self.normalize_to_epoch(timestamp - lifespan, rollup) def incr( self, model: TSDBModel, key: TSDBKey, timestamp: datetime | None = None, count: int = 1, environment_id: int | None = None, ) -> None: """ Increment project ID=1: >>> incr(TimeSeriesModel.project, 1) """ raise NotImplementedError def incr_multi( self, items: Sequence[tuple[TSDBModel, TSDBKey] | tuple[TSDBModel, TSDBKey, IncrMultiOptions]], timestamp: datetime | None = None, count: int = 1, environment_id: int | None = None, ) -> None: """ Increment project ID=1 and group ID=5: >>> incr_multi([(TimeSeriesModel.project, 1), (TimeSeriesModel.group, 5)]) Increment individual timestamps: >>> incr_multi([(TimeSeriesModel.project, 1, {"timestamp": ...}), ... (TimeSeriesModel.group, 5, {"timestamp": ...})]) """ for item in items: if len(item) == 2: model, key = item _timestamp: datetime | None = timestamp _count: int = count elif len(item) == 3: model, key, options = item _timestamp = options.get("timestamp", timestamp) or timestamp _count = options.get("count", count) or count else: raise AssertionError("unreachable") self.incr( model, key, timestamp=_timestamp, count=_count, environment_id=environment_id, ) def merge( self, model: TSDBModel, destination: int, sources: list[int], timestamp: datetime | None = None, environment_ids: Iterable[int] | None = None, ) -> None: """ Transfer all counters from the source keys to the destination key. """ raise NotImplementedError def delete( self, models: list[TSDBModel], keys: list[int], start: datetime | None = None, end: datetime | None = None, timestamp: datetime | None = None, environment_ids: Iterable[int | None] | None = None, ) -> None: """ Delete all counters. """ raise NotImplementedError def get_range( self, model: TSDBModel, keys: Sequence[TSDBKey], start: datetime, end: datetime, rollup: int | None = None, environment_ids: Sequence[int] | None = None, conditions=None, use_cache: bool = False, jitter_value: int | None = None, tenant_ids: dict[str, str | int] | None = None, referrer_suffix: str | None = None, group_on_time: bool = True, aggregation_override: str | None = None, project_ids: Sequence[int] | None = None, ) -> dict[TSDBKey, list[tuple[int, int]]]: """ To get a range of data for group ID=[1, 2, 3]: Returns a mapping of key => [(timestamp, count), ...]. >>> now = timezone.now() >>> get_range([TSDBModel.group], [1, 2, 3], >>> start=now - timedelta(days=1), >>> end=now) """ raise NotImplementedError def get_timeseries_sums( self, model: TSDBModel, keys: Sequence[TSDBKey], start: datetime, end: datetime, rollup: int | None = None, environment_id: int | None = None, use_cache: bool = False, jitter_value: int | None = None, tenant_ids: dict[str, str | int] | None = None, referrer_suffix: str | None = None, conditions: list[SnubaCondition] | None = None, group_on_time: bool = True, project_ids: Sequence[int] | None = None, ) -> dict[TSDBKey, int]: range_set = self.get_range( model, keys, start, end, rollup, environment_ids=[environment_id] if environment_id is not None else None, use_cache=use_cache, jitter_value=jitter_value, tenant_ids=tenant_ids, referrer_suffix=referrer_suffix, conditions=conditions, project_ids=project_ids, ) sum_set = {key: sum(p for _, p in points) for (key, points) in range_set.items()} return sum_set def get_sums_data( self, model: TSDBModel, keys: Sequence[TSDBKey], start: datetime, end: datetime, rollup: int | None = None, environment_ids: Sequence[int] | None = None, conditions=None, use_cache: bool = False, jitter_value: int | None = None, tenant_ids: dict[str, str | int] | None = None, referrer_suffix: str | None = None, group_on_time: bool = True, project_ids: Sequence[int] | None = None, ) -> Mapping[TSDBKey, int]: raise NotImplementedError def get_sums( self, model: TSDBModel, keys: Sequence[TSDBKey], start: datetime, end: datetime, rollup: int | None = None, environment_id: int | None = None, use_cache: bool = False, jitter_value: int | None = None, tenant_ids: dict[str, str | int] | None = None, referrer_suffix: str | None = None, conditions: list[SnubaCondition] | None = None, group_on_time: bool = False, project_ids: Sequence[int] | None = None, ) -> Mapping[TSDBKey, int]: result: Mapping[TSDBKey, int] = self.get_sums_data( model, keys, start, end, rollup, [environment_id] if environment_id is not None else None, group_on_time=group_on_time, conditions=conditions, use_cache=use_cache, jitter_value=jitter_value, tenant_ids=tenant_ids, referrer_suffix=referrer_suffix, project_ids=project_ids, ) return result def _add_jitter_to_series( self, series: list[int], start: datetime, rollup: int, jitter_value: int | None ) -> list[int]: if jitter_value and series: jitter = jitter_value % rollup if (start - to_datetime(series[0])).total_seconds() < jitter: jitter -= rollup return [value + jitter for value in series] return series def rollup( self, values: Mapping[TSDBKey, Sequence[tuple[float, int]]], rollup: int ) -> dict[TSDBKey, list[list[float]]]: """ Given a set of values (as returned from ``get_range``), roll them up using the ``rollup`` time (in seconds). """ result: dict[TSDBKey, list[list[float]]] = {} for key, points in values.items(): result[key] = [] last_new_ts = None for ts, count in points: new_ts = self.normalize_ts_to_epoch(ts, rollup) if new_ts == last_new_ts: result[key][-1][1] += count else: result[key].append([new_ts, count]) last_new_ts = new_ts return result def record( self, model: TSDBModel, key: int, values: Iterable[str], timestamp: datetime | None = None, environment_id: int | None = None, ) -> None: """ Record occurrence of items in a single distinct counter. """ raise NotImplementedError def record_multi( self, items: Iterable[tuple[TSDBModel, int, Iterable[str]]], timestamp: datetime | None = None, environment_id: int | None = None, ) -> None: """ Record occurrence of items in multiple distinct counters. """ for model, key, values in items: self.record(model, key, values, timestamp, environment_id=environment_id) def get_distinct_counts_series( self, model: TSDBModel, keys: Sequence[int], start: datetime, end: datetime | None = None, rollup: int | None = None, environment_id: int | None = None, tenant_ids: dict[str, str | int] | None = None, project_ids: Sequence[int] | None = None, ) -> dict[int, list[tuple[int, Any]]]: """ Fetch counts of distinct items for each rollup interval within the range. """ raise NotImplementedError def get_distinct_counts_totals( self, model: TSDBModel, keys: Sequence[TSDBKey], start: datetime, end: datetime | None = None, rollup: int | None = None, environment_id: int | None = None, use_cache: bool = False, jitter_value: int | None = None, tenant_ids: dict[str, int | str] | None = None, referrer_suffix: str | None = None, conditions: list[SnubaCondition] | None = None, group_on_time: bool = False, project_ids: Sequence[int] | None = None, ) -> Mapping[TSDBKey, int]: """ Count distinct items during a time range with optional conditions """ raise NotImplementedError def merge_distinct_counts( self, model: TSDBModel, destination: int, sources: list[int], timestamp: datetime | None = None, environment_ids: Iterable[int] | None = None, ) -> None: """ Transfer all distinct counters from the source keys to the destination key. """ raise NotImplementedError def delete_distinct_counts( self, models: list[TSDBModel], keys: list[int], start: datetime | None = None, end: datetime | None = None, timestamp: datetime | None = None, environment_ids: Iterable[int] | None = None, ) -> None: """ Delete all distinct counters. """ raise NotImplementedError def record_frequency_multi( self, requests: Sequence[tuple[TSDBModel, Mapping[str, Mapping[str, int | float]]]], timestamp: datetime | None = None, environment_id: int | None = None, ) -> None: """ Record items in a frequency table. Metrics to increment should be passed as sequence pairs, using this structure: ``(model, {key: {item: score, ...}, ...})`` """ raise NotImplementedError def get_frequency_series( self, model: TSDBModel, items: Mapping[TSDBKey, Sequence[TSDBItem]], start: datetime, end: datetime | None = None, rollup: int | None = None, environment_id: int | None = None, tenant_ids: dict[str, str | int] | None = None, project_ids: Sequence[int] | None = None, ) -> dict[TSDBKey, list[tuple[float, dict[TSDBItem, float]]]]: """ Retrieve the frequency of known items in a table over time. The items requested should be passed as a mapping, where the key is the metric key, and the value is a sequence of members to retrieve scores for. Results are returned as a mapping, where the key is the key requested and the value is a list of ``(timestamp, {item: score, ...})`` pairs over the series. """ raise NotImplementedError def merge_frequencies( self, model: TSDBModel, destination: str, sources: Sequence[TSDBKey], timestamp: datetime | None = None, environment_ids: Iterable[int] | None = None, ) -> None: """ Transfer all frequency tables from the source keys to the destination key. """ raise NotImplementedError def delete_frequencies( self, models: list[TSDBModel], keys: Iterable[str], start: datetime | None = None, end: datetime | None = None, timestamp: datetime | None = None, environment_ids: Iterable[int] | None = None, ) -> None: """ Delete all frequency tables. """ raise NotImplementedError def flush(self) -> None: """ Delete all data. """ raise NotImplementedError
BaseTSDB
python
django__django
tests/model_options/test_default_related_name.py
{ "start": 144, "end": 1598 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.author = Author.objects.create(first_name="Dave", last_name="Loper") cls.editor = Editor.objects.create( name="Test Editions", bestselling_author=cls.author ) cls.book = Book.objects.create(title="Test Book", editor=cls.editor) cls.book.authors.add(cls.author) def test_no_default_related_name(self): self.assertEqual(list(self.author.editor_set.all()), [self.editor]) def test_default_related_name(self): self.assertEqual(list(self.author.books.all()), [self.book]) def test_default_related_name_in_queryset_lookup(self): self.assertEqual(Author.objects.get(books=self.book), self.author) def test_model_name_not_available_in_queryset_lookup(self): msg = "Cannot resolve keyword 'book' into field." with self.assertRaisesMessage(FieldError, msg): Author.objects.get(book=self.book) def test_related_name_overrides_default_related_name(self): self.assertEqual(list(self.editor.edited_books.all()), [self.book]) def test_inheritance(self): # model_options is the name of the application for this test. self.assertEqual(list(self.book.model_options_bookstores.all()), []) def test_inheritance_with_overridden_default_related_name(self): self.assertEqual(list(self.book.editor_stores.all()), [])
DefaultRelatedNameTests
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_run_cancellation.py
{ "start": 7612, "end": 9844 }
class ____(ReadonlyGraphQLContextTestMatrix): def test_termination_permission_failure(self, graphql_context: WorkspaceRequestContext): run_id = create_run_for_test(graphql_context.instance).run_id result = execute_dagster_graphql( graphql_context, RUN_CANCELLATION_QUERY, variables={"runId": run_id} ) assert not result.errors assert result.data # just test existence assert result.data["terminatePipelineExecution"]["__typename"] == "TerminateRunFailure" assert "do not have permission" in result.data["terminatePipelineExecution"]["message"] def test_cancel_runs_permission_failure(self, graphql_context: WorkspaceRequestContext): run_id = create_run_for_test(graphql_context.instance).run_id result = execute_dagster_graphql( graphql_context, RUNS_CANCELLATION_QUERY, variables={"runIds": [run_id]} ) assert not result.errors assert result.data # just test existence assert result.data["terminateRuns"]["__typename"] == "TerminateRunsResult" assert len(result.data["terminateRuns"]["terminateRunResults"]) == 1 assert ( result.data["terminateRuns"]["terminateRunResults"][0]["__typename"] == "TerminateRunFailure" ) assert ( "do not have permission" in result.data["terminateRuns"]["terminateRunResults"][0]["message"] ) def test_cancel_runs_permission_failure_non_existent_run( self, graphql_context: WorkspaceRequestContext ): run_id = make_new_run_id() result = execute_dagster_graphql( graphql_context, RUNS_CANCELLATION_QUERY, variables={"runIds": [run_id]} ) assert ( result.data["terminateRuns"]["terminateRunResults"][0]["__typename"] == "UnauthorizedError" ) def test_no_bulk_terminate_permission(self, graphql_context: WorkspaceRequestContext): result = execute_dagster_graphql(graphql_context, BULK_TERMINATION_PERMISSIONS_QUERY) assert not result.errors assert result.data assert result.data["canBulkTerminate"] is False
TestTerminationReadonly
python
python__mypy
mypy/test/testparse.py
{ "start": 479, "end": 2498 }
class ____(DataSuite): required_out_section = True base_path = "." files = find_test_files(pattern="parse*.test", exclude=["parse-errors.test"]) if sys.version_info < (3, 12): files.remove("parse-python312.test") if sys.version_info < (3, 13): files.remove("parse-python313.test") if sys.version_info < (3, 14): files.remove("parse-python314.test") def run_case(self, testcase: DataDrivenTestCase) -> None: test_parser(testcase) def test_parser(testcase: DataDrivenTestCase) -> None: """Perform a single parser test case. The argument contains the description of the test case. """ options = Options() options.hide_error_codes = True if testcase.file.endswith("python310.test"): options.python_version = (3, 10) elif testcase.file.endswith("python312.test"): options.python_version = (3, 12) elif testcase.file.endswith("python313.test"): options.python_version = (3, 13) elif testcase.file.endswith("python314.test"): options.python_version = (3, 14) else: options.python_version = defaults.PYTHON3_VERSION source = "\n".join(testcase.input) # Apply mypy: comments to options. comments = get_mypy_comments(source) changes, _ = parse_mypy_comments(comments, options) options = options.apply_changes(changes) try: n = parse( bytes(source, "ascii"), fnam="main", module="__main__", errors=Errors(options), options=options, raise_on_error=True, ) a = n.str_with_options(options).split("\n") except CompileError as e: a = e.messages assert_string_arrays_equal( testcase.output, a, f"Invalid parser output ({testcase.file}, line {testcase.line})" ) # The file name shown in test case output. This is displayed in error # messages, and must match the file name in the test case descriptions. INPUT_FILE_NAME = "file"
ParserSuite
python
neetcode-gh__leetcode
python/0838-push-dominoes.py
{ "start": 0, "end": 736 }
class ____: def pushDominoes(self, dominoes: str) -> str: dom = list(dominoes) q = collections.deque() for i, d in enumerate(dom): if d != '.': q.append((i, d)) while q: i, d = q.popleft() if d == 'L' and i > 0 and dom[i - 1] == '.': q.append((i - 1, 'L')) dom[i - 1] = 'L' elif d == 'R': if i + 1 < len(dom) and dom[i + 1] == '.': if i + 2 < len(dom) and dom[i + 2] == 'L': q.popleft() else: q.append((i + 1, 'R')) dom[i + 1] = 'R' return ''.join(dom)
Solution
python
Netflix__metaflow
metaflow/plugins/datatools/s3/s3.py
{ "start": 2774, "end": 2868 }
class ____(MetaflowException): headline = "Not a string-like object"
MetaflowS3InvalidObject
python
paramiko__paramiko
paramiko/channel.py
{ "start": 48665, "end": 48989 }
class ____(ChannelFile): """ A file-like wrapper around `.Channel` stderr. See `Channel.makefile_stderr` for details. """ def _read(self, size): return self.channel.recv_stderr(size) def _write(self, data): self.channel.sendall_stderr(data) return len(data)
ChannelStderrFile
python
getsentry__sentry
tests/sentry/incidents/endpoints/test_organization_ondemand_rule_stats_endpoint.py
{ "start": 191, "end": 3302 }
class ____(BaseAlertRuleSerializerTest, APITestCase): endpoint = "sentry-api-0-organization-ondemand-rules-stats" def setUp(self) -> None: super().setUp() self.features = {"organizations:on-demand-metrics-extraction": True} # no metric alert self.alert1 = self.create_alert_rule() # on-demand metric alert due to query but using transactions dataset self.alert2 = self.create_alert_rule( aggregate="count()", query="transaction.duration:>=10", dataset=Dataset.Transactions, ) # on-demand metric alert due to query self.alert3 = self.create_alert_rule( aggregate="count()", query="transaction.duration:>=1000", dataset=Dataset.PerformanceMetrics, ) # on-demand metric alert due to the apdex aggregation - it's the only metric which is on demand also without a query. self.alert4 = self.create_alert_rule( aggregate="apdex(300)", query="", dataset=Dataset.PerformanceMetrics, ) self.login_as(user=self.user) def do_success_request(self, extra_features: dict[str, bool] | None = None) -> dict[str, int]: _features = {**self.features, **(extra_features or {})} with self.feature(_features): response = self.get_success_response(self.organization.slug, project_id=self.project.id) return response.data def test_missing_project_id(self) -> None: response = self.get_error_response( self.organization.slug, ) assert response.data["detail"] == "Missing required parameter 'project_id'" def test_endpoint_return_correct_counts(self) -> None: response_data = self.do_success_request() assert response_data == { "totalOnDemandAlertSpecs": 2, # alert3 and alert4 "maxAllowed": 50, } # When the prefill feature is enabled, the logic includes metrics from the transactions dataset response_data = self.do_success_request({"organizations:on-demand-metrics-prefill": True}) assert response_data == { "totalOnDemandAlertSpecs": 3, # alert2, alert3 and alert4 "maxAllowed": 50, } def test_on_demand_alerts_exceeding_limit(self) -> None: for _ in range(50): self.create_alert_rule( aggregate="count()", query="transaction.duration:>=1400", dataset=Dataset.PerformanceMetrics, ) response_data = self.do_success_request() assert response_data == { # 2 from the set_up + 50 from the loop = 52 "totalOnDemandAlertSpecs": 52, "maxAllowed": 50, } response_data = self.do_success_request({"organizations:on-demand-metrics-prefill": True}) assert response_data == { # 3 from the set_up + 50 from the loop = 53 "totalOnDemandAlertSpecs": 53, "maxAllowed": 50, }
OrganizationOnDemandRuleStatsEndpointTest
python
ray-project__ray
python/ray/data/_internal/arrow_block.py
{ "start": 16513, "end": 20572 }
class ____(BlockColumnAccessor): def __init__(self, col: Union["pyarrow.Array", "pyarrow.ChunkedArray"]): super().__init__(col) def count(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: import pyarrow.compute as pac res = pac.count(self._column, mode="only_valid" if ignore_nulls else "all") return res.as_py() if as_py else res def sum(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: import pyarrow.compute as pac res = pac.sum(self._column, skip_nulls=ignore_nulls) return res.as_py() if as_py else res def min(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: import pyarrow.compute as pac res = pac.min(self._column, skip_nulls=ignore_nulls) return res.as_py() if as_py else res def max(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: import pyarrow.compute as pac res = pac.max(self._column, skip_nulls=ignore_nulls) return res.as_py() if as_py else res def mean(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: import pyarrow.compute as pac res = pac.mean(self._column, skip_nulls=ignore_nulls) return res.as_py() if as_py else res def sum_of_squared_diffs_from_mean( self, ignore_nulls: bool, mean: Optional[U] = None, as_py: bool = True ) -> Optional[U]: import pyarrow.compute as pac # Calculate mean if not provided if mean is None: mean = self.mean(ignore_nulls=ignore_nulls) if mean is None: return None res = pac.sum( pac.power(pac.subtract(self._column, mean), 2), skip_nulls=ignore_nulls ) return res.as_py() if as_py else res def quantile( self, *, q: float, ignore_nulls: bool, as_py: bool = True ) -> Optional[U]: import pyarrow.compute as pac array = pac.quantile(self._column, q=q, skip_nulls=ignore_nulls) # NOTE: That quantile method still returns an array res = array[0] return res.as_py() if as_py else res def unique(self) -> BlockColumn: import pyarrow.compute as pac return pac.unique(self._column) def value_counts(self) -> Optional[Dict[str, List]]: import pyarrow.compute as pac value_counts: pyarrow.StructArray = pac.value_counts(self._column) if len(value_counts) == 0: return None return { "values": value_counts.field("values").to_pylist(), "counts": value_counts.field("counts").to_pylist(), } def hash(self) -> BlockColumn: import polars as pl df = pl.DataFrame({"col": self._column}) hashes = df.hash_rows().cast(pl.Int64, wrap_numerical=True) return hashes.to_arrow() def flatten(self) -> BlockColumn: import pyarrow.compute as pac return pac.list_flatten(self._column) def dropna(self) -> BlockColumn: import pyarrow.compute as pac return pac.drop_null(self._column) def is_composed_of_lists(self, types: Optional[Tuple] = None) -> bool: if not types: types = (pyarrow.lib.ListType, pyarrow.lib.LargeListType) return isinstance(self._column.type, types) def to_pylist(self) -> List[Any]: return self._column.to_pylist() def to_numpy(self, zero_copy_only: bool = False) -> np.ndarray: if get_pyarrow_version() < _MIN_PYARROW_VERSION_TO_NUMPY_ZERO_COPY_ONLY: if isinstance( self._column, pyarrow.ChunkedArray ): # NOTE: ChunkedArray in Pyarrow < 13.0.0 does not support ``zero_copy_only`` return self._column.to_numpy() else: return self._column.to_numpy(zero_copy_only=zero_copy_only) return self._column.to_numpy(zero_copy_only=zero_copy_only) def _as_arrow_compatible(self) -> Union[List[Any], "pyarrow.Array"]: return self._column
ArrowBlockColumnAccessor
python
pytorch__pytorch
torch/utils/weak.py
{ "start": 453, "end": 2691 }
class ____: # This context manager registers itself in the current iterators of the # weak container, such as to delay all removals until the context manager # exits. # This technique should be relatively thread-safe (since sets are). def __init__(self, weakcontainer) -> None: # Don't create cycles self.weakcontainer = ref(weakcontainer) def __enter__(self): w = self.weakcontainer() if w is not None: w._iterating.add(self) return self def __exit__(self, e, t, b): w = self.weakcontainer() if w is not None: s = w._iterating s.remove(self) if not s: w._commit_removals() # This file defines a variant of WeakKeyDictionary that overrides the hashing # behavior of the key to use object identity, rather than the builtin # __eq__/__hash__ functions. This is useful for Tensor weak keys, as their # __eq__ implementation return a Tensor (elementwise equality), which means # you can't use them directly with the WeakKeyDictionary in standard library. # # Our implementation strategy is to create a wrapper weak key object, which we # use as a key in a stock Python dictionary. This is similar to how weakref # implements WeakKeyDictionary, but instead of using weakref.ref as the # wrapper, we use a custom wrapper that has different __eq__ and __hash__ # behavior. Note that we subsequently store this weak key directly in an # ORDINARY dictionary, since the newly constructed WeakIdKey's only use would # be a dictionary so it would have no strong references. Ensuring that # only live WeakIdKeys are in the map is handled by putting finalizers on the # original key object. # It is simpler to implement this with composition, but if we want to # directly reuse the callback mechanism on weakref, we need the weakref # and the key to be exactly the same object. Reusing the callback mechanism # minimizes the divergence between our implementation and Lib/weakref.py # # NB: Prefer using this when working with weakrefs of Tensors; e.g., do # WeakIdRef(tensor) rather than weakref.ref(tensor); it handles a number of # easy to get wrong cases transparently for you.
_IterationGuard
python
openai__openai-python
src/openai/types/responses/response_input_item_param.py
{ "start": 4001, "end": 4784 }
class ____(TypedDict, total=False): call_id: Required[str] """The unique ID of the function tool call generated by the model.""" output: Required[Union[str, ResponseFunctionCallOutputItemListParam]] """Text, image, or file output of the function tool call.""" type: Required[Literal["function_call_output"]] """The type of the function tool call output. Always `function_call_output`.""" id: Optional[str] """The unique ID of the function tool call output. Populated when this item is returned via API. """ status: Optional[Literal["in_progress", "completed", "incomplete"]] """The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. """
FunctionCallOutput
python
pandas-dev__pandas
pandas/tests/io/formats/test_to_latex.py
{ "start": 24863, "end": 26198 }
class ____: def test_to_latex_position(self): the_position = "h" df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) result = df.to_latex(position=the_position) expected = _dedent( r""" \begin{table}[h] \begin{tabular}{lrl} \toprule & a & b \\ \midrule 0 & 1 & b1 \\ 1 & 2 & b2 \\ \bottomrule \end{tabular} \end{table} """ ) assert result == expected def test_to_latex_longtable_position(self): the_position = "t" df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) result = df.to_latex(longtable=True, position=the_position) expected = _dedent( r""" \begin{longtable}[t]{lrl} \toprule & a & b \\ \midrule \endfirsthead \toprule & a & b \\ \midrule \endhead \midrule \multicolumn{3}{r}{Continued on next page} \\ \midrule \endfoot \bottomrule \endlastfoot 0 & 1 & b1 \\ 1 & 2 & b2 \\ \end{longtable} """ ) assert result == expected
TestToLatexPosition
python
airbytehq__airbyte
airbyte-integrations/connectors/source-mixpanel/source_mixpanel/source.py
{ "start": 2078, "end": 6971 }
class ____(YamlDeclarativeSource): def __init__(self, catalog: Optional[ConfiguredAirbyteCatalog], config: Optional[Mapping[str, Any]], state: TState, **kwargs): super().__init__(catalog=catalog, config=config, state=state, **{"path_to_yaml": "manifest.yaml"}) @staticmethod def validate_date(name: str, date_str: str, default: pendulum.date) -> pendulum.date: if not date_str: return default try: return pendulum.parse(date_str).date() except pendulum.parsing.exceptions.ParserError as e: raise_config_error(f"Could not parse {name}: {date_str}. Please enter a valid {name}.", e) @adapt_validate_if_testing def _validate_and_transform(self, config: MutableMapping[str, Any]): ( project_timezone, start_date, end_date, attribution_window, select_properties_by_default, region, date_window_size, project_id, page_size, export_lookback_window, ) = ( config.get("project_timezone", "US/Pacific"), config.get("start_date"), config.get("end_date"), config.get("attribution_window", 5), config.get("select_properties_by_default", True), config.get("region", "US"), config.get("date_window_size", 30), config.get("credentials", dict()).get("project_id"), config.get("page_size", 1000), config.get("export_lookback_window", 0), ) try: project_timezone = pendulum.timezone(project_timezone) except pendulum.tz.zoneinfo.exceptions.InvalidTimezone as e: raise_config_error(f"Could not parse time zone: {project_timezone}, please enter a valid timezone.", e) if region not in ("US", "EU"): raise_config_error("Region must be either EU or US.") if select_properties_by_default not in (True, False, "", None): raise_config_error("Please provide a valid True/False value for the `Select properties by default` parameter.") if not isinstance(attribution_window, int) or attribution_window < 0: raise_config_error("Please provide a valid integer for the `Attribution window` parameter.") if not isinstance(date_window_size, int) or date_window_size < 1: raise_config_error("Please provide a valid integer for the `Date slicing window` parameter.") if not isinstance(export_lookback_window, int) or export_lookback_window < 0: raise_config_error("Please provide a valid integer for the `Export Lookback Window` parameter.") auth = self.get_authenticator(config) if isinstance(auth, TokenAuthenticatorBase64) and project_id: config.get("credentials").pop("project_id") if isinstance(auth, BasicHttpAuthenticator) and not isinstance(project_id, int): raise_config_error("Required parameter 'project_id' missing or malformed. Please provide a valid project ID.") today = pendulum.today(tz=project_timezone).date() config["project_timezone"] = project_timezone config["start_date"] = self.validate_date("start date", start_date, today.subtract(days=365)) config["end_date"] = self.validate_date("end date", end_date, today.subtract(days=1)) config["attribution_window"] = attribution_window config["select_properties_by_default"] = select_properties_by_default config["region"] = region config["date_window_size"] = date_window_size config["project_id"] = project_id config["page_size"] = page_size config["export_lookback_window"] = export_lookback_window return config @staticmethod def get_authenticator(config: Mapping[str, Any]) -> TokenAuthenticator: credentials = config["credentials"] username = credentials.get("username") secret = credentials.get("secret") if username and secret: return BasicHttpAuthenticator(username=username, password=secret) return TokenAuthenticatorBase64(token=credentials["api_secret"]) def streams(self, config: Mapping[str, Any]) -> List[Stream]: credentials = config.get("credentials") if not credentials.get("option_title"): if credentials.get("api_secret"): credentials["option_title"] = "Project Secret" else: credentials["option_title"] = "Service Account" streams = super().streams(config=config) config_transformed = copy.deepcopy(config) config_transformed = self._validate_and_transform(config_transformed) auth = self.get_authenticator(config) streams.append(Export(authenticator=auth, **config_transformed)) return streams
SourceMixpanel
python
google__pytype
pytype/tests/test_utils.py
{ "start": 2632, "end": 3228 }
class ____(pretty_printer_base.PrettyPrinterBase): """Fake pretty printer for constructing an error log.""" def __init__(self): options = config.Options.create() super().__init__(make_context(options)) def print_generic_type(self, t) -> str: return "" def print_type_of_instance(self, t, instance=None) -> str: return "" def print_type(self, t, literal=False) -> str: return "" def print_function_def(self, fn) -> str: return "" def print_var_type(self, *args) -> str: return "" def show_variable(self, var) -> str: return ""
FakePrettyPrinter
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/comprehend.py
{ "start": 2531, "end": 4063 }
class ____(AwsBaseWaiterTrigger): """ Trigger when a Comprehend document classifier is complete. :param document_classifier_arn: The arn of the Comprehend document classifier. :param waiter_delay: The amount of time in seconds to wait between attempts. (default: 120) :param waiter_max_attempts: The maximum number of attempts to be made. (default: 75) :param aws_conn_id: The Airflow connection used for AWS credentials. """ def __init__( self, *, document_classifier_arn: str, waiter_delay: int = 120, waiter_max_attempts: int = 75, aws_conn_id: str | None = "aws_default", ) -> None: super().__init__( serialized_fields={"document_classifier_arn": document_classifier_arn}, waiter_name="create_document_classifier_complete", waiter_args={"DocumentClassifierArn": document_classifier_arn}, failure_message="Comprehend create document classifier failed.", status_message="Status of Comprehend create document classifier is", status_queries=["DocumentClassifierProperties.Status"], return_key="document_classifier_arn", return_value=document_classifier_arn, waiter_delay=waiter_delay, waiter_max_attempts=waiter_max_attempts, aws_conn_id=aws_conn_id, ) def hook(self) -> AwsGenericHook: return ComprehendHook(aws_conn_id=self.aws_conn_id)
ComprehendCreateDocumentClassifierCompletedTrigger
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 223441, "end": 224589 }
class ____(JSONRoundTripTest): __requires__ = ("postgresql_jsonb",) data_type = JSONB @testing.requires.postgresql_utf8_server_encoding def test_unicode_round_trip(self, connection): super().test_unicode_round_trip(connection) @testing.only_on("postgresql >= 12") def test_cast_jsonpath(self, connection): self._fixture_data(connection) def go(path, res): q = select(func.count("*")).where( func.jsonb_path_exists( self.data_table.c.data, cast(path, JSONB.JSONPathType) ) ) eq_(connection.scalar(q), res) go("$.k1.k2", 0) go("$.k1.r6v1", 1) @testing.combinations( ["k1", "r6v1", "subr", 1], array(["k1", "r6v1", "subr", 1]), argnames="path", ) def test_delete_path(self, connection, path): self._fixture_data(connection) q = select(self.data_table.c.data.delete_path(path)).where( self.data_table.c.name == "r6" ) res = connection.scalar(q) eq_(res, {"k1": {"r6v1": {"subr": [1, 3]}}})
JSONBRoundTripTest
python
PyCQA__pylint
tests/functional/g/generic_alias/generic_alias_side_effects.py
{ "start": 2057, "end": 2147 }
class ____(Generic[IN, OUT], ConsumingMixin[IN], ProducingMixin[OUT]): pass
StreamingMixin
python
numpy__numpy
numpy/_core/tests/test_umath_complex.py
{ "start": 21737, "end": 23611 }
class ____: @pytest.mark.parametrize("stride", [-4, -3, -2, -1, 1, 2, 3, 4]) @pytest.mark.parametrize("astype", [np.complex64, np.complex128]) @pytest.mark.parametrize("func", ['abs', 'square', 'conjugate']) def test_array(self, stride, astype, func): dtype = [('template_id', '<i8'), ('bank_chisq', '<f4'), ('bank_chisq_dof', '<i8'), ('chisq', '<f4'), ('chisq_dof', '<i8'), ('cont_chisq', '<f4'), ('psd_var_val', '<f4'), ('sg_chisq', '<f4'), ('mycomplex', astype), ('time_index', '<i8')] vec = np.array([ (0, 0., 0, -31.666483, 200, 0., 0., 1. , 3.0 + 4.0j , 613090), # noqa: E203,E501 (1, 0., 0, 260.91525 , 42, 0., 0., 1. , 5.0 + 12.0j , 787315), # noqa: E203,E501 (1, 0., 0, 52.15155 , 42, 0., 0., 1. , 8.0 + 15.0j , 806641), # noqa: E203,E501 (1, 0., 0, 52.430195, 42, 0., 0., 1. , 7.0 + 24.0j , 1363540), # noqa: E203,E501 (2, 0., 0, 304.43646 , 58, 0., 0., 1. , 20.0 + 21.0j, 787323), # noqa: E203,E501 (3, 0., 0, 299.42108 , 52, 0., 0., 1. , 12.0 + 35.0j, 787332), # noqa: E203,E501 (4, 0., 0, 39.4836 , 28, 0., 0., 9.182192, 9.0 + 40.0j , 787304), # noqa: E203,E501 (4, 0., 0, 76.83787 , 28, 0., 0., 1. , 28.0 + 45.0j, 1321869), # noqa: E203,E501 (5, 0., 0, 143.26366 , 24, 0., 0., 10.996129, 11.0 + 60.0j, 787299)], # noqa: E203,E501 dtype=dtype) myfunc = getattr(np, func) a = vec['mycomplex'] g = myfunc(a[::stride]) b = vec['mycomplex'].copy() h = myfunc(b[::stride]) assert_array_max_ulp(h.real, g.real, 1) assert_array_max_ulp(h.imag, g.imag, 1)
TestComplexAbsoluteMixedDTypes
python
django__django
tests/model_regress/test_state.py
{ "start": 119, "end": 290 }
class ____(SimpleTestCase): def test_fields_cache_descriptor(self): self.assertIsInstance(ModelState.fields_cache, ModelStateFieldsCacheDescriptor)
ModelStateTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/property6.py
{ "start": 127, "end": 765 }
class ____(Generic[_T]): @property def prop_1(self) -> float | None: return 2 @prop_1.setter def prop_1(self, value: int) -> None: pass @property def prop_2(self) -> int | None: return 2 # This should generate an error because a float # is not assignable to an Optional[int]. @prop_2.setter def prop_2(self, value: float) -> None: pass @property def prop_3(self) -> list[_T]: return [] # This should generate an error because _T is # not assignable to List[_T]. @prop_3.setter def prop_3(self, value: _T) -> None: pass
ClassA
python
wandb__wandb
wandb/sdk/lib/auth/auth.py
{ "start": 1149, "end": 1868 }
class ____(Auth): """An API key for connecting to a W&B server.""" @override def __init__(self, *, host: str | HostUrl, api_key: str) -> None: """Initialize AuthApiKey. Args: host: The W&B server URL. api_key: The API key. Raises: ValueError: If the host is invalid. AuthenticationError: If the API key is in an invalid format. """ super().__init__(host=host) if problems := validation.check_api_key(api_key): raise AuthenticationError(problems) self._api_key = api_key @property def api_key(self) -> str: """The API key.""" return self._api_key @final
AuthApiKey
python
doocs__leetcode
solution/3400-3499/3437.Permutations III/Solution.py
{ "start": 0, "end": 541 }
class ____: def permute(self, n: int) -> List[List[int]]: def dfs(i: int) -> None: if i >= n: ans.append(t[:]) return for j in range(1, n + 1): if not vis[j] and (i == 0 or t[-1] % 2 != j % 2): t.append(j) vis[j] = True dfs(i + 1) vis[j] = False t.pop() ans = [] t = [] vis = [False] * (n + 1) dfs(0) return ans
Solution
python
getsentry__sentry-python
sentry_sdk/integrations/logging.py
{ "start": 4755, "end": 6229 }
class ____(logging.Handler): COMMON_RECORD_ATTRS = frozenset( ( "args", "created", "exc_info", "exc_text", "filename", "funcName", "levelname", "levelno", "linenno", "lineno", "message", "module", "msecs", "msg", "name", "pathname", "process", "processName", "relativeCreated", "stack", "tags", "taskName", "thread", "threadName", "stack_info", ) ) def _can_record(self, record): # type: (LogRecord) -> bool """Prevents ignored loggers from recording""" for logger in _IGNORED_LOGGERS: if fnmatch(record.name.strip(), logger): return False return True def _logging_to_event_level(self, record): # type: (LogRecord) -> str return LOGGING_TO_EVENT_LEVEL.get( record.levelno, record.levelname.lower() if record.levelname else "" ) def _extra_from_record(self, record): # type: (LogRecord) -> MutableMapping[str, object] return { k: v for k, v in vars(record).items() if k not in self.COMMON_RECORD_ATTRS and (not isinstance(k, str) or not k.startswith("_")) }
_BaseHandler
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py
{ "start": 25455, "end": 26801 }
class ____(Node): __slots__ = ('loc', 'name', 'type', 'default_value', 'directives') _fields = ('name', 'type', 'default_value',) def __init__(self, name, type, default_value=None, loc=None, directives=None): self.loc = loc self.name = name self.type = type self.default_value = default_value self.directives = directives def __eq__(self, other): return ( self is other or ( isinstance(other, InputValueDefinition) and # self.loc == other.loc and self.name == other.name and self.type == other.type and self.default_value == other.default_value and self.directives == other.directives ) ) def __repr__(self): return ('InputValueDefinition(' 'name={self.name!r}' ', type={self.type!r}' ', default_value={self.default_value!r}' ', directives={self.directives!r}' ')').format(self=self) def __copy__(self): return type(self)( self.name, self.type, self.default_value, self.loc, self.directives, ) def __hash__(self): return id(self)
InputValueDefinition
python
pytorch__pytorch
test/quantization/pt2e/test_quantize_pt2e_qat.py
{ "start": 35156, "end": 36622 }
class ____(Quantizer): """ Dummy quantizer that annotates conv bn in such a way that the weights are quantized per channel to int32. """ def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: conv_node, bn_node, getitem_node = _get_conv_bn_getitem_nodes(model) act_qspec = QuantizationSpec( dtype=torch.uint8, quant_min=0, quant_max=255, qscheme=torch.per_tensor_affine, observer_or_fake_quant_ctr=default_fake_quant, ) weight_qspec = QuantizationSpec( dtype=torch.int32, quant_min=0, quant_max=2**31 - 1, qscheme=torch.per_channel_affine, observer_or_fake_quant_ctr=FusedMovingAvgObsFakeQuantize.with_args( observer=MovingAveragePerChannelMinMaxObserver, ), ) conv_node.meta["quantization_annotation"] = QuantizationAnnotation( input_qspec_map={ conv_node.args[0]: act_qspec, conv_node.args[1]: weight_qspec, }, _annotated=True, ) # See NOTE [training ir has no getitem for bn node]. bn_node.meta["quantization_annotation"] = QuantizationAnnotation( output_qspec=act_qspec, _annotated=True, ) return model def validate(self, model: torch.fx.GraphModule): pass
ConvBnInt32WeightQuantizer
python
astropy__astropy
astropy/table/column.py
{ "start": 53895, "end": 67164 }
class ____(Column, _MaskedColumnGetitemShim, ma.MaskedArray): """Define a masked data column for use in a Table object. Parameters ---------- data : list, ndarray, or None Column data values name : str Column name and key for reference within Table mask : list, ndarray or None Boolean mask for which True indicates missing or invalid data fill_value : float, int, str, or None Value used when filling masked column elements dtype : `~numpy.dtype`-like Data type for column shape : tuple or () Dimensions of a single row element in the column data length : int or 0 Number of row elements in column data description : str or None Full description of column unit : str or None Physical unit format : str, None, or callable Format string for outputting column values. This can be an "old-style" (``format % value``) or "new-style" (`str.format`) format specification string or a function or any callable object that accepts a single value and returns a string. meta : dict-like or None Meta-data associated with the column Examples -------- A MaskedColumn is similar to a Column except that it includes ``mask`` and ``fill_value`` attributes. It can be created in two different ways: - Provide a ``data`` value but not ``shape`` or ``length`` (which are inferred from the data). Examples:: col = MaskedColumn(data=[1, 2], name='name') col = MaskedColumn(data=[1, 2], name='name', mask=[True, False]) col = MaskedColumn(data=[1, 2], name='name', dtype=float, fill_value=99) The ``mask`` argument will be cast as a boolean array and specifies which elements are considered to be missing or invalid. The ``dtype`` argument can be any value which is an acceptable fixed-size data-type initializer for the numpy.dtype() method. See `<https://numpy.org/doc/stable/reference/arrays.dtypes.html>`_. Examples include: - Python non-string type (float, int, bool) - Numpy non-string type (e.g. np.float32, np.int64, np.bool\\_) - Numpy.dtype array-protocol type strings (e.g. 'i4', 'f8', 'S15') If no ``dtype`` value is provide then the type is inferred using ``np.array(data)``. When ``data`` is provided then the ``shape`` and ``length`` arguments are ignored. - Provide ``length`` and optionally ``shape``, but not ``data`` Examples:: col = MaskedColumn(name='name', length=5) col = MaskedColumn(name='name', dtype=int, length=10, shape=(3,4)) The default ``dtype`` is ``np.float64``. The ``shape`` argument is the array shape of a single cell in the column. To access the ``Column`` data as a raw `numpy.ma.MaskedArray` object, you can use one of the ``data`` or ``value`` attributes (which are equivalent):: col.data col.value """ info = MaskedColumnInfo() def __new__( cls, data=None, name=None, mask=None, fill_value=None, dtype=None, shape=(), length=0, description=None, unit=None, format=None, meta=None, copy=COPY_IF_NEEDED, copy_indices=True, ): if mask is None: # If mask is None then we need to determine the mask (if any) from the data. # The naive method is looking for a mask attribute on data, but this can fail, # see #8816. Instead use ``MaskedArray`` to do the work. mask = ma.MaskedArray(data).mask if mask is np.ma.nomask: # Handle odd-ball issue with np.ma.nomask (numpy #13758), and see below. mask = False elif copy: mask = mask.copy() elif mask is np.ma.nomask: # Force the creation of a full mask array as nomask is tricky to # use and will fail in an unexpected manner when setting a value # to the mask. mask = False else: mask = deepcopy(mask) # Create self using MaskedArray as a wrapper class, following the example of # class MSubArray in # https://github.com/numpy/numpy/blob/maintenance/1.8.x/numpy/ma/tests/test_subclassing.py # This pattern makes it so that __array_finalize__ is called as expected (e.g. #1471 and # https://github.com/astropy/astropy/commit/ff6039e8) # First just pass through all args and kwargs to BaseColumn, then wrap that object # with MaskedArray. self_data = BaseColumn( data, dtype=dtype, shape=shape, length=length, name=name, unit=unit, format=format, description=description, meta=meta, copy=copy, copy_indices=copy_indices, ) self = ma.MaskedArray.__new__(cls, data=self_data, mask=mask) # The above process preserves info relevant for Column, but this does # not include serialize_method (and possibly other future attributes) # relevant for MaskedColumn, so we set info explicitly. if "info" in getattr(data, "__dict__", {}): self.info = data.info # Note: do not set fill_value in the MaskedArray constructor because this does not # go through the fill_value workarounds. if fill_value is None: data_fill_value = getattr(data, "fill_value", None) if ( data_fill_value is not None and data_fill_value != np.ma.default_fill_value(data.dtype) ): fill_value = np.array(data_fill_value, self.dtype)[()] self.fill_value = fill_value self.parent_table = None # needs to be done here since self doesn't come from BaseColumn.__new__ for index in self.indices: index.replace_col(self_data, self) return self @property def fill_value(self): return self.get_fill_value() # defer to native ma.MaskedArray method @fill_value.setter def fill_value(self, val): """Set fill value both in the masked column view and in the parent table if it exists. Setting one or the other alone doesn't work. """ # another ma bug workaround: If the value of fill_value for a string array is # requested but not yet set then it gets created as 'N/A'. From this point onward # any new fill_values are truncated to 3 characters. Note that this does not # occur if the masked array is a structured array (as in the previous block that # deals with the parent table). # # >>> x = ma.array(['xxxx']) # >>> x.fill_value # fill_value now gets represented as an 'S3' array # 'N/A' # >>> x.fill_value='yyyy' # >>> x.fill_value # 'yyy' # # To handle this we are forced to reset a private variable first: self._fill_value = None self.set_fill_value(val) # defer to native ma.MaskedArray method @property def data(self): """The plain MaskedArray data held by this column.""" out = self.view(np.ma.MaskedArray) # By default, a MaskedArray view will set the _baseclass to be the # same as that of our own class, i.e., BaseColumn. Since we want # to return a plain MaskedArray, we reset the baseclass accordingly. out._baseclass = np.ndarray return out def filled(self, fill_value=None): """Return a copy of self, with masked values filled with a given value. Parameters ---------- fill_value : scalar; optional The value to use for invalid entries (`None` by default). If `None`, the ``fill_value`` attribute of the array is used instead. Returns ------- filled_column : Column A copy of ``self`` with masked entries replaced by `fill_value` (be it the function argument or the attribute of ``self``). """ if fill_value is None: fill_value = self.fill_value data = super().filled(fill_value) # Use parent table definition of Column if available column_cls = ( self.parent_table.Column if (self.parent_table is not None) else Column ) out = column_cls( name=self.name, data=data, unit=self.unit, format=self.format, description=self.description, meta=deepcopy(self.meta), ) return out def insert(self, obj, values, mask=None, axis=0): """ Insert values along the given axis before the given indices and return a new `~astropy.table.MaskedColumn` object. Parameters ---------- obj : int, slice or sequence of int Object that defines the index or indices before which ``values`` is inserted. values : array-like Value(s) to insert. If the type of ``values`` is different from that of the column, ``values`` is converted to the matching type. ``values`` should be shaped so that it can be broadcast appropriately. mask : bool or array-like Mask value(s) to insert. If not supplied, and values does not have a mask either, then False is used. axis : int, optional Axis along which to insert ``values``. If ``axis`` is None then the column array is flattened before insertion. Default is 0, which will insert a row. Returns ------- out : `~astropy.table.MaskedColumn` A copy of column with ``values`` and ``mask`` inserted. Note that the insertion does not occur in-place: a new masked column is returned. """ self_ma = self.data # self viewed as MaskedArray if self.dtype.kind == "O": # Even if values is array-like (e.g. [1,2,3]), insert as a single # object. Numpy.insert instead inserts each element in an array-like # input individually. new_data = np.insert(self_ma.data, obj, None, axis=axis) new_data[obj] = values else: self_ma = _expand_string_array_for_values(self_ma, values) new_data = np.insert(self_ma.data, obj, values, axis=axis) if mask is None: mask = getattr(values, "mask", np.ma.nomask) if mask is np.ma.nomask: if self.dtype.kind == "O": mask = False else: mask = np.zeros(np.shape(values), dtype=bool) new_mask = np.insert(self_ma.mask, obj, mask, axis=axis) new_ma = np.ma.array(new_data, mask=new_mask, copy=False) out = new_ma.view(self.__class__) out.parent_table = None out.indices = [] out._copy_attrs(self) out.fill_value = self.fill_value return out def convert_unit_to(self, new_unit, equivalencies=[]): # This is a workaround to fix gh-9521 super().convert_unit_to(new_unit, equivalencies) self._basedict["_unit"] = new_unit self._optinfo["_unit"] = new_unit def _copy_attrs_slice(self, out): # Fixes issue #3023: when calling getitem with a MaskedArray subclass # the original object attributes are not copied. if out.__class__ is self.__class__: # TODO: this part is essentially the same as what is done in # __array_finalize__ and could probably be called directly in our # override of __getitem__ in _columns_mixins.pyx). Refactor? if "info" in self.__dict__: out.info = self.info out.parent_table = None # we need this because __getitem__ does a shallow copy of indices if out.indices is self.indices: out.indices = [] out._copy_attrs(self) return out def __setitem__(self, index, value): # Issue warning for string assignment that truncates ``value`` if self.dtype.char == "S": value = self._encode_str(value) if issubclass(self.dtype.type, np.character): # Account for a bug in np.ma.MaskedArray setitem. # https://github.com/numpy/numpy/issues/8624 value = np.ma.asanyarray(value, dtype=self.dtype.type) # Check for string truncation after filling masked items with # empty (zero-length) string. Note that filled() does not make # a copy if there are no masked items. self._check_string_truncate(value.filled("")) # update indices self.info.adjust_indices(index, value, len(self)) ma.MaskedArray.__setitem__(self, index, value) # We do this to make the methods show up in the API docs name = BaseColumn.name copy = BaseColumn.copy more = BaseColumn.more pprint = BaseColumn.pprint pformat = BaseColumn.pformat
MaskedColumn
python
dask__dask
dask/dataframe/dask_expr/_reductions.py
{ "start": 45119, "end": 45354 }
class ____(IsMonotonicIncreasing): reduction_chunk = methods.monotonic_decreasing_chunk reduction_combine = methods.monotonic_decreasing_combine reduction_aggregate = methods.monotonic_decreasing_aggregate
IsMonotonicDecreasing
python
getsentry__sentry
src/sentry/models/groupopenperiodactivity.py
{ "start": 575, "end": 1267 }
class ____(DefaultFieldsModel): """ The GroupOpenPeriodActivity tracks state changes within open periods. """ __relocation_scope__ = RelocationScope.Excluded group_open_period = FlexibleForeignKey("sentry.GroupOpenPeriod") # OpenPeriodActivityType type: models.Field = models.IntegerField() # The priority associated with this activity row. # Can be None if the row corresponds to open period closure. value = models.IntegerField(null=True) notification_uuid = models.UUIDField("notification_uuid", default=generate_random_uuid) class Meta: app_label = "sentry" db_table = "sentry_groupopenperiodactivity"
GroupOpenPeriodActivity
python
wandb__wandb
wandb/vendor/pygments/lexers/python.py
{ "start": 23250, "end": 24706 }
class ____(RegexLexer): """ For Python 3.0 tracebacks, with support for chained exceptions. .. versionadded:: 1.0 """ name = 'Python 3.0 Traceback' aliases = ['py3tb'] filenames = ['*.py3tb'] mimetypes = ['text/x-python3-traceback'] tokens = { 'root': [ (r'\n', Text), (r'^Traceback \(most recent call last\):\n', Generic.Traceback, 'intb'), (r'^During handling of the above exception, another ' r'exception occurred:\n\n', Generic.Traceback), (r'^The above exception was the direct cause of the ' r'following exception:\n\n', Generic.Traceback), (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'), ], 'intb': [ (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)', bygroups(Text, Name.Builtin, Text, Number, Text, Name, Text)), (r'^( File )("[^"]+")(, line )(\d+)(\n)', bygroups(Text, Name.Builtin, Text, Number, Text)), (r'^( )(.+)(\n)', bygroups(Text, using(Python3Lexer), Text)), (r'^([ \t]*)(\.\.\.)(\n)', bygroups(Text, Comment, Text)), # for doctests... (r'^([^:]+)(: )(.+)(\n)', bygroups(Generic.Error, Text, Name, Text), '#pop'), (r'^([a-zA-Z_]\w*)(:?\n)', bygroups(Generic.Error, Text), '#pop') ], }
Python3TracebackLexer
python
django__django
tests/delete/models.py
{ "start": 811, "end": 1022 }
class ____(models.Model): p = models.ForeignKey(RelatedDbOptionGrandParent, models.DB_CASCADE, null=True) class Meta: required_db_features = {"supports_on_delete_db_cascade"}
RelatedDbOptionParent
python
walkccc__LeetCode
solutions/214. Shortest Palindrome/214.py
{ "start": 0, "end": 181 }
class ____: def shortestPalindrome(self, s: str) -> str: t = s[::-1] for i in range(len(t)): if s.startswith(t[i:]): return t[:i] + s return t + s
Solution
python
kamyu104__LeetCode-Solutions
Python/count-subarrays-with-more-ones-than-zeros.py
{ "start": 50, "end": 679 }
class ____(object): def subarraysWithMoreZerosThanOnes(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 lookup = collections.defaultdict(int) lookup[0] = 1 result = total = same = more = 0 for x in nums: total += 1 if x == 1 else -1 new_same = lookup[total] new_more = (same+more+1)%MOD if x == 1 else (more-new_same)%MOD lookup[total] += 1 result = (result+new_more)%MOD same, more = new_same, new_more return result # Time: O(n) # Space: O(n)
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 619527, "end": 619836 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("Sponsor", graphql_name="node")
SponsorEdge
python
Farama-Foundation__Gymnasium
gymnasium/envs/box2d/bipedal_walker.py
{ "start": 2521, "end": 27828 }
class ____(gym.Env, EzPickle): """ ## Description This is a simple 4-joint walker robot environment. There are two versions: - Normal, with slightly uneven terrain. - Hardcore, with ladders, stumps, pitfalls. To solve the normal version, you need to get 300 points in 1600 time steps. To solve the hardcore version, you need 300 points in 2000 time steps. A heuristic is provided for testing. It's also useful to get demonstrations to learn from. To run the heuristic: ``` python gymnasium/envs/box2d/bipedal_walker.py ``` ## Action Space Actions are motor speed values in the [-1, 1] range for each of the 4 joints at both hips and knees. ## Observation Space State consists of hull angle speed, angular velocity, horizontal speed, vertical speed, position of joints and joints angular speed, legs contact with ground, and 10 lidar rangefinder measurements. There are no coordinates in the state vector. ## Rewards Reward is given for moving forward, totaling 300+ points up to the far end. If the robot falls, it gets -100. Applying motor torque costs a small amount of points. A more optimal agent will get a better score. ## Starting State The walker starts standing at the left end of the terrain with the hull horizontal, and both legs in the same position with a slight knee angle. ## Episode Termination The episode will terminate if the hull gets in contact with the ground or if the walker exceeds the right end of the terrain length. ## Arguments To use the _hardcore_ environment, you need to specify the `hardcore=True`: ```python >>> import gymnasium as gym >>> env = gym.make("BipedalWalker-v3", hardcore=True, render_mode="rgb_array") >>> env <TimeLimit<OrderEnforcing<PassiveEnvChecker<BipedalWalker<BipedalWalker-v3>>>>> ``` ## Version History - v3: Returns the closest lidar trace instead of furthest; faster video recording - v2: Count energy spent - v1: Legs now report contact with ground; motors have higher torque and speed; ground has higher friction; lidar rendered less nervously. - v0: Initial version <!-- ## References --> ## Credits Created by Oleg Klimov """ metadata = { "render_modes": ["human", "rgb_array"], "render_fps": FPS, } def __init__(self, render_mode: str | None = None, hardcore: bool = False): EzPickle.__init__(self, render_mode, hardcore) self.isopen = True self.world = Box2D.b2World() self.terrain: list[Box2D.b2Body] = [] self.hull: Box2D.b2Body | None = None self.prev_shaping = None self.hardcore = hardcore self.fd_polygon = fixtureDef( shape=polygonShape(vertices=[(0, 0), (1, 0), (1, -1), (0, -1)]), friction=FRICTION, ) self.fd_edge = fixtureDef( shape=edgeShape(vertices=[(0, 0), (1, 1)]), friction=FRICTION, categoryBits=0x0001, ) # we use 5.0 to represent the joints moving at maximum # 5 x the rated speed due to impulses from ground contact etc. low = np.array( [ -math.pi, -5.0, -5.0, -5.0, -math.pi, -5.0, -math.pi, -5.0, -0.0, -math.pi, -5.0, -math.pi, -5.0, -0.0, ] + [-1.0] * 10 ).astype(np.float32) high = np.array( [ math.pi, 5.0, 5.0, 5.0, math.pi, 5.0, math.pi, 5.0, 5.0, math.pi, 5.0, math.pi, 5.0, 5.0, ] + [1.0] * 10 ).astype(np.float32) self.action_space = spaces.Box( np.array([-1, -1, -1, -1]).astype(np.float32), np.array([1, 1, 1, 1]).astype(np.float32), ) self.observation_space = spaces.Box(low, high) # state = [ # self.hull.angle, # Normal angles up to 0.5 here, but sure more is possible. # 2.0 * self.hull.angularVelocity / FPS, # 0.3 * vel.x * (VIEWPORT_W / SCALE) / FPS, # Normalized to get -1..1 range # 0.3 * vel.y * (VIEWPORT_H / SCALE) / FPS, # self.joints[ # 0 # ].angle, # This will give 1.1 on high up, but it's still OK (and there should be spikes on hitting the ground, that's normal too) # self.joints[0].speed / SPEED_HIP, # self.joints[1].angle + 1.0, # self.joints[1].speed / SPEED_KNEE, # 1.0 if self.legs[1].ground_contact else 0.0, # self.joints[2].angle, # self.joints[2].speed / SPEED_HIP, # self.joints[3].angle + 1.0, # self.joints[3].speed / SPEED_KNEE, # 1.0 if self.legs[3].ground_contact else 0.0, # ] # state += [l.fraction for l in self.lidar] self.render_mode = render_mode self.screen: pygame.Surface | None = None self.clock = None def _destroy(self): if not self.terrain: return self.world.contactListener = None for t in self.terrain: self.world.DestroyBody(t) self.terrain = [] self.world.DestroyBody(self.hull) self.hull = None for leg in self.legs: self.world.DestroyBody(leg) self.legs = [] self.joints = [] def _generate_terrain(self, hardcore): GRASS, STUMP, STAIRS, PIT, _STATES_ = range(5) state = GRASS velocity = 0.0 y = TERRAIN_HEIGHT counter = TERRAIN_STARTPAD oneshot = False self.terrain = [] self.terrain_x = [] self.terrain_y = [] stair_steps, stair_width, stair_height = 0, 0, 0 original_y = 0 for i in range(TERRAIN_LENGTH): x = i * TERRAIN_STEP self.terrain_x.append(x) if state == GRASS and not oneshot: velocity = 0.8 * velocity + 0.01 * np.sign(TERRAIN_HEIGHT - y) if i > TERRAIN_STARTPAD: velocity += self.np_random.uniform(-1, 1) / SCALE # 1 y += velocity elif state == PIT and oneshot: counter = self.np_random.integers(3, 5) poly = [ (x, y), (x + TERRAIN_STEP, y), (x + TERRAIN_STEP, y - 4 * TERRAIN_STEP), (x, y - 4 * TERRAIN_STEP), ] self.fd_polygon.shape.vertices = poly t = self.world.CreateStaticBody(fixtures=self.fd_polygon) t.color1, t.color2 = (255, 255, 255), (153, 153, 153) self.terrain.append(t) self.fd_polygon.shape.vertices = [ (p[0] + TERRAIN_STEP * counter, p[1]) for p in poly ] t = self.world.CreateStaticBody(fixtures=self.fd_polygon) t.color1, t.color2 = (255, 255, 255), (153, 153, 153) self.terrain.append(t) counter += 2 original_y = y elif state == PIT and not oneshot: y = original_y if counter > 1: y -= 4 * TERRAIN_STEP elif state == STUMP and oneshot: counter = self.np_random.integers(1, 3) poly = [ (x, y), (x + counter * TERRAIN_STEP, y), (x + counter * TERRAIN_STEP, y + counter * TERRAIN_STEP), (x, y + counter * TERRAIN_STEP), ] self.fd_polygon.shape.vertices = poly t = self.world.CreateStaticBody(fixtures=self.fd_polygon) t.color1, t.color2 = (255, 255, 255), (153, 153, 153) self.terrain.append(t) elif state == STAIRS and oneshot: stair_height = +1 if self.np_random.random() > 0.5 else -1 stair_width = self.np_random.integers(4, 5) stair_steps = self.np_random.integers(3, 5) original_y = y for s in range(stair_steps): poly = [ ( x + (s * stair_width) * TERRAIN_STEP, y + (s * stair_height) * TERRAIN_STEP, ), ( x + ((1 + s) * stair_width) * TERRAIN_STEP, y + (s * stair_height) * TERRAIN_STEP, ), ( x + ((1 + s) * stair_width) * TERRAIN_STEP, y + (-1 + s * stair_height) * TERRAIN_STEP, ), ( x + (s * stair_width) * TERRAIN_STEP, y + (-1 + s * stair_height) * TERRAIN_STEP, ), ] self.fd_polygon.shape.vertices = poly t = self.world.CreateStaticBody(fixtures=self.fd_polygon) t.color1, t.color2 = (255, 255, 255), (153, 153, 153) self.terrain.append(t) counter = stair_steps * stair_width elif state == STAIRS and not oneshot: s = stair_steps * stair_width - counter - stair_height n = s / stair_width y = original_y + (n * stair_height) * TERRAIN_STEP oneshot = False self.terrain_y.append(y) counter -= 1 if counter == 0: counter = self.np_random.integers(TERRAIN_GRASS / 2, TERRAIN_GRASS) if state == GRASS and hardcore: state = self.np_random.integers(1, _STATES_) oneshot = True else: state = GRASS oneshot = True self.terrain_poly = [] for i in range(TERRAIN_LENGTH - 1): poly = [ (self.terrain_x[i], self.terrain_y[i]), (self.terrain_x[i + 1], self.terrain_y[i + 1]), ] self.fd_edge.shape.vertices = poly t = self.world.CreateStaticBody(fixtures=self.fd_edge) color = (76, 255 if i % 2 == 0 else 204, 76) t.color1 = color t.color2 = color self.terrain.append(t) color = (102, 153, 76) poly += [(poly[1][0], 0), (poly[0][0], 0)] self.terrain_poly.append((poly, color)) self.terrain.reverse() def _generate_clouds(self): # Sorry for the clouds, couldn't resist self.cloud_poly = [] for i in range(TERRAIN_LENGTH // 20): x = self.np_random.uniform(0, TERRAIN_LENGTH) * TERRAIN_STEP y = VIEWPORT_H / SCALE * 3 / 4 poly = [ ( x + 15 * TERRAIN_STEP * math.sin(3.14 * 2 * a / 5) + self.np_random.uniform(0, 5 * TERRAIN_STEP), y + 5 * TERRAIN_STEP * math.cos(3.14 * 2 * a / 5) + self.np_random.uniform(0, 5 * TERRAIN_STEP), ) for a in range(5) ] x1 = min(p[0] for p in poly) x2 = max(p[0] for p in poly) self.cloud_poly.append((poly, x1, x2)) def reset( self, *, seed: int | None = None, options: dict | None = None, ): super().reset(seed=seed) self._destroy() self.world.contactListener_bug_workaround = ContactDetector(self) self.world.contactListener = self.world.contactListener_bug_workaround self.game_over = False self.prev_shaping = None self.scroll = 0.0 self.lidar_render = 0 self._generate_terrain(self.hardcore) self._generate_clouds() init_x = TERRAIN_STEP * TERRAIN_STARTPAD / 2 init_y = TERRAIN_HEIGHT + 2 * LEG_H self.hull = self.world.CreateDynamicBody( position=(init_x, init_y), fixtures=HULL_FD ) self.hull.color1 = (127, 51, 229) self.hull.color2 = (76, 76, 127) self.hull.ApplyForceToCenter( (self.np_random.uniform(-INITIAL_RANDOM, INITIAL_RANDOM), 0), True ) self.legs: list[Box2D.b2Body] = [] self.joints: list[Box2D.b2RevoluteJoint] = [] for i in [-1, +1]: leg = self.world.CreateDynamicBody( position=(init_x, init_y - LEG_H / 2 - LEG_DOWN), angle=(i * 0.05), fixtures=LEG_FD, ) leg.color1 = (153 - i * 25, 76 - i * 25, 127 - i * 25) leg.color2 = (102 - i * 25, 51 - i * 25, 76 - i * 25) rjd = revoluteJointDef( bodyA=self.hull, bodyB=leg, localAnchorA=(0, LEG_DOWN), localAnchorB=(0, LEG_H / 2), enableMotor=True, enableLimit=True, maxMotorTorque=MOTORS_TORQUE, motorSpeed=i, lowerAngle=-0.8, upperAngle=1.1, ) self.legs.append(leg) self.joints.append(self.world.CreateJoint(rjd)) lower = self.world.CreateDynamicBody( position=(init_x, init_y - LEG_H * 3 / 2 - LEG_DOWN), angle=(i * 0.05), fixtures=LOWER_FD, ) lower.color1 = (153 - i * 25, 76 - i * 25, 127 - i * 25) lower.color2 = (102 - i * 25, 51 - i * 25, 76 - i * 25) rjd = revoluteJointDef( bodyA=leg, bodyB=lower, localAnchorA=(0, -LEG_H / 2), localAnchorB=(0, LEG_H / 2), enableMotor=True, enableLimit=True, maxMotorTorque=MOTORS_TORQUE, motorSpeed=1, lowerAngle=-1.6, upperAngle=-0.1, ) lower.ground_contact = False self.legs.append(lower) self.joints.append(self.world.CreateJoint(rjd)) self.drawlist = self.terrain + self.legs + [self.hull] class LidarCallback(Box2D.b2.rayCastCallback): def ReportFixture(self, fixture, point, normal, fraction): if (fixture.filterData.categoryBits & 1) == 0: return -1 self.p2 = point self.fraction = fraction return fraction self.lidar = [LidarCallback() for _ in range(10)] if self.render_mode == "human": self.render() return self.step(np.array([0, 0, 0, 0]))[0], {} def step(self, action: np.ndarray): assert self.hull is not None # self.hull.ApplyForceToCenter((0, 20), True) -- Uncomment this to receive a bit of stability help control_speed = False # Should be easier as well if control_speed: self.joints[0].motorSpeed = float(SPEED_HIP * np.clip(action[0], -1, 1)) self.joints[1].motorSpeed = float(SPEED_KNEE * np.clip(action[1], -1, 1)) self.joints[2].motorSpeed = float(SPEED_HIP * np.clip(action[2], -1, 1)) self.joints[3].motorSpeed = float(SPEED_KNEE * np.clip(action[3], -1, 1)) else: self.joints[0].motorSpeed = float(SPEED_HIP * np.sign(action[0])) self.joints[0].maxMotorTorque = float( MOTORS_TORQUE * np.clip(np.abs(action[0]), 0, 1) ) self.joints[1].motorSpeed = float(SPEED_KNEE * np.sign(action[1])) self.joints[1].maxMotorTorque = float( MOTORS_TORQUE * np.clip(np.abs(action[1]), 0, 1) ) self.joints[2].motorSpeed = float(SPEED_HIP * np.sign(action[2])) self.joints[2].maxMotorTorque = float( MOTORS_TORQUE * np.clip(np.abs(action[2]), 0, 1) ) self.joints[3].motorSpeed = float(SPEED_KNEE * np.sign(action[3])) self.joints[3].maxMotorTorque = float( MOTORS_TORQUE * np.clip(np.abs(action[3]), 0, 1) ) self.world.Step(1.0 / FPS, 6 * 30, 2 * 30) pos = self.hull.position vel = self.hull.linearVelocity for i in range(10): self.lidar[i].fraction = 1.0 self.lidar[i].p1 = pos self.lidar[i].p2 = ( pos[0] + math.sin(1.5 * i / 10.0) * LIDAR_RANGE, pos[1] - math.cos(1.5 * i / 10.0) * LIDAR_RANGE, ) self.world.RayCast(self.lidar[i], self.lidar[i].p1, self.lidar[i].p2) state = [ self.hull.angle, # Normal angles up to 0.5 here, but sure more is possible. 2.0 * self.hull.angularVelocity / FPS, 0.3 * vel.x * (VIEWPORT_W / SCALE) / FPS, # Normalized to get -1..1 range 0.3 * vel.y * (VIEWPORT_H / SCALE) / FPS, self.joints[0].angle, # This will give 1.1 on high up, but it's still OK (and there should be spikes on hitting the ground, that's normal too) self.joints[0].speed / SPEED_HIP, self.joints[1].angle + 1.0, self.joints[1].speed / SPEED_KNEE, 1.0 if self.legs[1].ground_contact else 0.0, self.joints[2].angle, self.joints[2].speed / SPEED_HIP, self.joints[3].angle + 1.0, self.joints[3].speed / SPEED_KNEE, 1.0 if self.legs[3].ground_contact else 0.0, ] state += [l.fraction for l in self.lidar] assert len(state) == 24 self.scroll = pos.x - VIEWPORT_W / SCALE / 5 shaping = ( 130 * pos[0] / SCALE ) # moving forward is a way to receive reward (normalized to get 300 on completion) shaping -= 5.0 * abs( state[0] ) # keep head straight, other than that and falling, any behavior is unpunished reward = 0 if self.prev_shaping is not None: reward = shaping - self.prev_shaping self.prev_shaping = shaping for a in action: reward -= 0.00035 * MOTORS_TORQUE * np.clip(np.abs(a), 0, 1) # normalized to about -50.0 using heuristic, more optimal agent should spend less terminated = False if self.game_over or pos[0] < 0: reward = -100 terminated = True if pos[0] > (TERRAIN_LENGTH - TERRAIN_GRASS) * TERRAIN_STEP: terminated = True if self.render_mode == "human": self.render() # truncation=False as the time limit is handled by the `TimeLimit` wrapper added during `make` return np.array(state, dtype=np.float32), reward, terminated, False, {} def render(self): if self.render_mode is None: assert self.spec is not None gym.logger.warn( "You are calling render method without specifying any render mode. " "You can specify the render_mode at initialization, " f'e.g. gym.make("{self.spec.id}", render_mode="rgb_array")' ) return try: import pygame from pygame import gfxdraw except ImportError as e: raise DependencyNotInstalled( 'pygame is not installed, run `pip install "gymnasium[box2d]"`' ) from e if self.screen is None and self.render_mode == "human": pygame.init() pygame.display.init() self.screen = pygame.display.set_mode((VIEWPORT_W, VIEWPORT_H)) if self.clock is None: self.clock = pygame.time.Clock() self.surf = pygame.Surface( (VIEWPORT_W + max(0.0, self.scroll) * SCALE, VIEWPORT_H) ) pygame.transform.scale(self.surf, (SCALE, SCALE)) pygame.draw.polygon( self.surf, color=(215, 215, 255), points=[ (self.scroll * SCALE, 0), (self.scroll * SCALE + VIEWPORT_W, 0), (self.scroll * SCALE + VIEWPORT_W, VIEWPORT_H), (self.scroll * SCALE, VIEWPORT_H), ], ) for poly, x1, x2 in self.cloud_poly: if x2 < self.scroll / 2: continue if x1 > self.scroll / 2 + VIEWPORT_W / SCALE: continue pygame.draw.polygon( self.surf, color=(255, 255, 255), points=[ (p[0] * SCALE + self.scroll * SCALE / 2, p[1] * SCALE) for p in poly ], ) gfxdraw.aapolygon( self.surf, [(p[0] * SCALE + self.scroll * SCALE / 2, p[1] * SCALE) for p in poly], (255, 255, 255), ) for poly, color in self.terrain_poly: if poly[1][0] < self.scroll: continue if poly[0][0] > self.scroll + VIEWPORT_W / SCALE: continue scaled_poly = [] for coord in poly: scaled_poly.append([coord[0] * SCALE, coord[1] * SCALE]) pygame.draw.polygon(self.surf, color=color, points=scaled_poly) gfxdraw.aapolygon(self.surf, scaled_poly, color) self.lidar_render = (self.lidar_render + 1) % 100 i = self.lidar_render if i < 2 * len(self.lidar): single_lidar = ( self.lidar[i] if i < len(self.lidar) else self.lidar[len(self.lidar) - i - 1] ) if hasattr(single_lidar, "p1") and hasattr(single_lidar, "p2"): pygame.draw.line( self.surf, color=(255, 0, 0), start_pos=(single_lidar.p1[0] * SCALE, single_lidar.p1[1] * SCALE), end_pos=(single_lidar.p2[0] * SCALE, single_lidar.p2[1] * SCALE), width=1, ) for obj in self.drawlist: for f in obj.fixtures: trans = f.body.transform if type(f.shape) is circleShape: pygame.draw.circle( self.surf, color=obj.color1, center=trans * f.shape.pos * SCALE, radius=f.shape.radius * SCALE, ) pygame.draw.circle( self.surf, color=obj.color2, center=trans * f.shape.pos * SCALE, radius=f.shape.radius * SCALE, ) else: path = [trans * v * SCALE for v in f.shape.vertices] if len(path) > 2: pygame.draw.polygon(self.surf, color=obj.color1, points=path) gfxdraw.aapolygon(self.surf, path, obj.color1) path.append(path[0]) pygame.draw.polygon( self.surf, color=obj.color2, points=path, width=1 ) gfxdraw.aapolygon(self.surf, path, obj.color2) else: pygame.draw.aaline( self.surf, start_pos=path[0], end_pos=path[1], color=obj.color1, ) flagy1 = TERRAIN_HEIGHT * SCALE flagy2 = flagy1 + 50 x = TERRAIN_STEP * 3 * SCALE pygame.draw.aaline( self.surf, color=(0, 0, 0), start_pos=(x, flagy1), end_pos=(x, flagy2) ) f = [ (x, flagy2), (x, flagy2 - 10), (x + 25, flagy2 - 5), ] pygame.draw.polygon(self.surf, color=(230, 51, 0), points=f) pygame.draw.lines( self.surf, color=(0, 0, 0), points=f + [f[0]], width=1, closed=False ) self.surf = pygame.transform.flip(self.surf, False, True) if self.render_mode == "human": assert self.screen is not None self.screen.blit(self.surf, (-self.scroll * SCALE, 0)) pygame.event.pump() self.clock.tick(self.metadata["render_fps"]) pygame.display.flip() elif self.render_mode == "rgb_array": return np.transpose( np.array(pygame.surfarray.pixels3d(self.surf)), axes=(1, 0, 2) )[:, -VIEWPORT_W:] def close(self): if self.screen is not None: import pygame pygame.display.quit() pygame.quit() self.isopen = False
BipedalWalker
python
sphinx-doc__sphinx
sphinx/directives/patches.py
{ "start": 831, "end": 1683 }
class ____(images.Figure): # type: ignore[misc] """The figure directive which applies `:name:` option to the figure node instead of the image node. """ def run(self) -> list[Node]: name = self.options.pop('name', None) result = super().run() if len(result) == 2 or isinstance(result[0], nodes.system_message): return result assert len(result) == 1 figure_node = cast('nodes.figure', result[0]) if name: # set ``name`` to figure_node if given self.options['name'] = name self.add_name(figure_node) # copy lineno from image node if figure_node.line is None and len(figure_node) == 2: caption = cast('nodes.caption', figure_node[1]) figure_node.line = caption.line return [figure_node]
Figure
python
keras-team__keras
keras/src/losses/losses_test.py
{ "start": 69780, "end": 70451 }
class ____(testing.TestCase): def test_config(self): self.run_class_serialization_test(losses.CTC(name="myctc")) def test_correctness(self): logits = (np.arange(24).reshape((2, 4, 3)).astype("float32") - 12) / 100 y_true = np.array(([[1, 2, 1, 0], [1, 2, 0, 2]])) output = losses.CTC()(y_true, logits) self.assertAllClose(output, 2.448645) def test_dtype_arg(self): logits = (np.arange(24).reshape((2, 4, 3)).astype("float32") - 12) / 100 y_true = np.array(([[1, 2, 1, 0], [1, 2, 0, 2]])) output = losses.CTC(dtype="bfloat16")(y_true, logits) self.assertDType(output, "bfloat16")
CTCTest
python
tensorflow__tensorflow
tensorflow/dtensor/python/tests/api_test.py
{ "start": 1641, "end": 11192 }
class ____(test_util.DTensorBaseTest): def setUp(self): super(APITest, self).setUp() global_ids = test_util.create_device_ids_array((2, 2)) local_device_ids = np.ravel(global_ids).tolist() mesh_dict = { 'CPU': Mesh( [_MESH_DIM_X, _MESH_DIM_Y], global_ids, local_device_ids, test_util.create_device_list((2, 2), 'CPU'), ) } self.mesh = self.configTestMesh(mesh_dict) self.layouts_1d = [ Layout.replicated(self.mesh, rank=1), Layout.batch_sharded(self.mesh, _MESH_DIM_X, rank=1), Layout.batch_sharded(self.mesh, _MESH_DIM_Y, rank=1), ] self.layouts_2d = [ Layout.replicated(self.mesh, rank=2), Layout.batch_sharded(self.mesh, _MESH_DIM_X, rank=2), Layout.inner_sharded(self.mesh, _MESH_DIM_X, rank=2), Layout([_MESH_DIM_X, _MESH_DIM_Y], self.mesh), ] def testV2API(self): layout = Layout.replicated(self.mesh, rank=1) zero_tensor = array_ops.zeros([10], layout=layout) zero_like_tensor = array_ops.zeros_like_v2(zero_tensor, layout=layout) self.assertAllEqual(zero_like_tensor.numpy(), zero_tensor.numpy()) ones_tensor = array_ops.ones([10], layout=layout) ones_like_tensor = array_ops.ones_like_v2(zero_tensor, layout=layout) self.assertAllEqual(ones_like_tensor.numpy(), ones_tensor.numpy()) def testStatelessRandom(self): # test dtype default float32 random result = stateless_random_ops.stateless_random_uniform( [10], seed=constant_op.constant([0, 0], dtype=dtypes.int64), minval=0.0, maxval=10.0, ) self.assertEqual([10], result.shape) # test dtype default int32 minval maxval are both None result = stateless_random_ops.stateless_random_uniform( [10], seed=constant_op.constant([1, 2], dtype=dtypes.int64), dtype=dtypes.int32, minval=None, maxval=None, ) self.assertEqual([10], result.shape) # test maxval is None or not given result = stateless_random_ops.stateless_random_uniform( [10], seed=constant_op.constant([1, 2], dtype=dtypes.int64), maxval=12, dtype=dtypes.int32, ) self.assertEqual([10], result.shape) self.assertAllInRange(result, 0, 12) def testStatelessRandomNormal(self): # test dtype default float32 random result = stateless_random_ops.stateless_random_normal( [10], seed=constant_op.constant([0, 0], dtype=dtypes.int32) ) self.assertEqual([10], result.shape) # test dtype double result = stateless_random_ops.stateless_random_normal( [10], seed=constant_op.constant([1, 2], dtype=dtypes.int32), dtype=dtypes.double, ) self.assertEqual([10], result.shape) # test mean and stddev result = stateless_random_ops.stateless_random_normal( [10], seed=constant_op.constant([1, 2], dtype=dtypes.int32), mean=0, stddev=0, ) self.assertEqual([10], result.shape) self.assertAllInRange(result, 0, 0) # test dtensor version of each, check layouts layout = Layout.replicated(self.mesh, rank=1) # test dtype default float 32 random result = d_random.stateless_random_normal( [10], seed=constant_op.constant([0, 0], dtype=dtypes.int32), layout=layout, ) self.assertEqual([10], result.shape) self.assertEqual(layout, api.fetch_layout(result)) # test dtype double result = d_random.stateless_random_normal( [10], seed=constant_op.constant([1, 2], dtype=dtypes.int32), dtype=dtypes.double, layout=layout, ) self.assertEqual([10], result.shape) self.assertEqual(layout, api.fetch_layout(result)) # test mean and stddev result = d_random.stateless_random_normal( [10], seed=constant_op.constant([1, 2], dtype=dtypes.int32), mean=0, stddev=0, layout=layout, ) self.assertEqual([10], result.shape) self.assertAllInRange(result, 0, 0) self.assertEqual(layout, api.fetch_layout(result)) @parameterized.named_parameters(*set( test_util.product((('_labels_unsharded', 0), ('_labels_batch', 1), ('_labels_inner', 2), ('_labels_both', 3)), (('_logits_unsharded', 0), ('_logits_batch', 1), ('_logits_inner', 2), ('_logits_both', 3))))) def testSoftmaxCrossentropyWithLogits(self, labels_layout, logits_layout): expected_layout = Layout.replicated(self.mesh, rank=1) if (labels_layout == 1 or labels_layout == 3 or logits_layout == 1 or logits_layout == 3): expected_layout = Layout.inner_sharded(self.mesh, _MESH_DIM_X, rank=1) labels_layout = self.layouts_2d[labels_layout] logits_layout = self.layouts_2d[logits_layout] labels_numpy = np.random.uniform(size=[6, 4]) logits_numpy = np.random.uniform(size=[6, 4]) labels = constant_op.constant(labels_numpy, dtype=dtypes.float32) logits = constant_op.constant(logits_numpy, dtype=dtypes.float32) # Should we test against the built in version or the patched version? expected = nn_ops.softmax_cross_entropy_with_logits_v2( labels=labels, logits=logits ) labels = numpy_util.pack_numpy(labels, labels_layout) logits = numpy_util.pack_numpy(logits, logits_layout) dtensor_result = nn_ops.softmax_cross_entropy_with_logits_v2( labels=labels, logits=logits ) self.assertDTensorEqual(expected, expected_layout, dtensor_result) @parameterized.named_parameters(*set( test_util.product((('_labels_unsharded', 0), ('_labels_batch_x', 1), ('_labels_batch_y', 2)), (('_logits_unsharded', 0), ('_logits_batch', 1), ('_logits_inner', 2), ('_logits_both', 3))))) def testSparseSoftmaxCrossentropyWithLogits(self, labels_layout, logits_layout): expected_layout = Layout.replicated(self.mesh, rank=1) if labels_layout == 1 or logits_layout == 1 or logits_layout == 3: expected_layout = Layout.inner_sharded(self.mesh, _MESH_DIM_X, rank=1) elif labels_layout == 2: expected_layout = Layout.inner_sharded(self.mesh, _MESH_DIM_Y, rank=1) labels_layout = self.layouts_1d[labels_layout] logits_layout = self.layouts_2d[logits_layout] labels_numpy = np.random.randint(size=[6], low=0, high=4) logits_numpy = np.random.uniform(size=[6, 4]) labels = constant_op.constant(labels_numpy, dtype=dtypes.int64) logits = constant_op.constant(logits_numpy, dtype=dtypes.float32) # Should we test against the built in version or the patched version? expected = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( labels=labels, logits=logits ) labels = numpy_util.pack_numpy(labels, labels_layout) logits = numpy_util.pack_numpy(logits, logits_layout) dtensor_result = nn_ops.sparse_softmax_cross_entropy_with_logits_v2( labels=labels, logits=logits ) self.assertDTensorEqual(expected, expected_layout, dtensor_result) def test_dropout_raises_on_none_seed(self): with api.default_mesh(self.mesh): with self.assertRaisesRegex(ValueError, 'seed must be specified'): _ = d_random.dropout( array_ops.ones([2, 2], dtype=dtypes.float32), rate=0.5, seed=None ) def test_default_mesh(self): @polymorphic_function.function def func(a): return a + 3.0 with api.default_mesh(self.mesh): a = array_ops.zeros(shape=()) result = func(a) self.assertEqual(result, 3.0) self.assertEqual(api.fetch_layout(result).mesh, self.mesh) self.assertTrue(api.fetch_layout(result).is_fully_replicated()) self.assertEqual(result.device, api.device_name()) # Also make sure it works as wrapper @api.default_mesh(self.mesh) def func2(): b = array_ops.ones(shape=()) return func(b) result = func2() self.assertEqual(result, 4.0) self.assertEqual(api.fetch_layout(result).mesh, self.mesh) self.assertTrue(api.fetch_layout(result).is_fully_replicated()) self.assertEqual(result.device, api.device_name()) with self.assertRaisesRegex(ValueError, 'Expect `mesh` to be `Mesh`'): with api.default_mesh(None): pass def test_default_mesh_with_constant(self): @polymorphic_function.function def func(): return constant_op.constant([3, 4]) with api.default_mesh(self.mesh): result = func() self.assertAllEqual(result, [3, 4]) self.assertEqual(api.fetch_layout(result).mesh, self.mesh) self.assertTrue(api.fetch_layout(result).is_fully_replicated()) self.assertEqual(result.device, api.device_name()) def test_error_no_default_mesh(self): with self.assertRaisesRegex( errors_impl.InvalidArgumentError, 'No default mesh has been registered to DTensor', ): with ops.device_v2(api.device_name()): _ = constant_op.constant(3.0) def test_get_default_mesh(self): self.assertIsNone(api.get_default_mesh()) with api.default_mesh(self.mesh): self.assertEqual(api.get_default_mesh(), self.mesh) with api.default_mesh(self.mesh.host_mesh()): self.assertEqual(api.get_default_mesh(), self.mesh.host_mesh()) self.assertEqual(api.get_default_mesh(), self.mesh) self.assertIsNone(api.get_default_mesh()) if __name__ == '__main__': test.main()
APITest
python
pypa__pip
src/pip/_vendor/packaging/_structures.py
{ "start": 182, "end": 804 }
class ____: def __repr__(self) -> str: return "Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return False def __le__(self, other: object) -> bool: return False def __eq__(self, other: object) -> bool: return isinstance(other, self.__class__) def __gt__(self, other: object) -> bool: return True def __ge__(self, other: object) -> bool: return True def __neg__(self: object) -> "NegativeInfinityType": return NegativeInfinity Infinity = InfinityType()
InfinityType
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/resolution_tests/test_resolvable_model.py
{ "start": 576, "end": 1651 }
class ____(BaseModel, dg.Resolvable): int_val: int str_val: str inners: Optional[Sequence[InnerObject]] def test_valid_resolution_simple() -> None: context = dg.ResolutionContext(scope={"some_int": 1, "some_str": "a"}) inner_schema = InnerObject.model()( val1="{{ some_int }}", val2="{{ some_str }}_b", ) inner = InnerObject.resolve_from_model(context, inner_schema) assert inner == InnerObject(val1_renamed=21, val2="a_b") def test_valid_resolution_nested() -> None: context = dg.ResolutionContext(scope={"some_int": 1, "some_str": "a"}) params = TargetObject.model()( int_val="{{ some_int }}", str_val="{{ some_str }}_x", inners=[ InnerObject.model()( val1="{{ some_int }}", val2="{{ some_str }}_y", ) ], ) target = TargetObject.resolve_from_model(context, params) assert target == TargetObject( int_val=1, str_val="a_x", inners=[InnerObject(val1_renamed=21, val2="a_y")], )
TargetObject