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
patrick-kidger__equinox
equinox/internal/_omega.py
{ "start": 5273, "end": 7126 }
class ____ωUpdateRef: def __init__(self, value, item, is_leaf): self.value = value self.item = item self.is_leaf = is_leaf def _set_binary_at(base, name: str, op: Callable[[Any, Any, Any], Any]) -> None: def fn(self, other): if isinstance(other, ω): if jtu.tree_structure(self.value) != jtu.tree_structure(other.ω): raise ValueError("PyTree structures must match.") if not _equal_code(self.is_leaf, other.is_leaf): raise ValueError("is_leaf specifications must match.") return ω( jtu.tree_map( lambda x, y: op(x, self.item, y), self.value, other.ω, is_leaf=self.is_leaf, ), is_leaf=self.is_leaf, ) elif isinstance(other, (bool, complex, float, int, jax.Array)): return ω( jtu.tree_map( lambda x: op(x, self.item, other), self.value, is_leaf=self.is_leaf ), is_leaf=self.is_leaf, ) else: raise RuntimeError("Type of `other` not understood.") fn.__name__ = name fn.__qualname__ = base.__qualname__ + "." + name setattr(base, name, fn) for name, op in [ ("set", lambda x, y, z, **kwargs: x.at[y].set(z, **kwargs)), ("add", lambda x, y, z, **kwargs: x.at[y].add(z, **kwargs)), ("multiply", lambda x, y, z, **kwargs: x.at[y].multiply(z, **kwargs)), ("divide", lambda x, y, z, **kwargs: x.at[y].divide(z, **kwargs)), ("power", lambda x, y, z, **kwargs: x.at[y].power(z, **kwargs)), ("min", lambda x, y, z, **kwargs: x.at[y].min(z, **kwargs)), ("max", lambda x, y, z, **kwargs: x.at[y].max(z, **kwargs)), ]: _set_binary_at(_ωUpdateRef, name, op)
_
python
tensorflow__tensorflow
tensorflow/python/feature_column/feature_column_v2.py
{ "start": 127179, "end": 132993 }
class ____( CategoricalColumn, fc_old._CategoricalColumn, # pylint: disable=protected-access collections.namedtuple( 'VocabularyFileCategoricalColumn', ('key', 'vocabulary_file', 'vocabulary_size', 'num_oov_buckets', 'dtype', 'default_value', 'file_format'))): """See `categorical_column_with_vocabulary_file`.""" def __new__(cls, key, vocabulary_file, vocabulary_size, num_oov_buckets, dtype, default_value, file_format=None): return super(VocabularyFileCategoricalColumn, cls).__new__( cls, key=key, vocabulary_file=vocabulary_file, vocabulary_size=vocabulary_size, num_oov_buckets=num_oov_buckets, dtype=dtype, default_value=default_value, file_format=file_format) @property def _is_v2_column(self): return True @property def name(self): """See `FeatureColumn` base class.""" return self.key @property def parse_example_spec(self): """See `FeatureColumn` base class.""" return {self.key: parsing_ops.VarLenFeature(self.dtype)} @property @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, _FEATURE_COLUMN_DEPRECATION) def _parse_example_spec(self): return self.parse_example_spec def _make_table_from_tfrecord_gzip_file(self, key_dtype, name): dataset = readers.TFRecordDataset( self.vocabulary_file, compression_type='GZIP') def key_dtype_fn(key): return key if key_dtype is dtypes.string else string_ops.string_to_number( key, out_type=key_dtype) return data_lookup_ops.index_table_from_dataset( dataset.map(key_dtype_fn), num_oov_buckets=self.num_oov_buckets, vocab_size=self.vocabulary_size, default_value=self.default_value, key_dtype=key_dtype, name=name) def _make_table(self, key_dtype, state_manager): name = '{}_lookup'.format(self.key) if state_manager is None or not state_manager.has_resource(self, name): with ops.init_scope(): if self.file_format == 'tfrecord_gzip': table = self._make_table_from_tfrecord_gzip_file(key_dtype, name) else: table = lookup_ops.index_table_from_file( vocabulary_file=self.vocabulary_file, num_oov_buckets=self.num_oov_buckets, vocab_size=self.vocabulary_size, default_value=self.default_value, key_dtype=key_dtype, name=name) if state_manager is not None: state_manager.add_resource(self, name, table) else: # Reuse the table from the previous run. table = state_manager.get_resource(self, name) return table def _transform_input_tensor(self, input_tensor, state_manager=None): """Creates a lookup table for the vocabulary.""" if self.dtype.is_integer != input_tensor.dtype.is_integer: raise ValueError( 'Column dtype and SparseTensors dtype must be compatible. ' 'key: {}, column dtype: {}, tensor dtype: {}'.format( self.key, self.dtype, input_tensor.dtype)) fc_utils.assert_string_or_int( input_tensor.dtype, prefix='column_name: {} input_tensor'.format(self.key)) key_dtype = self.dtype if input_tensor.dtype.is_integer: # `index_table_from_file` requires 64-bit integer keys. key_dtype = dtypes.int64 input_tensor = math_ops.cast(input_tensor, dtypes.int64) return self._make_table(key_dtype, state_manager).lookup(input_tensor) def transform_feature(self, transformation_cache, state_manager): """Creates a lookup table for the vocabulary.""" input_tensor = _to_sparse_input_and_drop_ignore_values( transformation_cache.get(self.key, state_manager)) return self._transform_input_tensor(input_tensor, state_manager) @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, _FEATURE_COLUMN_DEPRECATION) def _transform_feature(self, inputs): input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) return self._transform_input_tensor(input_tensor) @property def num_buckets(self): """Returns number of buckets in this sparse feature.""" return self.vocabulary_size + self.num_oov_buckets @property @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, _FEATURE_COLUMN_DEPRECATION) def _num_buckets(self): return self.num_buckets def get_sparse_tensors(self, transformation_cache, state_manager): """See `CategoricalColumn` base class.""" return CategoricalColumn.IdWeightPair( transformation_cache.get(self, state_manager), None) @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, _FEATURE_COLUMN_DEPRECATION) def _get_sparse_tensors(self, inputs, weight_collections=None, trainable=None): del weight_collections del trainable return CategoricalColumn.IdWeightPair(inputs.get(self), None) @property def parents(self): """See 'FeatureColumn` base class.""" return [self.key] def get_config(self): """See 'FeatureColumn` base class.""" config = dict(zip(self._fields, self)) config['dtype'] = self.dtype.name return config @classmethod def from_config(cls, config, custom_objects=None, columns_by_name=None): """See 'FeatureColumn` base class.""" _check_config_keys(config, cls._fields) kwargs = _standardize_and_copy_config(config) kwargs['dtype'] = dtypes.as_dtype(config['dtype']) return cls(**kwargs) @serialization.register_feature_column
VocabularyFileCategoricalColumn
python
viewflow__viewflow
viewflow/workflow/flow/mixins.py
{ "start": 183, "end": 1428 }
class ____(metaclass=ViewsetMeta): """Task detail view.""" index_view_class: Optional[Type[View]] = None @viewprop def index_view(self): """View for a task detail.""" if self.index_view_class: return self.index_view_class.as_view() @property def index_path(self): if self.index_view: return path( f"<int:process_pk>/{self.name}/<int:task_pk>/", utils.wrap_task_view(self, self.index_view), name="index", ) detail_view_class: Optional[Type[View]] = None @viewprop def detail_view(self): """View for a task detail.""" if self.detail_view_class: return self.detail_view_class.as_view() @property def detail_path(self): if self.detail_view: return path( f"<int:process_pk>/{self.name}/<int:task_pk>/detail/", utils.wrap_task_view(self, self.detail_view, permission=self.can_view), name="detail", ) def can_view(self, user, task): """Check if user has a view task detail permission.""" return self.flow_class.instance.has_view_permission(user, task)
NodeDetailMixin
python
pypa__pip
src/pip/_vendor/urllib3/exceptions.py
{ "start": 1071, "end": 1305 }
class ____(HTTPError): """Raised when the connection to a proxy fails.""" def __init__(self, message, error, *args): super(ProxyError, self).__init__(message, error, *args) self.original_error = error
ProxyError
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py
{ "start": 6441, "end": 6533 }
class ____: pass def method1(): return 1 def method2(): return 22 # end # E302
Test
python
facebookresearch__faiss
benchs/bench_fw/benchmark_io.py
{ "start": 1396, "end": 9229 }
class ____: path: str # local path def __init__(self, path: str): self.path = path self.cached_ds: Dict[Any, Any] = {} def clone(self): return BenchmarkIO(path=self.path) def get_local_filepath(self, filename): if len(filename) > 184: fn, ext = os.path.splitext(filename) filename = ( fn[:184] + hashlib.sha256(filename.encode()).hexdigest() + ext ) return os.path.join(self.path, filename) def get_remote_filepath(self, filename) -> Optional[str]: return None def download_file_from_blobstore( self, filename: str, bucket: Optional[str] = None, path: Optional[str] = None, ): return self.get_local_filepath(filename) def upload_file_to_blobstore( self, filename: str, bucket: Optional[str] = None, path: Optional[str] = None, overwrite: bool = False, ): pass def file_exist(self, filename: str): fn = self.get_local_filepath(filename) exists = os.path.exists(fn) logger.info(f"{filename} {exists=}") return exists def read_file(self, filename: str, keys: List[str]): fn = self.download_file_from_blobstore(filename) logger.info(f"Loading file {fn}") results = [] with ZipFile(fn, "r") as zip_file: for key in keys: with zip_file.open(key, "r") as f: if key in ["D", "I", "R", "lims"]: results.append(np.load(f)) elif key in ["P"]: t = io.TextIOWrapper(f) results.append(json.load(t)) else: raise AssertionError() return results def write_file( self, filename: str, keys: List[str], values: List[Any], overwrite: bool = False, ): fn = self.get_local_filepath(filename) with ZipFile(fn, "w") as zip_file: for key, value in zip(keys, values, strict=True): with zip_file.open(key, "w", force_zip64=True) as f: if key in ["D", "I", "R", "lims"]: np.save(f, value) elif key in ["P"]: t = io.TextIOWrapper(f, write_through=True) json.dump(value, t) else: raise AssertionError() self.upload_file_to_blobstore(filename, overwrite=overwrite) def get_dataset(self, dataset): if dataset not in self.cached_ds: if ( dataset.namespace is not None and dataset.namespace[:4] == "std_" ): if dataset.tablename not in self.cached_ds: self.cached_ds[dataset.tablename] = dataset_from_name( dataset.tablename, ) p = dataset.namespace[4] if p == "t": self.cached_ds[dataset] = self.cached_ds[ dataset.tablename ].get_train(dataset.num_vectors) elif p == "d": self.cached_ds[dataset] = self.cached_ds[ dataset.tablename ].get_database() elif p == "q": self.cached_ds[dataset] = self.cached_ds[ dataset.tablename ].get_queries() else: raise ValueError elif dataset.namespace == "syn": d, seed = dataset.tablename.split("_") d = int(d) seed = int(seed) n = dataset.num_vectors # based on faiss.contrib.datasets.SyntheticDataset d1 = 10 rs = np.random.RandomState(seed) x = rs.normal(size=(n, d1)) x = np.dot(x, rs.rand(d1, d)) x = x * (rs.rand(d) * 4 + 0.1) x = np.sin(x) x = x.astype(np.float32) self.cached_ds[dataset] = x else: self.cached_ds[dataset] = self.read_nparray( os.path.join(self.path, dataset.tablename), mmap_mode="r", )[: dataset.num_vectors].copy() return self.cached_ds[dataset] def read_nparray( self, filename: str, mmap_mode: Optional[str] = None, ): fn = self.download_file_from_blobstore(filename) logger.info(f"Loading nparray from {fn}") nparray = np.load(fn, mmap_mode=mmap_mode) logger.info(f"Loaded nparray {nparray.shape} from {fn}") return nparray def write_nparray( self, nparray: np.ndarray, filename: str, ): fn = self.get_local_filepath(filename) logger.info(f"Saving nparray {nparray.shape} to {fn}") np.save(fn, nparray) self.upload_file_to_blobstore(filename) def read_json( self, filename: str, ): fn = self.download_file_from_blobstore(filename) logger.info(f"Loading json {fn}") with open(fn, "r") as fp: json_dict = json.load(fp) logger.info(f"Loaded json {json_dict} from {fn}") return json_dict def write_json( self, json_dict: dict[str, Any], filename: str, overwrite: bool = False, ): fn = self.get_local_filepath(filename) logger.info(f"Saving json {json_dict} to {fn}") with open(fn, "w") as fp: json.dump(json_dict, fp) self.upload_file_to_blobstore(filename, overwrite=overwrite) def read_index( self, filename: str, bucket: Optional[str] = None, path: Optional[str] = None, ): fn = self.download_file_from_blobstore(filename, bucket, path) logger.info(f"Loading index {fn}") ext = os.path.splitext(fn)[1] if ext in [".faiss", ".codec", ".index"]: index = faiss.read_index(fn) elif ext == ".pkl": with open(fn, "rb") as model_file: model = pickle.load(model_file) rcq_coarse_quantizer, itq_encoder = model["model"] index = merge_rcq_itq(rcq_coarse_quantizer, itq_encoder) logger.info(f"Loaded index from {fn}") return index def write_index( self, index: faiss.Index, filename: str, ): fn = self.get_local_filepath(filename) logger.info(f"Saving index to {fn}") faiss.write_index(index, fn) self.upload_file_to_blobstore(filename) assert os.path.exists(fn) return os.path.getsize(fn) def launch_jobs(self, func, params, local=True): if local: results = [func(p) for p in params] return results logger.info(f"launching {len(params)} jobs") executor = submitit.AutoExecutor(folder="/checkpoint/gsz/jobs") executor.update_parameters( nodes=1, gpus_per_node=8, cpus_per_task=80, # mem_gb=640, tasks_per_node=1, name="faiss_benchmark", slurm_array_parallelism=512, slurm_partition="scavenge", slurm_time=4 * 60, slurm_constraint="bldg1", ) jobs = executor.map_array(func, params) logger.info(f"launched {len(jobs)} jobs") for job, param in zip(jobs, params): logger.info(f"{job.job_id=} {param[0]=}") results = [job.result() for job in jobs] print(f"received {len(results)} results") return results
BenchmarkIO
python
python__mypy
mypy/nodes.py
{ "start": 46975, "end": 50992 }
class ____(Statement): """Class definition""" __slots__ = ( "name", "_fullname", "defs", "type_args", "type_vars", "base_type_exprs", "removed_base_type_exprs", "info", "metaclass", "decorators", "keywords", "analyzed", "has_incompatible_baseclass", "docstring", "removed_statements", ) __match_args__ = ("name", "defs") name: str # Name of the class without module prefix _fullname: str # Fully qualified name of the class defs: Block # New-style type parameters (PEP 695), unanalyzed type_args: list[TypeParam] | None # Semantically analyzed type parameters (all syntax variants) type_vars: list[mypy.types.TypeVarLikeType] # Base class expressions (not semantically analyzed -- can be arbitrary expressions) base_type_exprs: list[Expression] # Special base classes like Generic[...] get moved here during semantic analysis removed_base_type_exprs: list[Expression] info: TypeInfo # Related TypeInfo metaclass: Expression | None decorators: list[Expression] keywords: dict[str, Expression] analyzed: Expression | None has_incompatible_baseclass: bool # Used by special forms like NamedTuple and TypedDict to store invalid statements removed_statements: list[Statement] def __init__( self, name: str, defs: Block, type_vars: list[mypy.types.TypeVarLikeType] | None = None, base_type_exprs: list[Expression] | None = None, metaclass: Expression | None = None, keywords: list[tuple[str, Expression]] | None = None, type_args: list[TypeParam] | None = None, ) -> None: super().__init__() self.name = name self._fullname = "" self.defs = defs self.type_vars = type_vars or [] self.type_args = type_args self.base_type_exprs = base_type_exprs or [] self.removed_base_type_exprs = [] self.info = CLASSDEF_NO_INFO self.metaclass = metaclass self.decorators = [] self.keywords = dict(keywords) if keywords else {} self.analyzed = None self.has_incompatible_baseclass = False self.docstring: str | None = None self.removed_statements = [] @property def fullname(self) -> str: return self._fullname @fullname.setter def fullname(self, v: str) -> None: self._fullname = v def accept(self, visitor: StatementVisitor[T]) -> T: return visitor.visit_class_def(self) def is_generic(self) -> bool: return self.info.is_generic() def serialize(self) -> JsonDict: # Not serialized: defs, base_type_exprs, metaclass, decorators, # analyzed (for named tuples etc.) return { ".class": "ClassDef", "name": self.name, "fullname": self.fullname, "type_vars": [v.serialize() for v in self.type_vars], } @classmethod def deserialize(cls, data: JsonDict) -> ClassDef: assert data[".class"] == "ClassDef" res = ClassDef( data["name"], Block([]), # https://github.com/python/mypy/issues/12257 [ cast(mypy.types.TypeVarLikeType, mypy.types.deserialize_type(v)) for v in data["type_vars"] ], ) res.fullname = data["fullname"] return res def write(self, data: WriteBuffer) -> None: write_tag(data, CLASS_DEF) write_str(data, self.name) mypy.types.write_type_list(data, self.type_vars) write_str(data, self.fullname) write_tag(data, END_TAG) @classmethod def read(cls, data: ReadBuffer) -> ClassDef: res = ClassDef(read_str(data), Block([]), mypy.types.read_type_var_likes(data)) res.fullname = read_str(data) assert read_tag(data) == END_TAG return res
ClassDef
python
allegroai__clearml
clearml/backend_api/services/v2_13/workers.py
{ "start": 402, "end": 2166 }
class ____(NonStrictDataModel): """ :param name: Name of the metrics category. :type name: str :param metric_keys: The names of the metrics in the category. :type metric_keys: Sequence[str] """ _schema = { "properties": { "metric_keys": { "description": "The names of the metrics in the category.", "items": {"type": "string"}, "type": ["array", "null"], }, "name": { "description": "Name of the metrics category.", "type": ["string", "null"], }, }, "type": "object", } def __init__(self, name: Optional[str] = None, metric_keys: Optional[List[str]] = None, **kwargs: Any) -> None: super(MetricsCategory, self).__init__(**kwargs) self.name = name self.metric_keys = metric_keys @schema_property("name") def name(self) -> Optional[str]: return self._property_name @name.setter def name(self, value: Optional[str]) -> None: if value is None: self._property_name = None return self.assert_isinstance(value, "name", six.string_types) self._property_name = value @schema_property("metric_keys") def metric_keys(self) -> Optional[List[str]]: return self._property_metric_keys @metric_keys.setter def metric_keys(self, value: Optional[List[str]]) -> None: if value is None: self._property_metric_keys = None return self.assert_isinstance(value, "metric_keys", (list, tuple)) self.assert_isinstance(value, "metric_keys", six.string_types, is_array=True) self._property_metric_keys = value
MetricsCategory
python
sympy__sympy
sympy/combinatorics/free_groups.py
{ "start": 3282, "end": 9552 }
class ____(DefaultPrinting): """ Free group with finite or infinite number of generators. Its input API is that of a str, Symbol/Expr or a sequence of one of these types (which may be empty) See Also ======== sympy.polys.rings.PolyRing References ========== .. [1] https://www.gap-system.org/Manuals/doc/ref/chap37.html .. [2] https://en.wikipedia.org/wiki/Free_group """ is_associative = True is_group = True is_FreeGroup = True is_PermutationGroup = False relators: list[Expr] = [] def __new__(cls, symbols): symbols = tuple(_parse_symbols(symbols)) rank = len(symbols) _hash = hash((cls.__name__, symbols, rank)) obj = _free_group_cache.get(_hash) if obj is None: obj = object.__new__(cls) obj._hash = _hash obj._rank = rank # dtype method is used to create new instances of FreeGroupElement obj.dtype = type("FreeGroupElement", (FreeGroupElement,), {"group": obj}) obj.symbols = symbols obj.generators = obj._generators() obj._gens_set = set(obj.generators) for symbol, generator in zip(obj.symbols, obj.generators): if isinstance(symbol, Symbol): name = symbol.name if hasattr(obj, name): setattr(obj, name, generator) _free_group_cache[_hash] = obj return obj def __getnewargs__(self): """Return a tuple of arguments that must be passed to __new__ in order to support pickling this object.""" return (self.symbols,) def __getstate__(self): # Don't pickle any fields because they are regenerated within __new__ return None def _generators(group): """Returns the generators of the FreeGroup. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y, z = free_group("x, y, z") >>> F.generators (x, y, z) """ gens = [] for sym in group.symbols: elm = ((sym, 1),) gens.append(group.dtype(elm)) return tuple(gens) def clone(self, symbols=None): return self.__class__(symbols or self.symbols) def __contains__(self, i): """Return True if ``i`` is contained in FreeGroup.""" if not isinstance(i, FreeGroupElement): return False group = i.group return self == group def __hash__(self): return self._hash def __len__(self): return self.rank def __str__(self): if self.rank > 30: str_form = "<free group with %s generators>" % self.rank else: str_form = "<free group on the generators " gens = self.generators str_form += str(gens) + ">" return str_form __repr__ = __str__ def __getitem__(self, index): symbols = self.symbols[index] return self.clone(symbols=symbols) def __eq__(self, other): """No ``FreeGroup`` is equal to any "other" ``FreeGroup``. """ return self is other def index(self, gen): """Return the index of the generator `gen` from ``(f_0, ..., f_(n-1))``. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> F.index(y) 1 >>> F.index(x) 0 """ if isinstance(gen, self.dtype): return self.generators.index(gen) else: raise ValueError("expected a generator of Free Group %s, got %s" % (self, gen)) def order(self): """Return the order of the free group. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> F.order() oo >>> free_group("")[0].order() 1 """ if self.rank == 0: return S.One else: return S.Infinity @property def elements(self): """ Return the elements of the free group. Examples ======== >>> from sympy.combinatorics import free_group >>> (z,) = free_group("") >>> z.elements {<identity>} """ if self.rank == 0: # A set containing Identity element of `FreeGroup` self is returned return {self.identity} else: raise ValueError("Group contains infinitely many elements" ", hence cannot be represented") @property def rank(self): r""" In group theory, the `rank` of a group `G`, denoted `G.rank`, can refer to the smallest cardinality of a generating set for G, that is \operatorname{rank}(G)=\min\{ |X|: X\subseteq G, \left\langle X\right\rangle =G\}. """ return self._rank @property def is_abelian(self): """Returns if the group is Abelian. Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> f.is_abelian False """ return self.rank in (0, 1) @property def identity(self): """Returns the identity element of free group.""" return self.dtype() def contains(self, g): """Tests if Free Group element ``g`` belong to self, ``G``. In mathematical terms any linear combination of generators of a Free Group is contained in it. Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> f.contains(x**3*y**2) True """ return isinstance(g, FreeGroupElement) and self == g.group def center(self): """Returns the center of the free group `self`.""" return {self.identity} ############################################################################ # FreeGroupElement # ############################################################################
FreeGroup
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs.py
{ "start": 2131, "end": 2172 }
class ____: foo: int = 1 @attr.frozen
C
python
imageio__imageio
imageio/plugins/_freeimage.py
{ "start": 23817, "end": 31325 }
class ____(object): def __init__(self, fi, filename, ftype, flags): self._fi = fi self._filename = filename self._ftype = ftype self._flags = flags self._bitmap = None self._close_funcs = [] def __del__(self): self.close() def close(self): if (self._bitmap is not None) and self._close_funcs: for close_func in self._close_funcs: try: with self._fi: fun = close_func[0] fun(*close_func[1:]) except Exception: # pragma: no cover pass self._close_funcs = [] self._bitmap = None def _set_bitmap(self, bitmap, close_func=None): """Function to set the bitmap and specify the function to unload it.""" if self._bitmap is not None: pass # bitmap is converted if close_func is None: close_func = self._fi.lib.FreeImage_Unload, bitmap self._bitmap = bitmap if close_func: self._close_funcs.append(close_func) def get_meta_data(self): # todo: there is also FreeImage_TagToString, is that useful? # and would that work well when reading and then saving? # Create a list of (model_name, number) tuples models = [ (name[5:], number) for name, number in METADATA_MODELS.__dict__.items() if name.startswith("FIMD_") ] # Prepare metadata = Dict() tag = ctypes.c_void_p() with self._fi as lib: # Iterate over all FreeImage meta models for model_name, number in models: # Find beginning, get search handle mdhandle = lib.FreeImage_FindFirstMetadata( number, self._bitmap, ctypes.byref(tag) ) mdhandle = ctypes.c_void_p(mdhandle) if mdhandle: # Iterate over all tags in this model more = True while more: # Get info about tag tag_name = lib.FreeImage_GetTagKey(tag).decode("utf-8") tag_type = lib.FreeImage_GetTagType(tag) byte_size = lib.FreeImage_GetTagLength(tag) char_ptr = ctypes.c_char * byte_size data = char_ptr.from_address(lib.FreeImage_GetTagValue(tag)) # Convert in a way compatible with Pypy tag_bytes = bytes(bytearray(data)) # The default value is the raw bytes tag_val = tag_bytes # Convert to a Python value in the metadata dict if tag_type == METADATA_DATATYPE.FIDT_ASCII: tag_val = tag_bytes.decode("utf-8", "replace") elif tag_type in METADATA_DATATYPE.dtypes: dtype = METADATA_DATATYPE.dtypes[tag_type] if IS_PYPY and isinstance(dtype, (list, tuple)): pass # pragma: no cover - or we get a segfault else: try: tag_val = numpy.frombuffer( tag_bytes, dtype=dtype ).copy() if len(tag_val) == 1: tag_val = tag_val[0] except Exception: # pragma: no cover pass # Store data in dict subdict = metadata.setdefault(model_name, Dict()) subdict[tag_name] = tag_val # Next more = lib.FreeImage_FindNextMetadata( mdhandle, ctypes.byref(tag) ) # Close search handle for current meta model lib.FreeImage_FindCloseMetadata(mdhandle) # Done return metadata def set_meta_data(self, metadata): # Create a dict mapping model_name to number models = {} for name, number in METADATA_MODELS.__dict__.items(): if name.startswith("FIMD_"): models[name[5:]] = number # Create a mapping from numpy.dtype to METADATA_DATATYPE def get_tag_type_number(dtype): for number, numpy_dtype in METADATA_DATATYPE.dtypes.items(): if dtype == numpy_dtype: return number else: return None with self._fi as lib: for model_name, subdict in metadata.items(): # Get model number number = models.get(model_name, None) if number is None: continue # Unknown model, silent ignore for tag_name, tag_val in subdict.items(): # Create new tag tag = lib.FreeImage_CreateTag() tag = ctypes.c_void_p(tag) try: # Convert Python value to FI type, val is_ascii = False if isinstance(tag_val, str): try: tag_bytes = tag_val.encode("ascii") is_ascii = True except UnicodeError: pass if is_ascii: tag_type = METADATA_DATATYPE.FIDT_ASCII tag_count = len(tag_bytes) else: if not hasattr(tag_val, "dtype"): tag_val = numpy.array([tag_val]) tag_type = get_tag_type_number(tag_val.dtype) if tag_type is None: logger.warning( "imageio.freeimage warning: Could not " "determine tag type of %r." % tag_name ) continue tag_bytes = tag_val.tobytes() tag_count = tag_val.size # Set properties lib.FreeImage_SetTagKey(tag, tag_name.encode("utf-8")) lib.FreeImage_SetTagType(tag, tag_type) lib.FreeImage_SetTagCount(tag, tag_count) lib.FreeImage_SetTagLength(tag, len(tag_bytes)) lib.FreeImage_SetTagValue(tag, tag_bytes) # Store tag tag_key = lib.FreeImage_GetTagKey(tag) lib.FreeImage_SetMetadata(number, self._bitmap, tag_key, tag) except Exception as err: # pragma: no cover logger.warning( "imagio.freeimage warning: Could not set tag " "%r: %s, %s" % (tag_name, self._fi._get_error_message(), str(err)) ) finally: lib.FreeImage_DeleteTag(tag)
FIBaseBitmap
python
kamyu104__LeetCode-Solutions
Python/count-square-sum-triples.py
{ "start": 31, "end": 398 }
class ____(object): def countTriples(self, n): """ :type n: int :rtype: int """ lookup = set() for i in xrange(1, n+1): lookup.add(i**2) result = 0 for i in xrange(1, n+1): for j in xrange(1, n+1): result += int(i**2+j**2 in lookup) return result
Solution
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-neptune/llama_index/vector_stores/neptune/base.py
{ "start": 495, "end": 1074 }
class ____(Exception): """Exception for the Neptune queries.""" def __init__(self, exception: Union[str, Dict]): if isinstance(exception, dict): self.message = exception["message"] if "message" in exception else "unknown" self.details = exception["details"] if "details" in exception else "unknown" else: self.message = exception self.details = "unknown" def get_message(self) -> str: return self.message def get_details(self) -> Any: return self.details
NeptuneVectorQueryException
python
numpy__numpy
tools/swig/test/testVector.py
{ "start": 13291, "end": 13556 }
class ____(VectorTestCase): def __init__(self, methodName="runTest"): VectorTestCase.__init__(self, methodName) self.typeStr = "float" self.typeCode = "f" ######################################################################
floatTestCase
python
django-haystack__django-haystack
test_haystack/mocks.py
{ "start": 807, "end": 1175 }
class ____(SearchResult): def __init__(self, app_label, model_name, pk, score, **kwargs): super().__init__(app_label, model_name, pk, score, **kwargs) self._model = apps.get_model("core", model_name) MOCK_SEARCH_RESULTS = [ MockSearchResult("core", "MockModel", i, 1 - (i / 100.0)) for i in range(1, 100) ] MOCK_INDEX_DATA = {}
MockSearchResult
python
joke2k__faker
faker/providers/automotive/en_PH/__init__.py
{ "start": 108, "end": 2499 }
class ____(AutomotiveProvider): """Implement automotive provider for ``en_PH`` locale. Vehicle registration in the Philippines has many controversies and is full of quirks. On top of that, some terms are highly subject to interpretation or to varying definitions when applied colloquially, e.g. "motor" usually refers to either a machine's motor or a motorcycle, "vehicles" usually means cars, SUVs, vans, and trucks but not motorcycles. Please read any additional notes of individual methods for more details. Sources: - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_Philippines """ protocol_licenses = [str(x) for x in range(1, 18) if x != 15] motorcycle_license_formats = [ "??####", # 1981 series "??#####", # 2014 series ] automobile_license_formats = [ "???###", # 1981 series "???####", # 2014 series ] license_formats = motorcycle_license_formats + automobile_license_formats def _license_plate(self, license_format: List[str]) -> str: return self.bothify(self.random_element(license_format), ascii_uppercase) def protocol_license_plate(self) -> str: """Generate a protocol license plate. .. note:: High ranking government officials are entitled to use low numbered protocol license plates. """ return self.random_element(self.protocol_licenses) def motorcycle_license_plate(self) -> str: """Generate a motorcycle license plate. .. note:: Motorcycles and any improvised vehicle with a motorcycle as its base are issued motorcycle license plates. """ return self._license_plate(self.motorcycle_license_formats) def automobile_license_plate(self) -> str: """Generate an automobile license plate. .. note:: Cars, SUVs, vans, trucks, and other 4-wheeled civilian vehicles are considered automobiles for this purpose. """ return self._license_plate(self.automobile_license_formats) def license_plate(self) -> str: """Generate a license plate. .. note:: This method will never generate protocol plates, because such plates are only for specific use cases. """ return self._license_plate(self.license_formats)
Provider
python
pallets__werkzeug
examples/cupoftee/network.py
{ "start": 3595, "end": 3795 }
class ____: def __init__(self, server, name, score): self.server = server self.name = name self.score = score self.size = round(100 + log(max(score, 1)) * 25, 2)
Player
python
pytorch__pytorch
test/quantization/core/test_quantized_module.py
{ "start": 59023, "end": 79703 }
class ____(QuantizationTestCase): def _test_qconv_impl(self, q_mod, dq_mod, dim, dtype, bias): in_channels = 3 out_channels = 10 kernel_size = 2 stride = 1 padding = 0 dilation = 1 groups = 1 padding_mode = 'zeros' if qengine_is_qnnpack(): reduce_range = False else: reduce_range = True X_fp32 = torch.randn(*([in_channels] * dim)) s, z = _calculate_dynamic_qparams(X_fp32, dtype, reduce_range) X_q = torch.quantize_per_tensor(X_fp32, s, z, dtype) X_dq = torch.dequantize(X_q) quantized_module = q_mod(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode) dynamic_module = dq_mod(in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode) quantized_module.scale, quantized_module.zero_point = s, z dynamic_module.set_weight_bias(*quantized_module._weight_bias()) Y_q_ref = quantized_module(X_q) Y_ref = torch.dequantize(Y_q_ref) Y = dynamic_module(X_dq, reduce_range) self.assertEqual(Y, Y_ref) # Test serialization of quantized Conv Module using state_dict W_q, b = dynamic_module._weight_bias() model_dict = dynamic_module.state_dict() self.assertEqual(model_dict['weight'], W_q) self.assertEqual(model_dict['bias'], b) bytes_io = io.BytesIO() torch.save(model_dict, bytes_io) for weights_only in [True, False]: bytes_io.seek(0) loaded_dict = torch.load(bytes_io, weights_only=weights_only) for key in loaded_dict: self.assertEqual(model_dict[key], loaded_dict[key]) loaded_qconv_module = type(dynamic_module)( in_channels, out_channels, kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode) loaded_qconv_module.load_state_dict(loaded_dict) self.assertTrue(dir(loaded_qconv_module) == dir(dynamic_module)) self.assertTrue(dynamic_module._get_name() == loaded_qconv_module._get_name()) self.assertTrue(hasattr(loaded_qconv_module, '_packed_params')) self.assertTrue(hasattr(loaded_qconv_module, '_weight_bias')) self.assertEqual(dynamic_module.weight(), loaded_qconv_module.weight()) if bias: self.assertEqual(dynamic_module.bias(), loaded_qconv_module.bias()) self.assertEqual(dynamic_module.scale, loaded_qconv_module.scale) self.assertEqual(dynamic_module.zero_point, loaded_qconv_module.zero_point) Y_loaded = loaded_qconv_module(X_fp32, reduce_range) np.testing.assert_array_almost_equal( Y.numpy(), Y_loaded.numpy(), decimal=0) # Test serialization b = io.BytesIO() torch.save(dynamic_module, b) b.seek(0) # weights_only=False as this is legacy code that saves the model loaded_conv = torch.load(b, weights_only=False) self.assertEqual(loaded_conv.bias(), dynamic_module.bias()) self.assertEqual(loaded_conv.scale, dynamic_module.scale) self.assertEqual(loaded_conv.zero_point, dynamic_module.zero_point) # Test copy and deepcopy copied_conv = copy.copy(dynamic_module) self.assertEqual(copied_conv.bias(), dynamic_module.bias()) self.assertEqual(copied_conv.scale, dynamic_module.scale) self.assertEqual(copied_conv.zero_point, dynamic_module.zero_point) Y_copied = copied_conv(X_fp32, reduce_range) np.testing.assert_array_almost_equal( Y.numpy(), Y_copied.numpy(), decimal=0) deepcopied_conv = copy.deepcopy(dynamic_module) self.assertEqual(deepcopied_conv.bias(), dynamic_module.bias()) self.assertEqual(deepcopied_conv.scale, dynamic_module.scale) self.assertEqual(deepcopied_conv.zero_point, dynamic_module.zero_point) Y_deepcopied = copied_conv(X_fp32, reduce_range) np.testing.assert_array_almost_equal( Y.numpy(), Y_deepcopied.numpy(), decimal=0) # need to fix this # JIT testing self.checkScriptable( dynamic_module, [[X_dq]], check_save_load=True) # Test from_float conv_module = dynamic_module._FLOAT_MODULE(in_channels, out_channels, kernel_size) conv_module.qconfig = torch.ao.quantization.default_dynamic_qconfig # type: ignore[assignment] prepare_dynamic(conv_module) conv_module(X_dq) quantized_conv_module = dq_mod.from_float(conv_module) # Smoke test to make sure the module actually runs quantized_conv_module(X_dq) # Smoke test extra_repr self.assertEqual(dynamic_module._get_name(), quantized_conv_module._get_name()) @override_qengines def test_dynamic_conv1d(self): q_mod = torch.ao.nn.quantized.Conv1d dq_mod = torch.ao.nn.quantized.dynamic.Conv1d dim = 3 dtype = torch.quint8 for bias in [True, False]: self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias) @override_qengines def test_dynamic_conv2d(self): q_mod = torch.ao.nn.quantized.Conv2d dq_mod = torch.ao.nn.quantized.dynamic.Conv2d dim = 4 dtype = torch.quint8 for bias in [True, False]: self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias) @override_qengines def test_dynamic_conv3d(self): q_mod = torch.ao.nn.quantized.Conv3d dq_mod = torch.ao.nn.quantized.dynamic.Conv3d dim = 5 dtype = torch.quint8 if qengine_is_qnnpack(): return # qnnpack doesn't support unpacking conv3d for bias in [True, False]: self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias) @override_qengines def test_dynamic_convtranspose1d(self): q_mod = torch.ao.nn.quantized.ConvTranspose1d dq_mod = torch.ao.nn.quantized.dynamic.ConvTranspose1d dim = 3 dtype = torch.quint8 for bias in [True, False]: self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias) @override_qengines def test_dynamic_convtranspose2d(self): q_mod = torch.ao.nn.quantized.ConvTranspose2d dq_mod = torch.ao.nn.quantized.dynamic.ConvTranspose2d dim = 4 dtype = torch.quint8 for bias in [True, False]: self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias) @override_qengines def test_dynamic_convtranspose3d(self): q_mod = torch.ao.nn.quantized.ConvTranspose3d dq_mod = torch.ao.nn.quantized.dynamic.ConvTranspose3d dim = 5 dtype = torch.quint8 if qengine_is_qnnpack(): return # qnnpack doesn't support unpacking conv3d for bias in [True, False]: self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias) @given( batch_size=st.integers(1, 5), in_features=st.integers(16, 32), out_features=st.integers(4, 8), use_bias=st.booleans(), use_default_observer=st.booleans(), ) @override_qengines def test_linear_api(self, batch_size, in_features, out_features, use_bias, use_default_observer): """test API functionality for nn.quantized.dynamic.Linear""" W = torch.rand(out_features, in_features).float() qscheme = torch.per_tensor_symmetric if qengine_is_onednn() else torch.per_tensor_affine W_scale, W_zp = _calculate_dynamic_qparams(W, torch.qint8, qscheme=qscheme) W_q = torch.quantize_per_tensor(W, W_scale, W_zp, torch.qint8) X = torch.rand(batch_size, in_features).float() B = torch.rand(out_features).float() if use_bias else None qlinear = nnqd.Linear(in_features, out_features) # Run module with default-initialized parameters. # This tests that the constructor is correct. qlinear.set_weight_bias(W_q, B) qlinear(X) # Simple round-trip test to ensure weight()/set_weight() API self.assertEqual(qlinear.weight(), W_q) W_pack = qlinear._packed_params._packed_params Z_dq = qlinear(X) # Check if the module implementation matches calling the # ops directly Z_ref = torch.ops.quantized.linear_dynamic(X, W_pack, reduce_range=True) self.assertEqual(Z_ref, Z_dq) # Test serialization of dynamic quantized Linear Module using state_dict model_dict = qlinear.state_dict() b = io.BytesIO() torch.save(model_dict, b) for weights_only in [True, False]: b.seek(0) loaded_dict = torch.load(b, weights_only=weights_only) for key in model_dict: if isinstance(model_dict[key], torch._C.ScriptObject): assert isinstance(loaded_dict[key], torch._C.ScriptObject) w_model, b_model = torch.ops.quantized.linear_unpack(model_dict[key]) w_loaded, b_loaded = torch.ops.quantized.linear_unpack(loaded_dict[key]) self.assertEqual(w_model, w_loaded) self.assertEqual(b_model, b_loaded) else: self.assertEqual(model_dict[key], loaded_dict[key]) loaded_qlinear = nnqd.Linear(in_features, out_features) loaded_qlinear.load_state_dict(loaded_dict) linear_unpack = torch.ops.quantized.linear_unpack self.assertEqual(linear_unpack(qlinear._packed_params._packed_params), linear_unpack(loaded_qlinear._packed_params._packed_params)) if use_bias: self.assertEqual(qlinear.bias(), loaded_qlinear.bias()) self.assertTrue(dir(qlinear) == dir(loaded_qlinear)) self.assertTrue(hasattr(qlinear, '_packed_params')) self.assertTrue(hasattr(loaded_qlinear, '_packed_params')) self.assertTrue(hasattr(qlinear, '_weight_bias')) self.assertTrue(hasattr(loaded_qlinear, '_weight_bias')) self.assertEqual(qlinear._weight_bias(), loaded_qlinear._weight_bias()) self.assertEqual(qlinear._weight_bias(), torch.ops.quantized.linear_unpack(qlinear._packed_params._packed_params)) Z_dq2 = qlinear(X) self.assertEqual(Z_dq, Z_dq2) b = io.BytesIO() torch.save(qlinear, b) b.seek(0) # weights_only=False as this is legacy code that saves the model loaded = torch.load(b, weights_only=False) self.assertEqual(qlinear.weight(), loaded.weight()) self.assertEqual(qlinear.zero_point, loaded.zero_point) # Test JIT self.checkScriptable(qlinear, [[X]], check_save_load=True) modules_under_test = [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear] for mut in modules_under_test: # Test from_float float_linear = mut(in_features, out_features).float() if use_default_observer: float_linear.qconfig = torch.ao.quantization.default_dynamic_qconfig prepare_dynamic(float_linear) float_linear(X.float()) quantized_float_linear = nnqd.Linear.from_float(float_linear) # Smoke test to make sure the module actually runs quantized_float_linear(X) # Smoke test extra_repr self.assertTrue('QuantizedLinear' in str(quantized_float_linear)) @given( dtype=st.sampled_from([torch.qint8, torch.float16]), bidirectional=st.booleans(), ) @override_qengines def test_lstm_api(self, dtype, bidirectional): r"""Test execution and serialization for dynamic quantized lstm modules on int8 and fp16 """ # Check that module matches the numerics of the op and ensure that module can be # instantiated for all engines and dtypes seq_len = 4 batch = 2 input_size = 3 hidden_size = 7 num_layers = 2 bias = True weight_keys = [] bias_keys = [] num_directions = 2 if bidirectional else 1 for layer in range(num_layers): for direction in range(num_directions): suffix = '_reverse' if direction == 1 else '' key_name1 = f'weight_ih_l{layer}{suffix}' key_name2 = f'weight_hh_l{layer}{suffix}' weight_keys.append(key_name1) weight_keys.append(key_name2) key_name1 = f'bias_ih_l{layer}{suffix}' key_name2 = f'bias_hh_l{layer}{suffix}' bias_keys.append(key_name1) bias_keys.append(key_name2) if not (dtype == torch.float16 and torch.backends.quantized.engine in ("qnnpack", "onednn")): # fp16 dynamic quant is not supported for qnnpack or onednn x = torch.randn(seq_len, batch, input_size) h = torch.randn(num_layers * (bidirectional + 1), batch, hidden_size) c = torch.randn(num_layers * (bidirectional + 1), batch, hidden_size) cell_dq = torch.ao.nn.quantized.dynamic.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bias=bias, batch_first=False, dropout=0.0, bidirectional=bidirectional, dtype=dtype) ref_dq = torch.ao.nn.quantized.dynamic.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bias=bias, batch_first=False, dropout=0.0, bidirectional=bidirectional, dtype=dtype) _all_params = ([m.param for m in cell_dq._all_weight_values]) result = torch.quantized_lstm(x, (h, c), _all_params, cell_dq.bias, cell_dq.num_layers, float(cell_dq.dropout), False, bidirectional, False, dtype=dtype, use_dynamic=True) y, (h, c) = cell_dq(x, (h, c)) self.assertEqual(result[0], y) self.assertEqual(result[1], h) self.assertEqual(result[2], c) x = torch.randn(10, 20, 3) self.check_eager_serialization(cell_dq, ref_dq, [x]) self.check_weight_bias_api(cell_dq, weight_keys, bias_keys) @override_qengines def test_gru_api(self): r"""Test execution and serialization for dynamic quantized lstm modules on int8 and fp16 """ # Check that module matches the numerics of the op and ensure that module can be # instantiated for all engines and dtypes for dtype in [torch.qint8, torch.float16]: if dtype == torch.float16 and torch.backends.quantized.engine in ("qnnpack", "onednn"): # fp16 dynamic quant is not supported for qnnpack or onednn continue # Test default instantiation seq_len = 4 batch = 2 input_size = 3 hidden_size = 7 num_layers = 2 bias = True bidirectional = False x = torch.rand(seq_len, batch, input_size) h = torch.rand(num_layers * (bidirectional + 1), batch, hidden_size) cell_dq = torch.ao.nn.quantized.dynamic.GRU(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, bias=bias, batch_first=False, dropout=0.0, bidirectional=bidirectional, dtype=dtype) _all_params = ([m.param for m in cell_dq._all_weight_values]) result = torch.quantized_gru(x, h, _all_params, cell_dq.bias, cell_dq.num_layers, float(cell_dq.dropout), False, bidirectional, False) y, h = cell_dq(x, h) self.assertEqual(result[0], y, msg="GRU module API failed") self.assertEqual(result[1], h, msg="GRU module API failed") @given( dtype=st.sampled_from([torch.qint8, torch.float16]), ) @override_qengines def test_cell_api(self, dtype): r"""Test execution and serialization for dynamic quantized lstm modules on int8 and fp16 """ # Check that module matches the numerics of the op and ensure that module can be # instantiated for all engines and dtypes batch = 7 input_size = 3 hidden_size = 7 bias = True x = torch.rand(batch, input_size) h = torch.rand(batch, hidden_size) cell_dict = {'LSTMCell': torch.ao.nn.quantized.dynamic.LSTMCell, 'GRUCell': torch.ao.nn.quantized.dynamic.GRUCell, 'RNNTanh': torch.ao.nn.quantized.dynamic.RNNCell, 'RNNReLU': torch.ao.nn.quantized.dynamic.RNNCell } state = {'LSTMCell': (h, h), 'GRUCell': h, 'RNNTanh': h, 'RNNReLU': h} qfn_dict = {'LSTMCell': torch.ops.quantized.quantized_lstm_cell_dynamic, 'GRUCell': torch.ops.quantized.quantized_gru_cell_dynamic, 'RNNTanh': torch.ops.quantized.quantized_rnn_tanh_cell_dynamic, 'RNNReLU': torch.ops.quantized.quantized_rnn_relu_cell_dynamic} for rnn_type in cell_dict: if not (dtype == torch.float16 and torch.backends.quantized.engine in ("qnnpack", "onednn")): # fp16 dynamic quant is not supported for qnnpack or onednn kwargs = {'input_size': input_size, 'hidden_size': hidden_size, 'bias': bias, 'dtype': dtype} if rnn_type == 'RNNReLU': kwargs['nonlinearity'] = "relu" elif rnn_type == 'RNNTanh': kwargs['nonlinearity'] = "tanh" cell_dq = cell_dict[rnn_type](**kwargs) result = qfn_dict[rnn_type](x, state[rnn_type], cell_dq._packed_weight_ih, cell_dq._packed_weight_hh, cell_dq.bias_ih, cell_dq.bias_hh) result_module = cell_dq(x, state[rnn_type]) self.assertEqual(result[0], result_module[0], msg="RNNCell module API failed") self.assertEqual(result[1], result_module[1], msg="RNNCell module API failed") weight_keys = ['weight_ih', 'weight_hh'] bias_keys = ['bias_ih', 'bias_hh'] self.check_eager_serialization(cell_dq, cell_dict[rnn_type](**kwargs), [x]) self.check_weight_bias_api(cell_dq, weight_keys, bias_keys)
TestDynamicQuantizedModule
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_cloud_batch.py
{ "start": 13066, "end": 13939 }
class ____: @pytest.mark.asyncio @mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__", new=mock_base_gcp_hook_default_project_id, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_batch.BatchServiceAsyncClient") async def test_get_job(self, mock_client): expected_job = {"name": "somename"} async def _get_job(name): return expected_job job_name = "jobname" mock_client.return_value = mock.MagicMock() mock_client.return_value.get_job = _get_job hook = CloudBatchAsyncHook() hook.get_credentials = self._dummy_get_credentials returned_operation = await hook.get_batch_job(job_name=job_name) assert returned_operation == expected_job def _dummy_get_credentials(self): pass
TestCloudBatchAsyncHook
python
aio-libs__aiohttp
aiohttp/pytest_plugin.py
{ "start": 621, "end": 1156 }
class ____(Protocol): # TODO(PY311): Use Unpack to specify ClientSession kwargs. @overload async def __call__( self, __param: Application, *, server_kwargs: dict[str, Any] | None = None, **kwargs: Any, ) -> TestClient[Request, Application]: ... @overload async def __call__( self, __param: BaseTestServer[_Request], *, server_kwargs: dict[str, Any] | None = None, **kwargs: Any, ) -> TestClient[_Request, None]: ...
AiohttpClient
python
doocs__leetcode
solution/0400-0499/0452.Minimum Number of Arrows to Burst Balloons/Solution.py
{ "start": 0, "end": 259 }
class ____: def findMinArrowShots(self, points: List[List[int]]) -> int: ans, last = 0, -inf for a, b in sorted(points, key=lambda x: x[1]): if a > last: ans += 1 last = b return ans
Solution
python
pypa__warehouse
warehouse/search/tasks.py
{ "start": 2740, "end": 9434 }
class ____(Lock): def __init__(self, redis_client, timeout=None, blocking_timeout=None): super().__init__( redis_client, name="search-index", timeout=timeout, blocking_timeout=blocking_timeout, ) @tasks.task(bind=True, ignore_result=True, acks_late=True) def reindex(self, request): """ Recreate the Search Index. """ r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"]) try: with SearchLock(r, timeout=30 * 60, blocking_timeout=30): p = parse_url(request.registry.settings["opensearch.url"]) qs = urllib.parse.parse_qs(p.query) kwargs = { "hosts": [urllib.parse.urlunparse((p.scheme, p.netloc) + ("",) * 4)], "verify_certs": True, "ca_certs": certifi.where(), "timeout": 30, "retry_on_timeout": True, "serializer": opensearchpy.serializer.serializer, } aws_auth = bool(qs.get("aws_auth", False)) if aws_auth: aws_region = qs.get("region", ["us-east-1"])[0] kwargs["connection_class"] = opensearchpy.RequestsHttpConnection kwargs["http_auth"] = requests_aws4auth.AWS4Auth( request.registry.settings["aws.key_id"], request.registry.settings["aws.secret_key"], aws_region, "es", ) client = opensearchpy.OpenSearch(**kwargs) number_of_replicas = request.registry.get("opensearch.replicas", 0) refresh_interval = request.registry.get("opensearch.interval", "1s") # We use a randomly named index so that we can do a zero downtime reindex. # Essentially we'll use a randomly named index which we will use until all # of the data has been reindexed, at which point we'll point an alias at # our randomly named index, and then delete the old randomly named index. # Create the new index and associate all of our doc types with it. index_base = request.registry["opensearch.index"] random_token = binascii.hexlify(os.urandom(5)).decode("ascii") new_index_name = f"{index_base}-{random_token}" doc_types = request.registry.get("search.doc_types", set()) shards = request.registry.get("opensearch.shards", 1) # Create the new index with zero replicas and index refreshes disabled # while we are bulk indexing. new_index = get_index( new_index_name, doc_types, using=client, shards=shards, replicas=0, interval="-1", ) new_index.create(wait_for_active_shards=shards) # From this point on, if any error occurs, we want to be able to delete our # in progress index. try: request.db.execute(text("SET statement_timeout = '600s'")) for _ in parallel_bulk( client, _project_docs(request.db), index=new_index_name, chunk_size=100, max_chunk_bytes=10 * 1024 * 1024, # 10MB, per OpenSearch defaults ): pass except: # noqa new_index.delete() raise finally: request.db.rollback() request.db.close() # Now that we've finished indexing all of our data we can update the # replicas and refresh intervals. client.indices.put_settings( index=new_index_name, body={ "index": { "number_of_replicas": number_of_replicas, "refresh_interval": refresh_interval, } }, ) # Point the alias at our new randomly named index and delete the old index. if client.indices.exists_alias(name=index_base): to_delete = set() actions = [] for name in client.indices.get_alias(name=index_base): to_delete.add(name) actions.append({"remove": {"index": name, "alias": index_base}}) actions.append({"add": {"index": new_index_name, "alias": index_base}}) client.indices.update_aliases(body={"actions": actions}) for index_to_delete in to_delete: client.indices.delete(index=index_to_delete) else: client.indices.put_alias(name=index_base, index=new_index_name) except redis.exceptions.LockError as exc: sentry_sdk.capture_exception(exc) raise self.retry(countdown=60, exc=exc) @tasks.task(bind=True, ignore_result=True, acks_late=True) def reindex_project(self, request, project_name): r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"]) try: with SearchLock(r, timeout=15, blocking_timeout=1): client = request.registry["opensearch.client"] doc_types = request.registry.get("search.doc_types", set()) index_name = request.registry["opensearch.index"] get_index( index_name, doc_types, using=client, shards=request.registry.get("opensearch.shards", 1), replicas=request.registry.get("opensearch.replicas", 0), ) for _ in parallel_bulk( client, _project_docs(request.db, project_name), index=index_name ): pass except redis.exceptions.LockError as exc: sentry_sdk.capture_exception(exc) raise self.retry(countdown=60, exc=exc) @tasks.task(bind=True, ignore_result=True, acks_late=True) def unindex_project(self, request, project_name): r = redis.StrictRedis.from_url(request.registry.settings["celery.scheduler_url"]) try: with SearchLock(r, timeout=15, blocking_timeout=1): client = request.registry["opensearch.client"] index_name = request.registry["opensearch.index"] try: client.delete(index=index_name, id=project_name) except opensearchpy.exceptions.NotFoundError: pass except redis.exceptions.LockError as exc: sentry_sdk.capture_exception(exc) raise self.retry(countdown=60, exc=exc)
SearchLock
python
MongoEngine__mongoengine
mongoengine/base/datastructures.py
{ "start": 6569, "end": 12347 }
class ____(BaseList): @classmethod def __match_all(cls, embedded_doc, kwargs): """Return True if a given embedded doc matches all the filter kwargs. If it doesn't return False. """ for key, expected_value in kwargs.items(): doc_val = getattr(embedded_doc, key) if doc_val != expected_value and str(doc_val) != expected_value: return False return True @classmethod def __only_matches(cls, embedded_docs, kwargs): """Return embedded docs that match the filter kwargs.""" if not kwargs: return embedded_docs return [doc for doc in embedded_docs if cls.__match_all(doc, kwargs)] def filter(self, **kwargs): """ Filters the list by only including embedded documents with the given keyword arguments. This method only supports simple comparison (e.g. .filter(name='John Doe')) and does not support operators like __gte, __lte, __icontains like queryset.filter does :param kwargs: The keyword arguments corresponding to the fields to filter on. *Multiple arguments are treated as if they are ANDed together.* :return: A new ``EmbeddedDocumentList`` containing the matching embedded documents. Raises ``AttributeError`` if a given keyword is not a valid field for the embedded document class. """ values = self.__only_matches(self, kwargs) return EmbeddedDocumentList(values, self._instance, self._name) def exclude(self, **kwargs): """ Filters the list by excluding embedded documents with the given keyword arguments. :param kwargs: The keyword arguments corresponding to the fields to exclude on. *Multiple arguments are treated as if they are ANDed together.* :return: A new ``EmbeddedDocumentList`` containing the non-matching embedded documents. Raises ``AttributeError`` if a given keyword is not a valid field for the embedded document class. """ exclude = self.__only_matches(self, kwargs) values = [item for item in self if item not in exclude] return EmbeddedDocumentList(values, self._instance, self._name) def count(self): """ The number of embedded documents in the list. :return: The length of the list, equivalent to the result of ``len()``. """ return len(self) def get(self, **kwargs): """ Retrieves an embedded document determined by the given keyword arguments. :param kwargs: The keyword arguments corresponding to the fields to search on. *Multiple arguments are treated as if they are ANDed together.* :return: The embedded document matched by the given keyword arguments. Raises ``DoesNotExist`` if the arguments used to query an embedded document returns no results. ``MultipleObjectsReturned`` if more than one result is returned. """ values = self.__only_matches(self, kwargs) if len(values) == 0: raise DoesNotExist("%s matching query does not exist." % self._name) elif len(values) > 1: raise MultipleObjectsReturned( "%d items returned, instead of 1" % len(values) ) return values[0] def first(self): """Return the first embedded document in the list, or ``None`` if empty. """ if len(self) > 0: return self[0] def create(self, **values): """ Creates a new instance of the EmbeddedDocument and appends it to this EmbeddedDocumentList. .. note:: the instance of the EmbeddedDocument is not automatically saved to the database. You still need to call .save() on the parent Document. :param values: A dictionary of values for the embedded document. :return: The new embedded document instance. """ name = self._name EmbeddedClass = self._instance._fields[name].field.document_type_obj self._instance[self._name].append(EmbeddedClass(**values)) return self._instance[self._name][-1] def save(self, *args, **kwargs): """ Saves the ancestor document. :param args: Arguments passed up to the ancestor Document's save method. :param kwargs: Keyword arguments passed up to the ancestor Document's save method. """ self._instance.save(*args, **kwargs) def delete(self): """ Deletes the embedded documents from the database. .. note:: The embedded document changes are not automatically saved to the database after calling this method. :return: The number of entries deleted. """ values = list(self) for item in values: self._instance[self._name].remove(item) return len(values) def update(self, **update): """ Updates the embedded documents with the given replacement values. This function does not support mongoDB update operators such as ``inc__``. .. note:: The embedded document changes are not automatically saved to the database after calling this method. :param update: A dictionary of update values to apply to each embedded document. :return: The number of entries updated. """ if len(update) == 0: return 0 values = list(self) for item in values: for k, v in update.items(): setattr(item, k, v) return len(values)
EmbeddedDocumentList
python
tensorflow__tensorflow
tensorflow/python/eager/forwardprop_test.py
{ "start": 38816, "end": 40863 }
class ____(test.TestCase, parameterized.TestCase): @parameterized.parameters([(math_ops.sin, (2, 3), 5), (math_ops.sin, (2, 3, 4), 10)]) def testJVPBatchCorrectness(self, f, primal_shape, batch_size): primals = [random_ops.random_uniform(primal_shape)] tangent_batch = [random_ops.random_uniform([batch_size, *primal_shape])] self.assertAllClose( _jvp_batch(f, primals, tangent_batch)[1], _jvp_batch_matmul(f, primals, *tangent_batch)) def testBatchCorrectness(self): x = constant_op.constant(2.0) y = constant_op.constant(5.0) tangents = ( constant_op.constant([1., 0., 1.]), constant_op.constant([0., 1., 1.]), ) with forwardprop.ForwardAccumulator._batch_accumulator((x, y), tangents) as acc: z = x * y self.assertAllClose(acc.jvp(z), constant_op.constant([5.0, 2.0, 7.0])) @parameterized.named_parameters([("ForwardPropFirst", True), ("TapeFirst", False)]) def testBatchBackwardOverForward(self, forward_prop_first): x = constant_op.constant(1.) tangents = random_ops.random_normal(shape=[10], seed=1) expected = [-t * math_ops.cos(1.) for t in tangents] if forward_prop_first: batch_acc = forwardprop.ForwardAccumulator._batch_accumulator(x, tangents) gradient_tape = backprop.GradientTape(persistent=True) else: gradient_tape = backprop.GradientTape(persistent=True) batch_acc = forwardprop.ForwardAccumulator._batch_accumulator(x, tangents) with gradient_tape as tape: with batch_acc as acc: tape.watch(x) y = math_ops.cos(x) self.assertTrue(record.should_record_backprop((acc.jvp(y),))) jvps = acc.jvp(y) d2y_dx2 = [tape.gradient(dy_dx, x) for dy_dx in jvps] self.assertAllClose(expected, d2y_dx2) if __name__ == "__main__": # TODO(allenl): Also test with 1.x-style graph mode. ops.enable_eager_execution() test.main()
BatchTests
python
pydantic__pydantic
pydantic-core/tests/serializers/test_string.py
{ "start": 6534, "end": 6578 }
class ____(str, BasicClass): pass
StrMixin
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 186915, "end": 186998 }
class ____(_Int4RangeTests, _RangeTypeCompilation): pass
Int4RangeCompilationTest
python
scipy__scipy
scipy/linalg/tests/test_decomp.py
{ "start": 112075, "end": 117147 }
class ____: def test_null_space(self): rng = np.random.RandomState(1) dtypes = [np.float32, np.float64, np.complex64, np.complex128] sizes = [1, 2, 3, 10, 100] for dt, n in itertools.product(dtypes, sizes): X = np.ones((2, n), dtype=dt) eps = np.finfo(dt).eps tol = 1000 * eps Y = null_space(X) assert_equal(Y.shape, (n, n-1)) assert_allclose(X @ Y, 0, atol=tol) Y = null_space(X.T) assert_equal(Y.shape, (2, 1)) assert_allclose(X.T @ Y, 0, atol=tol) X = rng.randn(1 + n//2, n) Y = null_space(X) assert_equal(Y.shape, (n, n - 1 - n//2)) assert_allclose(X @ Y, 0, atol=tol) if n > 5: rng = np.random.RandomState(1) X = rng.rand(n, 5) @ rng.rand(5, n) X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n) X = X.astype(dt) Y = null_space(X, rcond=1e-3) assert_equal(Y.shape, (n, n - 5)) Y = null_space(X, rcond=1e-6) assert_equal(Y.shape, (n, n - 6)) @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64]) def test_null_space_empty(self, dt): a = np.empty((0, 0), dtype=dt) a0 = np.eye(2, dtype=dt) nsa = null_space(a) assert nsa.shape == (0, 0) assert nsa.dtype == null_space(a0).dtype @pytest.mark.parametrize("overwrite_a", [True, False]) @pytest.mark.parametrize("check_finite", [True, False]) @pytest.mark.parametrize("lapack_driver", ["gesdd", "gesvd"]) def test_null_space_options(self, overwrite_a, check_finite, lapack_driver): rng = np.random.default_rng(42887289350573064398746) n = 10 X = rng.standard_normal((1 + n//2, n)) Y = null_space(X.copy(), overwrite_a=overwrite_a, check_finite=check_finite, lapack_driver=lapack_driver) assert_allclose(X @ Y, 0, atol=np.finfo(X.dtype).eps*100) def test_subspace_angles(): H = hadamard(8, float) A = H[:, :3] B = H[:, 3:] assert_allclose(subspace_angles(A, B), [np.pi / 2.] * 3, atol=1e-14) assert_allclose(subspace_angles(B, A), [np.pi / 2.] * 3, atol=1e-14) for x in (A, B): assert_allclose(subspace_angles(x, x), np.zeros(x.shape[1]), atol=1e-14) # From MATLAB function "subspace", which effectively only returns the # last value that we calculate x = np.array( [[0.537667139546100, 0.318765239858981, 3.578396939725760, 0.725404224946106], # noqa: E501 [1.833885014595086, -1.307688296305273, 2.769437029884877, -0.063054873189656], # noqa: E501 [-2.258846861003648, -0.433592022305684, -1.349886940156521, 0.714742903826096], # noqa: E501 [0.862173320368121, 0.342624466538650, 3.034923466331855, -0.204966058299775]]) # noqa: E501 expected = 1.481454682101605 assert_allclose(subspace_angles(x[:, :2], x[:, 2:])[0], expected, rtol=1e-12) assert_allclose(subspace_angles(x[:, 2:], x[:, :2])[0], expected, rtol=1e-12) expected = 0.746361174247302 assert_allclose(subspace_angles(x[:, :2], x[:, [2]]), expected, rtol=1e-12) assert_allclose(subspace_angles(x[:, [2]], x[:, :2]), expected, rtol=1e-12) expected = 0.487163718534313 assert_allclose(subspace_angles(x[:, :3], x[:, [3]]), expected, rtol=1e-12) assert_allclose(subspace_angles(x[:, [3]], x[:, :3]), expected, rtol=1e-12) expected = 0.328950515907756 assert_allclose(subspace_angles(x[:, :2], x[:, 1:]), [expected, 0], atol=1e-12) # Degenerate conditions assert_raises(ValueError, subspace_angles, x[0], x) assert_raises(ValueError, subspace_angles, x, x[0]) assert_raises(ValueError, subspace_angles, x[:-1], x) # Test branch if mask.any is True: A = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0], [0, 0, 0]]) B = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 0], [0, 0, 1]]) expected = np.array([np.pi/2, 0, 0]) assert_allclose(subspace_angles(A, B), expected, rtol=1e-12) # Complex # second column in "b" does not affect result, just there so that # b can have more cols than a, and vice-versa (both conditional code paths) a = [[1 + 1j], [0]] b = [[1 - 1j, 0], [0, 1]] assert_allclose(subspace_angles(a, b), 0., atol=1e-14) assert_allclose(subspace_angles(b, a), 0., atol=1e-14) # Empty a = np.empty((0, 0)) b = np.empty((0, 0)) assert_allclose(subspace_angles(a, b), np.empty((0,))) a = np.empty((2, 0)) b = np.empty((2, 0)) assert_allclose(subspace_angles(a, b), np.empty((0,))) a = np.empty((0, 2)) b = np.empty((0, 3)) assert_allclose(subspace_angles(a, b), np.empty((0,)))
TestNullSpace
python
getsentry__sentry
src/sentry/integrations/jira_server/actions/form.py
{ "start": 348, "end": 949 }
class ____(IntegrationNotifyServiceForm): provider = IntegrationProviderSlug.JIRA_SERVER.value def clean(self) -> dict[str, Any] | None: cleaned_data = super().clean() or {} integration_id = cleaned_data.get("integration") integration = integration_service.get_integration( integration_id=integration_id, provider=self.provider ) if not integration: raise forms.ValidationError( _("Jira Server integration is a required field."), code="invalid" ) return cleaned_data
JiraServerNotifyServiceForm
python
Pylons__pyramid
src/pyramid/config/assets.py
{ "start": 7039, "end": 7267 }
class ____: def __init__(self, path, source): self.path = path self.source = source def __call__(self, resource_name): if resource_name == self.path: return self.source, ''
FileOverride
python
airbytehq__airbyte
airbyte-integrations/connectors/source-monday/components.py
{ "start": 17057, "end": 18948 }
class ____(PageIncrement): """ Page increment strategy with subpages for the `items` stream. From the `items` documentation https://developer.monday.com/api-reference/docs/items: Please note that you cannot return more than 100 items per query when using items at the root. To adjust your query, try only returning items on a specific board, nesting items inside a boards query, looping through the boards on your account, or querying less than 100 items at a time. This pagination strategy supports nested loop through `boards` on the top level and `items` on the second. See boards documentation for more details: https://developer.monday.com/api-reference/docs/boards#queries. """ def __post_init__(self, parameters: Mapping[str, Any]): # `self._page` corresponds to board page number # `self._sub_page` corresponds to item page number within its board self.start_from_page = 1 self._page: Optional[int] = self.start_from_page self._sub_page: Optional[int] = self.start_from_page def next_page_token( self, response: requests.Response, last_page_size: int, last_record: Optional[Record], last_page_token_value: Optional[Any] ) -> Optional[Tuple[Optional[int], Optional[int]]]: """ Determines page and subpage numbers for the `items` stream Attributes: response: Contains `boards` and corresponding lists of `items` for each `board` last_records: Parsed `items` from the response """ if last_page_size >= self.page_size: self._sub_page += 1 else: self._sub_page = self.start_from_page if response.json()["data"].get("boards"): self._page += 1 else: return None return self._page, self._sub_page
ItemPaginationStrategy
python
openai__openai-python
src/openai/types/responses/response_function_tool_call_item.py
{ "start": 199, "end": 340 }
class ____(ResponseFunctionToolCall): id: str # type: ignore """The unique ID of the function tool call."""
ResponseFunctionToolCallItem
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 925882, "end": 926600 }
class ____(sgqlc.types.Type): """Autogenerated return type of RemoveEnterpriseMember""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "enterprise", "user", "viewer") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" enterprise = sgqlc.types.Field("Enterprise", graphql_name="enterprise") """The updated enterprise.""" user = sgqlc.types.Field("User", graphql_name="user") """The user that was removed from the enterprise.""" viewer = sgqlc.types.Field("User", graphql_name="viewer") """The viewer performing the mutation."""
RemoveEnterpriseMemberPayload
python
numba__numba
numba/cuda/tests/cudapy/test_vectorize_decor.py
{ "start": 549, "end": 1548 }
class ____(CUDATestCase): def test_broadcast(self): a = np.random.randn(100, 3, 1) b = a.transpose(2, 1, 0) def fn(a, b): return a - b @vectorize(['float64(float64,float64)'], target='cuda') def fngpu(a, b): return a - b expect = fn(a, b) got = fngpu(a, b) np.testing.assert_almost_equal(expect, got) def test_device_broadcast(self): """ Same test as .test_broadcast() but with device array as inputs """ a = np.random.randn(100, 3, 1) b = a.transpose(2, 1, 0) def fn(a, b): return a - b @vectorize(['float64(float64,float64)'], target='cuda') def fngpu(a, b): return a - b expect = fn(a, b) got = fngpu(cuda.to_device(a), cuda.to_device(b)) np.testing.assert_almost_equal(expect, got.copy_to_host()) @skip_on_cudasim('ufunc API unsupported in the simulator')
TestGPUVectorizeBroadcast
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 38444, "end": 39551 }
class ____( _CompositeTestBase, fixtures.MappedTest ): @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("x", Integer, default=5), Column("y", Integer, default=9), Column("unrelated_data", String(50)), ) @classmethod def setup_mappers(cls): foo = cls.tables.foo cls.Point = cls._type_fixture() cls.mapper_registry.map_imperatively( Foo, foo, properties={"data": composite(cls.Point, foo.c.x, foo.c.y)}, ) def test_evt_on_flush_refresh(self): # this still worked prior to #3427 being fixed in any case sess = fixture_session() f1 = Foo(data=self.Point(None, None)) sess.add(f1) sess.flush() eq_(f1.data, self.Point(5, 9)) assert f1 not in sess.dirty f1.data.x = 10 assert f1 in sess.dirty
MutableCompositeColumnDefaultTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/tasks.py
{ "start": 44418, "end": 48065 }
class ____(GoogleCloudBaseOperator): """ Forces to run a task in Cloud Tasks. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudTasksTaskRunOperator` :param location: The location name in which the task was created. :param queue_name: The queue's name. :param task_name: The task's name. :param project_id: (Optional) The ID of the Google Cloud project that owns the Cloud Tasks. If set to None or missing, the default project_id from the Google Cloud connection is used. :param response_view: (Optional) This field specifies which subset of the Task will be returned. :param retry: (Optional) A retry object used to retry requests. If None is specified, requests will not be retried. :param timeout: (Optional) The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. :param metadata: (Optional) Additional metadata that is provided to the method. :param gcp_conn_id: (Optional) The connection ID used to connect 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). """ template_fields: Sequence[str] = ( "location", "queue_name", "task_name", "project_id", "gcp_conn_id", "impersonation_chain", ) operator_extra_links = (CloudTasksQueueLink(),) def __init__( self, *, location: str, queue_name: str, task_name: str, project_id: str = PROVIDE_PROJECT_ID, response_view: Task.View | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: MetaData = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.location = location self.queue_name = queue_name self.task_name = task_name self.project_id = project_id self.response_view = response_view self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = CloudTasksHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) task = hook.run_task( location=self.location, queue_name=self.queue_name, task_name=self.task_name, project_id=self.project_id, response_view=self.response_view, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) CloudTasksQueueLink.persist( context=context, queue_name=task.name, ) return Task.to_dict(task)
CloudTasksTaskRunOperator
python
coleifer__peewee
tests/test_utils.py
{ "start": 201, "end": 292 }
class ____(TestModel): key = CharField() class Meta: order_by = ('key',)
Data
python
rushter__MLAlgorithms
mla/gaussian_mixture.py
{ "start": 194, "end": 6850 }
class ____(BaseEstimator): """Gaussian Mixture Model: clusters with Gaussian prior. Finds clusters by repeatedly performing Expectation–Maximization (EM) algorithm on the dataset. GMM assumes the datasets is distributed in multivariate Gaussian, and tries to find the underlying structure of the Gaussian, i.e. mean and covariance. E-step computes the "responsibility" of the data to each cluster, given the mean and covariance; M-step computes the mean, covariance and weights (prior of each cluster), given the responsibilities. It iterates until the total likelihood changes less than the tolerance. Parameters ---------- K : int The number of clusters into which the dataset is partitioned. max_iters: int The maximum iterations of assigning points to the perform EM. Short-circuited by the assignments converging on their own. init: str, default 'random' The name of the method used to initialize the first clustering. 'random' - Randomly select values from the dataset as the K centroids. 'kmeans' - Initialize the centroids, covariances, weights with KMeams's clusters. tolerance: float, default 1e-3 The tolerance of difference of the two latest likelihood for convergence. """ y_required = False def __init__(self, K=4, init="random", max_iters=500, tolerance=1e-3): self.K = K self.max_iters = max_iters self.init = init self.assignments = None self.likelihood = [] self.tolerance = tolerance def fit(self, X, y=None): """Perform Expectation–Maximization (EM) until converged.""" self._setup_input(X, y) self._initialize() for _ in range(self.max_iters): self._E_step() self._M_step() if self._is_converged(): break def _initialize(self): """Set the initial weights, means and covs (with full covariance matrix). weights: the prior of the clusters (what percentage of data does a cluster have) means: the mean points of the clusters covs: the covariance matrix of the clusters """ self.weights = np.ones(self.K) if self.init == "random": self.means = [ self.X[x] for x in random.sample(range(self.n_samples), self.K) ] self.covs = [np.cov(self.X.T) for _ in range(self.K)] elif self.init == "kmeans": kmeans = KMeans(K=self.K, max_iters=self.max_iters // 3, init="++") kmeans.fit(self.X) self.assignments = kmeans.predict() self.means = kmeans.centroids self.covs = [] for i in np.unique(self.assignments): self.weights[int(i)] = (self.assignments == i).sum() self.covs.append(np.cov(self.X[self.assignments == i].T)) else: raise ValueError("Unknown type of init parameter") self.weights /= self.weights.sum() def _E_step(self): """Expectation(E-step) for Gaussian Mixture.""" likelihoods = self._get_likelihood(self.X) self.likelihood.append(likelihoods.sum()) weighted_likelihoods = self._get_weighted_likelihood(likelihoods) self.assignments = weighted_likelihoods.argmax(axis=1) weighted_likelihoods /= weighted_likelihoods.sum(axis=1)[:, np.newaxis] self.responsibilities = weighted_likelihoods def _M_step(self): """Maximization (M-step) for Gaussian Mixture.""" weights = self.responsibilities.sum(axis=0) for assignment in range(self.K): resp = self.responsibilities[:, assignment][:, np.newaxis] self.means[assignment] = (resp * self.X).sum(axis=0) / resp.sum() self.covs[assignment] = (self.X - self.means[assignment]).T.dot( (self.X - self.means[assignment]) * resp ) / weights[assignment] self.weights = weights / weights.sum() def _is_converged(self): """Check if the difference of the latest two likelihood is less than the tolerance.""" if (len(self.likelihood) > 1) and ( self.likelihood[-1] - self.likelihood[-2] <= self.tolerance ): return True return False def _predict(self, X): """Get the assignments for X with GMM clusters.""" if not X.shape: return self.assignments likelihoods = self._get_likelihood(X) weighted_likelihoods = self._get_weighted_likelihood(likelihoods) assignments = weighted_likelihoods.argmax(axis=1) return assignments def _get_likelihood(self, data): n_data = data.shape[0] likelihoods = np.zeros([n_data, self.K]) for c in range(self.K): likelihoods[:, c] = multivariate_normal.pdf( data, self.means[c], self.covs[c] ) return likelihoods def _get_weighted_likelihood(self, likelihood): return self.weights * likelihood def plot(self, data=None, ax=None, holdon=False): """Plot contour for 2D data.""" if not (len(self.X.shape) == 2 and self.X.shape[1] == 2): raise AttributeError("Only support for visualizing 2D data.") if ax is None: _, ax = plt.subplots() if data is None: data = self.X assignments = self.assignments else: assignments = self.predict(data) COLOR = "bgrcmyk" cmap = lambda assignment: COLOR[int(assignment) % len(COLOR)] # generate grid delta = 0.025 margin = 0.2 xmax, ymax = self.X.max(axis=0) + margin xmin, ymin = self.X.min(axis=0) - margin axis_X, axis_Y = np.meshgrid( np.arange(xmin, xmax, delta), np.arange(ymin, ymax, delta) ) def grid_gaussian_pdf(mean, cov): grid_array = np.array(list(zip(axis_X.flatten(), axis_Y.flatten()))) return multivariate_normal.pdf(grid_array, mean, cov).reshape(axis_X.shape) # plot scatters if assignments is None: c = None else: c = [cmap(assignment) for assignment in assignments] ax.scatter(data[:, 0], data[:, 1], c=c) # plot contours for assignment in range(self.K): ax.contour( axis_X, axis_Y, grid_gaussian_pdf(self.means[assignment], self.covs[assignment]), colors=cmap(assignment), ) if not holdon: plt.show()
GaussianMixture
python
walkccc__LeetCode
solutions/3111. Minimum Rectangles to Cover Points/3111.py
{ "start": 0, "end": 260 }
class ____: def minRectanglesToCoverPoints(self, points: list[list[int]], w: int) -> int: ans = 0 prevX = -w - 1 xs = sorted([x for x, _ in points]) for x in xs: if x > prevX + w: ans += 1 prevX = x return ans
Solution
python
dask__distributed
distributed/deploy/ssh.py
{ "start": 5779, "end": 15241 }
class ____(Process): """A Remote Dask Scheduler controlled by SSH Parameters ---------- address: str The hostname where we should run this worker connect_options: dict kwargs to be passed to asyncssh connections remote_python: str Path to Python on remote node to run this scheduler. kwargs: dict These will be passed through the dask scheduler CLI to the dask.distributed.Scheduler class """ def __init__( self, address: str, connect_options: dict, kwargs: dict, remote_python: str | None = None, ): super().__init__() self.address = address self.kwargs = kwargs self.connect_options = connect_options self.remote_python = remote_python or sys.executable async def start(self): try: import asyncssh # import now to avoid adding to module startup time except ImportError: raise ImportError( "Dask's SSHCluster requires the `asyncssh` package to be installed. " "Please install it using pip or conda." ) logger.debug("Created Scheduler Connection") self.connection = await asyncssh.connect(self.address, **self.connect_options) result = await self.connection.run("uname") if result.exit_status == 0: set_env = f'env DASK_INTERNAL_INHERIT_CONFIG="{dask.config.serialize(dask.config.global_config)}"' else: result = await self.connection.run("cmd /c ver") if result.exit_status == 0: set_env = f"set DASK_INTERNAL_INHERIT_CONFIG={dask.config.serialize(dask.config.global_config)} &&" else: raise Exception( "Scheduler failed to set DASK_INTERNAL_INHERIT_CONFIG variable " ) cmd = " ".join( [ set_env, self.remote_python, "-m", "distributed.cli.dask_spec", "--spec", "'%s'" % dumps({"cls": "distributed.Scheduler", "opts": self.kwargs}), ] ) self.proc = await self.connection.create_process(cmd) # We watch stderr in order to get the address, then we return while True: line = await self.proc.stderr.readline() if not line.strip(): raise Exception("Worker failed to start") logger.info(line.strip()) if "Scheduler at" in line: self.address = line.split("Scheduler at:")[1].strip() break logger.debug("%s", line) await super().start() old_cluster_kwargs = { "scheduler_addr", "scheduler_port", "worker_addrs", "nthreads", "nprocs", "n_workers", "ssh_username", "ssh_port", "ssh_private_key", "nohost", "logdir", "remote_python", "memory_limit", "worker_port", "nanny_port", "remote_dask_worker", } def SSHCluster( hosts: list[str] | None = None, connect_options: dict | list[dict] | None = None, worker_options: dict | None = None, scheduler_options: dict | None = None, worker_module: str = "deprecated", worker_class: str = "distributed.Nanny", remote_python: str | list[str] | None = None, **kwargs: Any, ) -> SpecCluster: """Deploy a Dask cluster using SSH The SSHCluster function deploys a Dask Scheduler and Workers for you on a set of machine addresses that you provide. The first address will be used for the scheduler while the rest will be used for the workers (feel free to repeat the first hostname if you want to have the scheduler and worker co-habitate one machine.) You may configure the scheduler and workers by passing ``scheduler_options`` and ``worker_options`` dictionary keywords. See the ``dask.distributed.Scheduler`` and ``dask.distributed.Worker`` classes for details on the available options, but the defaults should work in most situations. You may configure your use of SSH itself using the ``connect_options`` keyword, which passes values to the ``asyncssh.connect`` function. For more information on these see the documentation for the ``asyncssh`` library https://asyncssh.readthedocs.io . Parameters ---------- hosts List of hostnames or addresses on which to launch our cluster. The first will be used for the scheduler and the rest for workers. connect_options Keywords to pass through to :func:`asyncssh.connect`. This could include things such as ``port``, ``username``, ``password`` or ``known_hosts``. See docs for :func:`asyncssh.connect` and :class:`asyncssh.SSHClientConnectionOptions` for full information. If a list it must have the same length as ``hosts``. worker_options Keywords to pass on to workers. scheduler_options Keywords to pass on to scheduler. worker_class The python class to use to create the worker(s). remote_python Path to Python on remote nodes. Examples -------- Create a cluster with one worker: >>> from dask.distributed import Client, SSHCluster >>> cluster = SSHCluster(["localhost", "localhost"]) >>> client = Client(cluster) Create a cluster with three workers, each with two threads and host the dashdoard on port 8797: >>> from dask.distributed import Client, SSHCluster >>> cluster = SSHCluster( ... ["localhost", "localhost", "localhost", "localhost"], ... connect_options={"known_hosts": None}, ... worker_options={"nthreads": 2}, ... scheduler_options={"port": 0, "dashboard_address": ":8797"} ... ) >>> client = Client(cluster) Create a cluster with two workers on each host: >>> from dask.distributed import Client, SSHCluster >>> cluster = SSHCluster( ... ["localhost", "localhost", "localhost", "localhost"], ... connect_options={"known_hosts": None}, ... worker_options={"nthreads": 2, "n_workers": 2}, ... scheduler_options={"port": 0, "dashboard_address": ":8797"} ... ) >>> client = Client(cluster) An example using a different worker class, in particular the ``CUDAWorker`` from the ``dask-cuda`` project: >>> from dask.distributed import Client, SSHCluster >>> cluster = SSHCluster( ... ["localhost", "hostwithgpus", "anothergpuhost"], ... connect_options={"known_hosts": None}, ... scheduler_options={"port": 0, "dashboard_address": ":8797"}, ... worker_class="dask_cuda.CUDAWorker") >>> client = Client(cluster) See Also -------- dask.distributed.Scheduler dask.distributed.Worker asyncssh.connect """ connect_options = connect_options or {} worker_options = worker_options or {} scheduler_options = scheduler_options or {} if worker_module != "deprecated": raise ValueError( "worker_module has been deprecated in favor of worker_class. " "Please specify a Python class rather than a CLI module." ) if set(kwargs) & old_cluster_kwargs: from distributed.deploy.old_ssh import SSHCluster as OldSSHCluster warnings.warn( "Note that the SSHCluster API has been replaced. " "We're routing you to the older implementation. " "This will be removed in the future" ) kwargs.setdefault("worker_addrs", hosts) return OldSSHCluster(**kwargs) # type: ignore if not hosts: raise ValueError( f"`hosts` must be a non empty list, value {repr(hosts)!r} found." ) if isinstance(connect_options, list) and len(connect_options) != len(hosts): raise RuntimeError( "When specifying a list of connect_options you must provide a " "dictionary for each address." ) if isinstance(remote_python, list) and len(remote_python) != len(hosts): raise RuntimeError( "When specifying a list of remote_python you must provide a " "path for each address." ) scheduler = { "cls": Scheduler, "options": { "address": hosts[0], "connect_options": ( connect_options if isinstance(connect_options, dict) else connect_options[0] ), "kwargs": scheduler_options, "remote_python": ( remote_python[0] if isinstance(remote_python, list) else remote_python ), }, } workers = { i: { "cls": Worker, "options": { "address": host, "connect_options": ( connect_options if isinstance(connect_options, dict) else connect_options[i + 1] ), "kwargs": worker_options, "worker_class": worker_class, "remote_python": ( remote_python[i + 1] if isinstance(remote_python, list) else remote_python ), }, } for i, host in enumerate(hosts[1:]) } return SpecCluster(workers, scheduler, name="SSHCluster", **kwargs)
Scheduler
python
joblib__joblib
joblib/externals/loky/process_executor.py
{ "start": 40312, "end": 40479 }
class ____(RuntimeError): """ Raised when a ProcessPoolExecutor is shutdown while a future was in the running or pending state. """
ShutdownExecutorError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 133169, "end": 133823 }
class ____(sgqlc.types.Input): """Autogenerated input type of AddProjectV2ItemById""" __schema__ = github_schema __field_names__ = ("project_id", "content_id", "client_mutation_id") project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId") """The ID of the Project to add the item to.""" content_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="contentId") """The id of the Issue or Pull Request to add.""" client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
AddProjectV2ItemByIdInput
python
walkccc__LeetCode
solutions/2902. Count of Sub-Multisets With Bounded Sum/2902.py
{ "start": 0, "end": 730 }
class ____: def countSubMultisets(self, nums: list[int], l: int, r: int) -> int: MOD = 1_000_000_007 # dp[i] := the number of submultisets of `nums` with sum i dp = [1] + [0] * r count = collections.Counter(nums) zeros = count.pop(0, 0) for num, freq in count.items(): # stride[i] := dp[i] + dp[i - num] + dp[i - 2 * num] + ... stride = dp.copy() for i in range(num, r + 1): stride[i] += stride[i - num] for i in range(r, 0, -1): if i >= num * (freq + 1): # dp[i] + dp[i - num] + dp[i - freq * num] dp[i] = stride[i] - stride[i - num * (freq + 1)] else: dp[i] = stride[i] return (zeros + 1) * sum(dp[l:r + 1]) % MOD
Solution
python
PyCQA__pylint
tests/functional/u/unpacking/unpacking_non_sequence.py
{ "start": 2558, "end": 2717 }
class ____: 'base class with `test` method implementation' @staticmethod def test(data): 'default implementation' return data
TestBase
python
wandb__wandb
wandb/vendor/pygments/lexers/dsls.py
{ "start": 26223, "end": 29213 }
class ____(RegexLexer): """ Lexer for `Flatline <https://github.com/bigmlcom/flatline>`_ expressions. .. versionadded:: 2.2 """ name = 'Flatline' aliases = ['flatline'] filenames = [] mimetypes = ['text/x-flatline'] special_forms = ('let',) builtins = ( "!=", "*", "+", "-", "<", "<=", "=", ">", ">=", "abs", "acos", "all", "all-but", "all-with-defaults", "all-with-numeric-default", "and", "asin", "atan", "avg", "avg-window", "bin-center", "bin-count", "call", "category-count", "ceil", "cond", "cond-window", "cons", "cos", "cosh", "count", "diff-window", "div", "ensure-value", "ensure-weighted-value", "epoch", "epoch-day", "epoch-fields", "epoch-hour", "epoch-millisecond", "epoch-minute", "epoch-month", "epoch-second", "epoch-weekday", "epoch-year", "exp", "f", "field", "field-prop", "fields", "filter", "first", "floor", "head", "if", "in", "integer", "language", "length", "levenshtein", "linear-regression", "list", "ln", "log", "log10", "map", "matches", "matches?", "max", "maximum", "md5", "mean", "median", "min", "minimum", "missing", "missing-count", "missing?", "missing_count", "mod", "mode", "normalize", "not", "nth", "occurrences", "or", "percentile", "percentile-label", "population", "population-fraction", "pow", "preferred", "preferred?", "quantile-label", "rand", "rand-int", "random-value", "re-quote", "real", "replace", "replace-first", "rest", "round", "row-number", "segment-label", "sha1", "sha256", "sin", "sinh", "sqrt", "square", "standard-deviation", "standard_deviation", "str", "subs", "sum", "sum-squares", "sum-window", "sum_squares", "summary", "summary-no", "summary-str", "tail", "tan", "tanh", "to-degrees", "to-radians", "variance", "vectorize", "weighted-random-value", "window", "winnow", "within-percentiles?", "z-score", ) valid_name = r'(?!#)[\w!$%*+<=>?/.#-]+' tokens = { 'root': [ # whitespaces - usually not relevant (r'[,\s]+', Text), # numbers (r'-?\d+\.\d+', Number.Float), (r'-?\d+', Number.Integer), (r'0x-?[a-f\d]+', Number.Hex), # strings, symbols and characters (r'"(\\\\|\\"|[^"])*"', String), (r"\\(.|[a-z]+)", String.Char), # expression template placeholder (r'_', String.Symbol), # highlight the special forms (words(special_forms, suffix=' '), Keyword), # highlight the builtins (words(builtins, suffix=' '), Name.Builtin), # the remaining functions (r'(?<=\()' + valid_name, Name.Function), # find the remaining variables (valid_name, Name.Variable), # parentheses (r'(\(|\))', Punctuation), ], }
FlatlineLexer
python
etianen__django-reversion
tests/test_app/models.py
{ "start": 2141, "end": 2326 }
class ____(models.Model): revision = models.ForeignKey( Revision, on_delete=models.CASCADE, ) name = models.CharField( max_length=191, )
TestMeta
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/rpc_test.py
{ "start": 9608, "end": 14292 }
class ____(Exception): def __init__(self, bool, msg): self.bool = bool super().__init__(msg) def raise_func(): raise ValueError(expected_err) def custom_raise_func(): raise CustomException(True, "foo") @torch.jit.script def raise_func_script(expected_err: str) -> torch.Tensor: raise ValueError(expected_err) expected_err_escape = ( "\nFirst line of error \n next line of error \n last line of error" ) def raise_func_escape(): raise ValueError(expected_err_escape) global_rref = None def set_global_rref(rref): global global_rref global_rref = rref def clear_global_rref(): global global_rref global_rref = None def check_rref_confirmed(rref): return rref.confirmed_by_owner() def get_rref_debug_info(): return _rref_context_get_debug_info() def add_use_future_cb(to, x, y, z): out = concurrent.futures.Future() def callback(fut): out.set_result(fut.wait() + z) fut = rpc.rpc_async(to, torch.add, args=(x, y)) fut.then(callback) return out.result() def get_events_from_profile(profile_rref): return profile_rref.local_value().process_global_function_events def add_use_future_set_result(to, x, y, z): out = torch.futures.Future() fut = rpc.rpc_async(to, torch.add, args=(x, y)) fut.then(lambda fut: out.set_result(fut.wait() + z)) return out.wait() def add_use_future_nested_cb(to, x, y, z): out = torch.futures.Future() def callback(fut1): fut2 = rpc.rpc_async(to, torch.add, args=(fut1.wait(), z)) fut2.then(lambda fut2: out.set_result(fut2.wait())) fut1 = rpc.rpc_async(to, torch.add, args=(x, y)) fut1.then(callback) return out.wait() def fail_on_fut(fut): pass @rpc.functions.async_execution def async_raise_func(): raise RuntimeError("Expected error") @rpc.functions.async_execution def async_wrong_type(): return torch.zeros(2, 2) @rpc.functions.async_execution def async_add(to, x, y): return rpc.rpc_async(to, torch.add, args=(x, y)) def slow_add(x, y, device="cpu"): time.sleep(1) x = x.to(device) y = y.to(device) return torch.add(x, y).cpu() @rpc.functions.async_execution def slow_async_add(to, x, y, device="cpu"): return rpc.rpc_async(to, slow_add, args=(x, y, device)) @rpc.functions.async_execution def async_add_with_future_ctor(to, x, y, z): fut = torch.futures.Future() rpc.rpc_async(to, torch.add, args=(x, y)).then( lambda fut1: fut.set_result(fut1.wait() + z) ) return fut @rpc.functions.async_execution def async_add_chained(to, x, y, z): return rpc.rpc_async(to, torch.add, args=(x, y)).then(lambda fut: fut.wait() + z) @rpc.functions.async_execution def async_add_chained_multi(to, x, num, step): fut = rpc.rpc_async(to, torch.add, args=(x, 0)) for _ in range(num): fut = fut.then(lambda fut: fut.wait() + step) return fut @rpc.functions.async_execution def async_add_nested(to, x, y, z): return rpc.rpc_async(to, async_add, args=(to, x, y)).then( lambda fut: fut.wait() + z ) @rpc.functions.async_execution def async_add_multi_fanout(to, x, num, step): futs = [] for i in range(num): if i == 0: futs.append(rpc.rpc_async(to, torch.add, args=(x, step))) else: futs.append(rpc.rpc_async(to, torch.add, args=(0, step))) # TODO: use torch.futures.collect_all lock = Lock() state = {"cnt": 0, "ret": torch.zeros_like(x)} ret_future = torch.futures.Future() def inc_and_set(fut): with lock: state["cnt"] += 1 state["ret"] += fut.wait() if state["cnt"] >= len(futs): ret_future.set_result(state["ret"]) for fut in futs: fut.then(inc_and_set) return ret_future @rpc.functions.async_execution def async_cuda_sleep_and_set_to_one(t): device = t.device original_stream = torch.cuda.current_stream(device) new_stream = torch.cuda.Stream(device) new_stream.wait_stream(original_stream) with torch.cuda.stream(new_stream): torch.cuda._sleep(int(1000 * get_cycles_per_ms())) t.fill_(1) fut = Future(devices=[device]) fut.set_result(t) return fut @rpc.functions.async_execution def async_cuda_nested_add(to, x, y, z): def cb(fut): torch.cuda._sleep(int(1000 * get_cycles_per_ms())) return fut.value() + z return rpc.rpc_async(to, torch.add, args=(x, y)).then(cb) # A custom Python class that contains a tensor, needed to see if we correctly # use the Python pickler to extract tensors from non-IValue-convertible types.
CustomException
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_cond_format23.py
{ "start": 345, "end": 7880 }
class ____(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test writing a worksheet with conditional formatting.""" self.maxDiff = None fh = StringIO() worksheet = Worksheet() worksheet._set_filehandle(fh) worksheet.select() worksheet.write("A1", 1) worksheet.write("A2", 2) worksheet.write("A3", 3) worksheet.write("A4", 4) worksheet.write("A5", 5) worksheet.write("A6", 6) worksheet.write("A7", 7) worksheet.write("A8", 8) worksheet.conditional_format( "A1", {"type": "icon_set", "icon_style": "3_arrows_gray"} ) worksheet.conditional_format( "A2", {"type": "icon_set", "icon_style": "3_traffic_lights"} ) worksheet.conditional_format( "A3", {"type": "icon_set", "icon_style": "3_signs"} ) worksheet.conditional_format( "A4", {"type": "icon_set", "icon_style": "3_symbols"} ) worksheet.conditional_format( "A5", {"type": "icon_set", "icon_style": "4_arrows_gray"} ) worksheet.conditional_format( "A6", {"type": "icon_set", "icon_style": "4_ratings"} ) worksheet.conditional_format( "A7", {"type": "icon_set", "icon_style": "5_arrows"} ) worksheet.conditional_format( "A8", {"type": "icon_set", "icon_style": "5_ratings"} ) worksheet._assemble_xml_file() exp = _xml_to_list( """ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <dimension ref="A1:A8"/> <sheetViews> <sheetView tabSelected="1" workbookViewId="0"/> </sheetViews> <sheetFormatPr defaultRowHeight="15"/> <sheetData> <row r="1" spans="1:1"> <c r="A1"> <v>1</v> </c> </row> <row r="2" spans="1:1"> <c r="A2"> <v>2</v> </c> </row> <row r="3" spans="1:1"> <c r="A3"> <v>3</v> </c> </row> <row r="4" spans="1:1"> <c r="A4"> <v>4</v> </c> </row> <row r="5" spans="1:1"> <c r="A5"> <v>5</v> </c> </row> <row r="6" spans="1:1"> <c r="A6"> <v>6</v> </c> </row> <row r="7" spans="1:1"> <c r="A7"> <v>7</v> </c> </row> <row r="8" spans="1:1"> <c r="A8"> <v>8</v> </c> </row> </sheetData> <conditionalFormatting sqref="A1"> <cfRule type="iconSet" priority="1"> <iconSet iconSet="3ArrowsGray"> <cfvo type="percent" val="0"/> <cfvo type="percent" val="33"/> <cfvo type="percent" val="67"/> </iconSet> </cfRule> </conditionalFormatting> <conditionalFormatting sqref="A2"> <cfRule type="iconSet" priority="2"> <iconSet> <cfvo type="percent" val="0"/> <cfvo type="percent" val="33"/> <cfvo type="percent" val="67"/> </iconSet> </cfRule> </conditionalFormatting> <conditionalFormatting sqref="A3"> <cfRule type="iconSet" priority="3"> <iconSet iconSet="3Signs"> <cfvo type="percent" val="0"/> <cfvo type="percent" val="33"/> <cfvo type="percent" val="67"/> </iconSet> </cfRule> </conditionalFormatting> <conditionalFormatting sqref="A4"> <cfRule type="iconSet" priority="4"> <iconSet iconSet="3Symbols2"> <cfvo type="percent" val="0"/> <cfvo type="percent" val="33"/> <cfvo type="percent" val="67"/> </iconSet> </cfRule> </conditionalFormatting> <conditionalFormatting sqref="A5"> <cfRule type="iconSet" priority="5"> <iconSet iconSet="4ArrowsGray"> <cfvo type="percent" val="0"/> <cfvo type="percent" val="25"/> <cfvo type="percent" val="50"/> <cfvo type="percent" val="75"/> </iconSet> </cfRule> </conditionalFormatting> <conditionalFormatting sqref="A6"> <cfRule type="iconSet" priority="6"> <iconSet iconSet="4Rating"> <cfvo type="percent" val="0"/> <cfvo type="percent" val="25"/> <cfvo type="percent" val="50"/> <cfvo type="percent" val="75"/> </iconSet> </cfRule> </conditionalFormatting> <conditionalFormatting sqref="A7"> <cfRule type="iconSet" priority="7"> <iconSet iconSet="5Arrows"> <cfvo type="percent" val="0"/> <cfvo type="percent" val="20"/> <cfvo type="percent" val="40"/> <cfvo type="percent" val="60"/> <cfvo type="percent" val="80"/> </iconSet> </cfRule> </conditionalFormatting> <conditionalFormatting sqref="A8"> <cfRule type="iconSet" priority="8"> <iconSet iconSet="5Rating"> <cfvo type="percent" val="0"/> <cfvo type="percent" val="20"/> <cfvo type="percent" val="40"/> <cfvo type="percent" val="60"/> <cfvo type="percent" val="80"/> </iconSet> </cfRule> </conditionalFormatting> <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/> </worksheet> """ ) got = _xml_to_list(fh.getvalue()) self.assertEqual(exp, got)
TestAssembleWorksheet
python
walkccc__LeetCode
solutions/3433. Count Mentions Per User/3433.py
{ "start": 202, "end": 1592 }
class ____: def countMentions( self, numberOfUsers: int, events: list[list[str]] ) -> list[int]: ans = [0] * numberOfUsers online = [True] * numberOfUsers offlineQueue = [] # min-heap to track users that are offline allMentionsCount = 0 events.sort(key=lambda x: (int(x[1]), -ord(x[0][0]))) for eventType, t, messageContent in events: timestamp = int(t) # Bring users back online if their offline period has ended. while offlineQueue and offlineQueue[0].returnTimestamp <= timestamp: user = heapq.heappop(offlineQueue) online[user.userId] = True if eventType == "MESSAGE": match messageContent: case "ALL": allMentionsCount += 1 case "HERE": for userId in range(numberOfUsers): if online[userId]: ans[userId] += 1 case _: for userId in [int(part[2:]) for part in messageContent.split()]: ans[userId] += 1 elif eventType == "OFFLINE": userId = int(messageContent) online[userId] = False # Add to queue to bring back online after 60 units. heapq.heappush(offlineQueue, OfflineUser(timestamp + 60, userId)) # Add the "ALL" mentions to all users. for userId in range(numberOfUsers): ans[userId] += allMentionsCount return ans
Solution
python
instagram__MonkeyType
tests/test_stubs.py
{ "start": 4214, "end": 4580 }
class ____: @pytest.mark.parametrize( 'stub, expected', [ (AttributeStub(name='foo', typ=int), ' foo: int'), (AttributeStub(name='foo', typ=make_forward_ref('Foo')), ' foo: \'Foo\''), ], ) def test_simple_attribute(self, stub, expected): assert stub.render(' ') == expected
TestAttributeStub
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/ingress.py
{ "start": 564, "end": 782 }
class ____(BaseModel): host: str path: str pathType: IngressPathType tls: IngressTLSConfiguration precedingPaths: list[IngressPath] succeedingPaths: list[IngressPath]
WebserverIngressConfiguration
python
pallets__werkzeug
tests/test_formparser.py
{ "start": 8358, "end": 16845 }
class ____: def test_basic(self): resources = join(dirname(__file__), "multipart") client = Client(form_data_consumer) repository = [ ( "firefox3-2png1txt", "---------------------------186454651713519341951581030105", [ ("anchor.png", "file1", "image/png", "file1.png"), ("application_edit.png", "file2", "image/png", "file2.png"), ], "example text", ), ( "firefox3-2pnglongtext", "---------------------------14904044739787191031754711748", [ ("accept.png", "file1", "image/png", "file1.png"), ("add.png", "file2", "image/png", "file2.png"), ], "--long text\r\n--with boundary\r\n--lookalikes--", ), ( "opera8-2png1txt", "----------zEO9jQKmLc2Cq88c23Dx19", [ ("arrow_branch.png", "file1", "image/png", "file1.png"), ("award_star_bronze_1.png", "file2", "image/png", "file2.png"), ], "blafasel öäü", ), ( "webkit3-2png1txt", "----WebKitFormBoundaryjdSFhcARk8fyGNy6", [ ("gtk-apply.png", "file1", "image/png", "file1.png"), ("gtk-no.png", "file2", "image/png", "file2.png"), ], "this is another text with ümläüts", ), ( "ie6-2png1txt", "---------------------------7d91b03a20128", [ ("file1.png", "file1", "image/x-png", "file1.png"), ("file2.png", "file2", "image/x-png", "file2.png"), ], "ie6 sucks :-/", ), ] for name, boundary, files, text in repository: folder = join(resources, name) data = get_contents(join(folder, "request.http")) for filename, field, content_type, fsname in files: with client.post( f"/?object={field}", data=data, content_type=f'multipart/form-data; boundary="{boundary}"', content_length=len(data), ) as response: lines = response.get_data().split(b"\n", 3) assert lines[0] == repr(filename).encode("ascii") assert lines[1] == repr(field).encode("ascii") assert lines[2] == repr(content_type).encode("ascii") assert lines[3] == get_contents(join(folder, fsname)) with client.post( "/?object=text", data=data, content_type=f'multipart/form-data; boundary="{boundary}"', content_length=len(data), ) as response: assert response.get_data() == repr(text).encode() @pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") def test_ie7_unc_path(self): client = Client(form_data_consumer) data_file = join(dirname(__file__), "multipart", "ie7_full_path_request.http") data = get_contents(data_file) boundary = "---------------------------7da36d1b4a0164" with client.post( "/?object=cb_file_upload_multiple", data=data, content_type=f'multipart/form-data; boundary="{boundary}"', content_length=len(data), ) as response: lines = response.get_data().split(b"\n", 3) assert lines[0] == b"'Sellersburg Town Council Meeting 02-22-2010doc.doc'" def test_end_of_file(self): # This test looks innocent but it was actually timing out in # the Werkzeug 0.5 release version (#394) data = ( b"--foo\r\n" b'Content-Disposition: form-data; name="test"; filename="test.txt"\r\n' b"Content-Type: text/plain\r\n\r\n" b"file contents and no end" ) with Request.from_values( input_stream=io.BytesIO(data), content_length=len(data), content_type="multipart/form-data; boundary=foo", method="POST", ) as data: assert not data.files assert not data.form def test_file_no_content_type(self): data = ( b"--foo\r\n" b'Content-Disposition: form-data; name="test"; filename="test.txt"\r\n\r\n' b"file contents\r\n--foo--" ) with Request.from_values( input_stream=io.BytesIO(data), content_length=len(data), content_type="multipart/form-data; boundary=foo", method="POST", ) as data: assert data.files["test"].filename == "test.txt" assert data.files["test"].read() == b"file contents" def test_extra_newline(self): # this test looks innocent but it was actually timing out in # the Werkzeug 0.5 release version (#394) data = ( b"\r\n\r\n--foo\r\n" b'Content-Disposition: form-data; name="foo"\r\n\r\n' b"a string\r\n" b"--foo--" ) data = Request.from_values( input_stream=io.BytesIO(data), content_length=len(data), content_type="multipart/form-data; boundary=foo", method="POST", ) assert not data.files assert data.form["foo"] == "a string" def test_headers(self): data = ( b"--foo\r\n" b'Content-Disposition: form-data; name="foo"; filename="foo.txt"\r\n' b"X-Custom-Header: blah\r\n" b"Content-Type: text/plain; charset=utf-8\r\n\r\n" b"file contents, just the contents\r\n" b"--foo--" ) with Request.from_values( input_stream=io.BytesIO(data), content_length=len(data), content_type="multipart/form-data; boundary=foo", method="POST", ) as req: foo = req.files["foo"] assert foo.mimetype == "text/plain" assert foo.mimetype_params == {"charset": "utf-8"} assert foo.headers["content-type"] == foo.content_type assert foo.content_type == "text/plain; charset=utf-8" assert foo.headers["x-custom-header"] == "blah" @pytest.mark.parametrize("ending", [b"\n", b"\r", b"\r\n"]) def test_nonstandard_line_endings(self, ending: bytes): data = ending.join( ( b"--foo", b"Content-Disposition: form-data; name=foo", b"", b"this is just bar", b"--foo", b"Content-Disposition: form-data; name=bar", b"", b"blafasel", b"--foo--", ) ) req = Request.from_values( input_stream=io.BytesIO(data), content_length=len(data), content_type="multipart/form-data; boundary=foo", method="POST", ) assert req.form["foo"] == "this is just bar" assert req.form["bar"] == "blafasel" def test_failures(self): def parse_multipart(stream, boundary, content_length): parser = formparser.MultiPartParser(content_length) return parser.parse(stream, boundary, content_length) data = b"--foo\r\n\r\nHello World\r\n--foo--" pytest.raises(ValueError, parse_multipart, io.BytesIO(data), b"foo", len(data)) data = ( b"--foo\r\nContent-Disposition: form-field; name=foo\r\n\r\nHello World\r\n" ) pytest.raises(ValueError, parse_multipart, io.BytesIO(data), b"foo", len(data)) def test_empty_multipart(self): environ = {} data = b"--boundary--" environ["REQUEST_METHOD"] = "POST" environ["CONTENT_TYPE"] = "multipart/form-data; boundary=boundary" environ["CONTENT_LENGTH"] = str(len(data)) environ["wsgi.input"] = io.BytesIO(data) stream, form, files = parse_form_data(environ, silent=False) rv = stream.read() assert rv == b"" assert form == MultiDict() assert files == MultiDict()
TestMultiPart
python
dagster-io__dagster
python_modules/libraries/dagster-snowflake/dagster_snowflake/snowflake_io_manager.py
{ "start": 5264, "end": 13917 }
class ____(ConfigurableIOManagerFactory): """Base class for an IO manager definition that reads inputs from and writes outputs to Snowflake. Examples: .. code-block:: python from dagster_snowflake import SnowflakeIOManager from dagster_snowflake_pandas import SnowflakePandasTypeHandler from dagster_snowflake_pyspark import SnowflakePySparkTypeHandler from dagster import Definitions, EnvVar class MySnowflakeIOManager(SnowflakeIOManager): @staticmethod def type_handlers() -> Sequence[DbTypeHandler]: return [SnowflakePandasTypeHandler(), SnowflakePySparkTypeHandler()] @asset( key_prefix=["my_schema"] # will be used as the schema in snowflake ) def my_table() -> pd.DataFrame: # the name of the asset will be the table name ... defs = Definitions( assets=[my_table], resources={ "io_manager": MySnowflakeIOManager(database="my_database", account=EnvVar("SNOWFLAKE_ACCOUNT"), ...) } ) You can set a default schema to store the assets using the ``schema`` configuration value of the Snowflake I/O Manager. This schema will be used if no other schema is specified directly on an asset or op. .. code-block:: python defs = Definitions( assets=[my_table] resources={ "io_manager" MySnowflakeIOManager(database="my_database", schema="my_schema", ...) } ) On individual assets, you an also specify the schema where they should be stored using metadata or by adding a ``key_prefix`` to the asset key. If both ``key_prefix`` and metadata are defined, the metadata will take precedence. .. code-block:: python @asset( key_prefix=["my_schema"] # will be used as the schema in snowflake ) def my_table() -> pd.DataFrame: ... @asset( metadata={"schema": "my_schema"} # will be used as the schema in snowflake ) def my_other_table() -> pd.DataFrame: ... For ops, the schema can be specified by including a "schema" entry in output metadata. .. code-block:: python @op( out={"my_table": Out(metadata={"schema": "my_schema"})} ) def make_my_table() -> pd.DataFrame: ... If none of these is provided, the schema will default to "public". To only use specific columns of a table as input to a downstream op or asset, add the metadata ``columns`` to the In or AssetIn. .. code-block:: python @asset( ins={"my_table": AssetIn("my_table", metadata={"columns": ["a"]})} ) def my_table_a(my_table: pd.DataFrame) -> pd.DataFrame: # my_table will just contain the data from column "a" ... """ database: str = Field(description="Name of the database to use.") account: str = Field( description=( "Your Snowflake account name. For more details, see the `Snowflake documentation." " <https://docs.snowflake.com/developer-guide/python-connector/python-connector-api>`__" ), ) user: str = Field(description="User login name.") schema_: Optional[str] = Field( default=None, alias="schema", description="Name of the schema to use." ) # schema is a reserved word for pydantic password: Optional[str] = Field(default=None, description="User password.") warehouse: Optional[str] = Field(default=None, description="Name of the warehouse to use.") role: Optional[str] = Field(default=None, description="Name of the role to use.") private_key: Optional[str] = Field( default=None, description=( "Raw private key to use. See the `Snowflake documentation" " <https://docs.snowflake.com/en/user-guide/key-pair-auth.html>`__ for details. To" " avoid issues with newlines in the keys, you can base64 encode the key. You can" " retrieve the base64 encoded key with this shell command: cat rsa_key.p8 | base64" ), ) private_key_path: Optional[str] = Field( default=None, description=( "Path to the private key. See the `Snowflake documentation" " <https://docs.snowflake.com/en/user-guide/key-pair-auth.html>`__ for details." ), ) private_key_password: Optional[str] = Field( default=None, description=( "The password of the private key. See the `Snowflake documentation" " <https://docs.snowflake.com/en/user-guide/key-pair-auth.html>`__ for details." " Required for both private_key and private_key_path if the private key is encrypted." " For unencrypted keys, this config can be omitted or set to None." ), ) store_timestamps_as_strings: bool = Field( default=False, description=( "If using Pandas DataFrames, whether to convert time data to strings. If True, time" " data will be converted to strings when storing the DataFrame and converted back to" " time data when loading the DataFrame. If False, time data without a timezone will be" " set to UTC timezone to avoid a Snowflake bug. Defaults to False." ), ) authenticator: Optional[str] = Field( default=None, description="Optional parameter to specify the authentication mechanism to use.", ) additional_snowflake_connection_args: Optional[dict[str, Any]] = Field( default=None, description=( "Additional keyword arguments to pass to the snowflake.connector.connect function. For a full list of" " available arguments, see the `Snowflake documentation" " <https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-connect>`__." " This config will be ignored if using the sqlalchemy connector." ), ) @staticmethod @abstractmethod def type_handlers() -> Sequence[DbTypeHandler]: """type_handlers should return a list of the TypeHandlers that the I/O manager can use. .. code-block:: python from dagster_snowflake import SnowflakeIOManager from dagster_snowflake_pandas import SnowflakePandasTypeHandler from dagster_snowflake_pyspark import SnowflakePySparkTypeHandler from dagster import Definitions, EnvVar class MySnowflakeIOManager(SnowflakeIOManager): @staticmethod def type_handlers() -> Sequence[DbTypeHandler]: return [SnowflakePandasTypeHandler(), SnowflakePySparkTypeHandler()] """ ... @staticmethod def default_load_type() -> Optional[type]: """If an asset or op is not annotated with an return type, default_load_type will be used to determine which TypeHandler to use to store and load the output. If left unimplemented, default_load_type will return None. In that case, if there is only one TypeHandler, the I/O manager will default to loading unannotated outputs with that TypeHandler. .. code-block:: python from dagster_snowflake import SnowflakeIOManager from dagster_snowflake_pandas import SnowflakePandasTypeHandler from dagster_snowflake_pyspark import SnowflakePySparkTypeHandler from dagster import Definitions, EnvVar import pandas as pd class MySnowflakeIOManager(SnowflakeIOManager): @staticmethod def type_handlers() -> Sequence[DbTypeHandler]: return [SnowflakePandasTypeHandler(), SnowflakePySparkTypeHandler()] @staticmethod def default_load_type() -> Optional[Type]: return pd.DataFrame """ return None def create_io_manager(self, context) -> DbIOManager: return DbIOManager( db_client=SnowflakeDbClient(), io_manager_name="SnowflakeIOManager", database=self.database, schema=self.schema_, type_handlers=self.type_handlers(), default_load_type=self.default_load_type(), )
SnowflakeIOManager
python
pytorch__pytorch
test/functorch/test_aotdispatch.py
{ "start": 322590, "end": 323958 }
class ____(AOTTestCase): @modules(module_db, allowed_dtypes=(torch.float,)) @decorateForModules(unittest.expectedFailure, aot_autograd_module_failures) def test_aot_autograd_module_exhaustive(self, device, dtype, training, module_info): _test_aot_autograd_module_helper(self, device, dtype, training, module_info) @modules(module_db, allowed_dtypes=(torch.float,)) @decorateForModules( unittest.expectedFailure, aot_autograd_module_failures | symbolic_aot_autograd_module_failures, ) def test_aot_autograd_symbolic_module_exhaustive( self, device, dtype, training, module_info ): _test_aot_autograd_module_helper( self, device, dtype, training, module_info, dynamic=True ) instantiate_parametrized_tests(TestAOTAutograd) instantiate_parametrized_tests(TestAOTModuleSimplified) only_for = "cpu" instantiate_device_type_tests( TestPythonKey, globals(), only_for=only_for, ) instantiate_device_type_tests(TestEagerFusionOpInfo, globals(), only_for=only_for) instantiate_device_type_tests(TestEagerFusionModuleInfo, globals(), only_for=only_for) @xfail_inherited_tests( [ "test_set__and_data_mutation_bad", "test_subclass_metadata_mutation_req_grad_True", "test_subclass_metadata_mutation_req_grad_False", ] )
TestEagerFusionModuleInfo
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py
{ "start": 8347, "end": 22437 }
class ____: @mock.patch(VERTEX_AI_PATH.format("custom_job.Dataset")) @mock.patch(VERTEX_AI_PATH.format("custom_job.CustomJobHook")) def test_execute(self, mock_hook, mock_dataset): mock_hook.return_value.create_custom_container_training_job.return_value = ( None, "training_id", "custom_job_id", ) op = CreateCustomContainerTrainingJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, staging_bucket=STAGING_BUCKET, display_name=DISPLAY_NAME, args=ARGS, container_uri=CONTAINER_URI, model_serving_container_image_uri=CONTAINER_URI, command=COMMAND_2, model_display_name=DISPLAY_NAME_2, replica_count=REPLICA_COUNT, machine_type=MACHINE_TYPE, accelerator_type=ACCELERATOR_TYPE, accelerator_count=ACCELERATOR_COUNT, training_fraction_split=TRAINING_FRACTION_SPLIT, validation_fraction_split=VALIDATION_FRACTION_SPLIT, test_fraction_split=TEST_FRACTION_SPLIT, region=GCP_LOCATION, project_id=GCP_PROJECT, dataset_id=TEST_DATASET_ID, parent_model=TEST_PARENT_MODEL, ) op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()}) mock_dataset.assert_called_once_with(name=TEST_DATASET_ID) mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN) mock_hook.return_value.create_custom_container_training_job.assert_called_once_with( staging_bucket=STAGING_BUCKET, display_name=DISPLAY_NAME, args=ARGS, container_uri=CONTAINER_URI, model_serving_container_image_uri=CONTAINER_URI, command=COMMAND_2, dataset=mock_dataset.return_value, model_display_name=DISPLAY_NAME_2, replica_count=REPLICA_COUNT, machine_type=MACHINE_TYPE, accelerator_type=ACCELERATOR_TYPE, accelerator_count=ACCELERATOR_COUNT, training_fraction_split=TRAINING_FRACTION_SPLIT, validation_fraction_split=VALIDATION_FRACTION_SPLIT, test_fraction_split=TEST_FRACTION_SPLIT, region=GCP_LOCATION, project_id=GCP_PROJECT, parent_model=TEST_PARENT_MODEL, model_serving_container_predict_route=None, model_serving_container_health_route=None, model_serving_container_command=None, model_serving_container_args=None, model_serving_container_environment_variables=None, model_serving_container_ports=None, model_description=None, model_instance_schema_uri=None, model_parameters_schema_uri=None, model_prediction_schema_uri=None, labels=None, training_encryption_spec_key_name=None, model_encryption_spec_key_name=None, # RUN annotation_schema_uri=None, model_labels=None, base_output_dir=None, service_account=None, network=None, bigquery_destination=None, environment_variables=None, boot_disk_type="pd-ssd", boot_disk_size_gb=100, training_filter_split=None, validation_filter_split=None, test_filter_split=None, predefined_split_column_name=None, timestamp_split_column_name=None, tensorboard=None, sync=True, is_default_version=None, model_version_aliases=None, model_version_description=None, psc_interface_config=None, ) @mock.patch(VERTEX_AI_PATH.format("custom_job.Dataset")) @mock.patch(VERTEX_AI_PATH.format("custom_job.CustomJobHook")) def test_execute__parent_model_version_index_is_removed(self, mock_hook, mock_dataset): mock_hook.return_value.create_custom_container_training_job.return_value = ( None, "training_id", "custom_job_id", ) op = CreateCustomContainerTrainingJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, staging_bucket=STAGING_BUCKET, display_name=DISPLAY_NAME, args=ARGS, container_uri=CONTAINER_URI, model_serving_container_image_uri=CONTAINER_URI, command=COMMAND_2, model_display_name=DISPLAY_NAME_2, replica_count=REPLICA_COUNT, machine_type=MACHINE_TYPE, accelerator_type=ACCELERATOR_TYPE, accelerator_count=ACCELERATOR_COUNT, training_fraction_split=TRAINING_FRACTION_SPLIT, validation_fraction_split=VALIDATION_FRACTION_SPLIT, test_fraction_split=TEST_FRACTION_SPLIT, region=GCP_LOCATION, project_id=GCP_PROJECT, dataset_id=TEST_DATASET_ID, parent_model=VERSIONED_TEST_PARENT_MODEL, ) op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()}) mock_hook.return_value.create_custom_container_training_job.assert_called_once_with( staging_bucket=STAGING_BUCKET, display_name=DISPLAY_NAME, args=ARGS, container_uri=CONTAINER_URI, model_serving_container_image_uri=CONTAINER_URI, command=COMMAND_2, dataset=mock_dataset.return_value, model_display_name=DISPLAY_NAME_2, replica_count=REPLICA_COUNT, machine_type=MACHINE_TYPE, accelerator_type=ACCELERATOR_TYPE, accelerator_count=ACCELERATOR_COUNT, training_fraction_split=TRAINING_FRACTION_SPLIT, validation_fraction_split=VALIDATION_FRACTION_SPLIT, test_fraction_split=TEST_FRACTION_SPLIT, region=GCP_LOCATION, project_id=GCP_PROJECT, parent_model=TEST_PARENT_MODEL, model_serving_container_predict_route=None, model_serving_container_health_route=None, model_serving_container_command=None, model_serving_container_args=None, model_serving_container_environment_variables=None, model_serving_container_ports=None, model_description=None, model_instance_schema_uri=None, model_parameters_schema_uri=None, model_prediction_schema_uri=None, labels=None, training_encryption_spec_key_name=None, model_encryption_spec_key_name=None, # RUN annotation_schema_uri=None, model_labels=None, base_output_dir=None, service_account=None, network=None, bigquery_destination=None, environment_variables=None, boot_disk_type="pd-ssd", boot_disk_size_gb=100, training_filter_split=None, validation_filter_split=None, test_filter_split=None, predefined_split_column_name=None, timestamp_split_column_name=None, tensorboard=None, sync=True, is_default_version=None, model_version_aliases=None, model_version_description=None, psc_interface_config=None, ) @mock.patch(VERTEX_AI_PATH.format("custom_job.CreateCustomContainerTrainingJobOperator.hook")) def test_execute_enters_deferred_state(self, mock_hook): task = CreateCustomContainerTrainingJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, staging_bucket=STAGING_BUCKET, display_name=DISPLAY_NAME, args=ARGS, container_uri=CONTAINER_URI, model_serving_container_image_uri=CONTAINER_URI, command=COMMAND_2, model_display_name=DISPLAY_NAME_2, replica_count=REPLICA_COUNT, machine_type=MACHINE_TYPE, accelerator_type=ACCELERATOR_TYPE, accelerator_count=ACCELERATOR_COUNT, training_fraction_split=TRAINING_FRACTION_SPLIT, validation_fraction_split=VALIDATION_FRACTION_SPLIT, test_fraction_split=TEST_FRACTION_SPLIT, region=GCP_LOCATION, project_id=GCP_PROJECT, deferrable=True, ) mock_hook.return_value.exists.return_value = False with pytest.raises(TaskDeferred) as exc: task.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()}) assert isinstance(exc.value.trigger, CustomContainerTrainingJobTrigger), ( "Trigger is not a CustomContainerTrainingJobTrigger" ) @mock.patch(VERTEX_AI_LINKS_PATH.format("VertexAIModelLink.persist")) @mock.patch( VERTEX_AI_PATH.format("custom_job.CreateCustomContainerTrainingJobOperator.hook.extract_model_id") ) @mock.patch(VERTEX_AI_PATH.format("custom_job.CreateCustomContainerTrainingJobOperator.hook")) def test_execute_complete_success(self, mock_hook, mock_hook_extract_model_id, mock_link_persist): task = CreateCustomContainerTrainingJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, staging_bucket=STAGING_BUCKET, display_name=DISPLAY_NAME, args=ARGS, container_uri=CONTAINER_URI, model_serving_container_image_uri=CONTAINER_URI, command=COMMAND_2, model_display_name=DISPLAY_NAME_2, replica_count=REPLICA_COUNT, machine_type=MACHINE_TYPE, accelerator_type=ACCELERATOR_TYPE, accelerator_count=ACCELERATOR_COUNT, training_fraction_split=TRAINING_FRACTION_SPLIT, validation_fraction_split=VALIDATION_FRACTION_SPLIT, test_fraction_split=TEST_FRACTION_SPLIT, region=GCP_LOCATION, project_id=GCP_PROJECT, deferrable=True, ) expected_result = TEST_TRAINING_PIPELINE_DATA["model_to_upload"] mock_hook_extract_model_id.return_value = "test-model" mock_ti = mock.MagicMock() mock_context = {"ti": mock_ti} actual_result = task.execute_complete( context=mock_context, event={ "status": "success", "message": "", "job": TEST_TRAINING_PIPELINE_DATA, }, ) mock_ti.xcom_push.assert_any_call(key="model_id", value="test-model") mock_link_persist.assert_called_once_with(context=mock_context, model_id="test-model") assert actual_result == expected_result def test_execute_complete_error_status_raises_exception(self): task = CreateCustomContainerTrainingJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, staging_bucket=STAGING_BUCKET, display_name=DISPLAY_NAME, args=ARGS, container_uri=CONTAINER_URI, model_serving_container_image_uri=CONTAINER_URI, command=COMMAND_2, model_display_name=DISPLAY_NAME_2, replica_count=REPLICA_COUNT, machine_type=MACHINE_TYPE, accelerator_type=ACCELERATOR_TYPE, accelerator_count=ACCELERATOR_COUNT, training_fraction_split=TRAINING_FRACTION_SPLIT, validation_fraction_split=VALIDATION_FRACTION_SPLIT, test_fraction_split=TEST_FRACTION_SPLIT, region=GCP_LOCATION, project_id=GCP_PROJECT, deferrable=True, ) with pytest.raises(AirflowException): task.execute_complete(context=None, event={"status": "error", "message": "test message"}) @mock.patch(VERTEX_AI_LINKS_PATH.format("VertexAIModelLink.persist")) @mock.patch( VERTEX_AI_PATH.format("custom_job.CreateCustomContainerTrainingJobOperator.hook.extract_model_id") ) @mock.patch(VERTEX_AI_PATH.format("custom_job.CreateCustomContainerTrainingJobOperator.hook")) def test_execute_complete_no_model_produced( self, mock_hook, hook_extract_model_id, mock_link_persist, ): task = CreateCustomContainerTrainingJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, staging_bucket=STAGING_BUCKET, display_name=DISPLAY_NAME, args=ARGS, container_uri=CONTAINER_URI, command=COMMAND_2, replica_count=REPLICA_COUNT, machine_type=MACHINE_TYPE, accelerator_type=ACCELERATOR_TYPE, accelerator_count=ACCELERATOR_COUNT, training_fraction_split=TRAINING_FRACTION_SPLIT, validation_fraction_split=VALIDATION_FRACTION_SPLIT, test_fraction_split=TEST_FRACTION_SPLIT, region=GCP_LOCATION, project_id=GCP_PROJECT, deferrable=True, ) expected_result = None hook_extract_model_id.return_value = None mock_ti = mock.MagicMock() mock_context = {"ti": mock_ti} actual_result = task.execute_complete( context=mock_context, event={"status": "success", "message": "", "job": TEST_TRAINING_PIPELINE_DATA_NO_MODEL}, ) # When no model is produced, xcom_push should still be called but with None value mock_ti.xcom_push.assert_called_once() mock_link_persist.assert_not_called() assert actual_result == expected_result
TestVertexAICreateCustomContainerTrainingJobOperator
python
hyperopt__hyperopt
hyperopt/tests/unit/test_pyll_utils.py
{ "start": 3945, "end": 4559 }
class ____(unittest.TestCase): def test_hp_uniform_raises_error_when_range_is_zero(self): self.assertRaises(ValueError, hp.uniform, "stub", 10, 10) def test_hp_quniform_raises_error_when_range_is_zero(self): self.assertRaises(ValueError, hp.quniform, "stub", 10, 10, 1) def test_hp_loguniform_raises_error_when_range_is_zero(self): self.assertRaises(ValueError, hp.loguniform, "stub", 10, 10, 1) def test_hp_qloguniform_raises_error_when_range_is_zero(self): self.assertRaises(ValueError, hp.qloguniform, "stub", 10, 10, 1)
TestDistributionsWithRangeValidateBoundries
python
pytorch__pytorch
test/export/test_sparse.py
{ "start": 1136, "end": 1211 }
class ____(torch.nn.Module): def forward(self, x): return x
IdNet
python
pytorch__pytorch
torch/_inductor/utils.py
{ "start": 114455, "end": 116657 }
class ____(MutableMapping[KeyType, ValType]): """ A dictionary-like object that allows for scoped updates. It maintains an original dictionary and a set of new items that can override the original items within the scope. The original dictionary is unmodified. """ def __init__(self, original_dict: Mapping[KeyType, ValType]): self.original_dict = original_dict self.new_items: dict[KeyType, ValType] = {} def __getitem__(self, key: KeyType) -> ValType: if key in self.new_items: return self.new_items[key] return self.original_dict[key] def __setitem__(self, key: KeyType, value: ValType) -> None: self.new_items[key] = value def __contains__(self, key: object) -> bool: return key in self.new_items or key in self.original_dict def get(self, key: KeyType, default: Optional[ValType] = None) -> Optional[ValType]: # type: ignore[override] if key in self.new_items: return self.new_items[key] return self.original_dict.get(key, default) def __len__(self) -> int: n = len(self.original_dict) for k in self.new_items: if k not in self.original_dict: n += 1 return n def __iter__(self) -> Iterator[KeyType]: yield from self.original_dict for k in self.new_items: if k not in self.original_dict: yield k def __bool__(self) -> bool: return bool(self.original_dict or self.new_items) def __delitem__(self, key: KeyType) -> None: raise NotImplementedError @dataclass_transform(frozen_default=True) def ir_dataclass(cls: Optional[type[Any]] = None, /, *, frozen: bool = True) -> Any: def wrap(cls: _T) -> _T: return dataclasses.dataclass(cls, kw_only=True, frozen=frozen) # type: ignore[call-overload] if cls is None: return wrap return wrap(cls) def get_donated_idxs() -> Optional[list[int]]: tracing_context = torch._guards.TracingContext.try_get() if tracing_context is not None and tracing_context.fw_metadata: return tracing_context.fw_metadata.bw_donated_idxs return None
ScopedDict
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 16312, "end": 19572 }
class ____: def test_zero_division(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) assert_(np.isinf(b / a)) b = t(complex(np.inf, np.inf)) assert_(np.isinf(b / a)) b = t(complex(np.inf, np.nan)) assert_(np.isinf(b / a)) b = t(complex(np.nan, np.inf)) assert_(np.isinf(b / a)) b = t(complex(np.nan, np.nan)) assert_(np.isnan(b / a)) b = t(0.) assert_(np.isnan(b / a)) def test_signed_zeros(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = ( (( 0.0, -1.0), ( 0.0, 1.0), (-1.0, -0.0)), (( 0.0, -1.0), ( 0.0, -1.0), ( 1.0, -0.0)), (( 0.0, -1.0), (-0.0, -1.0), ( 1.0, 0.0)), (( 0.0, -1.0), (-0.0, 1.0), (-1.0, 0.0)), (( 0.0, 1.0), ( 0.0, -1.0), (-1.0, 0.0)), (( 0.0, -1.0), ( 0.0, -1.0), ( 1.0, -0.0)), ((-0.0, -1.0), ( 0.0, -1.0), ( 1.0, -0.0)), ((-0.0, 1.0), ( 0.0, -1.0), (-1.0, -0.0)) ) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1]) def test_branches(self): with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: # tupled (numerator, denominator, expected) # for testing as expected == numerator/denominator data = [] # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by else condition as neither are == 0 data.append((( 2.0, 1.0), ( 2.0, 1.0), (1.0, 0.0))) # trigger branch: real(fabs(denom)) > imag(fabs(denom)) # followed by if condition as both are == 0 # is performed in test_zero_division(), so this is skipped # trigger else if branch: real(fabs(denom)) < imag(fabs(denom)) data.append(((1.0, 2.0), (1.0, 2.0), (1.0, 0.0))) for cases in data: n = cases[0] d = cases[1] ex = cases[2] result = t(complex(n[0], n[1])) / t(complex(d[0], d[1])) # check real and imag parts separately to avoid comparison # in array context, which does not account for signed zeros assert_equal(result.real, ex[0]) assert_equal(result.imag, ex[1])
TestComplexDivision
python
mwaskom__seaborn
tests/_marks/test_base.py
{ "start": 224, "end": 4973 }
class ____: def mark(self, **features): @dataclass class MockMark(Mark): linewidth: float = Mappable(rc="lines.linewidth") pointsize: float = Mappable(4) color: str = Mappable("C0") fillcolor: str = Mappable(depend="color") alpha: float = Mappable(1) fillalpha: float = Mappable(depend="alpha") m = MockMark(**features) return m def test_repr(self): assert str(Mappable(.5)) == "<0.5>" assert str(Mappable("CO")) == "<'CO'>" assert str(Mappable(rc="lines.linewidth")) == "<rc:lines.linewidth>" assert str(Mappable(depend="color")) == "<depend:color>" assert str(Mappable(auto=True)) == "<auto>" def test_input_checks(self): with pytest.raises(AssertionError): Mappable(rc="bogus.parameter") with pytest.raises(AssertionError): Mappable(depend="nonexistent_feature") def test_value(self): val = 3 m = self.mark(linewidth=val) assert m._resolve({}, "linewidth") == val df = pd.DataFrame(index=pd.RangeIndex(10)) assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val)) def test_default(self): val = 3 m = self.mark(linewidth=Mappable(val)) assert m._resolve({}, "linewidth") == val df = pd.DataFrame(index=pd.RangeIndex(10)) assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val)) def test_rcparam(self): param = "lines.linewidth" val = mpl.rcParams[param] m = self.mark(linewidth=Mappable(rc=param)) assert m._resolve({}, "linewidth") == val df = pd.DataFrame(index=pd.RangeIndex(10)) assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val)) def test_depends(self): val = 2 df = pd.DataFrame(index=pd.RangeIndex(10)) m = self.mark(pointsize=Mappable(val), linewidth=Mappable(depend="pointsize")) assert m._resolve({}, "linewidth") == val assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val)) m = self.mark(pointsize=val * 2, linewidth=Mappable(depend="pointsize")) assert m._resolve({}, "linewidth") == val * 2 assert_array_equal(m._resolve(df, "linewidth"), np.full(len(df), val * 2)) def test_mapped(self): values = {"a": 1, "b": 2, "c": 3} def f(x): return np.array([values[x_i] for x_i in x]) m = self.mark(linewidth=Mappable(2)) scales = {"linewidth": f} assert m._resolve({"linewidth": "c"}, "linewidth", scales) == 3 df = pd.DataFrame({"linewidth": ["a", "b", "c"]}) expected = np.array([1, 2, 3], float) assert_array_equal(m._resolve(df, "linewidth", scales), expected) def test_color(self): c, a = "C1", .5 m = self.mark(color=c, alpha=a) assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a) df = pd.DataFrame(index=pd.RangeIndex(10)) cs = [c] * len(df) assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a)) def test_color_mapped_alpha(self): c = "r" values = {"a": .2, "b": .5, "c": .8} m = self.mark(color=c, alpha=Mappable(1)) scales = {"alpha": lambda s: np.array([values[s_i] for s_i in s])} assert resolve_color(m, {"alpha": "b"}, "", scales) == mpl.colors.to_rgba(c, .5) df = pd.DataFrame({"alpha": list(values.keys())}) # Do this in two steps for mpl 3.2 compat expected = mpl.colors.to_rgba_array([c] * len(df)) expected[:, 3] = list(values.values()) assert_array_equal(resolve_color(m, df, "", scales), expected) def test_color_scaled_as_strings(self): colors = ["C1", "dodgerblue", "#445566"] m = self.mark() scales = {"color": lambda s: colors} actual = resolve_color(m, {"color": pd.Series(["a", "b", "c"])}, "", scales) expected = mpl.colors.to_rgba_array(colors) assert_array_equal(actual, expected) def test_fillcolor(self): c, a = "green", .8 fa = .2 m = self.mark( color=c, alpha=a, fillcolor=Mappable(depend="color"), fillalpha=Mappable(fa), ) assert resolve_color(m, {}) == mpl.colors.to_rgba(c, a) assert resolve_color(m, {}, "fill") == mpl.colors.to_rgba(c, fa) df = pd.DataFrame(index=pd.RangeIndex(10)) cs = [c] * len(df) assert_array_equal(resolve_color(m, df), mpl.colors.to_rgba_array(cs, a)) assert_array_equal( resolve_color(m, df, "fill"), mpl.colors.to_rgba_array(cs, fa) )
TestMappable
python
django__django
tests/generic_relations/tests.py
{ "start": 37754, "end": 38126 }
class ____(SimpleTestCase): def test_none_allowed(self): # AllowsNullGFK doesn't require a content_type, so None argument should # also be allowed. AllowsNullGFK(content_object=None) # TaggedItem requires a content_type but initializing with None should # be allowed. TaggedItem(content_object=None)
TestInitWithNoneArgument
python
pytest-dev__pytest
testing/test_subtests.py
{ "start": 26826, "end": 31689 }
class ____: """Check --pdb support for subtests fixture and TestCase.subTest.""" class _FakePdb: """Fake debugger class implementation that tracks which methods were called on it.""" quitting: bool = False calls: list[str] = [] def __init__(self, *_: object, **__: object) -> None: self.calls.append("init") def reset(self) -> None: self.calls.append("reset") def interaction(self, *_: object) -> None: self.calls.append("interaction") @pytest.fixture(autouse=True) def cleanup_calls(self) -> None: self._FakePdb.calls.clear() def test_pdb_fixture( self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch ) -> None: pytester.makepyfile( """ def test(subtests): with subtests.test(): assert 0 """ ) self.runpytest_and_check_pdb(pytester, monkeypatch) def test_pdb_unittest( self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch ) -> None: pytester.makepyfile( """ from unittest import TestCase class Test(TestCase): def test(self): with self.subTest(): assert 0 """ ) self.runpytest_and_check_pdb(pytester, monkeypatch) def runpytest_and_check_pdb( self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch ) -> None: # Install the fake pdb implementation in _pytest.subtests so we can reference # it in the command line (any module would do). import _pytest.subtests monkeypatch.setattr( _pytest.subtests, "_CustomPdb", self._FakePdb, raising=False ) result = pytester.runpytest("--pdb", "--pdbcls=_pytest.subtests:_CustomPdb") # Ensure pytest entered in debugging mode when encountering the failing # assert. result.stdout.fnmatch_lines("*entering PDB*") assert self._FakePdb.calls == ["init", "reset", "interaction"] def test_exitfirst(pytester: pytest.Pytester) -> None: """Validate that when passing --exitfirst the test exits after the first failed subtest.""" pytester.makepyfile( """ def test_foo(subtests): with subtests.test("sub1"): assert False with subtests.test("sub2"): assert False """ ) result = pytester.runpytest("--exitfirst") assert result.parseoutcomes()["failed"] == 2 result.stdout.fnmatch_lines( [ "SUBFAILED*[[]sub1[]] *.py::test_foo - assert False*", "FAILED *.py::test_foo - assert False", "* stopping after 2 failures*", ], consecutive=True, ) result.stdout.no_fnmatch_line("*sub2*") # sub2 not executed. def test_do_not_swallow_pytest_exit(pytester: pytest.Pytester) -> None: pytester.makepyfile( """ import pytest def test(subtests): with subtests.test(): pytest.exit() def test2(): pass """ ) result = pytester.runpytest_subprocess() result.stdout.fnmatch_lines( [ "* _pytest.outcomes.Exit *", "* 1 failed in *", ] ) def test_nested(pytester: pytest.Pytester) -> None: """ Currently we do nothing special with nested subtests. This test only sediments how they work now, we might reconsider adding some kind of nesting support in the future. """ pytester.makepyfile( """ import pytest def test(subtests): with subtests.test("a"): with subtests.test("b"): assert False, "b failed" assert False, "a failed" """ ) result = pytester.runpytest_subprocess() result.stdout.fnmatch_lines( [ "SUBFAILED[b] test_nested.py::test - AssertionError: b failed", "SUBFAILED[a] test_nested.py::test - AssertionError: a failed", "* 3 failed in *", ] ) def test_serialization() -> None: from _pytest.subtests import pytest_report_from_serializable from _pytest.subtests import pytest_report_to_serializable report = SubtestReport( "test_foo::test_foo", ("test_foo.py", 12, ""), keywords={}, outcome="passed", when="call", longrepr=None, context=SubtestContext(msg="custom message", kwargs=dict(i=10)), ) data = pytest_report_to_serializable(report) assert data is not None new_report = pytest_report_from_serializable(data) assert new_report is not None assert new_report.context == SubtestContext(msg="custom message", kwargs=dict(i=10))
TestDebugging
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/matchClass3.py
{ "start": 592, "end": 630 }
class ____: title: str @final
AFinal
python
pytorch__pytorch
torch/_dynamo/types.py
{ "start": 3950, "end": 4034 }
class ____(Protocol): def __call__(self, record: Any) -> None: ...
ProfilerEndHook
python
getsentry__sentry
tests/sentry/models/test_projectcodeowners.py
{ "start": 223, "end": 3148 }
class ____(TestCase): def tearDown(self) -> None: cache.delete(ProjectCodeOwners.get_cache_key(self.project.id)) super().tearDown() def setUp(self) -> None: self.login_as(user=self.user) self.team = self.create_team( organization=self.organization, slug="tiger-team", members=[self.user] ) self.project = self.project = self.create_project( organization=self.organization, teams=[self.team], slug="bengal" ) self.code_mapping = self.create_code_mapping( project=self.project, ) self.external_team = self.create_external_team(integration=self.integration) self.external_user = self.create_external_user( self.user, self.organization, integration=self.integration, external_name="@NisanthanNanthakumar", ) self.data = { "raw": "docs/* @NisanthanNanthakumar @getsentry/ecosystem\n", } def test_merge_codeowners(self) -> None: self.code_mapping_2 = self.create_code_mapping( project=self.project, stack_root="stack/root/", ) code_owners_1_rule = Rule( Matcher("codeowners", "docs/*"), [Owner("user", self.user.email), Owner("team", self.team.slug)], ) code_owners_2_rule = Rule( Matcher("codeowners", "stack/root/docs/*"), [Owner("user", self.user.email), Owner("team", self.team.slug)], ) self.code_owners = self.create_codeowners( self.project, self.code_mapping, raw=self.data["raw"], schema=dump_schema([code_owners_1_rule]), ) self.code_owners_2 = self.create_codeowners( self.project, self.code_mapping_2, raw=self.data["raw"], schema=dump_schema([code_owners_2_rule]), ) code_owners = ProjectCodeOwners.objects.filter(project=self.project) merged = ProjectCodeOwners.merge_code_owners_list(code_owners_list=code_owners) assert merged is not None assert merged.schema == { "$version": 1, "rules": [ { "matcher": {"type": "codeowners", "pattern": "docs/*"}, "owners": [ {"type": "user", "identifier": "admin@localhost"}, {"type": "team", "identifier": "tiger-team"}, ], }, { "matcher": {"type": "codeowners", "pattern": "stack/root/docs/*"}, "owners": [ {"type": "user", "identifier": "admin@localhost"}, {"type": "team", "identifier": "tiger-team"}, ], }, ], }
ProjectCodeOwnersTestCase
python
pyparsing__pyparsing
examples/tiny/tiny_engine.py
{ "start": 1923, "end": 15187 }
class ____: """Runtime engine to execute TINY AST nodes. Responsibilities: - Manage I/O buffers (text-based input and output) - Maintain a simple variable environment (name -> value, with optional type) - Maintain a stack of frames (local variables) to scope variables defined in functions - Provide helpers for declaring and assigning variables - Evaluate parser expression trees produced by `tiny_parser` Notes: - Types supported: int, float, string. Numeric operations promote to float when needed. - Boolean context: 0 or empty string is False; anything else is True. """ def __init__(self) -> None: # Dedicated program-level globals and function registry self._globals: TinyFrame = TinyFrame() self._functions: dict[str, TinyNode] = {} # Function signatures: name -> (return_type, [(ptype, pname), ...]) # Used when functions are registered as AST nodes to bind parameters self._function_sigs: dict[str, tuple[str, list[tuple[str, str]]]] = {} # Stack of frames (last is current); empty until main/function entry self._frames: list[TinyFrame] = [] self._in: list[str] = [] self._out: list[str] = [] # ----- Program-level registry (globals/functions) ----- def register_function(self, name: str, fn: TinyNode) -> None: """Register a program-level function definition by name.""" self._functions[name] = fn def get_function(self, name: str) -> TinyNode | None: return self._functions.get(name) def register_function_signature( self, name: str, return_type: str, params: list[tuple[str, str]] ) -> None: """Register or update a function's signature metadata. params: list of (ptype, pname) """ self._function_sigs[name] = (return_type, params) # ----- Frame management ----- @property def current_frame(self) -> TinyFrame: if not self._frames: raise RuntimeError( "No current frame: push_frame() must be called before using locals" ) return self._frames[-1] def push_frame(self) -> None: self._frames.append(TinyFrame()) def pop_frame(self) -> None: if not self._frames: raise RuntimeError("No frame to pop") self._frames.pop() # ----- I/O API ----- def input_text(self, data: str) -> None: """Load whitespace-delimited tokens into the input buffer. Example: engine.input_text("10 20 hello") """ # split on any whitespace; preserve order for FIFO consumption if data: self._in.extend(data.split()) def output_text(self) -> None: """Print the current buffered output and clear the buffer.""" print("".join(self._out), end="") self._out.clear() # Optional helpers for potential node use def _write(self, s: str) -> None: self._out.append(s) def _writeln(self) -> None: self._out.append("\n") # ----- Variables API ----- def declare_var( self, name: str, dtype: str, init_value: object | None = None ) -> None: """Declare a variable with an optional initial value. dtype: 'int' | 'float' | 'string' """ # Declare in the current frame only if dtype not in {"int", "float", "string"}: raise TypeError(f"Unsupported datatype: {dtype!r}") if name in self.current_frame: raise NameError(f"Variable already declared: {name!r}") value = ( self._coerce(init_value, dtype) if init_value is not None else self._default_for(dtype) ) self.current_frame.declare(name, dtype, value) # Globals API def declare_global_var( self, name: str, dtype: str, init_value: object | None = None ) -> None: if dtype not in {"int", "float", "string"}: raise TypeError(f"Unsupported datatype: {dtype!r}") if name in self._globals: raise NameError(f"Global already declared: {name!r}") value = ( self._coerce(init_value, dtype) if init_value is not None else self._default_for(dtype) ) self._globals.declare(name, dtype, value) def assign_global_var(self, name: str, value: object) -> None: if name not in self._globals: # If not declared, infer type and declare inferred = self._infer_type_from_value(value) self.declare_global_var(name, inferred, value) return dtype = self._globals.get_type(name) self._globals.set(name, self._coerce(value, dtype)) def assign_var(self, name: str, value: object) -> None: """Assign to an existing variable; if undeclared, declare using inferred type.""" if ( isinstance(value, (list, tuple)) or hasattr(value, "__class__") and value.__class__.__name__ == "ParseResults" ): # Late evaluation if a parse tree is passed accidentally value = self.eval_expr(value) # type: ignore[arg-type] # Find the nearest frame containing the variable; fall back to globals; otherwise declare local frame = self.current_frame if name in frame: dtype = frame.get_type(name) frame.set(name, self._coerce(value, dtype)) return if name in self._globals: dtype = self._globals.get_type(name) self._globals.set(name, self._coerce(value, dtype)) return # Not found anywhere; declare locally with inferred type inferred = self._infer_type_from_value(value) self.declare_var(name, inferred, value) def get_var(self, name: str) -> object: frame = self.current_frame if name in frame: return frame.get(name) if name in self._globals: return self._globals.get(name) raise NameError(f"Variable not declared: {name!r}") # ----- Expression Evaluation ----- def eval_expr(self, expr: object) -> object: """Evaluate an expression built by pyparsing's infix_notation and tokens. Accepts primitives (int/float/str), identifiers (str that is a declared var), pyparsing ParseResults for infix trees, and function call groups with tag type 'func_call'. """ # Primitive values if isinstance(expr, (int, float, str)): # Identifier lookup: if a bare string matches a var name, read its value if isinstance(expr, str): fr = self.current_frame if expr in fr: return fr.get(expr) if expr in self._globals: return self._globals.get(expr) return expr # ParseResults cases if isinstance(expr, pp.ParseResults): # Function call group if "type" in expr and expr["type"] == "func_call": # type: ignore[index] name = expr.name arg_values = [ self.eval_expr(arg) for arg in (expr.get("args", []) or []) ] return self.call_function(name, arg_values) # Infix notation yields list-like tokens tokens = list(expr) if not tokens: return None # Unary + or - : [op, operand] if len(tokens) == 2 and tokens[0] in {"+", "-"}: op, rhs = tokens rv = self.eval_expr(rhs) return +self._to_number(rv) if op == "+" else -self._to_number(rv) # Binary or n-ary left-assoc: [lhs, op, rhs, op, rhs, ...] # We fold left-to-right respecting the original parsed precedence. acc = self.eval_expr(tokens[0]) i = 1 while i < len(tokens): op = tokens[i] rhs = self.eval_expr(tokens[i + 1]) acc = self._apply_op(acc, op, rhs) i += 2 return acc # Lists/tuples could be token sequences if isinstance(expr, (list, tuple)): acc: object | None = None for part in expr: acc = self.eval_expr(part) return acc # Fallback return expr # ----- Functions API (execution helper to share with CallStmtNode) ----- def call_function(self, name: str, args: list[object]) -> object | None: """Call a user-defined function by name with already-evaluated arguments. This method is used by expression evaluation (for `func_call` terms) and can be reused by `CallStmtNode.execute` to perform statement-style calls. """ fn = self.get_function(name) if fn is None: raise NameError(f"Undefined function: {name!r}") if name not in self._function_sigs: raise TypeError(f"Missing signature for function {name!r}") return_type, params = self._function_sigs[name] if len(args) != len(params): raise TypeError( f"Function {name!r} expects {len(params)} args, got {len(args)}" ) self.push_frame() try: # Bind parameters in order for (ptype, pname), value in zip(params, args): self.declare_var(pname, ptype or "int", value) # Execute body node return fn.execute(self) finally: self.pop_frame() # ----- Helpers ----- def _default_for(self, dtype: str) -> object: return 0 if dtype == "int" else 0.0 if dtype == "float" else "" def _infer_type_from_value(self, value: object) -> str: if isinstance(value, bool): return "int" # treat bool as int if isinstance(value, int): return "int" if isinstance(value, float): return "float" if isinstance(value, str): return "string" # Unknown types default to string via str() return "string" def _coerce(self, value: object, dtype: str) -> object: if dtype == "int": try: return int(value) except ValueError: raise TypeError(f"Cannot coerce {value!r} to int") from None if dtype == "float": try: return float(value) except ValueError: raise TypeError(f"Cannot coerce {value!r} to float") from None if dtype == "string": return str(value) raise TypeError(f"Unsupported datatype: {dtype!r}") def _to_number(self, v: object) -> int | float: """Return a numeric value for v following Tiny semantics. Rules: - If v is already an int or float, return it unchanged (no float coercion). - If v is a string, treat it as a variable name; fetch its current value from the environment. If that value is int or float, return it; otherwise raise TypeError. - For all other types, raise TypeError. """ # Already numeric: return as-is (do not coerce int->float) if isinstance(v, (int, float)): return v # If it's a string, interpret as variable name and resolve if isinstance(v, str): try: val = self.get_var(v) except NameError as exc: raise TypeError( f"Expected numeric variable name, got undefined identifier {v!r}" ) from exc if isinstance(val, (int, float)): return val raise TypeError(f"Variable {v!r} is not numeric: {val!r}") # Anything else is not acceptable as a numeric raise TypeError(f"Expected numeric, got {v!r}") def _apply_op(self, lhs: object, op: str, rhs: object) -> object: # Boolean ops if op in {"&&", "||"}: lv = bool(lhs) rv = bool(rhs) return _op_map[op](lv, rv) # Relational ops if op in {"<", ">", "=", "<>", ">=", "<="}: # Numeric compare if both numeric-like; else string compare if isinstance(lhs, (int, float)) or isinstance(rhs, (int, float)): lnum = self._to_number(lhs) rnum = self._to_number(rhs) return _op_map[op](lnum, rnum) else: lstr = str(lhs) rstr = str(rhs) return _op_map[op](lstr, rstr) # Arithmetic ops if op in {"+", "-", "*", "/"}: # String concatenation when both are strings and op '+' if op == "+" and isinstance(lhs, str) and isinstance(rhs, str): return lhs + rhs # Numeric operations lnum = self._to_number(lhs) rnum = self._to_number(rhs) # leave ints as ints ret = _op_map[op](lnum, rnum) if op != "/" and isinstance(lnum, int) and isinstance(rnum, int): ret = self._coerce(ret, "int") return ret raise NotImplementedError(f"Operator not implemented: {op!r}")
TinyEngine
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/call17.py
{ "start": 420, "end": 772 }
class ____(Generic[E_co]): def or_else(self, op: Callable[[E_co], Result[T_co, F]]) -> Result[T_co, F]: ... Result = Ok[T_co] | Err[E_co] def inner(func: Callable[[E_co], Err[F]], r: Result[T_co, E_co]) -> Result[T_co, F]: match r: case Ok(): return r.or_else(func) case Err(): return r.or_else(func)
Err
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-azure-translate/llama_index/tools/azure_translate/base.py
{ "start": 194, "end": 1194 }
class ____(BaseToolSpec): """Azure Translate tool spec.""" spec_functions = ["translate"] def __init__(self, api_key: str, region: str) -> None: """Initialize with parameters.""" self.headers = { "Ocp-Apim-Subscription-Key": api_key, "Ocp-Apim-Subscription-Region": region, "Content-type": "application/json", } def translate(self, text: str, language: str): """ Use this tool to translate text from one language to another. The source language will be automatically detected. You need to specify the target language using a two character language code. Args: language (str): Target translation language. """ request = requests.post( ENDPOINT_BASE_URL, params={"api-version": "3.0", "to": language}, headers=self.headers, json=[{"text": text}], ) return request.json()
AzureTranslateToolSpec
python
joke2k__faker
faker/providers/internet/bn_BD/__init__.py
{ "start": 46, "end": 500 }
class ____(InternetProvider): """ Implement internet provider for ``bn_BD`` locale. """ free_email_domains = ( "gmail.com", "yahoo.com", "hotmail.com", "mail.ru", "yandex.ru", "rambler.ru", ) tlds = ( "com", "com", "com", "com", "com", "com", "biz", "info", "net", "org", "com.bd", )
Provider
python
huggingface__transformers
src/transformers/models/florence2/modeling_florence2.py
{ "start": 3026, "end": 4157 }
class ____(nn.Module): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, config: Florence2Config): super().__init__() num_pos = config.vision_config.max_position_embeddings embedding_dim = config.vision_config.embed_dim[-1] self.row_embeddings = nn.Embedding(num_pos, embedding_dim // 2) self.column_embeddings = nn.Embedding(num_pos, embedding_dim - (embedding_dim // 2)) def forward(self, pixel_values, pixel_mask=None): height, width = pixel_values.shape[-2:] width_values = torch.arange(width, device=pixel_values.device) height_values = torch.arange(height, device=pixel_values.device) x_emb = self.column_embeddings(width_values) y_emb = self.row_embeddings(height_values) pos = torch.cat([x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1) pos = pos.permute(2, 0, 1) pos = pos.unsqueeze(0) pos = pos.repeat(pixel_values.shape[0], 1, 1, 1) return pos
Florence2VisionLearnedAbsolutePositionEmbedding2D
python
networkx__networkx
networkx/lazy_imports.py
{ "start": 2281, "end": 5764 }
class ____(types.ModuleType): def __init__(self, frame_data, *args, **kwargs): self.__frame_data = frame_data super().__init__(*args, **kwargs) def __getattr__(self, x): if x in ("__class__", "__file__", "__frame_data"): super().__getattr__(x) else: fd = self.__frame_data raise ModuleNotFoundError( f"No module named '{fd['spec']}'\n\n" "This error is lazily reported, having originally occurred in\n" f" File {fd['filename']}, line {fd['lineno']}, in {fd['function']}\n\n" f"----> {''.join(fd['code_context'] or '').strip()}" ) def _lazy_import(fullname): """Return a lazily imported proxy for a module or library. Warning ------- Importing using this function can currently cause trouble when the user tries to import from a subpackage of a module before the package is fully imported. In particular, this idiom may not work: np = lazy_import("numpy") from numpy.lib import recfunctions This is due to a difference in the way Python's LazyLoader handles subpackage imports compared to the normal import process. Hopefully we will get Python's LazyLoader to fix this, or find a workaround. In the meantime, this is a potential problem. The workaround is to import numpy before importing from the subpackage. Notes ----- We often see the following pattern:: def myfunc(): import scipy as sp sp.argmin(...) .... This is to prevent a library, in this case `scipy`, from being imported at function definition time, since that can be slow. This function provides a proxy module that, upon access, imports the actual module. So the idiom equivalent to the above example is:: sp = lazy.load("scipy") def myfunc(): sp.argmin(...) .... The initial import time is fast because the actual import is delayed until the first attribute is requested. The overall import time may decrease as well for users that don't make use of large portions of the library. Parameters ---------- fullname : str The full name of the package or subpackage to import. For example:: sp = lazy.load("scipy") # import scipy as sp spla = lazy.load("scipy.linalg") # import scipy.linalg as spla Returns ------- pm : importlib.util._LazyModule Proxy module. Can be used like any regularly imported module. Actual loading of the module occurs upon first attribute request. """ try: return sys.modules[fullname] except: pass # Not previously loaded -- look it up spec = importlib.util.find_spec(fullname) if spec is None: try: parent = inspect.stack()[1] frame_data = { "spec": fullname, "filename": parent.filename, "lineno": parent.lineno, "function": parent.function, "code_context": parent.code_context, } return DelayedImportErrorModule(frame_data, "DelayedImportErrorModule") finally: del parent module = importlib.util.module_from_spec(spec) sys.modules[fullname] = module loader = importlib.util.LazyLoader(spec.loader) loader.exec_module(module) return module
DelayedImportErrorModule
python
ray-project__ray
python/ray/data/tests/test_predicate_pushdown.py
{ "start": 28891, "end": 31214 }
class ____: """Tests for PUSH_INTO_BRANCHES behavior operators. Operator: Union Predicates are duplicated and pushed into each branch. """ def test_simple_union_with_filter(self, ray_start_regular_shared): """Filter after union should push into both branches.""" ds1 = ray.data.range(100, parallelism=2) ds2 = ray.data.range(100, parallelism=2) ds = ds1.union(ds2).filter(expr=col("id") >= 50) # Verify correctness: should have duplicates from both branches base = ray.data.range(100) expected = base.filter(expr=col("id") >= 50).union( base.filter(expr=col("id") >= 50) ) assert rows_same(ds.to_pandas(), expected.to_pandas()) def test_multiple_unions_with_filter(self, ray_start_regular_shared): """Filter should push into all branches of multiple unions.""" ds1 = ray.data.read_parquet("example://iris.parquet") ds2 = ray.data.read_parquet("example://iris.parquet") ds3 = ray.data.read_parquet("example://iris.parquet") ds = ds1.union(ds2).union(ds3).filter(expr=col("sepal.length") > 5.0) # Verify correctness: should have 3x the filtered results single_filtered = ray.data.read_parquet("example://iris.parquet").filter( expr=col("sepal.length") > 5.0 ) expected = single_filtered.union(single_filtered).union(single_filtered) assert rows_same(ds.to_pandas(), expected.to_pandas()) def test_branch_filters_plus_union_filter(self, ray_start_regular_shared): """Individual branch filters plus union filter should all push.""" parquet_ds = ray.data.read_parquet("example://iris.parquet") ds1 = parquet_ds.filter(expr=col("sepal.width") > 2.0) ds2 = parquet_ds.filter(expr=col("sepal.width") > 2.0) ds = ds1.union(ds2).filter(expr=col("sepal.length") < 5.0) # Verify correctness: both filters applied expected_single = parquet_ds.filter( expr=(col("sepal.width") > 2.0) & (col("sepal.length") < 5.0) ) expected = expected_single.union(expected_single) assert rows_same(ds.to_pandas(), expected.to_pandas()) if __name__ == "__main__": import sys sys.exit(pytest.main(["-v", __file__]))
TestPushIntoBranchesBehavior
python
milvus-io__pymilvus
tests/test_connections.py
{ "start": 294, "end": 7595 }
class ____: """ Connect to a connected alias will: - ignore and return if no configs are given - raise ConnectionConfigException if inconsistent configs are given Connect to an existing and not connected alias will: - connect with the existing alias config if no configs are given - connect with the providing configs if valid, and replace the old ones. Connect to a new alias will: - connect with the providing configs if valid, store the new alias with these configs """ @pytest.fixture(scope="function", params=[ {}, {"random": "not useful"}, ]) def no_host_port(self, request): return request.param @pytest.fixture(scope="function", params=[ {"port": "19530"}, {"host": "localhost"}, ]) def no_host_or_port(self, request): return request.param @pytest.fixture(scope="function", params=[ {"uri": "https://127.0.0.1:19530"}, {"uri": "tcp://127.0.0.1:19530"}, {"uri": "http://127.0.0.1:19530"}, {"uri": "http://example.com:80"}, {"uri": "http://example.com:80/database1"}, {"uri": "https://127.0.0.1:19530/database2"}, {"uri": "https://127.0.0.1/database3"}, {"uri": "http://127.0.0.1/database4"}, ]) def uri(self, request): return request.param def test_connect_with_default_config(self): alias = "default" default_addr = {"address": "localhost:19530", "user": ""} assert connections.has_connection(alias) is False addr = connections.get_connection_addr(alias) assert addr == default_addr with mock.patch(f"{mock_prefix}.__init__", return_value=None), mock.patch(f"{mock_prefix}._wait_for_channel_ready", return_value=None): connections.connect(keep_alive=False) assert connections.has_connection(alias) is True addr = connections.get_connection_addr(alias) assert addr == default_addr with mock.patch(f"{mock_prefix}.close", return_value=None): connections.disconnect(alias) @pytest.fixture(scope="function", params=[ ("", {"address": "localhost:19530", "user": ""}), ("localhost", {"address": "localhost:19530", "user": ""}), ("localhost:19530", {"address": "localhost:19530", "user": ""}), ("abc@localhost", {"address": "localhost:19530", "user": "abc"}), ("milvus_host", {"address": "milvus_host:19530", "user": ""}), ("milvus_host:12012", {"address": "milvus_host:12012", "user": ""}), ("abc@milvus_host:12012", {"address": "milvus_host:12012", "user": "abc"}), ("abc@milvus_host", {"address": "milvus_host:19530", "user": "abc"}), ]) def test_connect_with_default_config_from_environment(self, env_result): os.environ[DefaultConfig.MILVUS_URI] = env_result[0] assert env_result[1] == connections._read_default_config_from_os_env() # use env with mock.patch(f"{mock_prefix}.__init__", return_value=None), mock.patch(f"{mock_prefix}._wait_for_channel_ready", return_value=None): connections.connect(keep_alive=False) assert env_result[1] == connections.get_connection_addr(DefaultConfig.MILVUS_CONN_ALIAS) # use param with mock.patch(f"{mock_prefix}.__init__", return_value=None), mock.patch(f"{mock_prefix}._wait_for_channel_ready", return_value=None): connections.connect(DefaultConfig.MILVUS_CONN_ALIAS, host="test_host", port="19999", keep_alive=False) curr_addr = connections.get_connection_addr(DefaultConfig.MILVUS_CONN_ALIAS) assert env_result[1] != curr_addr assert curr_addr == {"address":"test_host:19999", "user": ""} with mock.patch(f"{mock_prefix}.close", return_value=None): connections.remove_connection(DefaultConfig.MILVUS_CONN_ALIAS) def test_connect_new_alias_with_configs(self): alias = "exist" addr = {"address": "localhost:19530"} assert connections.has_connection(alias) is False a = connections.get_connection_addr(alias) assert a == {} with mock.patch(f"{mock_prefix}.__init__", return_value=None), mock.patch(f"{mock_prefix}._wait_for_channel_ready", return_value=None): connections.connect(alias, **addr, keep_alive=False) assert connections.has_connection(alias) is True a = connections.get_connection_addr(alias) a.pop("user") assert a == addr with mock.patch(f"{mock_prefix}.close", return_value=None): connections.remove_connection(alias) def test_connect_new_alias_with_configs_NoHostOrPort(self, no_host_or_port): alias = "no_host_or_port" assert connections.has_connection(alias) is False a = connections.get_connection_addr(alias) assert a == {} with mock.patch(f"{mock_prefix}.__init__", return_value=None), mock.patch(f"{mock_prefix}._wait_for_channel_ready", return_value=None): connections.connect(alias, **no_host_or_port, keep_alive=False) assert connections.has_connection(alias) is True assert connections.get_connection_addr(alias) == {"address": "localhost:19530", "user": ""} with mock.patch(f"{mock_prefix}.close", return_value=None): connections.remove_connection(alias) def test_connect_new_alias_with_no_config(self): alias = self.test_connect_new_alias_with_no_config.__name__ assert connections.has_connection(alias) is False a = connections.get_connection_addr(alias) assert a == {} with pytest.raises(MilvusException) as excinfo: connections.connect(alias, keep_alive=False) LOGGER.info(f"Exception info: {excinfo.value}") assert "You need to pass in the configuration" in excinfo.value.message assert excinfo.value.code == ErrorCode.UNEXPECTED_ERROR def test_connect_with_uri(self, uri): alias = self.test_connect_with_uri.__name__ with mock.patch(f"{mock_prefix}._setup_grpc_channel", return_value=None), mock.patch(f"{mock_prefix}._wait_for_channel_ready", return_value=None): connections.connect(alias, **uri, keep_alive=False) addr = connections.get_connection_addr(alias) LOGGER.debug(addr) assert connections.has_connection(alias) is True with mock.patch(f"{mock_prefix}.close", return_value=None): connections.remove_connection(alias) def test_add_connection_then_connect(self, uri): alias = self.test_add_connection_then_connect.__name__ connections.add_connection(**{alias: uri}) addr1 = connections.get_connection_addr(alias) LOGGER.debug(f"addr1: {addr1}") with mock.patch(f"{mock_prefix}._setup_grpc_channel", return_value=None), mock.patch(f"{mock_prefix}._wait_for_channel_ready", return_value=None): connections.connect(alias, keep_alive=False) addr2 = connections.get_connection_addr(alias) LOGGER.debug(f"addr2: {addr2}") assert addr1 == addr2 with mock.patch(f"{mock_prefix}.close", return_value=None): connections.remove_connection(alias)
TestConnect
python
bokeh__bokeh
src/bokeh/models/renderers/renderer.py
{ "start": 2376, "end": 3889 }
class ____(StyledElement): """An abstract base class for renderer types. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) level = Enum(RenderLevel, help=""" Specifies the level in which to paint this renderer. """) visible = Bool(default=True, help=""" Is the renderer visible. """) coordinates = Nullable(Instance(CoordinateMapping)) x_range_name = String("default", help=""" A particular (named) x-range to use for computing screen locations when rendering glyphs on the plot. If unset, use the default x-range. """) y_range_name = String("default", help=""" A particular (named) y-range to use for computing screen locations when rendering glyphs on the plot. If unset, use the default y-range. """) group = Nullable(Instance(RendererGroup), help=""" .. note:: This property is experimental and may change at any point. """) propagate_hover = Bool(default=False, help=""" Allows to propagate hover events to the parent renderer, frame or canvas. .. note:: This property is experimental and may change at any point. """) context_menu = Nullable(Instance(".models.ui.Menu"), default=None, help=""" A menu to display when user right clicks on the component. .. note:: Use shift key when right clicking to display the native context menu. """) @abstract
Renderer
python
lazyprogrammer__machine_learning_examples
supervised_class2/bagging_regression.py
{ "start": 1018, "end": 1927 }
class ____: def __init__(self, B): self.B = B def fit(self, X, Y): N = len(X) self.models = [] for b in range(self.B): idx = np.random.choice(N, size=N, replace=True) Xb = X[idx] Yb = Y[idx] model = DecisionTreeRegressor() model.fit(Xb, Yb) self.models.append(model) def predict(self, X): predictions = np.zeros(len(X)) for model in self.models: predictions += model.predict(X) return predictions / self.B def score(self, X, Y): d1 = Y - self.predict(X) d2 = Y - Y.mean() return 1 - d1.dot(d1) / d2.dot(d2) model = BaggedTreeRegressor(200) model.fit(Xtrain, Ytrain) print("score for bagged tree:", model.score(x_axis.reshape(T, 1), y_axis)) prediction = model.predict(x_axis.reshape(T, 1)) # plot the bagged regressor's predictions plt.plot(x_axis, prediction) plt.plot(x_axis, y_axis) plt.show()
BaggedTreeRegressor
python
openai__openai-python
src/openai/types/evals/create_eval_completions_run_data_source.py
{ "start": 1408, "end": 1529 }
class ____(BaseModel): item: Dict[str, object] sample: Optional[Dict[str, object]] = None
SourceFileContentContent
python
getsentry__sentry
src/sentry/rules/conditions/reappeared_event.py
{ "start": 395, "end": 1532 }
class ____(EventCondition): id = "sentry.rules.conditions.reappeared_event.ReappearedEventCondition" label = "The issue changes state from archived to escalating" def passes(self, event: GroupEvent, state: EventState) -> bool: return state.has_escalated def get_activity( self, start: datetime, end: datetime, limit: int ) -> Sequence[ConditionActivity]: # escalations are recorded as SET_ESCALATING activities = ( Activity.objects.filter( project=self.project, datetime__gte=start, datetime__lt=end, type=ActivityType.SET_ESCALATING.value, ) .order_by("-datetime")[:limit] .values_list("group", "datetime", "data") ) return [ ConditionActivity( group_id=group_id, type=ConditionActivityType.REAPPEARED, timestamp=timestamp, data=data or {}, ) for group_id, timestamp, data in activities if group_id is not None ]
ReappearedEventCondition
python
huggingface__transformers
src/transformers/models/decision_transformer/modeling_decision_transformer.py
{ "start": 3394, "end": 12458 }
class ____(nn.Module): def __init__(self, config, is_cross_attention=False, layer_idx=None): super().__init__() self.config = config max_positions = config.max_position_embeddings self.register_buffer( "bias", torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view( 1, 1, max_positions, max_positions ), persistent=False, ) self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False) self.embed_dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.embed_dim // self.num_heads self.split_size = self.embed_dim if self.head_dim * self.num_heads != self.embed_dim: raise ValueError( f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" f" {self.num_heads})." ) self.scale_attn_weights = config.scale_attn_weights self.is_cross_attention = is_cross_attention # Layer-wise attention scaling, reordering, and upcasting self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx self.layer_idx = layer_idx self.reorder_and_upcast_attn = config.reorder_and_upcast_attn if self.is_cross_attention: self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim) self.q_attn = Conv1D(self.embed_dim, self.embed_dim) else: self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim) self.c_proj = Conv1D(self.embed_dim, self.embed_dim) self.attn_dropout = nn.Dropout(config.attn_pdrop) self.resid_dropout = nn.Dropout(config.resid_pdrop) self.is_causal = not is_cross_attention def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None): # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM) bsz, num_heads, q_seq_len, dk = query.size() _, _, k_seq_len, _ = key.size() # Preallocate attn_weights for `baddbmm` attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device) # Compute Scale Factor scale_factor = 1.0 if self.scale_attn_weights: scale_factor /= float(value.size(-1)) ** 0.5 if self.scale_attn_by_inverse_layer_idx: scale_factor /= float(self.layer_idx + 1) # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk)) with torch.autocast(query.device.type, enabled=False): q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len) attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor) attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len) if not self.is_cross_attention: # if only "normal" attention layer implements causal mask query_length, key_length = query.size(-2), key.size(-2) causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length] mask_value = torch.finfo(attn_weights.dtype).min # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`. # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device` mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype, device=attn_weights.device) attn_weights = torch.where(causal_mask, attn_weights, mask_value) if attention_mask is not None: # Apply the attention mask attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise if attn_weights.dtype != torch.float32: raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32") attn_weights = attn_weights.type(value.dtype) attn_weights = self.attn_dropout(attn_weights) attn_output = torch.matmul(attn_weights, value) attn_output = attn_output.transpose(1, 2) return attn_output, attn_weights def forward( self, hidden_states: Optional[tuple[torch.FloatTensor]], past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = False, **kwargs, ) -> tuple[Union[torch.Tensor, tuple[torch.Tensor]], ...]: is_cross_attention = encoder_hidden_states is not None if past_key_values is not None: if isinstance(past_key_values, EncoderDecoderCache): is_updated = past_key_values.is_updated.get(self.layer_idx) if is_cross_attention: # after the first generated id, we can subsequently re-use all key/value_layer from cache curr_past_key_values = past_key_values.cross_attention_cache else: curr_past_key_values = past_key_values.self_attention_cache else: curr_past_key_values = past_key_values if is_cross_attention: if not hasattr(self, "q_attn"): raise ValueError( "If class is used as cross attention, the weights `q_attn` have to be defined. " "Please make sure to instantiate class with `DecisionTransformerGPT2Attention(..., is_cross_attention=True)`." ) query_states = self.q_attn(hidden_states) attention_mask = encoder_attention_mask # Try to get key/value states from cache if possible if past_key_values is not None and is_updated: key_states = curr_past_key_values.layers[self.layer_idx].keys value_states = curr_past_key_values.layers[self.layer_idx].values else: key_states, value_states = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2) shape_kv = (*key_states.shape[:-1], -1, self.head_dim) key_states = key_states.view(shape_kv).transpose(1, 2) value_states = value_states.view(shape_kv).transpose(1, 2) else: query_states, key_states, value_states = self.c_attn(hidden_states).split(self.split_size, dim=2) shape_kv = (*key_states.shape[:-1], -1, self.head_dim) key_states = key_states.view(shape_kv).transpose(1, 2) value_states = value_states.view(shape_kv).transpose(1, 2) shape_q = (*query_states.shape[:-1], -1, self.head_dim) query_states = query_states.view(shape_q).transpose(1, 2) if (past_key_values is not None and not is_cross_attention) or ( past_key_values is not None and is_cross_attention and not is_updated ): # save all key/value_layer to cache to be re-used for fast auto-regressive generation cache_position = cache_position if not is_cross_attention else None key_states, value_states = curr_past_key_values.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls if is_cross_attention: past_key_values.is_updated[self.layer_idx] = True using_eager = self.config._attn_implementation == "eager" attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] if using_eager and self.reorder_and_upcast_attn: attn_output, attn_weights = self._upcast_and_reordered_attn( query_states, key_states, value_states, attention_mask ) else: attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=self.attn_dropout.p if self.training else 0.0, **kwargs, ) attn_output = attn_output.reshape(*attn_output.shape[:-2], -1).contiguous() attn_output = self.c_proj(attn_output) attn_output = self.resid_dropout(attn_output) return attn_output, attn_weights # Copied from transformers.models.gpt2.modeling_gpt2.GPT2MLP with GPT2->DecisionTransformerGPT2
DecisionTransformerGPT2Attention
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/events.py
{ "start": 10575, "end": 13008 }
class ____(FileSystemEventHandler): """ Matches given patterns with file paths associated with occurring events. """ def __init__(self, patterns=None, ignore_patterns=None, ignore_directories=False, case_sensitive=False): super(PatternMatchingEventHandler, self).__init__() self._patterns = patterns self._ignore_patterns = ignore_patterns self._ignore_directories = ignore_directories self._case_sensitive = case_sensitive @property def patterns(self): """ (Read-only) Patterns to allow matching event paths. """ return self._patterns @property def ignore_patterns(self): """ (Read-only) Patterns to ignore matching event paths. """ return self._ignore_patterns @property def ignore_directories(self): """ (Read-only) ``True`` if directories should be ignored; ``False`` otherwise. """ return self._ignore_directories @property def case_sensitive(self): """ (Read-only) ``True`` if path names should be matched sensitive to case; ``False`` otherwise. """ return self._case_sensitive def dispatch(self, event): """Dispatches events to the appropriate methods. :param event: The event object representing the file system event. :type event: :class:`FileSystemEvent` """ if self.ignore_directories and event.is_directory: return paths = [] if has_attribute(event, 'dest_path'): paths.append(unicode_paths.decode(event.dest_path)) if event.src_path: paths.append(unicode_paths.decode(event.src_path)) if match_any_paths(paths, included_patterns=self.patterns, excluded_patterns=self.ignore_patterns, case_sensitive=self.case_sensitive): self.on_any_event(event) _method_map = { EVENT_TYPE_MODIFIED: self.on_modified, EVENT_TYPE_MOVED: self.on_moved, EVENT_TYPE_CREATED: self.on_created, EVENT_TYPE_DELETED: self.on_deleted, } event_type = event.event_type _method_map[event_type](event)
PatternMatchingEventHandler
python
kamyu104__LeetCode-Solutions
Python/contains-duplicate.py
{ "start": 29, "end": 189 }
class ____(object): # @param {integer[]} nums # @return {boolean} def containsDuplicate(self, nums): return len(nums) > len(set(nums))
Solution
python
huggingface__transformers
tests/models/fsmt/test_modeling_fsmt.py
{ "start": 20786, "end": 23700 }
class ____(unittest.TestCase): padding_idx = 1 tolerance = 1e-4 def test_basic(self): input_ids = torch.tensor([[4, 10]], dtype=torch.long, device=torch_device) emb1 = SinusoidalPositionalEmbedding(num_positions=6, embedding_dim=6, padding_idx=self.padding_idx).to( torch_device ) emb1.make_weight(*emb1.weight.shape, emb1.padding_idx) emb = emb1(input_ids) desired_weights = torch.tensor( [ [9.0930e-01, 1.9999e-02, 2.0000e-04, -4.1615e-01, 9.9980e-01, 1.0000e00], [1.4112e-01, 2.9995e-02, 3.0000e-04, -9.8999e-01, 9.9955e-01, 1.0000e00], ] ).to(torch_device) self.assertTrue( torch.allclose(emb[0], desired_weights, atol=self.tolerance), msg=f"\nexp:\n{desired_weights}\ngot:\n{emb[0]}\n", ) def test_odd_embed_dim(self): # odd embedding_dim is allowed test = SinusoidalPositionalEmbedding(num_positions=4, embedding_dim=5, padding_idx=self.padding_idx).to( torch_device ) test.make_weight(*test.weight.shape, test.padding_idx) # odd num_embeddings is allowed test = SinusoidalPositionalEmbedding(num_positions=5, embedding_dim=4, padding_idx=self.padding_idx).to( torch_device ) test.make_weight(*test.weight.shape, test.padding_idx) @unittest.skip(reason="different from marian (needs more research)") def test_positional_emb_weights_against_marian(self): desired_weights = torch.tensor( [ [0, 0, 0, 0, 0], [0.84147096, 0.82177866, 0.80180490, 0.78165019, 0.76140374], [0.90929741, 0.93651021, 0.95829457, 0.97505713, 0.98720258], ] ) emb1 = SinusoidalPositionalEmbedding(num_positions=512, embedding_dim=512, padding_idx=self.padding_idx).to( torch_device ) emb1.make_weight(*emb1.weight.shape, emb1.padding_idx) weights = emb1.weights.data[:3, :5] # XXX: only the 1st and 3rd lines match - this is testing against # verbatim copy of SinusoidalPositionalEmbedding from fairseq self.assertTrue( torch.allclose(weights, desired_weights, atol=self.tolerance), msg=f"\nexp:\n{desired_weights}\ngot:\n{weights}\n", ) # test that forward pass is just a lookup, there is no ignore padding logic input_ids = torch.tensor( [[4, 10, self.padding_idx, self.padding_idx, self.padding_idx]], dtype=torch.long, device=torch_device ) no_cache_pad_zero = emb1(input_ids)[0] # XXX: only the 1st line matches the 3rd torch.testing.assert_close( torch.tensor(desired_weights, device=torch_device), no_cache_pad_zero[:3, :5], rtol=1e-3, atol=1e-3 )
TestSinusoidalPositionalEmbeddings
python
realpython__materials
python-maze-solver/source_code_final/src/maze_solver/models/border.py
{ "start": 33, "end": 539 }
class ____(IntFlag): EMPTY = 0 TOP = auto() BOTTOM = auto() LEFT = auto() RIGHT = auto() @property def corner(self) -> bool: return self in ( self.TOP | self.LEFT, self.TOP | self.RIGHT, self.BOTTOM | self.LEFT, self.BOTTOM | self.RIGHT, ) @property def dead_end(self) -> bool: return self.bit_count() == 3 @property def intersection(self) -> bool: return self.bit_count() < 2
Border
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 312894, "end": 314039 }
class ____(StatNode): child_attrs = [] is_terminator = True def analyse_expressions(self, env): return self nogil_check = Node.gil_error gil_message = "Raising exception" def generate_execution_code(self, code): code.mark_pos(self.pos) vars = code.funcstate.exc_vars if vars: code.globalstate.use_utility_code(restore_exception_utility_code) code.put_giveref(vars[0], py_object_type) code.put_giveref(vars[1], py_object_type) # fresh exceptions may not have a traceback yet (-> finally!) code.put_xgiveref(vars[2], py_object_type) code.putln("__Pyx_ErrRestoreWithState(%s, %s, %s);" % tuple(vars)) code.putln(" ".join([f"{varname} = 0; " for varname in vars])) else: code.globalstate.use_utility_code( UtilityCode.load_cached("ReRaiseException", "Exceptions.c")) code.putln("__Pyx_ReraiseException();") if code.is_tracing(): code.put_trace_exception(self.pos, reraise=True) code.putln(code.error_goto(self.pos))
ReraiseStatNode
python
ray-project__ray
python/ray/air/config.py
{ "start": 14472, "end": 21131 }
class ____: """Configurable parameters for defining the checkpointing strategy. Default behavior is to persist all checkpoints to disk. If ``num_to_keep`` is set, the default retention policy is to keep the checkpoints with maximum timestamp, i.e. the most recent checkpoints. Args: num_to_keep: The number of checkpoints to keep on disk for this run. If a checkpoint is persisted to disk after there are already this many checkpoints, then an existing checkpoint will be deleted. If this is ``None`` then checkpoints will not be deleted. Must be >= 1. checkpoint_score_attribute: The attribute that will be used to score checkpoints to determine which checkpoints should be kept on disk when there are greater than ``num_to_keep`` checkpoints. This attribute must be a key from the checkpoint dictionary which has a numerical value. Per default, the last checkpoints will be kept. checkpoint_score_order: Either "max" or "min". If "max", then checkpoints with highest values of ``checkpoint_score_attribute`` will be kept. If "min", then checkpoints with lowest values of ``checkpoint_score_attribute`` will be kept. checkpoint_frequency: Number of iterations between checkpoints. If 0 this will disable checkpointing. Please note that most trainers will still save one checkpoint at the end of training. This attribute is only supported by trainers that don't take in custom training loops. checkpoint_at_end: If True, will save a checkpoint at the end of training. This attribute is only supported by trainers that don't take in custom training loops. Defaults to True for trainers that support it and False for generic function trainables. _checkpoint_keep_all_ranks: This experimental config is deprecated. This behavior is now controlled by reporting `checkpoint=None` in the workers that shouldn't persist a checkpoint. For example, if you only want the rank 0 worker to persist a checkpoint (e.g., in standard data parallel training), then you should save and report a checkpoint if `ray.train.get_context().get_world_rank() == 0` and `None` otherwise. _checkpoint_upload_from_workers: This experimental config is deprecated. Uploading checkpoint directly from the worker is now the default behavior. """ num_to_keep: Optional[int] = None checkpoint_score_attribute: Optional[str] = None checkpoint_score_order: Optional[str] = MAX checkpoint_frequency: Optional[int] = 0 checkpoint_at_end: Optional[bool] = None _checkpoint_keep_all_ranks: Optional[bool] = _DEPRECATED_VALUE _checkpoint_upload_from_workers: Optional[bool] = _DEPRECATED_VALUE def __post_init__(self): if self._checkpoint_keep_all_ranks != _DEPRECATED_VALUE: raise DeprecationWarning( "The experimental `_checkpoint_keep_all_ranks` config is deprecated. " "This behavior is now controlled by reporting `checkpoint=None` " "in the workers that shouldn't persist a checkpoint. " "For example, if you only want the rank 0 worker to persist a " "checkpoint (e.g., in standard data parallel training), " "then you should save and report a checkpoint if " "`ray.train.get_context().get_world_rank() == 0` " "and `None` otherwise." ) if self._checkpoint_upload_from_workers != _DEPRECATED_VALUE: raise DeprecationWarning( "The experimental `_checkpoint_upload_from_workers` config is " "deprecated. Uploading checkpoint directly from the worker is " "now the default behavior." ) if self.num_to_keep is not None and self.num_to_keep <= 0: raise ValueError( f"Received invalid num_to_keep: " f"{self.num_to_keep}. " f"Must be None or an integer >= 1." ) if self.checkpoint_score_order not in (MAX, MIN): raise ValueError( f"checkpoint_score_order must be either " f'"{MAX}" or "{MIN}".' ) if self.checkpoint_frequency < 0: raise ValueError( f"checkpoint_frequency must be >=0, got {self.checkpoint_frequency}" ) def __repr__(self): return _repr_dataclass(self) def _repr_html_(self) -> str: if self.num_to_keep is None: num_to_keep_repr = "All" else: num_to_keep_repr = self.num_to_keep if self.checkpoint_score_attribute is None: checkpoint_score_attribute_repr = "Most recent" else: checkpoint_score_attribute_repr = self.checkpoint_score_attribute if self.checkpoint_at_end is None: checkpoint_at_end_repr = "" else: checkpoint_at_end_repr = self.checkpoint_at_end return Template("scrollableTable.html.j2").render( table=tabulate( { "Setting": [ "Number of checkpoints to keep", "Checkpoint score attribute", "Checkpoint score order", "Checkpoint frequency", "Checkpoint at end", ], "Value": [ num_to_keep_repr, checkpoint_score_attribute_repr, self.checkpoint_score_order, self.checkpoint_frequency, checkpoint_at_end_repr, ], }, tablefmt="html", showindex=False, headers="keys", ), max_height="none", ) @property def _tune_legacy_checkpoint_score_attr(self) -> Optional[str]: """Same as ``checkpoint_score_attr`` in ``tune.run``. Only used for Legacy API compatibility. """ if self.checkpoint_score_attribute is None: return self.checkpoint_score_attribute prefix = "" if self.checkpoint_score_order == MIN: prefix = "min-" return f"{prefix}{self.checkpoint_score_attribute}" @dataclass @PublicAPI(stability="stable")
CheckpointConfig
python
tornadoweb__tornado
tornado/test/ioloop_test.py
{ "start": 807, "end": 16180 }
class ____(AsyncTestCase): def test_add_callback_return_sequence(self): # A callback returning {} or [] shouldn't spin the CPU, see Issue #1803. self.calls = 0 loop = self.io_loop test = self old_add_callback = loop.add_callback def add_callback(self, callback, *args, **kwargs): test.calls += 1 old_add_callback(callback, *args, **kwargs) loop.add_callback = types.MethodType(add_callback, loop) # type: ignore loop.add_callback(lambda: {}) # type: ignore loop.add_callback(lambda: []) # type: ignore loop.add_timeout(datetime.timedelta(milliseconds=50), loop.stop) loop.start() self.assertLess(self.calls, 10) def test_add_callback_wakeup(self): # Make sure that add_callback from inside a running IOLoop # wakes up the IOLoop immediately instead of waiting for a timeout. def callback(): self.called = True self.stop() def schedule_callback(): self.called = False self.io_loop.add_callback(callback) # Store away the time so we can check if we woke up immediately self.start_time = time.time() self.io_loop.add_timeout(self.io_loop.time(), schedule_callback) self.wait() self.assertAlmostEqual(time.time(), self.start_time, places=2) self.assertTrue(self.called) def test_add_callback_wakeup_other_thread(self): def target(): # sleep a bit to let the ioloop go into its poll loop time.sleep(0.01) self.stop_time = time.time() self.io_loop.add_callback(self.stop) thread = threading.Thread(target=target) self.io_loop.add_callback(thread.start) self.wait() delta = time.time() - self.stop_time self.assertLess(delta, 0.1) thread.join() def test_add_timeout_timedelta(self): self.io_loop.add_timeout(datetime.timedelta(microseconds=1), self.stop) self.wait() def test_multiple_add(self): sock, port = bind_unused_port() try: self.io_loop.add_handler( sock.fileno(), lambda fd, events: None, IOLoop.READ ) # Attempting to add the same handler twice fails # (with a platform-dependent exception) self.assertRaises( Exception, self.io_loop.add_handler, sock.fileno(), lambda fd, events: None, IOLoop.READ, ) finally: self.io_loop.remove_handler(sock.fileno()) sock.close() def test_remove_without_add(self): # remove_handler should not throw an exception if called on an fd # was never added. sock, port = bind_unused_port() try: self.io_loop.remove_handler(sock.fileno()) finally: sock.close() def test_add_callback_from_signal(self): # cheat a little bit and just run this normally, since we can't # easily simulate the races that happen with real signal handlers with ignore_deprecation(): self.io_loop.add_callback_from_signal(self.stop) self.wait() def test_add_callback_from_signal_other_thread(self): # Very crude test, just to make sure that we cover this case. # This also happens to be the first test where we run an IOLoop in # a non-main thread. other_ioloop = IOLoop(make_current=False) thread = threading.Thread(target=other_ioloop.start) thread.start() with ignore_deprecation(): other_ioloop.add_callback_from_signal(other_ioloop.stop) thread.join() other_ioloop.close() def test_add_callback_while_closing(self): # add_callback should not fail if it races with another thread # closing the IOLoop. The callbacks are dropped silently # without executing. closing = threading.Event() def target(): other_ioloop.add_callback(other_ioloop.stop) other_ioloop.start() closing.set() other_ioloop.close(all_fds=True) other_ioloop = IOLoop(make_current=False) thread = threading.Thread(target=target) thread.start() closing.wait() for i in range(1000): other_ioloop.add_callback(lambda: None) @skipIfNonUnix # just because socketpair is so convenient def test_read_while_writeable(self): # Ensure that write events don't come in while we're waiting for # a read and haven't asked for writeability. (the reverse is # difficult to test for) client, server = socket.socketpair() try: def handler(fd, events): self.assertEqual(events, IOLoop.READ) self.stop() self.io_loop.add_handler(client.fileno(), handler, IOLoop.READ) self.io_loop.add_timeout( self.io_loop.time() + 0.01, functools.partial(server.send, b"asdf") ) self.wait() self.io_loop.remove_handler(client.fileno()) finally: client.close() server.close() def test_remove_timeout_after_fire(self): # It is not an error to call remove_timeout after it has run. handle = self.io_loop.add_timeout(self.io_loop.time(), self.stop) self.wait() self.io_loop.remove_timeout(handle) def test_remove_timeout_cleanup(self): # Add and remove enough callbacks to trigger cleanup. # Not a very thorough test, but it ensures that the cleanup code # gets executed and doesn't blow up. This test is only really useful # on PollIOLoop subclasses, but it should run silently on any # implementation. for i in range(2000): timeout = self.io_loop.add_timeout(self.io_loop.time() + 3600, lambda: None) self.io_loop.remove_timeout(timeout) # HACK: wait two IOLoop iterations for the GC to happen. self.io_loop.add_callback(lambda: self.io_loop.add_callback(self.stop)) self.wait() def test_remove_timeout_from_timeout(self): calls = [False, False] # Schedule several callbacks and wait for them all to come due at once. # t2 should be cancelled by t1, even though it is already scheduled to # be run before the ioloop even looks at it. now = self.io_loop.time() def t1(): calls[0] = True self.io_loop.remove_timeout(t2_handle) self.io_loop.add_timeout(now + 0.01, t1) def t2(): calls[1] = True t2_handle = self.io_loop.add_timeout(now + 0.02, t2) self.io_loop.add_timeout(now + 0.03, self.stop) time.sleep(0.03) self.wait() self.assertEqual(calls, [True, False]) def test_timeout_with_arguments(self): # This tests that all the timeout methods pass through *args correctly. results = [] # type: List[int] self.io_loop.add_timeout(self.io_loop.time(), results.append, 1) self.io_loop.add_timeout(datetime.timedelta(seconds=0), results.append, 2) self.io_loop.call_at(self.io_loop.time(), results.append, 3) self.io_loop.call_later(0, results.append, 4) self.io_loop.call_later(0, self.stop) self.wait() # The asyncio event loop does not guarantee the order of these # callbacks. self.assertEqual(sorted(results), [1, 2, 3, 4]) def test_add_timeout_return(self): # All the timeout methods return non-None handles that can be # passed to remove_timeout. handle = self.io_loop.add_timeout(self.io_loop.time(), lambda: None) self.assertIsNotNone(handle) self.io_loop.remove_timeout(handle) def test_call_at_return(self): handle = self.io_loop.call_at(self.io_loop.time(), lambda: None) self.assertIsNotNone(handle) self.io_loop.remove_timeout(handle) def test_call_later_return(self): handle = self.io_loop.call_later(0, lambda: None) self.assertIsNotNone(handle) self.io_loop.remove_timeout(handle) def test_close_file_object(self): """When a file object is used instead of a numeric file descriptor, the object should be closed (by IOLoop.close(all_fds=True), not just the fd. """ # Use a socket since they are supported by IOLoop on all platforms. # Unfortunately, sockets don't support the .closed attribute for # inspecting their close status, so we must use a wrapper. class SocketWrapper: def __init__(self, sockobj): self.sockobj = sockobj self.closed = False def fileno(self): return self.sockobj.fileno() def close(self): self.closed = True self.sockobj.close() sockobj, port = bind_unused_port() socket_wrapper = SocketWrapper(sockobj) io_loop = IOLoop(make_current=False) io_loop.run_sync( lambda: io_loop.add_handler( socket_wrapper, lambda fd, events: None, IOLoop.READ ) ) io_loop.close(all_fds=True) self.assertTrue(socket_wrapper.closed) def test_handler_callback_file_object(self): """The handler callback receives the same fd object it passed in.""" server_sock, port = bind_unused_port() fds = [] def handle_connection(fd, events): fds.append(fd) conn, addr = server_sock.accept() conn.close() self.stop() self.io_loop.add_handler(server_sock, handle_connection, IOLoop.READ) with contextlib.closing(socket.socket()) as client_sock: client_sock.connect(("127.0.0.1", port)) self.wait() self.io_loop.remove_handler(server_sock) self.io_loop.add_handler(server_sock.fileno(), handle_connection, IOLoop.READ) with contextlib.closing(socket.socket()) as client_sock: client_sock.connect(("127.0.0.1", port)) self.wait() self.assertIs(fds[0], server_sock) self.assertEqual(fds[1], server_sock.fileno()) self.io_loop.remove_handler(server_sock.fileno()) server_sock.close() def test_mixed_fd_fileobj(self): server_sock, port = bind_unused_port() def f(fd, events): pass self.io_loop.add_handler(server_sock, f, IOLoop.READ) with self.assertRaises(Exception): # The exact error is unspecified - some implementations use # IOError, others use ValueError. self.io_loop.add_handler(server_sock.fileno(), f, IOLoop.READ) self.io_loop.remove_handler(server_sock.fileno()) server_sock.close() def test_reentrant(self): """Calling start() twice should raise an error, not deadlock.""" returned_from_start = [False] got_exception = [False] def callback(): try: self.io_loop.start() returned_from_start[0] = True except Exception: got_exception[0] = True self.stop() self.io_loop.add_callback(callback) self.wait() self.assertTrue(got_exception[0]) self.assertFalse(returned_from_start[0]) def test_exception_logging(self): """Uncaught exceptions get logged by the IOLoop.""" self.io_loop.add_callback(lambda: 1 / 0) self.io_loop.add_callback(self.stop) with ExpectLog(app_log, "Exception in callback"): self.wait() def test_exception_logging_future(self): """The IOLoop examines exceptions from Futures and logs them.""" @gen.coroutine def callback(): self.io_loop.add_callback(self.stop) 1 / 0 self.io_loop.add_callback(callback) with ExpectLog(app_log, "Exception in callback"): self.wait() def test_exception_logging_native_coro(self): """The IOLoop examines exceptions from awaitables and logs them.""" async def callback(): # Stop the IOLoop two iterations after raising an exception # to give the exception time to be logged. self.io_loop.add_callback(self.io_loop.add_callback, self.stop) 1 / 0 self.io_loop.add_callback(callback) with ExpectLog(app_log, "Exception in callback"): self.wait() def test_spawn_callback(self): # Both add_callback and spawn_callback run directly on the IOLoop, # so their errors are logged without stopping the test. self.io_loop.add_callback(lambda: 1 / 0) self.io_loop.add_callback(self.stop) with ExpectLog(app_log, "Exception in callback"): self.wait() # A spawned callback is run directly on the IOLoop, so it will be # logged without stopping the test. self.io_loop.spawn_callback(lambda: 1 / 0) self.io_loop.add_callback(self.stop) with ExpectLog(app_log, "Exception in callback"): self.wait() @skipIfNonUnix def test_remove_handler_from_handler(self): # Create two sockets with simultaneous read events. client, server = socket.socketpair() try: client.send(b"abc") server.send(b"abc") # After reading from one fd, remove the other from the IOLoop. chunks = [] def handle_read(fd, events): chunks.append(fd.recv(1024)) if fd is client: self.io_loop.remove_handler(server) else: self.io_loop.remove_handler(client) self.io_loop.add_handler(client, handle_read, self.io_loop.READ) self.io_loop.add_handler(server, handle_read, self.io_loop.READ) self.io_loop.call_later(0.1, self.stop) self.wait() # Only one fd was read; the other was cleanly removed. self.assertEqual(chunks, [b"abc"]) finally: client.close() server.close() @skipIfNonUnix @gen_test def test_init_close_race(self): # Regression test for #2367 # # Skipped on windows because of what looks like a bug in the # proactor event loop when started and stopped on non-main # threads. def f(): for i in range(10): loop = IOLoop(make_current=False) loop.close() yield gen.multi([self.io_loop.run_in_executor(None, f) for i in range(2)]) def test_explicit_asyncio_loop(self): asyncio_loop = asyncio.new_event_loop() loop = IOLoop(asyncio_loop=asyncio_loop, make_current=False) assert loop.asyncio_loop is asyncio_loop # type: ignore with self.assertRaises(RuntimeError): # Can't register two IOLoops with the same asyncio_loop IOLoop(asyncio_loop=asyncio_loop, make_current=False) loop.close() # Deliberately not a subclass of AsyncTestCase so the IOLoop isn't # automatically set as current.
TestIOLoop
python
langchain-ai__langchain
libs/core/langchain_core/example_selectors/base.py
{ "start": 178, "end": 1716 }
class ____(ABC): """Interface for selecting examples to include in prompts.""" @abstractmethod def add_example(self, example: dict[str, str]) -> Any: """Add new example to store. Args: example: A dictionary with keys as input variables and values as their values. Returns: Any return value. """ async def aadd_example(self, example: dict[str, str]) -> Any: """Async add new example to store. Args: example: A dictionary with keys as input variables and values as their values. Returns: Any return value. """ return await run_in_executor(None, self.add_example, example) @abstractmethod def select_examples(self, input_variables: dict[str, str]) -> list[dict]: """Select which examples to use based on the inputs. Args: input_variables: A dictionary with keys as input variables and values as their values. Returns: A list of examples. """ async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]: """Async select which examples to use based on the inputs. Args: input_variables: A dictionary with keys as input variables and values as their values. Returns: A list of examples. """ return await run_in_executor(None, self.select_examples, input_variables)
BaseExampleSelector
python
spulec__freezegun
tests/test_warnings.py
{ "start": 139, "end": 2895 }
class ____: """ A module that triggers warnings on attribute access. This does not happen with regular modules, there has to be a bit of lazy module magic going on in order for this to happen. Examples of modules that uses this pattern in real projects can be found at: py.code - the compiler package import causes a warning to be emitted: https://github.com/pytest-dev/py/blob/67987e26aadddbbe7d1ec76c16ea9be346ae9811/py/__init__.py https://github.com/pytest-dev/py/blob/67987e26aadddbbe7d1ec76c16ea9be346ae9811/py/_code/_assertionold.py#L3 celery.task - the sets module is listed in __all__ in celery.task and freeze_time accesses it: https://github.com/celery/celery/blob/46c92025cdec07a4a30ad44901cf66cb27346638/celery/task/__init__.py https://github.com/celery/celery/blob/46c92025cdec07a4a30ad44901cf66cb27346638/celery/task/sets.py """ __name__ = 'module_with_warning' __dict__ = {} warning_triggered = False counter = 0 @property def attribute_that_emits_a_warning(self) -> None: # Use unique warning messages to avoid messages being only reported once self.__class__.counter += 1 warnings.warn(f'this is test warning #{self.__class__.counter}') self.warning_triggered = True @contextlib.contextmanager def assert_module_with_emitted_warning() -> Iterator[None]: """Install a module that triggers warnings into sys.modules and ensure the warning was triggered in the with-block. """ module = sys.modules['module_with_warning'] = ModuleWithWarning() # type: ignore try: yield finally: del sys.modules['module_with_warning'] assert module.warning_triggered @contextlib.contextmanager def assert_no_warnings() -> Iterator[None]: """A context manager that makes sure no warnings was emitted.""" with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings('always') yield assert not caught_warnings def test_ignore_warnings_in_start() -> None: """Make sure that modules being introspected in start() does not emit warnings.""" with assert_module_with_emitted_warning(): freezer = freeze_time(datetime.datetime(2016, 10, 27, 9, 56)) try: with assert_no_warnings(): freezer.start() finally: freezer.stop() def test_ignore_warnings_in_stop() -> None: """Make sure that modules that was loaded after start() does not trigger warnings in stop()""" freezer = freeze_time(datetime.datetime(2016, 10, 27, 9, 56)) freezer.start() with assert_module_with_emitted_warning(): with assert_no_warnings(): freezer.stop()
ModuleWithWarning
python
lxml__lxml
src/lxml/html/diff.py
{ "start": 21747, "end": 32304 }
class ____(token): """ Represents the href in an anchor tag. Unlike other words, we only show the href when it changes. """ hide_when_equal = True def html(self): return ' Link: %s' % self def tokenize(html, include_hrefs=True): """ Parse the given HTML and returns token objects (words with attached tags). This parses only the content of a page; anything in the head is ignored, and the <head> and <body> elements are themselves optional. The content is then parsed by lxml, which ensures the validity of the resulting parsed document (though lxml may make incorrect guesses when the markup is particular bad). <ins> and <del> tags are also eliminated from the document, as that gets confusing. If include_hrefs is true, then the href attribute of <a> tags is included as a special kind of diffable token.""" if etree.iselement(html): body_el = html else: body_el = parse_html(html, cleanup=True) # Then we split the document into text chunks for each tag, word, and end tag: chunks = flatten_el(body_el, skip_tag=True, include_hrefs=include_hrefs) # Finally re-joining them into token objects: return fixup_chunks(chunks) def parse_html(html, cleanup=True): """ Parses an HTML fragment, returning an lxml element. Note that the HTML will be wrapped in a <div> tag that was not in the original document. If cleanup is true, make sure there's no <head> or <body>, and get rid of any <ins> and <del> tags. """ if cleanup: # This removes any extra markup or structure like <head>: html = cleanup_html(html) return fragment_fromstring(html, create_parent=True) _search_body = re.compile(r'<body.*?>', re.I|re.S).search _search_end_body = re.compile(r'</body.*?>', re.I|re.S).search _replace_ins_del = re.compile(r'</?(ins|del).*?>', re.I|re.S).sub def cleanup_html(html): """ This 'cleans' the HTML, meaning that any page structure is removed (only the contents of <body> are used, if there is any <body). Also <ins> and <del> tags are removed. """ match = _search_body(html) if match: html = html[match.end():] match = _search_end_body(html) if match: html = html[:match.start()] html = _replace_ins_del('', html) return html def split_trailing_whitespace(word): """ This function takes a word, such as 'test\n\n' and returns ('test','\n\n') """ stripped_length = len(word.rstrip()) return word[0:stripped_length], word[stripped_length:] def fixup_chunks(chunks): """ This function takes a list of chunks and produces a list of tokens. """ tag_accum = [] cur_word = None result = [] for chunk in chunks: if isinstance(chunk, tuple): if chunk[0] == 'img': src = chunk[1] tag, trailing_whitespace = split_trailing_whitespace(chunk[2]) cur_word = tag_token('img', src, html_repr=tag, pre_tags=tag_accum, trailing_whitespace=trailing_whitespace) tag_accum = [] result.append(cur_word) elif chunk[0] == 'href': href = chunk[1] cur_word = href_token(href, pre_tags=tag_accum, trailing_whitespace=" ") tag_accum = [] result.append(cur_word) continue if is_word(chunk): chunk, trailing_whitespace = split_trailing_whitespace(chunk) cur_word = token(chunk, pre_tags=tag_accum, trailing_whitespace=trailing_whitespace) tag_accum = [] result.append(cur_word) elif is_start_tag(chunk): tag_accum.append(chunk) elif is_end_tag(chunk): if tag_accum: tag_accum.append(chunk) else: assert cur_word, ( "Weird state, cur_word=%r, result=%r, chunks=%r of %r" % (cur_word, result, chunk, chunks)) cur_word.post_tags.append(chunk) else: assert False if not result: return [token('', pre_tags=tag_accum)] else: result[-1].post_tags.extend(tag_accum) return result # All the tags in HTML that don't require end tags: empty_tags = cython.declare(frozenset, defs.empty_tags) block_level_tags = cython.declare(frozenset, frozenset([ 'address', 'blockquote', 'center', 'dir', 'div', 'dl', 'fieldset', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'isindex', 'menu', 'noframes', 'noscript', 'ol', 'p', 'pre', 'table', 'ul', ])) block_level_container_tags = cython.declare(frozenset, frozenset([ 'dd', 'dt', 'frameset', 'li', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', ])) any_block_level_tag = cython.declare(tuple, tuple(sorted( block_level_tags | block_level_container_tags)) ) def flatten_el(el, include_hrefs, skip_tag=False): """ Takes an lxml element el, and generates all the text chunks for that tag. Each start tag is a chunk, each word is a chunk, and each end tag is a chunk. If skip_tag is true, then the outermost container tag is not returned (just its contents).""" if not skip_tag: if el.tag == 'img': yield ('img', el.get('src'), start_tag(el)) else: yield start_tag(el) if el.tag in empty_tags and not el.text and not len(el) and not el.tail: return start_words = split_words(el.text) for word in start_words: yield html_escape(word) for child in el: yield from flatten_el(child, include_hrefs=include_hrefs) if el.tag == 'a' and el.get('href') and include_hrefs: yield ('href', el.get('href')) if not skip_tag: yield end_tag(el) end_words = split_words(el.tail) for word in end_words: yield html_escape(word) _find_words = re.compile(r'\S+(?:\s+|$)', re.U).findall def split_words(text): """ Splits some text into words. Includes trailing whitespace on each word when appropriate. """ if not text or not text.strip(): return [] words = _find_words(text) return words _has_start_whitespace = re.compile(r'^[ \t\n\r]').match def start_tag(el): """ The text representation of the start tag for a tag. """ attributes = ''.join([ f' {name}="{html_escape(value)}"' for name, value in el.attrib.items() ]) return f'<{el.tag}{attributes}>' def end_tag(el): """ The text representation of an end tag for a tag. Includes trailing whitespace when appropriate. """ tail = el.tail extra = ' ' if tail and _has_start_whitespace(tail) else '' return f'</{el.tag}>{extra}' def is_word(tok): return not tok.startswith('<') def is_end_tag(tok): return tok.startswith('</') def is_start_tag(tok): return tok.startswith('<') and not tok.startswith('</') def fixup_ins_del_tags(html): """ Given an html string, move any <ins> or <del> tags inside of any block-level elements, e.g. transform <ins><p>word</p></ins> to <p><ins>word</ins></p> """ doc = parse_html(html, cleanup=False) _fixup_ins_del_tags(doc) html = serialize_html_fragment(doc, skip_outer=True) return html def serialize_html_fragment(el, skip_outer=False): """ Serialize a single lxml element as HTML. The serialized form includes the elements tail. If skip_outer is true, then don't serialize the outermost tag """ assert not isinstance(el, str), ( f"You should pass in an element, not a string like {el!r}") html = etree.tostring(el, method="html", encoding='unicode') if skip_outer: # Get rid of the extra starting tag: html = html[html.find('>')+1:] # Get rid of the extra end tag: html = html[:html.rfind('<')] return html.strip() else: return html @cython.cfunc def _fixup_ins_del_tags(doc): """fixup_ins_del_tags that works on an lxml document in-place """ for el in list(doc.iter('ins', 'del')): if not _contains_block_level_tag(el): continue _move_el_inside_block(el, tag=el.tag) el.drop_tag() #_merge_element_contents(el) @cython.cfunc def _contains_block_level_tag(el): """True if the element contains any block-level elements, like <p>, <td>, etc. """ for el in el.iter(*any_block_level_tag): return True return False @cython.cfunc def _move_el_inside_block(el, tag): """ helper for _fixup_ins_del_tags; actually takes the <ins> etc tags and moves them inside any block-level tags. """ makeelement = el.makeelement for block_level_el in el.iter(*any_block_level_tag): if block_level_el is not el: break else: # No block-level tags in any child children_tag = makeelement(tag) children_tag.text = el.text el.text = None children_tag.extend(iter(el)) el[:] = [children_tag] return for child in list(el): if _contains_block_level_tag(child): _move_el_inside_block(child, tag) if child.tail: tail_tag = makeelement(tag) tail_tag.text = child.tail child.tail = None child.addnext(tail_tag) else: child_tag = makeelement(tag) el.replace(child, child_tag) child_tag.append(child) if el.text: text_tag = makeelement(tag) text_tag.text = el.text el.text = None el.insert(0, text_tag) def _merge_element_contents(el): """ Removes an element, but merges its contents into its place, e.g., given <p>Hi <i>there!</i></p>, if you remove the <i> element you get <p>Hi there!</p> """ parent = el.getparent() text = el.text tail = el.tail if tail: if not len(el): text = (text or '') + tail else: el[-1].tail = (el[-1].tail or '') + tail index = parent.index(el) if text: previous = el.getprevious() if previous is None: parent.text = (parent.text or '') + text else: previous.tail = (previous.tail or '') + text parent[index:index+1] = el.getchildren() @cython.final @cython.cclass
href_token
python
pytorch__pytorch
test/distributed/test_c10d_gloo.py
{ "start": 7542, "end": 7759 }
class ____(test_c10d_common.AbstractTimeoutTest, TestCase): @requires_gloo() @retry_on_connect_failures def test_default_store_timeout_gloo(self): self._test_default_store_timeout("gloo")
TimeoutTest
python
walkccc__LeetCode
solutions/2976. Minimum Cost to Convert String I/2976.py
{ "start": 0, "end": 891 }
class ____: def minimumCost( self, source: str, target: str, original: list[str], changed: list[str], cost: list[int], ) -> int: ans = 0 # dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v) dist = [[math.inf] * 26 for _ in range(26)] for a, b, c in zip(original, changed, cost): u = ord(a) - ord('a') v = ord(b) - ord('a') dist[u][v] = min(dist[u][v], c) for k in range(26): for i in range(26): if dist[i][k] < math.inf: for j in range(26): if dist[k][j] < math.inf: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for s, t in zip(source, target): if s == t: continue u = ord(s) - ord('a') v = ord(t) - ord('a') if dist[u][v] == math.inf: return -1 ans += dist[u][v] return ans
Solution
python
huggingface__transformers
tests/models/esm/test_modeling_esmfold.py
{ "start": 1151, "end": 6105 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=False, use_input_mask=True, use_token_type_ids=False, use_labels=False, vocab_size=19, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, 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, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size 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 def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): esmfold_config = { "trunk": { "num_blocks": 2, "sequence_state_dim": 64, "pairwise_state_dim": 16, "sequence_head_width": 4, "pairwise_head_width": 4, "position_bins": 4, "chunk_size": 16, "structure_module": { "ipa_dim": 16, "num_angles": 7, "num_blocks": 2, "num_heads_ipa": 4, "pairwise_dim": 16, "resnet_dim": 16, "sequence_dim": 48, }, }, "fp16_esm": False, "lddt_head_hid_dim": 16, } config = EsmConfig( vocab_size=33, hidden_size=self.hidden_size, pad_token_id=1, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.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, initializer_range=self.initializer_range, is_folding_model=True, esmfold_config=esmfold_config, ) return config def create_and_check_model(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels): model = EsmForProteinFolding(config=config).float() model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask) result = model(input_ids) result = model(input_ids) self.parent.assertEqual(result.positions.shape, (2, self.batch_size, self.seq_length, 14, 3)) self.parent.assertEqual(result.angles.shape, (2, self.batch_size, self.seq_length, 7, 2)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
EsmFoldModelTester
python
keras-team__keras
guides/functional_api.py
{ "start": 22211, "end": 25135 }
class ____(keras.Model): def __init__(self, **kwargs): super().__init__(**kwargs) self.dense_1 = layers.Dense(64, activation='relu') self.dense_2 = layers.Dense(10) def call(self, inputs): x = self.dense_1(inputs) return self.dense_2(x) # Instantiate the model. mlp = MLP() # Necessary to create the model's state. # The model doesn't have a state until it's called at least once. _ = mlp(ops.zeros((1, 32))) ``` #### Model validation while defining its connectivity graph In the functional API, the input specification (shape and dtype) is created in advance (using `Input`). Every time you call a layer, the layer checks that the specification passed to it matches its assumptions, and it will raise a helpful error message if not. This guarantees that any model you can build with the functional API will run. All debugging -- other than convergence-related debugging -- happens statically during the model construction and not at execution time. This is similar to type checking in a compiler. #### A functional model is plottable and inspectable You can plot the model as a graph, and you can easily access intermediate nodes in this graph. For example, to extract and reuse the activations of intermediate layers (as seen in a previous example): ```python features_list = [layer.output for layer in vgg19.layers] feat_extraction_model = keras.Model(inputs=vgg19.input, outputs=features_list) ``` #### A functional model can be serialized or cloned Because a functional model is a data structure rather than a piece of code, it is safely serializable and can be saved as a single file that allows you to recreate the exact same model without having access to any of the original code. See the [serialization & saving guide](/guides/serialization_and_saving/). To serialize a subclassed model, it is necessary for the implementer to specify a `get_config()` and `from_config()` method at the model level. ### Functional API weakness: #### It does not support dynamic architectures The functional API treats models as DAGs of layers. This is true for most deep learning architectures, but not all -- for example, recursive networks or Tree RNNs do not follow this assumption and cannot be implemented in the functional API. """ """ ## Mix-and-match API styles Choosing between the functional API or Model subclassing isn't a binary decision that restricts you into one category of models. All models in the `keras` API can interact with each other, whether they're `Sequential` models, functional models, or subclassed models that are written from scratch. You can always use a functional model or `Sequential` model as part of a subclassed model or layer: """ units = 32 timesteps = 10 input_dim = 5 # Define a Functional model inputs = keras.Input((None, units)) x = layers.GlobalAveragePooling1D()(inputs) outputs = layers.Dense(1)(x) model = keras.Model(inputs, outputs)
MLP
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 91961, "end": 92474 }
class ____: def test_log1p(self): assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) assert_almost_equal(ncu.log1p(1e-6), ncu.log(1 + 1e-6)) def test_special(self): with np.errstate(invalid="ignore", divide="ignore"): assert_equal(ncu.log1p(np.nan), np.nan) assert_equal(ncu.log1p(np.inf), np.inf) assert_equal(ncu.log1p(-1.), -np.inf) assert_equal(ncu.log1p(-2.), np.nan) assert_equal(ncu.log1p(-np.inf), np.nan)
TestLog1p
python
davidhalter__jedi
test/completion/lambdas.py
{ "start": 1408, "end": 1835 }
class ____(object): def __init__(self, pred=lambda a, b: a): self.a = 1 #? int() self.a #? float() pred(1.0, 2) # ----------------- # test_nocond in grammar (happens in list comprehensions with `if`) # ----------------- # Doesn't need to do anything yet. It should just not raise an error. These # nocond lambdas make no sense at all. #? int() [a for a in [1,2] if (lambda: 3)][0]
Test
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/ExampleApp.py
{ "start": 1172, "end": 1635 }
class ____: Red = "#B71C1C" Pink = "#FCE4EC" Purple = "#4A148C" DeepPurple = "#311B92" Indigo = "#1A237E" Blue = "#0D47A1" LightBlue = "#01579B" Cyan = "#006064" Teal = "#004D40" Green = "#1B5E20" LightGreen = "#33691E" Lime = "#827717" Yellow = "#F57F17" Amber = "#FF6F00" Orange = "#E65100" DeepOrange = "#BF360C" Brown = "#3E2723" Grey = "#212121" BlueGrey = "#263238"
LightThemeColors
python
huggingface__transformers
src/transformers/models/phi/modular_phi.py
{ "start": 8182, "end": 12411 }
class ____(LlamaModel): def __init__(self, config: PhiConfig): super().__init__(config) self.layers = nn.ModuleList( [PhiDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.embed_dropout = nn.Dropout(config.embd_pdrop) self.final_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) del self.norm def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) causal_mask = create_causal_mask( config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, position_ids=position_ids, ) inputs_embeds = self.embed_dropout(inputs_embeds) # diff with Llama hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for decoder_layer in self.layers[: self.config.num_hidden_layers]: if output_hidden_states: all_hidden_states += (hidden_states,) layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_values=past_key_values, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = layer_outputs[0] if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states = self.final_layernorm(hidden_states) # diff with Llama # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, hidden_states=all_hidden_states, attentions=all_self_attns, )
PhiModel
python
gevent__gevent
src/gevent/hub.py
{ "start": 34270, "end": 34590 }
class ____(object): __slots__ = ['callback', 'obj'] def __init__(self, callback, obj): self.callback = callback self.obj = obj def __call__(self, *args): callback = self.callback obj = self.obj self.callback = None self.obj = None callback(obj)
linkproxy
python
ansible__ansible
lib/ansible/plugins/lookup/nested.py
{ "start": 1458, "end": 1995 }
class ____(LookupBase): def run(self, terms, variables=None, **kwargs): my_list = terms[:] my_list.reverse() if len(my_list) == 0: raise AnsibleError("with_nested requires at least one element in the nested list") result = my_list.pop() while len(my_list) > 0: result2 = self._combine(result, my_list.pop()) result = result2 new_result = [] for x in result: new_result.append(self._flatten(x)) return new_result
LookupModule
python
doocs__leetcode
solution/1200-1299/1253.Reconstruct a 2-Row Binary Matrix/Solution.py
{ "start": 0, "end": 671 }
class ____: def reconstructMatrix( self, upper: int, lower: int, colsum: List[int] ) -> List[List[int]]: n = len(colsum) ans = [[0] * n for _ in range(2)] for j, v in enumerate(colsum): if v == 2: ans[0][j] = ans[1][j] = 1 upper, lower = upper - 1, lower - 1 if v == 1: if upper > lower: upper -= 1 ans[0][j] = 1 else: lower -= 1 ans[1][j] = 1 if upper < 0 or lower < 0: return [] return ans if lower == upper == 0 else []
Solution
python
PyCQA__pylint
tests/functional/u/unused/unused_private_member.py
{ "start": 162, "end": 247 }
class ____(): def __test(self): # [unused-private-member] pass
AnotherClass
python
weaviate__weaviate-python-client
weaviate/collections/queries/near_vector/generate/async_.py
{ "start": 318, "end": 473 }
class ____( Generic[Properties, References], _NearVectorGenerateExecutor[ConnectionAsync, Properties, References], ): pass
_NearVectorGenerateAsync