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
ipython__ipython
tests/test_completerlib.py
{ "start": 776, "end": 2995 }
class ____(unittest.TestCase): files = ["aao.py", "a.py", "b.py", "aao.txt"] dirs = ["adir/", "bdir/"] def setUp(self): self.BASETESTDIR = tempfile.mkdtemp() for fil in self.files: with open(join(self.BASETESTDIR, fil), "w", encoding="utf-8") as sfile: sfile.write("pass\n") for d in self.dirs: os.mkdir(join(self.BASETESTDIR, d)) self.oldpath = os.getcwd() os.chdir(self.BASETESTDIR) def tearDown(self): os.chdir(self.oldpath) shutil.rmtree(self.BASETESTDIR) def test_1(self): """Test magic_run_completer, should match two alternatives""" event = MockEvent("%run a") mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {"a.py", "aao.py", "adir/"}) def test_2(self): """Test magic_run_completer, should match one alternative""" event = MockEvent("%run aa") mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {"aao.py"}) def test_3(self): """Test magic_run_completer with unterminated " """ event = MockEvent('%run "a') mockself = None match = set(magic_run_completer(mockself, event)) self.assertEqual(match, {"a.py", "aao.py", "adir/"}) def test_completion_more_args(self): event = MockEvent("%run a.py ") match = set(magic_run_completer(None, event)) self.assertEqual(match, set(self.files + self.dirs)) def test_completion_in_dir(self): # Github issue #3459 event = MockEvent("%run a.py {}".format(join(self.BASETESTDIR, "a"))) print(repr(event.line)) match = set(magic_run_completer(None, event)) # We specifically use replace here rather than normpath, because # at one point there were duplicates 'adir' and 'adir/', and normpath # would hide the failure for that. self.assertEqual( match, { join(self.BASETESTDIR, f).replace("\\", "/") for f in ("a.py", "aao.py", "aao.txt", "adir/") }, )
Test_magic_run_completer
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/test/utils.py
{ "start": 1189, "end": 1244 }
class ____(TypedDict): key: str value: str
GqlTag
python
pypa__warehouse
tests/unit/cache/test_http.py
{ "start": 3376, "end": 8446 }
class ____: def test_has_last_modified(self): response = pretend.stub( last_modified=pretend.stub(), status_code=200, etag=None, conditional_response=False, app_iter=iter([b"foo"]), content_length=None, ) handler = pretend.call_recorder(lambda request: response) request = pretend.stub(method="GET") tween = conditional_http_tween_factory(handler, pretend.stub()) assert tween(request) is response assert handler.calls == [pretend.call(request)] assert response.conditional_response def test_explicit_etag(self): response = pretend.stub( last_modified=None, etag="foo", conditional_response=False, app_iter=iter([b"foo"]), ) handler = pretend.call_recorder(lambda request: response) request = pretend.stub() tween = conditional_http_tween_factory(handler, pretend.stub()) assert tween(request) is response assert handler.calls == [pretend.call(request)] assert response.conditional_response @pytest.mark.parametrize("method", ["GET", "HEAD"]) def test_implicit_etag(self, method): response = pretend.stub( last_modified=None, etag=None, conditional_response=False, md5_etag=pretend.call_recorder(lambda: None), app_iter=[b"foo"], status_code=200, ) handler = pretend.call_recorder(lambda request: response) request = pretend.stub(method=method) tween = conditional_http_tween_factory(handler, pretend.stub()) assert tween(request) is response assert handler.calls == [pretend.call(request)] assert response.conditional_response assert response.md5_etag.calls == [pretend.call()] @pytest.mark.parametrize("method", ["GET", "HEAD"]) def test_implicit_etag_buffers_streaming(self, method): response = pretend.stub( last_modified=None, etag=None, conditional_response=False, md5_etag=pretend.call_recorder(lambda: None), app_iter=iter([b"foo"]), body=b"foo", content_length=3, status_code=200, ) handler = pretend.call_recorder(lambda request: response) request = pretend.stub(method=method) tween = conditional_http_tween_factory(handler, pretend.stub()) assert tween(request) is response assert handler.calls == [pretend.call(request)] assert response.conditional_response assert response.md5_etag.calls == [pretend.call()] @pytest.mark.parametrize("method", ["GET", "HEAD"]) def test_no_implicit_etag_no_200(self, method): response = pretend.stub( last_modified=None, etag=None, conditional_response=False, md5_etag=pretend.call_recorder(lambda: None), app_iter=[b"foo"], status_code=201, ) handler = pretend.call_recorder(lambda request: response) request = pretend.stub(method=method) tween = conditional_http_tween_factory(handler, pretend.stub()) assert tween(request) is response assert handler.calls == [pretend.call(request)] assert not response.conditional_response assert response.md5_etag.calls == [] @pytest.mark.parametrize("method", ["POST", "PUT"]) def test_no_implicit_etag_wrong_method(self, method): response = pretend.stub( last_modified=None, etag=None, conditional_response=False, md5_etag=pretend.call_recorder(lambda: None), app_iter=[b"foo"], status_code=200, ) handler = pretend.call_recorder(lambda request: response) request = pretend.stub(method=method) tween = conditional_http_tween_factory(handler, pretend.stub()) assert tween(request) is response assert handler.calls == [pretend.call(request)] assert not response.conditional_response assert response.md5_etag.calls == [] def test_no_etag(self): response = pretend.stub( status_code=200, last_modified=None, etag=None, conditional_response=False, app_iter=iter([b"foo"]), content_length=None, ) handler = pretend.call_recorder(lambda request: response) request = pretend.stub(method="GET") tween = conditional_http_tween_factory(handler, pretend.stub()) assert tween(request) is response assert handler.calls == [pretend.call(request)] assert not response.conditional_response def test_includeme(): config = pretend.stub(add_tween=pretend.call_recorder(lambda t: None)) includeme(config) assert config.add_tween.calls == [ pretend.call("warehouse.cache.http.conditional_http_tween_factory") ]
TestConditionalHTTPTween
python
mwaskom__seaborn
seaborn/matrix.py
{ "start": 17203, "end": 25447 }
class ____: """Object for drawing tree of similarities between data rows/columns""" def __init__(self, data, linkage, metric, method, axis, label, rotate): """Plot a dendrogram of the relationships between the columns of data Parameters ---------- data : pandas.DataFrame Rectangular data """ self.axis = axis if self.axis == 1: data = data.T if isinstance(data, pd.DataFrame): array = data.values else: array = np.asarray(data) data = pd.DataFrame(array) self.array = array self.data = data self.shape = self.data.shape self.metric = metric self.method = method self.axis = axis self.label = label self.rotate = rotate if linkage is None: self.linkage = self.calculated_linkage else: self.linkage = linkage self.dendrogram = self.calculate_dendrogram() # Dendrogram ends are always at multiples of 5, who knows why ticks = 10 * np.arange(self.data.shape[0]) + 5 if self.label: ticklabels = _index_to_ticklabels(self.data.index) ticklabels = [ticklabels[i] for i in self.reordered_ind] if self.rotate: self.xticks = [] self.yticks = ticks self.xticklabels = [] self.yticklabels = ticklabels self.ylabel = _index_to_label(self.data.index) self.xlabel = '' else: self.xticks = ticks self.yticks = [] self.xticklabels = ticklabels self.yticklabels = [] self.ylabel = '' self.xlabel = _index_to_label(self.data.index) else: self.xticks, self.yticks = [], [] self.yticklabels, self.xticklabels = [], [] self.xlabel, self.ylabel = '', '' self.dependent_coord = self.dendrogram['dcoord'] self.independent_coord = self.dendrogram['icoord'] def _calculate_linkage_scipy(self): linkage = hierarchy.linkage(self.array, method=self.method, metric=self.metric) return linkage def _calculate_linkage_fastcluster(self): import fastcluster # Fastcluster has a memory-saving vectorized version, but only # with certain linkage methods, and mostly with euclidean metric # vector_methods = ('single', 'centroid', 'median', 'ward') euclidean_methods = ('centroid', 'median', 'ward') euclidean = self.metric == 'euclidean' and self.method in \ euclidean_methods if euclidean or self.method == 'single': return fastcluster.linkage_vector(self.array, method=self.method, metric=self.metric) else: linkage = fastcluster.linkage(self.array, method=self.method, metric=self.metric) return linkage @property def calculated_linkage(self): try: return self._calculate_linkage_fastcluster() except ImportError: if np.prod(self.shape) >= 10000: msg = ("Clustering large matrix with scipy. Installing " "`fastcluster` may give better performance.") warnings.warn(msg) return self._calculate_linkage_scipy() def calculate_dendrogram(self): """Calculates a dendrogram based on the linkage matrix Made a separate function, not a property because don't want to recalculate the dendrogram every time it is accessed. Returns ------- dendrogram : dict Dendrogram dictionary as returned by scipy.cluster.hierarchy .dendrogram. The important key-value pairing is "reordered_ind" which indicates the re-ordering of the matrix """ return hierarchy.dendrogram(self.linkage, no_plot=True, color_threshold=-np.inf) @property def reordered_ind(self): """Indices of the matrix, reordered by the dendrogram""" return self.dendrogram['leaves'] def plot(self, ax, tree_kws): """Plots a dendrogram of the similarities between data on the axes Parameters ---------- ax : matplotlib.axes.Axes Axes object upon which the dendrogram is plotted """ tree_kws = {} if tree_kws is None else tree_kws.copy() tree_kws.setdefault("linewidths", .5) tree_kws.setdefault("colors", tree_kws.pop("color", (.2, .2, .2))) if self.rotate and self.axis == 0: coords = zip(self.dependent_coord, self.independent_coord) else: coords = zip(self.independent_coord, self.dependent_coord) lines = LineCollection([list(zip(x, y)) for x, y in coords], **tree_kws) ax.add_collection(lines) number_of_leaves = len(self.reordered_ind) max_dependent_coord = max(map(max, self.dependent_coord)) if self.rotate: ax.yaxis.set_ticks_position('right') # Constants 10 and 1.05 come from # `scipy.cluster.hierarchy._plot_dendrogram` ax.set_ylim(0, number_of_leaves * 10) ax.set_xlim(0, max_dependent_coord * 1.05) ax.invert_xaxis() ax.invert_yaxis() else: # Constants 10 and 1.05 come from # `scipy.cluster.hierarchy._plot_dendrogram` ax.set_xlim(0, number_of_leaves * 10) ax.set_ylim(0, max_dependent_coord * 1.05) despine(ax=ax, bottom=True, left=True) ax.set(xticks=self.xticks, yticks=self.yticks, xlabel=self.xlabel, ylabel=self.ylabel) xtl = ax.set_xticklabels(self.xticklabels) ytl = ax.set_yticklabels(self.yticklabels, rotation='vertical') # Force a draw of the plot to avoid matplotlib window error _draw_figure(ax.figure) if len(ytl) > 0 and axis_ticklabels_overlap(ytl): plt.setp(ytl, rotation="horizontal") if len(xtl) > 0 and axis_ticklabels_overlap(xtl): plt.setp(xtl, rotation="vertical") return self def dendrogram( data, *, linkage=None, axis=1, label=True, metric='euclidean', method='average', rotate=False, tree_kws=None, ax=None ): """Draw a tree diagram of relationships within a matrix Parameters ---------- data : pandas.DataFrame Rectangular data linkage : numpy.array, optional Linkage matrix axis : int, optional Which axis to use to calculate linkage. 0 is rows, 1 is columns. label : bool, optional If True, label the dendrogram at leaves with column or row names metric : str, optional Distance metric. Anything valid for scipy.spatial.distance.pdist method : str, optional Linkage method to use. Anything valid for scipy.cluster.hierarchy.linkage rotate : bool, optional When plotting the matrix, whether to rotate it 90 degrees counter-clockwise, so the leaves face right tree_kws : dict, optional Keyword arguments for the ``matplotlib.collections.LineCollection`` that is used for plotting the lines of the dendrogram tree. ax : matplotlib axis, optional Axis to plot on, otherwise uses current axis Returns ------- dendrogramplotter : _DendrogramPlotter A Dendrogram plotter object. Notes ----- Access the reordered dendrogram indices with dendrogramplotter.reordered_ind """ if _no_scipy: raise RuntimeError("dendrogram requires scipy to be installed") plotter = _DendrogramPlotter(data, linkage=linkage, axis=axis, metric=metric, method=method, label=label, rotate=rotate) if ax is None: ax = plt.gca() return plotter.plot(ax=ax, tree_kws=tree_kws)
_DendrogramPlotter
python
tox-dev__tox
src/tox/execute/pep517_backend.py
{ "start": 712, "end": 4063 }
class ____(Execute): """Executor holding the backend process.""" def __init__(self, colored: bool, cmd: Sequence[str], env: dict[str, str], cwd: Path) -> None: # noqa: FBT001 super().__init__(colored) self.cmd = cmd self.env = env self.cwd = cwd self._local_execute: tuple[LocalSubProcessExecuteInstance, ExecuteStatus] | None = None self._exc: Exception | None = None self.is_alive: bool = False def build_instance( self, request: ExecuteRequest, options: ExecuteOptions, out: SyncWrite, err: SyncWrite, ) -> ExecuteInstance: return LocalSubProcessPep517ExecuteInstance(request, options, out, err, self.local_execute(options)) def local_execute(self, options: ExecuteOptions) -> tuple[LocalSubProcessExecuteInstance, ExecuteStatus]: if self._exc is not None: raise self._exc if self._local_execute is None: request = ExecuteRequest(cmd=self.cmd, cwd=self.cwd, env=self.env, stdin=StdinSource.API, run_id="pep517") instance = LocalSubProcessExecuteInstance( request=request, options=options, out=SyncWrite(name="pep517-out", target=None, color=None), # not enabled no need to enter/exit err=SyncWrite(name="pep517-err", target=None, color=None), # not enabled no need to enter/exit on_exit_drain=False, ) status = instance.__enter__() # noqa: PLC2801 self._local_execute = instance, status while True: if b"started backend " in status.out: self.is_alive = True break if b"failed to start backend" in status.err: from tox.tox_env.python.virtual_env.package.pyproject import ToxBackendFailed # noqa: PLC0415 failure = BackendFailed( result={ "code": -5, "exc_type": "FailedToStart", "exc_msg": "could not start backend", }, out=status.out.decode(), err=status.err.decode(), ) self._exc = ToxBackendFailed(failure) raise self._exc time.sleep(0.01) # wait a short while for the output to populate return self._local_execute @staticmethod def _handler(into: bytearray, content: bytes) -> None: """Ignore content generated.""" into.extend(content) # pragma: no cover def close(self) -> None: if self._local_execute is not None: # pragma: no branch execute, _status = self._local_execute execute.__exit__(None, None, None) if execute.process is not None and execute.process.returncode is None: # pragma: no cover try: # pragma: no cover execute.process.wait(timeout=0.1) # pragma: no cover except TimeoutExpired: # pragma: no cover execute.process.terminate() # pragma: no cover # if does not stop on its own kill it self._local_execute = None self.is_alive = False
LocalSubProcessPep517Executor
python
tiangolo__fastapi
docs_src/path_operation_configuration/tutorial004_py39.py
{ "start": 104, "end": 676 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None tags: set[str] = set() @app.post("/items/", response_model=Item, summary="Create an item") async def create_item(item: Item): """ Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item """ return item
Item
python
huggingface__transformers
src/transformers/models/rt_detr/modeling_rt_detr.py
{ "start": 6849, "end": 10830 }
class ____(ModelOutput): r""" last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`): Sequence of hidden-states at the output of the last layer of the decoder of the model. intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`): Stacked intermediate hidden states (output of each layer of the decoder). intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, config.num_labels)`): Stacked intermediate logits (logits of each layer of the decoder). intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`): Stacked intermediate reference points (reference points of each layer of the decoder). intermediate_predicted_corners (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`): Stacked intermediate predicted corners (predicted corners of each layer of the decoder). initial_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`): Initial reference points used for the first decoder layer. init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`): Initial reference points sent through the Transformer decoder. enc_topk_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`): Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are picked as region proposals in the encoder stage. Output of bounding box binary classification (i.e. foreground and background). enc_topk_bboxes (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`): Logits of predicted bounding boxes coordinates in the encoder stage. enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`): Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are picked as region proposals in the first stage. Output of bounding box binary classification (i.e. foreground and background). enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`): Logits of predicted bounding boxes coordinates in the first stage. denoising_meta_values (`dict`): Extra dictionary for the denoising related values. """ last_hidden_state: Optional[torch.FloatTensor] = None intermediate_hidden_states: Optional[torch.FloatTensor] = None intermediate_logits: Optional[torch.FloatTensor] = None intermediate_reference_points: Optional[torch.FloatTensor] = None intermediate_predicted_corners: Optional[torch.FloatTensor] = None initial_reference_points: Optional[torch.FloatTensor] = None decoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None decoder_attentions: Optional[tuple[torch.FloatTensor]] = None cross_attentions: Optional[tuple[torch.FloatTensor]] = None encoder_last_hidden_state: Optional[torch.FloatTensor] = None encoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None encoder_attentions: Optional[tuple[torch.FloatTensor]] = None init_reference_points: Optional[torch.FloatTensor] = None enc_topk_logits: Optional[torch.FloatTensor] = None enc_topk_bboxes: Optional[torch.FloatTensor] = None enc_outputs_class: Optional[torch.FloatTensor] = None enc_outputs_coord_logits: Optional[torch.FloatTensor] = None denoising_meta_values: Optional[dict] = None @dataclass @auto_docstring( custom_intro=""" Output type of [`RTDetrForObjectDetection`]. """ )
RTDetrModelOutput
python
jd__tenacity
tenacity/_utils.py
{ "start": 849, "end": 3211 }
class ____(typing.Protocol): """ Protocol used by utils expecting a logger (eg: before_log). Compatible with logging, structlog, loguru, etc... """ def log( self, level: int, msg: str, /, *args: typing.Any, **kwargs: typing.Any ) -> typing.Any: ... def find_ordinal(pos_num: int) -> str: # See: https://en.wikipedia.org/wiki/English_numerals#Ordinal_numbers if pos_num == 0: return "th" elif pos_num == 1: return "st" elif pos_num == 2: return "nd" elif pos_num == 3: return "rd" elif 4 <= pos_num <= 20: return "th" else: return find_ordinal(pos_num % 10) def to_ordinal(pos_num: int) -> str: return f"{pos_num}{find_ordinal(pos_num)}" def get_callback_name(cb: typing.Callable[..., typing.Any]) -> str: """Get a callback fully-qualified name. If no name can be produced ``repr(cb)`` is called and returned. """ segments = [] try: segments.append(cb.__qualname__) except AttributeError: try: segments.append(cb.__name__) except AttributeError: pass if not segments: return repr(cb) else: try: # When running under sphinx it appears this can be none? if cb.__module__: segments.insert(0, cb.__module__) except AttributeError: pass return ".".join(segments) time_unit_type = typing.Union[int, float, timedelta] def to_seconds(time_unit: time_unit_type) -> float: return float( time_unit.total_seconds() if isinstance(time_unit, timedelta) else time_unit ) def is_coroutine_callable(call: typing.Callable[..., typing.Any]) -> bool: if inspect.isclass(call): return False if inspect.iscoroutinefunction(call): return True partial_call = isinstance(call, functools.partial) and call.func dunder_call = partial_call or getattr(call, "__call__", None) return inspect.iscoroutinefunction(dunder_call) def wrap_to_async_func( call: typing.Callable[..., typing.Any], ) -> typing.Callable[..., typing.Awaitable[typing.Any]]: if is_coroutine_callable(call): return call async def inner(*args: typing.Any, **kwargs: typing.Any) -> typing.Any: return call(*args, **kwargs) return inner
LoggerProtocol
python
doocs__leetcode
solution/2700-2799/2744.Find Maximum Number of String Pairs/Solution.py
{ "start": 0, "end": 222 }
class ____: def maximumNumberOfStringPairs(self, words: List[str]) -> int: cnt = Counter() ans = 0 for w in words: ans += cnt[w[::-1]] cnt[w] += 1 return ans
Solution
python
great-expectations__great_expectations
tests/integration/fluent/test_integration_datasource.py
{ "start": 20274, "end": 21736 }
class ____: datasource: SparkDatasource dataframe: SparkDataFrame def _validate_whole_dataframe_batch( source_and_frame: PandasDataSourceAndFrame | SparkDataSourceAndFrame, ): my_expectation = gxe.ExpectColumnMeanToBeBetween( column="column_name", min_value=2.5, max_value=3.5 ) asset = source_and_frame.datasource.add_dataframe_asset(name="asset") bd = asset.add_batch_definition_whole_dataframe(name="bd") batch = bd.get_batch(batch_parameters={"dataframe": source_and_frame.dataframe}) result = batch.validate(my_expectation) assert result.success @pytest.mark.unit def test_validate_pandas_batch(): context = gx.get_context(mode="ephemeral") datasource = context.data_sources.add_pandas(name="ds") df = pd.DataFrame({"column_name": [1, 2, 3, 4, 5]}) _validate_whole_dataframe_batch(PandasDataSourceAndFrame(datasource=datasource, dataframe=df)) @pytest.mark.spark def test_validate_spark_batch( spark_session: SparkSession, spark_df_from_pandas_df: Callable[[SparkSession, pd.DataFrame], SparkDataFrame], ): context = gx.get_context(mode="ephemeral") datasource = context.data_sources.add_spark(name="ds") spark_df = spark_df_from_pandas_df( spark_session, pd.DataFrame({"column_name": [1, 2, 3, 4, 5]}) ) _validate_whole_dataframe_batch( SparkDataSourceAndFrame(datasource=datasource, dataframe=spark_df) ) @dataclass
SparkDataSourceAndFrame
python
pytorch__pytorch
torch/_inductor/runtime/autotune_cache.py
{ "start": 3496, "end": 11174 }
class ____: configs_hash: str local_cache: tuple[RemoteCache[JsonDataTy], str] | None = None remote_cache: tuple[RemoteCache[JsonDataTy], str] | None = None # Create a AutotuneCache. Returns None if none of the caches can be used. @staticmethod def create( inductor_meta: _InductorMetaTy, filename: str, configs_hash: str ) -> AutotuneCache | None: cache = AutotuneCache(configs_hash) key = AutotuneCache._prepare_key(filename) cache._setup_local_cache(inductor_meta, os.path.dirname(filename), key) cache._setup_remote_autotune_cache(inductor_meta, key) if cache.local_cache or cache.remote_cache: return cache else: return None @staticmethod def _prepare_key(filename: str) -> str: from torch.compiler import config as cconfig # base of filename is already sha256 hash the source contents key = f"{os.path.basename(filename)}:{cconfig.cache_key_tag}" return hashlib.sha256(key.encode("utf-8")).hexdigest() # Read the best config options from the most local cache and return it. def _read(self) -> dict[str, JsonDataTy] | None: if local_cache := self.local_cache: cache, key = local_cache if best_config := cache.get(key): if isinstance(best_config, dict): return best_config if remote_cache := self.remote_cache: cache, key = remote_cache if best_config := cache.get(key): if isinstance(best_config, dict): return best_config return None # Read the best config options from the most local cache and figure out # which `configs` represents that option. def read_best( self, inductor_meta: _InductorMetaTy, configs: list[Config] ) -> Config | None: if best := self._read(): return _load_cached_autotuning( best, self.configs_hash, configs, inductor_meta ) return None # Set up local filesystem caching information def _setup_local_cache( self, inductor_meta: _InductorMetaTy, dirname: str, cache_key: str ) -> None: if not inductor_meta.get("autotune_local_cache", True): return from ..codecache import torch_key """ [Note: torch_key in autotune cache key] Include torch_key() in the cache key so that different versions of torch result in cache invalidation. This is important in case of changes to the best_config format or other code changes that are not backward compatible w.r.t. the cache. """ hasher = hashlib.sha256() hasher.update(cache_key.encode("utf-8")) hasher.update(torch_key()) updated_cache_key = hasher.hexdigest() cache_filename = f"{dirname}/{updated_cache_key}.best_config" local_cache = LocalAutotuneCache() self.local_cache = (local_cache, cache_filename) # Set up remote caching information def _setup_remote_autotune_cache( self, inductor_meta: _InductorMetaTy, cache_key: str ) -> None: if not _should_use_remote_autotune_cache(inductor_meta): return if (backend_hash := inductor_meta.get("backend_hash", None)) is None: log.debug( "backend_hash is not passed on the inductor_meta, unable to use autotune remote cache" ) return assert isinstance(backend_hash, str) from ..codecache import torch_key is_fbcode = bool(inductor_meta.get("is_fbcode", False)) salt = "autotune-best-config-v2" # re: torch_key - see [Note: torch_key in autotune cache key] key = torch_key().hex() + backend_hash + self.configs_hash + salt key = hashlib.sha256(key.encode("utf-8")).hexdigest() remote_cache = create_cache( key, is_fbcode, "FbRemoteAutotuneCache", "RemoteAutotuneCache", ) if not remote_cache: return # Save the args passed to create_cache # in case AutotuneCache needs to be pickled self.remote_cache_full_key = key self.is_fbcode = is_fbcode self.remote_cache = (remote_cache, cache_key) # The AutotuneCache may be serialized/deserialized if we're using # AsyncCompile worker processes to run triton compilation. # This is because AutotuneCache instances are created on the worker # process, but we need to run AutotuneCache.save on the parent process # when actually doing autotuning. def __getstate__(self) -> dict[str, Any]: # The remote cache handles themselves may not be serializable # So clear it and reconstruct it on setstate remote_cache = getattr(self, "remote_cache", None) return { **self.__dict__, # Save the cache_key portion "remote_cache": remote_cache and remote_cache[1], } def __setstate__(self, state: dict[str, Any]) -> None: # Reconstruct the remote cache on the parent class self.__dict__.update(state) if self.remote_cache is not None: assert isinstance(self.remote_cache, str) assert hasattr(self, "remote_cache_full_key") assert hasattr(self, "is_fbcode") cache_key = self.remote_cache remote_cache = create_cache( self.remote_cache_full_key, self.is_fbcode, "FbRemoteAutotuneCache", "RemoteAutotuneCache", ) if remote_cache is not None: self.remote_cache = (remote_cache, cache_key) else: log.warning("Warning, failed to recreate remote cache after pickling") self.remote_cache = None # Save the config in the caches def save( self, config: Config, time_taken_ns: int, found_by_coordesc: bool = False, triton_cache_hash: str | None = None, ) -> None: data = { # pyrefly: ignore [missing-attribute] **config.kwargs, # pyrefly: ignore [missing-attribute] "num_warps": config.num_warps, # pyrefly: ignore [missing-attribute] "num_stages": config.num_stages, "configs_hash": self.configs_hash, "found_by_coordesc": found_by_coordesc, "time_taken_ms": time_taken_ns // 1000000, # Convert from NS to MS "triton_cache_hash": triton_cache_hash, } if HAS_WARP_SPEC: data.update( { "num_consumer_groups": getattr(config, "num_consumer_groups", 0), "num_buffers_warp_spec": getattr( config, "num_buffers_warp_spec", 0 ), } ) if local_cache := self.local_cache: cache, key = local_cache cache.put(key, data) AutotuneCacheBundler.put(key, data) autotune_artifact_key = os.path.join(*key.split(os.sep)[-2:]) CacheArtifactManager.record_artifact( AutotuneCacheArtifact.type(), autotune_artifact_key, data ) if log.isEnabledFor(logging.DEBUG): type_str = "coordesc" if found_by_coordesc else "heuristic" log.debug("Save %s tuning result to %s", type_str, key) if remote_cache := self.remote_cache: cache, key = remote_cache cache.put(key, data)
AutotuneCache
python
google__jax
jax/experimental/key_reuse/_core.py
{ "start": 4228, "end": 4506 }
class ____(NamedTuple): in_idx: int out_idx: int def __repr__(self): return f"Forward({self.in_idx}, {self.out_idx})" # KeyReuseSignature is essentially a frozen set of Source/Sink/Forward # objects, with a few convenience methods related to key reuse checking.
Forward
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1535064, "end": 1535357 }
class ____(sgqlc.types.Type, Node, GitObject): """Represents a Git tree.""" __schema__ = github_schema __field_names__ = ("entries",) entries = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null(TreeEntry)), graphql_name="entries") """A list of tree entries."""
Tree
python
dagster-io__dagster
python_modules/libraries/dagster-fivetran/dagster_fivetran/ops.py
{ "start": 4124, "end": 7694 }
class ____(SyncConfig): resync_parameters: Optional[dict[str, Any]] = Field( None, description=( "Optional resync parameters to send in the payload to the Fivetran API. You can" " find an example resync payload here:" " https://fivetran.com/docs/rest-api/connectors#request_7" ), ) @op( ins={"start_after": In(Nothing)}, out=Out( FivetranOutput, description=( "Parsed json dictionary representing the details of the Fivetran connector after the" " resync successfully completes. See the [Fivetran API" " Docs](https://fivetran.com/docs/rest-api/connectors#retrieveconnectordetails) to see" " detailed information on this response." ), ), tags={COMPUTE_KIND_TAG: "fivetran"}, ) @deprecated( breaking_version="0.30", additional_warn_text=( "Fivetran ops are no longer best practice and will soon be removed. " "Use `FivetranWorkspace` resource and `@fivetran_asset` decorator instead." ), ) def fivetran_resync_op( config: FivetranResyncConfig, fivetran: FivetranResource, ) -> Any: """Executes a Fivetran historical resync for a given ``connector_id``, and polls until that resync completes, raising an error if it is unsuccessful. It outputs a FivetranOutput which contains the details of the Fivetran connector after the resync successfully completes, as well as details about which tables the resync updates. It requires the use of the :py:class:`~dagster_fivetran.fivetran_resource`, which allows it to communicate with the Fivetran API. Examples: .. code-block:: python from dagster import job from dagster_fivetran import fivetran_resource, fivetran_resync_op my_fivetran_resource = fivetran_resource.configured( { "api_key": {"env": "FIVETRAN_API_KEY"}, "api_secret": {"env": "FIVETRAN_API_SECRET"}, } ) sync_foobar = fivetran_resync_op.configured( { "connector_id": "foobar", "resync_parameters": { "schema_a": ["table_a", "table_b"], "schema_b": ["table_c"] } }, name="sync_foobar" ) @job(resource_defs={"fivetran": my_fivetran_resource}) def my_simple_fivetran_job(): sync_foobar() @job(resource_defs={"fivetran": my_fivetran_resource}) def my_composed_fivetran_job(): final_foobar_state = sync_foobar(start_after=some_op()) other_op(final_foobar_state) """ fivetran_output = fivetran.resync_and_poll( connector_id=config.connector_id, resync_parameters=config.resync_parameters, poll_interval=config.poll_interval, poll_timeout=config.poll_timeout, ) if config.yield_materializations: asset_key_filter = ( [ AssetKey(config.asset_key_prefix + [schema, table]) for schema, tables in config.resync_parameters.items() for table in tables ] if config.resync_parameters is not None else None ) for mat in generate_materializations( fivetran_output, asset_key_prefix=config.asset_key_prefix ): if asset_key_filter is None or mat.asset_key in asset_key_filter: yield mat yield Output(fivetran_output)
FivetranResyncConfig
python
davidhalter__jedi
test/completion/pep0526_variables.py
{ "start": 1245, "end": 1873 }
class ____(VarClass): var_class3: typing.ClassVar[int] def __init__(self): #? int() self.var_class3 #? ['var_class1', 'var_class2', 'var_instance1', 'var_class3', 'var_instance2'] VarClass.var_ #? int() VarClass.var_instance1 #? float() VarClass.var_instance2 #? str() VarClass.var_class1 #? bytes() VarClass.var_class2 #? [] VarClass.int d = VarClass() #? ['var_class1', 'var_class2', 'var_class3', 'var_instance1', 'var_instance2'] d.var_ #? int() d.var_instance1 #? float() d.var_instance2 #? str() d.var_class1 #? bytes() d.var_class2 #? [] d.int import dataclasses @dataclasses.dataclass
VarClass2
python
doocs__leetcode
solution/3300-3399/3362.Zero Array Transformation III/Solution.py
{ "start": 0, "end": 552 }
class ____: def maxRemoval(self, nums: List[int], queries: List[List[int]]) -> int: queries.sort() pq = [] d = [0] * (len(nums) + 1) s = j = 0 for i, x in enumerate(nums): s += d[i] while j < len(queries) and queries[j][0] <= i: heappush(pq, -queries[j][1]) j += 1 while s < x and pq and -pq[0] >= i: s += 1 d[-heappop(pq) + 1] -= 1 if s < x: return -1 return len(pq)
Solution
python
ansible__ansible
lib/ansible/module_utils/_internal/_json/_legacy_encoder.py
{ "start": 165, "end": 1191 }
class ____(_tagless.Encoder): """Compatibility wrapper over `legacy` profile JSON encoder to support trust stripping and vault value plaintext conversion.""" def __init__(self, preprocess_unsafe: bool = False, vault_to_text: bool = False, _decode_bytes: bool = False, **kwargs) -> None: self._decode_bytes = _decode_bytes # NOTE: The preprocess_unsafe and vault_to_text arguments are features of LegacyControllerJSONEncoder. # They are implemented here to allow callers to pass them without raising an error, but they have no effect. super().__init__(**kwargs) def default(self, o: object) -> object: if self._decode_bytes: if type(o) is _profiles._WrappedValue: # pylint: disable=unidiomatic-typecheck o = o.wrapped if isinstance(o, bytes): return o.decode(errors='surrogateescape') # backward compatibility with `ansible.module_utils.basic.jsonify` return super().default(o)
LegacyTargetJSONEncoder
python
django__django
tests/admin_changelist/admin.py
{ "start": 4235, "end": 4511 }
class ____(admin.ModelAdmin): actions = None # prevent ['action_checkbox'] + list(list_display) list_display = ("origin", "load", "speed", "swallowonetoone") list_editable = ["load", "speed"] list_per_page = 3 site.register(Swallow, SwallowAdmin)
SwallowAdmin
python
facebook__pyre-check
client/command_arguments.py
{ "start": 8915, "end": 9138 }
class ____: paths: Optional[List[Path]] = None log_identifier: Optional[str] = None log_results: bool = False aggregate: bool = False print_summary: bool = False @dataclass(frozen=True)
StatisticsArguments
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_init.py
{ "start": 2983, "end": 6018 }
class ____(FSDPTestMultiThread): """Tests that DTensor parameters are moved to the expected device.""" @property def world_size(self) -> int: return 4 @skip_if_lt_x_gpu(1) def test_move_states_to_device_dtensor_valid(self): assert self.world_size >= 4, f"{self.world_size}" dp_size = 2 global_mesh = init_device_mesh( device_type.type, (dp_size, self.world_size // dp_size), mesh_dim_names=("dp", "tp"), ) dp_mesh, tp_mesh = global_mesh["dp"], global_mesh["tp"] model = MLP(8, torch.device("cpu"), with_buffer=True) parallelize_module( model, tp_mesh, {"in_proj": ColwiseParallel(), "out_proj": RowwiseParallel()}, ) accelerator_device = torch.device( device_type.type, torch.get_device_module(device_type).current_device() ) for tensor in itertools.chain(model.parameters(), model.buffers()): if isinstance(tensor, DTensor): # DTensor constructor moves to the mesh's device self.assertEqual(tensor.device, accelerator_device) self.assertEqual(tensor._local_tensor.device, accelerator_device) else: self.assertEqual(tensor.device, torch.device("cpu")) fully_shard(model, mesh=dp_mesh) for tensor in itertools.chain(model.parameters(), model.buffers()): self.assertEqual(tensor.device, accelerator_device) if isinstance(tensor, DTensor): self.assertEqual(tensor._local_tensor.device, accelerator_device) @skip_if_lt_x_gpu(1) def test_move_states_to_device_dtensor_invalid(self): assert self.world_size >= 4, f"{self.world_size}" dp_size = 2 global_accelerator_mesh = init_device_mesh( device_type.type, (dp_size, self.world_size // dp_size), mesh_dim_names=("dp", "tp"), ) global_cpu_mesh = init_device_mesh( "cpu", (dp_size, self.world_size // dp_size), mesh_dim_names=("dp", "tp") ) dp_mesh = global_accelerator_mesh["dp"] tp_mesh = global_cpu_mesh["tp"] # mismatched meshes! model = MLP(8, torch.device("cpu"), with_buffer=True) parallelize_module( model, tp_mesh, {"in_proj": ColwiseParallel(), "out_proj": RowwiseParallel()}, ) for tensor in itertools.chain(model.parameters(), model.buffers()): self.assertEqual(tensor.device, torch.device("cpu")) if isinstance(tensor, DTensor): self.assertEqual(tensor._local_tensor.device, torch.device("cpu")) regex = ( rf"Requires DTensor to have mesh of the same type as the FSDP mesh but got " rf"cpu for DTensor and {device_type.type} for FSDP" ) with self.assertRaisesRegex(ValueError, regex): fully_shard(model, mesh=dp_mesh)
TestFullyShardDeviceDTensor
python
python-openxml__python-docx
tests/image/test_jpeg.py
{ "start": 10014, "end": 13313 }
class ____: def it_can_construct_from_a_stream_and_offset( self, _App1Marker__init_, _tiff_from_exif_segment_ ): bytes_ = b"\x00\x42Exif\x00\x00" marker_code, offset, length = JPEG_MARKER_CODE.APP1, 0, 66 horz_dpi, vert_dpi = 42, 24 stream = StreamReader(io.BytesIO(bytes_), BIG_ENDIAN) app1_marker = _App1Marker.from_stream(stream, marker_code, offset) _tiff_from_exif_segment_.assert_called_once_with(stream, offset, length) _App1Marker__init_.assert_called_once_with( ANY, marker_code, offset, length, horz_dpi, vert_dpi ) assert isinstance(app1_marker, _App1Marker) def it_can_construct_from_non_Exif_APP1_segment(self, _App1Marker__init_): bytes_ = b"\x00\x42Foobar" marker_code, offset, length = JPEG_MARKER_CODE.APP1, 0, 66 stream = StreamReader(io.BytesIO(bytes_), BIG_ENDIAN) app1_marker = _App1Marker.from_stream(stream, marker_code, offset) _App1Marker__init_.assert_called_once_with(ANY, marker_code, offset, length, 72, 72) assert isinstance(app1_marker, _App1Marker) def it_gets_a_tiff_from_its_Exif_segment_to_help_construct(self, get_tiff_fixture): stream, offset, length = get_tiff_fixture[:3] BytesIO_, segment_bytes, substream_ = get_tiff_fixture[3:6] Tiff_, tiff_ = get_tiff_fixture[6:] tiff = _App1Marker._tiff_from_exif_segment(stream, offset, length) BytesIO_.assert_called_once_with(segment_bytes) Tiff_.from_stream.assert_called_once_with(substream_) assert tiff is tiff_ def it_knows_the_image_dpi(self): horz_dpi, vert_dpi = 42, 24 app1 = _App1Marker(None, None, None, horz_dpi, vert_dpi) assert app1.horz_dpi == horz_dpi assert app1.vert_dpi == vert_dpi # fixtures ------------------------------------------------------- @pytest.fixture def _App1Marker__init_(self, request): return initializer_mock(request, _App1Marker) @pytest.fixture def get_tiff_fixture(self, request, substream_, Tiff_, tiff_): bytes_ = b"xfillerxMM\x00*\x00\x00\x00\x42" stream_reader = StreamReader(io.BytesIO(bytes_), BIG_ENDIAN) BytesIO_ = class_mock(request, "docx.image.jpeg.io.BytesIO", return_value=substream_) offset, segment_length, segment_bytes = 0, 16, bytes_[8:] return ( stream_reader, offset, segment_length, BytesIO_, segment_bytes, substream_, Tiff_, tiff_, ) @pytest.fixture def substream_(self, request): return instance_mock(request, io.BytesIO) @pytest.fixture def Tiff_(self, request, tiff_): Tiff_ = class_mock(request, "docx.image.jpeg.Tiff") Tiff_.from_stream.return_value = tiff_ return Tiff_ @pytest.fixture def tiff_(self, request): return instance_mock(request, Tiff, horz_dpi=42, vert_dpi=24) @pytest.fixture def _tiff_from_exif_segment_(self, request, tiff_): return method_mock( request, _App1Marker, "_tiff_from_exif_segment", autospec=False, return_value=tiff_, )
Describe_App1Marker
python
ansible__ansible
test/units/_internal/_errors/test_error_utils.py
{ "start": 449, "end": 722 }
class ____(Exception, _error_utils.ContributesToTaskResult): @property def omit_failed_key(self) -> bool: return True @property def result_contribution(self) -> c.Mapping[str, object]: return dict(unreachable=True)
_TestContributesUnreachable
python
tiangolo__fastapi
scripts/people.py
{ "start": 1590, "end": 1668 }
class ____(BaseModel): totalCount: int nodes: list[CommentsNode]
Replies
python
django__django
django/contrib/gis/gdal/geometries.py
{ "start": 26735, "end": 26802 }
class ____(GeometryCollection): geos_support = False
MultiSurface
python
scipy__scipy
scipy/integrate/tests/test_cubature.py
{ "start": 14814, "end": 31476 }
class ____: """ Tests that `cubature` gives the correct answer. """ @skip_xp_backends("dask.array", reason="Dask hangs/takes a long time for some test cases") @pytest.mark.parametrize("problem", [ # -- f1 -- ( # Function to integrate, like `f(x, *args)` genz_malik_1980_f_1, # Exact solution, like `exact(a, b, *args)` genz_malik_1980_f_1_exact, # Coordinates of `a` [0], # Coordinates of `b` [10], # Arguments to pass to `f` and `exact` ( 1/4, [5], ) ), ( genz_malik_1980_f_1, genz_malik_1980_f_1_exact, [0, 0], [1, 1], ( 1/4, [2, 4], ), ), ( genz_malik_1980_f_1, genz_malik_1980_f_1_exact, [0, 0], [5, 5], ( 1/2, [2, 4], ) ), ( genz_malik_1980_f_1, genz_malik_1980_f_1_exact, [0, 0, 0], [5, 5, 5], ( 1/2, [1, 1, 1], ) ), # -- f2 -- ( genz_malik_1980_f_2, genz_malik_1980_f_2_exact, [-1], [1], ( [5], [4], ) ), ( genz_malik_1980_f_2, genz_malik_1980_f_2_exact, [0, 0], [10, 50], ( [-3, 3], [-2, 2], ), ), ( genz_malik_1980_f_2, genz_malik_1980_f_2_exact, [0, 0, 0], [1, 1, 1], ( [1, 1, 1], [1, 1, 1], ) ), ( genz_malik_1980_f_2, genz_malik_1980_f_2_exact, [0, 0, 0], [1, 1, 1], ( [2, 3, 4], [2, 3, 4], ) ), ( genz_malik_1980_f_2, genz_malik_1980_f_2_exact, [-1, -1, -1], [1, 1, 1], ( [1, 1, 1], [2, 2, 2], ) ), ( genz_malik_1980_f_2, genz_malik_1980_f_2_exact, [-1, -1, -1, -1], [1, 1, 1, 1], ( [1, 1, 1, 1], [1, 1, 1, 1], ) ), # -- f3 -- ( genz_malik_1980_f_3, genz_malik_1980_f_3_exact, [-1], [1], ( [1/2], ), ), ( genz_malik_1980_f_3, genz_malik_1980_f_3_exact, [0, -1], [1, 1], ( [5, 5], ), ), ( genz_malik_1980_f_3, genz_malik_1980_f_3_exact, [-1, -1, -1], [1, 1, 1], ( [1, 1, 1], ), ), # -- f4 -- ( genz_malik_1980_f_4, genz_malik_1980_f_4_exact, [0], [2], ( [1], ), ), ( genz_malik_1980_f_4, genz_malik_1980_f_4_exact, [0, 0], [2, 1], ([1, 1],), ), ( genz_malik_1980_f_4, genz_malik_1980_f_4_exact, [0, 0, 0], [1, 1, 1], ([1, 1, 1],), ), # -- f5 -- ( genz_malik_1980_f_5, genz_malik_1980_f_5_exact, [-1], [1], ( [-2], [2], ), ), ( genz_malik_1980_f_5, genz_malik_1980_f_5_exact, [-1, -1], [1, 1], ( [2, 3], [4, 5], ), ), ( genz_malik_1980_f_5, genz_malik_1980_f_5_exact, [-1, -1], [1, 1], ( [-1, 1], [0, 0], ), ), ( genz_malik_1980_f_5, genz_malik_1980_f_5_exact, [-1, -1, -1], [1, 1, 1], ( [1, 1, 1], [1, 1, 1], ), ), ]) def test_scalar_output(self, problem, rule, rtol, atol, xp): f, exact, a, b, args = problem a = xp.asarray(a, dtype=xp.float64) b = xp.asarray(b, dtype=xp.float64) args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args) ndim = xp_size(a) if rule == "genz-malik" and ndim < 2: pytest.skip("Genz-Malik cubature does not support 1D integrals") res = cubature( f, a, b, rule=rule, rtol=rtol, atol=atol, args=(*args, xp), ) assert res.status == "converged" est = res.estimate exact_sol = exact(a, b, *args, xp) xp_assert_close( est, exact_sol, rtol=rtol, atol=atol, err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}", ) @skip_xp_backends("dask.array", reason="Dask hangs/takes a long time for some test cases") @pytest.mark.parametrize("problem", [ ( # Function to integrate, like `f(x, *args)` genz_malik_1980_f_1, # Exact solution, like `exact(a, b, *args)` genz_malik_1980_f_1_exact, # Function that generates random args of a certain shape. genz_malik_1980_f_1_random_args, ), ( genz_malik_1980_f_2, genz_malik_1980_f_2_exact, genz_malik_1980_f_2_random_args, ), ( genz_malik_1980_f_3, genz_malik_1980_f_3_exact, genz_malik_1980_f_3_random_args ), ( genz_malik_1980_f_4, genz_malik_1980_f_4_exact, genz_malik_1980_f_4_random_args ), ( genz_malik_1980_f_5, genz_malik_1980_f_5_exact, genz_malik_1980_f_5_random_args, ), ]) @pytest.mark.parametrize("shape", [ (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (3, 2), (3, 4, 2), (2, 1, 3), ]) def test_array_output(self, problem, rule, shape, rtol, atol, xp): rng = np_compat.random.default_rng(1) ndim = shape[-1] if rule == "genz-malik" and ndim < 2: pytest.skip("Genz-Malik cubature does not support 1D integrals") if rule == "genz-malik" and ndim >= 5: pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim") f, exact, random_args = problem args = random_args(rng, shape, xp) a = xp.asarray([0] * ndim, dtype=xp.float64) b = xp.asarray([1] * ndim, dtype=xp.float64) res = cubature( f, a, b, rule=rule, rtol=rtol, atol=atol, args=(*args, xp), ) est = res.estimate exact_sol = exact(a, b, *args, xp) xp_assert_close( est, exact_sol, rtol=rtol, atol=atol, err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}", ) err_msg = (f"estimate_error={res.error}, " f"subdivisions= {res.subdivisions}, " f"true_error={xp.abs(res.estimate - exact_sol)}") assert res.status == "converged", err_msg assert res.estimate.shape == shape[:-1] @pytest.mark.parametrize("problem", [ ( # Function to integrate lambda x, xp: x, # Exact value [50.0], # Coordinates of `a` [0], # Coordinates of `b` [10], # Points by which to split up the initial region None, ), ( lambda x, xp: xp.sin(x)/x, [2.551496047169878], # si(1) + si(2), [-1], [2], [ [0.0], ], ), ( lambda x, xp: xp.ones((x.shape[0], 1)), [1.0], [0, 0, 0], [1, 1, 1], [ [0.5, 0.5, 0.5], ], ), ( lambda x, xp: xp.ones((x.shape[0], 1)), [1.0], [0, 0, 0], [1, 1, 1], [ [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], ], ), ( lambda x, xp: xp.ones((x.shape[0], 1)), [1.0], [0, 0, 0], [1, 1, 1], [ [0.1, 0.25, 0.5], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], ], ) ]) def test_break_points(self, problem, rule, rtol, atol, xp): f, exact, a, b, points = problem a = xp.asarray(a, dtype=xp.float64) b = xp.asarray(b, dtype=xp.float64) exact = xp.asarray(exact, dtype=xp.float64) if points is not None: points = [xp.asarray(point, dtype=xp.float64) for point in points] ndim = xp_size(a) if rule == "genz-malik" and ndim < 2: pytest.skip("Genz-Malik cubature does not support 1D integrals") if rule == "genz-malik" and ndim >= 5: pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim") res = cubature( f, a, b, rule=rule, rtol=rtol, atol=atol, points=points, args=(xp,), ) xp_assert_close( res.estimate, exact, rtol=rtol, atol=atol, err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}", check_dtype=False, ) err_msg = (f"estimate_error={res.error}, " f"subdivisions= {res.subdivisions}, " f"true_error={xp.abs(res.estimate - exact)}") assert res.status == "converged", err_msg @pytest.mark.skip_xp_backends('jax.numpy', reason=boolean_index_skip_reason) @pytest.mark.skip_xp_backends('dask.array', reason=boolean_index_skip_reason) @pytest.mark.parametrize("problem", [ ( # Function to integrate f_gaussian, # Exact solution f_gaussian_exact, # Arguments passed to f f_gaussian_random_args, (1, 1), # Limits, have to match the shape of the arguments [-math.inf], # a [math.inf], # b ), ( f_gaussian, f_gaussian_exact, f_gaussian_random_args, (2, 2), [-math.inf, -math.inf], [math.inf, math.inf], ), ( f_gaussian, f_gaussian_exact, f_gaussian_random_args, (1, 1), [0], [math.inf], ), ( f_gaussian, f_gaussian_exact, f_gaussian_random_args, (1, 1), [-math.inf], [0], ), ( f_gaussian, f_gaussian_exact, f_gaussian_random_args, (2, 2), [0, 0], [math.inf, math.inf], ), ( f_gaussian, f_gaussian_exact, f_gaussian_random_args, (2, 2), [0, -math.inf], [math.inf, math.inf], ), ( f_gaussian, f_gaussian_exact, f_gaussian_random_args, (1, 4), [0, 0, -math.inf, -math.inf], [math.inf, math.inf, math.inf, math.inf], ), ( f_gaussian, f_gaussian_exact, f_gaussian_random_args, (1, 4), [-math.inf, -math.inf, -math.inf, -math.inf], [0, 0, math.inf, math.inf], ), ( lambda x, xp: 1/xp.prod(x, axis=-1)**2, # Exact only for the below limits, not for general `a` and `b`. lambda a, b, xp: xp.asarray(1/6, dtype=xp.float64), # Arguments lambda rng, shape, xp: tuple(), tuple(), [1, -math.inf, 3], [math.inf, -2, math.inf], ), # This particular problem can be slow pytest.param( ( # f(x, y, z, w) = x^n * sqrt(y) * exp(-y-z**2-w**2) for n in [0,1,2,3] f_modified_gaussian, # This exact solution is for the below limits, not in general f_modified_gaussian_exact, # Constant arguments lambda rng, shape, xp: (xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64),), tuple(), [0, 0, -math.inf, -math.inf], [1, math.inf, math.inf, math.inf] ), marks=pytest.mark.xslow, ), ]) def test_infinite_limits(self, problem, rule, rtol, atol, xp): rng = np_compat.random.default_rng(1) f, exact, random_args_func, random_args_shape, a, b = problem a = xp.asarray(a, dtype=xp.float64) b = xp.asarray(b, dtype=xp.float64) args = random_args_func(rng, random_args_shape, xp) ndim = xp_size(a) if rule == "genz-malik" and ndim < 2: pytest.skip("Genz-Malik cubature does not support 1D integrals") if rule == "genz-malik" and ndim >= 4: pytest.mark.slow("Genz-Malik is slow in >= 5 dim") if rule == "genz-malik" and ndim >= 4 and is_array_api_strict(xp): pytest.mark.xslow("Genz-Malik very slow for array_api_strict in >= 4 dim") res = cubature( f, a, b, rule=rule, rtol=rtol, atol=atol, args=(*args, xp), ) assert res.status == "converged" xp_assert_close( res.estimate, exact(a, b, *args, xp), rtol=rtol, atol=atol, err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}", check_0d=False, ) @pytest.mark.skip_xp_backends('jax.numpy', reason=boolean_index_skip_reason) @pytest.mark.skip_xp_backends('dask.array', reason=boolean_index_skip_reason) @pytest.mark.parametrize("problem", [ ( # Function to integrate lambda x, xp: (xp.sin(x) / x)**8, # Exact value [151/315 * math.pi], # Limits [-math.inf], [math.inf], # Breakpoints [[0]], ), ( # Function to integrate lambda x, xp: (xp.sin(x[:, 0]) / x[:, 0])**8, # Exact value 151/315 * math.pi, # Limits [-math.inf, 0], [math.inf, 1], # Breakpoints [[0, 0.5]], ) ]) def test_infinite_limits_and_break_points(self, problem, rule, rtol, atol, xp): f, exact, a, b, points = problem a = xp.asarray(a, dtype=xp.float64) b = xp.asarray(b, dtype=xp.float64) exact = xp.asarray(exact, dtype=xp.float64) ndim = xp_size(a) if rule == "genz-malik" and ndim < 2: pytest.skip("Genz-Malik cubature does not support 1D integrals") if points is not None: points = [xp.asarray(point, dtype=xp.float64) for point in points] res = cubature( f, a, b, rule=rule, rtol=rtol, atol=atol, points=points, args=(xp,), ) assert res.status == "converged" xp_assert_close( res.estimate, exact, rtol=rtol, atol=atol, err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}", check_0d=False, )
TestCubatureProblems
python
getsentry__sentry
tests/sentry/api/serializers/test_organization.py
{ "start": 9527, "end": 10252 }
class ____(TestCase): def test_trusted_relay_serializer(self) -> None: completion_seen = timezone.now() serializer = OnboardingTasksSerializer() task = OrganizationOnboardingTask.objects.create( organization_id=self.organization.id, task=OnboardingTask.FIRST_PROJECT, status=OnboardingTaskStatus.COMPLETE, user_id=self.user.id, completion_seen=completion_seen, ) result = serialize(task, self.user, serializer) assert result["task"] == "create_project" assert result["status"] == "complete" assert result["completionSeen"] == completion_seen assert result["data"] == {}
TrustedRelaySerializer
python
PyCQA__pylint
doc/data/messages/m/match-class-bind-self/bad.py
{ "start": 0, "end": 339 }
class ____: __match_args__ = ("title", "year") def __init__(self, title, year): self.title = title self.year = year def func(item: Book): match item: case Book(title=str(title)): # [match-class-bind-self] ... case Book(year=int(year)): # [match-class-bind-self] ...
Book
python
PrefectHQ__prefect
tests/test_flows.py
{ "start": 86953, "end": 88178 }
class ____: def test_func_is_a_flow(self, tmp_path): flow_code = """ from prefect import flow @flow def dog(): return "woof!" """ fpath = tmp_path / "f.py" fpath.write_text(dedent(flow_code)) flow = load_function_and_convert_to_flow(f"{fpath}:dog") assert flow.fn() == "woof!" assert isinstance(flow, Flow) assert flow.name == "dog" def test_func_is_not_a_flow(self, tmp_path): flow_code = """ def dog(): return "woof!" """ fpath = tmp_path / "f.py" fpath.write_text(dedent(flow_code)) flow = load_function_and_convert_to_flow(f"{fpath}:dog") assert isinstance(flow, Flow) assert flow.name == "dog" assert flow.log_prints is True assert flow.fn() == "woof!" def test_func_not_found(self, tmp_path): flow_code = "" fpath = tmp_path / "f.py" fpath.write_text(dedent(flow_code)) with pytest.raises( RuntimeError, match=f"Function with name 'dog' not found in '{fpath}'." ): load_function_and_convert_to_flow(f"{fpath}:dog")
TestLoadFunctionAndConvertToFlow
python
keras-team__keras
keras/src/activations/activations_test.py
{ "start": 1283, "end": 39617 }
class ____(testing.TestCase): def test_softmax(self): x = np.random.random((2, 5)) result = activations.softmax(x[np.newaxis, :])[0] expected = _ref_softmax(x[0]) self.assertAllClose(result[0], expected, rtol=1e-05) def test_softmax_2d_axis_0(self): x = np.random.random((2, 5)) result = activations.softmax(x[np.newaxis, :], axis=1)[0] expected = np.zeros((2, 5)) for i in range(5): expected[:, i] = _ref_softmax(x[:, i]) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_3d_axis_tuple(self): x = np.random.random((2, 3, 5)) result = activations.softmax(x, axis=(1, 2)) expected = np.zeros((2, 3, 5)) for i in range(2): expected[i, :, :] = _ref_softmax(x[i, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_1d(self): x = np.random.random(5) result = activations.softmax(x) expected = _ref_softmax(x) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_higher_dim(self): x = np.random.random((2, 3, 4, 5)) result = activations.softmax(x, axis=(2, 3)) expected = np.zeros((2, 3, 4, 5)) for i in range(2): for j in range(3): expected[i, j, :, :] = _ref_softmax(x[i, j, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_higher_dim_multiple_axes(self): x = np.random.random((2, 3, 4, 5, 6)) result = activations.softmax(x, axis=(2, 3, 4)) expected = np.zeros((2, 3, 4, 5, 6)) for i in range(2): for j in range(3): expected[i, j, :, :, :] = _ref_softmax(x[i, j, :, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_softmax_negative_axis(self): x = np.random.random((2, 5)) result = activations.softmax(x, axis=-1) expected = np.zeros((2, 5)) for i in range(2): expected[i, :] = _ref_softmax(x[i, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_temporal_softmax(self): x = np.random.random((2, 2, 3)) * 10 result = activations.softmax(x[np.newaxis, :])[0] expected = _ref_softmax(x[0, 0]) self.assertAllClose(result[0, 0], expected, rtol=1e-05) def test_log_softmax_2d_axis_0(self): x = np.random.random((2, 5)) result = activations.log_softmax(x[np.newaxis, :], axis=1)[0] expected = np.zeros((2, 5)) for i in range(5): expected[:, i] = _ref_log_softmax(x[:, i]) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_3d_axis_tuple(self): x = np.random.random((2, 3, 5)) result = activations.log_softmax(x, axis=(1, 2)) expected = np.zeros((2, 3, 5)) for i in range(2): expected[i, :, :] = _ref_log_softmax(x[i, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_1d(self): x = np.random.random(5) result = activations.log_softmax(x) expected = _ref_log_softmax(x) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_higher_dim(self): x = np.random.random((2, 3, 4, 5)) result = activations.log_softmax(x, axis=(2, 3)) expected = np.zeros((2, 3, 4, 5)) for i in range(2): for j in range(3): expected[i, j, :, :] = _ref_log_softmax(x[i, j, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_higher_dim_multiple_axes(self): x = np.random.random((2, 3, 4, 5, 6)) result = activations.log_softmax(x, axis=(2, 3, 4)) expected = np.zeros((2, 3, 4, 5, 6)) for i in range(2): for j in range(3): expected[i, j, :, :, :] = _ref_log_softmax(x[i, j, :, :, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_log_softmax_negative_axis(self): x = np.random.random((2, 5)) result = activations.log_softmax(x, axis=-1) expected = np.zeros((2, 5)) for i in range(2): expected[i, :] = _ref_log_softmax(x[i, :]) self.assertAllClose(result, expected, rtol=1e-05) def test_temporal_log_softmax(self): x = np.random.random((2, 2, 3)) * 10 result = activations.log_softmax(x[np.newaxis, :])[0] expected = _ref_log_softmax(x[0, 0]) self.assertAllClose(result[0, 0], expected, rtol=1e-05) def test_selu(self): alpha = 1.6732632423543772848170429916717 scale = 1.0507009873554804934193349852946 positive_values = np.array([[1, 2]], dtype=backend.floatx()) result = activations.selu(positive_values[np.newaxis, :])[0] self.assertAllClose(result, positive_values * scale, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=backend.floatx()) result = activations.selu(negative_values[np.newaxis, :])[0] true_result = (np.exp(negative_values) - 1) * scale * alpha self.assertAllClose(result, true_result) def test_softplus(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.softplus(x[np.newaxis, :])[0] expected = np.vectorize(_ref_softplus)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.softplus(x_1d) expected_1d = np.vectorize(_ref_softplus)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.softplus(x_3d) expected_3d = np.vectorize(_ref_softplus)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.softplus(x_zero) expected_zero = np.vectorize(_ref_softplus)(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(10, 100, (2, 5)) result_large_positive = activations.softplus(x_large_positive) expected_large_positive = np.vectorize(_ref_softplus)(x_large_positive) self.assertAllClose( result_large_positive, expected_large_positive, rtol=1e-05 ) # Test large negative values x_large_negative = np.random.uniform(-100, -10, (2, 5)) result_large_negative = activations.softplus(x_large_negative) expected_large_negative = np.vectorize(_ref_softplus)(x_large_negative) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_softsign(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.softsign(x[np.newaxis, :])[0] expected = np.vectorize(_ref_softsign)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.softsign(x_1d) expected_1d = np.vectorize(_ref_softsign)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.softsign(x_3d) expected_3d = np.vectorize(_ref_softsign)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.softsign(x_zero) expected_zero = np.vectorize(_ref_softsign)(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(10, 100, (2, 5)) result_large_positive = activations.softsign(x_large_positive) expected_large_positive = np.vectorize(_ref_softsign)(x_large_positive) self.assertAllClose( result_large_positive, expected_large_positive, rtol=1e-05 ) # Test large negative values x_large_negative = np.random.uniform(-100, -10, (2, 5)) result_large_negative = activations.softsign(x_large_negative) expected_large_negative = np.vectorize(_ref_softsign)(x_large_negative) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_sigmoid(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.sigmoid(x[np.newaxis, :])[0] expected = np.vectorize(_ref_sigmoid)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.sigmoid(x_1d) expected_1d = np.vectorize(_ref_sigmoid)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.sigmoid(x_3d) expected_3d = np.vectorize(_ref_sigmoid)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.sigmoid(x_zero) expected_zero = np.vectorize(_ref_sigmoid)(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(10, 100, (2, 5)) result_large_positive = activations.sigmoid(x_large_positive) expected_large_positive = np.vectorize(_ref_sigmoid)(x_large_positive) self.assertAllClose( result_large_positive, expected_large_positive, rtol=1e-05 ) # Test large negative values x_large_negative = np.random.uniform(-100, -10, (2, 5)) result_large_negative = activations.sigmoid(x_large_negative) expected_large_negative = np.vectorize(_ref_sigmoid)(x_large_negative) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_hard_sigmoid(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.hard_sigmoid(x[np.newaxis, :])[0] expected = np.vectorize(_ref_hard_sigmoid)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.hard_sigmoid(x_1d) expected_1d = np.vectorize(_ref_hard_sigmoid)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.hard_sigmoid(x_3d) expected_3d = np.vectorize(_ref_hard_sigmoid)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values much larger than 1 x_positive_above_1 = np.random.uniform( 5, 10, (2, 5) ) # Adjusted this range result_positive_above_1 = activations.hard_sigmoid(x_positive_above_1) expected_positive_above_1 = np.ones((2, 5)) self.assertAllClose( result_positive_above_1, expected_positive_above_1, rtol=1e-05 ) def test_sparse_sigmoid(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.sparse_sigmoid(x[np.newaxis, :])[0] expected = np.vectorize(_ref_sparse_sigmoid)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.sparse_sigmoid(x_1d) expected_1d = np.vectorize(_ref_sparse_sigmoid)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.sparse_sigmoid(x_3d) expected_3d = np.vectorize(_ref_sparse_sigmoid)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(10, 100, (2, 5)) result_large_positive = activations.sparse_sigmoid(x_large_positive) expected_large_positive = np.vectorize(_ref_sparse_sigmoid)( x_large_positive ) self.assertAllClose( result_large_positive, expected_large_positive, rtol=1e-05 ) # Test large negative values x_large_negative = np.random.uniform(-100, -10, (2, 5)) result_large_negative = activations.sparse_sigmoid(x_large_negative) expected_large_negative = np.vectorize(_ref_sparse_sigmoid)( x_large_negative ) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_log_sigmoid(self): # Basic test for random values between 0 and 1 x = np.random.uniform(0, 1, (2, 5)) result = activations.log_sigmoid(x[np.newaxis, :])[0] expected = np.vectorize(_ref_log_sigmoid)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.log_sigmoid(x_1d) expected_1d = np.vectorize(_ref_log_sigmoid)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.log_sigmoid(x_3d) expected_3d = np.vectorize(_ref_log_sigmoid)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(10, 100, (2, 5)) result_large_positive = activations.log_sigmoid(x_large_positive) expected_large_positive = np.vectorize(_ref_log_sigmoid)( x_large_positive ) self.assertAllClose( result_large_positive, expected_large_positive, rtol=1e-05 ) # Test large negative values x_large_negative = np.random.uniform(-100, -10, (2, 5)) result_large_negative = activations.log_sigmoid(x_large_negative) expected_large_negative = np.vectorize(_ref_log_sigmoid)( x_large_negative ) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_hard_silu(self): # Basic test for random values between -3 and 3 x = np.random.uniform(-3, 3, (2, 5)).astype("float32") result = activations.hard_silu(x[np.newaxis, :])[0] expected = np.vectorize(_ref_hard_silu)(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5).astype("float32") result_1d = activations.hard_silu(x_1d) expected_1d = np.vectorize(_ref_hard_silu)(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)).astype("float32") result_3d = activations.hard_silu(x_3d) expected_3d = np.vectorize(_ref_hard_silu)(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values much larger than 3 x_positive_above_3 = np.random.uniform(5, 10, (2, 5)).astype("float32") result_positive_above_3 = activations.hard_silu(x_positive_above_3) expected_positive_above_3 = x_positive_above_3 self.assertAllClose( result_positive_above_3, expected_positive_above_3, rtol=1e-05 ) # Test with strictly negative values much smaller than -3 x_negatives = np.random.uniform(-10, -5, (2, 5)).astype("float32") result = activations.hard_silu(x_negatives) expected_zeros = np.zeros_like(x_negatives) self.assertAllClose(result, expected_zeros, rtol=1e-05) def test_relu_negative_slope(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with only negative_slope result_negative_slope = activations.relu(x, negative_slope=0.5) expected_negative_slope = np.array([-5.0, -2.5, 0.0, 5.0, 10.0]) self.assertAllClose( result_negative_slope, expected_negative_slope, rtol=1e-05 ) def test_relu_max_value(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with only max_value result_max_value = activations.relu(x, max_value=5.0) expected_max_value = np.array([0.0, 0.0, 0.0, 5.0, 5.0]) self.assertAllClose(result_max_value, expected_max_value, rtol=1e-05) def test_relu_threshold(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with only threshold result_threshold = activations.relu(x, threshold=5.0) expected_threshold = np.array([-0.0, -0.0, 0.0, 0.0, 10.0]) self.assertAllClose(result_threshold, expected_threshold, rtol=1e-05) def test_relu_combined_threshold_and_max_value(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with threshold and max_value result_combined = activations.relu(x, threshold=5.0, max_value=5.0) expected_combined = np.array([0.0, 0.0, 0.0, 0.0, 5.0]) self.assertAllClose(result_combined, expected_combined, rtol=1e-05) def test_relu_combined_all_parameters(self): # Define the input tensor x = np.array([-10, -5, 0.0, 5, 10]) # Test with negative_slope, max_value, and threshold result_combined = activations.relu( x, negative_slope=0.5, max_value=5.0, threshold=5.0 ) expected_combined = np.array([-7.5, -5.0, -2.5, 0.0, 5.0]) self.assertAllClose(result_combined, expected_combined, rtol=1e-05) def test_relu_to_trigger_relu6(self): x = np.array([-10, -5, 0.0, 5, 10, 12]) result_relu6 = activations.relu(x, max_value=6.0) expected_relu6 = np.array([0.0, 0.0, 0.0, 5.0, 6.0, 6.0]) self.assertAllClose(result_relu6, expected_relu6, rtol=1e-05) def test_relu_to_trigger_leaky(self): x = np.array([-10, -5, 0.0, 5, 10]) result_leaky = activations.relu(x, negative_slope=0.5) expected_leaky = np.array([-5.0, -2.5, 0.0, 5.0, 10.0]) self.assertAllClose(result_leaky, expected_leaky, rtol=1e-05) def test_relu(self): # Basic test for positive values positive_values = np.random.uniform(0.1, 10, (2, 5)) result = activations.relu(positive_values[np.newaxis, :])[0] self.assertAllClose(result, positive_values, rtol=1e-05) # Basic test for negative values negative_values = np.random.uniform(-10, -0.1, (2, 5)) result = activations.relu(negative_values[np.newaxis, :])[0] expected = np.zeros((2, 5)) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.relu(x_1d) expected_1d = np.maximum(0, x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.relu(x_3d) expected_3d = np.maximum(0, x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.relu(x_zero) expected_zero = np.maximum(0, x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large positive values x_large_positive = np.random.uniform(1e4, 1e5, (2, 5)) result_large_positive = activations.relu(x_large_positive) self.assertAllClose(result_large_positive, x_large_positive, rtol=1e-05) # Test large negative values x_large_negative = np.random.uniform(-1e5, -1e4, (2, 5)) result_large_negative = activations.relu(x_large_negative) expected_large_negative = np.zeros((2, 5)) self.assertAllClose( result_large_negative, expected_large_negative, rtol=1e-05 ) def test_leaky_relu(self): leaky_relu_vectorized = np.vectorize(_ref_leaky_relu) # Test for negative_slope = 0.01 # Test positive values positive_values = np.random.random((2, 5)) result = activations.leaky_relu( positive_values[np.newaxis, :], negative_slope=0.01 )[0] expected = leaky_relu_vectorized(positive_values, alpha=0.01) self.assertAllClose(result, expected, rtol=1e-05) # Test negative values negative_values = np.random.uniform(-1, 0, (2, 5)) result = activations.leaky_relu( negative_values[np.newaxis, :], negative_slope=0.01 )[0] expected = leaky_relu_vectorized(negative_values, alpha=0.01) self.assertAllClose(result, expected, rtol=1e-05) # Test for negative_slope = 0.3 # Test positive values positive_values = np.random.random((2, 5)) result = activations.leaky_relu( positive_values[np.newaxis, :], negative_slope=0.3 )[0] expected = leaky_relu_vectorized(positive_values, alpha=0.3) self.assertAllClose(result, expected, rtol=1e-05) # Test negative values negative_values = np.random.uniform(-1, 0, (2, 5)) result = activations.leaky_relu( negative_values[np.newaxis, :], negative_slope=0.3 )[0] expected = leaky_relu_vectorized(negative_values, alpha=0.3) self.assertAllClose(result, expected, rtol=1e-05) def test_relu6(self): relu6_vectorized = np.vectorize(_ref_relu6) # Test positive values less than 6 positive_values = np.random.uniform(0, 5.9, (2, 5)) result = activations.relu6(positive_values[np.newaxis, :])[0] expected = relu6_vectorized(positive_values) self.assertAllClose(result, expected, rtol=1e-05) # Test positive values greater than 6 positive_values_above_6 = np.random.uniform(6.1, 10, (2, 5)) result = activations.relu6(positive_values_above_6[np.newaxis, :])[0] expected = relu6_vectorized(positive_values_above_6) self.assertAllClose(result, expected, rtol=1e-05) # Test negative values negative_values = np.random.uniform(-1, 0, (2, 5)) result = activations.relu6(negative_values[np.newaxis, :])[0] expected = relu6_vectorized(negative_values) self.assertAllClose(result, expected, rtol=1e-05) def test_silu(self): silu_vectorized = np.vectorize(_ref_silu) # Test positive values positive_values = np.random.uniform(0, 5.9, (2, 5)) result = activations.silu(positive_values[np.newaxis, :])[0] expected = silu_vectorized(positive_values) self.assertAllClose(result, expected, rtol=1e-05) # Test values around zero (to ensure sigmoid behaves correctly) around_zero_values = np.random.uniform(-1, 1, (2, 5)) result = activations.silu(around_zero_values[np.newaxis, :])[0] expected = silu_vectorized(around_zero_values) self.assertAllClose(result, expected, rtol=1e-05) # Test negative values negative_values = np.random.uniform(-5.9, 0, (2, 5)) result = activations.silu(negative_values[np.newaxis, :])[0] expected = silu_vectorized(negative_values) self.assertAllClose(result, expected, rtol=1e-05) def test_gelu(self): def gelu(x, approximate=False): if approximate: return ( 0.5 * x * ( 1.0 + np.tanh( np.sqrt(2.0 / np.pi) * (x + 0.044715 * np.power(x, 3)) ) ) ) else: from scipy.stats import norm return x * norm.cdf(x) x = np.random.random((2, 5)) result = activations.gelu(x[np.newaxis, :])[0] expected = gelu(x) self.assertAllClose(result, expected, rtol=1e-05) x = np.random.random((2, 5)) result = activations.gelu(x[np.newaxis, :], approximate=True)[0] expected = gelu(x, True) self.assertAllClose(result, expected, rtol=1e-05) def test_celu(self): def celu(x, alpha=1.0): return np.maximum(x, 0.0) + alpha * np.expm1( np.minimum(x, 0.0) / alpha ) x = np.random.random((2, 5)) result = activations.celu(x[np.newaxis, :])[0] expected = celu(x) self.assertAllClose(result, expected, rtol=1e-05) x = np.random.random((2, 5)) result = activations.celu(x[np.newaxis, :], alpha=0.5)[0] expected = celu(x, alpha=0.5) self.assertAllClose(result, expected, rtol=1e-05) def test_glu(self): def glu(x, axis=-1): x1, x2 = np.split(x, 2, axis) return x1 * (1 / (1 + np.exp(-x2))) x = np.random.random((2, 4)) result = activations.glu(x[np.newaxis, :])[0] expected = glu(x) self.assertAllClose(result, expected, rtol=1e-05) x = np.random.random((2, 4)) result = activations.glu(x[np.newaxis, :], axis=-2)[0] expected = glu(x, axis=-2) self.assertAllClose(result, expected, rtol=1e-05) def test_tanh_shrink(self): def tanh_shrink(x): return x - np.tanh(x) x = np.random.random((2, 5)) result = activations.tanh_shrink(x[np.newaxis, :])[0] expected = tanh_shrink(x) self.assertAllClose(result, expected, rtol=1e-05) def test_hard_tanh(self): def hard_tanh(x): return np.clip(x, -1.0, 1.0) x = np.random.random((2, 5)) result = activations.hard_tanh(x[np.newaxis, :])[0] expected = hard_tanh(x) self.assertAllClose(result, expected, rtol=1e-05) def test_hard_shrink(self): def hard_shrink(x): return np.where(np.abs(x) > 0.5, x, 0.0) x = np.random.random((2, 5)) result = activations.hard_shrink(x[np.newaxis, :])[0] expected = hard_shrink(x) self.assertAllClose(result, expected, rtol=1e-05) def test_threshold(self): def threshold(x, threshold_value, value): return np.where( x > threshold_value, x, np.array(value, dtype=x.dtype) ) x = np.random.random((2, 5)) result = activations.threshold(x[np.newaxis, :], 0, 0)[0] expected = threshold(x, 0, 0) self.assertAllClose(result, expected, rtol=1e-05) def test_squareplus(self): def squareplus(x, b=4): y = x + np.sqrt(x**2 + b) return y / 2 x = np.random.random((2, 5)) result = activations.squareplus(x[np.newaxis, :])[0] expected = squareplus(x) self.assertAllClose(result, expected, rtol=1e-05) def test_soft_shrink(self): def soft_shrink(x, threshold=0.5): return np.where( x > threshold, x - threshold, np.where(x < -threshold, x + threshold, 0.0), ) x = np.random.random((2, 5)) result = activations.soft_shrink(x[np.newaxis, :])[0] expected = soft_shrink(x) self.assertAllClose(result, expected, rtol=1e-05) def test_sparse_plus(self): def sparse_plus(x): return np.where( x <= -1, np.zeros_like(x), np.where(x < 1, (1 / 4) * (x + 1) ** 2, x), ) x = np.random.random((2, 5)) result = activations.sparse_plus(x[np.newaxis, :])[0] expected = sparse_plus(x) self.assertAllClose(result, expected, rtol=1e-05) def test_elu(self): x = np.random.random((2, 5)) result = activations.elu(x[np.newaxis, :])[0] self.assertAllClose(result, x, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=backend.floatx()) result = activations.elu(negative_values[np.newaxis, :])[0] true_result = np.exp(negative_values) - 1 self.assertAllClose(result, true_result) def test_tanh(self): # Basic test for the tanh activation function x = np.random.random((2, 5)) result = activations.tanh(x[np.newaxis, :])[0] expected = np.tanh(x) self.assertAllClose(result, expected, rtol=1e-05) # Basic test for the tanh activation function x = np.random.uniform(-10, 10, (2, 5)) result = activations.tanh(x[np.newaxis, :])[0] expected = np.tanh(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.tanh(x_1d) expected_1d = np.tanh(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.tanh(x_3d) expected_3d = np.tanh(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values x_positive = np.random.uniform(0, 10, (2, 5)) result_positive = activations.tanh(x_positive) expected_positive = np.tanh(x_positive) self.assertAllClose(result_positive, expected_positive, rtol=1e-05) # Test with strictly negative values x_negative = np.random.uniform(-10, 0, (2, 5)) result_negative = activations.tanh(x_negative) expected_negative = np.tanh(x_negative) self.assertAllClose(result_negative, expected_negative, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.tanh(x_zero) expected_zero = np.tanh(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large values to check stability x_large = np.random.uniform(1e4, 1e5, (2, 5)) result_large = activations.tanh(x_large) expected_large = np.tanh(x_large) self.assertAllClose(result_large, expected_large, rtol=1e-05) def test_exponential(self): # Basic test for the exponential activation function x = np.random.random((2, 5)) result = activations.exponential(x[np.newaxis, :])[0] expected = np.exp(x) self.assertAllClose(result, expected, rtol=1e-05) x = np.random.uniform(-10, 10, (2, 5)) result = activations.exponential(x[np.newaxis, :])[0] expected = np.exp(x) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.exponential(x_1d) expected_1d = np.exp(x_1d) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.exponential(x_3d) expected_3d = np.exp(x_3d) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values x_positive = np.random.uniform(0, 10, (2, 5)) result_positive = activations.exponential(x_positive) expected_positive = np.exp(x_positive) self.assertAllClose(result_positive, expected_positive, rtol=1e-05) # Test with strictly negative values x_negative = np.random.uniform(-10, 0, (2, 5)) result_negative = activations.exponential(x_negative) expected_negative = np.exp(x_negative) self.assertAllClose(result_negative, expected_negative, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.exponential(x_zero) expected_zero = np.exp(x_zero) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large values to check stability x_large = np.random.uniform(1e4, 1e5, (2, 5)) result_large = activations.exponential(x_large) expected_large = np.exp(x_large) self.assertAllClose(result_large, expected_large, rtol=1e-05) def test_mish(self): # Basic test for the mish activation function x = np.random.random((2, 5)) result = activations.mish(x[np.newaxis, :])[0] expected = x * np.tanh(_ref_softplus(x)) self.assertAllClose(result, expected, rtol=1e-05) x = np.random.uniform(-10, 10, (2, 5)) result = activations.mish(x[np.newaxis, :])[0] expected = x * np.tanh(_ref_softplus(x)) self.assertAllClose(result, expected, rtol=1e-05) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) result_1d = activations.mish(x_1d) expected_1d = x_1d * np.tanh(_ref_softplus(x_1d)) self.assertAllClose(result_1d, expected_1d, rtol=1e-05) # Test with 3D array x_3d = np.random.uniform(-10, 10, (3, 3, 3)) result_3d = activations.mish(x_3d) expected_3d = x_3d * np.tanh(_ref_softplus(x_3d)) self.assertAllClose(result_3d, expected_3d, rtol=1e-05) # Test with strictly positive values x_positive = np.random.uniform(0, 10, (2, 5)) result_positive = activations.mish(x_positive) expected_positive = x_positive * np.tanh(_ref_softplus(x_positive)) self.assertAllClose(result_positive, expected_positive, rtol=1e-05) # Test with strictly negative values x_negative = np.random.uniform(-10, 0, (2, 5)) result_negative = activations.mish(x_negative) expected_negative = x_negative * np.tanh(_ref_softplus(x_negative)) self.assertAllClose(result_negative, expected_negative, rtol=1e-05) # Test near zero values x_zero = np.random.uniform(-1e-7, 1e-7, (2, 5)) result_zero = activations.mish(x_zero) expected_zero = x_zero * np.tanh(_ref_softplus(x_zero)) self.assertAllClose(result_zero, expected_zero, rtol=1e-05) # Test large values to check stability x_large = np.random.uniform(1e4, 1e5, (2, 5)) result_large = activations.mish(x_large) expected_large = x_large * np.tanh(_ref_softplus(x_large)) self.assertAllClose(result_large, expected_large, rtol=1e-05) def test_linear(self): x = np.random.random((10, 5)) self.assertAllClose(x, activations.linear(x)) # Test with 1D array x_1d = np.random.uniform(-10, 10, 5) self.assertAllClose(x_1d, activations.linear(x_1d)) # Test with 2D array x = np.random.uniform(-10, 10, (10, 5)) self.assertAllClose(x, activations.linear(x)) # Test with 3D array x_3d = np.random.uniform(-10, 10, (5, 5, 5)) self.assertAllClose(x_3d, activations.linear(x_3d)) # Test with float32 data type x_float32 = np.random.uniform(-10, 10, (10, 5)).astype(np.float32) self.assertAllClose(x_float32, activations.linear(x_float32)) # Test with int32 data type x_int32 = np.random.randint(-10, 10, (10, 5)).astype(np.int32) self.assertAllClose(x_int32, activations.linear(x_int32)) def test_sparsemax(self): # result check with 1d x_1d = np.linspace(1, 12, num=12) expected_result = np.zeros_like(x_1d) expected_result[-1] = 1.0 self.assertAllClose(expected_result, activations.sparsemax(x_1d)) # result check with 2d x_2d = np.linspace(1, 12, num=12).reshape(-1, 2) expected_result = np.zeros_like(x_2d) expected_result[:, -1] = 1.0 self.assertAllClose(expected_result, activations.sparsemax(x_2d)) # result check with 3d x_3d = np.linspace(1, 12, num=12).reshape(-1, 1, 3) expected_result = np.zeros_like(x_3d) expected_result[:, :, -1] = 1.0 self.assertAllClose(expected_result, activations.sparsemax(x_3d)) # result check with axis=-2 with 2d input x_2d = np.linspace(1, 12, num=12).reshape(-1, 2) expected_result = np.zeros_like(x_2d) expected_result[-1, :] = 1.0 self.assertAllClose( expected_result, activations.sparsemax(x_2d, axis=-2) ) # result check with axis=-2 with 3d input x_3d = np.linspace(1, 12, num=12).reshape(-1, 1, 3) expected_result = np.ones_like(x_3d) self.assertAllClose( expected_result, activations.sparsemax(x_3d, axis=-2) ) # result check with axis=-3 with 3d input x_3d = np.linspace(1, 12, num=12).reshape(-1, 1, 3) expected_result = np.zeros_like(x_3d) expected_result[-1, :, :] = 1.0 self.assertAllClose( expected_result, activations.sparsemax(x_3d, axis=-3) ) # result check with axis=-3 with 4d input x_4d = np.linspace(1, 12, num=12).reshape(-1, 1, 1, 2) expected_result = np.ones_like(x_4d) self.assertAllClose( expected_result, activations.sparsemax(x_4d, axis=-3) ) def test_get_method(self): obj = activations.get("relu") self.assertEqual(obj, activations.relu) obj = activations.get(None) self.assertEqual(obj, activations.linear) with self.assertRaises(ValueError): activations.get("typo")
ActivationsTest
python
pytorch__pytorch
torch/_subclasses/fake_tensor.py
{ "start": 44532, "end": 44697 }
class ____(Exception): """ Signals cases that should skip FakeTensor caching. """ reason: str @dataclass(frozen=True, slots=True)
_BypassDispatchCache
python
eth-brownie__brownie
brownie/exceptions.py
{ "start": 1134, "end": 1185 }
class ____(Exception): pass @final
UnknownAccount
python
viewflow__viewflow
tests/json/test_json__nullboolean.py
{ "start": 95, "end": 223 }
class ____(models.Model): data = models.JSONField() nullboolean_field = jsonstore.NullBooleanField()
NullBooleanFieldModel
python
scikit-image__scikit-image
src/skimage/measure/fit.py
{ "start": 14726, "end": 22667 }
class ____(_BaseModel): """Total least squares estimator for 2D circles. The functional model of the circle is:: r**2 = (x - xc)**2 + (y - yc)**2 This estimator minimizes the squared distances from all points to the circle:: min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) } A minimum number of 3 points is required to solve for the parameters. Parameters ---------- center : array-like, shape (2,) Coordinates of circle center. radius : float Circle radius. Notes ----- The estimation is carried out using a 2D version of the spherical estimation given in [1]_. References ---------- .. [1] Jekel, Charles F. Obtaining non-linear orthotropic material models for pvc-coated polyester via inverse bubble inflation. Thesis (MEng), Stellenbosch University, 2016. Appendix A, pp. 83-87. https://hdl.handle.net/10019.1/98627 Raises ------ ValueError If `center` does not have length 2. Examples -------- >>> t = np.linspace(0, 2 * np.pi, 25) >>> xy = CircleModel((2, 3), 4).predict_xy(t) >>> model = CircleModel.from_estimate(xy) >>> model.center array([2., 3.]) >>> model.radius 4.0 >>> res = model.residuals(xy) >>> np.abs(np.round(res, 9)) array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) The estimation can fail when — for example — all the input or output points are the same. If this happens, you will get a transform that is not "truthy" - meaning that ``bool(tform)`` is ``False``: >>> # A successfully estimated model is truthy: >>> if model: ... print("Estimation succeeded.") Estimation succeeded. >>> # Not so for a degenerate model with identical points. >>> bad_data = np.ones((4, 2)) >>> bad_model = CircleModel.from_estimate(bad_data) >>> if not bad_model: ... print("Estimation failed.") Estimation failed. Trying to use this failed estimation transform result will give a suitable error: >>> bad_model.residuals(xy) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... FailedEstimationAccessError: No attribute "residuals" for failed estimation ... """ def _args_init(self, center, radius): """Initialize CircleModel instance. Parameters ---------- center : array-like, shape (2,) Coordinates of circle center. radius : float Circle radius. """ self.center, self.radius = self._check_init_values(center, radius) def _check_init_values(self, center, radius): center = np.array(center) if not len(center) == 2: raise ValueError('Center coordinates should be length 2') return center, radius def _params2init_values(self, params): params = np.array(params) if len(params) != 3: raise ValueError('Input `params` should be length 3') return self._check_init_values(params[:2], params[2]) @property @deprecate_func( deprecated_version=_PARAMS_DEP_START, removed_version=_PARAMS_DEP_STOP, hint='`params` attribute deprecated; use `center, radius` attributes instead', ) def params(self): """Return model attributes ``center, radius`` as 1D array.""" return np.r_[self.center, self.radius] @classmethod def from_estimate(cls, data): """Estimate circle model from data using total least squares. Parameters ---------- data : (N, 2) array N points with ``(x, y)`` coordinates, respectively. Returns ------- model : Self or `~.FailedEstimation` An instance of the circle model if the estimation succeeded. Otherwise, we return a special ``FailedEstimation`` object to signal a failed estimation. Testing the truth value of the failed estimation object will return ``False``. E.g. .. code-block:: python model = CircleModel.from_estimate(...) if not model: raise RuntimeError(f"Failed estimation: {model}") """ return super().from_estimate(data) def _estimate(self, data, warn_only=True): _check_data_dim(data, dim=2) # to prevent integer overflow, cast data to float, if it isn't already float_type = np.promote_types(data.dtype, np.float32) data = data.astype(float_type, copy=False) # normalize value range to avoid misfitting due to numeric errors if # the relative distanceses are small compared to absolute distances origin = data.mean(axis=0) data = data - origin scale = data.std() if scale < np.finfo(float_type).tiny: return _warn_or_msg( "Standard deviation of data is too small to estimate " "circle with meaningful precision.", warn_only=warn_only, ) data /= scale # Adapted from a spherical estimator covered in a blog post by Charles # Jeckel (see also reference 1 above): # https://jekel.me/2015/Least-Squares-Sphere-Fit/ A = np.append(data * 2, np.ones((data.shape[0], 1), dtype=float_type), axis=1) f = np.sum(data**2, axis=1) C, _, rank, _ = np.linalg.lstsq(A, f, rcond=None) if rank != 3: return _warn_or_msg( "Input does not contain enough significant data points.", warn_only=warn_only, ) center = C[0:2] distances = spatial.minkowski_distance(center, data) r = np.sqrt(np.mean(distances**2)) # Revert normalization and set init params. self.center = center * scale + origin self.radius = r * scale return None def residuals(self, data): """Determine residuals of data to model. For each point the shortest distance to the circle is returned. Parameters ---------- data : (N, 2) array N points with ``(x, y)`` coordinates, respectively. Returns ------- residuals : (N,) array Residual for each data point. """ _check_data_dim(data, dim=2) xc, yc = self.center r = self.radius x = data[:, 0] y = data[:, 1] return r - np.sqrt((x - xc) ** 2 + (y - yc) ** 2) @_deprecate_model_params def predict_xy(self, t, params=DEPRECATED): """Predict x- and y-coordinates using the estimated model. Parameters ---------- t : array-like Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system. Returns ------- xy : (..., 2) array Predicted x- and y-coordinates. Other parameters ---------------- params : `~.DEPRECATED`, optional Optional parameters ``xc``, ``yc``, `radius`. .. deprecated:: {{ start_version }} """ t = np.asanyarray(t) (xc, yc), r = self._get_init_values(params) x = xc + r * np.cos(t) y = yc + r * np.sin(t) return np.concatenate((x[..., None], y[..., None]), axis=t.ndim) @_deprecate_estimate def estimate(self, data): """Estimate circle model from data using total least squares. Parameters ---------- data : (N, 2) array N points with ``(x, y)`` coordinates, respectively. Returns ------- success : bool True, if model estimation succeeds. """ return self._estimate(data) is None @_deprecate_no_args
CircleModel
python
doocs__leetcode
solution/1900-1999/1918.Kth Smallest Subarray Sum/Solution.py
{ "start": 0, "end": 458 }
class ____: def kthSmallestSubarraySum(self, nums: List[int], k: int) -> int: def f(s): t = j = 0 cnt = 0 for i, x in enumerate(nums): t += x while t > s: t -= nums[j] j += 1 cnt += i - j + 1 return cnt >= k l, r = min(nums), sum(nums) return l + bisect_left(range(l, r + 1), True, key=f)
Solution
python
ray-project__ray
python/ray/train/error.py
{ "start": 74, "end": 183 }
class ____(Exception): """Indicates a method or function was used outside of a session."""
SessionMisuseError
python
allegroai__clearml
clearml/backend_api/services/v2_9/queues.py
{ "start": 59154, "end": 60530 }
class ____(Request): """ :param queue: Queue id :type queue: str :param task: Task id :type task: str """ _service = "queues" _action = "move_task_to_front" _version = "2.9" _schema = { "definitions": {}, "properties": { "queue": {"description": "Queue id", "type": "string"}, "task": {"description": "Task id", "type": "string"}, }, "required": ["queue", "task"], "type": "object", } def __init__(self, queue: str, task: str, **kwargs: Any) -> None: super(MoveTaskToFrontRequest, self).__init__(**kwargs) self.queue = queue self.task = task @schema_property("queue") def queue(self) -> str: return self._property_queue @queue.setter def queue(self, value: str) -> None: if value is None: self._property_queue = None return self.assert_isinstance(value, "queue", six.string_types) self._property_queue = value @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value
MoveTaskToFrontRequest
python
Textualize__textual
src/textual/widgets/_masked_input.py
{ "start": 649, "end": 1622 }
class ____(Flag): """Misc flags for a single template character definition""" NONE = 0 """Empty flags value""" REQUIRED = auto() """Is this character required for validation?""" SEPARATOR = auto() """Is this character a separator?""" UPPERCASE = auto() """Char is forced to be uppercase""" LOWERCASE = auto() """Char is forced to be lowercase""" _TEMPLATE_CHARACTERS = { "A": (r"[A-Za-z]", _CharFlags.REQUIRED), "a": (r"[A-Za-z]", None), "N": (r"[A-Za-z0-9]", _CharFlags.REQUIRED), "n": (r"[A-Za-z0-9]", None), "X": (r"[^ ]", _CharFlags.REQUIRED), "x": (r"[^ ]", None), "9": (r"[0-9]", _CharFlags.REQUIRED), "0": (r"[0-9]", None), "D": (r"[1-9]", _CharFlags.REQUIRED), "d": (r"[1-9]", None), "#": (r"[0-9+\-]", None), "H": (r"[A-Fa-f0-9]", _CharFlags.REQUIRED), "h": (r"[A-Fa-f0-9]", None), "B": (r"[0-1]", _CharFlags.REQUIRED), "b": (r"[0-1]", None), }
_CharFlags
python
docker__docker-py
docker/api/config.py
{ "start": 38, "end": 2706 }
class ____: @utils.minimum_version('1.30') def create_config(self, name, data, labels=None, templating=None): """ Create a config Args: name (string): Name of the config data (bytes): Config data to be stored labels (dict): A mapping of labels to assign to the config templating (dict): dictionary containing the name of the templating driver to be used expressed as { name: <templating_driver_name>} Returns (dict): ID of the newly created config """ if not isinstance(data, bytes): data = data.encode('utf-8') data = base64.b64encode(data) data = data.decode('ascii') body = { 'Data': data, 'Name': name, 'Labels': labels, 'Templating': templating } url = self._url('/configs/create') return self._result( self._post_json(url, data=body), True ) @utils.minimum_version('1.30') @utils.check_resource('id') def inspect_config(self, id): """ Retrieve config metadata Args: id (string): Full ID of the config to inspect Returns (dict): A dictionary of metadata Raises: :py:class:`docker.errors.NotFound` if no config with that ID exists """ url = self._url('/configs/{0}', id) return self._result(self._get(url), True) @utils.minimum_version('1.30') @utils.check_resource('id') def remove_config(self, id): """ Remove a config Args: id (string): Full ID of the config to remove Returns (boolean): True if successful Raises: :py:class:`docker.errors.NotFound` if no config with that ID exists """ url = self._url('/configs/{0}', id) res = self._delete(url) self._raise_for_status(res) return True @utils.minimum_version('1.30') def configs(self, filters=None): """ List configs Args: filters (dict): A map of filters to process on the configs list. Available filters: ``names`` Returns (list): A list of configs """ url = self._url('/configs') params = {} if filters: params['filters'] = utils.convert_filters(filters) return self._result(self._get(url, params=params), True)
ConfigApiMixin
python
celery__celery
celery/utils/collections.py
{ "start": 5723, "end": 9949 }
class ____(MutableMapping): """Key lookup on a sequence of maps.""" key_t = None changes = None defaults = None maps = None _observers = () def __init__(self, *maps, **kwargs): # type: (*Mapping, **Any) -> None maps = list(maps or [{}]) self.__dict__.update( key_t=kwargs.get('key_t'), maps=maps, changes=maps[0], defaults=maps[1:], _observers=[], ) def add_defaults(self, d): # type: (Mapping) -> None d = force_mapping(d) self.defaults.insert(0, d) self.maps.insert(1, d) def pop(self, key, *default): # type: (Any, *Any) -> Any try: return self.maps[0].pop(key, *default) except KeyError: raise KeyError( f'Key not found in the first mapping: {key!r}') def __missing__(self, key): # type: (Any) -> Any raise KeyError(key) def _key(self, key): # type: (Any) -> Any return self.key_t(key) if self.key_t is not None else key def __getitem__(self, key): # type: (Any) -> Any _key = self._key(key) for mapping in self.maps: try: return mapping[_key] except KeyError: pass return self.__missing__(key) def __setitem__(self, key, value): # type: (Any, Any) -> None self.changes[self._key(key)] = value def __delitem__(self, key): # type: (Any) -> None try: del self.changes[self._key(key)] except KeyError: raise KeyError(f'Key not found in first mapping: {key!r}') def clear(self): # type: () -> None self.changes.clear() def get(self, key, default=None): # type: (Any, Any) -> Any try: return self[self._key(key)] except KeyError: return default def __len__(self): # type: () -> int return len(set().union(*self.maps)) def __iter__(self): return self._iterate_keys() def __contains__(self, key): # type: (Any) -> bool key = self._key(key) return any(key in m for m in self.maps) def __bool__(self): # type: () -> bool return any(self.maps) __nonzero__ = __bool__ # Py2 def setdefault(self, key, default=None): # type: (Any, Any) -> None key = self._key(key) if key not in self: self[key] = default def update(self, *args, **kwargs): # type: (*Any, **Any) -> Any result = self.changes.update(*args, **kwargs) for callback in self._observers: callback(*args, **kwargs) return result def __repr__(self): # type: () -> str return '{0.__class__.__name__}({1})'.format( self, ', '.join(map(repr, self.maps))) @classmethod def fromkeys(cls, iterable, *args): # type: (type, Iterable, *Any) -> 'ChainMap' """Create a ChainMap with a single dict created from the iterable.""" return cls(dict.fromkeys(iterable, *args)) def copy(self): # type: () -> 'ChainMap' return self.__class__(self.maps[0].copy(), *self.maps[1:]) __copy__ = copy # Py2 def _iter(self, op): # type: (Callable) -> Iterable # defaults must be first in the stream, so values in # changes take precedence. # pylint: disable=bad-reversed-sequence # Someone should teach pylint about properties. return chain(*(op(d) for d in reversed(self.maps))) def _iterate_keys(self): # type: () -> Iterable return uniq(self._iter(lambda d: d.keys())) iterkeys = _iterate_keys def _iterate_items(self): # type: () -> Iterable return ((key, self[key]) for key in self) iteritems = _iterate_items def _iterate_values(self): # type: () -> Iterable return (self[key] for key in self) itervalues = _iterate_values def bind_to(self, callback): self._observers.append(callback) keys = _iterate_keys items = _iterate_items values = _iterate_values
ChainMap
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1328488, "end": 1328686 }
class ____(VegaLiteSchema): """TextDirection schema wrapper.""" _schema = {"$ref": "#/definitions/TextDirection"} def __init__(self, *args): super().__init__(*args)
TextDirection
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 4723, "end": 4887 }
class ____(BaseIntType): @classmethod def validate(cls, value: Any) -> None: cls.validate_int_in_range(value, 0, 18446744073709551615)
XsdUnsignedLong
python
mlflow__mlflow
mlflow/entities/assessment_source.py
{ "start": 347, "end": 3337 }
class ____(_MlflowObject): """ Source of an assessment (human, LLM as a judge with GPT-4, etc). When recording an assessment, MLflow mandates providing a source information to keep track of how the assessment is conducted. Args: source_type: The type of the assessment source. Must be one of the values in the AssessmentSourceType enum or an instance of the enumerator value. source_id: An identifier for the source, e.g. user ID or LLM judge ID. If not provided, the default value "default" is used. Note: The legacy AssessmentSourceType "AI_JUDGE" is deprecated and will be resolved as "LLM_JUDGE". You will receive a warning if using this deprecated value. This legacy term will be removed in a future version of MLflow. Example: Human annotation can be represented with a source type of "HUMAN": .. code-block:: python import mlflow from mlflow.entities.assessment import AssessmentSource, AssessmentSourceType source = AssessmentSource( source_type=AssessmentSourceType.HUMAN, # or "HUMAN" source_id="bob@example.com", ) LLM-as-a-judge can be represented with a source type of "LLM_JUDGE": .. code-block:: python import mlflow from mlflow.entities.assessment import AssessmentSource, AssessmentSourceType source = AssessmentSource( source_type=AssessmentSourceType.LLM_JUDGE, # or "LLM_JUDGE" source_id="gpt-4o-mini", ) Heuristic evaluation can be represented with a source type of "CODE": .. code-block:: python import mlflow from mlflow.entities.assessment import AssessmentSource, AssessmentSourceType source = AssessmentSource( source_type=AssessmentSourceType.CODE, # or "CODE" source_id="repo/evaluation_script.py", ) To record more context about the assessment, you can use the `metadata` field of the assessment logging APIs as well. """ source_type: str source_id: str = "default" def __post_init__(self): # Perform the standardization on source_type after initialization self.source_type = AssessmentSourceType._standardize(self.source_type) def to_dictionary(self) -> dict[str, Any]: return asdict(self) @classmethod def from_dictionary(cls, source_dict: dict[str, Any]) -> "AssessmentSource": return cls(**source_dict) def to_proto(self): source = ProtoAssessmentSource() source.source_type = ProtoAssessmentSource.SourceType.Value(self.source_type) if self.source_id is not None: source.source_id = self.source_id return source @classmethod def from_proto(cls, proto): return AssessmentSource( source_type=AssessmentSourceType.from_proto(proto.source_type), source_id=proto.source_id or None, )
AssessmentSource
python
tensorflow__tensorflow
tensorflow/python/eager/polymorphic_function/atomic_function.py
{ "start": 2746, "end": 23306 }
class ____(core.AtomicFunction): """A Python callable for functions in the TF Runtime. Provides core functionality for tf.function including: - automatic lifecycle management of runtime functions - structured inputs (including captures) and structured outputs - calls from both eager and graph mode - dependency tracking of children functions - runtime error interpolation to identify user code stack traces - control dependencies (including automatic) """ __slots__ = [ "_name", "_bound_context", "_function_type", "_children", "_call_options", "_cached_definition", "_cached_graph", "_generated_graph", ] def __init__( self, name: Union[str, bytes], bound_context: context.Context, function_type: function_type_lib.FunctionType, children: Optional[List["AtomicFunction"]] = None, call_options: CallOptions = CallOptions(), cached_graph: Optional[func_graph_module.FuncGraph] = None, ): """Construct a new AtomicFunction. Args: name: str/bytes name of the runtime function in the bound context. bound_context: interface to the runtime for the AtomicFunction. function_type: input/output contract for the AtomicFunction children: list of AtomicFunctions that are needed to call this one. call_options: extra configuration options for the call. cached_graph: FuncGraph that this AtomicFunction was generated from (if known). Otherwise it will lazily construct a new corresponding FuncGraph if ever needed. """ self._name = compat.as_bytes(name) self._bound_context = bound_context self._function_type = function_type self._children = children if children else [] self._call_options = call_options self._cached_definition = None self._cached_graph = cached_graph self._generated_graph = None ref_key = (self._bound_context.function_scope_id, self.name) if ref_key not in RUNTIME_FUNCTION_REFS: RUNTIME_FUNCTION_REFS[ref_key] = 1 else: RUNTIME_FUNCTION_REFS[ref_key] += 1 @property def name(self) -> bytes: """Name represented in UTF-8 encoded bytes.""" return self._name @property def function_type(self) -> function_type_lib.FunctionType: """Represents the input/output contract of this function.""" return self._function_type @property def children(self) -> List["AtomicFunction"]: """AtomicFunctions needed as dependencies for this one.""" return self._children @property def definition(self) -> function_pb2.FunctionDef: """Current FunctionDef in the Runtime.""" return self._bound_context.get_function_def(self.name) @property def attributes(self) -> Any: """Returns FunctionDef attributes in the Runtime.""" attrs = self.definition.attr # Remove construction context since it is specific to runtime and this fn. attrs.pop(attributes_lib.EAGER_RUNTIME_CONSTRUCTION_CONTEXT, None) return attrs @property def graph_debug_info(self) -> graph_debug_info_pb2.GraphDebugInfo: """A GraphDebugInfo proto mapping nodes to corresponding stack traces.""" return self._bound_context.get_graph_debug_info(self.name) @property def call_options(self) -> CallOptions: """Call options declared for this AtomicFunction.""" return self._call_options @property def graph_call_attrs(self) -> Dict[str, Any]: """Returns a dictionary of attributes needed to add a call in graph.""" attrs = { "is_stateful": self.call_options.is_stateful, "tout": [ o.dtype.as_datatype_enum for o in self.function_type.flat_outputs ], "xla_compile_attr": self.cached_definition.attr.get( attributes_lib.XLA_COMPILE, None ), } attrs.update(self._bound_context.function_call_options.as_attrs()) return attrs @property def _c_func(self) -> Any: """Returns a scoped pybind object containing FunctionRecord in runtime.""" return self._bound_context.get_c_function(self.name) # TODO(fmuham): Move caching to dependent code and remove method. @property def cached_definition(self) -> function_pb2.FunctionDef: """Cached FunctionDef (not guaranteed to be fresh).""" if self._cached_definition is None: self._cached_definition = self.definition return self._cached_definition @property def graph(self) -> func_graph_module.FuncGraph: """Returns a FuncGraph corresponding to the AtomicFunction.""" if self._cached_graph: return self._cached_graph # Lazily generate the graph if one is not specified. if not self._generated_graph: self._generated_graph = to_func_graph(self) return self._generated_graph def call_with_captures( self, args: Sequence[Any], kwargs: Dict[str, Any], captures: Sequence[Any] ) -> Any: """Calls with args, kwargs, captures and returns structured output.""" bound_parameters = self.function_type.bind(*args, **kwargs) tensor_inputs = self.function_type.unpack_inputs(bound_parameters) capture_inputs = self.function_type.unpack_captures(captures) return self.call_preflattened(tensor_inputs + capture_inputs) def call_preflattened(self, args: Sequence[core.Tensor]) -> Any: """Calls with flattened tensor inputs and returns the structured output.""" flat_outputs = self.call_flat(*args) return self.function_type.pack_output(flat_outputs) def call_flat(self, *args: core.Tensor) -> Sequence[core.Tensor]: """Calls with flat tensor inputs and returns flat tensor outputs. Args: *args: arguments to call this function with. Returns: The outputs of the function call. Raises: ValueError: if the number of arguments is incorrect. FunctionAlreadyGarbageCollectedError: if the function is no longer available to be called because it has been garbage collected. """ expected_len = len(self.cached_definition.signature.input_arg) if len(args) != expected_len: raise ValueError( f"Signature specifies {expected_len} arguments, got: {len(args)}." f" Expected inputs: {self.cached_definition.signature.input_arg}." f" Received inputs: {args}." f" Function Type: {self.function_type!r}" ) with InterpolateRuntimeError(self): with ops.control_dependencies(self._call_options.control_captures): # The caller must use record_operation to record this operation in the # eager case, so we enforce the same requirement for the non-eager # case by explicitly pausing recording. We don't have a gradient # registered for PartitionedCall, so recording this operation confuses # forwardprop code (GradientTape manages to ignore it). with record.stop_recording(): if self._bound_context.executing_eagerly(): outputs = self._bound_context.call_function( self.name, list(args), len(self.function_type.flat_outputs), ) else: outputs = make_call_op_in_graph( self, list(args), self._bound_context.function_call_options.as_attrs(), ) for i, output_type in enumerate(self.function_type.flat_outputs): handle_data = output_type.dtype._handle_data # pylint: disable=protected-access if handle_data: handle_data_util.set_handle_data( outputs[i], handle_data.shape_inference ) # TODO(fmuham): Use FunctionType cast here for all cases. if not self._bound_context.executing_eagerly(): for i, output_type in enumerate(self.function_type.flat_outputs): outputs[i].set_shape(output_type.shape) return outputs def __call__(self, *args, **kwargs) -> Any: if self.function_type.captures: raise ValueError( "The FunctionType defines captured inputs. Use call_with_captures" " instead." ) return self.call_with_captures(args, kwargs, []) def __del__(self): if self._generated_graph: func_graph_module.dismantle_func_graph(self._generated_graph) if RUNTIME_FUNCTION_REFS is None: return key = (self._bound_context.function_scope_id, self.name) RUNTIME_FUNCTION_REFS[key] -= 1 if RUNTIME_FUNCTION_REFS[key] < 0: raise RuntimeError( f"AtomicFunction Refcounting for {self.name} is invalid." ) if RUNTIME_FUNCTION_REFS[key] == 0: try: self._bound_context.remove_function(self.name) RUNTIME_FUNCTION_REFS.pop(key) except TypeError: # Suppress some exceptions, mainly for the case when we're running on # module deletion. Things that can go wrong include the context module # already being unloaded, self._handle._handle_data no longer being # valid, and so on. Printing warnings in these cases is silly # (exceptions raised from __del__ are printed as warnings to stderr). pass # 'NoneType' object is not callable when the handle has been # partially unloaded. except AttributeError: pass # 'NoneType' object has no attribute 'eager_mode' when context has # been unloaded. Will catch other module unloads as well. def __str__(self): return f"<AtomicFunction> {compat.as_str(self.name)}{self.function_type}" def __repr__(self): return ( f"AtomicFunction(name={self.name},\n" f"bound_context={self._bound_context},\n" f"function_type={self.function_type!r},\n" f"children={self._children!s},\n" f"call_options={self._call_options},\n" f"cached_graph={self._cached_graph})" ) def _set_read_only_resource_inputs_attr( op: ops.Operation, func_graph: func_graph_module.FuncGraph ): """Sets the list of resource inputs which are read-only. This is used by AutomaticControlDependencies. Args: op: PartitionedCall Operation. func_graph: FuncGraph. """ read_only_indices = acd.get_read_only_resource_input_indices_graph(func_graph) ops.set_int_list_attr( op, acd.READ_ONLY_RESOURCE_INPUTS_ATTR, read_only_indices ) def partitioned_call_op( name: str, args: Sequence[core.Tensor], is_stateful: bool, tout: Sequence[Any], config: Any = None, executor_type: Optional[str] = None, xla_compile_attr: Any = None, ) -> ops.Operation: """Generates a function call op respecting device annotations. Args: name: Name of the function to call. args: The arguments of the function, including captured inputs. is_stateful: If the function is stateful. tout: a list containing the output dtypes enums config: (Optional) A `tensorflow::ConfigProto` proto, serialized. If `None`, all optimizations are disabled. Currently only handled for eager defined functions. executor_type: (Optional) A string for the name of the executor to be used in the function call. If not set, or set to an empty string, the default tensorflow executor will be used. xla_compile_attr: (Optional) value of the XLA compilation attribute. Returns: Returns the operation. """ if config is None: config = function_utils.get_disabled_rewriter_config() if executor_type is None: executor_type = "" # The generated binding returns an empty list for functions that don't # return any Tensors, hence the need to use `create_op` directly. args = [ops.convert_to_tensor(x) for x in args] tin_attr = attr_value_pb2.AttrValue( list=attr_value_pb2.AttrValue.ListValue( type=[x.dtype.as_datatype_enum for x in args] ) ) tout_attr = attr_value_pb2.AttrValue( list=attr_value_pb2.AttrValue.ListValue(type=tout) ) func_attr = attr_value_pb2.AttrValue( func=attr_value_pb2.NameAttrList(name=name) ) executor_type_attr = attr_value_pb2.AttrValue( s=compat.as_bytes(executor_type) ) # When running in graph mode, the graph and function graphs are optimized # (i.e. run through grappler) per the session options, so we can disable any # eager-specific rewriting. config_proto = attr_value_pb2.AttrValue(s=config) op_name = "StatefulPartitionedCall" if is_stateful else "PartitionedCall" # Propagate the attribute indicating the need to compile from function to the # call itself. op_attrs = { "Tin": tin_attr, "Tout": tout_attr, "f": func_attr, "config_proto": config_proto, "executor_type": executor_type_attr, } if xla_compile_attr is not None: op_attrs[attributes_lib.XLA_COMPILE] = xla_compile_attr op = ops.get_default_graph().create_op( op_name, args, tout, name=op_name, attrs=op_attrs ) return op def make_call_op_in_graph( atomic: AtomicFunction, tensor_inputs: Sequence[core.Tensor], context_call_attrs: Dict[str, Any], ): """Adds an AtomicFunction to graph.""" graph = ops.get_default_graph() graph._add_function_recursive(atomic) # pylint: disable=protected-access op = partitioned_call_op( # pytype: disable=wrong-arg-types # always-use-property-annotation name=atomic.name, args=tensor_inputs, is_stateful=atomic.call_options.is_stateful, tout=[ o.dtype.as_datatype_enum for o in atomic.function_type.flat_outputs ], config=context_call_attrs["config_proto"], executor_type=context_call_attrs["executor_type"], xla_compile_attr=atomic.cached_definition.attr.get( attributes_lib.XLA_COMPILE, None ), ) _set_read_only_resource_inputs_attr(op, atomic.graph) ops.set_int_list_attr( op, acd.COLLECTIVE_MANAGER_IDS, atomic._call_options.collective_manager_ids_used, # pylint: disable=protected-access ) return op.outputs def from_function_def( function_def: function_pb2.FunctionDef, function_type: function_type_lib.FunctionType, ) -> AtomicFunction: """Create a new AtomicFunction from FunctionDef + FunctionType.""" bound_context = context.context() if bound_context.has_function(compat.as_bytes(function_def.signature.name)): raise ValueError("Function already registered in context.") bound_context.add_function_def(function_def) return AtomicFunction( function_def.signature.name, bound_context, function_type ) def from_func_graph( name: Union[str, bytes], graph: func_graph_module.FuncGraph, attrs: Dict[str, attr_value_pb2.AttrValue], function_type: Optional[function_type_lib.FunctionType] = None, overwrite: bool = False, ) -> AtomicFunction: """Initializes an AtomicFunction from FuncGraph. Args: name: str, the name for the created function. graph: Graph, the graph containing the operations in the function attrs: dict mapping names of attributes to their AttrValue values function_type: known FunctionType to use, otherwise one is derived. overwrite: overwrites function definition in the current context if needed Returns: An AtomicFunction instance. """ if attrs and attributes_lib.IMPLEMENTS in attrs: # The alternative is to silently drop "implements" tag # but it seems likely it would lead to hard to catch bugs. # Another alternative is to make func_body to preserve the order # of arguments if variables are present. Yet another option # is to automatically replace variables as arguments to functions # to v.read_value() whenever "implements" tag is present # Anytime we annotate existing function we probably want to wrap # it with safe read_value for backward compatibility. has_resource_vars = any( inp.dtype == dtypes.resource for inp in graph.inputs ) captured_inputs = graph.external_captures + graph.deferred_external_captures assert not any( (has_resource_vars, captured_inputs) ), ( 'Function {name} has "{attr}={value}" attribute and thus can not ' "depend on any tensors outside of its signature or modify variables. " "\n\nNote: variables are always captured and cause function " "re-tracing for every variable called.\n" " inputs: {inputs}\n captures: {captured}\n\n" "To pass a variable to such function use " "use variable.read_value().".format( name=graph.name, attr=attributes_lib.IMPLEMENTS, value=attrs[attributes_lib.IMPLEMENTS], inputs=graph.inputs, captured=captured_inputs, ) ) input_ops = set(arg.op for arg in graph.inputs) operations = [op for op in graph.get_operations() if op not in input_ops] graph_output_names = graph._output_names # pylint: disable=protected-access if graph_output_names is not None and all( ops.tensor_id(t) in graph_output_names for t in graph.outputs ): output_names = [ compat.as_bytes(graph_output_names[ops.tensor_id(t)]) for t in graph.outputs ] if len(set(output_names)) != len(output_names): # There are duplicate names for some reason, probably an invalid # signature. Revert to auto-naming. output_names = [] else: output_names = [] with graph._c_graph.get() as c_graph: # pylint: disable=protected-access fn = pywrap_tf_session.TF_GraphToFunction_wrapper( c_graph, compat.as_str(name), False, [o._c_op for o in operations], # pylint: disable=protected-access [t._as_tf_output() for t in graph.inputs], # pylint: disable=protected-access [t._as_tf_output() for t in graph.outputs], # pylint: disable=protected-access output_names, [o._c_op for o in graph.control_outputs], # pylint: disable=protected-access [], # control_output_names None, compat.as_str(""), ) attrs = attributes_lib.parse_func_attrs(attrs or {}) for attr_name, attr_value in attrs.items(): serialized = attr_value.SerializeToString() pywrap_tf_session.TF_FunctionSetAttrValueProto( fn, compat.as_str(attr_name), serialized ) name = compat.as_bytes(name) bound_context = context.context() if overwrite and bound_context.has_function(name): bound_context.remove_function(name) bound_context.add_c_function(fn) pywrap_tf_session.TF_DeleteFunction(fn) call_options = CallOptions( collective_manager_ids_used=getattr( graph, "collective_manager_ids_used", [] ), control_captures=graph.function_captures.control, is_stateful=any(op._is_stateful for op in operations), # pylint: disable=protected-access ) if not function_type: function_type = function_type_utils.derive_from_graph(graph) return AtomicFunction( name, bound_context, function_type, list(graph._functions.values()), # pylint: disable=protected-access, call_options, cached_graph=graph, ) def to_func_graph(atomic: AtomicFunction) -> func_graph_module.FuncGraph: """Generate a FuncGraph from an AtomicFunction.""" # pylint: disable=protected-access input_signature, output_signature = function_type_lib.to_structured_signature( atomic.function_type ) with ops.Graph().as_default(): # Insert dependencies in the default graph so the new graph can pull them. for f in atomic.children: ops.get_default_graph()._add_function(f) result = function_def_to_graph.function_def_to_graph( atomic.definition, structured_input_signature=input_signature, structured_outputs=output_signature, propagate_device_spec=True, include_library_functions=False, ) for f in atomic.children: result._add_function(f) # Set input shapes and handle data for i, input_type in enumerate(atomic.function_type.flat_inputs): handle_data = input_type.dtype._handle_data if handle_data: handle_data_util.set_handle_data( result.inputs[i], handle_data.shape_inference ) result.inputs[i].set_shape(input_type.shape) # Set output shapes and handle data for i, output_type in enumerate(atomic.function_type.flat_outputs): handle_data = output_type.dtype._handle_data if handle_data: handle_data_util.set_handle_data( result.outputs[i], handle_data.shape_inference ) result.outputs[i].set_shape(output_type.shape) result.collective_manager_ids_used = ( atomic.call_options.collective_manager_ids_used, ) # pylint: enable=protected-access return result
AtomicFunction
python
Pylons__pyramid
tests/test_location.py
{ "start": 1332, "end": 1381 }
class ____: __name__ = __parent__ = None
Location
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/asyncio/result.py
{ "start": 16744, "end": 20886 }
class ____(AsyncCommon[_R]): """A wrapper for a :class:`_asyncio.AsyncResult` that returns scalar values rather than :class:`_row.Row` values. The :class:`_asyncio.AsyncScalarResult` object is acquired by calling the :meth:`_asyncio.AsyncResult.scalars` method. Refer to the :class:`_result.ScalarResult` object in the synchronous SQLAlchemy API for a complete behavioral description. .. versionadded:: 1.4 """ __slots__ = () _generate_rows = False def __init__( self, real_result: Result[Unpack[TupleAny]], index: _KeyIndexType, ): self._real_result = real_result if real_result._source_supports_scalars: self._metadata = real_result._metadata self._post_creational_filter = None else: self._metadata = real_result._metadata._reduce([index]) self._post_creational_filter = operator.itemgetter(0) self._unique_filter_state = real_result._unique_filter_state def unique( self, strategy: Optional[_UniqueFilterType] = None, ) -> Self: """Apply unique filtering to the objects returned by this :class:`_asyncio.AsyncScalarResult`. See :meth:`_asyncio.AsyncResult.unique` for usage details. """ self._unique_filter_state = (set(), strategy) return self async def partitions( self, size: Optional[int] = None ) -> AsyncIterator[Sequence[_R]]: """Iterate through sub-lists of elements of the size given. Equivalent to :meth:`_asyncio.AsyncResult.partitions` except that scalar values, rather than :class:`_engine.Row` objects, are returned. """ getter = self._manyrow_getter while True: partition = await greenlet_spawn(getter, self, size) if partition: yield partition else: break async def fetchall(self) -> Sequence[_R]: """A synonym for the :meth:`_asyncio.AsyncScalarResult.all` method.""" return await greenlet_spawn(self._allrows) async def fetchmany(self, size: Optional[int] = None) -> Sequence[_R]: """Fetch many objects. Equivalent to :meth:`_asyncio.AsyncResult.fetchmany` except that scalar values, rather than :class:`_engine.Row` objects, are returned. """ return await greenlet_spawn(self._manyrow_getter, self, size) async def all(self) -> Sequence[_R]: """Return all scalar values in a list. Equivalent to :meth:`_asyncio.AsyncResult.all` except that scalar values, rather than :class:`_engine.Row` objects, are returned. """ return await greenlet_spawn(self._allrows) def __aiter__(self) -> AsyncScalarResult[_R]: return self async def __anext__(self) -> _R: row = await greenlet_spawn(self._onerow_getter, self) if row is _NO_ROW: raise StopAsyncIteration() else: return row async def first(self) -> Optional[_R]: """Fetch the first object or ``None`` if no object is present. Equivalent to :meth:`_asyncio.AsyncResult.first` except that scalar values, rather than :class:`_engine.Row` objects, are returned. """ return await greenlet_spawn(self._only_one_row, False, False, False) async def one_or_none(self) -> Optional[_R]: """Return at most one object or raise an exception. Equivalent to :meth:`_asyncio.AsyncResult.one_or_none` except that scalar values, rather than :class:`_engine.Row` objects, are returned. """ return await greenlet_spawn(self._only_one_row, True, False, False) async def one(self) -> _R: """Return exactly one object or raise an exception. Equivalent to :meth:`_asyncio.AsyncResult.one` except that scalar values, rather than :class:`_engine.Row` objects, are returned. """ return await greenlet_spawn(self._only_one_row, True, True, False)
AsyncScalarResult
python
pypa__pip
tests/unit/test_index.py
{ "start": 11436, "end": 19030 }
class ____: @pytest.mark.parametrize( "allow_all_prereleases, prefer_binary", [ (False, False), (False, True), (True, False), (True, True), ], ) def test_create(self, allow_all_prereleases: bool, prefer_binary: bool) -> None: target_python = TargetPython() target_python._valid_tags = [Tag("py36", "none", "any")] specifier = SpecifierSet() evaluator = CandidateEvaluator.create( project_name="my-project", target_python=target_python, allow_all_prereleases=allow_all_prereleases, prefer_binary=prefer_binary, specifier=specifier, ) assert evaluator._allow_all_prereleases == allow_all_prereleases assert evaluator._prefer_binary == prefer_binary assert evaluator._specifier is specifier assert evaluator._supported_tags == [Tag("py36", "none", "any")] def test_create__target_python_none(self) -> None: """ Test passing target_python=None. """ evaluator = CandidateEvaluator.create("my-project") expected_tags = get_supported() assert evaluator._supported_tags == expected_tags def test_create__specifier_none(self) -> None: """ Test passing specifier=None. """ evaluator = CandidateEvaluator.create("my-project") expected_specifier = SpecifierSet() assert evaluator._specifier == expected_specifier def test_get_applicable_candidates(self) -> None: specifier = SpecifierSet("<= 1.11") versions = ["1.10", "1.11", "1.12"] candidates = [make_mock_candidate(version) for version in versions] evaluator = CandidateEvaluator.create( "my-project", specifier=specifier, ) actual = evaluator.get_applicable_candidates(candidates) expected_applicable = candidates[:2] assert [str(c.version) for c in expected_applicable] == [ "1.10", "1.11", ] assert actual == expected_applicable @pytest.mark.parametrize( "specifier, expected_versions", [ # Test no version constraint. (SpecifierSet(), ["1.0", "1.2"]), # Test a version constraint that excludes the candidate whose # hash matches. Then the non-allowed hash is a candidate. (SpecifierSet("<= 1.1"), ["1.0", "1.1"]), ], ) def test_get_applicable_candidates__hashes( self, specifier: SpecifierSet, expected_versions: list[str], ) -> None: """ Test a non-None hashes value. """ candidates = [ make_mock_candidate("1.0"), make_mock_candidate("1.1", hex_digest=(64 * "a")), make_mock_candidate("1.2", hex_digest=(64 * "b")), ] hashes_data = { "sha256": [64 * "b"], } hashes = Hashes(hashes_data) evaluator = CandidateEvaluator.create( "my-project", specifier=specifier, hashes=hashes, ) actual = evaluator.get_applicable_candidates(candidates) actual_versions = [str(c.version) for c in actual] assert actual_versions == expected_versions def test_compute_best_candidate(self) -> None: specifier = SpecifierSet("<= 1.11") versions = ["1.10", "1.11", "1.12"] candidates = [make_mock_candidate(version) for version in versions] evaluator = CandidateEvaluator.create( "my-project", specifier=specifier, ) result = evaluator.compute_best_candidate(candidates) assert result.all_candidates == candidates expected_applicable = candidates[:2] assert [str(c.version) for c in expected_applicable] == [ "1.10", "1.11", ] assert result.applicable_candidates == expected_applicable assert result.best_candidate is expected_applicable[1] def test_compute_best_candidate__none_best(self) -> None: """ Test returning a None best candidate. """ specifier = SpecifierSet("<= 1.10") versions = ["1.11", "1.12"] candidates = [make_mock_candidate(version) for version in versions] evaluator = CandidateEvaluator.create( "my-project", specifier=specifier, ) result = evaluator.compute_best_candidate(candidates) assert result.all_candidates == candidates assert result.applicable_candidates == [] assert result.best_candidate is None @pytest.mark.parametrize( "hex_digest, expected", [ # Test a link with no hash. (None, 0), # Test a link with an allowed hash. (64 * "a", 1), # Test a link with a hash that isn't allowed. (64 * "b", 0), ], ) def test_sort_key__hash(self, hex_digest: str | None, expected: int) -> None: """ Test the effect of the link's hash on _sort_key()'s return value. """ candidate = make_mock_candidate("1.0", hex_digest=hex_digest) hashes_data = { "sha256": [64 * "a"], } hashes = Hashes(hashes_data) evaluator = CandidateEvaluator.create("my-project", hashes=hashes) sort_value = evaluator._sort_key(candidate) # The hash is reflected in the first element of the tuple. actual = sort_value[0] assert actual == expected @pytest.mark.parametrize( "yanked_reason, expected", [ # Test a non-yanked file. (None, 0), # Test a yanked file (has a lower value than non-yanked). ("bad metadata", -1), ], ) def test_sort_key__is_yanked( self, yanked_reason: str | None, expected: int ) -> None: """ Test the effect of is_yanked on _sort_key()'s return value. """ candidate = make_mock_candidate("1.0", yanked_reason=yanked_reason) evaluator = CandidateEvaluator.create("my-project") sort_value = evaluator._sort_key(candidate) # Yanked / non-yanked is reflected in the second element of the tuple. actual = sort_value[1] assert actual == expected def test_sort_best_candidate__no_candidates(self) -> None: """ Test passing an empty list. """ evaluator = CandidateEvaluator.create("my-project") actual = evaluator.sort_best_candidate([]) assert actual is None def test_sort_best_candidate__best_yanked_but_not_all( self, caplog: pytest.LogCaptureFixture, ) -> None: """ Test the best candidates being yanked, but not all. """ caplog.set_level(logging.INFO) candidates = [ make_mock_candidate("4.0", yanked_reason="bad metadata #4"), # Put the best candidate in the middle, to test sorting. make_mock_candidate("2.0"), make_mock_candidate("3.0", yanked_reason="bad metadata #3"), make_mock_candidate("1.0"), ] expected_best = candidates[1] evaluator = CandidateEvaluator.create("my-project") actual = evaluator.sort_best_candidate(candidates) assert actual is expected_best assert str(actual.version) == "2.0" # Check the log messages. assert len(caplog.records) == 0
TestCandidateEvaluator
python
keon__algorithms
algorithms/graph/clone_graph.py
{ "start": 782, "end": 3436 }
class ____: """ A node in an undirected graph. Contains a label and a list of neighbouring nodes (initially empty). """ def __init__(self, label): self.label = label self.neighbors = [] def shallow_copy(self): """ Return a shallow copy of this node (ignoring any neighbors) """ return UndirectedGraphNode(self.label) def add_neighbor(self, node): """ Adds a new neighbor """ self.neighbors.append(node) def clone_graph1(node): """ Returns a new graph as seen from the given node using a breadth first search (BFS). """ if not node: return None node_copy = node.shallow_copy() dic = {node: node_copy} queue = collections.deque([node]) while queue: node = queue.popleft() for neighbor in node.neighbors: if neighbor not in dic: # neighbor is not visited neighbor_copy = neighbor.shallow_copy() dic[neighbor] = neighbor_copy dic[node].add_neighbor(neighbor_copy) queue.append(neighbor) else: dic[node].add_neighbor(dic[neighbor]) return node_copy def clone_graph2(node): """ Returns a new graph as seen from the given node using an iterative depth first search (DFS). """ if not node: return None node_copy = node.shallow_copy() dic = {node: node_copy} stack = [node] while stack: node = stack.pop() for neighbor in node.neighbors: if neighbor not in dic: neighbor_copy = neighbor.shallow_copy() dic[neighbor] = neighbor_copy dic[node].add_neighbor(neighbor_copy) stack.append(neighbor) else: dic[node].add_neighbor(dic[neighbor]) return node_copy def clone_graph(node): """ Returns a new graph as seen from the given node using a recursive depth first search (DFS). """ if not node: return None node_copy = node.shallow_copy() dic = {node: node_copy} dfs(node, dic) return node_copy def dfs(node, dic): """ Clones a graph using a recursive depth first search. Stores the clones in the dictionary, keyed by the original nodes. """ for neighbor in node.neighbors: if neighbor not in dic: neighbor_copy = neighbor.shallow_copy() dic[neighbor] = neighbor_copy dic[node].add_neighbor(neighbor_copy) dfs(neighbor, dic) else: dic[node].add_neighbor(dic[neighbor])
UndirectedGraphNode
python
kamyu104__LeetCode-Solutions
Python/armstrong-number.py
{ "start": 33, "end": 235 }
class ____(object): def isArmstrong(self, N): """ :type N: int :rtype: bool """ n_str = str(N) return sum(int(i)**len(n_str) for i in n_str) == N
Solution
python
numpy__numpy
numpy/f2py/tests/test_crackfortran.py
{ "start": 13050, "end": 13408 }
class ____(util.F2PyTest): def test_end_if_comment(self): # gh-23533 fpath = util.getpath("tests", "src", "crackfortran", "gh23533.f") try: crackfortran.crackfortran([str(fpath)]) except Exception as exc: assert False, f"'crackfortran.crackfortran' raised an exception {exc}"
TestFortranGroupCounters
python
django__django
tests/i18n/tests.py
{ "start": 88326, "end": 90033 }
class ____(SimpleTestCase): @override_settings(USE_I18N=False) def test_i18n_disabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_not_called() def test_i18n_enabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) self.assertGreater(mocked_sender.watch_dir.call_count, 1) def test_i18n_locale_paths(self): mocked_sender = mock.MagicMock() with tempfile.TemporaryDirectory() as app_dir: with self.settings(LOCALE_PATHS=[app_dir]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo") def test_i18n_app_dirs(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["i18n.sampleproject"]): watch_for_translation_changes(mocked_sender) project_dir = Path(__file__).parent / "sampleproject" / "locale" mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo") def test_i18n_app_dirs_ignore_django_apps(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["django.contrib.admin"]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo") def test_i18n_local_locale(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) locale_dir = Path(__file__).parent / "locale" mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo")
WatchForTranslationChangesTests
python
plotly__plotly.py
plotly/graph_objs/mesh3d/_legendgrouptitle.py
{ "start": 233, "end": 2932 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "mesh3d" _path_str = "mesh3d.legendgrouptitle" _valid_props = {"font", "text"} @property def font(self): """ Sets this legend group's title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.mesh3d.legendgrouptitle.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.mesh3d.legendgrouptitle.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def text(self): """ Sets the title of the legend group. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def _prop_descriptions(self): return """\ font Sets this legend group's title font. text Sets the title of the legend group. """ def __init__(self, arg=None, font=None, text=None, **kwargs): """ Construct a new Legendgrouptitle object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.mesh3d.Legendgrouptitle` font Sets this legend group's title font. text Sets the title of the legend group. Returns ------- Legendgrouptitle """ super().__init__("legendgrouptitle") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.mesh3d.Legendgrouptitle constructor must be a dict or an instance of :class:`plotly.graph_objs.mesh3d.Legendgrouptitle`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("font", arg, font) self._set_property("text", arg, text) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Legendgrouptitle
python
prakhar1989__Algorithms
lists/singlylinkedlist.py
{ "start": 161, "end": 1977 }
class ____(object): def __init__(self, iterable=[]): self.head = None self.size = 0 for item in iterable: self.append(item) def __repr__(self): (current, nodes) = self.head, [] while current: nodes.append(str(current)) current = current.next return "->".join(nodes) def __len__(self): return self.size def __iter__(self): current = self.head while current: yield current current = current.next raise StopIteration def __contains__(self, data): tmp = self.head found = False while tmp and not found: if data == tmp.data: found = True else: tmp = tmp.next return found def append(self, data): tmp = Node(data) tmp.next = self.head self.head = tmp self.size += 1 def getHead(self): return self.head def getTail(self): tmp = self.head while tmp.next: tmp = tmp.next return tmp def delete(self, data): tmp = self.head prev = None found = False while tmp and not found: if data == tmp.data: found = True else: prev = tmp tmp = tmp.next if found: self.size -= 1 if prev == None: self.head = self.head.next else: prev.next = tmp.next if __name__ == "__main__": list1 = SinglyLinkedList(range(0, 100, 10)) print list1 # testing repr print 50 in list1, 110 not in list1 # testing contains list1.delete(50) # testing delete print len(list1) == 9, 50 not in list1 # testing size
SinglyLinkedList
python
django__django
django/contrib/auth/context_processors.py
{ "start": 120, "end": 724 }
class ____: def __init__(self, user, app_label): self.user, self.app_label = user, app_label def __repr__(self): return str(self.user.get_all_permissions()) def __getitem__(self, perm_name): return self.user.has_perm("%s.%s" % (self.app_label, perm_name)) def __iter__(self): # To fix 'item in perms.someapp' and __getitem__ interaction we need to # define __iter__. See #18979 for details. raise TypeError("PermLookupDict is not iterable.") def __bool__(self): return self.user.has_module_perms(self.app_label)
PermLookupDict
python
prabhupant__python-ds
data_structures/bst/insertion_recursive.py
{ "start": 0, "end": 846 }
class ____(): def __init__(self, val): self.val = val self.left = None self.right = None def insertion_recursive(root, val): if not root: return Node(val) else: if root.val < val: if root.right is None: root.right = Node(val) else: insertion_recursive(root.right, val) else: if root.left is None: root.left = Node(val) else: insertion_recursive(root.left, val) def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) root = Node(5) root.left = Node(3) root.right = Node(7) root.left.left = Node(1) root.left. right = Node(4) root.right.right = Node(8) inorder(root) insertion_recursive(root, 6) inorder(root)
Node
python
ansible__ansible
lib/ansible/plugins/doc_fragments/shell_windows.py
{ "start": 167, "end": 1234 }
class ____(object): # Windows shell documentation fragment # FIXME: set_module_language don't belong here but must be set so they don't fail when someone # get_option('set_module_language') on this plugin DOCUMENTATION = r""" options: async_dir: description: - Directory in which ansible will keep async job information. - Before Ansible 2.8, this was set to C(remote_tmp + "\.ansible_async"). default: '%USERPROFILE%\.ansible_async' ini: - section: powershell key: async_dir vars: - name: ansible_async_dir version_added: '2.8' remote_tmp: description: - Temporary directory to use on targets when copying files to the host. default: '%TEMP%' ini: - section: powershell key: remote_tmp vars: - name: ansible_remote_tmp set_module_language: description: - Controls if we set the locale for modules when executing on the target. - Windows only supports V(no) as an option. type: bool default: 'no' choices: ['no', False] """
ModuleDocFragment
python
huggingface__transformers
src/transformers/models/edgetam_video/configuration_edgetam_video.py
{ "start": 6712, "end": 23679 }
class ____(PreTrainedConfig): r""" [`EdgeTamVideoConfig`] is the configuration class to store the configuration of a [`EdgeTamVideoModel`]. It is used to instantiate a EDGETAM model according to the specified arguments, defining the memory attention, memory encoder, and image encoder configs. Instantiating a configuration defaults will yield a similar configuration to that of the SAM 2.1 Hiera-tiny [facebook/EdgeTAM](https://huggingface.co/facebook/EdgeTAM) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vision_config (Union[`dict`, `EdgeTamVideoVisionConfig`], *optional*): Dictionary of configuration options used to initialize [`EdgeTamVideoVisionConfig`]. prompt_encoder_config (Union[`dict`, `EdgeTamVideoPromptEncoderConfig`], *optional*): Dictionary of configuration options used to initialize [`EdgeTamVideoPromptEncoderConfig`]. mask_decoder_config (Union[`dict`, `EdgeTamVideoMaskDecoderConfig`], *optional*): Dictionary of configuration options used to initialize [`EdgeTamMaskDecoderConfig`]. initializer_range (`float`, *optional*, defaults to 0.02): Standard deviation for parameter initialization. num_maskmem (`int`, *optional*, defaults to 7): The number of memory slots for the mask memory. image_size (`int`, *optional*, defaults to 1024): The size of the input images. sigmoid_scale_for_mem_enc (`float`, *optional*, defaults to 20.0): Scale factor for the sigmoid function in the memory encoder. sigmoid_bias_for_mem_enc (`float`, *optional*, defaults to -10.0): Bias for the sigmoid function in the memory encoder. enable_occlusion_spatial_embedding (`bool`, *optional*, defaults to `True`): Whether to enable spatial embedding for occlusions. multimask_output_in_sam (`bool`, *optional*, defaults to `True`): Whether to output multiple masks from the SAM head. multimask_min_pt_num (`int`, *optional*, defaults to 0): The minimum number of points to trigger multimask output. multimask_max_pt_num (`int`, *optional*, defaults to 1): The maximum number of points to trigger multimask output. multimask_output_for_tracking (`bool`, *optional*, defaults to `True`): Whether to use multimask output for tracking. max_object_pointers_in_encoder (`int`, *optional*, defaults to 16): The maximum number of object pointers in the encoder. max_cond_frame_num (`int`, *optional*, defaults to -1): Maximum number of conditioning frames to use in memory attention. Set to -1 to use all conditioning frames. enable_temporal_pos_encoding_for_object_pointers (`bool`, *optional*, defaults to `True`): Whether to enable temporal positional encoding for object pointers. memory_attention_hidden_size (`int`, *optional*, defaults to 256): Dimensionality of the memory attention hidden states. memory_attention_num_layers (`int`, *optional*, defaults to 2): The number of layers in the memory attention module. memory_attention_num_attention_heads (`int`, *optional*, defaults to 1): Number of attention heads for each attention layer in the memory attention. memory_attention_downsample_rate (`int`, *optional*, defaults to 1): The downsample rate for the attention layers. memory_attention_mlp_hidden_size (`int`, *optional*, defaults to 2048): The dimension of the feedforward network in the memory attention module. memory_attention_mlp_hidden_act (`str`, *optional*, defaults to `"relu"`): The non-linear activation function in the feedforward network in the memory attention module. memory_attention_dropout (`float`, *optional*, defaults to 0.1): The dropout rate for the memory attention module. memory_attention_rope_theta (`float`, *optional*, defaults to 10000): The Rope theta parameter. memory_attention_rope_feat_sizes (`Tuple[int, int]`, *optional*, defaults to `[64, 64]`): The feature sizes for the Rope positional encoding. memory_attention_rope_k_sizes (`List[int]`, *optional*, defaults to `[16, 16]`): The key feature sizes for the RoPE positional encoding in memory attention. memory_attention_rope_dropout (`float`, *optional*, defaults to 0.1): The dropout rate for the Rope positional encoding. perceiver_resampler_num_latents (`int`, *optional*, defaults to 256): The number of 1D latent tokens in the perceiver resampler. perceiver_resampler_num_latents_2d (`int`, *optional*, defaults to 256): The number of 2D latent tokens in the perceiver resampler. perceiver_resampler_hidden_size (`int`, *optional*, defaults to 64): The hidden size of the perceiver resampler. perceiver_resampler_mlp_intermediate_size (`int`, *optional*, defaults to 256): The intermediate size of the feedforward network in the perceiver resampler. perceiver_resampler_num_attention_heads (`int`, *optional*, defaults to 1): The number of attention heads in the perceiver resampler. perceiver_resampler_attention_head_dim (`int`, *optional*, defaults to 64): The dimension of each attention head in the perceiver resampler. perceiver_resampler_num_layers (`int`, *optional*, defaults to 2): The number of layers in the perceiver resampler. perceiver_resampler_hidden_dropout (`float`, *optional*, defaults to 0.0): The dropout rate for the hidden layers in the perceiver resampler. perceiver_resampler_attention_dropout (`float`, *optional*, defaults to 0.0): The dropout rate for the attention layers in the perceiver resampler. memory_encoder_hidden_size (`int`, *optional*, defaults to 256): Dimensionality of the memory encoder hidden states. memory_encoder_output_channels (`int`, *optional*, defaults to 64): The number of output channels for the memory encoder. mask_downsampler_embed_dim (`int`, *optional*, defaults to 256): The dimension of the mask downsampler embedding. memory_fuser_intermediate_dim (`int`, *optional*, defaults to 1024): The intermediate dimension of the memory fuser feedforward network. mask_downsampler_kernel_size (`int`, *optional*, defaults to 3): The kernel size for the mask downsampler. mask_downsampler_stride (`int`, *optional*, defaults to 2): The stride for the mask downsampler. mask_downsampler_padding (`int`, *optional*, defaults to 1): The padding for the mask downsampler. mask_downsampler_total_stride (`int`, *optional*, defaults to 16): The total stride for the mask downsampler. mask_downsampler_hidden_act (`str`, *optional*, defaults to `"gelu"`): The non-linear activation function in the mask downsampler. memory_fuser_num_layers (`int`, *optional*, defaults to 2): The number of layers in the memory fuser. memory_fuser_embed_dim (`int`, *optional*, defaults to 256): The dimension of the memory fuser embedding. memory_fuser_kernel_size (`int`, *optional*, defaults to 7): The kernel size for the memory fuser. memory_fuser_padding (`int`, *optional*, defaults to 3): The padding for the memory fuser. memory_fuser_layer_scale_init_value (`float`, *optional*, defaults to 1e-06): The initial value for the layer scale in the memory fuser. memory_fuser_hidden_act (`str`, *optional*, defaults to `"gelu"`): The non-linear activation function in the memory fuser. Example: ```python >>> from transformers import ( ... EdgeTamVisionConfig, ... EdgeTamVideoPromptEncoderConfig, ... EdgeTamVideoMaskDecoderConfig, ... EdgeTamVideoModel, ... EdgeTamVideoConfig, ... ) >>> # Initializing a EdgeTamVideoConfig with `"facebook/edgetam.1_hiera_tiny"` style configuration >>> configuration = EdgeTamVideoConfig() >>> # Initializing a EdgeTamVideoModel (with random weights) from the `"facebook/edgetam.1_hiera_tiny"` style configuration >>> model = EdgeTamVideoModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config >>> # We can also initialize a EdgeTamConfig from a EdgeTamVisionConfig, EdgeTamPromptEncoderConfig, and EdgeTamMaskDecoderConfig >>> # Initializing EDGETAM vision encoder, memory attention, and memory encoder configurations >>> vision_config = EdgeTamVisionConfig() >>> prompt_encoder_config = EdgeTamVideoPromptEncoderConfig() >>> mask_decoder_config = EdgeTamVideoMaskDecoderConfig() >>> config = EdgeTamVideoConfig(vision_config, prompt_encoder_config, mask_decoder_config) ```""" model_type = "edgetam_video" sub_configs = { "vision_config": AutoConfig, "prompt_encoder_config": EdgeTamVideoPromptEncoderConfig, "mask_decoder_config": EdgeTamVideoMaskDecoderConfig, } def __init__( self, vision_config=None, prompt_encoder_config=None, mask_decoder_config=None, initializer_range=0.02, num_maskmem=7, image_size=1024, sigmoid_scale_for_mem_enc=20.0, sigmoid_bias_for_mem_enc=-10.0, enable_occlusion_spatial_embedding=True, multimask_output_in_sam=True, multimask_min_pt_num=0, multimask_max_pt_num=1, multimask_output_for_tracking=True, max_object_pointers_in_encoder=16, max_cond_frame_num=-1, enable_temporal_pos_encoding_for_object_pointers=True, # memory attention memory_attention_hidden_size=256, memory_attention_num_layers=2, memory_attention_num_attention_heads=1, memory_attention_downsample_rate=1, memory_attention_mlp_hidden_size=2048, memory_attention_mlp_hidden_act="relu", memory_attention_dropout=0.1, memory_attention_rope_theta=10000, memory_attention_rope_feat_sizes=None, memory_attention_rope_k_sizes=None, memory_attention_rope_dropout=0.1, # spatial perceiver resampler perceiver_resampler_num_latents=256, perceiver_resampler_num_latents_2d=256, perceiver_resampler_hidden_size=64, perceiver_resampler_mlp_intermediate_size=256, perceiver_resampler_num_attention_heads=1, perceiver_resampler_attention_head_dim=64, perceiver_resampler_num_layers=2, perceiver_resampler_hidden_dropout=0.0, perceiver_resampler_attention_dropout=0.0, # memory encoder memory_encoder_hidden_size=256, memory_encoder_output_channels=64, mask_downsampler_embed_dim=256, memory_fuser_intermediate_dim=1024, mask_downsampler_kernel_size=3, mask_downsampler_stride=2, mask_downsampler_padding=1, mask_downsampler_total_stride=16, mask_downsampler_hidden_act="gelu", memory_fuser_num_layers=2, memory_fuser_embed_dim=256, memory_fuser_kernel_size=7, memory_fuser_padding=3, memory_fuser_layer_scale_init_value=1e-6, memory_fuser_hidden_act="gelu", **kwargs, ): super().__init__(**kwargs) vision_config = vision_config if vision_config is not None else {} prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {} mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {} memory_attention_rope_feat_sizes = ( [64, 64] if memory_attention_rope_feat_sizes is None else memory_attention_rope_feat_sizes ) memory_attention_rope_k_sizes = ( [16, 16] if memory_attention_rope_k_sizes is None else memory_attention_rope_k_sizes ) if isinstance(vision_config, dict): vision_config["model_type"] = vision_config.get("model_type", "sam2_vision_model") vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config) if isinstance(prompt_encoder_config, EdgeTamVideoPromptEncoderConfig): prompt_encoder_config = prompt_encoder_config.to_dict() if isinstance(mask_decoder_config, EdgeTamVideoMaskDecoderConfig): mask_decoder_config = mask_decoder_config.to_dict() self.vision_config = vision_config self.prompt_encoder_config = EdgeTamVideoPromptEncoderConfig(**prompt_encoder_config) self.mask_decoder_config = EdgeTamVideoMaskDecoderConfig(**mask_decoder_config) self.initializer_range = initializer_range self.num_maskmem = num_maskmem # default 1 input frame + 6 previous frames self.image_size = image_size self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc # scale factor for mask sigmoid prob self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc # bias factor for mask sigmoid prob self.enable_occlusion_spatial_embedding = enable_occlusion_spatial_embedding self.multimask_output_in_sam = multimask_output_in_sam self.multimask_min_pt_num = multimask_min_pt_num self.multimask_max_pt_num = multimask_max_pt_num self.multimask_output_for_tracking = multimask_output_for_tracking self.max_object_pointers_in_encoder = max_object_pointers_in_encoder self.max_cond_frame_num = max_cond_frame_num self.enable_temporal_pos_encoding_for_object_pointers = enable_temporal_pos_encoding_for_object_pointers # memory attention self.memory_attention_hidden_size = memory_attention_hidden_size self.memory_attention_num_layers = memory_attention_num_layers self.memory_attention_num_attention_heads = memory_attention_num_attention_heads self.memory_attention_downsample_rate = memory_attention_downsample_rate self.memory_attention_mlp_hidden_size = memory_attention_mlp_hidden_size self.memory_attention_mlp_hidden_act = memory_attention_mlp_hidden_act self.memory_attention_dropout = memory_attention_dropout self.memory_attention_rope_theta = memory_attention_rope_theta self.memory_attention_rope_feat_sizes = memory_attention_rope_feat_sizes self.memory_attention_rope_k_sizes = memory_attention_rope_k_sizes self.memory_attention_rope_dropout = memory_attention_rope_dropout # spatial perceiver resampler self.perceiver_resampler_num_latents = perceiver_resampler_num_latents self.perceiver_resampler_num_latents_2d = perceiver_resampler_num_latents_2d self.perceiver_resampler_hidden_size = perceiver_resampler_hidden_size self.perceiver_resampler_mlp_intermediate_size = perceiver_resampler_mlp_intermediate_size self.perceiver_resampler_attention_head_dim = perceiver_resampler_attention_head_dim self.perceiver_resampler_num_attention_heads = perceiver_resampler_num_attention_heads self.perceiver_resampler_num_layers = perceiver_resampler_num_layers self.perceiver_resampler_hidden_dropout = perceiver_resampler_hidden_dropout self.perceiver_resampler_attention_dropout = perceiver_resampler_attention_dropout # memory encoder self.memory_encoder_hidden_size = memory_encoder_hidden_size self.memory_encoder_output_channels = memory_encoder_output_channels self.mask_downsampler_embed_dim = mask_downsampler_embed_dim self.mask_downsampler_kernel_size = mask_downsampler_kernel_size self.mask_downsampler_stride = mask_downsampler_stride self.mask_downsampler_padding = mask_downsampler_padding self.mask_downsampler_total_stride = mask_downsampler_total_stride self.mask_downsampler_hidden_act = mask_downsampler_hidden_act self.memory_fuser_num_layers = memory_fuser_num_layers self.memory_fuser_embed_dim = memory_fuser_embed_dim self.memory_fuser_intermediate_dim = memory_fuser_intermediate_dim self.memory_fuser_kernel_size = memory_fuser_kernel_size self.memory_fuser_padding = memory_fuser_padding self.memory_fuser_layer_scale_init_value = memory_fuser_layer_scale_init_value self.memory_fuser_hidden_act = memory_fuser_hidden_act __all__ = ["EdgeTamVideoMaskDecoderConfig", "EdgeTamVideoPromptEncoderConfig", "EdgeTamVideoConfig"]
EdgeTamVideoConfig
python
psf__black
src/black/report.py
{ "start": 244, "end": 354 }
class ____(UserWarning): """Raised when reformatted code is the same as source.""" @dataclass
NothingChanged
python
sympy__sympy
sympy/physics/vector/dyadic.py
{ "start": 214, "end": 18042 }
class ____(Printable, EvalfMixin): """A Dyadic object. See: https://en.wikipedia.org/wiki/Dyadic_tensor Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill A more powerful way to represent a rigid body's inertia. While it is more complex, by choosing Dyadic components to be in body fixed basis vectors, the resulting matrix is equivalent to the inertia tensor. """ is_number = False def __init__(self, inlist): """ Just like Vector's init, you should not call this unless creating a zero dyadic. zd = Dyadic(0) Stores a Dyadic as a list of lists; the inner list has the measure number and the two unit vectors; the outerlist holds each unique unit vector pair. """ self.args = [] if inlist == 0: inlist = [] while len(inlist) != 0: added = 0 for i, v in enumerate(self.args): if ((str(inlist[0][1]) == str(self.args[i][1])) and (str(inlist[0][2]) == str(self.args[i][2]))): self.args[i] = (self.args[i][0] + inlist[0][0], inlist[0][1], inlist[0][2]) inlist.remove(inlist[0]) added = 1 break if added != 1: self.args.append(inlist[0]) inlist.remove(inlist[0]) i = 0 # This code is to remove empty parts from the list while i < len(self.args): if ((self.args[i][0] == 0) | (self.args[i][1] == 0) | (self.args[i][2] == 0)): self.args.remove(self.args[i]) i -= 1 i += 1 @property def func(self): """Returns the class Dyadic. """ return Dyadic def __add__(self, other): """The add operator for Dyadic. """ other = _check_dyadic(other) return Dyadic(self.args + other.args) __radd__ = __add__ def __mul__(self, other): """Multiplies the Dyadic by a sympifyable expression. Parameters ========== other : Sympafiable The scalar to multiply this Dyadic with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> d = outer(N.x, N.x) >>> 5 * d 5*(N.x|N.x) """ newlist = list(self.args) other = sympify(other) for i in range(len(newlist)): newlist[i] = (other * newlist[i][0], newlist[i][1], newlist[i][2]) return Dyadic(newlist) __rmul__ = __mul__ def dot(self, other): """The inner product operator for a Dyadic and a Dyadic or Vector. Parameters ========== other : Dyadic or Vector The other Dyadic or Vector to take the inner product with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> D1 = outer(N.x, N.y) >>> D2 = outer(N.y, N.y) >>> D1.dot(D2) (N.x|N.y) >>> D1.dot(N.y) N.x """ from sympy.physics.vector.vector import Vector, _check_vector if isinstance(other, Dyadic): other = _check_dyadic(other) ol = Dyadic(0) for v in self.args: for v2 in other.args: ol += v[0] * v2[0] * (v[2].dot(v2[1])) * (v[1].outer(v2[2])) else: other = _check_vector(other) ol = Vector(0) for v in self.args: ol += v[0] * v[1] * (v[2].dot(other)) return ol # NOTE : supports non-advertised Dyadic & Dyadic, Dyadic & Vector notation __and__ = dot def __truediv__(self, other): """Divides the Dyadic by a sympifyable expression. """ return self.__mul__(1 / other) def __eq__(self, other): """Tests for equality. Is currently weak; needs stronger comparison testing """ if other == 0: other = Dyadic(0) other = _check_dyadic(other) if (self.args == []) and (other.args == []): return True elif (self.args == []) or (other.args == []): return False return set(self.args) == set(other.args) def __ne__(self, other): return not self == other def __neg__(self): return self * -1 def _latex(self, printer): ar = self.args # just to shorten things if len(ar) == 0: return str(0) ol = [] # output list, to be concatenated to a string for v in ar: # if the coef of the dyadic is 1, we skip the 1 if v[0] == 1: ol.append(' + ' + printer._print(v[1]) + r"\otimes " + printer._print(v[2])) # if the coef of the dyadic is -1, we skip the 1 elif v[0] == -1: ol.append(' - ' + printer._print(v[1]) + r"\otimes " + printer._print(v[2])) # If the coefficient of the dyadic is not 1 or -1, # we might wrap it in parentheses, for readability. elif v[0] != 0: arg_str = printer._print(v[0]) if isinstance(v[0], Add): arg_str = '(%s)' % arg_str if arg_str.startswith('-'): arg_str = arg_str[1:] str_start = ' - ' else: str_start = ' + ' ol.append(str_start + arg_str + printer._print(v[1]) + r"\otimes " + printer._print(v[2])) outstr = ''.join(ol) if outstr.startswith(' + '): outstr = outstr[3:] elif outstr.startswith(' '): outstr = outstr[1:] return outstr def _pretty(self, printer): e = self class Fake: baseline = 0 def render(self, *args, **kwargs): ar = e.args # just to shorten things mpp = printer if len(ar) == 0: return str(0) bar = "\N{CIRCLED TIMES}" if printer._use_unicode else "|" ol = [] # output list, to be concatenated to a string for v in ar: # if the coef of the dyadic is 1, we skip the 1 if v[0] == 1: ol.extend([" + ", mpp.doprint(v[1]), bar, mpp.doprint(v[2])]) # if the coef of the dyadic is -1, we skip the 1 elif v[0] == -1: ol.extend([" - ", mpp.doprint(v[1]), bar, mpp.doprint(v[2])]) # If the coefficient of the dyadic is not 1 or -1, # we might wrap it in parentheses, for readability. elif v[0] != 0: if isinstance(v[0], Add): arg_str = mpp._print( v[0]).parens()[0] else: arg_str = mpp.doprint(v[0]) if arg_str.startswith("-"): arg_str = arg_str[1:] str_start = " - " else: str_start = " + " ol.extend([str_start, arg_str, " ", mpp.doprint(v[1]), bar, mpp.doprint(v[2])]) outstr = "".join(ol) if outstr.startswith(" + "): outstr = outstr[3:] elif outstr.startswith(" "): outstr = outstr[1:] return outstr return Fake() def __rsub__(self, other): return (-1 * self) + other def _sympystr(self, printer): """Printing method. """ ar = self.args # just to shorten things if len(ar) == 0: return printer._print(0) ol = [] # output list, to be concatenated to a string for v in ar: # if the coef of the dyadic is 1, we skip the 1 if v[0] == 1: ol.append(' + (' + printer._print(v[1]) + '|' + printer._print(v[2]) + ')') # if the coef of the dyadic is -1, we skip the 1 elif v[0] == -1: ol.append(' - (' + printer._print(v[1]) + '|' + printer._print(v[2]) + ')') # If the coefficient of the dyadic is not 1 or -1, # we might wrap it in parentheses, for readability. elif v[0] != 0: arg_str = printer._print(v[0]) if isinstance(v[0], Add): arg_str = "(%s)" % arg_str if arg_str[0] == '-': arg_str = arg_str[1:] str_start = ' - ' else: str_start = ' + ' ol.append(str_start + arg_str + '*(' + printer._print(v[1]) + '|' + printer._print(v[2]) + ')') outstr = ''.join(ol) if outstr.startswith(' + '): outstr = outstr[3:] elif outstr.startswith(' '): outstr = outstr[1:] return outstr def __sub__(self, other): """The subtraction operator. """ return self.__add__(other * -1) def cross(self, other): """Returns the dyadic resulting from the dyadic vector cross product: Dyadic x Vector. Parameters ========== other : Vector Vector to cross with. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, cross >>> N = ReferenceFrame('N') >>> d = outer(N.x, N.x) >>> cross(d, N.y) (N.x|N.z) """ from sympy.physics.vector.vector import _check_vector other = _check_vector(other) ol = Dyadic(0) for v in self.args: ol += v[0] * (v[1].outer((v[2].cross(other)))) return ol # NOTE : supports non-advertised Dyadic ^ Vector notation __xor__ = cross def express(self, frame1, frame2=None): """Expresses this Dyadic in alternate frame(s) The first frame is the list side expression, the second frame is the right side; if Dyadic is in form A.x|B.y, you can express it in two different frames. If no second frame is given, the Dyadic is expressed in only one frame. Calls the global express function Parameters ========== frame1 : ReferenceFrame The frame to express the left side of the Dyadic in frame2 : ReferenceFrame If provided, the frame to express the right side of the Dyadic in Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> N = ReferenceFrame('N') >>> q = dynamicsymbols('q') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> d = outer(N.x, N.x) >>> d.express(B, N) cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x) """ from sympy.physics.vector.functions import express return express(self, frame1, frame2) def to_matrix(self, reference_frame, second_reference_frame=None): """Returns the matrix form of the dyadic with respect to one or two reference frames. Parameters ---------- reference_frame : ReferenceFrame The reference frame that the rows and columns of the matrix correspond to. If a second reference frame is provided, this only corresponds to the rows of the matrix. second_reference_frame : ReferenceFrame, optional, default=None The reference frame that the columns of the matrix correspond to. Returns ------- matrix : ImmutableMatrix, shape(3,3) The matrix that gives the 2D tensor form. Examples ======== >>> from sympy import symbols, trigsimp >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.mechanics import inertia >>> Ixx, Iyy, Izz, Ixy, Iyz, Ixz = symbols('Ixx, Iyy, Izz, Ixy, Iyz, Ixz') >>> N = ReferenceFrame('N') >>> inertia_dyadic = inertia(N, Ixx, Iyy, Izz, Ixy, Iyz, Ixz) >>> inertia_dyadic.to_matrix(N) Matrix([ [Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]]) >>> beta = symbols('beta') >>> A = N.orientnew('A', 'Axis', (beta, N.x)) >>> trigsimp(inertia_dyadic.to_matrix(A)) Matrix([ [ Ixx, Ixy*cos(beta) + Ixz*sin(beta), -Ixy*sin(beta) + Ixz*cos(beta)], [ Ixy*cos(beta) + Ixz*sin(beta), Iyy*cos(2*beta)/2 + Iyy/2 + Iyz*sin(2*beta) - Izz*cos(2*beta)/2 + Izz/2, -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2], [-Ixy*sin(beta) + Ixz*cos(beta), -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2, -Iyy*cos(2*beta)/2 + Iyy/2 - Iyz*sin(2*beta) + Izz*cos(2*beta)/2 + Izz/2]]) """ if second_reference_frame is None: second_reference_frame = reference_frame return Matrix([i.dot(self).dot(j) for i in reference_frame for j in second_reference_frame]).reshape(3, 3) def doit(self, **hints): """Calls .doit() on each term in the Dyadic""" return sum([Dyadic([(v[0].doit(**hints), v[1], v[2])]) for v in self.args], Dyadic(0)) def dt(self, frame): """Take the time derivative of this Dyadic in a frame. This function calls the global time_derivative method Parameters ========== frame : ReferenceFrame The frame to take the time derivative in Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> N = ReferenceFrame('N') >>> q = dynamicsymbols('q') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> d = outer(N.x, N.x) >>> d.dt(B) - q'*(N.y|N.x) - q'*(N.x|N.y) """ from sympy.physics.vector.functions import time_derivative return time_derivative(self, frame) def simplify(self): """Returns a simplified Dyadic.""" out = Dyadic(0) for v in self.args: out += Dyadic([(v[0].simplify(), v[1], v[2])]) return out def subs(self, *args, **kwargs): """Substitution on the Dyadic. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import Symbol >>> N = ReferenceFrame('N') >>> s = Symbol('s') >>> a = s*(N.x|N.x) >>> a.subs({s: 2}) 2*(N.x|N.x) """ return sum([Dyadic([(v[0].subs(*args, **kwargs), v[1], v[2])]) for v in self.args], Dyadic(0)) def applyfunc(self, f): """Apply a function to each component of a Dyadic.""" if not callable(f): raise TypeError("`f` must be callable.") out = Dyadic(0) for a, b, c in self.args: out += f(a) * (b.outer(c)) return out def _eval_evalf(self, prec): if not self.args: return self new_args = [] dps = prec_to_dps(prec) for inlist in self.args: new_inlist = list(inlist) new_inlist[0] = inlist[0].evalf(n=dps) new_args.append(tuple(new_inlist)) return Dyadic(new_args) def xreplace(self, rule): """ Replace occurrences of objects within the measure numbers of the Dyadic. Parameters ========== rule : dict-like Expresses a replacement rule. Returns ======= Dyadic Result of the replacement. Examples ======== >>> from sympy import symbols, pi >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> D = outer(N.x, N.x) >>> x, y, z = symbols('x y z') >>> ((1 + x*y) * D).xreplace({x: pi}) (pi*y + 1)*(N.x|N.x) >>> ((1 + x*y) * D).xreplace({x: pi, y: 2}) (1 + 2*pi)*(N.x|N.x) Replacements occur only if an entire node in the expression tree is matched: >>> ((x*y + z) * D).xreplace({x*y: pi}) (z + pi)*(N.x|N.x) >>> ((x*y*z) * D).xreplace({x*y: pi}) x*y*z*(N.x|N.x) """ new_args = [] for inlist in self.args: new_inlist = list(inlist) new_inlist[0] = new_inlist[0].xreplace(rule) new_args.append(tuple(new_inlist)) return Dyadic(new_args) def _check_dyadic(other): if not isinstance(other, Dyadic): raise TypeError('A Dyadic must be supplied') return other
Dyadic
python
scrapy__scrapy
tests/test_commands.py
{ "start": 3652, "end": 12075 }
class ____(scrapy.Spider): name = 'aiosp' custom_settings = {} async def start(self): await asyncio.sleep(0.01) self.logger.debug('It works!') return yield """) self._append_settings(proj_mod_path, "LOG_LEVEL = 'DEBUG'\n") @staticmethod def _append_settings(proj_mod_path: Path, text: str) -> None: """Add text to the end of the project settings.py.""" with (proj_mod_path / "settings.py").open("a", encoding="utf-8") as f: f.write(text) @staticmethod def _replace_custom_settings( proj_mod_path: Path, spider_name: str, text: str ) -> None: """Replace custom_settings in the given spider file with the given text.""" spider_path = proj_mod_path / "spiders" / f"{spider_name}.py" with spider_path.open("r+", encoding="utf-8") as f: content = f.read() content = content.replace( "custom_settings = {}", f"custom_settings = {text}" ) f.seek(0) f.write(content) f.truncate() def _assert_spider_works(self, msg: str, proj_path: Path, *args: str) -> None: """The command uses the expected *CrawlerProcess, the spider works.""" _, _, err = proc(self.name, *args, cwd=proj_path) assert msg in err assert "It works!" in err assert "Spider closed (finished)" in err def _assert_spider_asyncio_fail( self, msg: str, proj_path: Path, *args: str ) -> None: """The command uses the expected *CrawlerProcess, the spider fails to use asyncio.""" _, _, err = proc(self.name, *args, cwd=proj_path) assert msg in err assert "no running event loop" in err def test_project_settings(self, proj_path: Path) -> None: """The reactor is set via the project default settings (to the asyncio value). AsyncCrawlerProcess, the asyncio reactor, both spiders work.""" for spider in ["sp", "aiosp"]: self._assert_spider_works(self.ASYNC_MSG, proj_path, spider) def test_cmdline_asyncio(self, proj_path: Path) -> None: """The reactor is set via the command line to the asyncio value. AsyncCrawlerProcess, the asyncio reactor, both spiders work.""" for spider in ["sp", "aiosp"]: self._assert_spider_works( self.ASYNC_MSG, proj_path, spider, "-s", f"TWISTED_REACTOR={_asyncio_reactor_path}", ) def test_project_settings_explicit_asyncio(self, proj_path: Path) -> None: """The reactor explicitly is set via the project settings to the asyncio value. AsyncCrawlerProcess, the asyncio reactor, both spiders work.""" self._append_settings( proj_path / self.project_name, f"TWISTED_REACTOR = '{_asyncio_reactor_path}'\n", ) for spider in ["sp", "aiosp"]: self._assert_spider_works(self.ASYNC_MSG, proj_path, spider) def test_cmdline_empty(self, proj_path: Path) -> None: """The reactor is set via the command line to the empty value. CrawlerProcess, the default reactor, only the normal spider works.""" self._assert_spider_works( self.NORMAL_MSG, proj_path, "sp", "-s", "TWISTED_REACTOR=" ) self._assert_spider_asyncio_fail( self.NORMAL_MSG, proj_path, "aiosp", "-s", "TWISTED_REACTOR=" ) def test_project_settings_empty(self, proj_path: Path) -> None: """The reactor is set via the project settings to the empty value. CrawlerProcess, the default reactor, only the normal spider works.""" self._append_settings(proj_path / self.project_name, "TWISTED_REACTOR = None\n") self._assert_spider_works(self.NORMAL_MSG, proj_path, "sp") self._assert_spider_asyncio_fail( self.NORMAL_MSG, proj_path, "aiosp", "-s", "TWISTED_REACTOR=" ) def test_spider_settings_asyncio(self, proj_path: Path) -> None: """The reactor is set via the spider settings to the asyncio value. AsyncCrawlerProcess, the asyncio reactor, both spiders work.""" for spider in ["sp", "aiosp"]: self._replace_custom_settings( proj_path / self.project_name, spider, f"{{'TWISTED_REACTOR': '{_asyncio_reactor_path}'}}", ) self._assert_spider_works(self.ASYNC_MSG, proj_path, spider) def test_spider_settings_asyncio_cmdline_empty(self, proj_path: Path) -> None: """The reactor is set via the spider settings to the asyncio value and via command line to the empty value. The command line value takes precedence so the spider settings don't matter. CrawlerProcess, the default reactor, only the normal spider works.""" for spider in ["sp", "aiosp"]: self._replace_custom_settings( proj_path / self.project_name, spider, f"{{'TWISTED_REACTOR': '{_asyncio_reactor_path}'}}", ) self._assert_spider_works( self.NORMAL_MSG, proj_path, "sp", "-s", "TWISTED_REACTOR=" ) self._assert_spider_asyncio_fail( self.NORMAL_MSG, proj_path, "aiosp", "-s", "TWISTED_REACTOR=" ) def test_project_empty_spider_settings_asyncio(self, proj_path: Path) -> None: """The reactor is set via the project settings to the empty value and via the spider settings to the asyncio value. CrawlerProcess is chosen based on the project settings, but the asyncio reactor is chosen based on the spider settings. CrawlerProcess, the asyncio reactor, both spiders work.""" self._append_settings(proj_path / self.project_name, "TWISTED_REACTOR = None\n") for spider in ["sp", "aiosp"]: self._replace_custom_settings( proj_path / self.project_name, spider, f"{{'TWISTED_REACTOR': '{_asyncio_reactor_path}'}}", ) self._assert_spider_works(self.NORMAL_MSG, proj_path, spider) def test_project_asyncio_spider_settings_select(self, proj_path: Path) -> None: """The reactor is set via the project settings to the asyncio value and via the spider settings to the select value. AsyncCrawlerProcess is chosen based on the project settings, and the conflicting reactor setting in the spider settings causes an exception. AsyncCrawlerProcess, the asyncio reactor, both spiders produce a mismatched reactor exception.""" self._append_settings( proj_path / self.project_name, f"TWISTED_REACTOR = '{_asyncio_reactor_path}'\n", ) for spider in ["sp", "aiosp"]: self._replace_custom_settings( proj_path / self.project_name, spider, "{'TWISTED_REACTOR': 'twisted.internet.selectreactor.SelectReactor'}", ) _, _, err = proc(self.name, spider, cwd=proj_path) assert self.ASYNC_MSG in err assert ( "The installed reactor (twisted.internet.asyncioreactor.AsyncioSelectorReactor)" " does not match the requested one" " (twisted.internet.selectreactor.SelectReactor)" ) in err def test_project_asyncio_spider_settings_select_forced( self, proj_path: Path ) -> None: """The reactor is set via the project settings to the asyncio value and via the spider settings to the select value, CrawlerProcess is forced via the project settings. The reactor is chosen based on the spider settings. CrawlerProcess, the select reactor, only the normal spider works.""" self._append_settings( proj_path / self.project_name, "FORCE_CRAWLER_PROCESS = True\n" ) for spider in ["sp", "aiosp"]: self._replace_custom_settings( proj_path / self.project_name, spider, "{'TWISTED_REACTOR': 'twisted.internet.selectreactor.SelectReactor'}", ) self._assert_spider_works(self.NORMAL_MSG, proj_path, "sp") self._assert_spider_asyncio_fail(self.NORMAL_MSG, proj_path, "aiosp")
MySpider
python
numba__numba
numba/core/types/containers.py
{ "start": 3238, "end": 4577 }
class ____(ConstSized, Hashable): """ The base class for all tuple types (with a known size). """ @classmethod def from_types(cls, tys, pyclass=None): """ Instantiate the right tuple type for the given element types. """ if pyclass is not None and pyclass is not tuple: # A subclass => is it a namedtuple? assert issubclass(pyclass, tuple) if hasattr(pyclass, "_asdict"): tys = tuple(map(unliteral, tys)) homogeneous = is_homogeneous(*tys) if homogeneous: return NamedUniTuple(tys[0], len(tys), pyclass) else: return NamedTuple(tys, pyclass) else: dtype = utils.unified_function_type(tys) if dtype is not None: return UniTuple(dtype, len(tys)) # non-named tuple homogeneous = is_homogeneous(*tys) if homogeneous: return cls._make_homogeneous_tuple(tys[0], len(tys)) else: return cls._make_heterogeneous_tuple(tys) @classmethod def _make_homogeneous_tuple(cls, dtype, count): return UniTuple(dtype, count) @classmethod def _make_heterogeneous_tuple(cls, tys): return Tuple(tys)
BaseTuple
python
docker__docker-py
tests/integration/errors_test.py
{ "start": 104, "end": 632 }
class ____(BaseAPIIntegrationTest): def test_api_error_parses_json(self): container = self.client.create_container(TEST_IMG, ['sleep', '10']) self.client.start(container['Id']) with pytest.raises(APIError) as cm: self.client.remove_container(container['Id']) explanation = cm.value.explanation.lower() assert 'stop the container before' in explanation assert '{"message":' not in explanation self.client.remove_container(container['Id'], force=True)
ErrorsTest
python
django-import-export__django-import-export
tests/core/tests/admin_integration/test_import_errors.py
{ "start": 10244, "end": 13103 }
class ____(AdminTestMixin, TestCase): # issue 1724 def setUp(self): super().setUp() self.csvdata = "id,name,author\r\n" "1,Ulysses,666\r\n" self.filedata = StringIO(self.csvdata) self.data = {"format": "0", "import_file": self.filedata} self._prepend_form_prefix(self.data) self.model_admin = BookAdmin(Book, AdminSite()) factory = RequestFactory() self.request = factory.post(self.book_import_url, self.data, follow=True) self.request.user = User.objects.create_user("admin1") def test_result_error_display_default(self): response = self.model_admin.import_action(self.request) response.render() content = response.content.decode() self.assertIn("import-error-display-message", content) self.assertIn( "Line number: 1 - Author matching query does not exist.", content, ) self.assertNotIn("import-error-display-row", content) self.assertNotIn("import-error-display-traceback", content) def test_result_error_display_message_only(self): self.model_admin.import_error_display = ("message",) response = self.model_admin.import_action(self.request) response.render() content = response.content.decode() self.assertIn( "Line number: 1 - Author matching query does not exist.", content, ) self.assertIn("import-error-display-message", content) self.assertNotIn("import-error-display-row", content) self.assertNotIn("import-error-display-traceback", content) def test_result_error_display_row_only(self): self.model_admin.import_error_display = ("row",) response = self.model_admin.import_action(self.request) response.render() content = response.content.decode() self.assertNotIn( "Line number: 1 - Author matching query does not exist.", content, ) self.assertNotIn("import-error-display-message", content) self.assertIn("import-error-display-row", content) self.assertNotIn("import-error-display-traceback", content) def test_result_error_display_traceback_only(self): self.model_admin.import_error_display = ("traceback",) response = self.model_admin.import_action(self.request) response.render() content = response.content.decode() self.assertNotIn( "Line number: 1 - Author matching query does not exist.", content, ) self.assertNotIn("import-error-display-message", content) self.assertNotIn("import-error-display-row", content) self.assertIn("import-error-display-traceback", content) self.assertIn("Traceback (most recent call last)", content)
TestImportErrorMessageFormat
python
django__django
tests/proxy_models/models.py
{ "start": 2550, "end": 2726 }
class ____(UserProxy, AnotherUserProxy): class Meta: proxy = True # We can still use `select_related()` to include related models in our # querysets.
MultiUserProxy
python
mlflow__mlflow
mlflow/types/responses_helpers.py
{ "start": 5705, "end": 6101 }
class ____(BaseModel): model_config = ConfigDict(extra="allow") type: str @model_validator(mode="after") def check_type(self) -> "Tool": if self.type == "function": FunctionTool(**self.model_dump()) elif self.type not in {"file_search", "computer_use", "web_search"}: warnings.warn(f"Invalid tool type: {self.type}") return self
Tool
python
ApeWorX__ape
src/ape_test/provider.py
{ "start": 3634, "end": 5242 }
class ____(EthereumTesterProvider): def __init__(self, config: "ApeTestConfig", chain_id: int): self.config = config self.chain_id = chain_id self._backend: Optional[ApeEVMBackend] = None self._ethereum_tester: Optional[EthereumTester] = None @property def ethereum_tester(self) -> EthereumTester: if self._ethereum_tester is None: self._backend = ApeEVMBackend(self.config, self.chain_id) self._ethereum_tester = EthereumTester(self._backend) return self._ethereum_tester @ethereum_tester.setter def ethereum_tester(self, value): self._ethereum_tester = value self._backend = value.backend @property def _batching_context(self): # type: ignore # TODO: Figure out correct way; remove this hack class MockBatchingContext: def get(self, *args, **kwargs): return None return MockBatchingContext() @property def backend(self) -> "ApeEVMBackend": if self._backend is None: self._backend = ApeEVMBackend(self.config, self.chain_id) self._ethereum_tester = EthereumTester(self._backend) return self._backend @backend.setter def backend(self, value): self._backend = value self._ethereum_tester = EthereumTester(self._backend) @cached_property def api_endpoints(self) -> dict: # type: ignore endpoints = {**API_ENDPOINTS} endpoints["eth"] = merge(endpoints["eth"], {"chainId": static_return(self.chain_id)}) return endpoints
ApeTester
python
getsentry__sentry
tests/sentry/core/endpoints/test_organization_avatar.py
{ "start": 338, "end": 756 }
class ____(OrganizationAvatarTestBase): def test_get(self) -> None: response = self.get_success_response(self.organization.slug) assert response.data["id"] == str(self.organization.id) assert response.data["avatar"]["avatarType"] == "letter_avatar" assert response.data["avatar"]["avatarUuid"] is None assert response.data["avatar"]["avatarUrl"] is None
OrganizationAvatarTest
python
run-llama__llama_index
llama-index-core/llama_index/core/ingestion/pipeline.py
{ "start": 4918, "end": 6013 }
class ____(str, Enum): """ Document de-duplication de-deduplication strategies work by comparing the hashes or ids stored in the document store. They require a document store to be set which must be persisted across pipeline runs. Attributes: UPSERTS: ('upserts') Use upserts to handle duplicates. Checks if the a document is already in the doc store based on its id. If it is not, or if the hash of the document is updated, it will update the document in the doc store and run the transformations. DUPLICATES_ONLY: ('duplicates_only') Only handle duplicates. Checks if the hash of a document is already in the doc store. Only then it will add the document to the doc store and run the transformations UPSERTS_AND_DELETE: ('upserts_and_delete') Use upserts and delete to handle duplicates. Like the upsert strategy but it will also delete non-existing documents from the doc store """ UPSERTS = "upserts" DUPLICATES_ONLY = "duplicates_only" UPSERTS_AND_DELETE = "upserts_and_delete"
DocstoreStrategy
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_emr_modify_cluster.py
{ "start": 1630, "end": 2864 }
class ____: def setup_method(self): args = {"owner": "airflow", "start_date": DEFAULT_DATE} self.mock_context = MagicMock() self.operator = EmrModifyClusterOperator( task_id="test_task", cluster_id="j-8989898989", step_concurrency_level=1, aws_conn_id="aws_default", dag=DAG("test_dag_id", schedule=None, default_args=args), ) def test_init(self): assert self.operator.cluster_id == "j-8989898989" assert self.operator.step_concurrency_level == 1 assert self.operator.aws_conn_id == "aws_default" def test_execute_returns_step_concurrency(self, mocked_hook_client): mocked_hook_client.modify_cluster.return_value = MODIFY_CLUSTER_SUCCESS_RETURN assert self.operator.execute(self.mock_context) == 1 def test_execute_returns_error(self, mocked_hook_client): mocked_hook_client.modify_cluster.return_value = MODIFY_CLUSTER_ERROR_RETURN with pytest.raises(AirflowException, match="Modify cluster failed"): self.operator.execute(self.mock_context) def test_template_fields(self): validate_template_fields(self.operator)
TestEmrModifyClusterOperator
python
walkccc__LeetCode
solutions/1973. Count Nodes Equal to Sum of Descendants/1973.py
{ "start": 96, "end": 500 }
class ____: def equalToDescendants(self, root: TreeNode | None) -> int: def dfs(root: TreeNode | None) -> T: if not root: return T(0, 0) left = dfs(root.left) right = dfs(root.right) return T(root.val + left.summ + right.summ, left.count + right.count + (1 if root.val == left.summ + right.summ else 0)) return dfs(root).count
Solution
python
tensorflow__tensorflow
tensorflow/core/function/trace_type/trace_type_test.py
{ "start": 1814, "end": 2113 }
class ____: """Helps test attrs collections.""" __attrs_attrs__ = (TestAttr('a'), TestAttr('b')) def __init__(self, a, b): self.a = a self.b = b def __eq__(self, other): return isinstance( other, TestAttrsClass) and self.a == other.a and self.b == other.b
TestAttrsClass
python
jazzband__django-oauth-toolkit
tests/test_authorization_code.py
{ "start": 81334, "end": 82390 }
class ____(BaseTest): def test_pre_auth_default_scopes(self): """ Test response for a valid client_id with response_type: code using default scopes """ self.client.login(username="test_user", password="123456") query_data = { "client_id": self.application.client_id, "response_type": "code", "state": "random_state_string", "redirect_uri": "http://example.org", } response = self.client.get(reverse("oauth2_provider:authorize"), data=query_data) self.assertEqual(response.status_code, 200) # check form is in context and form params are valid self.assertIn("form", response.context) form = response.context["form"] self.assertEqual(form["redirect_uri"].value(), "http://example.org") self.assertEqual(form["state"].value(), "random_state_string") self.assertEqual(form["scope"].value(), "read") self.assertEqual(form["client_id"].value(), self.application.client_id)
TestDefaultScopes
python
pandas-dev__pandas
asv_bench/benchmarks/groupby.py
{ "start": 6330, "end": 6824 }
class ____: def setup(self): arr = np.random.randint(-1 << 12, 1 << 12, (1 << 17, 5)) i = np.random.choice(len(arr), len(arr) * 5) arr = np.vstack((arr, arr[i])) i = np.random.permutation(len(arr)) arr = arr[i] self.cols = list("abcde") self.df = DataFrame(arr, columns=self.cols) self.df["jim"], self.df["joe"] = np.random.randn(2, len(self.df)) * 10 def time_overflow(self): self.df.groupby(self.cols).max()
Int64
python
wandb__wandb
wandb/sdk/internal/job_builder.py
{ "start": 2726, "end": 3246 }
class ____(TypedDict): id: str name: str def get_min_supported_for_source_dict( source: Union[GitSourceDict, ArtifactSourceDict, ImageSourceDict], ) -> Optional[Version]: """Get the minimum supported wandb version the source dict of wandb-job.json.""" min_seen = None for key in source: new_ver = SOURCE_KEYS_MIN_SUPPORTED_VERSION.get(key) if new_ver: if min_seen is None or new_ver < min_seen: min_seen = new_ver return min_seen
ArtifactInfoForJob
python
plotly__plotly.py
plotly/graph_objs/scattergl/selected/_textfont.py
{ "start": 233, "end": 2430 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scattergl.selected" _path_str = "scattergl.selected.textfont" _valid_props = {"color"} @property def color(self): """ Sets the text font color of selected points. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def _prop_descriptions(self): return """\ color Sets the text font color of selected points. """ def __init__(self, arg=None, color=None, **kwargs): """ Construct a new Textfont object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scattergl.selected.Textfont` color Sets the text font color of selected points. Returns ------- Textfont """ super().__init__("textfont") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.scattergl.selected.Textfont constructor must be a dict or an instance of :class:`plotly.graph_objs.scattergl.selected.Textfont`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Textfont
python
django__django
tests/prefetch_related/models.py
{ "start": 7199, "end": 7404 }
class ____(models.Model): name = models.CharField(max_length=50) boss = models.ForeignKey("self", models.SET_NULL, null=True, related_name="serfs") class Meta: ordering = ["id"]
Employee
python
pypa__hatch
tests/backend/builders/test_wheel.py
{ "start": 25147, "end": 25976 }
class ____: def test_default(self, isolation): builder = WheelBuilder(str(isolation)) assert builder.config.bypass_selection is False def test_correct(self, isolation): config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"bypass-selection": True}}}}}} builder = WheelBuilder(str(isolation), config=config) assert builder.config.bypass_selection is True def test_not_boolean(self, isolation): config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"bypass-selection": 9000}}}}}} builder = WheelBuilder(str(isolation), config=config) with pytest.raises( TypeError, match="Field `tool.hatch.build.targets.wheel.bypass-selection` must be a boolean" ): _ = builder.config.bypass_selection
TestBypassSelection
python
getsentry__sentry
src/sentry/relocation/api/endpoints/artifacts/details.py
{ "start": 1252, "end": 3891 }
class ____(Endpoint): owner = ApiOwner.HYBRID_CLOUD publish_status = { # TODO(getsentry/team-ospo#214): Stabilize before GA. "GET": ApiPublishStatus.EXPERIMENTAL, } permission_classes = (SuperuserOrStaffFeatureFlaggedPermission,) def get( self, request: Request, relocation_uuid: str, artifact_kind: str, file_name: str ) -> Response: """ Get a single relocation artifact. `````````````````````````````````````````````````` :pparam string relocation_uuid: a UUID identifying the relocation. :pparam string artifact_kind: one of `conf` | `in` | `out` | `findings`. :pparam string file_name: The name of the file itself. :auth: required """ logger.info("relocations.artifact.details.get.start", extra={"caller": request.user.id}) # TODO(schew2381): Remove the superuser reference below after feature flag is removed. # Must be superuser/staff AND have a `UserPermission` of `relocation.admin` to see access! if not has_elevated_mode(request): if has_staff_option(request.user): raise StaffRequired raise SuperuserRequired if not request.access.has_permission("relocation.admin"): raise PermissionDenied( "Cannot view relocation artifacts, as you do not have the appropriate permissions." ) try: relocation: Relocation = Relocation.objects.get(uuid=relocation_uuid) except Relocation.DoesNotExist: raise ResourceDoesNotExist file_path = f"runs/{relocation.uuid}/{artifact_kind}/{file_name}" relocation_storage = get_relocation_storage() if not relocation_storage.exists(file_path): raise ResourceDoesNotExist # TODO(azaslavsky): We can probably get all clever and stream these files, but it's not # necessary for now. with relocation_storage.open(file_path) as fp: if not file_name.endswith(".tar"): return self.respond({"contents": fp.read()}) unwrapped = unwrap_encrypted_export_tarball(fp) decryptor = GCPKMSDecryptor.from_bytes( orjson.dumps(get_default_crypto_key_version(), default=_orjson_default) ) plaintext_data_encryption_key = decryptor.decrypt_data_encryption_key(unwrapped) fernet = Fernet(plaintext_data_encryption_key) return self.respond( {"contents": fernet.decrypt(unwrapped.encrypted_json_blob).decode()} )
RelocationArtifactDetailsEndpoint
python
ethereum__web3.py
web3/middleware/base.py
{ "start": 4243, "end": 5714 }
class ____(Web3Middleware): @staticmethod @abstractmethod def build( w3: Union["AsyncWeb3[Any]", "Web3"], *args: Any, **kwargs: Any, ) -> Web3Middleware: """ Implementation should initialize the middleware class that implements it, load it with any of the necessary properties that it needs for processing, and curry for the ``w3`` argument since it isn't initially present when building the middleware. example implementation: ```py class MyMiddleware(Web3BuilderMiddleware): internal_property: str = None @staticmethod @curry def builder(user_provided_argument, w3): middleware = MyMiddleware(w3) middleware.internal_property = user_provided_argument return middleware def request_processor(self, method, params): ... def response_processor(self, method, response): ... construct_my_middleware = MyMiddleware.builder w3 = Web3(provider) my_middleware = construct_my_middleware("my argument") w3.middleware_onion.inject(my_middleware, layer=0) ``` """ raise NotImplementedError("Must be implemented by subclasses") # --- type definitions --- # Middleware = type[Web3Middleware] MiddlewareOnion = NamedElementOnion[str, Middleware]
Web3MiddlewareBuilder
python
pytorch__pytorch
test/functorch/test_vmap.py
{ "start": 3007, "end": 46213 }
class ____(TestCase): def test_non_tensor_output_raises(self): with self.assertRaisesRegex(ValueError, "got type <class 'float'>"): vmap(lambda x: 3.14)(torch.ones(3)) def multiple_outputs(x): return x, 3 with self.assertRaisesRegex(ValueError, "got type <class 'int'>"): vmap(multiple_outputs)(torch.ones(3)) def test_different_map_dim_size_raises(self): x = torch.randn(2) y = torch.randn(3) expected_msg = ( "Expected all tensors to have the same size in the mapped dimension" ) with self.assertRaisesRegex(ValueError, expected_msg): vmap(torch.mul)(x, y) with self.assertRaisesRegex(ValueError, expected_msg): vmap(lambda z: z[0] + z[1], in_dims=((0, 0),))((x, y)) with self.assertRaisesRegex(ValueError, expected_msg): vmap(lambda z: z["x"] + z["y"], in_dims=({"x": 0, "y": 0},))( {"x": x, "y": y} ) def test_func_with_no_inputs(self): expected_msg = "got no inputs" def foo(): return torch.randn(3) def bar(x): return torch.randn(3) with self.assertRaisesRegex(ValueError, expected_msg): vmap(foo)() with self.assertRaisesRegex(ValueError, expected_msg): vmap(bar)() def test_func_with_no_tensors(self): def foo(x): return torch.randn(3) with self.assertRaisesRegex(ValueError, "at least one Tensor"): vmap(foo, (None,))(1) def test_constant_function(self): output = vmap(lambda x: torch.tensor(3.14))(torch.ones(3)) self.assertEqual(output, torch.tensor([3.14, 3.14, 3.14])) def test_single_input(self): x = torch.randn(2, 3) def square(x): return x * x output = vmap(square)(x) self.assertEqual(output, x * x) def test_multiple_inputs(self): x = torch.randn(2, 3) y = torch.randn(2, 3) output = vmap(torch.mul)(x, y) self.assertEqual(output, x * y) def test_multiple_outputs(self): def foo(x): return x * x, x * x * x x = torch.randn(3) outputs = vmap(foo)(x) self.assertEqual(outputs[0], x * x) self.assertEqual(outputs[1], x * x * x) def test_multiple_outputs2(self): # This is the same thing as # def returns_tuple_of_tensors(x): # return x, x def returns_tuple_of_tensors(x): return (x, x) def returns_list_of_two_tensors(x): return [x, x] def returns_list_of_one_tensor(x): return [x] x = torch.randn(3) # should not throw vmap(returns_tuple_of_tensors)(x) vmap(returns_list_of_two_tensors)(x) vmap(returns_list_of_one_tensor)(x) def test_nested_with_same_map_dim(self): x = torch.randn(2, 3, 5) y = torch.randn(2, 3, 5) output = vmap(vmap(torch.mul))(x, y) self.assertEqual(output, x * y) output = vmap(vmap(vmap(torch.mul)))(x, y) self.assertEqual(output, x * y) def test_nested_with_diag_embed(self): # diag_embed requires special testing because it is registered with conditional functionalization. x = torch.randn(3, 3, 5) output = vmap(vmap(torch.diag_embed))(x) self.assertEqual(output, torch.diag_embed(x)) def test_nested_with_different_map_dim(self): x = torch.randn(2, 3) y = torch.randn(5, 3) output = vmap(lambda x: vmap(lambda y: x * y)(y))(x) self.assertEqual(output.shape, (2, 5, 3)) self.assertEqual(output, x.view(2, 1, 3) * y) z = torch.randn(7, 3) output = vmap(lambda x: vmap(lambda y: vmap(lambda z: x * y * z)(z))(y))(x) self.assertEqual(output.shape, (2, 5, 7, 3)) self.assertEqual(output, x.view(2, 1, 1, 3) * y.view(5, 1, 3) * z) def test_noop_in_inner_vmap(self): x = torch.randn(3) y = torch.randn(5) output = vmap(lambda x: vmap(lambda y: x)(y))(x) self.assertEqual(output, x.view(3, 1).expand(3, 5)) def test_checkpoint(self): A = torch.randn((3, 8, 8), dtype=torch.float64, requires_grad=True) def get_grad(checkpoint): A.grad = None def get_loss(A): ortho_A, _ = torch.func.vmap(torch.linalg.qr)(A) return torch.sum(ortho_A) if checkpoint: loss = torch.utils.checkpoint.checkpoint( get_loss, A, use_reentrant=False ) else: loss = get_loss(A) loss.backward() return A.grad expected = get_grad(checkpoint=False) result = get_grad(checkpoint=True) self.assertEqual(result, expected) def test_unsupported_op_err_msg(self): # Unsupported view op tensor = torch.randn(2, 3) msg = ( r"Batching rule not implemented for aten::.+; the " r"fallback path doesn't work on out= or view ops" ) # TODO: find a view op # with self.assertRaisesRegex(RuntimeError, msg): # vmap(torch.ravel)(tensor) def out_op(x, y): return torch.abs(x, out=y) with self.assertRaisesRegex(RuntimeError, msg): vmap(out_op)(tensor, tensor) # Don't support non-tensor returns. This is a limitation of vmap; # functions that don't return tensors must be special cased with self.assertRaisesRegex(RuntimeError, "Batching rule not implemented"): vmap(torch.equal)(tensor, tensor) def test_nonzero_out_dims(self): # Basic test tensor = torch.randn(2, 3) result = vmap(lambda x: x, out_dims=1)(tensor) self.assertEqual(result, tensor.permute(1, 0)) self.assertEqual(result.data_ptr(), tensor.data_ptr()) # Test that the batch dimension gets permuted to dim 2 tensor = torch.randn(2, 3, 5, 7) result = vmap(lambda x: x, out_dims=2)(tensor) self.assertEqual(result, tensor.permute(1, 2, 0, 3)) self.assertEqual(result.data_ptr(), tensor.data_ptr()) # negative out_dim tensor = torch.randn(2, 3, 5, 7) result = vmap(lambda x: x, out_dims=-1)(tensor) self.assertEqual(result, tensor.permute(1, 2, 3, 0)) self.assertEqual(result.data_ptr(), tensor.data_ptr()) # check that out_dims works on ALL outputs tensor = torch.randn(2, 3, 5, 7) other = torch.randn(2, 3, 5, 7) result = vmap(lambda x, y: (x, y), out_dims=2)(tensor, other) self.assertEqual( result, (tensor.permute(1, 2, 0, 3), other.permute(1, 2, 0, 3)) ) # use out_dims with the maximum vmap-able tensor dims (64 dims) ndims = 64 shape = [2] + [1] * (ndims - 1) expected_shape = [1, 1, 2] + [1] * (ndims - 3) tensor = torch.randn(shape) result = vmap(lambda x: x, out_dims=2)(tensor) self.assertEqual(result.shape, expected_shape) # test something that is not the identity function def foo(x, y): return x, x * y, x * y * y x = torch.randn(2, 3, 5) y = torch.randn(2, 3, 5) result = vmap(foo, out_dims=1)(x, y) self.assertEqual( result, ( x.permute(1, 0, 2), (x * y).permute(1, 0, 2), (x * y * y).permute(1, 0, 2), ), ) def test_multiple_out_dims(self): def foo(x): return x, x def bar(x, y): return x, x, x, x * y x = torch.randn(2, 3, 5) y = torch.randn(2, 3, 5) result = vmap(foo, out_dims=(0, 1))(x) self.assertEqual(result, (x, x.permute(1, 0, 2))) result = vmap(bar, out_dims=(-1, 0, 1, 2))(x, y) expected = ( x.permute(1, 2, 0), x, x.permute(1, 0, 2), (x * y).permute(1, 2, 0), ) self.assertEqual(result, expected) def test_nested_out_dims(self): y = torch.randn(2, 3, 5, 7) # Inner vmap has non-zero out_dim result = vmap(lambda y: vmap(lambda x: x, out_dims=1)(y))(y) self.assertEqual(result.shape, (2, 5, 3, 7)) self.assertEqual(result, y.permute(0, 2, 1, 3)) # all vmaps have non-zero out_dim result = vmap(lambda y: vmap(lambda x: x, out_dims=1)(y), out_dims=1)(y) self.assertEqual(result.shape, (5, 2, 3, 7)) self.assertEqual(result, y.permute(2, 0, 1, 3)) # throwing in some negative out_dims result = vmap(lambda y: vmap(lambda x: x, out_dims=-1)(y), out_dims=-1)(y) self.assertEqual(result.shape, (5, 7, 3, 2)) self.assertEqual(result, y.permute(2, 3, 1, 0)) # testing fn that isn't the identity x = torch.randn(2, 3) y = torch.randn(5, 3) result = vmap(lambda y: vmap(lambda x: x * y, out_dims=1)(x), out_dims=-1)(y) self.assertEqual(result.shape, (3, 2, 5)) self.assertEqual(result, (y.view(5, 1, 3) * x).permute(2, 1, 0)) def test_out_dims_edge_case(self): def foo(x): return x # Test that we accept out_dims=(1,) for a function with one output. tensor = torch.randn(2, 3) expected = vmap(foo, out_dims=1)(tensor) result = vmap(foo, out_dims=(1,))(tensor) self.assertEqual(result, expected) def test_out_dims_none_tuple(self): def foo(x): return x, "hello world" tensor = torch.randn(2, 3) result = vmap(foo, out_dims=(0, None))(tensor) self.assertEqual(result[1], "hello world") self.assertEqual(result[0], tensor) def foo(x): x.add_(1) return None, "hello world" result = vmap(foo, out_dims=(None, None))(tensor) self.assertEqual(result, (None, "hello world")) def test_out_dims_none(self): def foo(x): return x tensor = torch.randn(2, 3) with self.assertRaisesRegex( ValueError, "can not return a BatchedTensor when out_dim is None" ): vmap(foo, out_dims=None)(tensor) def foo(x): x.add_(1) return "hello world" result = vmap(foo, out_dims=None)(tensor) self.assertEqual(result, "hello world") def test_out_dims_normal_tensor(self): def foo(x): return torch.arange(3) tensor = torch.randn(2, 3) result = vmap(foo)(tensor) self.assertEqual(result.shape, [2, 3]) result = vmap(foo, out_dims=None)(tensor) self.assertEqual(result, torch.arange(3)) def test_pytree_returns(self): x = torch.randn(2, 3) def f(x): y = x.sin() return y, (y, y), [y, (y, y)] y0, (y1, y2), (y3, (y4, y5)) = vmap(f)(x) self.assertEqual(y0, x.sin()) self.assertEqual(y0, y1) self.assertEqual(y2, y1) self.assertEqual(y2, y3) self.assertEqual(y4, y3) self.assertEqual(y5, y4) def test_pytree_odict_returns(self): x = torch.randn(2, 3) def f(t): y = t.sin() return OrderedDict([("sin", y), ("cos", t.cos())]) out = vmap(f)(x) assert isinstance(out, OrderedDict) expected = f(x) self.assertEqual(out["sin"], expected["sin"]) self.assertEqual(out["cos"], expected["cos"]) def test_pytree_returns_outdims(self): x = torch.randn(2, 3) def f(x): y = x.sin() return y, (y, y) y0, (y1, y2) = vmap(f, out_dims=(0, (0, 1)))(x) self.assertEqual(y0, x.sin()) self.assertEqual(y1, x.sin()) self.assertEqual(y2, x.sin().t()) def test_pytree_returns_broadcast_simple(self): x = torch.randn(2, 3) def f(x): y = x.sin() return y, (y, y) y0, (y1, y2) = vmap(f, out_dims=1)(x) self.assertEqual(y0, x.sin().t()) self.assertEqual(y1, y0) self.assertEqual(y2, y0) def test_pytree_returns_broadcast_nested(self): x = torch.randn(2, 3) def f(x): y = x.sin() return y, (y, y) y0, (y1, y2) = vmap(f, out_dims=(0, 1))(x) self.assertEqual(y0, x.sin()) self.assertEqual(y1, y0.t()) self.assertEqual(y2, y0.t()) def test_out_dims_must_be_int_or_collection_of_int_err_msg(self): msg = "must be an int, None or a python collection of ints" tensor = torch.randn(2, 3) with self.assertRaisesRegex(ValueError, msg): vmap(lambda x: x, out_dims="lol")(tensor) with self.assertRaisesRegex(ValueError, msg): vmap(lambda x: x, out_dims=("lol",))(tensor) def test_out_dims_and_num_outputs_mismatch_err_msg(self): msg = "not compatible" x = torch.randn(2, 3, 5) # Too many out_dims with self.assertRaisesRegex(ValueError, msg): vmap(lambda x: x, out_dims=(0, 0))(x) with self.assertRaisesRegex(ValueError, msg): vmap(lambda x: (x, x, x), out_dims=(0, 0, 0, 0))(x) # Too few out_dims with self.assertRaisesRegex(ValueError, msg): vmap(lambda x: (x, x), out_dims=(0,))(x) with self.assertRaisesRegex(ValueError, msg): vmap(lambda x: (x, x, x), out_dims=(0, 0))(x) def test_out_dim_out_of_bounds_err_msg(self): # TODO(rzou): This error message isn't that great. It comes straight # from maybe_wrap_dim. Consider doing a try-catch-(add some context) to # the error message in the future in C++ msg = "Dimension out of range" x = torch.randn(2, 3, 5) with self.assertRaisesRegex(IndexError, msg): vmap(lambda x: x, out_dims=3)(x) with self.assertRaisesRegex(IndexError, msg): vmap(lambda x: x, out_dims=-4)(x) def test_non_zero_in_dims(self): tensor = torch.randn(2, 3, 5) # Implicit out_dims = 0; vmap will move the batch dim to the front. output = vmap(lambda x: x, (1,))(tensor) self.assertEqual(output, tensor.permute(1, 0, 2)) self.assertEqual(output.data_ptr(), tensor.data_ptr()) x = torch.randn(2, 3) y = torch.randn(3, 2) output = vmap(torch.mul, (0, 1))(x, y) self.assertEqual(output, x * y.t()) output = vmap(torch.mul, (1, 0))(x, y) self.assertEqual(output, x.t() * y) def test_none_in_dims(self): x = torch.randn(2, 3) y = torch.randn(2, 3) # None in_dim for a Tensor means we don't map over it output = vmap(torch.mul, (0, None))(x, y) self.assertEqual(output.shape, (2, 2, 3)) self.assertEqual(output, x.view(2, 1, 3) * y) # None in_dim for non-tensor arguments output = vmap(torch.mul, (0, None))(x, 2) self.assertEqual(output, x * 2) def test_nested_non_default_in_dims(self): x = torch.rand(5, 2, 3) y = torch.rand(3, 5, 2) result = vmap(vmap(vmap(torch.mul), (1, 0)), (1, 2))(x, y) self.assertEqual(result, x.permute(1, 2, 0) * y.permute(2, 0, 1)) def test_nested_negative_in_dims(self): x = torch.randn(2, 3) y = torch.randn(2, 3) output = vmap(torch.mul, (-1, -1))(x, y) self.assertEqual(output.shape, (3, 2)) self.assertEqual(output, (x * y).permute(1, 0)) def test_non_default_in_dims_out_dims(self): x = torch.randn(2, 3, 5) # Same in_dim as out_dim, vmap over identity result = vmap(lambda x: x, in_dims=1, out_dims=1)(x) self.assertEqual(result, x) self.assertEqual(result.data_ptr(), x.data_ptr()) # Different in_dim from out_dim, vmap over identity result = vmap(lambda x: x, in_dims=2, out_dims=1)(x) self.assertEqual(result.shape, (2, 5, 3)) self.assertEqual(result, x.transpose(1, 2)) self.assertEqual(result.data_ptr(), x.data_ptr()) def foo(x): return x * 2 # Same in_dim as out_dim, vmap over operation result = vmap(foo, in_dims=1, out_dims=1)(x) self.assertEqual(result, x * 2) # Different in_dim as out_dim, vmap over operation result = vmap(foo, in_dims=2, out_dims=1)(x) self.assertEqual(result.shape, (2, 5, 3)) self.assertEqual(result, (x * 2).transpose(1, 2)) # Basic nested test. result = vmap(vmap(foo, 1, 1), 1, 1)(x) self.assertEqual(result, x * 2) def test_item_throws(self): def f(x): return x.item() with self.assertRaisesRegex(RuntimeError, r"item\(\) on a Tensor"): vmap(f)(torch.randn(3)) def test_data_dependent_control_flow_throws(self): def f(x): if x: return x return 0 with self.assertRaisesRegex(RuntimeError, r"data-dependent control flow"): vmap(f)(torch.randn(3)) def test_accepts_nested_inputs(self): x = torch.randn(2, 3) y = torch.randn(2, 3) # Single layer of nesting out = vmap(lambda z: z[0] + z[1])((x, y)) self.assertEqual(out, x + y) out = vmap(lambda z: z[0] + z[1], in_dims=(0,))((x, y)) self.assertEqual(out, x + y) out = vmap(lambda z: z[0] + z[1], in_dims=((0, 0),))((x, y)) self.assertEqual(out, x + y) out = vmap(lambda z: z[0] + z[1])([x, y]) self.assertEqual(out, x + y) out = vmap(lambda z: z[0] + z[1], in_dims=(0,))([x, y]) self.assertEqual(out, x + y) out = vmap(lambda z: z[0] + z[1], in_dims=([0, 0],))([x, y]) self.assertEqual(out, x + y) out = vmap(lambda z: z["x"] + z["y"])({"x": x, "y": y}) self.assertEqual(out, x + y) out = vmap(lambda z: z["x"] + z["y"], in_dims=(0,))({"x": x, "y": y}) self.assertEqual(out, x + y) out = vmap(lambda z: z["x"] + z["y"], in_dims=({"x": 0, "y": 0},))( {"x": x, "y": y} ) self.assertEqual(out, x + y) # Multiple layers of nesting out_fn = vmap(lambda z: z["x"][0] + z["x"][1][0] + z["y"][0] + z["y"][1]) out = out_fn({"x": [x, (x,)], "y": [y, y]}) self.assertEqual(out, x + x + y + y) def test_in_dims_wrong_type_err_msg(self): x = torch.randn(3) y = torch.randn(3) msg = r"expected `in_dims` to be int or a \(potentially nested\) tuple" with self.assertRaisesRegex(ValueError, msg): vmap(torch.mul, [0, 0])(x, y) with self.assertRaisesRegex(ValueError, msg): vmap(torch.mul, set({0}))(x, y) with self.assertRaisesRegex(ValueError, msg): vmap(torch.mul, "lol")(x, y) with self.assertRaisesRegex(ValueError, msg): vmap(lambda z: z[0] + z[1], in_dims=[0, 0])([x, y]) # The following should not throw vmap(torch.mul, (0, 0))(x, y) def test_not_enough_in_dims_err_msg(self): x = torch.randn(3) y = torch.randn(3) msg = r"in_dims is not compatible with the structure of `inputs`" with self.assertRaisesRegex(ValueError, msg): vmap(torch.mul, (0,))(x, y) with self.assertRaisesRegex(ValueError, msg): vmap(torch.mul, (0, 0, 0))(x, y) with self.assertRaisesRegex(ValueError, msg): vmap(lambda z: z[0] + z[1], in_dims=([0],))([x, y]) with self.assertRaisesRegex(ValueError, msg): vmap(lambda z: z[0] + z[1], in_dims=((0, 0),))([x, y]) # The following should not throw vmap(torch.mul, (0, 0))(x, y) def test_integer_in_dim_but_not_tensor_input_err_msg(self): # noqa: F841 def foo(xy): return xy[0] * xy[1] def bar(x, yz): return x * yz[0] * yz[1] x = torch.randn(2, 3) # the following are errors in jax (and will always be errors) msg = "Got in_dim=0 for an input but the input is of type" with self.assertRaisesRegex(ValueError, msg): vmap(torch.sum)(x, 0) with self.assertRaisesRegex(ValueError, msg): vmap(torch.sum, (0, 0))(x, 0) with self.assertRaisesRegex(ValueError, msg): vmap(lambda z: z[0] + z[1], in_dims=([0, 0],))([x, 1]) # The following should not throw vmap(torch.sum, (0, None))(x, 0) def test_in_dim_not_in_tensor_err_msg(self): def foo(x): return x * x x = torch.randn(2, 3) y = torch.randn(2, 3) msg = r"Got in_dim=-?\w for some input, but that input is a Tensor of dimensionality \w" with self.assertRaisesRegex(ValueError, msg): vmap(foo)(torch.randn([])) with self.assertRaisesRegex(ValueError, msg): vmap(foo, in_dims=(0,))(torch.randn([])) with self.assertRaisesRegex(ValueError, msg): vmap(foo, in_dims=(-3,))(x) with self.assertRaisesRegex(ValueError, msg): vmap(foo, in_dims=(2,))(y) with self.assertRaisesRegex(ValueError, msg): vmap(lambda z: z[0] + z[1], in_dims=([3, 0],))([x, y]) # the following should not throw vmap(foo, in_dims=(0,))(torch.randn(2, 3)) vmap(foo, in_dims=(1,))(torch.randn(2, 3)) def test_fallback_does_not_warn_by_default(self): op = torch._test_functorch_fallback x = torch.randn(11) y = torch.randn(11) with warnings.catch_warnings(record=True) as wa: torch.vmap(op)(x, y) # The single warning here is the "vmap is experimental" # warning, not a warning from the vmap fallback path. self.assertEqual(len(wa), 1) @skipIfTorchDynamo("Flaky test") @unittest.expectedFailure def test_fallback_warns_when_warnings_are_enabled(self): # NB: One day we will implement a batching rule for torch.atan2. # If/when we do, this test should be replaced to test the fallback # path on another operator to avoid bitrot. op = torch._test_functorch_fallback x = torch.randn(11) y = torch.randn(11) with warnings.catch_warnings(record=True) as wa: with EnableVmapFallbackWarnings(): torch.vmap(op)(x, y) self.assertEqual(len(wa), 2) self.assertRegex(str(wa[-1].message), FALLBACK_REGEX) def _assert_uses_vmap_fallback(self, vmap_args, inputs): return # with warnings.catch_warnings(record=True) as wa: # with EnableVmapFallbackWarnings(): # result = vmap(*vmap_args)(*inputs) # self.assertEqual(len(wa), 2) # self.assertRegex(str(wa[-1].message), FALLBACK_REGEX) def test_fallback_zero_dim(self): op = torch._test_functorch_fallback x = torch.randn(11) y = torch.randn(11) self._assert_uses_vmap_fallback((op,), (x, y)) B0, B1 = 0, 3 x = torch.randn(B0, 11) y = torch.randn(11) msg = "The fallback path does not support vmap over dims of size 0" with self.assertRaisesRegex(RuntimeError, msg): vmap(op, (0, None))(x, y) with self.assertRaisesRegex(RuntimeError, msg): vmap(op, (None, 0))(y, x) with self.assertRaisesRegex(RuntimeError, msg): vmap(op)(x, x) x = torch.randn(B0, B1, 11) y = torch.randn(B1, 11) with self.assertRaisesRegex(RuntimeError, msg): vmap(op, (0, None))(x, y) with self.assertRaisesRegex(RuntimeError, msg): vmap(op, (None, 0))(y, x) with self.assertRaisesRegex(RuntimeError, msg): vmap(op)(x, x) def test_fallback_warning(self): # We use a dummy function _test_functorch_fallback # defined in prim_native_functions.cpp for this op = torch._test_functorch_fallback x = torch.randn(5, 7, 11) y = torch.randn(5, 7, 11) self._assert_uses_vmap_fallback((op,), (x, y)) x = torch.randn(7, 11, 5) y = torch.randn(5, 7, 11) result = vmap(op, (2, 0))(x, y) self.assertEqual(result, op(x.permute(2, 0, 1), y)) # nested vmap x = torch.randn(7, 11, 5) y = torch.randn(5, 7, 11) result = vmap(vmap(op), (2, 0))(x, y) self.assertEqual(result, op(x.permute(2, 0, 1), y)) # big batch size (total 10000) x = torch.randn(100, 10, 10, 5) y = torch.randn(100, 10, 10) result = vmap(vmap(vmap(op)))(x, y) self.assertEqual(result, op(x, y.view(100, 10, 10, 1))) # TODO: No clue what is wrong here. @unittest.skip def test_fallback_masked_fill(self): # NB: One day we will implement a batching rule for masked_fill # If/when we do, this test should be replaced to test the fallback # path on another operator to avoid bitrot. def run_test(batch_size): B0 = batch_size x = torch.randn(B0, 7, 11, 13) dim = 0 index = torch.tensor([0, 4, 2]) values = torch.randn(B0, 3, 13) self._assert_uses_vmap_fallback( (torch.index_add, (0, None, None, 0)), (x, dim, index, values) ) result = vmap(torch.index_add, (0, None, None, 0))(x, dim, index, values) expected = torch.index_add(x, dim + 1, index, values.view(B0, 3, 1, 13)) self.assertEqual(result, expected) run_test(batch_size=5) run_test(batch_size=1237) def test_fallback_multiple_returns(self): # NB: One day we will implement a batching rule for torch.var_mean # If/when we do, this test should be replaced to test the fallback # path on another operator to avoid bitrot. B0, B1, B2 = 2, 3, 1237 tensor = torch.randn(B0, 10) self._assert_uses_vmap_fallback((torch.var_mean,), (tensor,)) # fallback correctness on torch.var_mean result = vmap(torch.var_mean)(tensor) expected = torch.var_mean(tensor, dim=1) self.assertEqual(result, expected) # nested vmap tensor = torch.randn(B0, B1, 10) result = vmap(vmap(torch.var_mean))(tensor) expected = torch.var_mean(tensor, dim=2) self.assertEqual(result, expected) # big batch size, nested vmap tensor = torch.randn(B0, B1, B2, 10) result = vmap(vmap(vmap(torch.var_mean)))(tensor) expected = torch.var_mean(tensor, dim=3) self.assertEqual(result, expected) def test_inplace_fallback_unary(self): # Test the in-place fallback on an in-place method that takes no # additional Tensor arguments. This is the simplest case of the fallback. # NB: One day we will implement a batching rule for acos_. # If/when we do, this test should be replaced to test the fallback # path on another operator to avoid bitrot. op = Tensor.acos_ B0, B1, B2 = 2, 3, 10000 x = torch.randn(B0, 5) self._assert_uses_vmap_fallback((op,), (x,)) # Single vmap x_orig = torch.rand(B0, 5) x = x_orig.clone() result = vmap(op)(x) self.assertTrue(result is x) self.assertEqual(result, x_orig.acos()) # Single vmap + different out_dim produces a view(!) x_orig = torch.rand(B0, 5) x = x_orig.clone() result = vmap(op, out_dims=(1,))(x) self.assertTrue(result._base is x) self.assertEqual(result, x_orig.t().acos()) # Nested vmap x_orig = torch.randn(B0, B1, 5) x = x_orig.clone() result = vmap(vmap(op))(x) self.assertTrue(result is x) self.assertEqual(result, x_orig.acos()) # Nested vmap, large batch size x_orig = torch.randn(B0, B1, B2, 5) x = x_orig.clone() result = vmap(vmap(vmap(op)))(x) self.assertTrue(result is x) self.assertEqual(result, x_orig.acos()) def test_inplace_fallback_nary_same_levels(self): # NB: One day we will implement a batching rule for atan2_ # If/when we do, this test should be replaced to test the fallback # path on another operator to avoid bitrot. op = Tensor.atan2_ outplace_op = torch.atan2 x = torch.randn(5, 7, 11) y = torch.randn(5, 7, 11) self._assert_uses_vmap_fallback((op,), (x, y)) # Single vmap B0 = 5 x_orig = torch.randn(7, 11, B0) x = x_orig.clone() y = torch.randn(B0, 7, 11) vmap(op, (2, 0))(x, y) self.assertEqual(x, outplace_op(x_orig, y.movedim(0, 2))) # Nested vmap B0, B1 = 5, 7 x_orig = torch.randn(B1, 11, B0) x = x_orig.clone() y = torch.randn(B0, B1, 11) vmap(vmap(op), (2, 0))(x, y) self.assertEqual(x, outplace_op(x_orig, y.movedim([0, 1], [2, 0]))) # big batch size (total 10000) B0, B1, B2 = 100, 10, 10 x_orig = torch.randn(B0, B1, B2, 5) x = x_orig.clone() y = torch.randn(B0, B1, B2) vmap(vmap(vmap(op)))(x, y) self.assertEqual(x, outplace_op(x_orig, y.view(B0, B1, B2, 1))) # ("Fallback isInplaceVmapCompatible check is broken") @unittest.expectedFailure def test_inplace_fallback_nary_different_levels(self): # NB: One day we will implement a batching rule for atan2_ # If/when we do, this test should be replaced to test the fallback # path on another operator to avoid bitrot. op = Tensor.atan2_ outplace_op = torch.atan2 B0, B1 = 2, 3 x = torch.rand(B0, 7) y = torch.rand(7) self._assert_uses_vmap_fallback((op, (0, None)), (x, y)) # op(left, right): All of the levels in right are found in left x_orig = torch.rand(B0, 7) x = x_orig.clone() y = torch.rand(7) vmap(op, in_dims=(0, None))(x, y) self.assertEqual(x, outplace_op(x_orig, y)) x_orig = torch.rand(B0, B1, 7) x = x_orig.clone() y = torch.rand(B0, 7) vmap(vmap(op, in_dims=(0, None)))(x, y) self.assertEqual(x, outplace_op(x_orig, y.view(B0, 1, 7))) # op(left, right): Some of the levels in right are not found in left msg = r"vmap: aten::atan2_\(self, \*extra_args\) is not possible" x = torch.rand(7) y = torch.rand(B0, 7) with self.assertRaisesRegex(RuntimeError, msg): vmap(op, in_dims=(None, 0))(x, y) x = torch.rand(B1, 7) y = torch.rand(B0, 7) with self.assertRaisesRegex(RuntimeError, msg): vmap(vmap(op, in_dims=(0, None)), in_dims=(None, 0))(x, y) x = torch.rand(B1, 7) y = torch.rand(7, B0) with self.assertRaisesRegex(RuntimeError, msg): vmap(vmap(op, in_dims=(0, None)), in_dims=(None, 1))(x, y) x = torch.rand(B0, 7) y = torch.rand(B0, B1, 7) with self.assertRaisesRegex(RuntimeError, msg): vmap(vmap(op, in_dims=(None, 0)))(x, y) def test_backward_unsupported_interaction(self): x = torch.randn(3, requires_grad=True) y = torch.randn(5) grad = torch.randn_like(x) err_msg = r"backward\(\) called inside a functorch transform" def backward_on_vmapped_tensor(x): x.sum().backward() # FIXME return self.skipTest( "error: element 0 of tensors does not require grad and does not have a grad_fn" ) with self.assertRaisesRegex(RuntimeError, err_msg): vmap(backward_on_vmapped_tensor)(x) def backward_with_vmapped_grad(x, grad): x.backward(grad) with self.assertRaisesRegex(RuntimeError, err_msg): vmap(backward_with_vmapped_grad)(x, grad) def completely_unrelated_backward(y): x.sum().backward() return y with self.assertRaisesRegex(RuntimeError, err_msg): vmap(completely_unrelated_backward)(y) @unittest.expectedFailure def test_grad_unsupported_interaction(self): input_tensor = torch.randn(3, requires_grad=True) err_msg = "autograd.grad.* called inside torch.vmap" captured = torch.randn(3, requires_grad=True) def output_to_grad_is_vmapped(input_tensor): output = (captured * input_tensor).sum() return torch.autograd.grad([output], [captured])[0] with self.assertRaisesRegex(RuntimeError, err_msg): vmap(output_to_grad_is_vmapped)(input_tensor) output = (input_tensor**2).sum() def input_to_grad_is_vmapped(input_tensor): return torch.autograd.grad([output], [input_tensor])[0] with self.assertRaisesRegex(RuntimeError, err_msg): vmap(input_to_grad_is_vmapped)(input_tensor) def test_batched_gradient_basic(self): N = 3 x = torch.randn(N, requires_grad=True) y = torch.randn(N) def vjp_mul(v): return torch.autograd.grad([x * y], [x], grad_outputs=[v])[0] batched_v = torch.eye(N) jacobian = vmap(vjp_mul)(batched_v) self.assertEqual(jacobian, torch.diagflat(y)) def test_functools_partial(self): x = torch.randn(3) y = torch.randn(2, 3) result = vmap(functools.partial(torch.mul, x))(y) self.assertEqual(result, x * y) def test_nn_module(self): tensor = torch.randn(2, 3) model = torch.nn.Linear(3, 3, bias=False) result = vmap(model)(tensor) self.assertEqual(result, model(tensor)) def test_fallback_with_undefined_grad(self): B0 = 7 x = torch.randn(2, 3, 4, 5, requires_grad=True) weight = torch.randn(3, 3, 1, 1) v = torch.randn(B0, 2, 3, 4, 5) def get_vjp(v): result = torch.nn.functional.conv2d(x, weight) (grad_x,) = torch.autograd.grad(result, x, v) return grad_x # Runs vmap(get_vjp)(v), which should not error out. # The backward formula for convolution returns an undefined # Tensor for grad_bias because the original bias does not exist. # # In the future we'll probably add a batching rule for convolution # backward. When this happens, we should modify this test to use a # different op (and/or create and use a dummy operator) to avoid bitrot. self._assert_uses_vmap_fallback([get_vjp], [v]) def test_reshape_dim_into(self): x = torch.randn(2, 3, 5, 7) y = reshape_dim_into(0, 0, x) self.assertEqual(y, x.reshape(6, 5, 7)) y = reshape_dim_into(0, 1, x) self.assertEqual(y, x.movedim(0, 1).reshape(3, 2 * 5, 7)) y = reshape_dim_into(0, 2, x) self.assertEqual(y, x.movedim(0, 2).reshape(3, 5, 2 * 7)) y = reshape_dim_into(1, 2, x) self.assertEqual(y, x.movedim(1, 2).reshape(2, 5, 3 * 7)) y = reshape_dim_into(0, -2, x) self.assertEqual(y, x.movedim(0, 1).reshape(3, 2 * 5, 7)) y = reshape_dim_into(0, -1, x) self.assertEqual(y, x.movedim(0, 2).reshape(3, 5, 2 * 7)) y = reshape_dim_into(-4, -1, x) self.assertEqual(y, x.movedim(0, 2).reshape(3, 5, 2 * 7)) def test_reshape_dim_outof(self): x = torch.randn(12, 12, 12).permute(2, 1, 0) y = reshape_dim_outof(0, 2, x) self.assertEqual(y, x.reshape(2, 6, 12, 12)) y = reshape_dim_outof(1, 4, x) self.assertEqual(y, x.reshape(12, 4, 3, 12)) y = reshape_dim_outof(2, 6, x) self.assertEqual(y, x.reshape(12, 12, 6, 2)) y = reshape_dim_outof(-1, 6, x) self.assertEqual(y, x.reshape(12, 12, 6, 2)) # Case: `0` sized dim. x = torch.randn(12, 12, 0) y = reshape_dim_outof(-1, 6, x) self.assertEqual(y.shape, torch.Size((12, 12, 6, 0))) def test_batch_rule_does_not_need_to_handle_no_batched_input(self): def f(x, y): res = torch.dot(y, torch.ones(2)) return x + res x = torch.randn(7, 5) y = torch.randn(3, 2) out = vmap(vmap(f, in_dims=(0, None)), in_dims=(None, 0))(x, y) expected = torch.mv(y, torch.ones(2)).view(3, 1, 1) + x self.assertEqual(out, expected) def test_decomposition_under_python_dispatcher(self): # This test will raise an error if the vmap fallback gets invoked. # Here we test that decomps registered to FuncTorchBatchedDecomposition # are respected by the Python Dispatcher. t = torch.ones(3, 3) * 5 with DisableVmapFallback(): with torch._dispatch.python.enable_python_dispatcher(): o = torch.vmap(torch.square)(t) self.assertEqual(o, torch.square(t)) def _test_vmap_autocast(self, device): if torch.device(device).type == "cpu": amp_dtype = torch.bfloat16 else: amp_dtype = torch.float16 a_float32 = torch.rand(4, 2, 3, device=device) b_float32 = torch.rand(4, 3, 2, device=device) c_float32 = torch.rand(4, 2, 2, device=device) d_float32 = torch.rand(4, 3, 2, device=device) # Case 1, autocast inside vmapped function def func1(x, y, z, w): with torch.autocast(dtype=amp_dtype, device_type=device): e_float16 = torch.matmul(x, y) assert e_float16.dtype == amp_dtype, e_float16.dtype f_float16 = torch.matmul(z, e_float16) assert f_float16.dtype == amp_dtype, f_float16.dtype return torch.matmul(w, f_float16.float()) expected = func1(a_float32, b_float32, c_float32, d_float32) out = vmap(func1)(a_float32, b_float32, c_float32, d_float32) assert expected.allclose(out) # Case 2, autocast decorator inside vmapped function @torch.autocast(dtype=amp_dtype, device_type=device) def func2(x, y, z, w): e_float16 = torch.matmul(x, y) assert e_float16.dtype == amp_dtype, e_float16.dtype f_float16 = torch.matmul(z, e_float16) assert f_float16.dtype == amp_dtype, f_float16.dtype return torch.matmul(w, f_float16) expected = func2(a_float32, b_float32, c_float32, d_float32) out = vmap(func2)(a_float32, b_float32, c_float32, d_float32) assert expected.allclose(out) # Case 3, autocast is outside vmapped function def func3(x, y, z, w): e_float16 = torch.matmul(x, y) assert e_float16.dtype == amp_dtype, e_float16.dtype f_float16 = torch.matmul(z, e_float16) assert f_float16.dtype == amp_dtype, f_float16.dtype return torch.matmul(w, f_float16) with torch.autocast(dtype=amp_dtype, device_type=device): expected = func3(a_float32, b_float32, c_float32, d_float32) out = vmap(func3)(a_float32, b_float32, c_float32, d_float32) assert expected.allclose(out) @unittest.skip("Somehow, vmap and autocast do not work on CPU") def test_vmap_autocast_cpu(self): self._test_vmap_autocast("cpu") @skipIf(not torch.cuda.is_available(), "CUDA is unavailable") def test_vmap_autocast_cuda(self): self._test_vmap_autocast("cuda") def test_restore_vmap_pytree_input_output(self): def f(x, y): output0 = x[0] + x[1] output1 = y return {"a": output0, "b": output1} B = 2 x0 = torch.randn(B, 3) x1 = torch.randn(B) y = torch.randn(4, B) out, out_dims = restore_vmap(f, ((0, 0), 1), B, "error")((x0, x1), y) expected = vmap(f, in_dims=((0, 0), 1), out_dims={"a": 0, "b": 1})((x0, x1), y) self.assertEqual(out, expected) self.assertEqual(out_dims, {"a": 0, "b": 1}) def test_restore_vmap_no_vmapped_inputs(self): def f(x, y, z): return x, y * z, z B = 2 # Mix of tensor and non-tensor inputs x = torch.randn(3) y = torch.randn(4) z = 5 out, out_dims = restore_vmap(f, (None, None, None), B, "error")(x, y, z) self.assertEqual(out, f(x, y, z)) self.assertEqual(out_dims, (None, None, None)) def test_restore_vmap_unexpanded_outputs(self): def f(x, y): # Mix of tensor and non-tensor outputs return 3 * y, y.sum(), None B = 2 x = torch.randn(B, 3) y = torch.randn(4) out, out_dims = restore_vmap(f, (0, None), B, "error")(x, y) self.assertEqual(out, f(None, y)) self.assertEqual(out_dims, (None, None, None)) def test_data_attribute(self): def foo(x): y = x.data # noqa: F841 return x with self.assertRaisesRegex( RuntimeError, "accessing `data` under vmap transform" ): torch.func.vmap(foo)(torch.randn(3, 3)) def foo(x): x.data = torch.ones(3, 3) return x with self.assertRaisesRegex( RuntimeError, "mutating directly with `.data` under vmap" ): torch.func.vmap(foo)(torch.randn(3, 3)) def slice_inputs(inputs, bdims, i): result = [] for inp, bdim in zip(inputs, bdims): if bdim is None: result.append(inp) else: result.append(inp.select(bdim, i)) return tuple(result) def reference_vmap(op, inputs, in_dims=0, out_dims=0, return_nt=False): if isinstance(in_dims, int): in_dims = (in_dims,) * len(inputs) bdim_sizes = [inp.size(dim) for inp, dim in zip(inputs, in_dims) if dim is not None] assert all(bdim_size == bdim_sizes[0] for bdim_size in bdim_sizes) bdim_size = bdim_sizes[0] results = tuple(op(*slice_inputs(inputs, in_dims, i)) for i in range(bdim_size)) assert len(results) > 0 op_has_single_return = not isinstance(results[0], tuple) if op_has_single_return: assert all(isinstance(result, torch.Tensor) for result in results) if isinstance(out_dims, int): out_dims = (out_dims,) * 1 if return_nt: return torch.nested.nested_tensor(list(results)) else: return torch.stack(results, dim=out_dims[0]) assert all(isinstance(result, tuple) for result in results) num_returns = len(results[0]) assert all(len(result) == num_returns for result in results) if isinstance(out_dims, int): out_dims = (out_dims,) * num_returns if return_nt: return tuple( torch.nested.nested_tensor(list(result_shards)) for result_shards in zip(*results) ) else: return tuple( torch.stack(result_shards, out_dim) for result_shards, out_dim in zip(zip(*results), out_dims) )
TestVmapAPI
python
explosion__spaCy
spacy/lang/bo/__init__.py
{ "start": 217, "end": 313 }
class ____(Language): lang = "bo" Defaults = TibetanDefaults __all__ = ["Tibetan"]
Tibetan
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/completion_html.py
{ "start": 1490, "end": 3354 }
class ____(object): """a bound interval that follows a cursor internally used to scoll the completion view when the cursor try to go beyond the edges, and show '...' when rows are hidden """ _min = 0 _max = 1 _current = 0 def __init__(self, maximum=1, width=6, minimum=0, sticky_lenght=1): """Create a new bounded interval any value return by this will be bound between maximum and minimum. usual width will be 'width', and sticky_length set when the return interval should expand to max and min """ self._min = minimum self._max = maximum self._start = 0 self._width = width self._stop = self._start+self._width+1 self._sticky_lenght = sticky_lenght @property def current(self): """current cursor position""" return self._current @current.setter def current(self, value): """set current cursor position""" current = min(max(self._min, value), self._max) self._current = current if current > self._stop : self._stop = current self._start = current-self._width elif current < self._start : self._start = current self._stop = current + self._width if abs(self._start - self._min) <= self._sticky_lenght : self._start = self._min if abs(self._stop - self._max) <= self._sticky_lenght : self._stop = self._max @property def start(self): """begiiing of interval to show""" return self._start @property def stop(self): """end of interval to show""" return self._stop @property def width(self): return self._stop - self._start @property def nth(self): return self.current - self.start
SlidingInterval
python
pypa__warehouse
tests/unit/captcha/test_hcaptcha.py
{ "start": 1232, "end": 6152 }
class ____: @responses.activate def test_verify_service_disabled(self): responses.add( responses.POST, hcaptcha.VERIFY_URL, body="", ) service = hcaptcha.Service.create_service( context=None, request=pretend.stub( registry=pretend.stub( settings={}, ), ), ) assert service.verify_response("") is None @responses.activate def test_verify_response_success(self): responses.add( responses.POST, hcaptcha.VERIFY_URL, json={ "success": True, "hostname": "hostname_value", "challenge_ts": 0, }, ) service = hcaptcha.Service.create_service( context=None, request=_REQUEST, ) assert service.verify_response("meaningless") == interfaces.ChallengeResponse( challenge_ts=0, hostname="hostname_value", ) @responses.activate def test_remote_ip_added(self): responses.add( responses.POST, hcaptcha.VERIFY_URL, json={"success": True}, ) service = hcaptcha.Service.create_service( context=None, request=_REQUEST, ) assert service.verify_response( "meaningless", remote_ip="someip" ) == interfaces.ChallengeResponse( challenge_ts=None, hostname=None, ) def test_retries_on_timeout(self, monkeypatch): service = hcaptcha.Service.create_service( context=None, request=_REQUEST, ) monkeypatch.setattr( service.request.http, "post", pretend.raiser(requests.Timeout) ) with pytest.raises(pyramid_retry.RetryableException): service.verify_response("meaningless") def test_unexpected_error(self, monkeypatch): service = hcaptcha.Service.create_service( context=None, request=_REQUEST, ) monkeypatch.setattr( service.request.http, "post", pretend.raiser(Exception("unexpected error")) ) with pytest.raises(hcaptcha.UnexpectedError) as err: service.verify_response("meaningless") assert err.value.args == ("unexpected error",) @responses.activate def test_unexpected_data_error(self): responses.add( responses.POST, hcaptcha.VERIFY_URL, body="something awful", ) serv = hcaptcha.Service.create_service(context=None, request=_REQUEST) with pytest.raises(hcaptcha.UnexpectedError) as err: serv.verify_response("meaningless") expected = "Unexpected data in response body: something awful" assert str(err.value) == expected @responses.activate def test_missing_success_key(self): responses.add( responses.POST, hcaptcha.VERIFY_URL, json={}, ) serv = hcaptcha.Service.create_service(context=None, request=_REQUEST) with pytest.raises(hcaptcha.UnexpectedError) as err: serv.verify_response("meaningless") expected = "Missing 'success' key in response: {}" assert str(err.value) == expected @responses.activate def test_missing_error_codes_key(self): responses.add( responses.POST, hcaptcha.VERIFY_URL, json={"success": False}, ) serv = hcaptcha.Service.create_service(context=None, request=_REQUEST) with pytest.raises(hcaptcha.UnexpectedError) as err: serv.verify_response("meaningless") expected = "Response missing 'error-codes' key: {'success': False}" assert str(err.value) == expected @responses.activate def test_invalid_error_code(self): responses.add( responses.POST, hcaptcha.VERIFY_URL, json={"success": False, "error-codes": ["foo"]}, ) serv = hcaptcha.Service.create_service(context=None, request=_REQUEST) with pytest.raises(hcaptcha.UnexpectedError) as err: serv.verify_response("meaningless") expected = "Unexpected error code: foo" assert str(err.value) == expected @responses.activate def test_valid_error_code(self): responses.add( responses.POST, hcaptcha.VERIFY_URL, json={ "success": False, "error-codes": ["invalid-or-already-seen-response"], }, ) serv = hcaptcha.Service.create_service(context=None, request=_REQUEST) with pytest.raises(hcaptcha.InvalidOrAlreadySeenResponseError): serv.verify_response("meaningless")
TestVerifyResponse
python
getsentry__sentry
src/sentry/ingest/inbound_filters.py
{ "start": 2020, "end": 5210 }
class ____: ERROR_MESSAGES = "error_messages" RELEASES = "releases" LOG_MESSAGES = "log_messages" TRACE_METRIC_NAMES = "trace_metric_names" def get_filter_key(flt): return to_camel_case_name(flt.config_name.replace("-", "_")) def get_all_filter_specs(): """ Return metadata about the filters known by Sentry. An event filter is a function that receives a project_config and an event data payload and returns a tuple (should_filter:bool, filter_reason: string | None) representing :return: list of registered event filters """ filters = [ _localhost_filter, _browser_extensions_filter, _legacy_browsers_filter, _web_crawlers_filter, _healthcheck_filter, ] return tuple(filters) # returning tuple for backwards compatibility def set_filter_state(filter_id, project: Project, state): flt = _filter_from_filter_id(filter_id) if flt is None: raise FilterNotRegistered(filter_id) if flt == _legacy_browsers_filter: if state is None: state = {} option_val: object = "0" if "active" in state: if state["active"]: option_val = "1" elif "subfilters" in state and len(state["subfilters"]) > 0: option_val = sorted(set(state["subfilters"])) ProjectOption.objects.set_value( project=project, key=f"filters:{filter_id}", value=option_val ) return option_val == "1" if option_val in ("0", "1") else option_val else: # all boolean filters if state is None: state = {"active": True} ProjectOption.objects.set_value( project=project, key=f"filters:{filter_id}", value="1" if state.get("active", False) else "0", ) if state: inbound_filter_toggled.send(project=project, sender=flt) return state.get("active", False) def get_filter_state(filter_id, project): """ Returns the filter state IMPORTANT: this function accesses the database, it should NEVER be used by the ingestion pipe. This api is used by the ProjectFilterDetails and ProjectFilters endpoints :param filter_id: the filter Id :param project: the project for which we want the filter state :return: True if the filter is enabled False otherwise :raises: ValueError if filter id not registered """ flt = _filter_from_filter_id(filter_id) if flt is None: raise FilterNotRegistered(filter_id) filter_state = ProjectOption.objects.get_value(project=project, key=f"filters:{flt.id}") if filter_state is None: raise ValueError( "Could not find filter state for filter {}." " You need to register default filter state in projectoptions.defaults.".format( filter_id ) ) if flt == _legacy_browsers_filter: # special handling for legacy browser state if filter_state == "1": return True if filter_state == "0": return False return filter_state else: return filter_state == "1"
FilterTypes
python
facelessuser__pymdown-extensions
pymdownx/tasklist.py
{ "start": 4289, "end": 5359 }
class ____(Extension): """Tasklist extension.""" def __init__(self, *args, **kwargs): """Initialize.""" self.config = { 'custom_checkbox': [ False, "Add an empty label tag after the input tag to allow for custom styling - Default: False" ], 'clickable_checkbox': [ False, "Allow user to check/uncheck the checkbox - Default: False" ], 'delete': [True, "Enable delete - Default: True"], 'subscript': [True, "Enable subscript - Default: True"] } super().__init__(*args, **kwargs) def extendMarkdown(self, md): """Add checklist tree processor to Markdown instance.""" tasklist = TasklistTreeprocessor(md) tasklist.config = self.getConfigs() md.treeprocessors.register(tasklist, "task-list", 25) md.registerExtension(self) def makeExtension(*args, **kwargs): """Return extension.""" return TasklistExtension(*args, **kwargs)
TasklistExtension
python
django-import-export__django-import-export
import_export/mixins.py
{ "start": 9433, "end": 10241 }
class ____(BaseExportMixin): # Deprecated, and will be removed in a future release (see #1666) form_class = SelectableFieldsExportForm def get_export_data(self, file_format, queryset, **kwargs): """ Returns file_format representation for given queryset. """ data = self.get_data_for_export(self.request, queryset, **kwargs) export_data = file_format.export_data(data) return export_data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["formats"] = self.get_export_formats() kwargs["resources"] = self.get_export_resource_classes(self.request) return kwargs
ExportViewMixin
python
numba__llvmlite
llvmlite/ir/_utils.py
{ "start": 87, "end": 856 }
class ____(object): def __init__(self): self._useset = set(['']) self._basenamemap = defaultdict(int) def is_used(self, name): return name in self._useset def register(self, name, deduplicate=False): if deduplicate: name = self.deduplicate(name) elif self.is_used(name): raise DuplicatedNameError(name) self._useset.add(name) return name def deduplicate(self, name): basename = name while self.is_used(name): ident = self._basenamemap[basename] + 1 self._basenamemap[basename] = ident name = "{0}.{1}".format(basename, ident) return name def get_child(self): return type(self)(parent=self)
NameScope
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/benchmark_test.py
{ "start": 2450, "end": 7972 }
class ____(test.TestCase): def testGlobalBenchmarkRegistry(self): registry = list(benchmark.GLOBAL_BENCHMARK_REGISTRY) self.assertEqual(len(registry), 2) self.assertTrue(SomeRandomBenchmark in registry) self.assertTrue(TestReportingBenchmark in registry) def testRunSomeRandomBenchmark(self): # Validate that SomeBenchmark has not run yet self.assertFalse(_ran_somebenchmark_1[0]) self.assertFalse(_ran_somebenchmark_2[0]) self.assertFalse(_ran_somebenchmark_but_shouldnt[0]) # Run other benchmarks, but this wont run the one we care about with self.assertRaises(ValueError): benchmark._run_benchmarks("unrelated") # Validate that SomeBenchmark has not run yet self.assertFalse(_ran_somebenchmark_1[0]) self.assertFalse(_ran_somebenchmark_2[0]) self.assertFalse(_ran_somebenchmark_but_shouldnt[0]) # Run all the benchmarks, avoid generating any reports if benchmark.TEST_REPORTER_TEST_ENV in os.environ: del os.environ[benchmark.TEST_REPORTER_TEST_ENV] benchmark._run_benchmarks("SomeRandom") # Validate that SomeRandomBenchmark ran correctly self.assertTrue(_ran_somebenchmark_1[0]) self.assertTrue(_ran_somebenchmark_2[0]) self.assertFalse(_ran_somebenchmark_but_shouldnt[0]) _ran_somebenchmark_1[0] = False _ran_somebenchmark_2[0] = False _ran_somebenchmark_but_shouldnt[0] = False # Test running a specific method of SomeRandomBenchmark if benchmark.TEST_REPORTER_TEST_ENV in os.environ: del os.environ[benchmark.TEST_REPORTER_TEST_ENV] benchmark._run_benchmarks("SomeRandom.*1$") self.assertTrue(_ran_somebenchmark_1[0]) self.assertFalse(_ran_somebenchmark_2[0]) self.assertFalse(_ran_somebenchmark_but_shouldnt[0]) def testReportingBenchmark(self): tempdir = test.get_temp_dir() try: gfile.MakeDirs(tempdir) except OSError as e: # It's OK if the directory already exists. if " exists:" not in str(e): raise e prefix = os.path.join(tempdir, "reporting_bench_%016x_" % random.getrandbits(64)) expected_output_file = "%s%s" % (prefix, "TestReportingBenchmark.benchmarkReport1") expected_output_file_2 = "%s%s" % ( prefix, "TestReportingBenchmark.custom_benchmark_name") expected_output_file_3 = "%s%s" % (prefix, "TestReportingBenchmark.op_benchmark") try: self.assertFalse(gfile.Exists(expected_output_file)) # Run benchmark but without env, shouldn't write anything if benchmark.TEST_REPORTER_TEST_ENV in os.environ: del os.environ[benchmark.TEST_REPORTER_TEST_ENV] reporting = TestReportingBenchmark() reporting.benchmarkReport1() # This should run without writing anything self.assertFalse(gfile.Exists(expected_output_file)) # Runbenchmark with env, should write os.environ[benchmark.TEST_REPORTER_TEST_ENV] = prefix reporting = TestReportingBenchmark() reporting.benchmarkReport1() # This should write reporting.benchmarkReport2() # This should write benchmark_values3 = reporting.benchmark_times_an_op() # This should write # Check the files were written self.assertTrue(gfile.Exists(expected_output_file)) self.assertTrue(gfile.Exists(expected_output_file_2)) self.assertTrue(gfile.Exists(expected_output_file_3)) # Check the contents are correct expected_1 = test_log_pb2.BenchmarkEntry() expected_1.name = "TestReportingBenchmark.benchmarkReport1" expected_1.iters = 1 expected_2 = test_log_pb2.BenchmarkEntry() expected_2.name = "TestReportingBenchmark.custom_benchmark_name" expected_2.iters = 2 expected_2.extras["number_key"].double_value = 3 expected_2.extras["other_key"].string_value = "string" expected_3 = test_log_pb2.BenchmarkEntry() expected_3.name = "TestReportingBenchmark.op_benchmark" expected_3.iters = 1000 def read_benchmark_entry(f): s = gfile.GFile(f, "rb").read() entries = test_log_pb2.BenchmarkEntries.FromString(s) self.assertEqual(1, len(entries.entry)) return entries.entry[0] read_benchmark_1 = read_benchmark_entry(expected_output_file) self.assertProtoEquals(expected_1, read_benchmark_1) read_benchmark_2 = read_benchmark_entry(expected_output_file_2) self.assertProtoEquals(expected_2, read_benchmark_2) read_benchmark_3 = read_benchmark_entry(expected_output_file_3) self.assertEqual(expected_3.name, read_benchmark_3.name) self.assertEqual(expected_3.iters, read_benchmark_3.iters) self.assertGreater(read_benchmark_3.wall_time, 0) # Trace is not stored in benchmark entry. Instead we get it from # return value of `run_op_benchmark` call. full_trace = benchmark_values3["extras"]["full_trace_chrome_format"] json_trace = json.loads(full_trace) self.assertTrue(isinstance(json_trace, dict)) self.assertTrue("traceEvents" in json_trace.keys()) allocator_keys = [k for k in read_benchmark_3.extras.keys() if k.startswith("allocator_maximum_num_bytes_")] self.assertGreater(len(allocator_keys), 0) for k in allocator_keys: self.assertGreater(read_benchmark_3.extras[k].double_value, 0) finally: gfile.DeleteRecursively(tempdir) if __name__ == "__main__": test.main()
BenchmarkTest
python
realpython__materials
contact-book-python-textual/source_code/rpcontacts/database.py
{ "start": 87, "end": 1366 }
class ____: def __init__(self, db_path=DATABASE_PATH): self.db = sqlite3.connect(db_path) self.cursor = self.db.cursor() self._create_table() def _create_table(self): query = """ CREATE TABLE IF NOT EXISTS contacts( id INTEGER PRIMARY KEY, name TEXT, phone TEXT, email TEXT ); """ self._run_query(query) def _run_query(self, query, *query_args): result = self.cursor.execute(query, [*query_args]) self.db.commit() return result def get_all_contacts(self): result = self._run_query("SELECT * FROM contacts;") return result.fetchall() def get_last_contact(self): result = self._run_query( "SELECT * FROM contacts ORDER BY id DESC LIMIT 1;" ) return result.fetchone() def add_contact(self, contact): self._run_query( "INSERT INTO contacts VALUES (NULL, ?, ?, ?);", *contact, ) def delete_contact(self, id): self._run_query( "DELETE FROM contacts WHERE id=(?);", id, ) def clear_all_contacts(self): self._run_query("DELETE FROM contacts;")
Database
python
tensorflow__tensorflow
tensorflow/python/keras/callbacks.py
{ "start": 60067, "end": 65320 }
class ____(Callback): """Callback to back up and restore the training state. `BackupAndRestore` callback is intended to recover from interruptions that happened in the middle of a model.fit execution by backing up the training states in a temporary checkpoint file (based on TF CheckpointManager) at the end of each epoch. If training restarted before completion, the training state and model are restored to the most recently saved state at the beginning of a new model.fit() run. Note that user is responsible to bring jobs back up. This callback is important for the backup and restore mechanism for fault tolerance purpose. And the model to be restored from an previous checkpoint is expected to be the same as the one used to back up. If user changes arguments passed to compile or fit, the checkpoint saved for fault tolerance can become invalid. Note: 1. This callback is not compatible with disabling eager execution. 2. A checkpoint is saved at the end of each epoch, when restoring we'll redo any partial work from an unfinished epoch in which the training got restarted (so the work done before a interruption doesn't affect the final model state). 3. This works for both single worker and multi-worker mode, only MirroredStrategy and MultiWorkerMirroredStrategy are supported for now. Example: >>> class InterruptingCallback(tf.keras.callbacks.Callback): ... def on_epoch_begin(self, epoch, logs=None): ... if epoch == 4: ... raise RuntimeError('Interrupting!') >>> callback = tf.keras.callbacks.experimental.BackupAndRestore( ... backup_dir="/tmp/backup") >>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) >>> model.compile(tf.keras.optimizers.SGD(), loss='mse') >>> try: ... model.fit(np.arange(100).reshape(5, 20), np.zeros(5), epochs=10, ... batch_size=1, callbacks=[callback, InterruptingCallback()], ... verbose=0) ... except: ... pass >>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5), epochs=10, ... batch_size=1, callbacks=[callback], verbose=0) >>> # Only 6 more epochs are run, since first training got interrupted at >>> # zero-indexed epoch 4, second training will continue from 4 to 9. >>> len(history.history['loss']) 6 Args: backup_dir: String, path to store the checkpoint. e.g. backup_dir = os.path.join(working_dir, 'backup') This is the directory in which the system stores temporary files to recover the model from jobs terminated unexpectedly. The directory cannot be reused elsewhere to store other files, e.g. by BackupAndRestore callback of another training, or by another callback (ModelCheckpoint) of the same training. """ def __init__(self, backup_dir): super(BackupAndRestore, self).__init__() self.backup_dir = backup_dir self._supports_tf_logs = True self._supported_strategies = ( mirrored_strategy.MirroredStrategy, collective_all_reduce_strategy.CollectiveAllReduceStrategy, tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV2, parameter_server_strategy_v2.ParameterServerStrategyV2) if not context.executing_eagerly(): if ops.inside_function(): raise ValueError('This Callback\'s method contains Python state and ' 'should be called outside of `tf.function`s.') else: # Legacy graph mode: raise ValueError( 'BackupAndRestore only supports eager mode. In graph ' 'mode, consider using ModelCheckpoint to manually save ' 'and restore weights with `model.load_weights()` and by ' 'providing `initial_epoch` in `model.fit()` for fault tolerance.') # Only the chief worker writes model checkpoints, but all workers # restore checkpoint at on_train_begin(). self._chief_worker_only = False def on_train_begin(self, logs=None): # TrainingState is used to manage the training state needed for # failure-recovery of a worker in training. # pylint: disable=protected-access if self.model._distribution_strategy and not isinstance( self.model.distribute_strategy, self._supported_strategies): raise NotImplementedError( '%s is not supported yet. ' 'Currently BackupAndRestore callback only supports empty strategy, ' 'MirroredStrategy, MultiWorkerMirroredStrategy and TPUStrategy.' % type(self.model.distribute_strategy).__name__) self.model._training_state = ( worker_training_state.WorkerTrainingState(self.model, self.backup_dir)) self._training_state = self.model._training_state self._training_state.restore() def on_train_end(self, logs=None): # pylint: disable=protected-access # On exit of training, delete the training state backup file that was saved # for the purpose of worker recovery. self._training_state.delete_backup() # Clean up the training state. del self._training_state del self.model._training_state def on_epoch_end(self, epoch, logs=None): # Back up the model and current epoch for possible future recovery. self._training_state.back_up(epoch)
BackupAndRestore
python
getsentry__sentry
src/sentry/utils/sdk_crashes/sdk_crash_detector.py
{ "start": 333, "end": 5593 }
class ____: def __init__( self, config: SDKCrashDetectionConfig, ): self.config = config @property def fields_containing_paths(self) -> set[str]: return {"package", "module", "path", "abs_path", "filename"} def replace_sdk_frame_path(self, path_field: str, path_value: str) -> str | None: return self.config.sdk_frame_config.path_replacer.replace_path(path_field, path_value) def is_sdk_supported( self, sdk_name: str, sdk_version: str, ) -> bool: minimum_sdk_version_string = self.config.sdk_names.get(sdk_name) if not minimum_sdk_version_string: return False try: minimum_sdk_version = Version(minimum_sdk_version_string) actual_sdk_version = Version(sdk_version) if actual_sdk_version < minimum_sdk_version: return False except InvalidVersion: return False return True def should_detect_sdk_crash( self, sdk_name: str, sdk_version: str, event_data: NodeData ) -> bool: if not self.is_sdk_supported(sdk_name, sdk_version): return False mechanism_type = get_path(event_data, "exception", "values", -1, "mechanism", "type") if mechanism_type and mechanism_type in self.config.ignore_mechanism_type: return False if mechanism_type and mechanism_type in self.config.allow_mechanism_type: return True is_unhandled = ( get_path(event_data, "exception", "values", -1, "mechanism", "handled") is False ) if is_unhandled: return True is_fatal = get_path(event_data, "level") == "fatal" if is_fatal and self.config.report_fatal_errors: return True return False def is_sdk_crash(self, frames: Sequence[Mapping[str, Any]]) -> bool: """ Returns true if the stacktrace stems from an SDK crash. :param frames: The stacktrace frames ordered from newest to oldest. """ if not frames: return False # The frames are ordered from caller to callee, or oldest to youngest. # The last frame is the one creating the exception. # Therefore, we must iterate in reverse order. # In a first iteration of this algorithm, we checked for in_app frames, but # customers can change the in_app configuration, so we can't rely on that. # Furthermore, if they use static linking for including, for example, the Sentry Cocoa, # Cocoa SDK frames can be marked as in_app. Therefore, the algorithm only checks if frames # are SDK frames or from system libraries. iter_frames = [f for f in reversed(frames) if f is not None] for frame in iter_frames: function = frame.get("function") module = frame.get("module") if function: for matcher in self.config.sdk_crash_ignore_matchers: function_matches = glob_match( function, matcher.function_pattern, ignorecase=True ) module_matches = glob_match(module, matcher.module_pattern, ignorecase=True) if function_matches and module_matches: return False if self.is_sdk_frame(frame): return True if not self.is_system_library_frame(frame): return False return False def is_sdk_frame(self, frame: Mapping[str, Any]) -> bool: """ Returns true if frame is an SDK frame. :param frame: The frame of a stacktrace. """ function = frame.get("function") if function: for ( function_and_path_pattern ) in self.config.sdk_frame_config.function_and_path_patterns: function_pattern = function_and_path_pattern.function_pattern path_pattern = function_and_path_pattern.path_pattern function_matches = glob_match(function, function_pattern, ignorecase=True) path_matches = self._path_patters_match_frame({path_pattern}, frame) if function_matches and path_matches: return True for patterns in self.config.sdk_frame_config.function_patterns: if glob_match(function, patterns, ignorecase=True): return True return self._path_patters_match_frame(self.config.sdk_frame_config.path_patterns, frame) def is_system_library_frame(self, frame: Mapping[str, Any]) -> bool: return self._path_patters_match_frame(self.config.system_library_path_patterns, frame) def _path_patters_match_frame(self, path_patters: set[str], frame: Mapping[str, Any]) -> bool: for field in self.fields_containing_paths: for pattern in path_patters: field_with_path = frame.get(field) if field_with_path and glob_match( field_with_path, pattern, ignorecase=True, doublestar=True, path_normalize=True ): return True return False
SDKCrashDetector
python
PyCQA__pylint
tests/functional/t/try_except_raise.py
{ "start": 1439, "end": 2266 }
class ____: error1 = FileNotFoundError error2 = PermissionError parent_error=OSError try: pass except (NameSpace.error1, NameSpace.error2): raise except NameSpace.parent_error: print("a failure") # also consider tuples for subsequent exception handler instead of just bare except handler try: pass except (FileNotFoundError, PermissionError): raise except (OverflowError, OSError): print("a failure") try: pass except (FileNotFoundError, PermissionError): # [try-except-raise] raise except (OverflowError, ZeroDivisionError): print("a failure") try: pass except (FileNotFoundError, PermissionError): raise except Exception: print("a failure") try: pass except (FileNotFoundError, PermissionError): raise except (Exception,): print("a failure")
NameSpace
python
scikit-image__scikit-image
benchmarks/benchmark_metrics.py
{ "start": 161, "end": 776 }
class ____: shape = (6, 6) coords_a = np.zeros(shape, dtype=bool) coords_b = np.zeros(shape, dtype=bool) def setup(self): points_a = (1, 0) points_b = (5, 2) self.coords_a[points_a] = True self.coords_b[points_b] = True def time_hausdorff_distance(self): metrics.hausdorff_distance(self.coords_a, self.coords_b) def time_modified_hausdorff_distance(self): metrics.hausdorff_distance(self.coords_a, self.coords_b, method="modified") def time_hausdorff_pair(self): metrics.hausdorff_pair(self.coords_a, self.coords_b)
SetMetricsSuite
python
dagster-io__dagster
python_modules/libraries/dagster-duckdb-pyspark/dagster_duckdb_pyspark/duckdb_pyspark_type_handler.py
{ "start": 6400, "end": 9557 }
class ____(DuckDBIOManager): """An I/O manager definition that reads inputs from and writes PySpark DataFrames to DuckDB. When using the DuckDBPySparkIOManager, any inputs and outputs without type annotations will be loaded as PySpark DataFrames. Returns: IOManagerDefinition Examples: .. code-block:: python from dagster_duckdb_pyspark import DuckDBPySparkIOManager @asset( key_prefix=["my_schema"] # will be used as the schema in DuckDB ) def my_table() -> pyspark.sql.DataFrame: # the name of the asset will be the table name ... Definitions( assets=[my_table], resources={"io_manager": DuckDBPySparkIOManager(database="my_db.duckdb")} ) You can set a default schema to store the assets using the ``schema`` configuration value of the DuckDB I/O Manager. This schema will be used if no other schema is specified directly on an asset or op. .. code-block:: python Definitions( assets=[my_table], resources={"io_manager": DuckDBPySparkIOManager(database="my_db.duckdb", 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 duckdb ) def my_table() -> pyspark.sql.DataFrame: ... @asset( metadata={"schema": "my_schema"} # will be used as the schema in duckdb ) def my_other_table() -> pyspark.sql.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() -> pyspark.sql.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: pyspark.sql.DataFrame) -> pyspark.sql.DataFrame: # my_table will just contain the data from column "a" ... """ @classmethod def _is_dagster_maintained(cls) -> bool: return True @staticmethod def type_handlers() -> Sequence[DbTypeHandler]: return [DuckDBPySparkTypeHandler()] @staticmethod def default_load_type() -> Optional[type]: return pyspark.sql.DataFrame
DuckDBPySparkIOManager
python
mlflow__mlflow
mlflow/server/jobs/__init__.py
{ "start": 1010, "end": 7177 }
class ____: fn_fullname: str max_workers: int transient_error_classes: list[type[Exception]] | None = None python_env: _PythonEnv | None = None def job( max_workers: int, transient_error_classes: list[type[Exception]] | None = None, python_version: str | None = None, pip_requirements: list[str] | None = None, ) -> Callable[[Callable[P, R]], Callable[P, R]]: """ The decorator for the custom job function for setting max parallel workers that the job function can use. Each job is executed in an individual subprocess. Args: max_workers: The maximum number of workers that are allowed to run the jobs using this job function. transient_error_classes: (optional) Specify a list of classes that are regarded as transient error classes. python_version: (optional) The required python version to run the job function. pip_requirements: (optional) The required pip requirements to run the job function, relative file references such as "-r requirements.txt" are not supported. """ from mlflow.utils import PYTHON_VERSION from mlflow.utils.requirements_utils import _parse_requirements from mlflow.version import VERSION if not python_version and not pip_requirements: python_env = None else: python_version = python_version or PYTHON_VERSION try: pip_requirements = [ req.req_str for req in _parse_requirements(pip_requirements, is_constraint=False) ] except Exception as e: raise MlflowException.invalid_parameter_value( f"Invalid pip_requirements for job function: {pip_requirements}, " f"parsing error: {e!r}" ) if mlflow_home := os.environ.get("MLFLOW_HOME"): # Append MLflow dev version dependency (for testing) pip_requirements += [mlflow_home] else: pip_requirements += [f"mlflow=={VERSION}"] python_env = _PythonEnv( python=python_version, dependencies=pip_requirements, ) def decorator(fn: Callable[P, R]) -> Callable[P, R]: fn._job_fn_metadata = JobFunctionMetadata( fn_fullname=f"{fn.__module__}.{fn.__name__}", max_workers=max_workers, transient_error_classes=transient_error_classes, python_env=python_env, ) return fn return decorator def submit_job( function: Callable[..., Any], params: dict[str, Any], timeout: float | None = None, ) -> JobEntity: """ Submit a job to the job queue. The job is executed at most once. If the MLflow server crashes while the job is pending or running, it is rescheduled on restart. Note: This is a server-side API and requires the MLflow server to configure the backend store URI to a database URI. Args: function: The job function, it must be a python module-level function, and all params and return value must be JSON-serializable. The function can raise `TransientError` in order to trigger job retry, or you can annotate a list of transient error classes by ``@job(..., transient_error_classes=[...])``. You can set `MLFLOW_SERVER_JOB_TRANSIENT_ERROR_MAX_RETRIES` to configure maximum allowed retries for transient errors and set `MLFLOW_SERVER_JOB_TRANSIENT_ERROR_RETRY_BASE_DELAY` to configure base retry delay in seconds. The function must be decorated by `mlflow.server.jobs.job_function` decorator. params: The params to be passed to the job function. timeout: (optional) The job execution timeout, default None (no timeout) Returns: The job entity. You can call `get_job` API by the job id to get the updated job entity. """ from mlflow.environment_variables import MLFLOW_SERVER_ENABLE_JOB_EXECUTION from mlflow.server.jobs.utils import ( _check_requirements, _get_or_init_huey_instance, _validate_function_parameters, ) if not MLFLOW_SERVER_ENABLE_JOB_EXECUTION.get(): raise MlflowException( "Mlflow server job execution feature is not enabled, please set " "environment variable 'MLFLOW_SERVER_ENABLE_JOB_EXECUTION' to 'true' to enable it." ) _check_requirements() if not (isinstance(function, FunctionType) and "." not in function.__qualname__): raise MlflowException("The job function must be a python global function.") func_fullname = f"{function.__module__}.{function.__name__}" if func_fullname not in _ALLOWED_JOB_FUNCTION_LIST: raise MlflowException.invalid_parameter_value( f"The function {func_fullname} is not in the allowed job function list" ) if not hasattr(function, "_job_fn_metadata"): raise MlflowException( f"The job function {func_fullname} is not decorated by " "'mlflow.server.jobs.job_function'." ) if not isinstance(params, dict): raise MlflowException.invalid_parameter_value( "When calling 'submit_job', the 'params' argument must be a dict." ) # Validate that required parameters are provided _validate_function_parameters(function, params) job_store = _get_job_store() serialized_params = json.dumps(params) job = job_store.create_job(func_fullname, serialized_params, timeout) # enqueue job _get_or_init_huey_instance(func_fullname).submit_task( job.job_id, function, params, timeout, ) return job def get_job(job_id: str) -> JobEntity: """ Get the job entity by the job id. Note: This is a server-side API, and it requires MLflow server configures backend store URI to database URI. Args: job_id: The job id. Returns: The job entity. If the job does not exist, error is raised. """ job_store = _get_job_store() return job_store.get_job(job_id)
JobFunctionMetadata
python
protocolbuffers__protobuf
python/google/protobuf/symbol_database.py
{ "start": 1550, "end": 5752 }
class ____(): """A database of Python generated symbols.""" # local cache of registered classes. _classes = {} def __init__(self, pool=None): """Initializes a new SymbolDatabase.""" self.pool = pool or descriptor_pool.DescriptorPool() def RegisterMessage(self, message): """Registers the given message type in the local database. Calls to GetSymbol() and GetMessages() will return messages registered here. Args: message: A :class:`google.protobuf.message.Message` subclass (or instance); its descriptor will be registered. Returns: The provided message. """ desc = message.DESCRIPTOR self._classes[desc] = message self.RegisterMessageDescriptor(desc) return message def RegisterMessageDescriptor(self, message_descriptor): """Registers the given message descriptor in the local database. Args: message_descriptor (Descriptor): the message descriptor to add. """ if api_implementation.Type() == 'python': # pylint: disable=protected-access self.pool._AddDescriptor(message_descriptor) def RegisterEnumDescriptor(self, enum_descriptor): """Registers the given enum descriptor in the local database. Args: enum_descriptor (EnumDescriptor): The enum descriptor to register. Returns: EnumDescriptor: The provided descriptor. """ if api_implementation.Type() == 'python': # pylint: disable=protected-access self.pool._AddEnumDescriptor(enum_descriptor) return enum_descriptor def RegisterServiceDescriptor(self, service_descriptor): """Registers the given service descriptor in the local database. Args: service_descriptor (ServiceDescriptor): the service descriptor to register. """ if api_implementation.Type() == 'python': # pylint: disable=protected-access self.pool._AddServiceDescriptor(service_descriptor) def RegisterFileDescriptor(self, file_descriptor): """Registers the given file descriptor in the local database. Args: file_descriptor (FileDescriptor): The file descriptor to register. """ if api_implementation.Type() == 'python': # pylint: disable=protected-access self.pool._InternalAddFileDescriptor(file_descriptor) def GetSymbol(self, symbol): """Tries to find a symbol in the local database. Currently, this method only returns message.Message instances, however, if may be extended in future to support other symbol types. Args: symbol (str): a protocol buffer symbol. Returns: A Python class corresponding to the symbol. Raises: KeyError: if the symbol could not be found. """ return self._classes[self.pool.FindMessageTypeByName(symbol)] def GetMessages(self, files): # TODO: Fix the differences with MessageFactory. """Gets all registered messages from a specified file. Only messages already created and registered will be returned; (this is the case for imported _pb2 modules) But unlike MessageFactory, this version also returns already defined nested messages, but does not register any message extensions. Args: files (list[str]): The file names to extract messages from. Returns: A dictionary mapping proto names to the message classes. Raises: KeyError: if a file could not be found. """ def _GetAllMessages(desc): """Walk a message Descriptor and recursively yields all message names.""" yield desc for msg_desc in desc.nested_types: for nested_desc in _GetAllMessages(msg_desc): yield nested_desc result = {} for file_name in files: file_desc = self.pool.FindFileByName(file_name) for msg_desc in file_desc.message_types_by_name.values(): for desc in _GetAllMessages(msg_desc): try: result[desc.full_name] = self._classes[desc] except KeyError: # This descriptor has no registered class, skip it. pass return result _DEFAULT = SymbolDatabase(pool=descriptor_pool.Default()) def Default(): """Returns the default SymbolDatabase.""" return _DEFAULT
SymbolDatabase
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/utils/time_window.py
{ "start": 1455, "end": 1583 }
class ____(Enum): MATERIALIZING = "MATERIALIZING" MATERIALIZED = "MATERIALIZED" FAILED = "FAILED"
PartitionRangeStatus
python
cherrypy__cherrypy
cherrypy/test/helper.py
{ "start": 5615, "end": 13597 }
class ____(webtest.WebCase): """CherryPy web test case base.""" script_name = '' scheme = 'http' available_servers = { 'wsgi': LocalWSGISupervisor, 'wsgi_u': get_wsgi_u_supervisor, 'native': NativeServerSupervisor, 'cpmodpy': get_cpmodpy_supervisor, 'modpygw': get_modpygw_supervisor, 'modwsgi': get_modwsgi_supervisor, 'modfcgid': get_modfcgid_supervisor, 'modfastcgi': get_modfastcgi_supervisor, } default_server = 'wsgi' @classmethod def _setup_server(cls, supervisor, conf): v = sys.version.split()[0] log.info('Python version used to run this test script: %s' % v) log.info('CherryPy version: %s' % cherrypy.__version__) if supervisor.scheme == 'https': ssl = ' (ssl)' else: ssl = '' log.info('HTTP server version: %s%s' % (supervisor.protocol, ssl)) log.info('PID: %s' % os.getpid()) cherrypy.server.using_apache = supervisor.using_apache cherrypy.server.using_wsgi = supervisor.using_wsgi if sys.platform[:4] == 'java': cherrypy.config.update({'server.nodelay': False}) if isinstance(conf, text_or_bytes): parser = cherrypy.lib.reprconf.Parser() conf = parser.dict_from_file(conf).get('global', {}) else: conf = conf or {} baseconf = conf.copy() baseconf.update( { 'server.socket_host': supervisor.host, 'server.socket_port': supervisor.port, 'server.protocol_version': supervisor.protocol, 'environment': 'test_suite', }, ) if supervisor.scheme == 'https': # baseconf['server.ssl_module'] = 'builtin' baseconf['server.ssl_certificate'] = serverpem baseconf['server.ssl_private_key'] = serverpem # helper must be imported lazily so the coverage tool # can run against module-level statements within cherrypy. # Also, we have to do "from cherrypy.test import helper", # exactly like each test module does, because a relative import # would stick a second instance of webtest in sys.modules, # and we wouldn't be able to globally override the port anymore. if supervisor.scheme == 'https': webtest.WebCase.HTTP_CONN = HTTPSConnection return baseconf @classmethod def setup_class(cls): """Invoke a test server.""" conf = { 'scheme': 'http', 'protocol': 'HTTP/1.1', 'port': 54583, 'host': '127.0.0.1', 'validate': False, 'server': 'wsgi', } supervisor_factory = cls.available_servers.get( conf.get('server', 'wsgi'), ) if supervisor_factory is None: raise RuntimeError('Unknown server in config: %s' % conf['server']) supervisor = supervisor_factory(**conf) # Copied from "run_test_suite" cherrypy.config.reset() baseconf = cls._setup_server(supervisor, conf) cherrypy.config.update(baseconf) setup_client() if hasattr(cls, 'setup_server'): # Clear the cherrypy tree and clear the wsgi server so that # it can be updated with the new root cherrypy.tree = cherrypy._cptree.Tree() cherrypy.server.httpserver = None cls.setup_server() # Add a resource for verifying there are no refleaks # to *every* test class. cherrypy.tree.mount(gctools.GCRoot(), '/gc') cls.do_gc_test = not IS_PYPY supervisor.start(cls.__module__) cls.supervisor = supervisor @classmethod def teardown_class(cls): """Tear down the test server.""" if hasattr(cls, 'setup_server'): cls.supervisor.stop() do_gc_test = False def test_gc(self): """Perform the garbage collection testing.""" if not self.do_gc_test: return self.getPage('/gc/stats') try: self.assertBody('Statistics:') except Exception: 'Failures occur intermittently. See #1420' def prefix(self): """Get an HTTP handler prefix.""" return self.script_name.rstrip('/') def base(self): """Construct the base server URL.""" if (self.scheme == 'http' and self.PORT == 80) or ( self.scheme == 'https' and self.PORT == 443 ): port = '' else: port = ':%s' % self.PORT return '%s://%s%s%s' % ( self.scheme, self.HOST, port, self.script_name.rstrip('/'), ) def exit(self): """Terminate the program.""" sys.exit() def getPage(self, url, *args, **kwargs): """Open the url.""" if self.script_name: url = httputil.urljoin(self.script_name, url) return webtest.WebCase.getPage(self, url, *args, **kwargs) def skip(self, msg='skipped '): """Skip the currently running test.""" pytest.skip(msg) def assertErrorPage(self, status, message=None, pattern=''): """Compare the response body with a built in error page. The function will optionally look for the regexp pattern, within the exception embedded in the error page. """ # This will never contain a traceback page = cherrypy._cperror.get_error_page(status, message=message) # First, test the response body without checking the traceback. # Stick a match-all group (.*) in to grab the traceback. def esc(text): return re.escape(ntob(text)) epage = re.escape(page) epage = epage.replace( esc('<pre id="traceback"></pre>'), esc('<pre id="traceback">') + b'(.*)' + esc('</pre>'), ) m = re.match(epage, self.body, re.DOTALL) if not m: self._handlewebError( 'Error page does not match; expected:\n' + page, ) return # Now test the pattern against the traceback if pattern is None: # Special-case None to mean that there should be *no* traceback. if m and m.group(1): self._handlewebError('Error page contains traceback') else: if (m is None) or ( not re.search( ntob(re.escape(pattern), self.encoding), m.group(1), ) ): msg = 'Error page does not contain %s in traceback' self._handlewebError(msg % repr(pattern)) date_tolerance = 2 def assertEqualDates(self, dt1, dt2, seconds=None): """Assert abs(dt1 - dt2) is within Y seconds.""" if seconds is None: seconds = self.date_tolerance if dt1 > dt2: diff = dt1 - dt2 else: diff = dt2 - dt1 if not diff < datetime.timedelta(seconds=seconds): raise AssertionError( '%r and %r are not within %r seconds.' % (dt1, dt2, seconds), ) def _test_method_sorter(_, x, y): """Monkeypatch the test sorter to always run test_gc last in each suite.""" if x == 'test_gc': return 1 if y == 'test_gc': return -1 if x > y: return 1 if x < y: return -1 return 0 unittest.TestLoader.sortTestMethodsUsing = _test_method_sorter def setup_client(): """Set up the WebCase classes to match the server's socket settings.""" webtest.WebCase.PORT = cherrypy.server.socket_port webtest.WebCase.HOST = cherrypy.server.socket_host if cherrypy.server.ssl_certificate: CPWebCase.scheme = 'https' # --------------------------- Spawning helpers --------------------------- #
CPWebCase
python
tensorflow__tensorflow
tensorflow/python/keras/engine/training_generator_v1.py
{ "start": 21759, "end": 24618 }
class ____(training_utils_v1.TrainingLoop): """Generator-like. Input is Python generator, or Sequence object. The difference between this class and `GeneratorLikeTrainingFunction` is that this class only handles inputs that with x, y and sample_weight fused into one param. """ def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False): model._validate_or_infer_batch_size(batch_size, steps_per_epoch, x) training_utils_v1.check_generator_arguments( y, sample_weight, validation_split=validation_split) return fit_generator( model, x, steps_per_epoch=steps_per_epoch, epochs=epochs, verbose=verbose, callbacks=callbacks, validation_data=validation_data, validation_steps=validation_steps, validation_freq=validation_freq, class_weight=class_weight, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, shuffle=shuffle, initial_epoch=initial_epoch, steps_name='steps_per_epoch') def evaluate(self, model, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False): model._validate_or_infer_batch_size(batch_size, steps, x) training_utils_v1.check_generator_arguments(y, sample_weight) return evaluate_generator( model, x, steps=steps, verbose=verbose, callbacks=callbacks, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing) def predict(self, model, x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False): model._validate_or_infer_batch_size(batch_size, steps, x) return predict_generator( model, x, steps=steps, verbose=verbose, callbacks=callbacks, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing)
GeneratorOrSequenceTrainingLoop
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methods1.py
{ "start": 778, "end": 946 }
class ____: def __init__(self, func: Callable[..., Any]): self.func = func def __call__(self) -> None: print("Deco4.__call__:", f"{self=}")
Deco4
python
huggingface__transformers
tests/models/cpmant/test_tokenization_cpmant.py
{ "start": 906, "end": 2557 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "openbmb/cpm-ant-10b" tokenizer_class = CpmAntTokenizer test_rust_tokenizer = False @classmethod def setUpClass(cls): super().setUpClass() old_tmpdirname = cls.tmpdirname cls.tmpdirname = tempfile.mkdtemp() vocab_tokens = [ "<d>", "</d>", "<s>", "</s>", "</_>", "<unk>", "<pad>", "</n>", "我", "是", "C", "P", "M", "A", "n", "t", ] cls.vocab_file = os.path.join(cls.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) with open(cls.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) shutil.rmtree(old_tmpdirname, ignore_errors=True) @tooslow def test_pre_tokenization(self): tokenizer = CpmAntTokenizer.from_pretrained("openbmb/cpm-ant-10b") texts = "今天天气真好!" rjieba_tokens = ["今天", "天气", "真", "好", "!"] tokens = tokenizer.tokenize(texts) self.assertListEqual(tokens, rjieba_tokens) normalized_text = "今天天气真好!" input_tokens = [tokenizer.bos_token] + tokens input_rjieba_tokens = [6, 9802, 14962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_rjieba_tokens) reconstructed_text = tokenizer.decode(input_rjieba_tokens) self.assertEqual(reconstructed_text, normalized_text)
CPMAntTokenizationTest