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
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_http_status_code.py
{ "start": 1681, "end": 3978 }
class ____(ColumnMapExpectation): """Expect column values to be valid HTTP status codes.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_http_status_code": [ "100", # CONTINUE "200", # OK "404", # NOT FOUND "511", # NETWORK AUTHENTICATION REQUIRED ], "malformed_http_status_code": [ "", "0", "999", "This is not a HTTP status code", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "well_formed_http_status_code"}, "out": {"success": True}, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "malformed_http_status_code"}, "out": {"success": False}, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.valid_http_status_code" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": ["experimental", "hackathon", "typed-entities"], "contributors": [ "@voidforall", ], } if __name__ == "__main__": ExpectColumnValuesToBeValidHttpStatusCode().print_diagnostic_checklist()
ExpectColumnValuesToBeValidHttpStatusCode
python
kamyu104__LeetCode-Solutions
Python/count-substrings-that-satisfy-k-constraint-i.py
{ "start": 60, "end": 514 }
class ____(object): def countKConstraintSubstrings(self, s, k): """ :type s: str :type k: int :rtype: int """ result = cnt = left = 0 for right in xrange(len(s)): cnt += int(s[right] == '1') while not (cnt <= k or (right-left+1)-cnt <= k): cnt -= int(s[left] == '1') left += 1 result += right-left+1 return result
Solution
python
pytorch__pytorch
torch/_inductor/template_heuristics/contiguous_mm.py
{ "start": 719, "end": 1149 }
class ____(TemplateConfigHeuristics): """empty heuristics to skip contiguous mm on not cuda""" @register_template_heuristic( mm_contiguous_subgraph_template.uid, "cuda", register=torch.version.hip is not None, op_name="mm", ) @register_template_heuristic( addmm_contiguous_subgraph_template.uid, "cuda", register=torch.version.hip is not None, op_name="addmm", )
EmptyContiguousMMConfigHeuristics
python
ijl__orjson
test/test_enum.py
{ "start": 202, "end": 249 }
class ____(enum.IntEnum): ONE = 1
IntEnumEnum
python
google__jax
jax/_src/debugger/colab_lib.py
{ "start": 1046, "end": 1176 }
class ____(metaclass=abc.ABCMeta): @abc.abstractmethod def render(self): pass Element = Union[DOMElement, str]
DOMElement
python
django__django
django/core/management/commands/makemessages.py
{ "start": 1857, "end": 5995 }
class ____: """ Represent the state of a translatable file during the build process. """ def __init__(self, command, domain, translatable): self.command = command self.domain = domain self.translatable = translatable @cached_property def is_templatized(self): if self.domain == "django": file_ext = os.path.splitext(self.translatable.file)[1] return file_ext != ".py" return False @cached_property def path(self): return self.translatable.path @cached_property def work_path(self): """ Path to a file which is being fed into GNU gettext pipeline. This may be either a translatable or its preprocessed version. """ if not self.is_templatized: return self.path filename = f"{self.translatable.file}.py" return os.path.join(self.translatable.dirpath, filename) def preprocess(self): """ Preprocess (if necessary) a translatable file before passing it to xgettext GNU gettext utility. """ if not self.is_templatized: return with open(self.path, encoding="utf-8") as fp: src_data = fp.read() if self.domain == "django": content = templatize(src_data, origin=self.path[2:]) with open(self.work_path, "w", encoding="utf-8") as fp: fp.write(content) def postprocess_messages(self, msgs): """ Postprocess messages generated by xgettext GNU gettext utility. Transform paths as if these messages were generated from original translatable files rather than from preprocessed versions. """ if not self.is_templatized: return msgs # Remove '.py' suffix if os.name == "nt": # Preserve '.\' prefix on Windows to respect gettext behavior old_path = self.work_path new_path = self.path else: old_path = self.work_path[2:] new_path = self.path[2:] return re.sub( r"^(#: .*)(" + re.escape(old_path) + r")", lambda match: match[0].replace(old_path, new_path), msgs, flags=re.MULTILINE, ) def cleanup(self): """ Remove a preprocessed copy of a translatable file (if any). """ if self.is_templatized: # This check is needed for the case of a symlinked file and its # source being processed inside a single group (locale dir); # removing either of those two removes both. if os.path.exists(self.work_path): os.unlink(self.work_path) def normalize_eols(raw_contents): """ Take a block of raw text that will be passed through str.splitlines() to get universal newlines treatment. Return the resulting block of text with normalized `\n` EOL sequences ready to be written to disk using current platform's native EOLs. """ lines_list = raw_contents.splitlines() # Ensure last line has its EOL if lines_list and lines_list[-1]: lines_list.append("") return "\n".join(lines_list) def write_pot_file(potfile, msgs): """ Write the `potfile` with the `msgs` contents, making sure its format is valid. """ pot_lines = msgs.splitlines() if os.path.exists(potfile): # Strip the header lines = dropwhile(len, pot_lines) else: lines = [] found, header_read = False, False for line in pot_lines: if not found and not header_read: if "charset=CHARSET" in line: found = True line = line.replace("charset=CHARSET", "charset=UTF-8") if not line and not found: header_read = True lines.append(line) msgs = "\n".join(lines) # Force newlines of POT files to '\n' to work around # https://savannah.gnu.org/bugs/index.php?52395 with open(potfile, "a", encoding="utf-8", newline="\n") as fp: fp.write(msgs)
BuildFile
python
pytorch__pytorch
test/test_bundled_images.py
{ "start": 1727, "end": 3310 }
class ____(TestCase): def test_single_tensors(self): class SingleTensorModel(torch.nn.Module): def forward(self, arg): return arg im = cv2.imread("caffe2/test/test_img/p1.jpg") tensor = torch.from_numpy(im) inflatable_arg = bundle_jpeg_image(tensor, 90) input = [(inflatable_arg,)] sm = torch.jit.script(SingleTensorModel()) torch.utils.bundled_inputs.augment_model_with_bundled_inputs(sm, input) loaded = save_and_load(sm) inflated = loaded.get_all_bundled_inputs() decoded_data = inflated[0][0] # raw image raw_data = get_tensor_from_raw_BGR(im) self.assertEqual(len(inflated), 1) self.assertEqual(len(inflated[0]), 1) self.assertEqual(raw_data.shape, decoded_data.shape) self.assertEqual(raw_data, decoded_data, atol=0.1, rtol=1e-01) # Check if fb::image_decode_to_NCHW works as expected with open("caffe2/test/test_img/p1.jpg", "rb") as fp: weight = torch.full((3,), 1.0 / 255.0).diag() bias = torch.zeros(3) byte_tensor = torch.tensor(list(fp.read())).byte() im2_tensor = torch.ops.fb.image_decode_to_NCHW(byte_tensor, weight, bias) self.assertEqual(raw_data.shape, im2_tensor.shape) self.assertEqual(raw_data, im2_tensor, atol=0.1, rtol=1e-01) if __name__ == "__main__": raise RuntimeError( "This test is not currently used and should be " "enabled in discover_tests.py if required." )
TestBundledImages
python
weaviate__weaviate-python-client
integration/conftest.py
{ "start": 2224, "end": 6778 }
class ____(Protocol): """Typing for fixture.""" def __call__( self, headers: Optional[Dict[str, str]] = None, ports: Tuple[int, int] = (8080, 50051), auth_credentials: Optional[weaviate.auth.AuthCredentials] = None, ) -> weaviate.WeaviateClient: """Typing for fixture.""" ... @pytest.fixture def client_factory() -> Generator[ClientFactory, None, None]: client_fixture: Optional[weaviate.WeaviateClient] = None def _factory( headers: Optional[Dict[str, str]] = None, ports: Tuple[int, int] = (8080, 50051), auth_credentials: Optional[weaviate.auth.AuthCredentials] = None, ) -> weaviate.WeaviateClient: nonlocal client_fixture if client_fixture is None: client_fixture = weaviate.connect_to_local( headers=headers, grpc_port=ports[1], port=ports[0], additional_config=AdditionalConfig(timeout=(60, 120)), # for image tests auth_credentials=auth_credentials, ) return client_fixture try: yield _factory finally: if client_fixture is not None: client_fixture.close() @pytest.fixture def collection_factory( request: SubRequest, client_factory: ClientFactory ) -> Generator[CollectionFactory, None, None]: name_fixtures: List[str] = [] client_fixture: Optional[weaviate.WeaviateClient] = None call_counter: int = 0 def _factory( name: str = "", properties: Optional[List[Property]] = None, references: Optional[List[_ReferencePropertyBase]] = None, vectorizer_config: Optional[ Union[_VectorizerConfigCreate, List[_NamedVectorConfigCreate]] ] = None, inverted_index_config: Optional[_InvertedIndexConfigCreate] = None, multi_tenancy_config: Optional[_MultiTenancyConfigCreate] = None, generative_config: Optional[_GenerativeProvider] = None, headers: Optional[Dict[str, str]] = None, ports: Tuple[int, int] = (8080, 50051), data_model_properties: Optional[Type[Properties]] = None, data_model_refs: Optional[Type[Properties]] = None, replication_config: Optional[_ReplicationConfigCreate] = None, vector_index_config: Optional[_VectorIndexConfigCreate] = None, description: Optional[str] = None, reranker_config: Optional[_RerankerProvider] = None, vector_config: Optional[ Optional[Union[_VectorConfigCreate, List[_VectorConfigCreate]]] ] = None, ) -> Collection[Any, Any]: try: nonlocal client_fixture, name_fixtures, call_counter # noqa: F824 call_counter += 1 name_fixture = ( _sanitize_collection_name(request.node.fspath.basename + "_" + request.node.name) + name + "_" + str(call_counter) ) name_fixtures.append(name_fixture) client_fixture = client_factory( headers=headers, ports=ports, ) client_fixture.collections.delete(name_fixture) collection: Collection[Any, Any] = client_fixture.collections.create( name=name_fixture, description=description, vectorizer_config=vectorizer_config or (Configure.Vectorizer.none() if vector_config is None else None), properties=properties, references=references, inverted_index_config=inverted_index_config, multi_tenancy_config=multi_tenancy_config, generative_config=generative_config, data_model_properties=data_model_properties, data_model_references=data_model_refs, replication_config=replication_config, vector_index_config=vector_index_config, reranker_config=reranker_config, vector_config=vector_config, ) return collection except Exception as e: print("Got exception in _factory", e) raise e try: yield _factory except Exception as e: print("Got exception in collection_factory", e) raise e finally: if client_fixture is not None and name_fixtures is not None: for name_fixture in name_fixtures: client_fixture.collections.delete(name_fixture)
ClientFactory
python
Lightning-AI__lightning
src/lightning/fabric/plugins/environments/kubeflow.py
{ "start": 774, "end": 2362 }
class ____(ClusterEnvironment): """Environment for distributed training using the `PyTorchJob`_ operator from `Kubeflow`_. This environment, unlike others, does not get auto-detected and needs to be passed to the Fabric/Trainer constructor manually. .. _PyTorchJob: https://www.kubeflow.org/docs/components/trainer/legacy-v1/user-guides/pytorch/ .. _Kubeflow: https://www.kubeflow.org """ @property @override def creates_processes_externally(self) -> bool: return True @property @override def main_address(self) -> str: return os.environ["MASTER_ADDR"] @property @override def main_port(self) -> int: return int(os.environ["MASTER_PORT"]) @staticmethod @override def detect() -> bool: raise NotImplementedError("The Kubeflow environment can't be detected automatically.") @override def world_size(self) -> int: return int(os.environ["WORLD_SIZE"]) @override def set_world_size(self, size: int) -> None: log.debug("KubeflowEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") @override def global_rank(self) -> int: return int(os.environ["RANK"]) @override def set_global_rank(self, rank: int) -> None: log.debug("KubeflowEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.") @override def local_rank(self) -> int: return 0 @override def node_rank(self) -> int: return self.global_rank()
KubeflowEnvironment
python
numpy__numpy
numpy/_core/arrayprint.py
{ "start": 50195, "end": 51229 }
class ____: """ Formatter for subtypes of np.complexfloating """ def __init__(self, x, precision, floatmode, suppress_small, sign=False, *, legacy=None): # for backcompatibility, accept bools if isinstance(sign, bool): sign = '+' if sign else '-' floatmode_real = floatmode_imag = floatmode if legacy <= 113: floatmode_real = 'maxprec_equal' floatmode_imag = 'maxprec' self.real_format = FloatingFormat( x.real, precision, floatmode_real, suppress_small, sign=sign, legacy=legacy ) self.imag_format = FloatingFormat( x.imag, precision, floatmode_imag, suppress_small, sign='+', legacy=legacy ) def __call__(self, x): r = self.real_format(x.real) i = self.imag_format(x.imag) # add the 'j' before the terminal whitespace in i sp = len(i.rstrip()) i = i[:sp] + 'j' + i[sp:] return r + i
ComplexFloatingFormat
python
scipy__scipy
scipy/sparse/linalg/_interface.py
{ "start": 2104, "end": 19848 }
class ____: """Common interface for performing matrix vector products Many iterative methods (e.g. `cg`, `gmres`) do not need to know the individual entries of a matrix to solve a linear system ``A@x = b``. Such solvers only require the computation of matrix vector products, ``A@v`` where ``v`` is a dense vector. This class serves as an abstract interface between iterative solvers and matrix-like objects. To construct a concrete `LinearOperator`, either pass appropriate callables to the constructor of this class, or subclass it. A subclass must implement either one of the methods ``_matvec`` and ``_matmat``, and the attributes/properties ``shape`` (pair of integers) and ``dtype`` (may be None). It may call the ``__init__`` on this class to have these attributes validated. Implementing ``_matvec`` automatically implements ``_matmat`` (using a naive algorithm) and vice-versa. Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint`` to implement the Hermitian adjoint (conjugate transpose). As with ``_matvec`` and ``_matmat``, implementing either ``_rmatvec`` or ``_adjoint`` implements the other automatically. Implementing ``_adjoint`` is preferable; ``_rmatvec`` is mostly there for backwards compatibility. Parameters ---------- shape : tuple Matrix dimensions ``(M, N)``. matvec : callable f(v) Returns returns ``A @ v``. rmatvec : callable f(v) Returns ``A^H @ v``, where ``A^H`` is the conjugate transpose of ``A``. matmat : callable f(V) Returns ``A @ V``, where ``V`` is a dense matrix with dimensions ``(N, K)``. dtype : dtype Data type of the matrix. rmatmat : callable f(V) Returns ``A^H @ V``, where ``V`` is a dense matrix with dimensions ``(M, K)``. Attributes ---------- args : tuple For linear operators describing products etc. of other linear operators, the operands of the binary operation. ndim : int Number of dimensions (this is always 2) See Also -------- aslinearoperator : Construct LinearOperators Notes ----- The user-defined `matvec` function must properly handle the case where ``v`` has shape ``(N,)`` as well as the ``(N,1)`` case. The shape of the return type is handled internally by `LinearOperator`. It is highly recommended to explicitly specify the `dtype`, otherwise it is determined automatically at the cost of a single matvec application on ``int8`` zero vector using the promoted `dtype` of the output. Python ``int`` could be difficult to automatically cast to numpy integers in the definition of the `matvec` so the determination may be inaccurate. It is assumed that `matmat`, `rmatvec`, and `rmatmat` would result in the same dtype of the output given an ``int8`` input as `matvec`. LinearOperator instances can also be multiplied, added with each other and exponentiated, all lazily: the result of these operations is always a new, composite LinearOperator, that defers linear operations to the original operators and combines the results. More details regarding how to subclass a LinearOperator and several examples of concrete LinearOperator instances can be found in the external project `PyLops <https://pylops.readthedocs.io>`_. Examples -------- >>> import numpy as np >>> from scipy.sparse.linalg import LinearOperator >>> def mv(v): ... return np.array([2*v[0], 3*v[1]]) ... >>> A = LinearOperator((2,2), matvec=mv) >>> A <2x2 _CustomLinearOperator with dtype=int8> >>> A.matvec(np.ones(2)) array([ 2., 3.]) >>> A @ np.ones(2) array([ 2., 3.]) """ ndim = 2 # Necessary for right matmul with numpy arrays. __array_ufunc__ = None # generic type compatibility with scipy-stubs __class_getitem__ = classmethod(types.GenericAlias) def __new__(cls, *args, **kwargs): if cls is LinearOperator: # Operate as _CustomLinearOperator factory. return super().__new__(_CustomLinearOperator) else: obj = super().__new__(cls) if (type(obj)._matvec == LinearOperator._matvec and type(obj)._matmat == LinearOperator._matmat): warnings.warn("LinearOperator subclass should implement" " at least one of _matvec and _matmat.", category=RuntimeWarning, stacklevel=2) return obj def __init__(self, dtype, shape): """Initialize this LinearOperator. To be called by subclasses. ``dtype`` may be None; ``shape`` should be convertible to a length-2 tuple. """ if dtype is not None: dtype = np.dtype(dtype) shape = tuple(shape) if not isshape(shape): raise ValueError(f"invalid shape {shape!r} (must be 2-d)") self.dtype = dtype self.shape = shape def _init_dtype(self): """Determine the dtype by executing `matvec` on an `int8` test vector. In `np.promote_types` hierarchy, the type `int8` is the smallest, so we call `matvec` on `int8` and use the promoted dtype of the output to set the default `dtype` of the `LinearOperator`. We assume that `matmat`, `rmatvec`, and `rmatmat` would result in the same dtype of the output given an `int8` input as `matvec`. Called from subclasses at the end of the __init__ routine. """ if self.dtype is None: v = np.zeros(self.shape[-1], dtype=np.int8) try: matvec_v = np.asarray(self.matvec(v)) except OverflowError: # Python large `int` promoted to `np.int64`or `np.int32` self.dtype = np.dtype(int) else: self.dtype = matvec_v.dtype def _matmat(self, X): """Default matrix-matrix multiplication handler. Falls back on the user-defined _matvec method, so defining that will define matrix multiplication (though in a very suboptimal way). """ return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T]) def _matvec(self, x): """Default matrix-vector multiplication handler. If self is a linear operator of shape (M, N), then this method will be called on a shape (N,) or (N, 1) ndarray, and should return a shape (M,) or (M, 1) ndarray. This default implementation falls back on _matmat, so defining that will define matrix-vector multiplication as well. """ return self.matmat(x.reshape(-1, 1)) def matvec(self, x): """Matrix-vector multiplication. Performs the operation y=A@x where A is an MxN linear operator and x is a column vector or 1-d array. Parameters ---------- x : {matrix, ndarray} An array with shape (N,) or (N,1). Returns ------- y : {matrix, ndarray} A matrix or ndarray with shape (M,) or (M,1) depending on the type and shape of the x argument. Notes ----- This matvec wraps the user-specified matvec routine or overridden _matvec method to ensure that y has the correct shape and type. """ x = np.asanyarray(x) M,N = self.shape if x.shape != (N,) and x.shape != (N,1): raise ValueError('dimension mismatch') y = self._matvec(x) if isinstance(x, np.matrix): y = asmatrix(y) else: y = np.asarray(y) if x.ndim == 1: y = y.reshape(M) elif x.ndim == 2: y = y.reshape(M,1) else: raise ValueError('invalid shape returned by user-defined matvec()') return y def rmatvec(self, x): """Adjoint matrix-vector multiplication. Performs the operation y = A^H @ x where A is an MxN linear operator and x is a column vector or 1-d array. Parameters ---------- x : {matrix, ndarray} An array with shape (M,) or (M,1). Returns ------- y : {matrix, ndarray} A matrix or ndarray with shape (N,) or (N,1) depending on the type and shape of the x argument. Notes ----- This rmatvec wraps the user-specified rmatvec routine or overridden _rmatvec method to ensure that y has the correct shape and type. """ x = np.asanyarray(x) M,N = self.shape if x.shape != (M,) and x.shape != (M,1): raise ValueError('dimension mismatch') y = self._rmatvec(x) if isinstance(x, np.matrix): y = asmatrix(y) else: y = np.asarray(y) if x.ndim == 1: y = y.reshape(N) elif x.ndim == 2: y = y.reshape(N,1) else: raise ValueError('invalid shape returned by user-defined rmatvec()') return y def _rmatvec(self, x): """Default implementation of _rmatvec; defers to adjoint.""" if type(self)._adjoint == LinearOperator._adjoint: # _adjoint not overridden, prevent infinite recursion if (hasattr(self, "_rmatmat") and type(self)._rmatmat != LinearOperator._rmatmat): # Try to use _rmatmat as a fallback return self._rmatmat(x.reshape(-1, 1)).reshape(-1) raise NotImplementedError else: return self.H.matvec(x) def matmat(self, X): """Matrix-matrix multiplication. Performs the operation y=A@X where A is an MxN linear operator and X dense N*K matrix or ndarray. Parameters ---------- X : {matrix, ndarray} An array with shape (N,K). Returns ------- Y : {matrix, ndarray} A matrix or ndarray with shape (M,K) depending on the type of the X argument. Notes ----- This matmat wraps any user-specified matmat routine or overridden _matmat method to ensure that y has the correct type. """ if not (issparse(X) or is_pydata_spmatrix(X)): X = np.asanyarray(X) if X.ndim != 2: raise ValueError(f'expected 2-d ndarray or matrix, not {X.ndim}-d') if X.shape[0] != self.shape[1]: raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}') try: Y = self._matmat(X) except Exception as e: if issparse(X) or is_pydata_spmatrix(X): raise TypeError( "Unable to multiply a LinearOperator with a sparse matrix." " Wrap the matrix in aslinearoperator first." ) from e raise if isinstance(Y, np.matrix): Y = asmatrix(Y) return Y def rmatmat(self, X): """Adjoint matrix-matrix multiplication. Performs the operation y = A^H @ x where A is an MxN linear operator and x is a column vector or 1-d array, or 2-d array. The default implementation defers to the adjoint. Parameters ---------- X : {matrix, ndarray} A matrix or 2D array. Returns ------- Y : {matrix, ndarray} A matrix or 2D array depending on the type of the input. Notes ----- This rmatmat wraps the user-specified rmatmat routine. """ if not (issparse(X) or is_pydata_spmatrix(X)): X = np.asanyarray(X) if X.ndim != 2: raise ValueError(f'expected 2-d ndarray or matrix, not {X.ndim}-d') if X.shape[0] != self.shape[0]: raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}') try: Y = self._rmatmat(X) except Exception as e: if issparse(X) or is_pydata_spmatrix(X): raise TypeError( "Unable to multiply a LinearOperator with a sparse matrix." " Wrap the matrix in aslinearoperator() first." ) from e raise if isinstance(Y, np.matrix): Y = asmatrix(Y) return Y def _rmatmat(self, X): """Default implementation of _rmatmat defers to rmatvec or adjoint.""" if type(self)._adjoint == LinearOperator._adjoint: return np.hstack([self.rmatvec(col.reshape(-1, 1)) for col in X.T]) else: return self.H.matmat(X) def __call__(self, x): return self@x def __mul__(self, x): return self.dot(x) def __truediv__(self, other): if not np.isscalar(other): raise ValueError("Can only divide a linear operator by a scalar.") return _ScaledLinearOperator(self, 1.0/other) def dot(self, x): """Matrix-matrix or matrix-vector multiplication. Parameters ---------- x : array_like 1-d or 2-d array, representing a vector or matrix. Returns ------- Ax : array 1-d or 2-d array (depending on the shape of x) that represents the result of applying this linear operator on x. """ if isinstance(x, LinearOperator): return _ProductLinearOperator(self, x) elif np.isscalar(x): return _ScaledLinearOperator(self, x) else: if not issparse(x) and not is_pydata_spmatrix(x): # Sparse matrices shouldn't be converted to numpy arrays. x = np.asarray(x) if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1: return self.matvec(x) elif x.ndim == 2: return self.matmat(x) else: raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}') def __matmul__(self, other): if np.isscalar(other): raise ValueError("Scalar operands are not allowed, " "use '*' instead") return self.__mul__(other) def __rmatmul__(self, other): if np.isscalar(other): raise ValueError("Scalar operands are not allowed, " "use '*' instead") return self.__rmul__(other) def __rmul__(self, x): if np.isscalar(x): return _ScaledLinearOperator(self, x) else: return self._rdot(x) def _rdot(self, x): """Matrix-matrix or matrix-vector multiplication from the right. Parameters ---------- x : array_like 1-d or 2-d array, representing a vector or matrix. Returns ------- xA : array 1-d or 2-d array (depending on the shape of x) that represents the result of applying this linear operator on x from the right. Notes ----- This is copied from dot to implement right multiplication. """ if isinstance(x, LinearOperator): return _ProductLinearOperator(x, self) elif np.isscalar(x): return _ScaledLinearOperator(self, x) else: if not issparse(x) and not is_pydata_spmatrix(x): # Sparse matrices shouldn't be converted to numpy arrays. x = np.asarray(x) # We use transpose instead of rmatvec/rmatmat to avoid # unnecessary complex conjugation if possible. if x.ndim == 1 or x.ndim == 2 and x.shape[0] == 1: return self.T.matvec(x.T).T elif x.ndim == 2: return self.T.matmat(x.T).T else: raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}') def __pow__(self, p): if np.isscalar(p): return _PowerLinearOperator(self, p) else: return NotImplemented def __add__(self, x): if isinstance(x, LinearOperator): return _SumLinearOperator(self, x) else: return NotImplemented def __neg__(self): return _ScaledLinearOperator(self, -1) def __sub__(self, x): return self.__add__(-x) def __repr__(self): M,N = self.shape if self.dtype is None: dt = 'unspecified dtype' else: dt = 'dtype=' + str(self.dtype) return f'<{M}x{N} {self.__class__.__name__} with {dt}>' def adjoint(self): """Hermitian adjoint. Returns the Hermitian adjoint of self, aka the Hermitian conjugate or Hermitian transpose. For a complex matrix, the Hermitian adjoint is equal to the conjugate transpose. Can be abbreviated self.H instead of self.adjoint(). Returns ------- A_H : LinearOperator Hermitian adjoint of self. """ return self._adjoint() H = property(adjoint) def transpose(self): """Transpose this linear operator. Returns a LinearOperator that represents the transpose of this one. Can be abbreviated self.T instead of self.transpose(). """ return self._transpose() T = property(transpose) def _adjoint(self): """Default implementation of _adjoint; defers to rmatvec.""" return _AdjointLinearOperator(self) def _transpose(self): """ Default implementation of _transpose; defers to rmatvec + conj""" return _TransposedLinearOperator(self)
LinearOperator
python
kamyu104__LeetCode-Solutions
Python/minimum-moves-to-get-a-peaceful-board.py
{ "start": 512, "end": 981 }
class ____(object): def minMoves(self, rooks): """ :type rooks: List[List[int]] :rtype: int """ def count(arr): cnt = [0]*len(arr) for x in arr: cnt[x] += 1 result = bal = 0 for i in xrange(len(rooks)): bal += cnt[i]-1 result += abs(bal) return result return sum(count(arr) for arr in zip(*rooks))
Solution2
python
kamyu104__LeetCode-Solutions
Python/count-primes.py
{ "start": 717, "end": 1332 }
class ____(object): def countPrimes(self, n): """ :type n: int :rtype: int """ def linear_sieve_of_eratosthenes(n): primes = [] spf = [-1]*(n+1) # the smallest prime factor for i in xrange(2, n+1): if spf[i] == -1: spf[i] = i primes.append(i) for p in primes: if i*p > n or p > spf[i]: break spf[i*p] = p return primes return len(linear_sieve_of_eratosthenes(n-1))
Solution_TLE
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/component_tree_tests/test_get_all_components.py
{ "start": 254, "end": 400 }
class ____(dg.Component): def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: return dg.Definitions()
FooComponent
python
pallets__click
src/click/core.py
{ "start": 4265, "end": 5110 }
class ____(enum.Enum): """This is an :class:`~enum.Enum` that indicates the source of a parameter's value. Use :meth:`click.Context.get_parameter_source` to get the source for a parameter by name. .. versionchanged:: 8.0 Use :class:`~enum.Enum` and drop the ``validate`` method. .. versionchanged:: 8.0 Added the ``PROMPT`` value. """ COMMANDLINE = enum.auto() """The value was provided by the command line args.""" ENVIRONMENT = enum.auto() """The value was provided with an environment variable.""" DEFAULT = enum.auto() """Used the default specified by the parameter.""" DEFAULT_MAP = enum.auto() """Used a default provided by :attr:`Context.default_map`.""" PROMPT = enum.auto() """Used a prompt to confirm a default or provide a value."""
ParameterSource
python
django__django
django/contrib/postgres/validators.py
{ "start": 2568, "end": 2801 }
class ____(MinValueValidator): def compare(self, a, b): return a.lower is None or a.lower < b message = _( "Ensure that the lower bound of the range is not less than %(limit_value)s." )
RangeMinValueValidator
python
sympy__sympy
sympy/physics/secondquant.py
{ "start": 38831, "end": 40370 }
class ____: """ A single state, variable particle number basis set. Examples ======== >>> from sympy.physics.secondquant import VarBosonicBasis >>> b = VarBosonicBasis(5) >>> b [FockState((0,)), FockState((1,)), FockState((2,)), FockState((3,)), FockState((4,))] """ def __init__(self, n_max): self.n_max = n_max self._build_states() def _build_states(self): self.basis = [] for i in range(self.n_max): self.basis.append(FockStateBosonKet([i])) self.n_basis = len(self.basis) def index(self, state): """ Returns the index of state in basis. Examples ======== >>> from sympy.physics.secondquant import VarBosonicBasis >>> b = VarBosonicBasis(3) >>> state = b.state(1) >>> b [FockState((0,)), FockState((1,)), FockState((2,))] >>> state FockStateBosonKet((1,)) >>> b.index(state) 1 """ return self.basis.index(state) def state(self, i): """ The state of a single basis. Examples ======== >>> from sympy.physics.secondquant import VarBosonicBasis >>> b = VarBosonicBasis(5) >>> b.state(3) FockStateBosonKet((3,)) """ return self.basis[i] def __getitem__(self, i): return self.state(i) def __len__(self): return len(self.basis) def __repr__(self): return repr(self.basis)
VarBosonicBasis
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/transfers/sql_to_gcs.py
{ "start": 1368, "end": 22550 }
class ____(BaseOperator): """ Copy data from SQL to Google Cloud Storage in JSON, CSV, or Parquet format. :param sql: The SQL to execute. :param bucket: The bucket to upload to. :param filename: The filename to use as the object name when uploading to Google Cloud Storage. A ``{}`` should be specified in the filename to allow the operator to inject file numbers in cases where the file is split due to size. :param schema_filename: If set, the filename to use as the object name when uploading a .json file containing the BigQuery schema fields for the table that was dumped from the database. :param approx_max_file_size_bytes: This operator supports the ability to split large table dumps into multiple files (see notes in the filename param docs above). This param allows developers to specify the file size of the splits. Check https://cloud.google.com/storage/quotas to see the maximum allowed file size for a single object. :param export_format: Desired format of files to be exported. (json, csv or parquet) :param stringify_dict: Whether to dump Dictionary type objects (such as JSON columns) as a string. Applies only to CSV/JSON export format. :param field_delimiter: The delimiter to be used for CSV files. :param null_marker: The null marker to be used for CSV files. :param gzip: Option to compress file for upload (does not apply to schemas). :param schema: The schema to use, if any. Should be a list of dict or a str. Pass a string if using Jinja template, otherwise, pass a list of dict. Examples could be seen: https://cloud.google.com/bigquery/docs /schemas#specifying_a_json_schema_file :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. :param parameters: a parameters dict that is substituted at query runtime. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param upload_metadata: whether to upload the row count metadata as blob metadata :param exclude_columns: set of columns to exclude from transmission :param partition_columns: list of columns to use for file partitioning. In order to use this parameter, you must sort your dataset by partition_columns. Do this by passing an ORDER BY clause to the sql query. Files are uploaded to GCS as objects with a hive style partitioning directory structure (templated). :param write_on_empty: Optional parameter to specify whether to write a file if the export does not return any rows. Default is False so we will not write a file if the export returns no rows. :param parquet_row_group_size: The approximate number of rows in each row group when using parquet format. Using a large row group size can reduce the file size and improve the performance of reading the data, but it needs more memory to execute the operator. (default: 100000) """ template_fields: Sequence[str] = ( "sql", "bucket", "filename", "schema_filename", "schema", "parameters", "impersonation_chain", "partition_columns", ) template_ext: Sequence[str] = (".sql",) template_fields_renderers = {"sql": "sql"} ui_color = "#a0e08c" def __init__( self, *, sql: str, bucket: str, filename: str, schema_filename: str | None = None, approx_max_file_size_bytes: int = 1900000000, export_format: str = "json", stringify_dict: bool = False, field_delimiter: str = ",", null_marker: str | None = None, gzip: bool = False, schema: str | list | None = None, parameters: dict | None = None, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, upload_metadata: bool = False, exclude_columns: set | None = None, partition_columns: list | None = None, write_on_empty: bool = False, parquet_row_group_size: int = 100000, **kwargs, ) -> None: super().__init__(**kwargs) if exclude_columns is None: exclude_columns = set() self.sql = sql self.bucket = bucket self.filename = filename self.schema_filename = schema_filename self.approx_max_file_size_bytes = approx_max_file_size_bytes self.export_format = export_format.lower() self.stringify_dict = stringify_dict self.field_delimiter = field_delimiter self.null_marker = null_marker self.gzip = gzip self.schema = schema self.parameters = parameters self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain self.upload_metadata = upload_metadata self.exclude_columns = exclude_columns self.partition_columns = partition_columns self.write_on_empty = write_on_empty self.parquet_row_group_size = parquet_row_group_size self._uploaded_file_names: list[str] = [] def execute(self, context: Context): if self.partition_columns: self.log.info( "Found partition columns: %s. " "Assuming the SQL statement is properly sorted by these columns in " "ascending or descending order.", ",".join(self.partition_columns), ) self.log.info("Executing query") cursor = self.query() # If a schema is set, create a BQ schema JSON file. if self.schema_filename: self.log.info("Writing local schema file") schema_file = self._write_local_schema_file(cursor) # Flush file before uploading schema_file["file_handle"].flush() self.log.info("Uploading schema file to GCS.") self._upload_to_gcs(schema_file) schema_file["file_handle"].close() counter = 0 files = [] total_row_count = 0 total_files = 0 self.log.info("Writing local data files") for file_to_upload in self._write_local_data_files(cursor): # Flush file before uploading file_to_upload["file_handle"].flush() self.log.info("Uploading chunk file #%d to GCS.", counter) self._upload_to_gcs(file_to_upload) self.log.info("Removing local file") file_to_upload["file_handle"].close() # Metadata to be outputted to Xcom total_row_count += file_to_upload["file_row_count"] total_files += 1 files.append( { "file_name": file_to_upload["file_name"], "file_mime_type": file_to_upload["file_mime_type"], "file_row_count": file_to_upload["file_row_count"], } ) counter += 1 file_meta = { "bucket": self.bucket, "total_row_count": total_row_count, "total_files": total_files, "files": files, } return file_meta def convert_types(self, schema, col_type_dict, row) -> list: """Convert values from DBAPI to output-friendly formats.""" return [ self.convert_type(value, col_type_dict.get(name), stringify_dict=self.stringify_dict) for name, value in zip(schema, row) ] @staticmethod def _write_rows_to_parquet(parquet_writer: pq.ParquetWriter, rows): rows_pydic: dict[str, list[Any]] = {col: [] for col in parquet_writer.schema.names} for row in rows: for cell, col in zip(row, parquet_writer.schema.names): rows_pydic[col].append(cell) tbl = pa.Table.from_pydict(rows_pydic, parquet_writer.schema) parquet_writer.write_table(tbl) def _write_local_data_files(self, cursor): """ Take a cursor, and writes results to a local file. :return: A dictionary where keys are filenames to be used as object names in GCS, and values are file handles to local files that contain the data for the GCS objects. """ org_schema = [schema_tuple[0] for schema_tuple in cursor.description] schema = [column for column in org_schema if column not in self.exclude_columns] col_type_dict = self._get_col_type_dict() file_no = 0 file_mime_type = self._get_file_mime_type() file_to_upload, tmp_file_handle = self._get_file_to_upload(file_mime_type, file_no) if self.export_format == "csv": csv_writer = self._configure_csv_file(tmp_file_handle, schema) if self.export_format == "parquet": parquet_schema = self._convert_parquet_schema(cursor) parquet_writer = self._configure_parquet_file(tmp_file_handle, parquet_schema) rows_buffer = [] prev_partition_values = None curr_partition_values = None for row in cursor: if self.partition_columns: row_dict = dict(zip(schema, row)) curr_partition_values = tuple( [row_dict.get(partition_column, "") for partition_column in self.partition_columns] ) if prev_partition_values is None: # We haven't set prev_partition_values before. Set to current prev_partition_values = curr_partition_values elif prev_partition_values != curr_partition_values: # If the partition values differ, write the current local file out # Yield first before we write the current record file_no += 1 if self.export_format == "parquet": # Write out the remaining rows in the buffer if rows_buffer: self._write_rows_to_parquet(parquet_writer, rows_buffer) rows_buffer = [] parquet_writer.close() file_to_upload["partition_values"] = prev_partition_values yield file_to_upload file_to_upload, tmp_file_handle = self._get_file_to_upload(file_mime_type, file_no) if self.export_format == "csv": csv_writer = self._configure_csv_file(tmp_file_handle, schema) if self.export_format == "parquet": parquet_writer = self._configure_parquet_file(tmp_file_handle, parquet_schema) # Reset previous to current after writing out the file prev_partition_values = curr_partition_values # Incrementing file_row_count after partition yield ensures all rows are written file_to_upload["file_row_count"] += 1 # Proceed to write the row to the localfile if self.export_format == "csv": row2 = self.convert_types(schema, col_type_dict, row) if self.null_marker is not None: row2 = [value or self.null_marker for value in row2] csv_writer.writerow(row2) elif self.export_format == "parquet": row2 = self.convert_types(schema, col_type_dict, row) if self.null_marker is not None: row2 = [value or self.null_marker for value in row2] rows_buffer.append(row2) if len(rows_buffer) >= self.parquet_row_group_size: self._write_rows_to_parquet(parquet_writer, rows_buffer) rows_buffer = [] else: row2 = self.convert_types(schema, col_type_dict, row) row_dict = dict(zip(schema, row2)) json.dump(row_dict, tmp_file_handle, sort_keys=True, ensure_ascii=False) # Append newline to make dumps BigQuery compatible. tmp_file_handle.write("\n") # Stop if the file exceeds the file size limit. fppos = tmp_file_handle.tell() tmp_file_handle.seek(0, os.SEEK_END) file_size = tmp_file_handle.tell() tmp_file_handle.seek(fppos, os.SEEK_SET) if file_size >= self.approx_max_file_size_bytes: file_no += 1 if self.export_format == "parquet": # Write out the remaining rows in the buffer if rows_buffer: self._write_rows_to_parquet(parquet_writer, rows_buffer) rows_buffer = [] parquet_writer.close() file_to_upload["partition_values"] = curr_partition_values yield file_to_upload file_to_upload, tmp_file_handle = self._get_file_to_upload(file_mime_type, file_no) if self.export_format == "csv": csv_writer = self._configure_csv_file(tmp_file_handle, schema) if self.export_format == "parquet": parquet_writer = self._configure_parquet_file(tmp_file_handle, parquet_schema) if self.export_format == "parquet": # Write out the remaining rows in the buffer if rows_buffer: self._write_rows_to_parquet(parquet_writer, rows_buffer) rows_buffer = [] parquet_writer.close() # Last file may have 0 rows, don't yield if empty # However, if it is the first file and self.write_on_empty is True, then yield to write an empty file if file_to_upload["file_row_count"] > 0 or (file_no == 0 and self.write_on_empty): file_to_upload["partition_values"] = curr_partition_values yield file_to_upload def _get_file_to_upload(self, file_mime_type, file_no): """Return a dictionary that represents the file to upload.""" tmp_file_handle = NamedTemporaryFile(mode="w", encoding="utf-8", delete=True) return ( { "file_name": self.filename.format(file_no), "file_handle": tmp_file_handle, "file_mime_type": file_mime_type, "file_row_count": 0, }, tmp_file_handle, ) def _get_file_mime_type(self): if self.export_format == "csv": file_mime_type = "text/csv" elif self.export_format == "parquet": file_mime_type = "application/octet-stream" else: file_mime_type = "application/json" return file_mime_type def _configure_csv_file(self, file_handle, schema): """Configure a csv writer with the file_handle and write schema as headers for the new file.""" csv_writer = csv.writer(file_handle, delimiter=self.field_delimiter) csv_writer.writerow(schema) return csv_writer def _configure_parquet_file(self, file_handle, parquet_schema) -> pq.ParquetWriter: parquet_writer = pq.ParquetWriter(file_handle.name, parquet_schema) return parquet_writer def _convert_parquet_schema(self, cursor): type_map = { "INTEGER": pa.int64(), "FLOAT": pa.float64(), "NUMERIC": pa.float64(), "BIGNUMERIC": pa.float64(), "BOOL": pa.bool_(), "STRING": pa.string(), "BYTES": pa.binary(), "DATE": pa.date32(), "DATETIME": pa.date64(), "TIMESTAMP": pa.timestamp("s"), } columns = [field[0] for field in cursor.description] bq_fields = [self.field_to_bigquery(field) for field in cursor.description] bq_types = [bq_field.get("type") if bq_field is not None else None for bq_field in bq_fields] pq_types = [type_map.get(bq_type, pa.string()) for bq_type in bq_types] parquet_schema = pa.schema(zip(columns, pq_types)) return parquet_schema @abc.abstractmethod def query(self): """Execute DBAPI query.""" @abc.abstractmethod def field_to_bigquery(self, field) -> dict[str, str]: """Convert a DBAPI field to BigQuery schema format.""" @abc.abstractmethod def convert_type(self, value, schema_type, **kwargs): """Convert a value from DBAPI to output-friendly formats.""" def _get_col_type_dict(self): """Return a dict of column name and column type based on self.schema if not None.""" schema = [] if isinstance(self.schema, str): schema = json.loads(self.schema) elif isinstance(self.schema, list): schema = self.schema elif self.schema is not None: self.log.warning("Using default schema due to unexpected type. Should be a string or list.") col_type_dict = {} try: col_type_dict = {col["name"]: col["type"] for col in schema} except KeyError: self.log.warning( "Using default schema due to missing name or type. Please " "refer to: https://cloud.google.com/bigquery/docs/schemas" "#specifying_a_json_schema_file" ) return col_type_dict def _write_local_schema_file(self, cursor): """ Take a cursor, and writes the BigQuery schema for the results to a local file system. Schema for database will be read from cursor if not specified. :return: A dictionary where key is a filename to be used as an object name in GCS, and values are file handles to local files that contains the BigQuery schema fields in .json format. """ if self.schema: self.log.info("Using user schema") schema = self.schema else: self.log.info("Starts generating schema") schema = [ self.field_to_bigquery(field) for field in cursor.description if field[0] not in self.exclude_columns ] if isinstance(schema, list): schema = json.dumps(schema, sort_keys=True) self.log.info("Using schema for %s", self.schema_filename) self.log.debug("Current schema: %s", schema) tmp_schema_file_handle = NamedTemporaryFile(mode="w", encoding="utf-8", delete=True) tmp_schema_file_handle.write(schema) schema_file_to_upload = { "file_name": self.schema_filename, "file_handle": tmp_schema_file_handle, "file_mime_type": "application/json", } return schema_file_to_upload def _upload_to_gcs(self, file_to_upload): """Upload a file (data split or schema .json file) to Google Cloud Storage.""" hook = GCSHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) is_data_file = file_to_upload.get("file_name") != self.schema_filename metadata = None if is_data_file and self.upload_metadata: metadata = {"row_count": file_to_upload["file_row_count"]} object_name = file_to_upload.get("file_name") if is_data_file and self.partition_columns: # Add partition column values to object_name partition_values = file_to_upload.get("partition_values") head_path, tail_path = os.path.split(object_name) partition_subprefix = [ f"{col}={val}" for col, val in zip(self.partition_columns, partition_values) ] object_name = os.path.join(head_path, *partition_subprefix, tail_path) hook.upload( self.bucket, object_name, file_to_upload.get("file_handle").name, mime_type=file_to_upload.get("file_mime_type"), gzip=self.gzip if is_data_file else False, metadata=metadata, ) self._uploaded_file_names.append(object_name) def _get_openlineage_output_datasets(self) -> list[OutputDataset]: """Retrieve OpenLineage output datasets.""" from airflow.providers.common.compat.openlineage.facet import OutputDataset from airflow.providers.google.cloud.openlineage.utils import extract_ds_name_from_gcs_path return [ OutputDataset( namespace=f"gs://{self.bucket}", name=extract_ds_name_from_gcs_path(self.filename.split("{}", maxsplit=1)[0]), ) ]
BaseSQLToGCSOperator
python
Pylons__pyramid
tests/test_integration.py
{ "start": 7413, "end": 7528 }
class ____(StaticAppBase, unittest.TestCase): package = 'tests.pkgs.static_assetspec'
TestStaticAppUsingAssetSpec
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/links/logs.py
{ "start": 951, "end": 1608 }
class ____(BaseAwsLink): """Helper class for constructing AWS CloudWatch Events Link.""" name = "CloudWatch Events" key = "cloudwatch_events" format_str = ( BASE_AWS_CONSOLE_LINK + "/cloudwatch/home?region={awslogs_region}#logsV2:log-groups/log-group/{awslogs_group}" + "/log-events/{awslogs_stream_name}" ) def format_link(self, **kwargs) -> str: for field in ("awslogs_stream_name", "awslogs_group"): if field in kwargs: kwargs[field] = quote_plus(kwargs[field]) else: return "" return super().format_link(**kwargs)
CloudWatchEventsLink
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/ROI.py
{ "start": 69957, "end": 71165 }
class ____(ROI): r""" Rectangular ROI subclass with a single scale handle at the top-right corner. ============== ============================================================= **Arguments** pos (length-2 sequence) The position of the ROI origin. See ROI(). size (length-2 sequence) The size of the ROI. See ROI(). centered (bool) If True, scale handles affect the ROI relative to its center, rather than its origin. sideScalers (bool) If True, extra scale handles are added at the top and right edges. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos, size, centered=False, sideScalers=False, **args): ROI.__init__(self, pos, size, **args) if centered: center = [0.5, 0.5] else: center = [0, 0] self.addScaleHandle([1, 1], center) if sideScalers: self.addScaleHandle([1, 0.5], [center[0], 0.5]) self.addScaleHandle([0.5, 1], [0.5, center[1]])
RectROI
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor18.py
{ "start": 887, "end": 1019 }
class ____(Generic[_T2]): value: _T2 c1: ClassC[int] | ClassC[str] = ClassC("hi") c2: ClassC[int] | ClassC[str] = ClassC(1)
ClassC
python
getsentry__sentry
src/sentry/seer/anomaly_detection/types.py
{ "start": 153, "end": 261 }
class ____(TypedDict): timestamp: float value: float anomaly: NotRequired[Anomaly]
TimeSeriesPoint
python
catalyst-team__catalyst
catalyst/runners/supervised.py
{ "start": 775, "end": 5503 }
class ____(Runner): """IRunner for experiments with supervised model. Args: input_key: key in ``runner.batch`` dict mapping for model input output_key: key for ``runner.batch`` to store model output target_key: key in ``runner.batch`` dict mapping for target loss_key: key for ``runner.batch_metrics`` to store criterion loss output Abstraction, please check out implementations for more details: - :py:mod:`catalyst.runners.runner.SupervisedRunner` .. note:: ISupervisedRunner contains only the logic with batch handling. ISupervisedRunner logic pseudocode: .. code-block:: python batch = {"input_key": tensor, "target_key": tensor} output = model(batch["input_key"]) batch["output_key"] = output loss = criterion(batch["output_key"], batch["target_key"]) batch_metrics["loss_key"] = loss .. note:: Please follow the `minimal examples`_ sections for use cases. .. _`minimal examples`: https://github.com/catalyst-team/catalyst#minimal-examples # noqa: E501, W505 """ def __init__( self, input_key: Any = "features", output_key: Any = "logits", target_key: str = "targets", loss_key: str = "loss", ): """Init.""" IRunner.__init__(self) self._input_key = input_key self._output_key = output_key self._target_key = target_key self._loss_key = loss_key if isinstance(self._input_key, str): # when model expects value self._process_input = self._process_input_str elif isinstance(self._input_key, (list, tuple)): # when model expects tuple self._process_input = self._process_input_list elif self._input_key is None: # when model expects dict self._process_input = self._process_input_none else: raise NotImplementedError() if isinstance(output_key, str): # when model returns value self._process_output = self._process_output_str elif isinstance(output_key, (list, tuple)): # when model returns tuple self._process_output = self._process_output_list elif self._output_key is None: # when model returns dict self._process_output = self._process_output_none else: raise NotImplementedError() def _process_batch(self, batch): if isinstance(batch, (tuple, list)): assert len(batch) == 2 batch = {self._input_key: batch[0], self._target_key: batch[1]} return batch def _process_input_str(self, batch: Mapping[str, Any], **kwargs): output = self.model(batch[self._input_key], **kwargs) return output def _process_input_list(self, batch: Mapping[str, Any], **kwargs): input = {key: batch[key] for key in self._input_key} output = self.model(**input, **kwargs) return output def _process_input_none(self, batch: Mapping[str, Any], **kwargs): output = self.model(**batch, **kwargs) return output def _process_output_str(self, output: torch.Tensor): output = {self._output_key: output} return output def _process_output_list(self, output: Union[Tuple, List]): output = {key: value for key, value in zip(self._output_key, output)} return output def _process_output_none(self, output: Mapping[str, Any]): return output def forward(self, batch: Mapping[str, Any], **kwargs) -> Mapping[str, Any]: """ Forward method for your Runner. Should not be called directly outside of runner. If your model has specific interface, override this method to use it Args: batch (Mapping[str, Any]): dictionary with data batches from DataLoaders. **kwargs: additional parameters to pass to the model Returns: dict with model output batch """ output = self._process_input(batch, **kwargs) output = self._process_output(output) return output def on_batch_start(self, runner: "IRunner"): """Event handler.""" self.batch = self._process_batch(self.batch) super().on_batch_start(runner) def handle_batch(self, batch: Mapping[str, Any]) -> None: """ Inner method to handle specified data batch. Used to make a train/valid/infer step during Experiment run. Args: batch: dictionary with data batches from DataLoader. """ self.batch = {**batch, **self.forward(batch)}
ISupervisedRunner
python
tensorflow__tensorflow
tensorflow/python/distribute/coordinator/cluster_coordinator_test.py
{ "start": 3019, "end": 15383 }
class ____(test.TestCase): def testBasic(self): queue = coordinator_lib._CoordinatedClosureQueue() closure1 = self._create_closure(queue._cancellation_mgr) queue.put(closure1) self.assertIs(closure1, queue.get()) self.assertFalse(queue.done()) queue.put_back(closure1) self.assertEqual(closure1, queue.get()) queue.mark_finished() self.assertTrue(queue.done()) queue.wait() def testProcessAtLeaseOnce(self): closure_queue = coordinator_lib._CoordinatedClosureQueue() labels = ['A', 'B', 'C', 'D', 'E'] processed_count = collections.defaultdict(int) coord = coordinator.Coordinator(clean_stop_exception_types=[]) def process_queue(): with coord.stop_on_exception(): has_been_put_back = False while True: closure = closure_queue.get(timeout=30) if closure is None: break if not has_been_put_back: has_been_put_back = True closure_queue.put_back(closure) continue closure._function() closure_queue.mark_finished() def get_func(label): def func(): time.sleep(3) processed_count[label] += 1 return func cm = cancellation.CancellationManager() for label in labels: closure_queue.put(ClosureWithOutput(get_func(label), cm)) t1 = threading.Thread(target=process_queue, daemon=True) t1.start() t2 = threading.Thread(target=process_queue, daemon=True) t2.start() # Make sure multiple wait() calls are fine. closure_queue.wait() closure_queue.wait() closure_queue.wait() closure_queue.wait() self.assertEqual(processed_count, collections.Counter(labels)) coord.join([t1, t2]) def testNotifyBeforeWait(self): closure_queue = coordinator_lib._CoordinatedClosureQueue() def func(): logging.info('func running') coord = coordinator.Coordinator(clean_stop_exception_types=[]) def process_queue(): with coord.stop_on_exception(): closure_queue.get() closure_queue.mark_finished() closure_queue.put(ClosureWithOutput(func, closure_queue._cancellation_mgr)) t = threading.Thread(target=process_queue) t.start() coord.join([t]) # This test asserts that waiting at the time the function has been processed # doesn't time out. closure_queue.wait() def _assert_one_unblock_the_other(self, first_fn, second_fn): """Asserts `second_fn` wouldn't return before `first_fn` is finished.""" first_fn_done = threading.Event() second_fn_done = threading.Event() coord = coordinator.Coordinator(clean_stop_exception_types=[]) def wrapped_first_fn(): with coord.stop_on_exception(): self.assertFalse(second_fn_done.is_set()) first_fn() first_fn_done.set() self.assertFalse(first_fn_done.is_set()) t = threading.Thread(target=wrapped_first_fn) t.start() second_fn() self.assertTrue(first_fn_done.is_set()) second_fn_done.set() coord.join([t]) def _run_two_fns_in_parallel(self, first_fn, second_fn): coord = coordinator.Coordinator(clean_stop_exception_types=[]) def wrapped_first_fn(): with coord.stop_on_exception(): first_fn() t = threading.Thread(target=wrapped_first_fn) t.start() second_fn() coord.join([t]) def testWaitRaiseErrorAfterMarkFailure(self): if sys.version_info >= (3, 8) and platform.system() == 'Windows': # TODO(b/165013260): Fix this self.skipTest('Test is currently broken on Windows with Python 3.8') closure_queue = coordinator_lib._CoordinatedClosureQueue() closure_queue.put(self._create_closure(closure_queue._cancellation_mgr)) closure = closure_queue.get() wait_finish_event = threading.Event() coord = coordinator.Coordinator(clean_stop_exception_types=[]) # Using a thread to verify that closure_queue.wait() will not return until # all inflight closures are finished. def mark_finished_fn(): try: raise ValueError('Some error.') except ValueError as e: closure_queue.mark_failed(e) def wait_fn(): with self.assertRaises(ValueError): closure_queue.wait() self._assert_one_unblock_the_other(mark_finished_fn, wait_fn) self.assertTrue(closure_queue.done()) def _create_closure(self, cancellation_mgr): @def_function.function() def some_function(): return 1.0 return ClosureWithOutput(some_function, cancellation_mgr) def _put_two_closures_and_get_one(self): closure_queue = coordinator_lib._CoordinatedClosureQueue() closure1 = self._create_closure(closure_queue._cancellation_mgr) closure_queue.put(closure1) closure2 = self._create_closure(closure_queue._cancellation_mgr) closure_queue.put(closure2) closure_got = closure_queue.get() # returns closure1 self.assertIs(closure_got, closure1) self.assertIsNot(closure_got, closure2) return closure_queue, closure1, closure2 def testPutRaiseError(self): if sys.version_info >= (3, 8) and platform.system() == 'Windows': # TODO(b/165013260): Fix this self.skipTest('Test is currently broken on Windows with Python 3.8') closure_queue, _, closure2 = self._put_two_closures_and_get_one() closure_queue.mark_failed(ValueError()) with self.assertRaises(ValueError): closure_queue.put(self._create_closure(closure_queue._cancellation_mgr)) self.assertTrue(closure_queue.done()) with self.assertRaisesRegex( errors.CancelledError, 'The corresponding function is cancelled. Please reschedule the ' 'function.'): closure2.output_remote_value.fetch() # The error is cleared. closure_queue.put(self._create_closure(closure_queue._cancellation_mgr)) def testWaitRaiseError(self): if sys.version_info >= (3, 8) and platform.system() == 'Windows': # TODO(b/165013260): Fix this self.skipTest('Test is currently broken on Windows with Python 3.8') closure_queue, _, closure2 = self._put_two_closures_and_get_one() closure_queue.mark_failed(ValueError()) with self.assertRaises(ValueError): closure_queue.wait() self.assertTrue(closure_queue.done()) with self.assertRaisesRegex( errors.CancelledError, 'The corresponding function is cancelled. Please reschedule the ' 'function.'): closure2.output_remote_value.fetch() # The error is cleared. closure_queue.wait() def testDoneRaiseError(self): if sys.version_info >= (3, 8) and platform.system() == 'Windows': # TODO(b/165013260): Fix this self.skipTest('Test is currently broken on Windows with Python 3.8') closure_queue, _, _ = self._put_two_closures_and_get_one() self.assertFalse(closure_queue.done()) closure_queue.mark_failed(ValueError()) with self.assertRaises(ValueError): closure_queue.done() def _set_error(self, closure_queue, closure, error): try: raise error except Exception as e: # pylint: disable=broad-except closure.output_remote_value._set_error(e) closure_queue.mark_failed(e) def _test_cancel_closure_when_error(self, call_wait): if sys.version_info >= (3, 8) and platform.system() == 'Windows': # TODO(b/165013260): Fix this self.skipTest('Test is currently broken on Windows with Python 3.8') closure_queue, closure1, closure2 = self._put_two_closures_and_get_one() closure_queue.put(self._create_closure(closure_queue._cancellation_mgr)) closure_queue.get() # At this moment, there are two inflight, one in queue. self.assertEqual(closure_queue._inflight_closure_count, 2) # Hold a copy of the queue's cancellation manager at this point initial_cm = closure_queue._cancellation_mgr # Simulating closure1 fails. self._set_error(closure_queue, closure1, ValueError('Some error.')) # At this moment, there are one inflight, one in queue. self.assertEqual(closure_queue._queue.qsize(), 1) self.assertEqual(closure_queue._inflight_closure_count, 1) closure3 = self._create_closure(closure_queue._cancellation_mgr) def fake_cancellation(): self._set_error(closure_queue, closure2, ValueError('Fake cancellation error.')) def report_error(): # It should not report the fake cancellation error. with self.assertRaisesRegex(ValueError, 'Some error.'): # Verifying `wait()` or `put()` raises even if one closure is in # flight. if call_wait: closure_queue.wait() else: closure_queue.put(closure3) self._assert_one_unblock_the_other(fake_cancellation, report_error) # The original cancellation manager of the queue has been cancelled. self.assertTrue(initial_cm.is_cancelled) # At this moment, there is zero inflight, nothing in queue. self.assertTrue(closure_queue._queue.empty()) self.assertEqual(closure_queue._inflight_closure_count, 0) self.assertIsNone(closure_queue._error) # This asserts that closure1 has errored. with self.assertRaisesRegex(ValueError, 'Some error.'): closure1.output_remote_value.fetch() # The following asserts that closure3 should have been cancelled. if not call_wait: with self.assertRaisesRegex( errors.CancelledError, 'The corresponding function is cancelled. Please reschedule the ' 'function.'): closure3.output_remote_value.fetch() # Closure2 was an inflight closure when it got cancelled. self.assertEqual(closure2.output_remote_value._status, remote_value.RemoteValueStatus.READY) with self.assertRaisesRegex(ValueError, 'Fake cancellation error.'): closure2.output_remote_value.fetch() # This asserts that the queue has a clear state. self.testBasic() def testWaitRaiseErrorAfterCancelClosure(self): self._test_cancel_closure_when_error(call_wait=True) def testPutRaiseErrorAfterCancelClosure(self): self._test_cancel_closure_when_error(call_wait=False) def testStateIsRestoredAfterJoinIsCalled(self): if sys.version_info >= (3, 8) and platform.system() == 'Windows': # TODO(b/165013260): Fix this self.skipTest('Test is currently broken on Windows with Python 3.8') closure_queue, _, _ = self._put_two_closures_and_get_one() self.assertEqual(closure_queue._inflight_closure_count, 1) closure_queue.mark_failed(ValueError('test error')) with self.assertRaises(ValueError): closure_queue.put(self._create_closure(closure_queue._cancellation_mgr)) # Its error should have been cleared. self.assertIsNone(closure_queue._error) closure_queue.put(self._create_closure(closure_queue._cancellation_mgr)) self.assertIsNone(closure_queue._error) def testThreadSafey(self): thread_count = 10 queue = coordinator_lib._CoordinatedClosureQueue() # Each thread performs 20 queue actions: 10 are `put_back` and 10 are # `mark_finished`. action_count = 20 def func(): for i in range(action_count): closure = queue.get() if i % 2 == 0: queue.put_back(closure) else: queue.mark_finished() threads = [threading.Thread(target=func) for i in range(thread_count)] for t in threads: t.start() for _ in range(thread_count * action_count // 2): queue.put(self._create_closure(queue._cancellation_mgr)) queue.wait() self.assertTrue(queue.done()) def testPutGetWithTag(self): queue = coordinator_lib._CoordinatedClosureQueue() closure1 = self._create_closure(queue._cancellation_mgr) closure2 = self._create_closure(queue._cancellation_mgr) closure3 = self._create_closure(queue._cancellation_mgr) def put_fn(): queue.put(closure3, tag=1) queue.put(closure2, tag=2) queue.put(closure1) def get_fn(): # The get should only return the closure with tag 2. self.assertIs(closure2, queue.get(tag=2)) self._run_two_fns_in_parallel(put_fn, get_fn) self.assertFalse(queue.done()) self.assertEqual(closure1, queue.get()) queue.mark_finished() # It will not wait for closure3 self.assertTrue(queue.done()) queue.wait()
CoordinatedClosureQueueTest
python
pytorch__pytorch
test/torch_np/test_scalars_0D_arrays.py
{ "start": 2500, "end": 3823 }
class ____(TestCase): # # np.isscalar(...) checks that its argument is a numeric object with exactly one element. # # This differs from NumPy which also requires that shape == (). # scalars = [ subtest(42, "literal"), subtest(int(42.0), "int"), subtest(np.float32(42), "float32"), subtest(np.array(42), "array_0D", decorators=[xfailIfTorchDynamo]), subtest([42], "list", decorators=[xfailIfTorchDynamo]), subtest([[42]], "list-list", decorators=[xfailIfTorchDynamo]), subtest(np.array([42]), "array_1D", decorators=[xfailIfTorchDynamo]), subtest(np.array([[42]]), "array_2D", decorators=[xfailIfTorchDynamo]), ] import math not_scalars = [ int, np.float32, subtest("s", decorators=[xfailIfTorchDynamo]), subtest("string", decorators=[xfailIfTorchDynamo]), (), [], math.sin, np, np.transpose, [1, 2], np.asarray([1, 2]), np.float32([1, 2]), ] @parametrize("value", scalars) def test_is_scalar(self, value): assert np.isscalar(value) @parametrize("value", not_scalars) def test_is_not_scalar(self, value): assert not np.isscalar(value) if __name__ == "__main__": run_tests()
TestIsScalar
python
aimacode__aima-python
agents.py
{ "start": 12953, "end": 15360 }
class ____: """A direction class for agents that want to move in a 2D plane Usage: d = Direction("down") To change directions: d = d + "right" or d = d + Direction.R #Both do the same thing Note that the argument to __add__ must be a string and not a Direction object. Also, it (the argument) can only be right or left.""" R = "right" L = "left" U = "up" D = "down" def __init__(self, direction): self.direction = direction def __add__(self, heading): """ >>> d = Direction('right') >>> l1 = d.__add__(Direction.L) >>> l2 = d.__add__(Direction.R) >>> l1.direction 'up' >>> l2.direction 'down' >>> d = Direction('down') >>> l1 = d.__add__('right') >>> l2 = d.__add__('left') >>> l1.direction == Direction.L True >>> l2.direction == Direction.R True """ if self.direction == self.R: return { self.R: Direction(self.D), self.L: Direction(self.U), }.get(heading, None) elif self.direction == self.L: return { self.R: Direction(self.U), self.L: Direction(self.D), }.get(heading, None) elif self.direction == self.U: return { self.R: Direction(self.R), self.L: Direction(self.L), }.get(heading, None) elif self.direction == self.D: return { self.R: Direction(self.L), self.L: Direction(self.R), }.get(heading, None) def move_forward(self, from_location): """ >>> d = Direction('up') >>> l1 = d.move_forward((0, 0)) >>> l1 (0, -1) >>> d = Direction(Direction.R) >>> l1 = d.move_forward((0, 0)) >>> l1 (1, 0) """ # get the iterable class to return iclass = from_location.__class__ x, y = from_location if self.direction == self.R: return iclass((x + 1, y)) elif self.direction == self.L: return iclass((x - 1, y)) elif self.direction == self.U: return iclass((x, y - 1)) elif self.direction == self.D: return iclass((x, y + 1))
Direction
python
doocs__leetcode
solution/0400-0499/0496.Next Greater Element I/Solution.py
{ "start": 0, "end": 348 }
class ____: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: stk = [] d = {} for x in nums2[::-1]: while stk and stk[-1] < x: stk.pop() if stk: d[x] = stk[-1] stk.append(x) return [d.get(x, -1) for x in nums1]
Solution
python
psf__black
tests/data/cases/no_blank_line_before_docstring.py
{ "start": 312, "end": 402 }
class ____: """I'm so far and on so many lines... """
MultilineDocstringsAsWell
python
pydata__xarray
xarray/tests/test_datatree.py
{ "start": 21685, "end": 27872 }
class ____: def test_properties(self) -> None: # use int64 for repr consistency on windows ds = Dataset( data_vars={ "foo": (["x", "y"], np.random.randn(2, 3)), }, coords={ "x": ("x", np.array([-1, -2], "int64")), "y": ("y", np.array([0, 1, 2], "int64")), "a": ("x", np.array([4, 5], "int64")), "b": np.int64(-10), }, ) dt = DataTree(dataset=ds) dt["child"] = DataTree() coords = dt.coords assert isinstance(coords, DataTreeCoordinates) # len assert len(coords) == 4 # iter assert list(coords) == ["x", "y", "a", "b"] assert_identical(coords["x"].variable, dt["x"].variable) assert_identical(coords["y"].variable, dt["y"].variable) assert "x" in coords assert "a" in coords assert 0 not in coords assert "foo" not in coords assert "child" not in coords with pytest.raises(KeyError): coords["foo"] # TODO this currently raises a ValueError instead of a KeyError # with pytest.raises(KeyError): # coords[0] # repr expected = dedent( """\ Coordinates: * x (x) int64 16B -1 -2 * y (y) int64 24B 0 1 2 a (x) int64 16B 4 5 b int64 8B -10""" ) actual = repr(coords) assert expected == actual # dims assert coords.sizes == {"x": 2, "y": 3} # dtypes assert coords.dtypes == { "x": np.dtype("int64"), "y": np.dtype("int64"), "a": np.dtype("int64"), "b": np.dtype("int64"), } def test_modify(self) -> None: ds = Dataset( data_vars={ "foo": (["x", "y"], np.random.randn(2, 3)), }, coords={ "x": ("x", np.array([-1, -2], "int64")), "y": ("y", np.array([0, 1, 2], "int64")), "a": ("x", np.array([4, 5], "int64")), "b": np.int64(-10), }, ) dt = DataTree(dataset=ds) dt["child"] = DataTree() actual = dt.copy(deep=True) actual.coords["x"] = ("x", ["a", "b"]) assert_array_equal(actual["x"], ["a", "b"]) actual = dt.copy(deep=True) actual.coords["z"] = ("z", ["a", "b"]) assert_array_equal(actual["z"], ["a", "b"]) actual = dt.copy(deep=True) with pytest.raises(ValueError, match=r"conflicting dimension sizes"): actual.coords["x"] = ("x", [-1]) assert_identical(actual, dt) # should not be modified # TODO: re-enable after implementing reset_coords() # actual = dt.copy() # del actual.coords["b"] # expected = dt.reset_coords("b", drop=True) # assert_identical(expected, actual) with pytest.raises(KeyError): del dt.coords["not_found"] with pytest.raises(KeyError): del dt.coords["foo"] # TODO: re-enable after implementing assign_coords() # actual = dt.copy(deep=True) # actual.coords.update({"c": 11}) # expected = dt.assign_coords({"c": 11}) # assert_identical(expected, actual) # # regression test for GH3746 # del actual.coords["x"] # assert "x" not in actual.xindexes # test that constructors can also handle the `DataTreeCoordinates` object ds2 = Dataset(coords=dt.coords) assert_identical(ds2.coords, dt.coords) da = DataArray(coords=dt.coords) assert_identical(da.coords, dt.coords) # DataTree constructor doesn't accept coords= but should still be able to handle DatasetCoordinates dt2 = DataTree(dataset=dt.coords) assert_identical(dt2.coords, dt.coords) def test_inherited(self) -> None: ds = Dataset( data_vars={ "foo": (["x", "y"], np.random.randn(2, 3)), }, coords={ "x": ("x", np.array([-1, -2], "int64")), "y": ("y", np.array([0, 1, 2], "int64")), "a": ("x", np.array([4, 5], "int64")), "b": np.int64(-10), }, ) dt = DataTree(dataset=ds) dt["child"] = DataTree() child = dt["child"] assert set(dt.coords) == {"x", "y", "a", "b"} assert set(child.coords) == {"x", "y"} actual = child.copy(deep=True) actual.coords["x"] = ("x", ["a", "b"]) assert_array_equal(actual["x"], ["a", "b"]) actual = child.copy(deep=True) actual.coords.update({"c": 11}) expected = child.copy(deep=True) expected.coords["c"] = 11 # check we have only altered the child node assert_identical(expected.root, actual.root) with pytest.raises(KeyError): # cannot delete inherited coordinate from child node del child["x"] # TODO requires a fix for #9472 # actual = child.copy(deep=True) # actual.coords.update({"c": 11}) # expected = child.assign_coords({"c": 11}) # assert_identical(expected, actual) def test_delitem() -> None: ds = Dataset({"a": 0}, coords={"x": ("x", [1, 2]), "z": "a"}) dt = DataTree(ds, children={"c": DataTree()}) with pytest.raises(KeyError): del dt["foo"] # test delete children del dt["c"] assert dt.children == {} assert set(dt.variables) == {"x", "z", "a"} with pytest.raises(KeyError): del dt["c"] # test delete variables del dt["a"] assert set(dt.coords) == {"x", "z"} with pytest.raises(KeyError): del dt["a"] # test delete coordinates del dt["z"] assert set(dt.coords) == {"x"} with pytest.raises(KeyError): del dt["z"] # test delete indexed coordinates del dt["x"] assert dt.variables == {} assert dt.coords == {} assert dt.indexes == {} with pytest.raises(KeyError): del dt["x"]
TestCoords
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/information_schema.py
{ "start": 8324, "end": 8963 }
class ____(TypeDecorator): """This type casts sql_variant columns in the extended_properties view to nvarchar. This is required because pyodbc does not support sql_variant """ impl = Unicode cache_ok = True def column_expression(self, colexpr): return cast(colexpr, NVARCHAR) extended_properties = Table( "extended_properties", ischema, Column("class", Integer), # TINYINT Column("class_desc", CoerceUnicode), Column("major_id", Integer), Column("minor_id", Integer), Column("name", CoerceUnicode), Column("value", NVarcharSqlVariant), schema="sys", )
NVarcharSqlVariant
python
Netflix__metaflow
metaflow/plugins/aws/step_functions/step_functions_deployer_objects.py
{ "start": 300, "end": 1529 }
class ____(TriggeredRun): """ A class representing a triggered AWS Step Functions state machine execution. """ def terminate(self, **kwargs) -> bool: """ Terminate the running state machine execution. Parameters ---------- authorize : str, optional, default None Authorize the termination with a production token. Returns ------- bool True if the command was successful, False otherwise. """ _, run_id = self.pathspec.split("/") # every subclass needs to have `self.deployer_kwargs` command = get_lower_level_group( self.deployer.api, self.deployer.top_level_kwargs, self.deployer.TYPE, self.deployer.deployer_kwargs, ).terminate(run_id=run_id, **kwargs) pid = self.deployer.spm.run_command( [sys.executable, *command], env=self.deployer.env_vars, cwd=self.deployer.cwd, show_output=self.deployer.show_output, ) command_obj = self.deployer.spm.get(pid) command_obj.sync_wait() return command_obj.process.returncode == 0
StepFunctionsTriggeredRun
python
modin-project__modin
modin/core/execution/ray/common/deferred_execution.py
{ "start": 18277, "end": 19292 }
class ____(MaterializationHook): """ Used by MetaList.__getitem__() for lazy materialization and getting a single value from the list. Parameters ---------- meta : MetaList Non-materialized list to get the value from. idx : int The value index in the list. """ def __init__(self, meta: MetaList, idx: int): self.meta = meta self.idx = idx def pre_materialize(self): """ Get item at self.idx or object ref if not materialized. Returns ------- object """ obj = self.meta._obj return obj[self.idx] if isinstance(obj, list) else obj def post_materialize(self, materialized): """ Save the materialized list in self.meta and get the item at self.idx. Parameters ---------- materialized : list Returns ------- object """ self.meta._obj = materialized return materialized[self.idx]
MetaListHook
python
weaviate__weaviate-python-client
weaviate/cluster/models.py
{ "start": 514, "end": 960 }
class ____: """Class representing the status of a replication operation.""" state: ReplicateOperationState errors: List[str] @classmethod def _from_weaviate(cls, data: dict) -> "ReplicateOperationStatus": return cls( state=ReplicateOperationState(data["state"]), errors=data["errors"] or [], ) H = TypeVar("H", None, List[ReplicateOperationStatus]) @dataclass
ReplicateOperationStatus
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/redshift_data.py
{ "start": 1893, "end": 11841 }
class ____(AwsGenericHook["RedshiftDataAPIServiceClient"]): """ Interact with Amazon Redshift Data API. Provide thin wrapper around :external+boto3:py:class:`boto3.client("redshift-data") <RedshiftDataAPIService.Client>`. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBaseHook. .. seealso:: - :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` - `Amazon Redshift Data API \ <https://docs.aws.amazon.com/redshift-data/latest/APIReference/Welcome.html>`__ """ def __init__(self, *args, **kwargs) -> None: kwargs["client_type"] = "redshift-data" super().__init__(*args, **kwargs) def execute_query( self, sql: str | list[str], database: str | None = None, cluster_identifier: str | None = None, db_user: str | None = None, parameters: Iterable | None = None, secret_arn: str | None = None, statement_name: str | None = None, with_event: bool = False, wait_for_completion: bool = True, poll_interval: int = 10, workgroup_name: str | None = None, session_id: str | None = None, session_keep_alive_seconds: int | None = None, ) -> QueryExecutionOutput: """ Execute a statement against Amazon Redshift. :param sql: the SQL statement or list of SQL statement to run :param database: the name of the database :param cluster_identifier: unique identifier of a cluster :param db_user: the database username :param parameters: the parameters for the SQL statement :param secret_arn: the name or ARN of the secret that enables db access :param statement_name: the name of the SQL statement :param with_event: whether to send an event to EventBridge :param wait_for_completion: whether to wait for a result :param poll_interval: how often in seconds to check the query status :param workgroup_name: name of the Redshift Serverless workgroup. Mutually exclusive with `cluster_identifier`. Specify this parameter to query Redshift Serverless. More info https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-serverless.html :param session_id: the session identifier of the query :param session_keep_alive_seconds: duration in seconds to keep the session alive after the query finishes. The maximum time a session can keep alive is 24 hours :returns statement_id: str, the UUID of the statement """ kwargs: dict[str, Any] = { "ClusterIdentifier": cluster_identifier, "Database": database, "DbUser": db_user, "Parameters": parameters, "WithEvent": with_event, "SecretArn": secret_arn, "StatementName": statement_name, "WorkgroupName": workgroup_name, "SessionId": session_id, "SessionKeepAliveSeconds": session_keep_alive_seconds, } if sum(x is not None for x in (cluster_identifier, workgroup_name, session_id)) != 1: raise ValueError( "Exactly one of cluster_identifier, workgroup_name, or session_id must be provided" ) if session_id is not None: msg = "session_id must be a valid UUID4" try: if UUID(session_id).version != 4: raise ValueError(msg) except ValueError: raise ValueError(msg) if session_keep_alive_seconds is not None and ( session_keep_alive_seconds < 0 or duration(seconds=session_keep_alive_seconds).hours > 24 ): raise ValueError("Session keep alive duration must be between 0 and 86400 seconds.") if isinstance(sql, list): kwargs["Sqls"] = sql resp = self.conn.batch_execute_statement(**trim_none_values(kwargs)) else: kwargs["Sql"] = sql resp = self.conn.execute_statement(**trim_none_values(kwargs)) statement_id = resp["Id"] if wait_for_completion: self.wait_for_results(statement_id, poll_interval=poll_interval) return QueryExecutionOutput(statement_id=statement_id, session_id=resp.get("SessionId")) def wait_for_results(self, statement_id: str, poll_interval: int) -> str: while True: self.log.info("Polling statement %s", statement_id) is_finished = self.check_query_is_finished(statement_id) if is_finished: return FINISHED_STATE time.sleep(poll_interval) def check_query_is_finished(self, statement_id: str) -> bool: """Check whether query finished, raise exception is failed.""" resp = self.conn.describe_statement(Id=statement_id) return self.parse_statement_response(resp) def parse_statement_response(self, resp: DescribeStatementResponseTypeDef) -> bool: """Parse the response of describe_statement.""" status = resp["Status"] if status == FINISHED_STATE: num_rows = resp.get("ResultRows") if num_rows is not None: self.log.info("Processed %s rows", num_rows) return True if status in FAILURE_STATES: exception_cls = ( RedshiftDataQueryFailedError if status == FAILED_STATE else RedshiftDataQueryAbortedError ) raise exception_cls( f"Statement {resp['Id']} terminated with status {status}. Response details: {pformat(resp)}" ) self.log.info("Query status: %s", status) return False def get_table_primary_key( self, table: str, database: str, schema: str | None = "public", cluster_identifier: str | None = None, workgroup_name: str | None = None, db_user: str | None = None, secret_arn: str | None = None, statement_name: str | None = None, with_event: bool = False, wait_for_completion: bool = True, poll_interval: int = 10, ) -> list[str] | None: """ Return the table primary key. Copied from ``RedshiftSQLHook.get_table_primary_key()`` :param table: Name of the target table :param database: the name of the database :param schema: Name of the target schema, public by default :param cluster_identifier: unique identifier of a cluster :param workgroup_name: name of the Redshift Serverless workgroup. Mutually exclusive with `cluster_identifier`. Specify this parameter to query Redshift Serverless. More info https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-serverless.html :param db_user: the database username :param secret_arn: the name or ARN of the secret that enables db access :param statement_name: the name of the SQL statement :param with_event: indicates whether to send an event to EventBridge :param wait_for_completion: indicates whether to wait for a result, if True wait, if False don't wait :param poll_interval: how often in seconds to check the query status :return: Primary key columns list """ sql = f""" select kcu.column_name from information_schema.table_constraints tco join information_schema.key_column_usage kcu on kcu.constraint_name = tco.constraint_name and kcu.constraint_schema = tco.constraint_schema and kcu.constraint_name = tco.constraint_name where tco.constraint_type = 'PRIMARY KEY' and kcu.table_schema = {schema} and kcu.table_name = {table} """ stmt_id = self.execute_query( sql=sql, database=database, cluster_identifier=cluster_identifier, workgroup_name=workgroup_name, db_user=db_user, secret_arn=secret_arn, statement_name=statement_name, with_event=with_event, wait_for_completion=wait_for_completion, poll_interval=poll_interval, ).statement_id pk_columns = [] token = "" while True: kwargs = {"Id": stmt_id} if token: kwargs["NextToken"] = token response = self.conn.get_statement_result(**kwargs) # we only select a single column (that is a string), # so safe to assume that there is only a single col in the record pk_columns += [y["stringValue"] for x in response["Records"] for y in x] if "NextToken" in response: token = response["NextToken"] else: break return pk_columns or None async def is_still_running(self, statement_id: str) -> bool: """ Async function to check whether the query is still running. :param statement_id: the UUID of the statement """ async with await self.get_async_conn() as client: desc = await client.describe_statement(Id=statement_id) return desc["Status"] in RUNNING_STATES async def check_query_is_finished_async(self, statement_id: str) -> bool: """ Async function to check statement is finished. It takes statement_id, makes async connection to redshift data to get the query status by statement_id and returns the query status. :param statement_id: the UUID of the statement """ async with await self.get_async_conn() as client: resp = await client.describe_statement(Id=statement_id) return self.parse_statement_response(resp)
RedshiftDataHook
python
django__django
tests/staticfiles_tests/test_handlers.py
{ "start": 207, "end": 401 }
class ____: """ASGI application that returns a string indicating that it was called.""" async def __call__(self, scope, receive, send): return "Application called"
MockApplication
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/from_sparse_tensor_slices_test.py
{ "start": 1280, "end": 7767 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( combinations.combine(tf_api_version=1, mode=["graph"]), combinations.combine(slices=[[ [1., 2., 3.], [1.], [1.], [1., 2.], [], [1., 2.], [], [], [] ], [[1., 2.], [], [1., 2.], [1.], [1., 2.], [], [1., 2.]]]))) def testFromSparseTensorSlices(self, slices): """Test a dataset based on slices of a `tf.sparse.SparseTensor`.""" st = array_ops.sparse_placeholder(dtypes.float64) iterator = dataset_ops.make_initializable_iterator( dataset_ops.Dataset.from_sparse_tensor_slices(st)) init_op = iterator.initializer get_next = sparse_tensor.SparseTensor(*iterator.get_next()) with self.cached_session() as sess: # Test with sparse tensor in the appropriate order. # pylint: disable=g-complex-comprehension indices = np.array( [[i, j] for i in range(len(slices)) for j in range(len(slices[i]))]) values = np.array([val for s in slices for val in s]) # pylint: enable=g-complex-comprehension dense_shape = np.array([len(slices), max(len(s) for s in slices) + 1]) sparse_feed = sparse_tensor.SparseTensorValue(indices, values, dense_shape) sess.run(init_op, feed_dict={st: sparse_feed}) for i, s in enumerate(slices): results = sess.run(get_next) self.assertAllEqual(s, results.values) expected_indices = np.array( [[j] for j in range(len(slices[i]))]).reshape([-1, 1]) self.assertAllEqual(expected_indices, results.indices) self.assertAllEqual(dense_shape[1:], results.dense_shape) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) @combinations.generate( combinations.times( combinations.combine(tf_api_version=1, mode=["graph"]), combinations.combine(slices=[[ [1., 2., 3.], [1.], [1.], [1., 2.], [], [1., 2.], [], [], [] ], [[1., 2.], [], [1., 2.], [1.], [1., 2.], [], [1., 2.]]]))) def testFromSparseTensorSlicesInReverse(self, slices): """Test a dataset based on slices of a `tf.sparse.SparseTensor` in reverse order.""" st = array_ops.sparse_placeholder(dtypes.float64) iterator = dataset_ops.make_initializable_iterator( dataset_ops.Dataset.from_sparse_tensor_slices(st)) init_op = iterator.initializer with self.cached_session() as sess: # pylint: disable=g-complex-comprehension indices = np.array( [[i, j] for i in range(len(slices)) for j in range(len(slices[i]))]) values = np.array([val for s in slices for val in s]) # pylint: enable=g-complex-comprehension dense_shape = np.array([len(slices), max(len(s) for s in slices) + 1]) # Test with sparse tensor in the reverse order, which is not # currently supported. reverse_order_indices = indices[::-1, :] reverse_order_values = values[::-1] sparse_feed = sparse_tensor.SparseTensorValue( reverse_order_indices, reverse_order_values, dense_shape) with self.assertRaises(errors.UnimplementedError): sess.run(init_op, feed_dict={st: sparse_feed}) @combinations.generate(combinations.combine(tf_api_version=1, mode=["graph"])) def testEmptySparseTensorSlices(self): """Test a dataset based on slices of an empty `tf.sparse.SparseTensor`.""" st = array_ops.sparse_placeholder(dtypes.float64) iterator = dataset_ops.make_initializable_iterator( dataset_ops.Dataset.from_sparse_tensor_slices(st)) init_op = iterator.initializer get_next = sparse_tensor.SparseTensor(*iterator.get_next()) with self.cached_session() as sess: # Test with an empty sparse tensor. empty_indices = np.empty((0, 4), dtype=np.int64) empty_values = np.empty((0,), dtype=np.float64) empty_dense_shape = [0, 4, 37, 9] sparse_feed = sparse_tensor.SparseTensorValue(empty_indices, empty_values, empty_dense_shape) sess.run(init_op, feed_dict={st: sparse_feed}) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) @combinations.generate(combinations.combine(tf_api_version=1, mode=["graph"])) def testEmptySparseTensorSlicesInvalid(self): """Test a dataset based on invalid `tf.sparse.SparseTensor`.""" st = array_ops.sparse_placeholder(dtypes.float64) iterator = dataset_ops.make_initializable_iterator( dataset_ops.Dataset.from_sparse_tensor_slices(st)) init_op = iterator.initializer with self.cached_session() as sess: # Test with an empty sparse tensor but with non empty values. empty_indices = np.empty((0, 4), dtype=np.int64) non_empty_values = [1, 2, 3, 4] empty_dense_shape = [0, 4, 37, 9] sparse_feed = sparse_tensor.SparseTensorValue(empty_indices, non_empty_values, empty_dense_shape) # Here, we expect the test to fail when running the feed. with self.assertRaises(errors.InvalidArgumentError): sess.run(init_op, feed_dict={st: sparse_feed}) @combinations.generate(combinations.combine(tf_api_version=1, mode=["graph"])) def testEmptySparseTensorSlicesInvalid2(self): """Test a dataset based on invalid `tf.sparse.SparseTensor`.""" st = array_ops.sparse_placeholder(dtypes.float64) iterator = dataset_ops.make_initializable_iterator( dataset_ops.Dataset.from_sparse_tensor_slices(st)) init_op = iterator.initializer with self.cached_session() as sess: # Test with an empty sparse tensor but with non empty values. empty_indices = [[]] empty_values = [] dense_shape = [1, 1] sparse_feed = sparse_tensor.SparseTensorValue(empty_indices, empty_values, dense_shape) # Here, we expect the test to fail when running the feed. with self.assertRaises(errors.InvalidArgumentError): sess.run(init_op, feed_dict={st: sparse_feed}) @combinations.generate(combinations.combine(tf_api_version=2, mode=["eager"])) def testFromSparseTensorSlicesError(self): with self.assertRaises(AttributeError): dataset_ops.Dataset.from_sparse_tensor_slices(None)
FromSparseTensorSlicesTest
python
joke2k__faker
tests/providers/test_job.py
{ "start": 2269, "end": 2458 }
class ____: """Test de_DE job provider""" def test_job(self, faker, num_samples): for _ in range(num_samples): assert faker.job() in DeDeJobProvider.jobs
TestDeDe
python
tiangolo__fastapi
docs_src/path_operation_configuration/tutorial003.py
{ "start": 109, "end": 517 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None tags: Set[str] = set() @app.post( "/items/", response_model=Item, summary="Create an item", description="Create an item with all the information, name, description, price, tax and a set of unique tags", ) async def create_item(item: Item): return item
Item
python
sympy__sympy
sympy/assumptions/assume.py
{ "start": 2107, "end": 4723 }
class ____(Boolean): """ The class of expressions resulting from applying ``Predicate`` to the arguments. ``AppliedPredicate`` merely wraps its argument and remain unevaluated. To evaluate it, use the ``ask()`` function. Examples ======== >>> from sympy import Q, ask >>> Q.integer(1) Q.integer(1) The ``function`` attribute returns the predicate, and the ``arguments`` attribute returns the tuple of arguments. >>> type(Q.integer(1)) <class 'sympy.assumptions.assume.AppliedPredicate'> >>> Q.integer(1).function Q.integer >>> Q.integer(1).arguments (1,) Applied predicates can be evaluated to a boolean value with ``ask``: >>> ask(Q.integer(1)) True """ __slots__ = () def __new__(cls, predicate, *args): if not isinstance(predicate, Predicate): raise TypeError(f"{predicate} is not a Predicate.") args = map(_sympify, args) return super().__new__(cls, predicate, *args) @property def arg(self): """ Return the expression used by this assumption. Examples ======== >>> from sympy import Q, Symbol >>> x = Symbol('x') >>> a = Q.integer(x + 1) >>> a.arg x + 1 """ # Will be deprecated args = self._args if len(args) == 2: # backwards compatibility return args[1] raise TypeError("'arg' property is allowed only for unary predicates.") @property def function(self): """ Return the predicate. """ # Will be changed to self.args[0] after args overriding is removed return self._args[0] @property def arguments(self): """ Return the arguments which are applied to the predicate. """ # Will be changed to self.args[1:] after args overriding is removed return self._args[1:] def _eval_ask(self, assumptions): return self.function.eval(self.arguments, assumptions) @property def binary_symbols(self): from .ask import Q if self.function == Q.is_true: i = self.arguments[0] if i.is_Boolean or i.is_Symbol: return i.binary_symbols if self.function in (Q.eq, Q.ne): if true in self.arguments or false in self.arguments: if self.arguments[0].is_Symbol: return {self.arguments[0]} elif self.arguments[1].is_Symbol: return {self.arguments[1]} return set()
AppliedPredicate
python
PyCQA__pylint
tests/input/similar_lines_b.py
{ "start": 861, "end": 1110 }
class ____: def similar_function_3_lines(self, tellus): # line same #1 agittis = 10 # line same #2 tellus *= 300 # line same #3 laoreet = "commodo " # line diff return agittis, tellus, laoreet # line diff
Commodo
python
scipy__scipy
benchmarks/benchmarks/sparse.py
{ "start": 11337, "end": 14137 }
class ____(Benchmark): param_names = ['sparse_type', 'density', 'format'] params = [ ['spmatrix', 'sparray'], [0.05, 0.01], ['csr', 'csc', 'lil'], ] def _setup(self, sparse_type, density, format): n = 100000 k = 1000 # faster version of sparse.rand(n, k, format=format, density=density), # with non-exact nnz nz = int(n*k * density) row = np.random.randint(0, n, size=nz) col = np.random.randint(0, k, size=nz) data = np.ones(nz, dtype=np.float64) coo = sparse.coo_array if sparse_type == "sparray" else sparse.coo_matrix X = coo((data, (row, col)), shape=(n, k)) X.sum_duplicates() X = X.asformat(format) with open(f'{sparse_type}-{density}-{format}.pck', 'wb') as f: pickle.dump(X, f, protocol=pickle.HIGHEST_PROTOCOL) def setup_cache(self): for sparse_type in self.params[0]: for density in self.params[1]: for fmt in self.params[2]: self._setup(sparse_type, density, fmt) setup_cache.timeout = 120 def setup(self, sparse_type, density, format): # Unpickling is faster than computing the random matrix... with open(f'{sparse_type}-{density}-{format}.pck', 'rb') as f: self.X = pickle.load(f) def time_getrow(self, sparse_type, density, format): if sparse_type == "sparray": self.X[100] else: self.X.getrow(100) def time_getcol(self, sparse_type, density, format): if sparse_type == "sparray": self.X[:, 100] else: self.X.getcol(100) def time_3_rows(self, sparse_type, density, format): self.X[[0, 100, 105], :] def time_10000_rows(self, sparse_type, density, format): self.X[np.arange(10000), :] def time_3_cols(self, sparse_type, density, format): self.X[:, [0, 100, 105]] def time_100_cols(self, sparse_type, density, format): self.X[:, np.arange(100)] # Retain old benchmark results (remove this if changing the benchmark) time_10000_rows.version = ( "dc19210b894d5fd41d4563f85b7459ef5836cddaf77154b539df3ea91c5d5c1c" ) time_100_cols.version = ( "8d43ed52084cdab150018eedb289a749a39f35d4dfa31f53280f1ef286a23046" ) time_3_cols.version = ( "93e5123910772d62b3f72abff56c2732f83d217221bce409b70e77b89c311d26" ) time_3_rows.version = ( "a9eac80863a0b2f4b510269955041930e5fdd15607238257eb78244f891ebfe6" ) time_getcol.version = ( "291388763b355f0f3935db9272a29965d14fa3f305d3306059381e15300e638b" ) time_getrow.version = ( "edb9e4291560d6ba8dd58ef371b3a343a333bc10744496adb3ff964762d33c68" )
NullSlice
python
ray-project__ray
python/ray/dashboard/modules/job/tests/test_backwards_compatibility.py
{ "start": 916, "end": 4029 }
class ____: @pytest.mark.skipif( sys.platform == "darwin", reason="ray 2.0.1 runs differently on apple silicon than today's.", ) def test_cli(self): """ Test that the current commit's CLI works with old server-side Ray versions. 1) Create a new conda environment with old ray version X installed; inherits same env as current conda envionment except ray version 2) (Server) Start head node and dashboard with old ray version X 3) (Client) Use current commit's CLI code to do sample job submission flow 4) Deactivate the new conda environment and back to original place """ # Shell script creates and cleans up tmp conda environment regardless # of the outcome env_name = f"jobs-backwards-compatibility-{uuid.uuid4().hex}" with conda_env(env_name): shell_cmd = f"{_compatibility_script_path('test_backwards_compatibility.sh')}" # noqa: E501 try: subprocess.check_output(shell_cmd, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: logger.error(str(e)) logger.error(e.stdout.decode()) raise e @pytest.mark.skipif( os.environ.get("JOB_COMPATIBILITY_TEST_TEMP_ENV") is None, reason="This test is only meant to be run from the " "test_backwards_compatibility.sh shell script.", ) def test_error_message(): """ Check that we get a good error message when running against an old server version. """ client = JobSubmissionClient("http://127.0.0.1:8265") # Check that a basic job successfully runs. job_id = client.submit_job( entrypoint="echo 'hello world'", ) wait_for_condition(lambda: client.get_job_status(job_id) == JobStatus.SUCCEEDED) # `entrypoint_num_cpus`, `entrypoint_num_gpus`, and `entrypoint_resources` # are not supported in ray<2.2.0. for unsupported_submit_kwargs in [ {"entrypoint_num_cpus": 1}, {"entrypoint_num_gpus": 1}, {"entrypoint_resources": {"custom": 1}}, ]: with pytest.raises( Exception, match="Ray version 2.0.1 is running on the cluster. " "`entrypoint_num_cpus`, `entrypoint_num_gpus`, and " "`entrypoint_resources` kwargs" " are not supported on the Ray cluster. Please ensure the cluster is " "running Ray 2.2 or higher.", ): client.submit_job( entrypoint="echo hello", **unsupported_submit_kwargs, ) with pytest.raises( Exception, match="Ray version 2.0.1 is running on the cluster. " "`entrypoint_memory` kwarg" " is not supported on the Ray cluster. Please ensure the cluster is " "running Ray 2.8 or higher.", ): client.submit_job( entrypoint="echo hello", entrypoint_memory=4, ) assert True if __name__ == "__main__": sys.exit(pytest.main(["-v", __file__]))
TestBackwardsCompatibility
python
rapidsai__cudf
python/cudf_polars/cudf_polars/experimental/base.py
{ "start": 10717, "end": 11691 }
class ____: """ Join information. Notes ----- This class is used to track mappings between joined-on columns and joined-on keys (groups of columns). We need these mappings to calculate equivalence sets and make join-based unique-count and row-count estimates. """ __slots__ = ("column_map", "join_map", "key_map") column_map: MutableMapping[ColumnStats, set[ColumnStats]] """Mapping between joined columns.""" key_map: MutableMapping[JoinKey, set[JoinKey]] """Mapping between joined keys (groups of columns).""" join_map: dict[IR, list[JoinKey]] """Mapping between IR nodes and associated join keys.""" def __init__(self) -> None: self.column_map: MutableMapping[ColumnStats, set[ColumnStats]] = defaultdict( set[ColumnStats] ) self.key_map: MutableMapping[JoinKey, set[JoinKey]] = defaultdict(set[JoinKey]) self.join_map: dict[IR, list[JoinKey]] = {}
JoinInfo
python
fluentpython__example-code-2e
23-descriptor/bulkfood/bulkfood_v4.py
{ "start": 1366, "end": 1670 }
class ____: weight = Quantity() # <5> price = Quantity() def __init__(self, description, weight, price): self.description = description self.weight = weight self.price = price def subtotal(self): return self.weight * self.price # end::LINEITEM_V4[]
LineItem
python
numpy__numpy
numpy/_core/tests/test_defchararray.py
{ "start": 24472, "end": 28306 }
class ____: def A(self): return np.array([['abc', '123'], ['789', 'xyz']]).view(np.char.chararray) def B(self): return np.array([['efg', '456'], ['051', 'tuv']]).view(np.char.chararray) def test_argsort(self): arr = np.array(['abc'] * 4).view(np.char.chararray) actual = arr.argsort(stable=True) assert_array_equal(actual, [0, 1, 2, 3]) def test_add(self): A, B = self.A(), self.B() AB = np.array([['abcefg', '123456'], ['789051', 'xyztuv']]).view(np.char.chararray) assert_array_equal(AB, (A + B)) assert_(len((A + B)[0][0]) == 6) def test_radd(self): A = self.A() QA = np.array([['qabc', 'q123'], ['q789', 'qxyz']]).view(np.char.chararray) assert_array_equal(QA, ('q' + A)) def test_mul(self): A = self.A() for r in (2, 3, 5, 7, 197): Ar = np.array([[A[0, 0] * r, A[0, 1] * r], [A[1, 0] * r, A[1, 1] * r]]).view(np.char.chararray) assert_array_equal(Ar, (A * r)) for ob in [object(), 'qrs']: with assert_raises_regex(ValueError, 'Can only multiply by integers'): A * ob def test_rmul(self): A = self.A() for r in (2, 3, 5, 7, 197): Ar = np.array([[A[0, 0] * r, A[0, 1] * r], [A[1, 0] * r, A[1, 1] * r]]).view(np.char.chararray) assert_array_equal(Ar, (r * A)) for ob in [object(), 'qrs']: with assert_raises_regex(ValueError, 'Can only multiply by integers'): ob * A def test_mod(self): """Ticket #856""" F = np.array([['%d', '%f'], ['%s', '%r']]).view(np.char.chararray) C = np.array([[3, 7], [19, 1]], dtype=np.int64) FC = np.array([['3', '7.000000'], ['19', 'np.int64(1)']]).view(np.char.chararray) assert_array_equal(FC, F % C) A = np.array([['%.3f', '%d'], ['%s', '%r']]).view(np.char.chararray) A1 = np.array([['1.000', '1'], ['1', repr(np.array(1)[()])]]).view(np.char.chararray) assert_array_equal(A1, (A % 1)) A2 = np.array([['1.000', '2'], ['3', repr(np.array(4)[()])]]).view(np.char.chararray) assert_array_equal(A2, (A % [[1, 2], [3, 4]])) def test_rmod(self): A = self.A() assert_(f"{A}" == str(A)) assert_(f"{A!r}" == repr(A)) for ob in [42, object()]: with assert_raises_regex( TypeError, "unsupported operand type.* and 'chararray'"): ob % A def test_slice(self): """Regression test for https://github.com/numpy/numpy/issues/5982""" arr = np.array([['abc ', 'def '], ['geh ', 'ijk ']], dtype='S4').view(np.char.chararray) sl1 = arr[:] assert_array_equal(sl1, arr) assert_(sl1.base is arr) assert_(sl1.base.base is arr.base) sl2 = arr[:, :] assert_array_equal(sl2, arr) assert_(sl2.base is arr) assert_(sl2.base.base is arr.base) assert_(arr[0, 0] == b'abc') @pytest.mark.parametrize('data', [['plate', ' ', 'shrimp'], [b'retro', b' ', b'encabulator']]) def test_getitem_length_zero_item(self, data): # Regression test for gh-26375. a = np.char.array(data) # a.dtype.type() will be an empty string or bytes instance. # The equality test will fail if a[1] has the wrong type # or does not have length 0. assert_equal(a[1], a.dtype.type())
TestOperations
python
django__django
tests/urlpatterns_reverse/tests.py
{ "start": 29222, "end": 29811 }
class ____(AdminScriptTestCase): """ reverse_lazy can be used in settings without causing a circular import error. """ def setUp(self): super().setUp() self.write_settings( "settings.py", extra=( "from django.urls import reverse_lazy\n" "LOGIN_URL = reverse_lazy('login')" ), ) def test_lazy_in_settings(self): out, err = self.run_manage(["check"]) self.assertNoOutput(err) @override_settings(ROOT_URLCONF="urlpatterns_reverse.urls")
ReverseLazySettingsTest
python
getsentry__sentry
tests/sentry/middleware/integrations/test_classifications.py
{ "start": 1079, "end": 2447 }
class ____(BaseClassificationTestCase): get_response = MagicMock() plugin_cls = PluginClassification(response_handler=get_response) plugin_paths = [ "/plugins/github/installations/webhook/", "/plugins/github/organizations/1/webhook/", "/plugins/bitbucket/organizations/1/webhook/", ] @override_settings(SILO_MODE=SiloMode.CONTROL) @patch.object( PluginClassification, "should_operate", wraps=plugin_cls.should_operate, ) def test_should_operate_uses_parser(self, mock_should_operate) -> None: for plugin_path in self.plugin_paths: request = self.factory.get(plugin_path) prp = PluginRequestParser(request=request, response_handler=self.get_response) assert mock_should_operate(request) == prp.should_operate() @patch("sentry.middleware.integrations.parsers.plugin.PluginRequestParser.get_response") @override_settings(SILO_MODE=SiloMode.CONTROL) def test_get_response_uses_parser(self, mock_rp_get_response) -> None: for plugin_path in self.plugin_paths: assert not mock_rp_get_response.called request = self.factory.get(plugin_path) self.plugin_cls.get_response(request) assert mock_rp_get_response.called mock_rp_get_response.reset_mock()
PluginClassifiationTest
python
huggingface__transformers
src/transformers/models/tapas/modeling_tapas.py
{ "start": 29590, "end": 34903 }
class ____(TapasPreTrainedModel): _tied_weights_keys = { "cls.predictions.decoder.bias": "cls.predictions.bias", "cls.predictions.decoder.weight": "tapas.embeddings.word_embeddings.weight", } config: TapasConfig base_model_prefix = "tapas" def __init__(self, config): super().__init__(config) self.tapas = TapasModel(config, add_pooling_layer=False) self.cls = TapasOnlyMLMHead(config) # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddings): self.cls.predictions.decoder = new_embeddings self.cls.predictions.bias = new_embeddings.bias @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, **kwargs, ) -> Union[tuple, MaskedLMOutput]: r""" token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length, 7)`, *optional*): Token indices that encode tabular structure. Indices can be obtained using [`AutoTokenizer`]. See this class for more info. [What are token type IDs?](../glossary#token-type-ids) position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. If `reset_position_index_per_cell` of [`TapasConfig`] is set to `True`, relative position embeddings will be used. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` Examples: ```python >>> from transformers import AutoTokenizer, TapasForMaskedLM >>> import pandas as pd >>> tokenizer = AutoTokenizer.from_pretrained("google/tapas-base") >>> model = TapasForMaskedLM.from_pretrained("google/tapas-base") >>> data = { ... "Actors": ["Brad Pitt", "Leonardo Di Caprio", "George Clooney"], ... "Age": ["56", "45", "59"], ... "Number of movies": ["87", "53", "69"], ... } >>> table = pd.DataFrame.from_dict(data) >>> inputs = tokenizer( ... table=table, queries="How many [MASK] has George [MASK] played in?", return_tensors="pt" ... ) >>> labels = tokenizer( ... table=table, queries="How many movies has George Clooney played in?", return_tensors="pt" ... )["input_ids"] >>> outputs = model(**inputs, labels=labels) >>> logits = outputs.logits ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.tapas( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] prediction_scores = self.cls(sequence_output) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() # -100 index = padding token masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[2:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring( custom_intro=""" Tapas Model with a cell selection head and optional aggregation head on top for question-answering tasks on tables (linear layers on top of the hidden-states output to compute `logits` and optional `logits_aggregation`), e.g. for SQA, WTQ or WikiSQL-supervised tasks. """ )
TapasForMaskedLM
python
pytorch__pytorch
test/distributed/checkpoint/test_pg_transport.py
{ "start": 14859, "end": 21319 }
class ____(TestCase): def setUp(self): self.device = torch.device("cpu") self.pg = MagicMock() self.timeout = timedelta(seconds=10) # Mock Work object self.mock_work = MagicMock() self.mock_work.wait = MagicMock() # Setup process group mock to return mock_work self.pg.send = MagicMock(return_value=self.mock_work) self.pg.recv = MagicMock(return_value=self.mock_work) def test_send_checkpoint_basic(self): """Test basic send_checkpoint functionality with mocked process group.""" transport = PGTransport(self.pg, self.timeout, self.device) state_dict = {"weight": torch.randn(3, 4), "bias": torch.randn(4)} dst_ranks = [1, 2] transport.send_checkpoint(dst_ranks, state_dict) # Check that send was called with correct parameters # First for metadata length, then for metadata, then for each tensor expected_calls = len(dst_ranks) * (2 + len(state_dict)) self.assertEqual(self.pg.send.call_count, expected_calls) # Check that wait was called on all work objects self.assertEqual(self.mock_work.wait.call_count, expected_calls) def test_recv_checkpoint_basic(self): """Test basic recv_checkpoint functionality with mocked process group.""" # Setup mock for pickle.loads to return a valid _StateDictMeta with patch("pickle.loads") as mock_loads: # Create a mock state dict metadata from torch.utils._pytree import tree_flatten_with_path state_dict = {"weight": torch.randn(3, 4), "bias": torch.randn(4)} leaves, treespec = tree_flatten_with_path(state_dict) paths = [path for path, _ in leaves] # Create mock tensor metadata tensor_metas = [] for _, v in leaves: tensor_metas.append( _TensorMeta( shape=v.shape, dtype=v.dtype, storage_offset=v.storage_offset(), stride=v.stride(), nbytes=v.untyped_storage().nbytes(), ) ) mock_meta = _StateDictMeta( treespec=treespec, paths=paths, non_tensor_leaves=tensor_metas ) mock_loads.return_value = mock_meta # Setup len_t and buf tensors for the mock recv def side_effect(tensor_list, *args, **kwargs): if tensor_list[0].numel() == 1: # This is len_t tensor_list[0].fill_(100) # Some arbitrary length return self.mock_work self.pg.recv.side_effect = side_effect # Create transport and call recv_checkpoint transport = PGTransport(self.pg, self.timeout, self.device) transport.recv_checkpoint(src_rank=0) # Check that recv was called self.assertGreaterEqual( self.pg.recv.call_count, 2 ) # At least for len_t and buf # Check that wait was called self.assertGreaterEqual(self.mock_work.wait.call_count, 2) def test_send_checkpoint_empty_state_dict(self): """Test send_checkpoint with empty state dict.""" transport = PGTransport(self.pg, self.timeout, self.device) state_dict = {} dst_ranks = [1] transport.send_checkpoint(dst_ranks, state_dict) # Check that send was called only for metadata self.assertEqual(self.pg.send.call_count, 2) # len_t and buf_t # Check that wait was called self.assertEqual(self.mock_work.wait.call_count, 2) def test_send_checkpoint_with_non_tensor_values(self): """Test send_checkpoint with non-tensor values in state dict.""" transport = PGTransport(self.pg, self.timeout, self.device) state_dict = {"weight": torch.randn(3, 4), "config": {"lr": 0.01}} dst_ranks = [1] transport.send_checkpoint(dst_ranks, state_dict) # Check that send was called for metadata and one tensor self.assertEqual(self.pg.send.call_count, 3) # len_t, buf_t, and one tensor # Check that wait was called self.assertEqual(self.mock_work.wait.call_count, 3) def test_recv_checkpoint_with_state_dict_callback(self): """Test recv_checkpoint with state_dict callback.""" # Setup mock for pickle.loads to return a valid _StateDictMeta with patch("pickle.loads") as mock_loads: # Create a mock state dict metadata from torch.utils._pytree import tree_flatten_with_path state_dict = {"weight": torch.randn(3, 4), "bias": torch.randn(4)} leaves, treespec = tree_flatten_with_path(state_dict) paths = [path for path, _ in leaves] # Create mock tensor metadata tensor_metas = [] for _, v in leaves: tensor_metas.append( _TensorMeta( shape=v.shape, dtype=v.dtype, storage_offset=v.storage_offset(), stride=v.stride(), nbytes=v.untyped_storage().nbytes(), ) ) mock_meta = _StateDictMeta( treespec=treespec, paths=paths, non_tensor_leaves=tensor_metas ) mock_loads.return_value = mock_meta # Setup len_t and buf tensors for the mock recv def side_effect(tensor_list, *args, **kwargs): if tensor_list[0].numel() == 1: # This is len_t tensor_list[0].fill_(100) # Some arbitrary length return self.mock_work self.pg.recv.side_effect = side_effect # Create a state_dict callback callback_state_dict = {"weight": torch.randn(3, 4), "bias": torch.randn(4)} state_dict_callback = MagicMock(return_value=callback_state_dict) # Create transport with state_dict callback and call recv_checkpoint transport = PGTransport( self.pg, self.timeout, self.device, state_dict=state_dict_callback ) transport.recv_checkpoint(src_rank=0) # Check that state_dict callback was called state_dict_callback.assert_called_once()
TestPGTransportMocked
python
huggingface__transformers
src/transformers/activations.py
{ "start": 4674, "end": 5712 }
class ____(nn.Module): """ Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to https://huggingface.co/papers/2004.09602. Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))). See https://huggingface.co/papers/1606.08415 """ def __init__(self, min: float, max: float): if min > max: raise ValueError(f"min should be < max (got min: {min}, max: {max})") super().__init__() self.min = min self.max = max def forward(self, x: Tensor) -> Tensor: return torch.clip(gelu(x), self.min, self.max)
ClippedGELUActivation
python
doocs__leetcode
solution/2700-2799/2707.Extra Characters in a String/Solution.py
{ "start": 0, "end": 354 }
class ____: def minExtraChar(self, s: str, dictionary: List[str]) -> int: ss = set(dictionary) n = len(s) f = [0] * (n + 1) for i in range(1, n + 1): f[i] = f[i - 1] + 1 for j in range(i): if s[j:i] in ss and f[j] < f[i]: f[i] = f[j] return f[n]
Solution
python
apache__airflow
airflow-core/src/airflow/models/asset.py
{ "start": 16036, "end": 17689 }
class ____(Base): """Reference from a DAG to an asset URI reference of which it is a consumer.""" uri: Mapped[str] = mapped_column( String(length=1500).with_variant( String( length=1500, # latin1 allows for more indexed length in mysql # and this field should only be ascii chars collation="latin1_general_cs", ), "mysql", ), primary_key=True, nullable=False, ) dag_id: Mapped[str] = mapped_column(StringID(), primary_key=True, nullable=False) created_at: Mapped[datetime] = mapped_column(UtcDateTime, default=timezone.utcnow, nullable=False) dag = relationship("DagModel", back_populates="schedule_asset_uri_references") __tablename__ = "dag_schedule_asset_uri_reference" __table_args__ = ( PrimaryKeyConstraint(uri, dag_id, name="dsaur_pkey"), ForeignKeyConstraint( columns=(dag_id,), refcolumns=["dag.dag_id"], name="dsaur_dag_id_fkey", ondelete="CASCADE", ), Index("idx_dag_schedule_asset_uri_reference_dag_id", dag_id), ) def __eq__(self, other: object) -> bool: if isinstance(other, self.__class__): return self.uri == other.uri and self.dag_id == other.dag_id return NotImplemented def __hash__(self): return hash(self.__mapper__.primary_key) def __repr__(self): args = [f"{x.name}={getattr(self, x.name)!r}" for x in self.__mapper__.primary_key] return f"{self.__class__.__name__}({', '.join(args)})"
DagScheduleAssetUriReference
python
huggingface__transformers
src/transformers/trainer_utils.py
{ "start": 12978, "end": 14441 }
class ____(ExplicitEnum): """ Scheduler names for the parameter `lr_scheduler_type` in [`TrainingArguments`]. By default, it uses "linear". Internally, this retrieves `get_linear_schedule_with_warmup` scheduler from [`Trainer`]. Scheduler types: - "linear" = [`get_linear_schedule_with_warmup`] - "cosine" = [`get_cosine_schedule_with_warmup`] - "cosine_with_restarts" = [`get_cosine_with_hard_restarts_schedule_with_warmup`] - "polynomial" = [`get_polynomial_decay_schedule_with_warmup`] - "constant" = [`get_constant_schedule`] - "constant_with_warmup" = [`get_constant_schedule_with_warmup`] - "inverse_sqrt" = [`get_inverse_sqrt_schedule`] - "reduce_lr_on_plateau" = [`get_reduce_on_plateau_schedule`] - "cosine_with_min_lr" = [`get_cosine_with_min_lr_schedule_with_warmup`] - "cosine_warmup_with_min_lr" = [`get_cosine_with_min_lr_schedule_with_warmup_lr_rate`] - "warmup_stable_decay" = [`get_wsd_schedule`] """ LINEAR = "linear" COSINE = "cosine" COSINE_WITH_RESTARTS = "cosine_with_restarts" POLYNOMIAL = "polynomial" CONSTANT = "constant" CONSTANT_WITH_WARMUP = "constant_with_warmup" INVERSE_SQRT = "inverse_sqrt" REDUCE_ON_PLATEAU = "reduce_lr_on_plateau" COSINE_WITH_MIN_LR = "cosine_with_min_lr" COSINE_WARMUP_WITH_MIN_LR = "cosine_warmup_with_min_lr" WARMUP_STABLE_DECAY = "warmup_stable_decay"
SchedulerType
python
google__pytype
pytype/pytd/base_visitor_test.py
{ "start": 87, "end": 897 }
class ____(unittest.TestCase): def test_get_ancestor_map(self): ancestors = base_visitor._GetAncestorMap() # TypeDeclUnit is the top of the food chain - no ancestors other than # itself. self.assertEqual({"TypeDeclUnit"}, ancestors["TypeDeclUnit"]) # NamedType can appear in quite a few places, spot check a few. named_type = ancestors["NamedType"] self.assertIn("TypeDeclUnit", named_type) self.assertIn("Parameter", named_type) self.assertIn("GenericType", named_type) self.assertIn("NamedType", named_type) # Check a few places where NamedType cannot appear. self.assertNotIn("ClassType", named_type) self.assertNotIn("NothingType", named_type) self.assertNotIn("AnythingType", named_type) if __name__ == "__main__": unittest.main()
TestAncestorMap
python
pydantic__pydantic
pydantic/v1/class_validators.py
{ "start": 484, "end": 5879 }
class ____: __slots__ = 'func', 'pre', 'each_item', 'always', 'check_fields', 'skip_on_failure' def __init__( self, func: AnyCallable, pre: bool = False, each_item: bool = False, always: bool = False, check_fields: bool = False, skip_on_failure: bool = False, ): self.func = func self.pre = pre self.each_item = each_item self.always = always self.check_fields = check_fields self.skip_on_failure = skip_on_failure if TYPE_CHECKING: from inspect import Signature from pydantic.v1.config import BaseConfig from pydantic.v1.fields import ModelField from pydantic.v1.types import ModelOrDc ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], ModelField, Type[BaseConfig]], Any] ValidatorsList = List[ValidatorCallable] ValidatorListDict = Dict[str, List[Validator]] _FUNCS: Set[str] = set() VALIDATOR_CONFIG_KEY = '__validator_config__' ROOT_VALIDATOR_CONFIG_KEY = '__root_validator_config__' def validator( *fields: str, pre: bool = False, each_item: bool = False, always: bool = False, check_fields: bool = True, whole: Optional[bool] = None, allow_reuse: bool = False, ) -> Callable[[AnyCallable], 'AnyClassMethod']: """ Decorate methods on the class indicating that they should be used to validate fields :param fields: which field(s) the method should be called on :param pre: whether or not this validator should be called before the standard validators (else after) :param each_item: for complex objects (sets, lists etc.) whether to validate individual elements rather than the whole object :param always: whether this method and other validators should be called even if the value is missing :param check_fields: whether to check that the fields actually exist on the model :param allow_reuse: whether to track and raise an error if another validator refers to the decorated function """ if not fields: raise ConfigError('validator with no fields specified') elif isinstance(fields[0], FunctionType): raise ConfigError( "validators should be used with fields and keyword arguments, not bare. " # noqa: Q000 "E.g. usage should be `@validator('<field_name>', ...)`" ) elif not all(isinstance(field, str) for field in fields): raise ConfigError( "validator fields should be passed as separate string args. " # noqa: Q000 "E.g. usage should be `@validator('<field_name_1>', '<field_name_2>', ...)`" ) if whole is not None: warnings.warn( 'The "whole" keyword argument is deprecated, use "each_item" (inverse meaning, default False) instead', DeprecationWarning, ) assert each_item is False, '"each_item" and "whole" conflict, remove "whole"' each_item = not whole def dec(f: AnyCallable) -> 'AnyClassMethod': f_cls = _prepare_validator(f, allow_reuse) setattr( f_cls, VALIDATOR_CONFIG_KEY, ( fields, Validator(func=f_cls.__func__, pre=pre, each_item=each_item, always=always, check_fields=check_fields), ), ) return f_cls return dec @overload def root_validator(_func: AnyCallable) -> 'AnyClassMethod': ... @overload def root_validator( *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False ) -> Callable[[AnyCallable], 'AnyClassMethod']: ... def root_validator( _func: Optional[AnyCallable] = None, *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False ) -> Union['AnyClassMethod', Callable[[AnyCallable], 'AnyClassMethod']]: """ Decorate methods on a model indicating that they should be used to validate (and perhaps modify) data either before or after standard model parsing/validation is performed. """ if _func: f_cls = _prepare_validator(_func, allow_reuse) setattr( f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre, skip_on_failure=skip_on_failure) ) return f_cls def dec(f: AnyCallable) -> 'AnyClassMethod': f_cls = _prepare_validator(f, allow_reuse) setattr( f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre, skip_on_failure=skip_on_failure) ) return f_cls return dec def _prepare_validator(function: AnyCallable, allow_reuse: bool) -> 'AnyClassMethod': """ Avoid validators with duplicated names since without this, validators can be overwritten silently which generally isn't the intended behaviour, don't run in ipython (see #312) or if allow_reuse is False. """ f_cls = function if isinstance(function, classmethod) else classmethod(function) if not in_ipython() and not allow_reuse: ref = ( getattr(f_cls.__func__, '__module__', '<No __module__>') + '.' + getattr(f_cls.__func__, '__qualname__', f'<No __qualname__: id:{id(f_cls.__func__)}>') ) if ref in _FUNCS: raise ConfigError(f'duplicate validator function "{ref}"; if this is intended, set `allow_reuse=True`') _FUNCS.add(ref) return f_cls
Validator
python
google__pytype
pytype/imports/module_loader.py
{ "start": 314, "end": 3087 }
class ____: """Find a filepath for a module.""" def __init__(self, options: config.Options): self.options = options self.accessed_imports_paths: set[str] = set() def find_import(self, module_name: str) -> tuple[str, bool] | None: """Search through pythonpath for a module. Loops over self.options.pythonpath, taking care of the semantics for __init__.pyi, and pretending there's an empty __init__.pyi if the path (derived from module_name) is a directory. Args: module_name: module name Returns: - (path, file_exists) if we find a path (file_exists will be false if we have found a directory where we need to create an __init__.pyi) - None if we cannot find a full path """ module_name_split = module_name.split(".") for searchdir in self.options.pythonpath: path = path_utils.join(searchdir, *module_name_split) # See if this is a directory with a "__init__.py" defined. # (These also get automatically created in imports_map_loader.py) init_path = path_utils.join(path, "__init__") full_path = self.get_pyi_path(init_path) if full_path is not None: log.debug("Found module %r with path %r", module_name, init_path) return full_path, True elif self.options.imports_map is None and path_utils.isdir(path): # We allow directories to not have an __init__ file. # The module's empty, but you can still load submodules. log.debug( "Created empty module %r with path %r", module_name, init_path ) full_path = path_utils.join(path, "__init__.pyi") return full_path, False else: # Not a directory full_path = self.get_pyi_path(path) if full_path is not None: log.debug("Found module %r in path %r", module_name, path) return full_path, True return None def get_pyi_path(self, path: str) -> str | None: """Get a pyi file from path if it exists.""" path = self._get_pyi_path_no_access_audit(path) if path is not None: self.accessed_imports_paths.add(path) return path def _get_pyi_path_no_access_audit(self, path: str) -> str | None: """Get a pyi file, without recording that it was accessed.""" if self.options.imports_map is not None: if path in self.options.imports_map: full_path = self.options.imports_map[path] else: return None else: full_path = path + ".pyi" # We have /dev/null entries in the import_map - path_utils.isfile() returns # False for those. However, we *do* want to load them. Hence exists / isdir. if path_utils.exists(full_path) and not path_utils.isdir(full_path): return full_path else: return None
_PathFinder
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py
{ "start": 986, "end": 1130 }
class ____(BaseInfoResponse): """Scheduler info serializer for responses.""" latest_scheduler_heartbeat: str | None
SchedulerInfoResponse
python
huggingface__transformers
tests/models/xmod/test_modeling_xmod.py
{ "start": 26921, "end": 34328 }
class ____(unittest.TestCase): @slow def test_xmod_base(self): model = XmodModel.from_pretrained("facebook/xmod-base") # language en_XX model.set_default_language("en_XX") input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) # The dog is cute and lives in the garden house expected_output_shape = torch.Size((1, 12, 768)) # batch_size, sequence_length, embedding_vector_dim expected_output_values_last_dim = torch.tensor( [[-0.2394, -0.0036, 0.1252, -0.0087, 0.1325, 0.0580, -0.2049, -0.1978, -0.1223, 0.0648, -0.2599, -0.3724]] ) output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim torch.testing.assert_close(output[:, :, -1], expected_output_values_last_dim, rtol=1e-3, atol=1e-3) # language de_DE model.set_default_language("de_DE") input_ids = torch.tensor([[0, 1310, 49083, 443, 269, 71, 5486, 165, 60429, 660, 23, 2315, 58761, 18391, 5, 2]]) # Der Hund ist niedlich und wohnt in einem Gartenhaus. expected_output_shape = torch.Size((1, 16, 768)) # batch_size, sequence_length, embedding_vector_dim # fmt: off expected_output_values_last_dim = torch.tensor( [[0.0162, 0.0075, -0.1882, 0.2335, -0.0952, -0.3994, -0.0317, -0.1174, 0.0177, 0.4280, -0.0240, -0.2138, 0.0785, -0.1045, -0.2811, -0.3220]] ) # fmt: on output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim torch.testing.assert_close(output[:, :, -1], expected_output_values_last_dim, rtol=1e-3, atol=1e-3) @slow def test_xmod_large_prenorm(self): model = XmodModel.from_pretrained("facebook/xmod-large-prenorm") # language en_XX model.set_default_language("en_XX") input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) # The dog is cute and lives in the garden house expected_output_shape = torch.Size((1, 12, 1024)) # batch_size, sequence_length, embedding_vector_dim # fmt: off expected_output_values_last_dim = torch.tensor( [[-0.0121, -0.0194, -0.0240, -0.0160, -0.0205, -0.0159, -0.0243, -0.0206, -0.0161, -0.0335, -0.0196, -0.0141]] ) # fmt: on output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim torch.testing.assert_close(output[:, :, -1], expected_output_values_last_dim, rtol=1e-3, atol=1e-3) # language de_DE model.set_default_language("de_DE") input_ids = torch.tensor([[0, 1310, 49083, 443, 269, 71, 5486, 165, 60429, 660, 23, 2315, 58761, 18391, 5, 2]]) # Der Hund ist niedlich und wohnt in einem Gartenhaus. expected_output_shape = torch.Size((1, 16, 1024)) # batch_size, sequence_length, embedding_vector_dim # fmt: off expected_output_values_last_dim = torch.tensor( [[-0.0120, -0.0262, -0.0253, -0.0112, -0.0128, -0.0164, -0.0080, -0.0081, -0.0192, -0.0117, -0.0170, -0.0120, -0.0210, -0.0173, -0.0078, -0.0122]] ) # fmt: on output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim torch.testing.assert_close(output[:, :, -1], expected_output_values_last_dim, rtol=1e-3, atol=1e-3) @slow def test_multilingual_batch(self): model = XmodModel.from_pretrained("facebook/xmod-base") # fmt: off input_ids = torch.tensor([ [0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2], [0, 1310, 49083, 443, 269, 71, 5486, 165, 60429, 660, 23, 2], [0, 1310, 49083, 443, 269, 71, 5486, 165, 60429, 660, 23, 2], [0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2], ]) # fmt: on lang_ids = torch.LongTensor([0, 8, 8, 0]) expected_output_shape = torch.Size((4, 12, 768)) # batch_size, sequence_length, embedding_vector_dim # fmt: off expected_output_values_last_dim = torch.tensor([ [-0.2394, -0.0036, 0.1252, -0.0087, 0.1325, 0.0580, -0.2049, -0.1978, -0.1223, 0.0648, -0.2599, -0.3724], [-0.2668, -0.0235, -0.1739, 0.2266, -0.0901, -0.3482, 0.0105, -0.1915, 0.0397, 0.3822, 0.1836, -0.3407], [-0.2668, -0.0235, -0.1739, 0.2266, -0.0901, -0.3482, 0.0105, -0.1915, 0.0397, 0.3822, 0.1836, -0.3407], [-0.2394, -0.0036, 0.1252, -0.0087, 0.1325, 0.0580, -0.2049, -0.1978, -0.1223, 0.0648, -0.2599, -0.3724], ]) # fmt: on output = model(input_ids, lang_ids=lang_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim torch.testing.assert_close(output[:, :, -1], expected_output_values_last_dim, rtol=1e-3, atol=1e-3) @slow def test_end_to_end_mask_fill(self): tokenizer = XLMRobertaTokenizer.from_pretrained("FacebookAI/xlm-roberta-base") model = XmodForMaskedLM.from_pretrained("facebook/xmod-base", default_language="en_XX") model.to(torch_device) sentences = [ "Hello, my dog is a little <mask>.", "Hi <mask>!", ] inputs = tokenizer(sentences, return_tensors="pt", padding=True) input_ids = inputs["input_ids"].to(torch_device) outputs = model( input_ids=input_ids, attention_mask=inputs["attention_mask"].to(torch_device), ) probs = outputs.logits.softmax(dim=-1) _, predictions = probs.topk(1) predictions = predictions.squeeze(-1) inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device) output_non_padded = model(input_ids=inputs_non_padded) probs_non_padded = output_non_padded.logits.softmax(dim=-1) _, predictions_non_padded = probs_non_padded.topk(1) predictions_non_padded = predictions_non_padded.squeeze(-1) inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device) output_padded = model(input_ids=inputs_padded) probs_padded = output_padded.logits.softmax(dim=-1) _, predictions_padded = probs_padded.topk(1) predictions_padded = predictions_padded.squeeze(-1) batch_out_sentence = tokenizer.batch_decode(predictions, skip_special_tokens=True) non_padded_sentence = tokenizer.decode(predictions_non_padded[0], skip_special_tokens=True) padded_sentence = tokenizer.decode(predictions_padded[0], skip_special_tokens=True) expected_output_sentence = [ "Hello, my dog is a little girl .", "Hi everyone !", ] self.assertListEqual(expected_output_sentence, batch_out_sentence) self.assertListEqual(batch_out_sentence, [non_padded_sentence, padded_sentence])
XmodModelIntegrationTest
python
sympy__sympy
sympy/core/numbers.py
{ "start": 74180, "end": 92450 }
class ____(Expr): r""" Class for representing algebraic numbers in SymPy. Symbolically, an instance of this class represents an element $\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$. That is, the algebraic number $\alpha$ is represented as an element of a particular number field $\mathbb{Q}(\theta)$, with a particular embedding of this field into the complex numbers. Formally, the primitive element $\theta$ is given by two data points: (1) its minimal polynomial (which defines $\mathbb{Q}(\theta)$), and (2) a particular complex number that is a root of this polynomial (which defines the embedding $\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$). Finally, the algebraic number $\alpha$ which we represent is then given by the coefficients of a polynomial in $\theta$. """ __slots__ = ('rep', 'root', 'alias', 'minpoly', '_own_minpoly') is_AlgebraicNumber = True is_algebraic = True is_number = True kind = NumberKind # Optional alias symbol is not free. # Actually, alias should be a Str, but some methods # expect that it be an instance of Expr. free_symbols: set[Basic] = set() def __new__(cls, expr, coeffs=None, alias=None, **args): r""" Construct a new algebraic number $\alpha$ belonging to a number field $k = \mathbb{Q}(\theta)$. There are four instance attributes to be determined: =========== ============================================================================ Attribute Type/Meaning =========== ============================================================================ ``root`` :py:class:`~.Expr` for $\theta$ as a complex number ``minpoly`` :py:class:`~.Poly`, the minimal polynomial of $\theta$ ``rep`` :py:class:`~sympy.polys.polyclasses.DMP` giving $\alpha$ as poly in $\theta$ ``alias`` :py:class:`~.Symbol` for $\theta$, or ``None`` =========== ============================================================================ See Parameters section for how they are determined. Parameters ========== expr : :py:class:`~.Expr`, or pair $(m, r)$ There are three distinct modes of construction, depending on what is passed as *expr*. **(1)** *expr* is an :py:class:`~.AlgebraicNumber`: In this case we begin by copying all four instance attributes from *expr*. If *coeffs* were also given, we compose the two coeff polynomials (see below). If an *alias* was given, it overrides. **(2)** *expr* is any other type of :py:class:`~.Expr`: Then ``root`` will equal *expr*. Therefore it must express an algebraic quantity, and we will compute its ``minpoly``. **(3)** *expr* is an ordered pair $(m, r)$ giving the ``minpoly`` $m$, and a ``root`` $r$ thereof, which together define $\theta$. In this case $m$ may be either a univariate :py:class:`~.Poly` or any :py:class:`~.Expr` which represents the same, while $r$ must be some :py:class:`~.Expr` representing a complex number that is a root of $m$, including both explicit expressions in radicals, and instances of :py:class:`~.ComplexRootOf` or :py:class:`~.AlgebraicNumber`. coeffs : list, :py:class:`~.ANP`, None, optional (default=None) This defines ``rep``, giving the algebraic number $\alpha$ as a polynomial in $\theta$. If a list, the elements should be integers or rational numbers. If an :py:class:`~.ANP`, we take its coefficients (using its :py:meth:`~.ANP.to_list()` method). If ``None``, then the list of coefficients defaults to ``[1, 0]``, meaning that $\alpha = \theta$ is the primitive element of the field. If *expr* was an :py:class:`~.AlgebraicNumber`, let $g(x)$ be its ``rep`` polynomial, and let $f(x)$ be the polynomial defined by *coeffs*. Then ``self.rep`` will represent the composition $(f \circ g)(x)$. alias : str, :py:class:`~.Symbol`, None, optional (default=None) This is a way to provide a name for the primitive element. We described several ways in which the *expr* argument can define the value of the primitive element, but none of these methods gave it a name. Here, for example, *alias* could be set as ``Symbol('theta')``, in order to make this symbol appear when $\alpha$ is printed, or rendered as a polynomial, using the :py:meth:`~.as_poly()` method. Examples ======== Recall that we are constructing an algebraic number as a field element $\alpha \in \mathbb{Q}(\theta)$. >>> from sympy import AlgebraicNumber, sqrt, CRootOf, S >>> from sympy.abc import x Example (1): $\alpha = \theta = \sqrt{2}$ >>> a1 = AlgebraicNumber(sqrt(2)) >>> a1.minpoly_of_element().as_expr(x) x**2 - 2 >>> a1.evalf(10) 1.414213562 Example (2): $\alpha = 3 \sqrt{2} - 5$, $\theta = \sqrt{2}$. We can either build on the last example: >>> a2 = AlgebraicNumber(a1, [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2) or start from scratch: >>> a2 = AlgebraicNumber(sqrt(2), [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2) Example (3): $\alpha = 6 \sqrt{2} - 11$, $\theta = \sqrt{2}$. Again we can build on the previous example, and we see that the coeff polys are composed: >>> a3 = AlgebraicNumber(a2, [2, -1]) >>> a3.as_expr() -11 + 6*sqrt(2) reflecting the fact that $(2x - 1) \circ (3x - 5) = 6x - 11$. Example (4): $\alpha = \sqrt{2}$, $\theta = \sqrt{2} + \sqrt{3}$. The easiest way is to use the :py:func:`~.to_number_field()` function: >>> from sympy import to_number_field >>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) >>> a4.minpoly_of_element().as_expr(x) x**2 - 2 >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3) >>> a4.coeffs() [1/2, 0, -9/2, 0] but if you already knew the right coefficients, you could construct it directly: >>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0]) >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3) Example (5): Construct the Golden Ratio as an element of the 5th cyclotomic field, supposing we already know its coefficients. This time we introduce the alias $\zeta$ for the primitive element of the field: >>> from sympy import cyclotomic_poly >>> from sympy.abc import zeta >>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), ... [-1, -1, 0, 0], alias=zeta) >>> a5.as_poly().as_expr() -zeta**3 - zeta**2 >>> a5.evalf() 1.61803398874989 (The index ``-1`` to ``CRootOf`` selects the complex root with the largest real and imaginary parts, which in this case is $\mathrm{e}^{2i\pi/5}$. See :py:class:`~.ComplexRootOf`.) Example (6): Building on the last example, construct the number $2 \phi \in \mathbb{Q}(\phi)$, where $\phi$ is the Golden Ratio: >>> from sympy.abc import phi >>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi) >>> a6.as_poly().as_expr() 2*phi >>> a6.primitive_element().evalf() 1.61803398874989 Note that we needed to use ``a5.to_root()``, since passing ``a5`` as the first argument would have constructed the number $2 \phi$ as an element of the field $\mathbb{Q}(\zeta)$: >>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0]) >>> a6_wrong.as_poly().as_expr() -2*zeta**3 - 2*zeta**2 >>> a6_wrong.primitive_element().evalf() 0.309016994374947 + 0.951056516295154*I """ from sympy.polys.polyclasses import ANP, DMP from sympy.polys.numberfields import minimal_polynomial expr = sympify(expr) rep0 = None alias0 = None if isinstance(expr, (tuple, Tuple)): minpoly, root = expr if not minpoly.is_Poly: from sympy.polys.polytools import Poly minpoly = Poly(minpoly) elif expr.is_AlgebraicNumber: minpoly, root, rep0, alias0 = (expr.minpoly, expr.root, expr.rep, expr.alias) else: minpoly, root = minimal_polynomial( expr, args.get('gen'), polys=True), expr dom = minpoly.get_domain() if coeffs is not None: if not isinstance(coeffs, ANP): rep = DMP.from_sympy_list(sympify(coeffs), 0, dom) scoeffs = Tuple(*coeffs) else: rep = DMP.from_list(coeffs.to_list(), 0, dom) scoeffs = Tuple(*coeffs.to_list()) else: rep = DMP.from_list([1, 0], 0, dom) scoeffs = Tuple(1, 0) if rep0 is not None: from sympy.polys.densetools import dup_compose c = dup_compose(rep.to_list(), rep0.to_list(), dom) rep = DMP.from_list(c, 0, dom) scoeffs = Tuple(*c) if rep.degree() >= minpoly.degree(): rep = rep.rem(minpoly.rep) sargs = (root, scoeffs) alias = alias or alias0 if alias is not None: from .symbol import Symbol if not isinstance(alias, Symbol): alias = Symbol(alias) sargs = sargs + (alias,) obj = Expr.__new__(cls, *sargs) obj.rep = rep obj.root = root obj.alias = alias obj.minpoly = minpoly obj._own_minpoly = None return obj def __hash__(self): return super().__hash__() def _eval_evalf(self, prec): return self.as_expr()._evalf(prec) @property def is_aliased(self): """Returns ``True`` if ``alias`` was set. """ return self.alias is not None def as_poly(self, x=None): """Create a Poly instance from ``self``. """ from sympy.polys.polytools import Poly, PurePoly if x is not None: return Poly.new(self.rep, x) else: if self.alias is not None: return Poly.new(self.rep, self.alias) else: from .symbol import Dummy return PurePoly.new(self.rep, Dummy('x')) def as_expr(self, x=None): """Create a Basic expression from ``self``. """ return self.as_poly(x or self.root).as_expr().expand() def coeffs(self): """Returns all SymPy coefficients of an algebraic number. """ return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ] def native_coeffs(self): """Returns all native coefficients of an algebraic number. """ return self.rep.all_coeffs() def to_algebraic_integer(self): """Convert ``self`` to an algebraic integer. """ from sympy.polys.polytools import Poly f = self.minpoly if f.LC() == 1: return self coeff = f.LC()**(f.degree() - 1) poly = f.compose(Poly(f.gen/f.LC())) minpoly = poly*coeff root = f.LC()*self.root return AlgebraicNumber((minpoly, root), self.coeffs()) def _eval_simplify(self, **kwargs): from sympy.polys.rootoftools import CRootOf from sympy.polys import minpoly measure, ratio = kwargs['measure'], kwargs['ratio'] for r in [r for r in self.minpoly.all_roots() if r.func != CRootOf]: if minpoly(self.root - r).is_Symbol: # use the matching root if it's simpler if measure(r) < ratio*measure(self.root): return AlgebraicNumber(r) return self def field_element(self, coeffs): r""" Form another element of the same number field. Explanation =========== If we represent $\alpha \in \mathbb{Q}(\theta)$, form another element $\beta \in \mathbb{Q}(\theta)$ of the same number field. Parameters ========== coeffs : list, :py:class:`~.ANP` Like the *coeffs* arg to the class :py:meth:`constructor<.AlgebraicNumber.__new__>`, defines the new element as a polynomial in the primitive element. If a list, the elements should be integers or rational numbers. If an :py:class:`~.ANP`, we take its coefficients (using its :py:meth:`~.ANP.to_list()` method). Examples ======== >>> from sympy import AlgebraicNumber, sqrt >>> a = AlgebraicNumber(sqrt(5), [-1, 1]) >>> b = a.field_element([3, 2]) >>> print(a) 1 - sqrt(5) >>> print(b) 2 + 3*sqrt(5) >>> print(b.primitive_element() == a.primitive_element()) True See Also ======== AlgebraicNumber """ return AlgebraicNumber( (self.minpoly, self.root), coeffs=coeffs, alias=self.alias) @property def is_primitive_element(self): r""" Say whether this algebraic number $\alpha \in \mathbb{Q}(\theta)$ is equal to the primitive element $\theta$ for its field. """ c = self.coeffs() # Second case occurs if self.minpoly is linear: return c == [1, 0] or c == [self.root] def primitive_element(self): r""" Get the primitive element $\theta$ for the number field $\mathbb{Q}(\theta)$ to which this algebraic number $\alpha$ belongs. Returns ======= AlgebraicNumber """ if self.is_primitive_element: return self return self.field_element([1, 0]) def to_primitive_element(self, radicals=True): r""" Convert ``self`` to an :py:class:`~.AlgebraicNumber` instance that is equal to its own primitive element. Explanation =========== If we represent $\alpha \in \mathbb{Q}(\theta)$, $\alpha \neq \theta$, construct a new :py:class:`~.AlgebraicNumber` that represents $\alpha \in \mathbb{Q}(\alpha)$. Examples ======== >>> from sympy import sqrt, to_number_field >>> from sympy.abc import x >>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) The :py:class:`~.AlgebraicNumber` ``a`` represents the number $\sqrt{2}$ in the field $\mathbb{Q}(\sqrt{2} + \sqrt{3})$. Rendering ``a`` as a polynomial, >>> a.as_poly().as_expr(x) x**3/2 - 9*x/2 reflects the fact that $\sqrt{2} = \theta^3/2 - 9 \theta/2$, where $\theta = \sqrt{2} + \sqrt{3}$. ``a`` is not equal to its own primitive element. Its minpoly >>> a.minpoly.as_poly().as_expr(x) x**4 - 10*x**2 + 1 is that of $\theta$. Converting to a primitive element, >>> a_prim = a.to_primitive_element() >>> a_prim.minpoly.as_poly().as_expr(x) x**2 - 2 we obtain an :py:class:`~.AlgebraicNumber` whose ``minpoly`` is that of the number itself. Parameters ========== radicals : boolean, optional (default=True) If ``True``, then we will try to return an :py:class:`~.AlgebraicNumber` whose ``root`` is an expression in radicals. If that is not possible (or if *radicals* is ``False``), ``root`` will be a :py:class:`~.ComplexRootOf`. Returns ======= AlgebraicNumber See Also ======== is_primitive_element """ if self.is_primitive_element: return self m = self.minpoly_of_element() r = self.to_root(radicals=radicals) return AlgebraicNumber((m, r)) def minpoly_of_element(self): r""" Compute the minimal polynomial for this algebraic number. Explanation =========== Recall that we represent an element $\alpha \in \mathbb{Q}(\theta)$. Our instance attribute ``self.minpoly`` is the minimal polynomial for our primitive element $\theta$. This method computes the minimal polynomial for $\alpha$. """ if self._own_minpoly is None: if self.is_primitive_element: self._own_minpoly = self.minpoly else: from sympy.polys.numberfields.minpoly import minpoly theta = self.primitive_element() self._own_minpoly = minpoly(self.as_expr(theta), polys=True) return self._own_minpoly def to_root(self, radicals=True, minpoly=None): """ Convert to an :py:class:`~.Expr` that is not an :py:class:`~.AlgebraicNumber`, specifically, either a :py:class:`~.ComplexRootOf`, or, optionally and where possible, an expression in radicals. Parameters ========== radicals : boolean, optional (default=True) If ``True``, then we will try to return the root as an expression in radicals. If that is not possible, we will return a :py:class:`~.ComplexRootOf`. minpoly : :py:class:`~.Poly` If the minimal polynomial for `self` has been pre-computed, it can be passed in order to save time. """ if self.is_primitive_element and not isinstance(self.root, AlgebraicNumber): return self.root m = minpoly or self.minpoly_of_element() roots = m.all_roots(radicals=radicals) if len(roots) == 1: return roots[0] ex = self.as_expr() for b in roots: if m.same_root(b, ex): return b
AlgebraicNumber
python
tiangolo__fastapi
fastapi/openapi/models.py
{ "start": 10160, "end": 10253 }
class ____(ParameterBase): name: str in_: ParameterInType = Field(alias="in")
Parameter
python
mlflow__mlflow
mlflow/tracking/fluent.py
{ "start": 132585, "end": 141664 }
class ____(LoggedModel): """ Wrapper around :py:class:`mlflow.entities.LoggedModel` to enable using Python ``with`` syntax. """ def __init__(self, logged_model: LoggedModel, set_by_user: bool): super().__init__(**logged_model.to_dictionary()) self.last_active_model_context = _ACTIVE_MODEL_CONTEXT.get() _set_active_model_id(self.model_id, set_by_user) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if is_in_databricks_model_serving_environment(): # create a new instance of ActiveModelContext to make sure the # environment variable is updated in databricks serving environment _ACTIVE_MODEL_CONTEXT.set( ActiveModelContext( model_id=self.last_active_model_context.model_id, set_by_user=self.last_active_model_context.set_by_user, ) ) else: _ACTIVE_MODEL_CONTEXT.set(self.last_active_model_context) # NB: This function is only intended to be used publicly by users to set the # active model ID. MLflow internally should NEVER call this function directly, # since we need to differentiate between user and system set active model IDs. # For MLflow internal usage, use `_set_active_model` instead. def set_active_model(*, name: str | None = None, model_id: str | None = None) -> ActiveModel: """ Set the active model with the specified name or model ID, and it will be used for linking traces that are generated during the lifecycle of the model. The return value can be used as a context manager within a ``with`` block; otherwise, you must call ``set_active_model()`` to update active model. Args: name: The name of the :py:class:`mlflow.entities.LoggedModel` to set as active. If a LoggedModel with the name does not exist, it will be created under the current experiment. If multiple LoggedModels with the name exist, the latest one will be set as active. model_id: The ID of the :py:class:`mlflow.entities.LoggedModel` to set as active. If no LoggedModel with the ID exists, an exception will be raised. Returns: :py:class:`mlflow.ActiveModel` object that acts as a context manager wrapping the LoggedModel's state. .. code-block:: python :test: :caption: Example import mlflow # Set the active model by name mlflow.set_active_model(name="my_model") # Set the active model by model ID model = mlflow.create_external_model(name="test_model") mlflow.set_active_model(model_id=model.model_id) # Use the active model in a context manager with mlflow.set_active_model(name="new_model"): print(mlflow.get_active_model_id()) # Traces are automatically linked to the active model mlflow.set_active_model(name="my_model") @mlflow.trace def predict(model_input): return model_input predict("abc") traces = mlflow.search_traces(model_id=mlflow.get_active_model_id(), return_type="list") assert len(traces) == 1 """ return _set_active_model(name=name, model_id=model_id, set_by_user=True) def _set_active_model( *, name: str | None = None, model_id: str | None = None, set_by_user: bool = False ) -> ActiveModel: if name is None and model_id is None: raise MlflowException.invalid_parameter_value( message="Either name or model_id must be provided", ) if model_id is not None: logged_model = mlflow.get_logged_model(model_id) if name is not None and logged_model.name != name: raise MlflowException.invalid_parameter_value( f"LoggedModel with model_id {model_id!r} has name {logged_model.name!r}, which does" f" not match the provided name {name!r}." ) elif name is not None: logged_models = mlflow.search_logged_models( filter_string=f"name='{name}'", max_results=2, output_format="list" ) if len(logged_models) > 1: _logger.warning( f"Multiple LoggedModels found with name {name!r}, setting the latest one as active " "model." ) if len(logged_models) == 0: _logger.info(f"LoggedModel with name {name!r} does not exist, creating one...") logged_model = mlflow.create_external_model(name=name) else: logged_model = logged_models[0] return ActiveModel(logged_model=logged_model, set_by_user=set_by_user) def _set_active_model_id(model_id: str, set_by_user: bool = False) -> None: """ Set the active model ID in the active model context and update the corresponding environment variable. This should only be used when we know the LoggedModel with the model_id exists. This function should be used inside MLflow to set the active model while not blocking other code execution. """ try: _ACTIVE_MODEL_CONTEXT.set(ActiveModelContext(model_id, set_by_user)) except Exception as e: _logger.warning(f"Failed to set active model ID to {model_id}, error: {e}") else: _logger.info(f"Active model is set to the logged model with ID: {model_id}") if not set_by_user: _logger.info( "Use `mlflow.set_active_model` to set the active model " "to a different one if needed." ) def _get_active_model_context() -> ActiveModelContext: """ Get the active model context. This is used internally by MLflow to manage the active model context. """ return _ACTIVE_MODEL_CONTEXT.get() def get_active_model_id() -> str | None: """ Get the active model ID. If no active model is set with ``set_active_model()``, the default active model is set using model ID from the environment variable ``MLFLOW_ACTIVE_MODEL_ID`` or the legacy environment variable ``_MLFLOW_ACTIVE_MODEL_ID``. If neither is set, return None. Note that this function only get the active model ID from the current thread. Returns: The active model ID if set, otherwise None. """ return _get_active_model_context().model_id def _get_active_model_id_global() -> str | None: """ Get the active model ID from the global context by checking all threads. This is useful when we need to get the active_model_id set by a different thread. """ # if the active model ID is set in the current thread, always use it if model_id_in_current_thread := get_active_model_id(): _logger.debug(f"Active model ID found in the current thread: {model_id_in_current_thread}") return model_id_in_current_thread model_ids = [ ctx.model_id for ctx in _ACTIVE_MODEL_CONTEXT.get_all_thread_values().values() if ctx.model_id is not None ] if model_ids: if len(set(model_ids)) > 1: _logger.debug( "Failed to get one active model id from all threads, multiple active model IDs " f"found: {set(model_ids)}." ) return return model_ids[0] _logger.debug("No active model ID found in any thread.") def clear_active_model() -> None: """ Clear the active model. This will clear the active model previously set by :py:func:`mlflow.set_active_model` or via the ``MLFLOW_ACTIVE_MODEL_ID`` environment variable or the ``_MLFLOW_ACTIVE_MODEL_ID`` legacy environment variable. from current thread. To temporarily switch the active model, use ``with mlflow.set_active_model(...)`` instead. .. code-block:: python :test: :caption: Example import mlflow # Set the active model by name mlflow.set_active_model(name="my_model") # Clear the active model mlflow.clear_active_model() # Check that the active model is None assert mlflow.get_active_model_id() is None # If you want to temporarily set the active model, # use `set_active_model` as a context manager instead with mlflow.set_active_model(name="my_model") as active_model: assert mlflow.get_active_model_id() == active_model.model_id assert mlflow.get_active_model_id() is None """ # reset the environment variables as well to avoid them being used when creating # ActiveModelContext MLFLOW_ACTIVE_MODEL_ID.unset() _MLFLOW_ACTIVE_MODEL_ID.unset() # Reset the active model context to avoid the active model ID set by other threads # to be used when creating a new ActiveModelContext _ACTIVE_MODEL_CONTEXT.reset() # set_by_user is False because this API clears the state of active model # and MLflow might still set the active model in cases like `load_model` _ACTIVE_MODEL_CONTEXT.set(ActiveModelContext(set_by_user=False)) _logger.info("Active model is cleared")
ActiveModel
python
doocs__leetcode
solution/0700-0799/0773.Sliding Puzzle/Solution2.py
{ "start": 0, "end": 1578 }
class ____: def slidingPuzzle(self, board: List[List[int]]) -> int: m, n = 2, 3 seq = [] start, end = '', '123450' for i in range(m): for j in range(n): if board[i][j] != 0: seq.append(board[i][j]) start += str(board[i][j]) def check(seq): n = len(seq) cnt = sum(seq[i] > seq[j] for i in range(n) for j in range(i, n)) return cnt % 2 == 0 def f(s): ans = 0 for i in range(m * n): if s[i] != '0': num = ord(s[i]) - ord('1') ans += abs(i // n - num // n) + abs(i % n - num % n) return ans if not check(seq): return -1 q = [(f(start), start)] dist = {start: 0} while q: _, state = heappop(q) if state == end: return dist[state] p1 = state.index('0') i, j = p1 // n, p1 % n s = list(state) for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]: x, y = i + a, j + b if 0 <= x < m and 0 <= y < n: p2 = x * n + y s[p1], s[p2] = s[p2], s[p1] next = ''.join(s) s[p1], s[p2] = s[p2], s[p1] if next not in dist or dist[next] > dist[state] + 1: dist[next] = dist[state] + 1 heappush(q, (dist[next] + f(next), next)) return -1
Solution
python
astropy__astropy
astropy/utils/masked/tests/test_containers.py
{ "start": 2222, "end": 4399 }
class ____: def setup_class(self): self.ra = np.array([3.0, 5.0, 0.0]) << u.hourangle self.dec = np.array([4.0, 12.0, 1.0]) << u.deg self.sc = SkyCoord(self.ra, self.dec) self.mask = np.array([False, False, True]) self.mra = Masked(self.ra, self.mask) self.mdec = Masked(self.dec, self.mask) self.msc = SkyCoord(self.mra, self.mdec) def test_initialization(self): check = self.msc.dec == self.mdec assert_array_equal(check.unmasked, np.ones(3, bool)) assert_array_equal(check.mask, self.mask) assert_array_equal(self.msc.data.lon, self.mra) assert_array_equal(self.msc.data.lat, self.mdec) def test_transformation(self): gcrs = self.sc.gcrs mgcrs = self.msc.gcrs assert_array_equal(mgcrs.data.lon.mask, self.msc.data.lon.mask) assert_array_equal(mgcrs.data.lon.unmasked, gcrs.data.lon) assert_array_equal(mgcrs.data.lat.unmasked, gcrs.data.lat) @pytest.mark.filterwarnings("ignore:.*ERFA.*distance overridden.*") def test_apply_space_motion(self): # Regression test for gh-13041. It is important that the # distance is missing here, so that a warning is raised. # Before gh-16224, the ERFA warning machinery let to an error. kwargs = dict( ra=[1, 2] * u.deg, dec=[3, 4] * u.deg, pm_ra_cosdec=[5, 6] * u.mas / u.yr, pm_dec=[1, 2] * u.mas / u.yr, obstime=Time(["2000-10-22T12:23:45", "2000-10-22T12:23:45"]), ) sc = SkyCoord(**kwargs) mask = np.array([False, True]) kwargs["pm_ra_cosdec"] = Masked(kwargs["pm_ra_cosdec"], mask=mask) kwargs["pm_dec"] = Masked(kwargs["pm_dec"], mask=mask) msc = SkyCoord(**kwargs) new_time = Time("2020-10-22T12:23:45") sc2 = sc.apply_space_motion(new_obstime=new_time) msc2 = msc.apply_space_motion(new_obstime=new_time) assert_array_equal(msc2.data.lon.mask, [False, True]) assert_array_equal(msc2.data.lon.unmasked, sc2.data.lon) assert_array_equal(msc2.data.lat.unmasked, sc2.data.lat)
TestSkyCoord
python
scipy__scipy
scipy/signal/tests/test_signaltools.py
{ "start": 43924, "end": 46959 }
class ____: def test_invalid_shapes(self, convapproach, xp): a = np.arange(1, 7).reshape((2, 3)) b = np.arange(-6, 0).reshape((3, 2)) with assert_raises(ValueError, match="For 'valid' mode, one must be at least " "as large as the other in every dimension"): convapproach(a, b, mode='valid') def test_invalid_shapes_axes(self, convapproach, xp): a = np.zeros([5, 6, 2, 1]) b = np.zeros([5, 6, 3, 1]) with assert_raises(ValueError, match=r"incompatible shapes for in1 and in2:" r" \(5L?, 6L?, 2L?, 1L?\) and" r" \(5L?, 6L?, 3L?, 1L?\)"): convapproach(a, b, axes=[0, 1]) @pytest.mark.parametrize('a,b', [([1], 2), (1, [2]), ([3], [[2]])]) def test_mismatched_dims(self, a, b, convapproach, xp): with assert_raises(ValueError, match="in1 and in2 should have the same" " dimensionality"): convapproach(a, b) def test_invalid_flags(self, convapproach, xp): with assert_raises(ValueError, match="acceptable mode flags are 'valid'," " 'same', or 'full'"): convapproach([1], [2], mode='chips') with assert_raises(ValueError, match="when provided, axes cannot be empty"): convapproach([1], [2], axes=[]) with assert_raises(ValueError, match="axes must be a scalar or " "iterable of integers"): convapproach([1], [2], axes=[[1, 2], [3, 4]]) with assert_raises(ValueError, match="axes must be a scalar or " "iterable of integers"): convapproach([1], [2], axes=[1., 2., 3., 4.]) with assert_raises(ValueError, match="axes exceeds dimensionality of input"): convapproach([1], [2], axes=[1]) with assert_raises(ValueError, match="axes exceeds dimensionality of input"): convapproach([1], [2], axes=[-2]) with assert_raises(ValueError, match="all axes must be unique"): convapproach([1], [2], axes=[0, 0]) @skip_xp_backends(np_only=True, reason="assertions may differ on backends") @pytest.mark.filterwarnings('ignore::DeprecationWarning') @pytest.mark.parametrize('dtype', [np.longdouble, np.clongdouble]) @make_xp_test_case(convolve, fftconvolve) def test_convolve_longdtype_input(dtype, xp): x = np.random.random((27, 27)).astype(dtype) y = np.random.random((4, 4)).astype(dtype) if np.iscomplexobj(dtype()): x += .1j y -= .1j res = fftconvolve(x, y) xp_assert_close(res, convolve(x, y, method='direct')) assert res.dtype == dtype
TestAllFreqConvolves
python
google__pytype
pytype/tools/xref/parse_args_test.py
{ "start": 127, "end": 1340 }
class ____(unittest.TestCase): """Test parse_args.parse_args.""" def test_parse_filename(self): _, _, pytype_opts = parse_args.parse_args(["a.py"]) self.assertEqual(pytype_opts.input, "a.py") def test_parse_no_filename(self): with self.assertRaises(SystemExit): parse_args.parse_args([]) def test_kythe_args(self): _, kythe_args, _ = parse_args.parse_args( ["a.py", "--kythe_corpus", "foo", "--kythe_root", "bar", "--kythe_path", "baz"]) self.assertEqual(kythe_args.corpus, "foo") self.assertEqual(kythe_args.root, "bar") self.assertEqual(kythe_args.path, "baz") def test_imports_info(self): # The code reads and validates an import map within pytype's setup, so we # need to provide a syntactically valid one as a file. with test_utils.Tempdir() as d: pyi_file = d.create_file("baz.pyi") imports_info = d.create_file("foo", f"bar {pyi_file}") _, _, opts = parse_args.parse_args( ["a.py", "--imports_info", imports_info]) self.assertEqual(opts.imports_map.items, {"bar": pyi_file}) self.assertTrue(opts.use_pickled_files) if __name__ == "__main__": unittest.main()
TestParseArgs
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_name04.py
{ "start": 315, "end": 1827 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_font04.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "bar"}) chart.axis_ids = [43944960, 45705472] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series({"values": "=Sheet1!$A$1:$A$5"}) chart.add_series({"values": "=Sheet1!$B$1:$B$5"}) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) chart.set_title( { "name": ["Sheet1", 0, 0], "name_font": {"bold": 0, "italic": 1}, } ) chart.set_x_axis( { "name": ["Sheet1", 1, 0], "name_font": {"bold": 0, "italic": 1}, } ) chart.set_y_axis( { "name": ["Sheet1", 2, 0], "name_font": {"bold": 1, "italic": 1}, } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 569397, "end": 570181 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "edges", "nodes", "page_info", "total_count", "viewer_has_reacted", ) edges = sgqlc.types.Field(sgqlc.types.list_of("ReactionEdge"), graphql_name="edges") nodes = sgqlc.types.Field(sgqlc.types.list_of("Reaction"), graphql_name="nodes") page_info = sgqlc.types.Field( sgqlc.types.non_null(PageInfo), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" ) viewer_has_reacted = sgqlc.types.Field( sgqlc.types.non_null(Boolean), graphql_name="viewerHasReacted" )
ReactionConnection
python
getsentry__sentry
src/sentry/sentry_apps/metrics.py
{ "start": 626, "end": 1310 }
class ____(EventLifecycleMetric): """An event under the Sentry App umbrella""" operation_type: SentryAppInteractionType event_type: str def get_metric_key(self, outcome: EventLifecycleOutcome) -> str: tokens = ("sentry_app", self.operation_type, str(outcome)) return ".".join(tokens) def get_metric_tags(self) -> Mapping[str, str]: return { "operation_type": self.operation_type, "event_type": self.event_type, } def get_extras(self) -> Mapping[str, Any]: return { "event_type": self.event_type, "operation_type": self.operation_type, }
SentryAppInteractionEvent
python
walkccc__LeetCode
solutions/1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target/1546.py
{ "start": 0, "end": 590 }
class ____: def maxNonOverlapping(self, nums: list[int], target: int) -> int: # Ending the subarray ASAP always has a better result. ans = 0 prefix = 0 prefixes = {0} # Greedily find the subarrays that equal to the target. for num in nums: # Check if there is a subarray ends in here and equals to the target. prefix += num if prefix - target in prefixes: # Find one and discard all the prefixes that have been used. ans += 1 prefix = 0 prefixes = {0} else: prefixes.add(prefix) return ans
Solution
python
astropy__astropy
astropy/units/function/logarithmic.py
{ "start": 6409, "end": 15195 }
class ____(FunctionQuantity): """A representation of a (scaled) logarithm of a number with a unit. Parameters ---------- value : number, `~astropy.units.Quantity`, `~astropy.units.LogQuantity`, or sequence of quantity-like. The numerical value of the logarithmic quantity. If a number or a `~astropy.units.Quantity` with a logarithmic unit, it will be converted to ``unit`` and the physical unit will be inferred from ``unit``. If a `~astropy.units.Quantity` with just a physical unit, it will converted to the logarithmic unit, after, if necessary, converting it to the physical unit inferred from ``unit``. unit : str, `~astropy.units.UnitBase`, or `~astropy.units.FunctionUnitBase`, optional For an `~astropy.units.FunctionUnitBase` instance, the physical unit will be taken from it; for other input, it will be inferred from ``value``. By default, ``unit`` is set by the subclass. dtype : `~numpy.dtype`, optional The ``dtype`` of the resulting Numpy array or scalar that will hold the value. If not provided, is is determined automatically from the input value. copy : bool, optional If `True` (default), then the value is copied. Otherwise, a copy will only be made if ``__array__`` returns a copy, if value is a nested sequence, or if a copy is needed to satisfy an explicitly given ``dtype``. (The `False` option is intended mostly for internal use, to speed up initialization where a copy is known to have been made. Use with care.) Examples -------- Typically, use is made of an `~astropy.units.FunctionQuantity` subclass, as in:: >>> import astropy.units as u >>> u.Magnitude(-2.5) <Magnitude -2.5 mag> >>> u.Magnitude(10.*u.count/u.second) <Magnitude -2.5 mag(ct / s)> >>> u.Decibel(1.*u.W, u.DecibelUnit(u.mW)) # doctest: +FLOAT_CMP <Decibel 30. dB(mW)> """ # only override of FunctionQuantity _unit_class = LogUnit # additions that work just for logarithmic units def __add__(self, other): # Add function units, thus multiplying physical units. If no unit is # given, assume dimensionless_unscaled; this will give the appropriate # exception in LogUnit.__add__. new_unit = self.unit + getattr(other, "unit", dimensionless_unscaled) # Add actual logarithmic values, rescaling, e.g., dB -> dex. result = self._function_view + getattr(other, "_function_view", other) return self._new_view(result, new_unit) def __radd__(self, other): return self.__add__(other) def __iadd__(self, other): new_unit = self.unit + getattr(other, "unit", dimensionless_unscaled) # Do calculation in-place using _function_view of array. function_view = self._function_view function_view += getattr(other, "_function_view", other) self._set_unit(new_unit) return self def __sub__(self, other): # Subtract function units, thus dividing physical units. new_unit = self.unit - getattr(other, "unit", dimensionless_unscaled) # Subtract actual logarithmic values, rescaling, e.g., dB -> dex. result = self._function_view - getattr(other, "_function_view", other) return self._new_view(result, new_unit) def __rsub__(self, other): new_unit = self.unit.__rsub__(getattr(other, "unit", dimensionless_unscaled)) result = self._function_view.__rsub__(getattr(other, "_function_view", other)) # Ensure the result is in right function unit scale # (with rsub, this does not have to be one's own). result = result.to(new_unit.function_unit) return self._new_view(result, new_unit) def __isub__(self, other): new_unit = self.unit - getattr(other, "unit", dimensionless_unscaled) # Do calculation in-place using _function_view of array. function_view = self._function_view function_view -= getattr(other, "_function_view", other) self._set_unit(new_unit) return self def __mul__(self, other): # Multiply by a float or a dimensionless quantity if isinstance(other, numbers.Number): # Multiplying a log means putting the factor into the exponent # of the unit new_physical_unit = self.unit.physical_unit**other result = self.view(np.ndarray) * other return self._new_view(result, self.unit._copy(new_physical_unit)) else: return super().__mul__(other) def __rmul__(self, other): return self.__mul__(other) def __imul__(self, other): if isinstance(other, numbers.Number): new_physical_unit = self.unit.physical_unit**other function_view = self._function_view function_view *= other self._set_unit(self.unit._copy(new_physical_unit)) return self else: return super().__imul__(other) def __truediv__(self, other): # Divide by a float or a dimensionless quantity if isinstance(other, numbers.Number): # Dividing a log means putting the denominator into the exponent # of the unit new_physical_unit = self.unit.physical_unit ** (1 / other) result = self.view(np.ndarray) / other return self._new_view(result, self.unit._copy(new_physical_unit)) else: return super().__truediv__(other) def __itruediv__(self, other): if isinstance(other, numbers.Number): new_physical_unit = self.unit.physical_unit ** (1 / other) function_view = self._function_view function_view /= other self._set_unit(self.unit._copy(new_physical_unit)) return self else: return super().__itruediv__(other) def __pow__(self, other): # We check if this power is OK by applying it first to the unit. try: other = float(other) except TypeError: return NotImplemented new_unit = self.unit**other new_value = self.view(np.ndarray) ** other return self._new_view(new_value, new_unit) def __ilshift__(self, other): try: other = Unit(other) except UnitTypeError: return NotImplemented if not isinstance(other, self._unit_class): return NotImplemented try: factor = self.unit.physical_unit._to(other.physical_unit) except UnitConversionError: # Maybe via equivalencies? Now we do make a temporary copy. try: value = self._to_value(other) except UnitConversionError: return NotImplemented self.view(np.ndarray)[...] = value else: self.view(np.ndarray)[...] += self.unit.from_physical(factor) self._set_unit(other) return self # Methods that do not work for function units generally but are OK for # logarithmic units as they imply differences and independence of # physical unit. def var(self, axis=None, dtype=None, out=None, ddof=0): unit = self.unit.function_unit**2 return self._wrap_function(np.var, axis, dtype, out=out, ddof=ddof, unit=unit) def std(self, axis=None, dtype=None, out=None, ddof=0): unit = self.unit._copy(dimensionless_unscaled) return self._wrap_function(np.std, axis, dtype, out=out, ddof=ddof, unit=unit) if NUMPY_LT_2_0: def ptp(self, axis=None, out=None): unit = self.unit._copy(dimensionless_unscaled) return self._wrap_function(np.ptp, axis, out=out, unit=unit) else: def __array_function__(self, function, types, args, kwargs): # TODO: generalize this to all supported functions! if function is np.ptp: unit = self.unit._copy(dimensionless_unscaled) return self._wrap_function(np.ptp, *args[1:], unit=unit, **kwargs) else: return super().__array_function__(function, types, args, kwargs) def diff(self, n=1, axis=-1): unit = self.unit._copy(dimensionless_unscaled) return self._wrap_function(np.diff, n, axis, unit=unit) def ediff1d(self, to_end=None, to_begin=None): unit = self.unit._copy(dimensionless_unscaled) return self._wrap_function(np.ediff1d, to_end, to_begin, unit=unit) _supported_functions = FunctionQuantity._supported_functions | { getattr(np, function) for function in ("var", "std", "ptp", "diff", "ediff1d") }
LogQuantity
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar05.py
{ "start": 315, "end": 1350 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar05.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "bar"}) chart.axis_ids = [64264064, 64447232] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series({"values": ["Sheet1", 0, 0, 4, 0]}) chart.add_series({"values": ["Sheet1", 0, 1, 4, 1]}) chart.add_series({"values": ["Sheet1", 0, 2, 4, 2]}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
weaviate__weaviate-python-client
weaviate/collections/queries/near_vector/query/async_.py
{ "start": 312, "end": 461 }
class ____( Generic[Properties, References], _NearVectorQueryExecutor[ConnectionAsync, Properties, References], ): pass
_NearVectorQueryAsync
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_manytomany.py
{ "start": 6218, "end": 10658 }
class ____(fixtures.MappedTest): """deals with inheritance and many-to-many relationships""" @classmethod def define_tables(cls, metadata): global foo, bar, blub, bar_foo, blub_bar, blub_foo # the 'data' columns are to appease SQLite which can't handle a blank # INSERT foo = Table( "foo", metadata, Column( "id", Integer, normalize_sequence(config, Sequence("foo_seq", optional=True)), primary_key=True, ), Column("data", String(20)), ) bar = Table( "bar", metadata, Column("id", Integer, ForeignKey("foo.id"), primary_key=True), Column("bar_data", String(20)), ) blub = Table( "blub", metadata, Column("id", Integer, ForeignKey("bar.id"), primary_key=True), Column("blub_data", String(20)), ) bar_foo = Table( "bar_foo", metadata, Column("bar_id", Integer, ForeignKey("bar.id")), Column("foo_id", Integer, ForeignKey("foo.id")), ) blub_bar = Table( "bar_blub", metadata, Column("blub_id", Integer, ForeignKey("blub.id")), Column("bar_id", Integer, ForeignKey("bar.id")), ) blub_foo = Table( "blub_foo", metadata, Column("blub_id", Integer, ForeignKey("blub.id")), Column("foo_id", Integer, ForeignKey("foo.id")), ) def test_basic(self): class Foo: def __init__(self, data=None): self.data = data def __repr__(self): return "Foo id %d, data %s" % (self.id, self.data) self.mapper_registry.map_imperatively(Foo, foo) class Bar(Foo): def __repr__(self): return "Bar id %d, data %s" % (self.id, self.data) self.mapper_registry.map_imperatively( Bar, bar, inherits=Foo, properties={ "foos": relationship(Foo, secondary=bar_foo, lazy="select") }, ) sess = fixture_session() b = Bar("bar #1") sess.add(b) b.foos.append(Foo("foo #1")) b.foos.append(Foo("foo #2")) sess.flush() compare = [repr(b)] + sorted([repr(o) for o in b.foos]) sess.expunge_all() result = sess.query(Bar).all() print(repr(result[0]) + repr(result[0].foos)) found = [repr(result[0])] + sorted([repr(o) for o in result[0].foos]) eq_(found, compare) def test_advanced(self): class Foo: def __init__(self, data=None): self.data = data def __repr__(self): return "Foo id %d, data %s" % (self.id, self.data) self.mapper_registry.map_imperatively(Foo, foo) class Bar(Foo): def __repr__(self): return "Bar id %d, data %s" % (self.id, self.data) self.mapper_registry.map_imperatively(Bar, bar, inherits=Foo) class Blub(Bar): def __repr__(self): return "Blub id %d, data %s, bars %s, foos %s" % ( self.id, self.data, repr([b for b in self.bars]), repr([f for f in self.foos]), ) self.mapper_registry.map_imperatively( Blub, blub, inherits=Bar, properties={ "bars": relationship(Bar, secondary=blub_bar, lazy="joined"), "foos": relationship(Foo, secondary=blub_foo, lazy="joined"), }, ) sess = fixture_session() f1 = Foo("foo #1") b1 = Bar("bar #1") b2 = Bar("bar #2") bl1 = Blub("blub #1") for o in (f1, b1, b2, bl1): sess.add(o) bl1.foos.append(f1) bl1.bars.append(b2) sess.flush() compare = repr(bl1) blubid = bl1.id sess.expunge_all() result = sess.query(Blub).all() print(result) self.assert_(repr(result[0]) == compare) sess.expunge_all() x = sess.query(Blub).filter_by(id=blubid).one() print(x) self.assert_(repr(x) == compare)
InheritTest3
python
ansible__ansible
lib/ansible/module_utils/facts/network/hurd.py
{ "start": 780, "end": 2962 }
class ____(Network): """ This is a GNU Hurd specific subclass of Network. It use fsysopts to get the ip address and support only pfinet. """ platform = 'GNU' _socket_dir = '/servers/socket/' def assign_network_facts(self, network_facts, fsysopts_path, socket_path): rc, out, err = self.module.run_command([fsysopts_path, '-L', socket_path]) # FIXME: build up a interfaces datastructure, then assign into network_facts network_facts['interfaces'] = [] for i in out.split(): if '=' in i and i.startswith('--'): k, v = i.split('=', 1) # remove '--' k = k[2:] if k == 'interface': # remove /dev/ from /dev/eth0 v = v[5:] network_facts['interfaces'].append(v) network_facts[v] = { 'active': True, 'device': v, 'ipv4': {}, 'ipv6': [], } current_if = v elif k == 'address': network_facts[current_if]['ipv4']['address'] = v elif k == 'netmask': network_facts[current_if]['ipv4']['netmask'] = v elif k == 'address6': address, prefix = v.split('/') network_facts[current_if]['ipv6'].append({ 'address': address, 'prefix': prefix, }) return network_facts def populate(self, collected_facts=None): network_facts = {} fsysopts_path = self.module.get_bin_path('fsysopts') if fsysopts_path is None: return network_facts socket_path = None for l in ('inet', 'inet6'): link = os.path.join(self._socket_dir, l) if os.path.exists(link): socket_path = link break if socket_path is None: return network_facts return self.assign_network_facts(network_facts, fsysopts_path, socket_path)
HurdPfinetNetwork
python
kamyu104__LeetCode-Solutions
Python/minimum-discards-to-balance-inventory.py
{ "start": 93, "end": 792 }
class ____(object): def minArrivalsToDiscard(self, arrivals, w, m): """ :type arrivals: List[int] :type w: int :type m: int :rtype: int """ result = 0 cnt = collections.defaultdict(int) for i in xrange(len(arrivals)): cnt[arrivals[i]] += 1 if cnt[arrivals[i]] == m+1: cnt[arrivals[i]] -= 1 arrivals[i] = 0 result += 1 if i-w+1 >= 0: if arrivals[i-w+1]: cnt[arrivals[i-w+1]] -= 1 if not cnt[arrivals[i-w+1]]: del cnt[arrivals[i-w+1]] return result
Solution
python
joke2k__faker
tests/providers/test_phone_number.py
{ "start": 14019, "end": 15030 }
class ____: def test_phone_number(self, faker, num_samples): pattern_no_whitespaces: Pattern = re.compile( r"^0\d{9}$", ) pattern_no_country_prefix: Pattern = re.compile( r"^0\d \d{2} \d{2} \d{2} \d{2}$", ) pattern_country_prefix_1: Pattern = re.compile( r"^\+33 \(0\)\d \d{2} \d{2} \d{2} \d{2}$", ) pattern_country_prefix_2: Pattern = re.compile( r"^\+33 \d \d{2} \d{2} \d{2} \d{2}$", ) patterns = [ pattern_no_whitespaces, pattern_no_country_prefix, pattern_country_prefix_1, pattern_country_prefix_2, ] for _ in range(num_samples): phone_number = faker.phone_number() pattern_is_found = False for pattern in patterns: if re.match(pattern, phone_number): pattern_is_found = True break assert pattern_is_found
TestFrFr
python
getsentry__sentry
src/sentry/releases/endpoints/project_release_file_details.py
{ "start": 2296, "end": 7258 }
class ____: """Shared functionality of ProjectReleaseFileDetails and OrganizationReleaseFileDetails Only has class methods, but keep it as a class to be consistent with ReleaseFilesMixin. """ @staticmethod def download(releasefile): file = releasefile.file fp = file.getfile() response = FileResponse( fp, content_type=file.headers.get("content-type", "application/octet-stream"), ) response["Content-Length"] = file.size response["Content-Disposition"] = 'attachment; filename="%s"' % posixpath.basename( " ".join(releasefile.name.split()) ) return response @staticmethod def download_from_archive(release, entry): archive_ident = entry["archive_ident"] archive_file = ReleaseFile.objects.get(release_id=release.id, ident=archive_ident) archive_file_fp = archive_file.file.getfile() fp = ZipFile(archive_file_fp).open(entry["filename"]) headers = entry.get("headers", {}) response = FileResponse( ClosesDependentFiles(fp, archive_file_fp), content_type=headers.get("content-type", "application/octet-stream"), ) response["Content-Length"] = entry["size"] response["Content-Disposition"] = 'attachment; filename="%s"' % posixpath.basename( " ".join(entry["filename"].split()) ) return response @staticmethod def _get_releasefile(release: Release, file_id: str, index_op=_get_from_index): """Fetch ReleaseFile either from db or from artifact_index""" try: id = decode_release_file_id(file_id) except ValueError: raise ResourceDoesNotExist if isinstance(id, int): try: releasefile = ReleaseFile.public_objects.get(release_id=release.id, id=file_id) maybe_renew_releasefiles([releasefile]) return releasefile except ReleaseFile.DoesNotExist: raise ResourceDoesNotExist else: dist, url = id if dist is not None: # NOTE: Could do one less query if `read_artifact_index` accepted # `dist_name` try: dist = Distribution.objects.get( organization_id=release.organization_id, name=dist, release=release ) except Distribution.DoesNotExist: raise ResourceDoesNotExist return index_op(release, dist, url) @classmethod def get_releasefile(cls, request, release, file_id, check_permission_fn): download_requested = request.GET.get("download") is not None getter = _entry_from_index if download_requested else _get_from_index releasefile = cls._get_releasefile(release, file_id, getter) if download_requested and check_permission_fn(): if isinstance(releasefile, ReleaseFile): return cls.download(releasefile) else: return cls.download_from_archive(release, releasefile) elif download_requested: return Response(status=403) return Response(serialize(releasefile, request.user)) @staticmethod def update_releasefile(request, release, file_id): try: int(file_id) except ValueError: raise ParseError(INVALID_UPDATE_MESSAGE) try: releasefile = ReleaseFile.public_objects.get(release_id=release.id, id=file_id) except ReleaseFile.DoesNotExist: raise ResourceDoesNotExist serializer = ReleaseFileSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=400) result = serializer.validated_data releasefile.update(name=result["name"]) return Response(serialize(releasefile, request.user)) @classmethod def delete_releasefile(cls, release, file_id): result = cls._get_releasefile(release, file_id, delete_from_artifact_index) if result is True: # was successfully deleted from index return Response(status=204) if result is False: # was not found in index return Response(status=404) # At this point, assume that result is individual release file, not an archived artifact releasefile = result try: releasefile = ReleaseFile.public_objects.get(release_id=release.id, id=file_id) except ReleaseFile.DoesNotExist: raise ResourceDoesNotExist file = releasefile.file # TODO(dcramer): this doesnt handle a failure from file.delete() to # the actual deletion of the db row releasefile.delete() file.delete() return Response(status=204) @region_silo_endpoint
ReleaseFileDetailsMixin
python
huggingface__transformers
tests/models/t5gemma/test_modeling_t5gemma.py
{ "start": 1589, "end": 22698 }
class ____: config_class = T5GemmaConfig module_config_class = T5GemmaModuleConfig if is_torch_available(): model_class = T5GemmaModel causal_lm_class = T5GemmaForConditionalGeneration sequence_classification_class = T5GemmaForSequenceClassification token_classification_class = T5GemmaForTokenClassification def __init__( self, parent, batch_size=13, is_training=True, use_attention_mask=True, use_labels=True, vocab_size=99, # decoder-specific seq_length=7, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, num_key_value_heads=2, intermediate_size=37, # encoder-specific encoder_seq_length=7, encoder_hidden_size=32, encoder_num_hidden_layers=2, encoder_num_attention_heads=4, encoder_num_key_value_heads=2, encoder_intermediate_size=37, # common hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, # special ids eos_token_id=1, pad_token_id=0, bos_token_id=2, ): self.parent = parent self.batch_size = batch_size self.is_training = is_training self.use_attention_mask = use_attention_mask self.use_labels = use_labels self.vocab_size = vocab_size # decoder self.seq_length = seq_length self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.intermediate_size = intermediate_size # encoder self.encoder_seq_length = encoder_seq_length self.encoder_hidden_size = encoder_hidden_size self.encoder_num_hidden_layers = encoder_num_hidden_layers self.encoder_num_attention_heads = encoder_num_attention_heads self.encoder_num_key_value_heads = encoder_num_key_value_heads self.encoder_intermediate_size = encoder_intermediate_size # common self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope self.head_dim = self.hidden_size // self.num_attention_heads # assume encoder and decoder have the same head dimension. assert self.head_dim == self.encoder_hidden_size // self.encoder_num_attention_heads # special ids self.eos_token_id = eos_token_id self.pad_token_id = pad_token_id self.bos_token_id = bos_token_id # assume the number of attention heads are the same across encoder and decoder # only used for generation testing purpose. assert self.num_attention_heads == self.encoder_num_attention_heads def get_encoder_config(self): return self.module_config_class( vocab_size=self.vocab_size, hidden_size=self.encoder_hidden_size, num_hidden_layers=self.encoder_num_hidden_layers, num_attention_heads=self.encoder_num_attention_heads, num_key_value_heads=self.encoder_num_key_value_heads, intermediate_size=self.encoder_intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=False, initializer_range=self.initializer_range, head_dim=self.head_dim, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, pad_token_id=self.pad_token_id, ) def get_decoder_config(self): return self.module_config_class( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, num_key_value_heads=self.num_key_value_heads, intermediate_size=self.intermediate_size, cross_attention_hidden_size=self.encoder_hidden_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=True, initializer_range=self.initializer_range, head_dim=self.head_dim, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, pad_token_id=self.pad_token_id, ) def get_config(self, is_encoder_decoder=True): return self.config_class( encoder=self.get_encoder_config(), decoder=self.get_decoder_config(), is_encoder_decoder=is_encoder_decoder, # Used for generation test. num_attention_heads=self.num_attention_heads, num_key_value_heads=self.num_key_value_heads, vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, ) def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size) decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) # Remove BOS symbols from inputs. input_ids = torch.where(input_ids == self.bos_token_id, 42, input_ids) decoder_input_ids = torch.where(decoder_input_ids == self.bos_token_id, 42, decoder_input_ids) # Avoid leading PAD tokens from inputs. # `T5GemmaForTokenClassification` and `T5GemmaForSequenceClassification` specify `use_cache=False` when # calling `self.model`. For `self.use_attention_mask=False` case below, the model goes through # `make_default_2d_attention_mask`. When there are some pad tokens at the beginning of a sequence, it can't # attend to any place, and the computed mask `[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38]` # causes larger differences in some equivalence tests. # Let's avoid such leading PAD tokens. decoder_input_ids[:, 0] = self.pad_token_id + 1 attention_mask = None decoder_attention_mask = None if self.use_attention_mask: attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2) decoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) lm_labels = None if self.use_labels: lm_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) config = self.get_config() return ( config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ) = config_and_inputs inputs_dict = { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } return config, inputs_dict def create_and_check_model( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): model = self.model_class(config=config).to(torch_device).eval() result = model( input_ids=input_ids, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, ) decoder_output = result.last_hidden_state decoder_past = result.past_key_values encoder_output = result.encoder_last_hidden_state self.parent.assertEqual( encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.encoder_hidden_size) ) self.parent.assertEqual(decoder_output.size(), (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertIsNotNone(decoder_past) self.parent.assertEqual(len(decoder_past.self_attention_cache), config.decoder.num_hidden_layers) self.parent.assertEqual(len(decoder_past.cross_attention_cache), config.decoder.num_hidden_layers) def check_prepare_lm_labels_via_shift_left( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): model = self.model_class(config=config).to(torch_device).eval() # _shift_right should be called on labels shifted_labels = model._shift_right(lm_labels) # first token should be decoder_start_token_id self.parent.assertTrue(torch.all(shifted_labels[:, 0] == config.decoder.bos_token_id)) # the rest should be the labels shifted by one, with -100 replaced by pad_token_id labels_without_ignore_index = lm_labels.masked_fill(lm_labels == -100, config.decoder.pad_token_id) self.parent.assertTrue(torch.all(shifted_labels[:, 1:] == labels_without_ignore_index[:, :-1])) def create_and_check_with_lm_head( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): model = self.causal_lm_class(config=config).to(torch_device).eval() outputs = model( input_ids=input_ids, decoder_input_ids=decoder_input_ids, attention_mask=attention_mask, decoder_attention_mask=decoder_attention_mask, labels=lm_labels, ) self.parent.assertEqual(len(outputs), 5) self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertEqual(outputs["loss"].size(), ()) def create_and_check_with_sequence_classification_head( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): labels = torch.tensor([1] * self.batch_size, dtype=torch.long, device=torch_device) model = self.sequence_classification_class(config=config).to(torch_device).eval() outputs = model( input_ids=input_ids, decoder_input_ids=input_ids, labels=labels, ) self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, config.num_labels)) self.parent.assertEqual(outputs["loss"].size(), ()) def create_and_check_encoderonly_for_sequence_classification_head( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, is_encoder_decoder, ): labels = torch.tensor([1] * self.batch_size, dtype=torch.long, device=torch_device) model = self.sequence_classification_class(config=config, is_encoder_decoder=is_encoder_decoder) model = model.to(torch_device).eval() outputs = model( input_ids=input_ids, decoder_input_ids=input_ids, labels=labels, ) self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, config.num_labels)) self.parent.assertEqual(outputs["loss"].size(), ()) def create_and_check_encoderonly_for_token_classification_head( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, is_encoder_decoder, ): labels = torch.tensor([1] * self.seq_length * self.batch_size, dtype=torch.long, device=torch_device) model = self.token_classification_class(config=config, is_encoder_decoder=is_encoder_decoder) model = model.to(torch_device).eval() outputs = model( input_ids=input_ids, decoder_input_ids=input_ids, labels=labels, ) self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.seq_length, config.num_labels)) self.parent.assertEqual(outputs["loss"].size(), ()) def create_and_check_decoder_model_past( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): model = self.model_class(config=config).get_decoder().to(torch_device).eval() encoder_hidden_states = torch.ones( (self.batch_size, self.encoder_seq_length, self.encoder_hidden_size), dtype=torch.float32 ).to(torch_device) # first forward pass outputs = model(input_ids, encoder_hidden_states=encoder_hidden_states, use_cache=True) outputs_use_cache_conf = model(input_ids, encoder_hidden_states=encoder_hidden_states) outputs_no_past = model(input_ids, encoder_hidden_states=encoder_hidden_states, use_cache=False) self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) output, past_key_values = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) # append to next input_ids and next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) output_from_no_past = model(next_input_ids, encoder_hidden_states=encoder_hidden_states)["last_hidden_state"] output_from_past = model( next_tokens, encoder_hidden_states=encoder_hidden_states, past_key_values=past_key_values )["last_hidden_state"] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) def create_and_check_decoder_model_attention_mask_past( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): model = self.model_class(config=config).get_decoder().to(torch_device).eval() encoder_hidden_states = torch.ones( (self.batch_size, self.encoder_seq_length, self.encoder_hidden_size), dtype=torch.float32 ).to(torch_device) # create attention mask attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device) half_seq_length = input_ids.shape[-1] // 2 attn_mask[:, half_seq_length:] = 0 # first forward pass output, past_key_values = model( input_ids, encoder_hidden_states=encoder_hidden_states, attention_mask=attn_mask, use_cache=True ).to_tuple() # create hypothetical next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size) # change a random masked slice from input_ids random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1 random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1) input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens # append to next input_ids and attn_mask next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) attn_mask = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)], dim=1, ) # get two different outputs output_from_no_past = model( next_input_ids, encoder_hidden_states=encoder_hidden_states, attention_mask=attn_mask )["last_hidden_state"] output_from_past = model( next_tokens, encoder_hidden_states=encoder_hidden_states, past_key_values=past_key_values, attention_mask=attn_mask, )["last_hidden_state"] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach() output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) def create_and_check_decoder_model_past_large_inputs( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): model = self.model_class(config=config).get_decoder().to(torch_device).eval() encoder_hidden_states = torch.ones( (self.batch_size, self.encoder_seq_length, self.encoder_hidden_size), dtype=torch.float32 ).to(torch_device) # first forward pass outputs = model( input_ids, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask, use_cache=True ) output, past_key_values = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) # append to next input_ids and next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) next_attention_mask = torch.cat([attention_mask, next_mask], dim=-1) output_from_no_past = model( next_input_ids, encoder_hidden_states=encoder_hidden_states, attention_mask=next_attention_mask )["last_hidden_state"] output_from_past = model( next_tokens, encoder_hidden_states=encoder_hidden_states, attention_mask=next_attention_mask, past_key_values=past_key_values, )["last_hidden_state"] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach() output_from_past_slice = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) def create_and_check_generate_with_past_key_values( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): model = self.causal_lm_class(config=config).to(torch_device).eval() torch.manual_seed(0) output_without_past_cache = model.generate( input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False ) torch.manual_seed(0) output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True) self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache)) def create_and_check_model_fp16_forward( self, config, input_ids, decoder_input_ids, attention_mask, decoder_attention_mask, lm_labels, ): model = self.model_class(config=config).to(torch_device).half().eval() output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)["last_hidden_state"] self.parent.assertFalse(torch.isnan(output).any().item()) @require_torch
T5GemmaModelTester
python
dask__dask
dask/multiprocessing.py
{ "start": 1576, "end": 8519 }
class ____(Exception): """Remote Exception Contains the exception and traceback from a remotely run task """ def __init__(self, exception, traceback): self.exception = exception self.traceback = traceback def __str__(self): return f"{self.exception}\n\nTraceback\n---------\n{self.traceback}" def __dir__(self): return sorted(set(dir(type(self)) + list(self.__dict__) + dir(self.exception))) def __getattr__(self, key): try: return object.__getattribute__(self, key) except AttributeError: return getattr(self.exception, key) exceptions: dict[type[Exception], type[Exception]] = {} def remote_exception(exc: Exception, tb) -> Exception: """Metaclass that wraps exception type in RemoteException""" if type(exc) in exceptions: typ = exceptions[type(exc)] return typ(exc, tb) else: try: typ = type( exc.__class__.__name__, (RemoteException, type(exc)), {"exception_type": type(exc)}, ) exceptions[type(exc)] = typ return typ(exc, tb) except TypeError: return exc try: import tblib.pickling_support tblib.pickling_support.install() def _pack_traceback(tb): return tb except ImportError: def _pack_traceback(tb): return "".join(traceback.format_tb(tb)) def reraise(exc, tb=None): exc = remote_exception(exc, tb) raise exc def pack_exception(e, dumps): exc_type, exc_value, exc_traceback = sys.exc_info() tb = _pack_traceback(exc_traceback) try: result = dumps((e, tb)) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() tb = _pack_traceback(exc_traceback) result = dumps((e, tb)) return result _CONTEXT_UNSUPPORTED = """\ The 'multiprocessing.context' configuration option will be ignored on Python 2 and on Windows, because they each only support a single context. """ def get_context(): """Return the current multiprocessing context.""" # fork context does fork()-without-exec(), which can lead to deadlocks, # so default to "spawn". context_name = config.get("multiprocessing.context", "spawn") if sys.platform == "win32": if context_name != "spawn": # Only spawn is supported on Win32, can't change it: warn(_CONTEXT_UNSUPPORTED, UserWarning) return multiprocessing else: return multiprocessing.get_context(context_name) def get( dsk: Mapping, keys: Sequence[Key] | Key, num_workers=None, func_loads=None, func_dumps=None, optimize_graph=True, pool=None, initializer=None, chunksize=None, **kwargs, ): """Multiprocessed get function appropriate for Bags Parameters ---------- dsk : dict dask graph keys : object or list Desired results from graph num_workers : int Number of worker processes (defaults to number of cores) func_dumps : function Function to use for function serialization (defaults to cloudpickle.dumps) func_loads : function Function to use for function deserialization (defaults to cloudpickle.loads) optimize_graph : bool If True [default], `fuse` is applied to the graph before computation. pool : Executor or Pool Some sort of `Executor` or `Pool` to use initializer: function Ignored if ``pool`` has been set. Function to initialize a worker process before running any tasks in it. chunksize: int, optional Size of chunks to use when dispatching work. Defaults to 6 as some batching is helpful. If -1, will be computed to evenly divide ready work across workers. """ chunksize = chunksize or config.get("chunksize", 6) pool = pool or config.get("pool", None) initializer = initializer or config.get("multiprocessing.initializer", None) num_workers = num_workers or config.get("num_workers", None) or CPU_COUNT if pool is None: # In order to get consistent hashing in subprocesses, we need to set a # consistent seed for the Python hash algorithm. Unfortunately, there # is no way to specify environment variables only for the Pool # processes, so we have to rely on environment variables being # inherited. if os.environ.get("PYTHONHASHSEED") in (None, "0"): # This number is arbitrary; it was chosen to commemorate # https://github.com/dask/dask/issues/6640. os.environ["PYTHONHASHSEED"] = "6640" context = get_context() initializer = partial(initialize_worker_process, user_initializer=initializer) pool = ProcessPoolExecutor( num_workers, mp_context=context, initializer=initializer ) cleanup = True else: if initializer is not None: warn( "The ``initializer`` argument is ignored when ``pool`` is provided. " "The user should configure ``pool`` with the needed ``initializer`` " "on creation." ) if isinstance(pool, multiprocessing.pool.Pool): pool = MultiprocessingPoolExecutor(pool) cleanup = False if hasattr(dsk, "__dask_graph__"): dsk = dsk.__dask_graph__() dsk = ensure_dict(dsk) dsk2, dependencies = cull(dsk, keys) if optimize_graph: dsk3, dependencies = fuse(dsk2, keys, dependencies) else: dsk3 = dsk2 # We specify marshalling functions in order to catch serialization # errors and report them to the user. loads = func_loads or config.get("func_loads", None) or _loads dumps = func_dumps or config.get("func_dumps", None) or _dumps # Note former versions used a multiprocessing Manager to share # a Queue between parent and workers, but this is fragile on Windows # (issue #1652). try: # Run result = get_async( pool.submit, pool._max_workers, dsk3, keys, get_id=_process_get_id, dumps=dumps, loads=loads, pack_exception=pack_exception, raise_exception=reraise, chunksize=chunksize, **kwargs, ) finally: if cleanup: pool.shutdown() return result def default_initializer(): # If Numpy is already imported, presumably its random state was # inherited from the parent => re-seed it. np = sys.modules.get("numpy") if np is not None: np.random.seed() def initialize_worker_process(user_initializer=None): """ Initialize a worker process before running any tasks in it. """ default_initializer() if user_initializer is not None: user_initializer()
RemoteException
python
sphinx-doc__sphinx
sphinx/builders/linkcheck.py
{ "start": 11864, "end": 11952 }
class ____(NamedTuple): next_check: float hyperlink: Hyperlink | None
CheckRequest
python
run-llama__llama_index
llama-index-core/llama_index/core/base/llms/types.py
{ "start": 20564, "end": 21045 }
class ____(BaseModel): """Chat response.""" message: ChatMessage raw: Optional[Any] = None delta: Optional[str] = None logprobs: Optional[List[List[LogProb]]] = None additional_kwargs: dict = Field(default_factory=dict) def __str__(self) -> str: return str(self.message) ChatResponseGen = Generator[ChatResponse, None, None] ChatResponseAsyncGen = AsyncGenerator[ChatResponse, None] # ===== Generic Model Output - Completion =====
ChatResponse
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0009_added_external_version_type.py
{ "start": 150, "end": 1252 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0008_remove-version-tags"), ] operations = [ migrations.AlterField( model_name="version", name="type", field=models.CharField( choices=[ ("branch", "Branch"), ("tag", "Tag"), ("external", "External"), ("unknown", "Unknown"), ], default="unknown", max_length=20, verbose_name="Type", ), ), migrations.AlterField( model_name="versionautomationrule", name="version_type", field=models.CharField( choices=[ ("branch", "Branch"), ("tag", "Tag"), ("external", "External"), ("unknown", "Unknown"), ], max_length=32, verbose_name="Version type", ), ), ]
Migration
python
huggingface__transformers
src/transformers/models/informer/modeling_informer.py
{ "start": 3437, "end": 5178 }
class ____(nn.Module): """ Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by subtracting from the mean and dividing by the standard deviation. """ def __init__(self, config: InformerConfig): super().__init__() self.dim = config.scaling_dim if hasattr(config, "scaling_dim") else 1 self.keepdim = config.keepdim if hasattr(config, "keepdim") else True self.minimum_scale = config.minimum_scale if hasattr(config, "minimum_scale") else 1e-5 def forward( self, data: torch.Tensor, observed_indicator: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Parameters: data (`torch.Tensor` of shape `(batch_size, sequence_length, num_input_channels)`): input for Batch norm calculation observed_indicator (`torch.BoolTensor` of shape `(batch_size, sequence_length, num_input_channels)`): Calculating the scale on the observed indicator. Returns: tuple of `torch.Tensor` of shapes (`(batch_size, sequence_length, num_input_channels)`,`(batch_size, 1, num_input_channels)`, `(batch_size, 1, num_input_channels)`) """ denominator = observed_indicator.sum(self.dim, keepdim=self.keepdim) denominator = denominator.clamp_min(1.0) loc = (data * observed_indicator).sum(self.dim, keepdim=self.keepdim) / denominator variance = (((data - loc) * observed_indicator) ** 2).sum(self.dim, keepdim=self.keepdim) / denominator scale = torch.sqrt(variance + self.minimum_scale) return (data - loc) / scale, loc, scale
InformerStdScaler
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/dataflow.py
{ "start": 23479, "end": 29380 }
class ____(BaseTrigger): """ Trigger that checks for autoscaling events associated with a Dataflow job. :param job_id: Required. ID of the job. :param project_id: Required. The Google Cloud project ID in which the job was started. :param location: Optional. The location where the job is executed. If set to None then the value of DEFAULT_DATAFLOW_LOCATION will be used. :param gcp_conn_id: The connection ID to use for connecting to Google Cloud. :param poll_sleep: Time (seconds) to wait between two consecutive calls to check the job. :param impersonation_chain: Optional. Service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param fail_on_terminal_state: If set to True the trigger will yield a TriggerEvent with error status if the job reaches a terminal state. """ def __init__( self, job_id: str, project_id: str | None, location: str = DEFAULT_DATAFLOW_LOCATION, gcp_conn_id: str = "google_cloud_default", poll_sleep: int = 10, impersonation_chain: str | Sequence[str] | None = None, fail_on_terminal_state: bool = True, ): super().__init__() self.project_id = project_id self.job_id = job_id self.location = location self.gcp_conn_id = gcp_conn_id self.poll_sleep = poll_sleep self.impersonation_chain = impersonation_chain self.fail_on_terminal_state = fail_on_terminal_state def serialize(self) -> tuple[str, dict[str, Any]]: """Serialize class arguments and classpath.""" return ( "airflow.providers.google.cloud.triggers.dataflow.DataflowJobAutoScalingEventTrigger", { "project_id": self.project_id, "job_id": self.job_id, "location": self.location, "gcp_conn_id": self.gcp_conn_id, "poll_sleep": self.poll_sleep, "impersonation_chain": self.impersonation_chain, "fail_on_terminal_state": self.fail_on_terminal_state, }, ) async def run(self): """ Loop until a terminal job status or any autoscaling events are returned. Yields a TriggerEvent with success status, if the client returns any autoscaling events and fail_on_terminal_state attribute is False. Yields a TriggerEvent with error status, if the client returns a job status with a terminal state value and fail_on_terminal_state attribute is True. Yields a TriggerEvent with error status, if any exception is raised while looping. In any other case the Trigger will wait for a specified amount of time stored in self.poll_sleep variable. """ try: while True: job_status = await self.async_hook.get_job_status( job_id=self.job_id, project_id=self.project_id, location=self.location, ) autoscaling_events = await self.list_job_autoscaling_events() if self.fail_on_terminal_state and job_status.name in DataflowJobStatus.TERMINAL_STATES: yield TriggerEvent( { "status": "error", "message": f"Job with id '{self.job_id}' is already in terminal state: {job_status.name}", "result": None, } ) return if autoscaling_events: yield TriggerEvent( { "status": "success", "message": f"Detected {len(autoscaling_events)} autoscaling events for job '{self.job_id}'", "result": autoscaling_events, } ) return self.log.info("Sleeping for %s seconds.", self.poll_sleep) await asyncio.sleep(self.poll_sleep) except Exception as e: self.log.error("Exception occurred while checking for job's autoscaling events!") yield TriggerEvent({"status": "error", "message": str(e), "result": None}) async def list_job_autoscaling_events(self) -> list[dict[str, str | dict]]: """Wait for the Dataflow client response and then return it in a serialized list.""" job_response: ListJobMessagesAsyncPager = await self.async_hook.list_job_messages( job_id=self.job_id, project_id=self.project_id, location=self.location, ) return self._get_autoscaling_events_from_job_response(job_response) def _get_autoscaling_events_from_job_response( self, job_response: ListJobMessagesAsyncPager ) -> list[dict[str, str | dict]]: """Return a list of serialized AutoscalingEvent objects.""" return [AutoscalingEvent.to_dict(event) for event in job_response.autoscaling_events] @cached_property def async_hook(self) -> AsyncDataflowHook: return AsyncDataflowHook( gcp_conn_id=self.gcp_conn_id, poll_sleep=self.poll_sleep, impersonation_chain=self.impersonation_chain, )
DataflowJobAutoScalingEventTrigger
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/build_systems/python.py
{ "start": 329, "end": 416 }
class ____(PackageBase): def test_imports(self) -> None: pass
PythonExtension
python
ethereum__web3.py
web3/_utils/threads.py
{ "start": 3352, "end": 4235 }
class ____(threading.Thread): def __init__(self, interval: int, callback: Callable[..., Any], *args: Any) -> None: threading.Thread.__init__(self) self.callback = callback self.terminate_event = threading.Event() self.interval = interval self.args = args def run(self) -> None: while not self.terminate_event.is_set(): self.callback(*self.args) self.terminate_event.wait(self.interval) def stop(self) -> None: self.terminate_event.set() def spawn( target: Callable[..., TReturn], *args: Any, thread_class: type[ThreadWithReturn[TReturn]] = ThreadWithReturn, **kwargs: Any, ) -> ThreadWithReturn[TReturn]: thread = thread_class( target=target, args=args, kwargs=kwargs, ) thread.daemon = True thread.start() return thread
TimerClass
python
ray-project__ray
rllib/policy/policy_map.py
{ "start": 492, "end": 10247 }
class ____(dict): """Maps policy IDs to Policy objects. Thereby, keeps n policies in memory and - when capacity is reached - writes the least recently used to disk. This allows adding 100s of policies to a Algorithm for league-based setups w/o running out of memory. """ def __init__( self, *, capacity: int = 100, policy_states_are_swappable: bool = False, # Deprecated args. worker_index=None, num_workers=None, policy_config=None, session_creator=None, seed=None, ): """Initializes a PolicyMap instance. Args: capacity: The size of the Policy object cache. This is the maximum number of policies that are held in RAM memory. When reaching this capacity, the least recently used Policy's state will be stored in the Ray object store and recovered from there when being accessed again. policy_states_are_swappable: Whether all Policy objects in this map can be "swapped out" via a simple `state = A.get_state(); B.set_state(state)`, where `A` and `B` are policy instances in this map. You should set this to True for significantly speeding up the PolicyMap's cache lookup times, iff your policies all share the same neural network architecture and optimizer types. If True, the PolicyMap will not have to garbage collect old, least recently used policies, but instead keep them in memory and simply override their state with the state of the most recently accessed one. For example, in a league-based training setup, you might have 100s of the same policies in your map (playing against each other in various combinations), but all of them share the same state structure (are "swappable"). """ if policy_config is not None: deprecation_warning( old="PolicyMap(policy_config=..)", error=True, ) super().__init__() self.capacity = capacity if any( i is not None for i in [policy_config, worker_index, num_workers, session_creator, seed] ): deprecation_warning( old="PolicyMap([deprecated args]...)", new="PolicyMap(capacity=..., policy_states_are_swappable=...)", error=False, ) self.policy_states_are_swappable = policy_states_are_swappable # The actual cache with the in-memory policy objects. self.cache: Dict[str, Policy] = {} # Set of keys that may be looked up (cached or not). self._valid_keys: Set[str] = set() # The doubly-linked list holding the currently in-memory objects. self._deque = deque() # Ray object store references to the stashed Policy states. self._policy_state_refs = {} # Lock used for locking some methods on the object-level. # This prevents possible race conditions when accessing the map # and the underlying structures, like self._deque and others. self._lock = threading.RLock() @with_lock @override(dict) def __getitem__(self, item: PolicyID): # Never seen this key -> Error. if item not in self._valid_keys: raise KeyError( f"PolicyID '{item}' not found in this PolicyMap! " f"IDs stored in this map: {self._valid_keys}." ) # Item already in cache -> Rearrange deque (promote `item` to # "most recently used") and return it. if item in self.cache: self._deque.remove(item) self._deque.append(item) return self.cache[item] # Item not currently in cache -> Get from stash and - if at capacity - # remove leftmost one. if item not in self._policy_state_refs: raise AssertionError( f"PolicyID {item} not found in internal Ray object store cache!" ) policy_state = ray.get(self._policy_state_refs[item]) policy = None # We are at capacity: Remove the oldest policy from deque as well as the # cache and return it. if len(self._deque) == self.capacity: policy = self._stash_least_used_policy() # All our policies have same NN-architecture (are "swappable"). # -> Load new policy's state into the one that just got removed from the cache. # This way, we save the costly re-creation step. if policy is not None and self.policy_states_are_swappable: logger.debug(f"restoring policy: {item}") policy.set_state(policy_state) else: logger.debug(f"creating new policy: {item}") policy = Policy.from_state(policy_state) self.cache[item] = policy # Promote the item to most recently one. self._deque.append(item) return policy @with_lock @override(dict) def __setitem__(self, key: PolicyID, value: Policy): # Item already in cache -> Rearrange deque. if key in self.cache: self._deque.remove(key) # Item not currently in cache -> store new value and - if at capacity - # remove leftmost one. else: # Cache at capacity -> Drop leftmost item. if len(self._deque) == self.capacity: self._stash_least_used_policy() # Promote `key` to "most recently used". self._deque.append(key) # Update our cache. self.cache[key] = value self._valid_keys.add(key) @with_lock @override(dict) def __delitem__(self, key: PolicyID): # Make key invalid. self._valid_keys.remove(key) # Remove policy from deque if contained if key in self._deque: self._deque.remove(key) # Remove policy from memory if currently cached. if key in self.cache: policy = self.cache[key] self._close_session(policy) del self.cache[key] # Remove Ray object store reference (if this ID has already been stored # there), so the item gets garbage collected. if key in self._policy_state_refs: del self._policy_state_refs[key] @override(dict) def __iter__(self): return iter(self.keys()) @override(dict) def items(self): """Iterates over all policies, even the stashed ones.""" def gen(): for key in self._valid_keys: yield (key, self[key]) return gen() @override(dict) def keys(self): """Returns all valid keys, even the stashed ones.""" self._lock.acquire() ks = list(self._valid_keys) self._lock.release() def gen(): for key in ks: yield key return gen() @override(dict) def values(self): """Returns all valid values, even the stashed ones.""" self._lock.acquire() vs = [self[k] for k in self._valid_keys] self._lock.release() def gen(): for value in vs: yield value return gen() @with_lock @override(dict) def update(self, __m, **kwargs): """Updates the map with the given dict and/or kwargs.""" for k, v in __m.items(): self[k] = v for k, v in kwargs.items(): self[k] = v @with_lock @override(dict) def get(self, key: PolicyID): """Returns the value for the given key or None if not found.""" if key not in self._valid_keys: return None return self[key] @with_lock @override(dict) def __len__(self) -> int: """Returns number of all policies, including the stashed-to-disk ones.""" return len(self._valid_keys) @with_lock @override(dict) def __contains__(self, item: PolicyID): return item in self._valid_keys @override(dict) def __str__(self) -> str: # Only print out our keys (policy IDs), not values as this could trigger # the LRU caching. return ( f"<PolicyMap lru-caching-capacity={self.capacity} policy-IDs=" f"{list(self.keys())}>" ) def _stash_least_used_policy(self) -> Policy: """Writes the least-recently used policy's state to the Ray object store. Also closes the session - if applicable - of the stashed policy. Returns: The least-recently used policy, that just got removed from the cache. """ # Get policy's state for writing to object store. dropped_policy_id = self._deque.popleft() assert dropped_policy_id in self.cache policy = self.cache[dropped_policy_id] policy_state = policy.get_state() # If we don't simply swap out vs an existing policy: # Close the tf session, if any. if not self.policy_states_are_swappable: self._close_session(policy) # Remove from memory. This will clear the tf Graph as well. del self.cache[dropped_policy_id] # Store state in Ray object store. self._policy_state_refs[dropped_policy_id] = ray.put(policy_state) # Return the just removed policy, in case it's needed by the caller. return policy @staticmethod def _close_session(policy: Policy): sess = policy.get_session() # Closes the tf session, if any. if sess is not None: sess.close()
PolicyMap
python
django-haystack__django-haystack
test_haystack/elasticsearch5_tests/test_backend.py
{ "start": 1356, "end": 1673 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr="author", faceted=True) pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return MockModel
Elasticsearch5MockSearchIndex
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/stats.py
{ "start": 4108, "end": 4668 }
class ____(IHaveNew): start_time: Optional[float] end_time: Optional[float] key: Optional[str] def __new__( cls, start_time: Optional[float] = None, end_time: Optional[float] = None, key: Optional[str] = None, ): return super().__new__( cls, start_time=check.opt_float_param(start_time, "start_time"), end_time=check.opt_float_param(end_time, "end_time"), key=check.opt_str_param(key, "key"), ) @whitelist_for_serdes @record_custom
RunStepMarker
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/translate.py
{ "start": 69327, "end": 74744 }
class ____(GoogleCloudBaseOperator): """ Get a list of translation glossaries in a project. List the translation glossaries, using translation API V3. For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:TranslateListGlossariesOperator`. :param project_id: ID of the Google Cloud project where glossary is located. If not provided default project_id is used. :param page_size: Page size requested, if not set server use appropriate default. :param page_token: A token identifying a page of results the server should return. The first page is returned if ``page_token`` is empty or missing. :param filter_str: Filter specifying constraints of a list operation. Specify the constraint by the format of "key=value", where key must be ``src`` or ``tgt``, and the value must be a valid language code. For multiple restrictions, concatenate them by "AND" (uppercase only), such as: ``src=en-US AND tgt=zh-CN``. Notice that the exact match is used here, which means using 'en-US' and 'en' can lead to different results, which depends on the language code you used when you create the glossary. For the unidirectional glossaries, the ``src`` and ``tgt`` add restrictions on the source and target language code separately. For the equivalent term set glossaries, the ``src`` and/or ``tgt`` add restrictions on the term set. For example: ``src=en-US AND tgt=zh-CN`` will only pick the unidirectional glossaries which exactly match the source language code as ``en-US`` and the target language code ``zh-CN``, but all equivalent term set glossaries which contain ``en-US`` and ``zh-CN`` in their language set will be picked. If missing, no filtering is performed. :param location: The location of the project. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadata: Strings which should be sent along with the request as metadata. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ operator_extra_links = (TranslationGlossariesListLink(),) template_fields: Sequence[str] = ( "location", "project_id", "gcp_conn_id", "impersonation_chain", ) def __init__( self, *, project_id: str = PROVIDE_PROJECT_ID, location: str, page_size: int | None = None, page_token: str | None = None, filter_str: str | None = None, timeout: float | None = None, retry: Retry | _MethodDefault = DEFAULT, gcp_conn_id: str = "google_cloud_default", metadata: Sequence[tuple[str, str]] = (), impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.project_id = project_id self.location = location self.page_size = page_size self.page_token = page_token self.filter_str = filter_str self.metadata = metadata self.timeout = timeout self.retry = retry self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context) -> Sequence[str]: hook = TranslateHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) project_id = self.project_id or hook.project_id TranslationGlossariesListLink.persist( context=context, project_id=project_id, ) self.log.info("Requesting glossaries list") try: results_pager = hook.list_glossaries( project_id=project_id, location=self.location, page_size=self.page_size, page_token=self.page_token, filter_str=self.filter_str, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) except GoogleAPICallError as e: self.log.error("Error submitting list_glossaries request") raise AirflowException(e) result_ids = [] for glossary_item_raw in results_pager: glossary_item = type(glossary_item_raw).to_dict(glossary_item_raw) glossary_id = hook.extract_object_id(glossary_item) result_ids.append(glossary_id) self.log.info("Fetching the glossaries list complete. Glossary id-s: %s", result_ids) return result_ids
TranslateListGlossariesOperator
python
spack__spack
lib/spack/spack/detection/common.py
{ "start": 10892, "end": 17427 }
class ____: @staticmethod def find_windows_kit_roots() -> List[str]: """Return Windows kit root, typically %programfiles%\\Windows Kits\\10|11\\""" if sys.platform != "win32": return [] program_files = os.environ["PROGRAMFILES(x86)"] kit_base = os.path.join(program_files, "Windows Kits", "**") return glob.glob(kit_base) @staticmethod def find_windows_kit_bin_paths( kit_base: Union[Optional[str], Optional[list]] = None, ) -> List[str]: """Returns Windows kit bin directory per version""" kit_base = WindowsKitExternalPaths.find_windows_kit_roots() if not kit_base else kit_base assert kit_base, "Unexpectedly empty value for Windows kit base path" if isinstance(kit_base, str): kit_base = kit_base.split(";") kit_paths = [] for kit in kit_base: kit_bin = os.path.join(kit, "bin") kit_paths.extend(glob.glob(os.path.join(kit_bin, "[0-9]*", "*\\"))) return kit_paths @staticmethod def find_windows_kit_lib_paths( kit_base: Union[Optional[str], Optional[list]] = None, ) -> List[str]: """Returns Windows kit lib directory per version""" kit_base = WindowsKitExternalPaths.find_windows_kit_roots() if not kit_base else kit_base assert kit_base, "Unexpectedly empty value for Windows kit base path" if isinstance(kit_base, str): kit_base = kit_base.split(";") kit_paths = [] for kit in kit_base: kit_lib = os.path.join(kit, "Lib") kit_paths.extend(glob.glob(os.path.join(kit_lib, "[0-9]*", "*", "*\\"))) return kit_paths @staticmethod def find_windows_driver_development_kit_paths() -> List[str]: """Provides a list of all installation paths for the WDK by version and architecture """ wdk_content_root = os.getenv("WDKContentRoot") return WindowsKitExternalPaths.find_windows_kit_lib_paths(wdk_content_root) @staticmethod def find_windows_kit_reg_installed_roots_paths() -> List[str]: reg = spack.util.windows_registry.WindowsRegistryView( "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", root_key=spack.util.windows_registry.HKEY.HKEY_LOCAL_MACHINE, ) if not reg: # couldn't find key, return empty list return [] kit_root_reg = re.compile(r"KitsRoot[0-9]+") root_paths = [] for kit_root in filter(kit_root_reg.match, reg.get_values().keys()): root_paths.extend( WindowsKitExternalPaths.find_windows_kit_lib_paths(reg.get_value(kit_root).value) ) return root_paths @staticmethod def find_windows_kit_reg_sdk_paths() -> List[str]: sdk_paths = [] sdk_regex = re.compile(r"v[0-9]+.[0-9]+") windows_reg = spack.util.windows_registry.WindowsRegistryView( "SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SDKs\\Windows", root_key=spack.util.windows_registry.HKEY.HKEY_LOCAL_MACHINE, ) for key in filter(sdk_regex.match, [x.name for x in windows_reg.get_subkeys()]): reg = windows_reg.get_subkey(key) sdk_paths.extend( WindowsKitExternalPaths.find_windows_kit_lib_paths( reg.get_value("InstallationFolder").value ) ) return sdk_paths def find_win32_additional_install_paths() -> List[str]: """Not all programs on Windows live on the PATH Return a list of other potential install locations. """ drive_letter = _windows_drive() windows_search_ext = [] cuda_re = r"CUDA_PATH[a-zA-Z1-9_]*" # The list below should be expanded with other # common Windows install locations as necessary path_ext_keys = ["I_MPI_ONEAPI_ROOT", "MSMPI_BIN", "MLAB_ROOT", "NUGET_PACKAGES"] user = os.environ["USERPROFILE"] add_path = lambda key: re.search(cuda_re, key) or key in path_ext_keys windows_search_ext.extend([os.environ[key] for key in os.environ.keys() if add_path(key)]) # note windows paths are fine here as this method should only ever be invoked # to interact with Windows # Add search path for default Chocolatey (https://github.com/chocolatey/choco) # install directory windows_search_ext.append("%s\\ProgramData\\chocolatey\\bin" % drive_letter) # Add search path for NuGet package manager default install location windows_search_ext.append(os.path.join(user, ".nuget", "packages")) windows_search_ext.extend( spack.config.get("config:additional_external_search_paths", default=[]) ) windows_search_ext.extend(spack.util.environment.get_path("PATH")) return windows_search_ext def compute_windows_program_path_for_package(pkg: "spack.package_base.PackageBase") -> List[str]: """Given a package, attempts to compute its Windows program files location, and returns the list of best guesses. Args: pkg: package for which Program Files location is to be computed """ if sys.platform != "win32": return [] # note windows paths are fine here as this method should only ever be invoked # to interact with Windows program_files = "{}\\Program Files{}\\{}" drive_letter = _windows_drive() return [ program_files.format(drive_letter, arch, name) for arch, name in itertools.product(("", " (x86)"), (pkg.name, pkg.name.capitalize())) ] def compute_windows_user_path_for_package(pkg: "spack.package_base.PackageBase") -> List[str]: """Given a package attempt to compute its user scoped install location, return list of potential locations based on common heuristics. For more info on Windows user specific installs see: https://learn.microsoft.com/en-us/dotnet/api/system.environment.specialfolder?view=netframework-4.8 """ if sys.platform != "win32": return [] # Current user directory user = os.environ["USERPROFILE"] app_data = "AppData" app_data_locations = ["Local", "Roaming"] user_appdata_install_stubs = [os.path.join(app_data, x) for x in app_data_locations] return [ os.path.join(user, app_data, name) for app_data, name in list( itertools.product(user_appdata_install_stubs, (pkg.name, pkg.name.capitalize())) ) ] + [os.path.join(user, name) for name in (pkg.name, pkg.name.capitalize())]
WindowsKitExternalPaths
python
pydata__xarray
xarray/core/types.py
{ "start": 3434, "end": 9720 }
class ____(Protocol): """Represents any Xarray type that supports alignment. It may be ``Dataset``, ``DataArray`` or ``Coordinates``. This protocol class is needed since those types do not all have a common base class. """ @property def dims(self) -> Frozen[Hashable, int] | tuple[Hashable, ...]: ... @property def sizes(self) -> Mapping[Hashable, int]: ... @property def xindexes(self) -> Indexes[Index]: ... def _reindex_callback( self, aligner: Any, dim_pos_indexers: dict[Hashable, Any], variables: dict[Hashable, Variable], indexes: dict[Hashable, Index], fill_value: Any, exclude_dims: frozenset[Hashable], exclude_vars: frozenset[Hashable], ) -> Self: ... def _overwrite_indexes( self, indexes: Mapping[Any, Index], variables: Mapping[Any, Variable] | None = None, ) -> Self: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[Hashable]: ... def copy( self, deep: bool = False, ) -> Self: ... T_Alignable = TypeVar("T_Alignable", bound="Alignable") T_Aligner = TypeVar("T_Aligner", bound="Aligner") T_Backend = TypeVar("T_Backend", bound="BackendEntrypoint") T_Dataset = TypeVar("T_Dataset", bound="Dataset") T_DataArray = TypeVar("T_DataArray", bound="DataArray") T_Variable = TypeVar("T_Variable", bound="Variable") T_Coordinates = TypeVar("T_Coordinates", bound="Coordinates") T_Array = TypeVar("T_Array", bound="AbstractArray") T_Index = TypeVar("T_Index", bound="Index") # `T_Xarray` is a type variable that can be either "DataArray" or "Dataset". When used # in a function definition, all inputs and outputs annotated with `T_Xarray` must be of # the same concrete type, either "DataArray" or "Dataset". This is generally preferred # over `T_DataArrayOrSet`, given the type system can determine the exact type. T_Xarray = TypeVar("T_Xarray", "DataArray", "Dataset") # `T_DataArrayOrSet` is a type variable that is bounded to either "DataArray" or # "Dataset". Use it for functions that might return either type, but where the exact # type cannot be determined statically using the type system. T_DataArrayOrSet = TypeVar("T_DataArrayOrSet", bound=Union["Dataset", "DataArray"]) # For working directly with `DataWithCoords`. It will only allow using methods defined # on `DataWithCoords`. T_DataWithCoords = TypeVar("T_DataWithCoords", bound="DataWithCoords") # Temporary placeholder for indicating an array api compliant type. # hopefully in the future we can narrow this down more: T_DuckArray = TypeVar("T_DuckArray", bound=Any, covariant=True) # noqa: PLC0105 # For typing pandas extension arrays. T_ExtensionArray = TypeVar("T_ExtensionArray", bound=pd.api.extensions.ExtensionArray) ScalarOrArray = Union["ArrayLike", np.generic] VarCompatible = Union["Variable", "ScalarOrArray"] DaCompatible = Union["DataArray", "VarCompatible"] DsCompatible = Union["Dataset", "DaCompatible"] DtCompatible = Union["DataTree", "DsCompatible"] GroupByCompatible = Union["Dataset", "DataArray"] # Don't change to Hashable | Collection[Hashable] # Read: https://github.com/pydata/xarray/issues/6142 Dims = Union[str, Collection[Hashable], EllipsisType, None] # FYI in some cases we don't allow `None`, which this doesn't take account of. # FYI the `str` is for a size string, e.g. "16MB", supported by dask. T_ChunkDim: TypeAlias = str | int | Literal["auto"] | tuple[int, ...] | None # noqa: PYI051 T_ChunkDimFreq: TypeAlias = Union["Resampler", T_ChunkDim] T_ChunksFreq: TypeAlias = T_ChunkDim | Mapping[Any, T_ChunkDimFreq] # We allow the tuple form of this (though arguably we could transition to named dims only) T_Chunks: TypeAlias = T_ChunkDim | Mapping[Any, T_ChunkDim] T_NormalizedChunks = tuple[tuple[int, ...], ...] DataVars = Mapping[Any, Any] ErrorOptions = Literal["raise", "ignore"] ErrorOptionsWithWarn = Literal["raise", "warn", "ignore"] CompatOptions = Literal[ "identical", "equals", "broadcast_equals", "no_conflicts", "override", "minimal" ] ConcatOptions = Literal["all", "minimal", "different"] CombineAttrsOptions = Union[ Literal["drop", "identical", "no_conflicts", "drop_conflicts", "override"], Callable[..., Any], ] JoinOptions = Literal["outer", "inner", "left", "right", "exact", "override"] Interp1dOptions = Literal[ "linear", "nearest", "zero", "slinear", "quadratic", "cubic", "quintic", "polynomial", ] InterpolantOptions = Literal[ "barycentric", "krogh", "pchip", "spline", "akima", "makima" ] InterpnOptions = Literal["linear", "nearest", "slinear", "cubic", "quintic", "pchip"] InterpOptions = Union[Interp1dOptions, InterpolantOptions, InterpnOptions] DatetimeUnitOptions = ( Literal["W", "D", "h", "m", "s", "ms", "us", "μs", "ns", "ps", "fs", "as"] | None ) NPDatetimeUnitOptions = Literal["D", "h", "m", "s", "ms", "us", "ns"] PDDatetimeUnitOptions = Literal["s", "ms", "us", "ns"] QueryEngineOptions = Literal["python", "numexpr"] | None QueryParserOptions = Literal["pandas", "python"] ReindexMethodOptions = Literal["nearest", "pad", "ffill", "backfill", "bfill"] | None PadModeOptions = Literal[ "constant", "edge", "linear_ramp", "maximum", "mean", "median", "minimum", "reflect", "symmetric", "wrap", ] T_PadConstantValues = float | tuple[float, float] T_VarPadConstantValues = T_PadConstantValues | Mapping[Any, T_PadConstantValues] T_DatasetPadConstantValues = ( T_VarPadConstantValues | Mapping[Any, T_VarPadConstantValues] ) PadReflectOptions = Literal["even", "odd"] | None CFCalendar = Literal[ "standard", "gregorian", "proleptic_gregorian", "noleap", "365_day", "360_day", "julian", "all_leap", "366_day", ] CoarsenBoundaryOptions = Literal["exact", "trim", "pad"] SideOptions = Literal["left", "right"] InclusiveOptions = Literal["both", "neither", "left", "right"] ScaleOptions = Literal["linear", "symlog", "log", "logit"] | None HueStyleOptions = Literal["continuous", "discrete"] | None AspectOptions = Union[Literal["auto", "equal"], float, None] ExtendOptions = Literal["neither", "both", "min", "max"] | None _T_co = TypeVar("_T_co", covariant=True)
Alignable
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingLiteralMember1.py
{ "start": 2928, "end": 3182 }
class ____: thing: G | H def method1(self) -> None: if self.thing.type == 1: reveal_type(self.thing, expected_text="H") local = self.thing if local.type == 1: reveal_type(local, expected_text="H")
I
python
pandas-dev__pandas
pandas/core/window/rolling.py
{ "start": 113732, "end": 116027 }
class ____(BaseWindowGroupby, Rolling): """ Provide a rolling groupby implementation. """ _attributes = Rolling._attributes + BaseWindowGroupby._attributes def _get_window_indexer(self) -> GroupbyIndexer: """ Return an indexer class that will compute the window start and end bounds Returns ------- GroupbyIndexer """ rolling_indexer: type[BaseIndexer] indexer_kwargs: dict[str, Any] | None = None index_array = self._index_array if isinstance(self.window, BaseIndexer): rolling_indexer = type(self.window) indexer_kwargs = self.window.__dict__.copy() assert isinstance(indexer_kwargs, dict) # for mypy # We'll be using the index of each group later indexer_kwargs.pop("index_array", None) window = self.window elif self._win_freq_i8 is not None: rolling_indexer = VariableWindowIndexer # error: Incompatible types in assignment (expression has type # "int", variable has type "BaseIndexer") window = self._win_freq_i8 # type: ignore[assignment] else: rolling_indexer = FixedWindowIndexer window = self.window window_indexer = GroupbyIndexer( index_array=index_array, window_size=window, groupby_indices=self._grouper.indices, window_indexer=rolling_indexer, indexer_kwargs=indexer_kwargs, ) return window_indexer def _validate_datetimelike_monotonic(self) -> None: """ Validate that each group in self._on is monotonic """ # GH 46061 if self._on.hasnans: self._raise_monotonic_error("values must not have NaT") for group_indices in self._grouper.indices.values(): group_on = self._on.take(group_indices) if not ( group_on.is_monotonic_increasing or group_on.is_monotonic_decreasing ): on = "index" if self.on is None else self.on raise ValueError( f"Each group within {on} must be monotonic. " f"Sort the values in {on} first." )
RollingGroupby
python
Textualize__textual
src/textual/events.py
{ "start": 22565, "end": 22922 }
class ____(Event, bubble=True, verbose=True): """Sent when a child widget is focussed. - [X] Bubbles - [X] Verbose """ widget: Widget """The widget that was focused.""" @property def control(self) -> Widget: """The widget that was focused (alias of `widget`).""" return self.widget @dataclass
DescendantFocus
python
apache__airflow
airflow-core/tests/unit/models/test_dagrun.py
{ "start": 109756, "end": 113965 }
class ____: """Test the handle_dag_callback method (only uses in dag.test).""" def test_handle_dag_callback_success(self, dag_maker, session): """Test handle_dag_callback executes success callback with RuntimeTaskInstance context""" called = False context_received = None def on_success(context): nonlocal called, context_received called = True context_received = context with dag_maker("test_dag", session=session, on_success_callback=on_success) as dag: BashOperator(task_id="test_task", bash_command="echo 1") dr = dag_maker.create_dagrun() dag.on_success_callback = on_success dag.has_on_success_callback = True dr.handle_dag_callback(dag, success=True, reason="test_success") assert called is True assert context_received is not None # Should have RuntimeTaskInstance context with template variables assert "dag_run" in context_received assert "logical_date" in context_received assert "reason" in context_received assert context_received["reason"] == "test_success" assert "ts" in context_received assert "params" in context_received def test_handle_dag_callback_failure(self, dag_maker, session): """Test handle_dag_callback executes failure callback with RuntimeTaskInstance context""" called = False context_received = None def on_failure(context): nonlocal called, context_received called = True context_received = context with dag_maker("test_dag", session=session, on_failure_callback=on_failure) as dag: BashOperator(task_id="test_task", bash_command="echo 1") dr = dag_maker.create_dagrun() dag.on_failure_callback = on_failure dag.has_on_failure_callback = True dr.handle_dag_callback(dag, success=False, reason="test_failure") assert called is True assert context_received is not None # Should have RuntimeTaskInstance context with template variables assert "dag_run" in context_received assert "logical_date" in context_received assert "reason" in context_received assert context_received["reason"] == "test_failure" assert "ts" in context_received assert "params" in context_received def test_handle_dag_callback_multiple_callbacks(self, dag_maker, session): """Test handle_dag_callback executes multiple callbacks""" call_count = 0 def on_failure_1(context): nonlocal call_count call_count += 1 def on_failure_2(context): nonlocal call_count call_count += 1 with dag_maker("test_dag", session=session, on_failure_callback=[on_failure_1, on_failure_2]) as dag: BashOperator(task_id="test_task", bash_command="echo 1") dr = dag_maker.create_dagrun() dag.on_failure_callback = [on_failure_1, on_failure_2] dag.has_on_failure_callback = True dr.handle_dag_callback(dag, success=False, reason="test_failure") assert call_count == 2 def test_handle_dag_callback_context_has_correct_ti_info(self, dag_maker, session): """Test handle_dag_callback context contains correct task instance information""" context_received = None def on_failure(context): nonlocal context_received context_received = context with dag_maker("test_dag", session=session, on_failure_callback=on_failure) as dag: BashOperator(task_id="test_task", bash_command="echo 1", retries=2) dr = dag_maker.create_dagrun() dag.on_failure_callback = on_failure dag.has_on_failure_callback = True dr.handle_dag_callback(dag, success=False, reason="test_failure") assert context_received is not None # Check that context contains correct task info assert context_received["ti"].task_id == "test_task" assert context_received["ti"].dag_id == "test_dag" assert context_received["ti"].run_id == dr.run_id
TestDagRunHandleDagCallback
python
facebookresearch__faiss
faiss/gpu/test/torch_test_contrib_gpu.py
{ "start": 17611, "end": 18495 }
class ____(unittest.TestCase): def test_python_kmeans(self): """ Test the python implementation of kmeans """ ds = datasets.SyntheticDataset(32, 10000, 0, 0) x = ds.get_train() # bad distribution to stress-test split code xt = x[:10000].copy() xt[:5000] = x[0] # CPU baseline km_ref = faiss.Kmeans(ds.d, 100, niter=10) km_ref.train(xt) err = faiss.knn(xt, km_ref.centroids, 1)[0].sum() xt_torch = torch.from_numpy(xt).to("cuda:0") res = faiss.StandardGpuResources() data = clustering.DatasetAssignGPU(res, xt_torch) centroids = clustering.kmeans(100, data, 10) centroids = centroids.cpu().numpy() err2 = faiss.knn(xt, centroids, 1)[0].sum() # 33498.332 33380.477 print(err, err2) self.assertLess(err2, err * 1.1)
TestClustering
python
apache__airflow
airflow-core/tests/unit/jobs/test_triggerer_job.py
{ "start": 28460, "end": 31993 }
class ____(TriggerRunnerSupervisor): """ Make sure that the Supervisor stops after handling the events and do not keep running forever so the test can continue. """ def handle_events(self): self.stop = bool(self.events) super().handle_events() @pytest.mark.asyncio @pytest.mark.execution_timeout(20) async def test_trigger_can_call_variables_connections_and_xcoms_methods(session, dag_maker): """Checks that the trigger will successfully call Variables, Connections and XComs methods.""" # Create the test DAG and task with dag_maker(dag_id="trigger_accessing_variable_connection_and_xcom", session=session): EmptyOperator(task_id="dummy1") dr = dag_maker.create_dagrun() task_instance = dr.task_instances[0] # Make a task instance based on that and tie it to the trigger task_instance.state = TaskInstanceState.DEFERRED # Create a Trigger trigger = CustomTrigger(dag_id=dr.dag_id, run_id=dr.run_id, task_id=task_instance.task_id, map_index=-1) trigger_orm = Trigger( classpath=trigger.serialize()[0], kwargs={"dag_id": dr.dag_id, "run_id": dr.run_id, "task_id": task_instance.task_id, "map_index": -1}, ) session.add(trigger_orm) session.flush() task_instance.trigger_id = trigger_orm.id # Create the appropriate Connection, Variable and XCom connection = Connection( conn_id="test_connection", conn_type="http", schema="https", login="user", password="pass", extra={"key": "value"}, port=443, host="example.com", ) get_variable = Variable(key="test_get_variable", val="some_variable_value") delete_variable = Variable(key="test_delete_variable", val="delete_value") session.add(connection) session.add(get_variable) session.add(delete_variable) XComModel.set( key="test_get_xcom", value="some_xcom_value", task_id=task_instance.task_id, dag_id=dr.dag_id, run_id=dr.run_id, map_index=-1, session=session, ) XComModel.set( key="test_delete_xcom", value="some_xcom_value", task_id=task_instance.task_id, dag_id=dr.dag_id, run_id=dr.run_id, map_index=-1, session=session, ) job = Job() session.add(job) session.commit() supervisor = DummyTriggerRunnerSupervisor.start(job=job, capacity=1, logger=None) supervisor.run() task_instance.refresh_from_db() assert task_instance.state == TaskInstanceState.SCHEDULED assert task_instance.next_method != "__fail__" expected_event = { "event": { "connection": { "conn_id": "test_connection", "conn_type": "http", "description": None, "host": "example.com", "schema": "https", "login": "user", "password": "pass", "port": 443, "extra": '{"key": "value"}', }, "variable": { "get_variable": "some_variable_value", "set_variable": "set_value", "delete_variable": "test_delete_variable", }, "xcom": { "get_xcom": '"some_xcom_value"', "set_xcom": "set_xcom", "delete_xcom": "test_delete_xcom", }, } } assert task_instance.next_kwargs == expected_event
DummyTriggerRunnerSupervisor
python
astropy__astropy
astropy/io/ascii/ipac.py
{ "start": 1809, "end": 11568 }
class ____(fixedwidth.FixedWidthHeader): """IPAC table header.""" splitter_class = IpacHeaderSplitter # Defined ordered list of possible types. Ordering is needed to # distinguish between "d" (double) and "da" (date) as defined by # the IPAC standard for abbreviations. This gets used in get_col_type(). col_type_list = ( ("integer", core.IntType), ("long", core.IntType), ("double", core.FloatType), ("float", core.FloatType), ("real", core.FloatType), ("char", core.StrType), ("date", core.StrType), ) definition = "ignore" start_line = None def process_lines(self, lines): """Generator to yield IPAC header lines, i.e. those starting and ending with delimiter character (with trailing whitespace stripped). """ delim = self.splitter.delimiter for line in lines: line = line.rstrip() if line.startswith(delim) and line.endswith(delim): yield line.strip(delim) def update_meta(self, lines, meta): """ Extract table-level comments and keywords for IPAC table. See: https://irsa.ipac.caltech.edu/applications/DDGEN/Doc/ipac_tbl.html#kw. """ def process_keyword_value(val): """ Take a string value and convert to float, int or str, and strip quotes as needed. """ val = val.strip() try: val = int(val) except Exception: try: val = float(val) except Exception: # Strip leading/trailing quote. The spec says that a matched pair # of quotes is required, but this code will allow a non-quoted value. for quote in ('"', "'"): if val.startswith(quote) and val.endswith(quote): val = val[1:-1] break return val table_meta = meta["table"] table_meta["comments"] = [] table_meta["keywords"] = {} keywords = table_meta["keywords"] # fmt: off re_keyword = re.compile( r'\\' r'(?P<name> \w+)' r'\s* = (?P<value> .+) $', re.VERBOSE ) # fmt: on for line in lines: # Keywords and comments start with "\". Once the first non-slash # line is seen then bail out. if not line.startswith("\\"): break m = re_keyword.match(line) if m: name = m.group("name") val = process_keyword_value(m.group("value")) # IPAC allows for continuation keywords, e.g. # \SQL = 'WHERE ' # \SQL = 'SELECT (25 column names follow in next row.)' if name in keywords and isinstance(val, str): prev_val = keywords[name]["value"] if isinstance(prev_val, str): val = prev_val + val keywords[name] = {"value": val} else: # Comment is required to start with "\ " if line.startswith("\\ "): val = line[2:].strip() if val: table_meta["comments"].append(val) def get_col_type(self, col): for col_type_key, col_type in self.col_type_list: if col_type_key.startswith(col.raw_type.lower()): return col_type raise ValueError( f'Unknown data type ""{col.raw_type}"" for column "{col.name}"' ) def get_cols(self, lines): """ Initialize the header Column objects from the table ``lines``. Based on the previously set Header attributes find or create the column names. Sets ``self.cols`` with the list of Columns. Parameters ---------- lines : list List of table lines """ # generator returning valid header lines header_lines = self.process_lines(lines) header_vals = list(self.splitter(header_lines)) if len(header_vals) == 0: raise ValueError( "At least one header line beginning and ending with delimiter required" ) elif len(header_vals) > 4: raise ValueError("More than four header lines were found") # Generate column definitions cols = [] start = 1 for i, name in enumerate(header_vals[0]): col = core.Column(name=name.strip(" -")) col.start = start col.end = start + len(name) if len(header_vals) > 1: col.raw_type = header_vals[1][i].strip(" -") col.type = self.get_col_type(col) if len(header_vals) > 2: col.unit = header_vals[2][i].strip() or None # Can't strip dashes here if len(header_vals) > 3: # The IPAC null value corresponds to the io.ascii bad_value. # In this case there isn't a fill_value defined, so just put # in the minimal entry that is sure to convert properly to the # required type. # # Strip spaces but not dashes (not allowed in NULL row per # https://github.com/astropy/astropy/issues/361) null = header_vals[3][i].strip() fillval = "" if issubclass(col.type, core.StrType) else "0" self.data.fill_values.append((null, fillval, col.name)) start = col.end + 1 cols.append(col) # Correct column start/end based on definition if self.ipac_definition == "right": col.start -= 1 elif self.ipac_definition == "left": col.end += 1 self.names = [x.name for x in cols] self.cols = cols def str_vals(self): if self.DBMS: IpacFormatE = IpacFormatErrorDBMS else: IpacFormatE = IpacFormatError namelist = self.colnames if self.DBMS: countnamelist = defaultdict(int) for name in self.colnames: countnamelist[name.lower()] += 1 doublenames = [x for x in countnamelist if countnamelist[x] > 1] if doublenames != []: raise IpacFormatE( "IPAC DBMS tables are not case sensitive. " f"This causes duplicate column names: {doublenames}" ) for name in namelist: m = re.match(r"\w+", name) if m.end() != len(name): raise IpacFormatE( f"{name} - Only alphanumeric characters and _ " "are allowed in column names." ) if self.DBMS and not (name[0].isalpha() or (name[0] == "_")): raise IpacFormatE(f"Column name cannot start with numbers: {name}") if self.DBMS: if name in ["x", "y", "z", "X", "Y", "Z"]: raise IpacFormatE( f"{name} - x, y, z, X, Y, Z are reserved names and " "cannot be used as column names." ) if len(name) > 16: raise IpacFormatE( f"{name} - Maximum length for column name is 16 characters" ) else: if len(name) > 40: raise IpacFormatE( f"{name} - Maximum length for column name is 40 characters." ) dtypelist = [] unitlist = [] nullist = [] for col in self.cols: col_dtype = col.info.dtype col_unit = col.info.unit col_format = col.info.format if col_dtype.kind in ["i", "u"]: if col_dtype.itemsize <= 2: dtypelist.append("int") else: dtypelist.append("long") elif col_dtype.kind == "f": if col_dtype.itemsize <= 4: dtypelist.append("float") else: dtypelist.append("double") else: dtypelist.append("char") if col_unit is None: unitlist.append("") else: unitlist.append(str(col.info.unit)) # This may be incompatible with mixin columns null = col.fill_values[core.masked] try: auto_format_func = get_auto_format_func(col) format_func = col.info._format_funcs.get(col_format, auto_format_func) nullist.append((format_func(col_format, null)).strip()) except Exception: # It is possible that null and the column values have different # data types (e.g. number and null = 'null' (i.e. a string). # This could cause all kinds of exceptions, so a catch all # block is needed here nullist.append(str(null).strip()) return [namelist, dtypelist, unitlist, nullist] def write(self, lines, widths): """Write header. The width of each column is determined in Ipac.write. Writing the header must be delayed until that time. This function is called from there, once the width information is available. """ for vals in self.str_vals(): lines.append(self.splitter.join(vals, widths)) return lines
IpacHeader