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
readthedocs__readthedocs.org
readthedocs/subscriptions/tests/test_products.py
{ "start": 189, "end": 2073 }
class ____(TestCase): def test_add_feature(self): feature_a = RTDProductFeature(TYPE_CONCURRENT_BUILDS, value=1) feature_b = RTDProductFeature(TYPE_CONCURRENT_BUILDS, value=2) feature_c = feature_a + feature_b self.assertEqual(feature_c.unlimited, False) self.assertEqual(feature_c.value, 3) self.assertEqual(feature_c.type, TYPE_CONCURRENT_BUILDS) def test_add_feature_unlimited(self): feature_a = RTDProductFeature(TYPE_CONCURRENT_BUILDS, value=1) feature_b = RTDProductFeature(TYPE_CONCURRENT_BUILDS, unlimited=True) feature_c = feature_a + feature_b self.assertEqual(feature_c.unlimited, True) self.assertEqual(feature_c.type, TYPE_CONCURRENT_BUILDS) def test_add_different_features(self): feature_a = RTDProductFeature(TYPE_CONCURRENT_BUILDS, value=1) feature_b = RTDProductFeature(TYPE_AUDIT_LOGS, value=2) with self.assertRaises(ValueError): feature_a + feature_b def test_multiply_feature(self): feature_a = RTDProductFeature(TYPE_CONCURRENT_BUILDS, value=3) feature_b = feature_a * 2 self.assertEqual(feature_b.value, 6) self.assertEqual(feature_b.unlimited, False) self.assertEqual(feature_b.type, TYPE_CONCURRENT_BUILDS) feature_a = RTDProductFeature(TYPE_CONCURRENT_BUILDS, value=3) feature_b = feature_a * 1 self.assertEqual(feature_b.value, 3) self.assertEqual(feature_b.unlimited, False) self.assertEqual(feature_b.type, TYPE_CONCURRENT_BUILDS) def test_multiply_feature_unlimited(self): feature_a = RTDProductFeature(TYPE_CONCURRENT_BUILDS, unlimited=True) feature_b = feature_a * 2 self.assertEqual(feature_b.unlimited, True) self.assertEqual(feature_b.type, TYPE_CONCURRENT_BUILDS)
TestRTDProductFeature
python
aio-libs__aiohttp
aiohttp/web_urldispatcher.py
{ "start": 30202, "end": 30647 }
class ____(Sized, Iterable[AbstractResource], Container[AbstractResource]): def __init__(self, resources: list[AbstractResource]) -> None: self._resources = resources def __len__(self) -> int: return len(self._resources) def __iter__(self) -> Iterator[AbstractResource]: yield from self._resources def __contains__(self, resource: object) -> bool: return resource in self._resources
ResourcesView
python
django__django
tests/queries/models.py
{ "start": 9454, "end": 9494 }
class ____(ObjectA): pass
ChildObjectA
python
scikit-learn__scikit-learn
sklearn/linear_model/_stochastic_gradient.py
{ "start": 17141, "end": 31423 }
class ____(LinearClassifierMixin, BaseSGD, metaclass=ABCMeta): loss_functions = { "hinge": (Hinge, 1.0), "squared_hinge": (SquaredHinge, 1.0), "perceptron": (Hinge, 0.0), "log_loss": (CyHalfBinomialLoss,), "modified_huber": (ModifiedHuber,), "squared_error": (CyHalfSquaredError,), "huber": (CyHuberLoss, DEFAULT_EPSILON), "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, DEFAULT_EPSILON), } _parameter_constraints: dict = { **BaseSGD._parameter_constraints, "loss": [StrOptions(set(loss_functions))], "early_stopping": ["boolean"], "validation_fraction": [Interval(Real, 0, 1, closed="neither")], "n_iter_no_change": [Interval(Integral, 1, None, closed="left")], "n_jobs": [Integral, None], "class_weight": [StrOptions({"balanced"}), dict, None], } @abstractmethod def __init__( self, loss="hinge", *, penalty="l2", alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=None, random_state=None, learning_rate="optimal", eta0=0.01, power_t=0.5, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, class_weight=None, warm_start=False, average=False, ): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, warm_start=warm_start, average=average, ) self.class_weight = class_weight self.n_jobs = n_jobs def _partial_fit( self, X, y, alpha, loss, learning_rate, max_iter, classes, sample_weight, coef_init, intercept_init, ): first_call = not hasattr(self, "classes_") X, y = validate_data( self, X, y, accept_sparse="csr", dtype=[np.float64, np.float32], order="C", accept_large_sparse=False, reset=first_call, ) n_samples, n_features = X.shape _check_partial_fit_first_call(self, classes) n_classes = self.classes_.shape[0] # Allocate datastructures from input arguments self._expanded_class_weight = compute_class_weight( self.class_weight, classes=self.classes_, y=y ) sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) if getattr(self, "coef_", None) is None or coef_init is not None: self._allocate_parameter_mem( n_classes=n_classes, n_features=n_features, input_dtype=X.dtype, coef_init=coef_init, intercept_init=intercept_init, ) elif n_features != self.coef_.shape[-1]: raise ValueError( "Number of features %d does not match previous data %d." % (n_features, self.coef_.shape[-1]) ) self._loss_function_ = self._get_loss_function(loss) if not hasattr(self, "t_"): self.t_ = 1.0 # delegate to concrete training procedure if n_classes > 2: self._fit_multiclass( X, y, alpha=alpha, learning_rate=learning_rate, sample_weight=sample_weight, max_iter=max_iter, ) elif n_classes == 2: self._fit_binary( X, y, alpha=alpha, learning_rate=learning_rate, sample_weight=sample_weight, max_iter=max_iter, ) else: raise ValueError( "The number of classes has to be greater than one; got %d class" % n_classes ) return self def _fit( self, X, y, alpha, loss, learning_rate, coef_init=None, intercept_init=None, sample_weight=None, ): if hasattr(self, "classes_"): # delete the attribute otherwise _partial_fit thinks it's not the first call delattr(self, "classes_") # labels can be encoded as float, int, or string literals # np.unique sorts in asc order; largest class id is positive class y = validate_data(self, y=y) classes = np.unique(y) if self.warm_start and hasattr(self, "coef_"): if coef_init is None: coef_init = self.coef_ if intercept_init is None: intercept_init = self.intercept_ else: self.coef_ = None self.intercept_ = None if self.average > 0: self._standard_coef = self.coef_ self._standard_intercept = self.intercept_ self._average_coef = None self._average_intercept = None # Clear iteration count for multiple call to fit. self.t_ = 1.0 self._partial_fit( X, y, alpha, loss, learning_rate, self.max_iter, classes, sample_weight, coef_init, intercept_init, ) if ( self.tol is not None and self.tol > -np.inf and self.n_iter_ == self.max_iter ): warnings.warn( ( "Maximum number of iteration reached before " "convergence. Consider increasing max_iter to " "improve the fit." ), ConvergenceWarning, ) if self.power_t < 0: warnings.warn( "Negative values for `power_t` are deprecated in version 1.8 " "and will raise an error in 1.10. " "Use values in the range [0.0, inf) instead.", FutureWarning, ) return self def _fit_binary(self, X, y, alpha, sample_weight, learning_rate, max_iter): """Fit a binary classifier on X and y.""" coef, intercept, n_iter_ = fit_binary( self, 1, X, y, alpha, learning_rate, max_iter, self._expanded_class_weight[1], self._expanded_class_weight[0], sample_weight, random_state=self.random_state, ) self.t_ += n_iter_ * X.shape[0] self.n_iter_ = n_iter_ # need to be 2d if self.average > 0: if self.average <= self.t_ - 1: self.coef_ = self._average_coef.reshape(1, -1) self.intercept_ = self._average_intercept else: self.coef_ = self._standard_coef.reshape(1, -1) self._standard_intercept = np.atleast_1d(intercept) self.intercept_ = self._standard_intercept else: self.coef_ = coef.reshape(1, -1) # intercept is a float, need to convert it to an array of length 1 self.intercept_ = np.atleast_1d(intercept) def _fit_multiclass(self, X, y, alpha, learning_rate, sample_weight, max_iter): """Fit a multi-class classifier by combining binary classifiers Each binary classifier predicts one class versus all others. This strategy is called OvA (One versus All) or OvR (One versus Rest). """ # Precompute the validation split using the multiclass labels # to ensure proper balancing of the classes. validation_mask = self._make_validation_split(y, sample_mask=sample_weight > 0) # Use joblib to fit OvA in parallel. # Pick the random seed for each job outside of fit_binary to avoid # sharing the estimator random state between threads which could lead # to non-deterministic behavior random_state = check_random_state(self.random_state) seeds = random_state.randint(MAX_INT, size=len(self.classes_)) result = Parallel( n_jobs=self.n_jobs, verbose=self.verbose, require="sharedmem" )( delayed(fit_binary)( self, i, X, y, alpha, learning_rate, max_iter, self._expanded_class_weight[i], 1.0, sample_weight, validation_mask=validation_mask, random_state=seed, ) for i, seed in enumerate(seeds) ) # take the maximum of n_iter_ over every binary fit n_iter_ = 0.0 for i, (_, intercept, n_iter_i) in enumerate(result): self.intercept_[i] = intercept n_iter_ = max(n_iter_, n_iter_i) self.t_ += n_iter_ * X.shape[0] self.n_iter_ = n_iter_ if self.average > 0: if self.average <= self.t_ - 1.0: self.coef_ = self._average_coef self.intercept_ = self._average_intercept else: self.coef_ = self._standard_coef self._standard_intercept = np.atleast_1d(self.intercept_) self.intercept_ = self._standard_intercept @_fit_context(prefer_skip_nested_validation=True) def partial_fit(self, X, y, classes=None, sample_weight=None): """Perform one epoch of stochastic gradient descent on given samples. Internally, this method uses ``max_iter = 1``. Therefore, it is not guaranteed that a minimum of the cost function is reached after calling it once. Matters such as objective convergence, early stopping, and learning rate adjustments should be handled by the user. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Subset of the training data. y : ndarray of shape (n_samples,) Subset of the target values. classes : ndarray of shape (n_classes,), default=None Classes across all calls to partial_fit. Can be obtained by via `np.unique(y_all)`, where y_all is the target vector of the entire dataset. This argument is required for the first call to partial_fit and can be omitted in the subsequent calls. Note that y doesn't need to contain all labels in `classes`. sample_weight : array-like, shape (n_samples,), default=None Weights applied to individual samples. If not provided, uniform weights are assumed. Returns ------- self : object Returns an instance of self. """ if not hasattr(self, "classes_"): self._more_validate_params(for_partial_fit=True) if self.class_weight == "balanced": raise ValueError( "class_weight '{0}' is not supported for " "partial_fit. In order to use 'balanced' weights," " use compute_class_weight('{0}', " "classes=classes, y=y). " "In place of y you can use a large enough sample " "of the full training set target to properly " "estimate the class frequency distributions. " "Pass the resulting weights as the class_weight " "parameter.".format(self.class_weight) ) return self._partial_fit( X, y, alpha=self.alpha, loss=self.loss, learning_rate=self.learning_rate, max_iter=1, classes=classes, sample_weight=sample_weight, coef_init=None, intercept_init=None, ) @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): """Fit linear model with Stochastic Gradient Descent. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. y : ndarray of shape (n_samples,) Target values. coef_init : ndarray of shape (n_classes, n_features), default=None The initial coefficients to warm-start the optimization. intercept_init : ndarray of shape (n_classes,), default=None The initial intercept to warm-start the optimization. sample_weight : array-like, shape (n_samples,), default=None Weights applied to individual samples. If not provided, uniform weights are assumed. These weights will be multiplied with class_weight (passed through the constructor) if class_weight is specified. Returns ------- self : object Returns an instance of self. """ self._more_validate_params() return self._fit( X, y, alpha=self.alpha, loss=self.loss, learning_rate=self.learning_rate, coef_init=coef_init, intercept_init=intercept_init, sample_weight=sample_weight, ) def __sklearn_tags__(self): tags = super().__sklearn_tags__() tags.input_tags.sparse = True return tags
BaseSGDClassifier
python
gevent__gevent
src/greentest/3.12/test_subprocess.py
{ "start": 70872, "end": 79708 }
class ____(BaseTestCase): def run_python(self, code, **kwargs): """Run Python code in a subprocess using subprocess.run""" argv = [sys.executable, "-c", code] return subprocess.run(argv, **kwargs) def test_returncode(self): # call() function with sequence argument cp = self.run_python("import sys; sys.exit(47)") self.assertEqual(cp.returncode, 47) with self.assertRaises(subprocess.CalledProcessError): cp.check_returncode() def test_check(self): with self.assertRaises(subprocess.CalledProcessError) as c: self.run_python("import sys; sys.exit(47)", check=True) self.assertEqual(c.exception.returncode, 47) def test_check_zero(self): # check_returncode shouldn't raise when returncode is zero cp = subprocess.run(ZERO_RETURN_CMD, check=True) self.assertEqual(cp.returncode, 0) def test_timeout(self): # run() function with timeout argument; we want to test that the child # process gets killed when the timeout expires. If the child isn't # killed, this call will deadlock since subprocess.run waits for the # child. with self.assertRaises(subprocess.TimeoutExpired): self.run_python("while True: pass", timeout=0.0001) def test_capture_stdout(self): # capture stdout with zero return code cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE) self.assertIn(b'BDFL', cp.stdout) def test_capture_stderr(self): cp = self.run_python("import sys; sys.stderr.write('BDFL')", stderr=subprocess.PIPE) self.assertIn(b'BDFL', cp.stderr) def test_check_output_stdin_arg(self): # run() can be called with stdin set to a file tf = tempfile.TemporaryFile() self.addCleanup(tf.close) tf.write(b'pear') tf.seek(0) cp = self.run_python( "import sys; sys.stdout.write(sys.stdin.read().upper())", stdin=tf, stdout=subprocess.PIPE) self.assertIn(b'PEAR', cp.stdout) def test_check_output_input_arg(self): # check_output() can be called with input set to a string cp = self.run_python( "import sys; sys.stdout.write(sys.stdin.read().upper())", input=b'pear', stdout=subprocess.PIPE) self.assertIn(b'PEAR', cp.stdout) def test_check_output_stdin_with_input_arg(self): # run() refuses to accept 'stdin' with 'input' tf = tempfile.TemporaryFile() self.addCleanup(tf.close) tf.write(b'pear') tf.seek(0) with self.assertRaises(ValueError, msg="Expected ValueError when stdin and input args supplied.") as c: output = self.run_python("print('will not be run')", stdin=tf, input=b'hare') self.assertIn('stdin', c.exception.args[0]) self.assertIn('input', c.exception.args[0]) def test_check_output_timeout(self): with self.assertRaises(subprocess.TimeoutExpired) as c: cp = self.run_python( "import time; time.sleep(3600)", timeout=0.1, stdout=subprocess.PIPE) def test_run_kwargs(self): newenv = os.environ.copy() newenv["FRUIT"] = "banana" cp = self.run_python(('import sys, os;' 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'), env=newenv) self.assertEqual(cp.returncode, 33) def test_run_with_pathlike_path(self): # bpo-31961: test run(pathlike_object) # the name of a command that can be run without # any arguments that exit fast prog = 'tree.com' if mswindows else 'ls' path = shutil.which(prog) if path is None: self.skipTest(f'{prog} required for this test') path = FakePath(path) res = subprocess.run(path, stdout=subprocess.DEVNULL) self.assertEqual(res.returncode, 0) with self.assertRaises(TypeError): subprocess.run(path, stdout=subprocess.DEVNULL, shell=True) def test_run_with_bytes_path_and_arguments(self): # bpo-31961: test run([bytes_object, b'additional arguments']) path = os.fsencode(sys.executable) args = [path, '-c', b'import sys; sys.exit(57)'] res = subprocess.run(args) self.assertEqual(res.returncode, 57) def test_run_with_pathlike_path_and_arguments(self): # bpo-31961: test run([pathlike_object, 'additional arguments']) path = FakePath(sys.executable) args = [path, '-c', 'import sys; sys.exit(57)'] res = subprocess.run(args) self.assertEqual(res.returncode, 57) @unittest.skipUnless(mswindows, "Maybe test trigger a leak on Ubuntu") def test_run_with_an_empty_env(self): # gh-105436: fix subprocess.run(..., env={}) broken on Windows args = [sys.executable, "-c", 'pass'] # Ignore subprocess errors - we only care that the API doesn't # raise an OSError subprocess.run(args, env={}) def test_capture_output(self): cp = self.run_python(("import sys;" "sys.stdout.write('BDFL'); " "sys.stderr.write('FLUFL')"), capture_output=True) self.assertIn(b'BDFL', cp.stdout) self.assertIn(b'FLUFL', cp.stderr) def test_stdout_with_capture_output_arg(self): # run() refuses to accept 'stdout' with 'capture_output' tf = tempfile.TemporaryFile() self.addCleanup(tf.close) with self.assertRaises(ValueError, msg=("Expected ValueError when stdout and capture_output " "args supplied.")) as c: output = self.run_python("print('will not be run')", capture_output=True, stdout=tf) self.assertIn('stdout', c.exception.args[0]) self.assertIn('capture_output', c.exception.args[0]) def test_stderr_with_capture_output_arg(self): # run() refuses to accept 'stderr' with 'capture_output' tf = tempfile.TemporaryFile() self.addCleanup(tf.close) with self.assertRaises(ValueError, msg=("Expected ValueError when stderr and capture_output " "args supplied.")) as c: output = self.run_python("print('will not be run')", capture_output=True, stderr=tf) self.assertIn('stderr', c.exception.args[0]) self.assertIn('capture_output', c.exception.args[0]) # This test _might_ wind up a bit fragile on loaded build+test machines # as it depends on the timing with wide enough margins for normal situations # but does assert that it happened "soon enough" to believe the right thing # happened. @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command") def test_run_with_shell_timeout_and_capture_output(self): """Output capturing after a timeout mustn't hang forever on open filehandles.""" before_secs = time.monotonic() try: subprocess.run('sleep 3', shell=True, timeout=0.1, capture_output=True) # New session unspecified. except subprocess.TimeoutExpired as exc: after_secs = time.monotonic() stacks = traceback.format_exc() # assertRaises doesn't give this. else: self.fail("TimeoutExpired not raised.") self.assertLess(after_secs - before_secs, 1.5, msg="TimeoutExpired was delayed! Bad traceback:\n```\n" f"{stacks}```") def test_encoding_warning(self): code = textwrap.dedent("""\ from subprocess import * run("echo hello", shell=True, text=True) check_output("echo hello", shell=True, text=True) """) cp = subprocess.run([sys.executable, "-Xwarn_default_encoding", "-c", code], capture_output=True) lines = cp.stderr.splitlines() self.assertEqual(len(lines), 2, lines) self.assertTrue(lines[0].startswith(b"<string>:2: EncodingWarning: ")) self.assertTrue(lines[1].startswith(b"<string>:3: EncodingWarning: ")) def _get_test_grp_name(): for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'): if grp: try: grp.getgrnam(name_group) except KeyError: continue return name_group else: raise unittest.SkipTest('No identified group name to use for this test on this platform.') @unittest.skipIf(mswindows, "POSIX specific tests")
RunFuncTestCase
python
django__django
tests/admin_widgets/models.py
{ "start": 4128, "end": 4633 }
class ____(models.Model): """ A model with a FK to itself. It won't be registered with the admin, so the corresponding raw ID widget won't have a magnifying glass link to select related instances (rendering will be called programmatically in this case). """ name = models.CharField(max_length=20) parent = models.ForeignKey("self", models.SET_NULL, null=True) soulmate = models.ForeignKey( "self", models.CASCADE, null=True, related_name="soulmates" )
Individual
python
spyder-ide__spyder
spyder/plugins/pythonpath/plugin.py
{ "start": 743, "end": 4490 }
class ____(SpyderPluginV2): """ Pythonpath manager plugin. """ NAME = "pythonpath_manager" REQUIRES = [Plugins.Toolbar, Plugins.MainMenu] OPTIONAL = [Plugins.Projects] CONTAINER_CLASS = PythonpathContainer CONF_SECTION = NAME CONF_FILE = False sig_pythonpath_changed = Signal(object, bool) """ This signal is emitted when there is a change in the Pythonpath handled by Spyder. Parameters ---------- new_path_list: list of str New list of PYTHONPATH paths. prioritize Whether to prioritize PYTHONPATH in sys.path """ # ---- SpyderPluginV2 API @staticmethod def get_name(): return _("PYTHONPATH manager") @staticmethod def get_description(): return _("Manage additional locations to search for Python modules.") @classmethod def get_icon(cls): return cls.create_icon('python') def on_initialize(self): container = self.get_container() container.sig_pythonpath_changed.connect(self.sig_pythonpath_changed) @on_plugin_available(plugin=Plugins.MainMenu) def on_main_menu_available(self): container = self.get_container() main_menu = self.get_plugin(Plugins.MainMenu) main_menu.add_item_to_application_menu( container.path_manager_action, menu_id=ApplicationMenus.Tools, section=ToolsMenuSections.Managers, before=ApplicationActions.SpyderUserEnvVariables, before_section=ToolsMenuSections.Preferences, ) @on_plugin_available(plugin=Plugins.Projects) def on_projects_available(self): projects = self.get_plugin(Plugins.Projects) projects.sig_project_loaded.connect(self._on_project_loaded) projects.sig_project_closed.connect(self._on_project_closed) @on_plugin_available(plugin=Plugins.Toolbar) def on_toolbar_available(self): container = self.get_container() toolbar = self.get_plugin(Plugins.Toolbar) toolbar.add_item_to_application_toolbar( container.path_manager_action, toolbar_id=ApplicationToolbars.Main, section=MainToolbarSections.ApplicationSection ) @on_plugin_teardown(plugin=Plugins.MainMenu) def on_main_menu_teardown(self): main_menu = self.get_plugin(Plugins.MainMenu) main_menu.remove_item_from_application_menu( PythonpathActions.Manager, menu_id=ApplicationMenus.Tools, ) @on_plugin_teardown(plugin=Plugins.Projects) def on_projects_teardown(self): projects = self.get_plugin(Plugins.Projects) projects.sig_project_loaded.disconnect(self._on_project_loaded) projects.sig_project_closed.disconnect(self._on_project_closed) @on_plugin_teardown(plugin=Plugins.Toolbar) def on_toolbar_teardown(self): toolbar = self.get_plugin(Plugins.Toolbar) toolbar.remove_item_from_application_toolbar( PythonpathActions.Manager, toolbar_id=ApplicationToolbars.Main ) # ---- Public API def get_spyder_pythonpath(self): """Get Pythonpath paths handled by Spyder as a list.""" return self.get_container().get_spyder_pythonpath() def show_path_manager(self): """Show Path manager dialog.""" self.get_container().show_path_manager() @property def path_manager_dialog(self): return self.get_container().path_manager_dialog # ---- Private API def _on_project_loaded(self, path): self.get_container().update_active_project_path(path) def _on_project_closed(self, path): self.get_container().update_active_project_path(None)
PythonpathManager
python
dask__dask
dask/utils.py
{ "start": 19285, "end": 33396 }
class ____: """Simple single dispatch.""" def __init__(self, name=None): self._lookup = {} self._lazy = {} if name: self.__name__ = name def register(self, type, func=None): """Register dispatch of `func` on arguments of type `type`""" def wrapper(func): if isinstance(type, tuple): for t in type: self.register(t, func) else: self._lookup[type] = func return func return wrapper(func) if func is not None else wrapper def register_lazy(self, toplevel, func=None): """ Register a registration function which will be called if the *toplevel* module (e.g. 'pandas') is ever loaded. """ def wrapper(func): self._lazy[toplevel] = func return func return wrapper(func) if func is not None else wrapper def dispatch(self, cls): """Return the function implementation for the given ``cls``""" lk = self._lookup if cls in lk: return lk[cls] for cls2 in cls.__mro__: # Is a lazy registration function present? try: toplevel, _, _ = cls2.__module__.partition(".") except Exception: continue try: register = self._lazy[toplevel] except KeyError: pass else: register() self._lazy.pop(toplevel, None) meth = self.dispatch(cls) # recurse lk[cls] = meth lk[cls2] = meth return meth try: impl = lk[cls2] except KeyError: pass else: if cls is not cls2: # Cache lookup lk[cls] = impl return impl raise TypeError(f"No dispatch for {cls}") def __call__(self, arg, *args, **kwargs): """ Call the corresponding method based on type of argument. """ meth = self.dispatch(type(arg)) return meth(arg, *args, **kwargs) @property def __doc__(self): try: func = self.dispatch(object) return func.__doc__ except TypeError: return f"Single Dispatch for {self.__name__}" def ensure_not_exists(filename) -> None: """ Ensure that a file does not exist. """ try: os.unlink(filename) except OSError as e: if e.errno != ENOENT: raise def _skip_doctest(line): # NumPy docstring contains cursor and comment only example stripped = line.strip() if stripped == ">>>" or stripped.startswith(">>> #"): return line elif ">>>" in stripped and "+SKIP" not in stripped: if "# doctest:" in line: return f"{line}, +SKIP" else: return f"{line} # doctest: +SKIP" else: return line def skip_doctest(doc): if doc is None: return "" return "\n".join([_skip_doctest(line) for line in doc.split("\n")]) def extra_titles(doc): lines = doc.split("\n") titles = { i: lines[i].strip() for i in range(len(lines) - 1) if lines[i + 1].strip() and all(c == "-" for c in lines[i + 1].strip()) } seen = set() for i, title in sorted(titles.items()): if title in seen: new_title = f"Extra {title}" lines[i] = lines[i].replace(title, new_title) lines[i + 1] = lines[i + 1].replace("-" * len(title), "-" * len(new_title)) else: seen.add(title) return "\n".join(lines) def ignore_warning(doc, cls, name, extra="", skipblocks=0, inconsistencies=None): """Expand docstring by adding disclaimer and extra text""" import inspect if inspect.isclass(cls): l1 = f"This docstring was copied from {cls.__module__}.{cls.__name__}.{name}.\n\n" else: l1 = f"This docstring was copied from {cls.__name__}.{name}.\n\n" l2 = "Some inconsistencies with the Dask version may exist." i = doc.find("\n\n") if i != -1: # Insert our warning head = doc[: i + 2] tail = doc[i + 2 :] while skipblocks > 0: i = tail.find("\n\n") head = tail[: i + 2] tail = tail[i + 2 :] skipblocks -= 1 # Indentation of next line indent = re.match(r"\s*", tail).group(0) # Insert the warning, indented, with a blank line before and after if extra: more = [indent, extra.rstrip("\n") + "\n\n"] else: more = [] if inconsistencies is not None: l3 = f"Known inconsistencies: \n {inconsistencies}" bits = [head, indent, l1, l2, "\n\n", l3, "\n\n"] + more + [tail] else: bits = [head, indent, l1, indent, l2, "\n\n"] + more + [tail] doc = "".join(bits) return doc def unsupported_arguments(doc, args): """Mark unsupported arguments with a disclaimer""" lines = doc.split("\n") for arg in args: subset = [ (i, line) for i, line in enumerate(lines) if re.match(r"^\s*" + arg + " ?:", line) ] if len(subset) == 1: [(i, line)] = subset lines[i] = f"{line} (Not supported in Dask)" return "\n".join(lines) def _derived_from( cls, method, ua_args=None, extra="", skipblocks=0, inconsistencies=None ): """Helper function for derived_from to ease testing""" ua_args = ua_args or [] # do not use wraps here, as it hides keyword arguments displayed # in the doc original_method = getattr(cls, method.__name__) doc = getattr(original_method, "__doc__", None) if isinstance(original_method, property): # some things like SeriesGroupBy.unique are generated. original_method = original_method.fget if not doc: doc = getattr(original_method, "__doc__", None) if isinstance(original_method, functools.cached_property): original_method = original_method.func if not doc: doc = getattr(original_method, "__doc__", None) if doc is None: doc = "" # pandas DataFrame/Series sometimes override methods without setting __doc__ if not doc and cls.__name__ in {"DataFrame", "Series"}: for obj in cls.mro(): obj_method = getattr(obj, method.__name__, None) if obj_method is not None and obj_method.__doc__: doc = obj_method.__doc__ break # Insert disclaimer that this is a copied docstring if doc: doc = ignore_warning( doc, cls, method.__name__, extra=extra, skipblocks=skipblocks, inconsistencies=inconsistencies, ) elif extra: doc += extra.rstrip("\n") + "\n\n" # Mark unsupported arguments try: method_args = get_named_args(method) original_args = get_named_args(original_method) not_supported = [m for m in original_args if m not in method_args] except ValueError: not_supported = [] if len(ua_args) > 0: not_supported.extend(ua_args) if len(not_supported) > 0: doc = unsupported_arguments(doc, not_supported) doc = skip_doctest(doc) doc = extra_titles(doc) return doc def derived_from( original_klass, version=None, ua_args=None, skipblocks=0, inconsistencies=None ): """Decorator to attach original class's docstring to the wrapped method. The output structure will be: top line of docstring, disclaimer about this being auto-derived, any extra text associated with the method being patched, the body of the docstring and finally, the list of keywords that exist in the original method but not in the dask version. Parameters ---------- original_klass: type Original class which the method is derived from version : str Original package version which supports the wrapped method ua_args : list List of keywords which Dask doesn't support. Keywords existing in original but not in Dask will automatically be added. skipblocks : int How many text blocks (paragraphs) to skip from the start of the docstring. Useful for cases where the target has extra front-matter. inconsistencies: list List of known inconsistencies with method whose docstrings are being copied. """ ua_args = ua_args or [] def wrapper(method): try: extra = getattr(method, "__doc__", None) or "" method.__doc__ = _derived_from( original_klass, method, ua_args=ua_args, extra=extra, skipblocks=skipblocks, inconsistencies=inconsistencies, ) return method except AttributeError: module_name = original_klass.__module__.split(".")[0] @functools.wraps(method) def wrapped(*args, **kwargs): msg = f"Base package doesn't support '{method.__name__}'." if version is not None: msg2 = " Use {0} {1} or later to use this method." msg += msg2.format(module_name, version) raise NotImplementedError(msg) return wrapped return wrapper def funcname(func) -> str: """Get the name of a function.""" # functools.partial if isinstance(func, functools.partial): return funcname(func.func) # methodcaller if isinstance(func, methodcaller): return func.method[:50] module_name = getattr(func, "__module__", None) or "" type_name = getattr(type(func), "__name__", None) or "" # toolz.curry if "toolz" in module_name and "curry" == type_name: return func.func_name[:50] # multipledispatch objects if "multipledispatch" in module_name and "Dispatcher" == type_name: return func.name[:50] # numpy.vectorize objects if "numpy" in module_name and "vectorize" == type_name: return ("vectorize_" + funcname(func.pyfunc))[:50] # All other callables try: name = func.__name__ if name == "<lambda>": return "lambda" return name[:50] except AttributeError: return str(func)[:50] def typename(typ: Any, short: bool = False) -> str: """ Return the name of a type Examples -------- >>> typename(int) 'int' >>> from dask.core import literal >>> typename(literal) 'dask.core.literal' >>> typename(literal, short=True) 'dask.literal' """ if not isinstance(typ, type): return typename(type(typ)) try: if not typ.__module__ or typ.__module__ == "builtins": return typ.__name__ else: if short: module, *_ = typ.__module__.split(".") else: module = typ.__module__ return f"{module}.{typ.__name__}" except AttributeError: return str(typ) def ensure_bytes(s) -> bytes: """Attempt to turn `s` into bytes. Parameters ---------- s : Any The object to be converted. Will correctly handled * str * bytes * objects implementing the buffer protocol (memoryview, ndarray, etc.) Returns ------- b : bytes Raises ------ TypeError When `s` cannot be converted Examples -------- >>> ensure_bytes('123') b'123' >>> ensure_bytes(b'123') b'123' >>> ensure_bytes(bytearray(b'123')) b'123' """ if isinstance(s, bytes): return s elif hasattr(s, "encode"): return s.encode() else: try: return bytes(s) except Exception as e: raise TypeError( f"Object {s} is neither a bytes object nor can be encoded to bytes" ) from e def ensure_unicode(s) -> str: """Turn string or bytes to string >>> ensure_unicode('123') '123' >>> ensure_unicode(b'123') '123' """ if isinstance(s, str): return s elif hasattr(s, "decode"): return s.decode() else: try: return codecs.decode(s) except Exception as e: raise TypeError( f"Object {s} is neither a str object nor can be decoded to str" ) from e def digit(n, k, base): """ >>> digit(1234, 0, 10) 4 >>> digit(1234, 1, 10) 3 >>> digit(1234, 2, 10) 2 >>> digit(1234, 3, 10) 1 """ return n // base**k % base def insert(tup, loc, val): """ >>> insert(('a', 'b', 'c'), 0, 'x') ('x', 'b', 'c') """ L = list(tup) L[loc] = val return tuple(L) def memory_repr(num): for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: return f"{num:3.1f} {x}" num /= 1024.0 def asciitable(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i in r) for r in rows] columns = tuple(str(i) for i in columns) widths = tuple(max(*map(len, x), len(c)) for x, c in zip(zip(*rows), columns)) row_template = ("|" + (" %%-%ds |" * len(columns))) % widths header = row_template % tuple(columns) bar = "+{}+".format("+".join("-" * (w + 2) for w in widths)) data = "\n".join(row_template % r for r in rows) return "\n".join([bar, header, bar, data, bar]) def put_lines(buf, lines): if any(not isinstance(x, str) for x in lines): lines = [str(x) for x in lines] buf.write("\n".join(lines)) _method_cache: dict[str, methodcaller] = {}
Dispatch
python
numpy__numpy
numpy/ma/core.py
{ "start": 72969, "end": 78959 }
class ____: """ Handle the string used to represent missing data in a masked array. """ def __init__(self, display): """ Create the masked_print_option object. """ self._display = display self._enabled = True def display(self): """ Display the string to print for masked values. """ return self._display def set_display(self, s): """ Set the string to print for masked values. """ self._display = s def enabled(self): """ Is the use of the display value enabled? """ return self._enabled def enable(self, shrink=1): """ Set the enabling shrink to `shrink`. """ self._enabled = shrink def __str__(self): return str(self._display) __repr__ = __str__ # if you single index into a masked location you get this object. masked_print_option = _MaskedPrintOption('--') def _recursive_printoption(result, mask, printopt): """ Puts printoptions in result where mask is True. Private function allowing for recursion """ names = result.dtype.names if names is not None: for name in names: curdata = result[name] curmask = mask[name] _recursive_printoption(curdata, curmask, printopt) else: np.copyto(result, printopt, where=mask) # For better or worse, these end in a newline _legacy_print_templates = { 'long_std': textwrap.dedent("""\ masked_%(name)s(data = %(data)s, %(nlen)s mask = %(mask)s, %(nlen)s fill_value = %(fill)s) """), 'long_flx': textwrap.dedent("""\ masked_%(name)s(data = %(data)s, %(nlen)s mask = %(mask)s, %(nlen)s fill_value = %(fill)s, %(nlen)s dtype = %(dtype)s) """), 'short_std': textwrap.dedent("""\ masked_%(name)s(data = %(data)s, %(nlen)s mask = %(mask)s, %(nlen)s fill_value = %(fill)s) """), 'short_flx': textwrap.dedent("""\ masked_%(name)s(data = %(data)s, %(nlen)s mask = %(mask)s, %(nlen)s fill_value = %(fill)s, %(nlen)s dtype = %(dtype)s) """) } ############################################################################### # MaskedArray class # ############################################################################### def _recursive_filled(a, mask, fill_value): """ Recursively fill `a` with `fill_value`. """ names = a.dtype.names for name in names: current = a[name] if current.dtype.names is not None: _recursive_filled(current, mask[name], fill_value[name]) else: np.copyto(current, fill_value[name], where=mask[name]) def flatten_structured_array(a): """ Flatten a structured array. The data type of the output is chosen such that it can represent all of the (nested) fields. Parameters ---------- a : structured array Returns ------- output : masked array or ndarray A flattened masked array if the input is a masked array, otherwise a standard ndarray. Examples -------- >>> import numpy as np >>> ndtype = [('a', int), ('b', float)] >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype) >>> np.ma.flatten_structured_array(a) array([[1., 1.], [2., 2.]]) """ def flatten_sequence(iterable): """ Flattens a compound of nested iterables. """ for elm in iter(iterable): if hasattr(elm, '__iter__'): yield from flatten_sequence(elm) else: yield elm a = np.asanyarray(a) inishape = a.shape a = a.ravel() if isinstance(a, MaskedArray): out = np.array([tuple(flatten_sequence(d.item())) for d in a._data]) out = out.view(MaskedArray) out._mask = np.array([tuple(flatten_sequence(d.item())) for d in getmaskarray(a)]) else: out = np.array([tuple(flatten_sequence(d.item())) for d in a]) if len(inishape) > 1: newshape = list(out.shape) newshape[0] = inishape out.shape = tuple(flatten_sequence(newshape)) return out def _arraymethod(funcname, onmask=True): """ Return a class method wrapper around a basic array method. Creates a class method which returns a masked array, where the new ``_data`` array is the output of the corresponding basic method called on the original ``_data``. If `onmask` is True, the new mask is the output of the method called on the initial mask. Otherwise, the new mask is just a reference to the initial mask. Parameters ---------- funcname : str Name of the function to apply on data. onmask : bool Whether the mask must be processed also (True) or left alone (False). Default is True. Make available as `_onmask` attribute. Returns ------- method : instancemethod Class method wrapper of the specified basic array method. """ def wrapped_method(self, *args, **params): result = getattr(self._data, funcname)(*args, **params) result = result.view(type(self)) result._update_from(self) mask = self._mask if not onmask: result.__setmask__(mask) elif mask is not nomask: # __setmask__ makes a copy, which we don't want result._mask = getattr(mask, funcname)(*args, **params) return result methdoc = getattr(ndarray, funcname, None) or getattr(np, funcname, None) if methdoc is not None: wrapped_method.__doc__ = methdoc.__doc__ wrapped_method.__name__ = funcname return wrapped_method
_MaskedPrintOption
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 13765, "end": 14097 }
class ____(torch.nn.Module): """Once the below lazy module is initialized with its first input, it is transformed into this module.""" param: Parameter def __init__(self) -> None: super().__init__() self.register_parameter("param", None) def forward(self, x): return x
MaterializedModule
python
Textualize__textual
tests/test_disabled.py
{ "start": 415, "end": 2865 }
class ____(App[None]): """Application for testing Widget.disabled.""" def compose(self) -> ComposeResult: """Compose the child widgets.""" yield VerticalScroll( Button(), DataTable(), DirectoryTree("."), Input(), ListView(), Switch(), RichLog(), Tree("Test"), Markdown(), MarkdownViewer(), id="test-container", ) async def test_all_initially_enabled() -> None: """All widgets should start out enabled.""" async with DisableApp().run_test() as pilot: assert all( not node.disabled for node in pilot.app.screen.query("#test-container > *") ) async def test_enabled_widgets_have_enabled_pseudo_class() -> None: """All enabled widgets should have the :enabled pseudoclass.""" async with DisableApp().run_test() as pilot: assert all( node.has_pseudo_class("enabled") and not node.has_pseudo_class("disabled") for node in pilot.app.screen.query("#test-container > *") ) async def test_all_individually_disabled() -> None: """Post-disable all widgets should report being disabled.""" async with DisableApp().run_test() as pilot: for node in pilot.app.screen.query("VerticalScroll > *"): node.disabled = True assert all( node.disabled for node in pilot.app.screen.query("#test-container > *") ) async def test_disabled_widgets_have_disabled_pseudo_class() -> None: """All disabled widgets should have the :disabled pseudoclass.""" async with DisableApp().run_test() as pilot: for node in pilot.app.screen.query("#test-container > *"): node.disabled = True assert all( node.has_pseudo_class("disabled") and not node.has_pseudo_class("enabled") for node in pilot.app.screen.query("#test-container > *") ) async def test_disable_via_container() -> None: """All child widgets should appear (to CSS) as disabled by a container being disabled.""" async with DisableApp().run_test() as pilot: pilot.app.screen.query_one("#test-container", VerticalScroll).disabled = True assert all( node.has_pseudo_class("disabled") and not node.has_pseudo_class("enabled") for node in pilot.app.screen.query("#test-container > *") )
DisableApp
python
celery__celery
celery/contrib/testing/worker.py
{ "start": 766, "end": 7217 }
class ____(worker.WorkController): """Worker that can synchronize on being fully started.""" # When this class is imported in pytest files, prevent pytest from thinking # this is a test class __test__ = False logger_queue = None def __init__(self, *args, **kwargs): # type: (*Any, **Any) -> None self._on_started = threading.Event() super().__init__(*args, **kwargs) if self.pool_cls.__module__.split('.')[-1] == 'prefork': from billiard import Queue self.logger_queue = Queue() self.pid = os.getpid() try: from tblib import pickling_support pickling_support.install() except ImportError: pass # collect logs from forked process. # XXX: those logs will appear twice in the live log self.queue_listener = logging.handlers.QueueListener(self.logger_queue, logging.getLogger()) self.queue_listener.start() class QueueHandler(logging.handlers.QueueHandler): def prepare(self, record): record.from_queue = True # Keep origin record. return record def handleError(self, record): if logging.raiseExceptions: raise def start(self): if self.logger_queue: handler = self.QueueHandler(self.logger_queue) handler.addFilter(lambda r: r.process != self.pid and not getattr(r, 'from_queue', False)) logger = logging.getLogger() logger.addHandler(handler) return super().start() def on_consumer_ready(self, consumer): # type: (celery.worker.consumer.Consumer) -> None """Callback called when the Consumer blueprint is fully started.""" self._on_started.set() test_worker_started.send( sender=self.app, worker=self, consumer=consumer) def ensure_started(self): # type: () -> None """Wait for worker to be fully up and running. Warning: Worker must be started within a thread for this to work, or it will block forever. """ self._on_started.wait() @contextmanager def start_worker( app, # type: Celery concurrency=1, # type: int pool='solo', # type: str loglevel=WORKER_LOGLEVEL, # type: Union[str, int] logfile=None, # type: str perform_ping_check=True, # type: bool ping_task_timeout=10.0, # type: float shutdown_timeout=10.0, # type: float **kwargs # type: Any ): # type: (...) -> Iterable """Start embedded worker. Yields: celery.app.worker.Worker: worker instance. """ test_worker_starting.send(sender=app) worker = None try: with _start_worker_thread(app, concurrency=concurrency, pool=pool, loglevel=loglevel, logfile=logfile, perform_ping_check=perform_ping_check, shutdown_timeout=shutdown_timeout, **kwargs) as worker: if perform_ping_check: from .tasks import ping with allow_join_result(): assert ping.delay().get(timeout=ping_task_timeout) == 'pong' yield worker finally: test_worker_stopped.send(sender=app, worker=worker) @contextmanager def _start_worker_thread(app: Celery, concurrency: int = 1, pool: str = 'solo', loglevel: Union[str, int] = WORKER_LOGLEVEL, logfile: Optional[str] = None, WorkController: Any = TestWorkController, perform_ping_check: bool = True, shutdown_timeout: float = 10.0, **kwargs) -> Iterable[worker.WorkController]: """Start Celery worker in a thread. Yields: celery.worker.Worker: worker instance. """ setup_app_for_worker(app, loglevel, logfile) if perform_ping_check: assert 'celery.ping' in app.tasks # Make sure we can connect to the broker with app.connection(hostname=os.environ.get('TEST_BROKER')) as conn: conn.default_channel.queue_declare worker = WorkController( app=app, concurrency=concurrency, hostname=kwargs.pop("hostname", anon_nodename()), pool=pool, loglevel=loglevel, logfile=logfile, # not allowed to override TestWorkController.on_consumer_ready ready_callback=None, without_heartbeat=kwargs.pop("without_heartbeat", True), without_mingle=True, without_gossip=True, **kwargs) t = threading.Thread(target=worker.start, daemon=True) t.start() worker.ensure_started() _set_task_join_will_block(False) try: yield worker finally: from celery.worker import state state.should_terminate = 0 t.join(shutdown_timeout) if t.is_alive(): raise RuntimeError( "Worker thread failed to exit within the allocated timeout. " "Consider raising `shutdown_timeout` if your tasks take longer " "to execute." ) state.should_terminate = None @contextmanager def _start_worker_process(app, concurrency=1, pool='solo', loglevel=WORKER_LOGLEVEL, logfile=None, **kwargs): # type (Celery, int, str, Union[int, str], str, **Any) -> Iterable """Start worker in separate process. Yields: celery.app.worker.Worker: worker instance. """ from celery.apps.multi import Cluster, Node app.set_current() cluster = Cluster([Node('testworker1@%h')]) cluster.start() try: yield finally: cluster.stopwait() def setup_app_for_worker(app: Celery, loglevel: Union[str, int], logfile: str) -> None: """Setup the app to be used for starting an embedded worker.""" app.finalize() app.set_current() app.set_default() type(app.log)._setup = False app.log.setup(loglevel=loglevel, logfile=logfile)
TestWorkController
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1113713, "end": 1115255 }
class ____(sgqlc.types.Type, Node, RepositoryNode): """A thread of comments on a commit.""" __schema__ = github_schema __field_names__ = ("comments", "commit", "path", "position") comments = sgqlc.types.Field( sgqlc.types.non_null(CommitCommentConnection), graphql_name="comments", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) """The comments that exist in this thread. Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. """ commit = sgqlc.types.Field(Commit, graphql_name="commit") """The commit the comments were made on.""" path = sgqlc.types.Field(String, graphql_name="path") """The file the comments were made on.""" position = sgqlc.types.Field(Int, graphql_name="position") """The position in the diff for the commit that the comment was made on. """
CommitCommentThread
python
scikit-learn__scikit-learn
sklearn/model_selection/tests/test_validation.py
{ "start": 64053, "end": 72199 }
class ____(RandomForestClassifier): # None of the current multioutput-multiclass estimators have # decision function methods. Create a mock decision function # to test the cross_val_predict function's handling of this case. def decision_function(self, X): probs = self.predict_proba(X) msg = "This helper should only be used on multioutput-multiclass tasks" assert isinstance(probs, list), msg probs = [p[:, -1] if p.shape[1] == 2 else p for p in probs] return probs def test_cross_val_predict_with_method_multilabel_rf(): # The RandomForest allows multiple classes in each label. # Output of predict_proba is a list of outputs of predict_proba # for each individual label. n_classes = 4 X, y = make_multilabel_classification( n_samples=100, n_labels=3, n_classes=n_classes, n_features=5, random_state=42 ) y[:, 0] += y[:, 1] # Put three classes in the first column for method in ["predict_proba", "predict_log_proba", "decision_function"]: est = RFWithDecisionFunction(n_estimators=5, random_state=0) with warnings.catch_warnings(): # Suppress "RuntimeWarning: divide by zero encountered in log" warnings.simplefilter("ignore") check_cross_val_predict_multilabel(est, X, y, method=method) def test_cross_val_predict_with_method_rare_class(): # Test a multiclass problem where one class will be missing from # one of the CV training sets. rng = np.random.RandomState(0) X = rng.normal(0, 1, size=(14, 10)) y = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 3]) est = LogisticRegression() for method in ["predict_proba", "predict_log_proba", "decision_function"]: with warnings.catch_warnings(): # Suppress warning about too few examples of a class warnings.simplefilter("ignore") check_cross_val_predict_multiclass(est, X, y, method) def test_cross_val_predict_with_method_multilabel_rf_rare_class(): # The RandomForest allows anything for the contents of the labels. # Output of predict_proba is a list of outputs of predict_proba # for each individual label. # In this test, the first label has a class with a single example. # We'll have one CV fold where the training data don't include it. rng = np.random.RandomState(0) X = rng.normal(0, 1, size=(5, 10)) y = np.array([[0, 0], [1, 1], [2, 1], [0, 1], [1, 0]]) for method in ["predict_proba", "predict_log_proba"]: est = RFWithDecisionFunction(n_estimators=5, random_state=0) with warnings.catch_warnings(): # Suppress "RuntimeWarning: divide by zero encountered in log" warnings.simplefilter("ignore") check_cross_val_predict_multilabel(est, X, y, method=method) def get_expected_predictions(X, y, cv, classes, est, method): expected_predictions = np.zeros([len(y), classes]) func = getattr(est, method) for train, test in cv.split(X, y): est.fit(X[train], y[train]) expected_predictions_ = func(X[test]) # To avoid 2 dimensional indexing if method == "predict_proba": exp_pred_test = np.zeros((len(test), classes)) else: exp_pred_test = np.full( (len(test), classes), np.finfo(expected_predictions.dtype).min ) exp_pred_test[:, est.classes_] = expected_predictions_ expected_predictions[test] = exp_pred_test return expected_predictions def test_cross_val_predict_class_subset(): X = np.arange(200).reshape(100, 2) y = np.array([x // 10 for x in range(100)]) classes = 10 kfold3 = KFold(n_splits=3) kfold4 = KFold(n_splits=4) le = LabelEncoder() methods = ["decision_function", "predict_proba", "predict_log_proba"] for method in methods: est = LogisticRegression() # Test with n_splits=3 predictions = cross_val_predict(est, X, y, method=method, cv=kfold3) # Runs a naive loop (should be same as cross_val_predict): expected_predictions = get_expected_predictions( X, y, kfold3, classes, est, method ) assert_array_almost_equal(expected_predictions, predictions) # Test with n_splits=4 predictions = cross_val_predict(est, X, y, method=method, cv=kfold4) expected_predictions = get_expected_predictions( X, y, kfold4, classes, est, method ) assert_array_almost_equal(expected_predictions, predictions) # Testing unordered labels y = shuffle(np.repeat(range(10), 10), random_state=0) predictions = cross_val_predict(est, X, y, method=method, cv=kfold3) y = le.fit_transform(y) expected_predictions = get_expected_predictions( X, y, kfold3, classes, est, method ) assert_array_almost_equal(expected_predictions, predictions) def test_score_memmap(): # Ensure a scalar score of memmap type is accepted iris = load_iris() X, y = iris.data, iris.target clf = MockClassifier() tf = tempfile.NamedTemporaryFile(mode="wb", delete=False) tf.write(b"Hello world!!!!!") tf.close() scores = np.memmap(tf.name, dtype=np.float64) score = np.memmap(tf.name, shape=(), mode="r", dtype=np.float64) try: cross_val_score(clf, X, y, scoring=lambda est, X, y: score) with pytest.raises(ValueError): cross_val_score(clf, X, y, scoring=lambda est, X, y: scores) finally: # Best effort to release the mmap file handles before deleting the # backing file under Windows scores, score = None, None for _ in range(3): try: os.unlink(tf.name) break except OSError: sleep(1.0) def test_permutation_test_score_pandas(): # check permutation_test_score doesn't destroy pandas dataframe types = [(MockDataFrame, MockDataFrame)] try: from pandas import DataFrame, Series types.append((Series, DataFrame)) except ImportError: pass for TargetType, InputFeatureType in types: # X dataframe, y series iris = load_iris() X, y = iris.data, iris.target X_df, y_ser = InputFeatureType(X), TargetType(y) check_df = lambda x: isinstance(x, InputFeatureType) check_series = lambda x: isinstance(x, TargetType) clf = CheckingClassifier(check_X=check_df, check_y=check_series) permutation_test_score(clf, X_df, y_ser) def test_fit_and_score_failing(): # Create a failing classifier to deliberately fail failing_clf = FailingClassifier(FailingClassifier.FAILING_PARAMETER) # dummy X data X = np.arange(1, 10) train, test = np.arange(0, 5), np.arange(5, 9) fit_and_score_args = dict( estimator=failing_clf, X=X, y=None, scorer=dict(), train=train, test=test, verbose=0, parameters=None, fit_params=None, score_params=None, ) # passing error score to trigger the warning message fit_and_score_args["error_score"] = "raise" # check if exception was raised, with default error_score='raise' with pytest.raises(ValueError, match="Failing classifier failed as required"): _fit_and_score(**fit_and_score_args) assert failing_clf.score() == 0.0 # FailingClassifier coverage def test_fit_and_score_working(): X, y = make_classification(n_samples=30, random_state=0) clf = SVC(kernel="linear", random_state=0) train, test = next(ShuffleSplit().split(X)) # Test return_parameters option fit_and_score_args = dict( estimator=clf, X=X, y=y, scorer=dict(), train=train, test=test, verbose=0, parameters={"max_iter": 100, "tol": 0.1}, fit_params=None, score_params=None, return_parameters=True, ) result = _fit_and_score(**fit_and_score_args) assert result["parameters"] == fit_and_score_args["parameters"]
RFWithDecisionFunction
python
coleifer__peewee
tests/shortcuts.py
{ "start": 26475, "end": 27571 }
class ____(ModelTestCase): requires = [MMA, MMB, MMC] def test_resolve_multimodel_query(self): MMA.insert_many([('k0', 0), ('k1', 1)]).execute() MMB.insert_many([('k10',), ('k11',)]).execute() MMC.insert_many([('k20', 20, 'a'), ('k21', 21, 'b')]).execute() mma = MMA.select(MMA.key, MMA.value) mmb = MMB.select(MMB.key, Value(99).alias('value')) mmc = MMC.select(MMC.key, MMC.value) query = (mma | mmb | mmc).order_by(SQL('1')) data = [obj for obj in resolve_multimodel_query(query)] expected = [ MMA(key='k0', value=0), MMA(key='k1', value=1), MMB(key='k10', value=99), MMB(key='k11', value=99), MMC(key='k20', value=20), MMC(key='k21', value=21)] self.assertEqual(len(data), len(expected)) for row, exp_row in zip(data, expected): self.assertEqual(row.__class__, exp_row.__class__) self.assertEqual(row.key, exp_row.key) self.assertEqual(row.value, exp_row.value) ts_database = get_in_memory_db()
TestResolveMultiModelQuery
python
pytorch__pytorch
torch/export/_unlift.py
{ "start": 17121, "end": 33186 }
class ____(torch.fx.GraphModule, metaclass=_StatefulGraphModuleFactory): def __init__(self, root, graph, range_constraints=None): super().__init__(root, graph) # Need to fix up non-persistent buffers. self.range_constraints = range_constraints or [] self.validate_inputs = True def _create_stateful_graph_module( plain_graph_module: torch.fx.GraphModule, range_constraints, ep: ExportedProgram, ) -> _StatefulGraphModule: stateful_gm = _StatefulGraphModule._create( plain_graph_module, plain_graph_module.graph, range_constraints=range_constraints, ) module_types = _get_graph_inputs_of_type_nn_module(ep.example_inputs) stateful_gm.register_forward_pre_hook( lambda *args, **kwargs: _enter_enable_graph_inputs_of_type_nn_module( module_types ) ) stateful_gm.register_forward_pre_hook( _check_input_constraints_pre_hook, with_kwargs=True ) stateful_gm.register_forward_hook( lambda *args, **kwargs: _exit_enable_graph_inputs_of_type_nn_module( module_types ), always_call=True, ) # When we have a constant that has requires_grad=True, we need to detach it # when we unlift as the tensors that require gradients should be registered # via parameters. But this is problematic when we have aliasing two constants # because when we call detach, they will become different tensors. This dict # keeps track of this logic. original_tensor_to_detached_tensor = {} # Fix up lifted tensor constants. # fx.GraphModule() constructor silently turns a constant attribute of plain_graph_module # into a buffer in stateful_gm and creates an inconsistency with graph_signature. # We fix this by de-registering these buffers in lifted_tensor_constants # and call _assign_attr(attr_kind=CONSTANT) to register them as constants. for constant_fqn in ep.graph_signature.lifted_tensor_constants: # Sometimes, the constant can require gradient, this is probably a bug in user code, # e.g. `self.const = torch.randn(2, 2, requires_grad=True)`. # We call detach on the constant_val since they're tensor constants and we don't need to # compute their gradients anyway. # Users should properly register it as parameter if they want it to require gradient. buffer = stateful_gm.get_buffer(constant_fqn) if buffer.requires_grad: warnings.warn( f"A model attribute `{constant_fqn}` requires gradient. " f"but it's not properly registered as a parameter. " f"torch.export will detach it and treat it as a constant tensor " f"but please register it as parameter instead.", stacklevel=2, ) detached_buffer = buffer.detach() original_tensor_to_detached_tensor[buffer] = detached_buffer buffer = detached_buffer *prefix, field = constant_fqn.rsplit(".") submod = torch.fx.graph_module._get_attr_via_attr_list(stateful_gm, prefix) delattr(submod, field) _assign_attr(buffer, stateful_gm, constant_fqn, attr_kind=_AttrKind.CONSTANT) # Constants are not preserved well when we create a new GraphModule unlike param/buffers for const_name, value in ep.constants.items(): if not torch.fx.graph_module._has_attr(stateful_gm, const_name): if isinstance(value, torch.Tensor): if value.requires_grad: warnings.warn( f"A model attribute `{const_name}` requires gradient " f"but it's not properly registered as a parameter. " f"torch.export will detach it and treat it as a constant tensor " f"but please register it as parameter instead.", stacklevel=2, ) if value in original_tensor_to_detached_tensor: value = original_tensor_to_detached_tensor[value] else: detached_value = value.detach() original_tensor_to_detached_tensor[value] = detached_value value = detached_value _assign_attr( value, stateful_gm, const_name, attr_kind=_AttrKind.CONSTANT, ) # Fix up non-persistent buffers. torch.fx does not distinguish between # persistent and non-persistent buffers, so we must restore that distinction # here. for buffer in ep.graph_signature.non_persistent_buffers: _assign_attr( plain_graph_module.get_buffer(buffer), stateful_gm, buffer, attr_kind=_AttrKind.BUFFER, persistent=False, ) return stateful_gm def _get_input_paths(example_inputs, signature): """ Generate paths of placeholders, needed for generating the guards function. NOTE: Here we make use of the example inputs used for export as well as the signature of the unlifted graph module (not preserved by export). """ args, kwargs = example_inputs binded = signature.bind(*args, **kwargs) binded.apply_defaults() ctx = binded.arguments flat_example_inputs_with_paths = pytree.tree_leaves_with_path(ctx) return [path for path, _ in flat_example_inputs_with_paths] def _replace_sources(result_str: str, flat_input_paths: list[Any]): """ Given user specified input paths, maybe fix up the guard string to reflect user path instead of tracer path. """ name_mapping = {} for idx, path in enumerate(flat_input_paths): name_mapping[f"L['flat_args'][{idx}]"] = f"L{pytree.keystr(path)}" replace = result_str for key, val in name_mapping.items(): replace = replace.replace(key, val) return replace def _get_input_guards_for_graph( placeholders: list[torch.fx.Node], range_constraints: dict[sympy.Symbol, ValueRanges], paths_for_placeholders: list[pytree.KeyPath], ): """ Guards generated by the tracer include conditions observed in code, but but do not include some additional checks we typically do in export. For example, when dynamic shapes get specialized, are specified to be within a range, or are specified to be in some equational relation, corresponding input invalidation is done within a pre_hook, specifically, `_check_input_constraints_for_graph`. Here we generate guards corresponding to the checks that happen in `_check_input_constraints_for_graph`, and add them to the guards already generated by the tracer. In the future, it may be worthwhile to separate them so that we can allow clients to turn off one but not the other. (Looking at you, AOTI.) NOTE: We should eventually reconcile this logic with `build_guards` that is used by AOT Precompile. """ deferred_expressions = [] new_guards_code = [] sources: dict[sympy.Expr, str] = {} def handle_symint(expr, src): if len(expr.free_symbols) == 1: # complex equations (e.g., involving derived dims) need to # handled later, since we may not have enough information # just as we are passing through the placeholders in order deferred_expressions.append((src, expr)) if expr in sources: # expressions that appear in multiple sources should force # inputs corresponding to those sources to be equal # e.g., x.shape[0] == y.shape[1] orig_src = sources[expr] new_guards_code.append(f"{src} == {orig_src}") else: sources[expr] = src # process value ranges as elsewhere in export min_val, max_val = _convert_range_to_int(range_constraints[expr]) if min_val > 2: new_guards_code.append(f"{src} >= {min_val}") if max_val < math.inf: new_guards_code.append(f"{src} <= {max_val}") for placeholder, path in zip(placeholders, paths_for_placeholders): src = "L" + pytree.keystr(path) meta = placeholder.meta["val"] # specializations if isinstance(meta, int): new_guards_code.append(f"{src} == {meta}") if isinstance(meta, float): if meta == math.inf: new_guards_code.append(f"{src} == math.inf") elif meta == -math.inf: new_guards_code.append(f"{src} == -math.inf") else: new_guards_code.append(f"{src} == {meta}") elif isinstance(meta, str): new_guards_code.append(f"{src} == '{meta}'") # range constraints and equalities elif isinstance(meta, torch.SymInt) and meta.node.expr in range_constraints: handle_symint(meta.node.expr, src) elif isinstance(meta, torch.Tensor): for i, dim in enumerate(meta.shape): src = "L" + pytree.keystr(path) + f".size()[{i}]" if isinstance(dim, int): # specializations new_guards_code.append(f"{src} == {dim}") elif ( isinstance(dim, torch.SymInt) and dim.node.expr in range_constraints ): # range constraints and equalities handle_symint(dim.node.expr, src) unification_map: dict[sympy.Symbol, sympy.Expr] = {} py_printer = torch.utils._sympy.printers.PythonPrinter() # process complex equations (e.g., involving derived dims) for src, expr in deferred_expressions: # we know this is the only symbol in expr (see check above) symbol = next(iter(expr.free_symbols)) if symbol in sources: # if s0 is already known to be directly sourced from inputs, # e.g., z.shape[2], we do not need to do anything further # (assume we have already processed constraints on s0 above) continue # otherwise s0 has some "hidden" source like 'dim' # example: src = y.shape[1], expr = s0 + 1 if symbol in unification_map: # suppose that we already know that s0 = x.shape[0] * 2 # so we can emit the guard: x.shape[0] * 2 + 1 = y.shape[1] substitution = expr.subs(unification_map) new_guards_code.append( py_printer.doprint(sympy.Eq(substitution, sympy.Symbol(src))) ) else: # we do not yet know what s0 is, but given s0 + 1 = y.shape[1], # we can solve for s0...now knowing that s0 = y.shape[1] - 1 solution = try_solve(sympy.Eq(expr, sympy.Symbol(src)), symbol) if solution is not None: definition = solution[1] unification_map[symbol] = definition return new_guards_code def _ok_to_generate_guards_fn(): patterns = [ "executorch", "modai", "on_device_ai", "torchao", ] # force check_guards=False for files matching `patterns` # because they have too many calls to .module() and # do not like any call modules in the graph # TODO: fix these files to handle guard fns frame = inspect.currentframe() while frame is not None: if any(path in frame.f_code.co_filename for path in patterns): return False frame = frame.f_back return True def _unlift_exported_program_lifted_states( ep: ExportedProgram, check_guards=True ) -> torch.fx.GraphModule: check_guards = check_guards and _ok_to_generate_guards_fn() source_node_dict = { node.name: node for node in ep.graph.nodes if node.op != "placeholder" } # placeholder node name might change after deepcopy placeholder_source_node_dict = { node.target: node for node in ep.graph.nodes if node.op == "placeholder" } new_gm = torch.fx.GraphModule(ep.graph_module, copy.deepcopy(ep.graph)) new_gm.meta.update(ep.graph_module.meta) ep = copy.copy(ep) ep._graph_module = new_gm # TODO T206340015 if ep.verifiers[0].dialect != "TRAINING": ep = _remove_effect_tokens(ep) _register_attrs_to_new_gm(new_gm, ep.graph_signature, ep.state_dict, ep.constants) forward_arg_names = ( sig.forward_arg_names if (sig := ep.module_call_graph[0].signature) else None ) lifted_inputs: list[Optional[str]] = [ ( in_spec.target if in_spec.kind in ( InputKind.BUFFER, InputKind.CONSTANT_TENSOR, InputKind.PARAMETER, InputKind.CUSTOM_OBJ, ) else None ) for in_spec in ep.graph_signature.input_specs ] mutated_outputs: list[Optional[str]] = [ ( out_spec.target if out_spec.kind in ( OutputKind.BUFFER_MUTATION, OutputKind.USER_INPUT_MUTATION, OutputKind.PARAMETER_MUTATION, ) else None ) for out_spec in ep.graph_signature.output_specs ] for node in new_gm.graph.nodes: source_node = None if node.op == "placeholder": source_node = placeholder_source_node_dict.get(node.target) else: if node.name in source_node_dict: source_node = source_node_dict.get(node.name) node.meta["from_node"] = [ NodeSource( source_node, "ExportedProgram.module()", NodeSourceAction.CREATE, ) ] assert ep.call_spec.in_spec is not None new_gm = _unlift( new_gm, lifted_inputs, mutated_outputs, ep.call_spec.in_spec, ep.call_spec.out_spec, forward_arg_names=forward_arg_names, ) unlift_gm = _create_stateful_graph_module(new_gm, ep.range_constraints, ep) unlift_gm.meta.update(ep.graph_module.meta) # create a _guards_fn submodule and insert a call to it after placeholders graph = unlift_gm.graph placeholders = graph.find_nodes(op="placeholder") if check_guards and placeholders and ep.example_inputs: sig = inspect.signature(unlift_gm.forward) input_paths = _get_input_paths( ep.example_inputs, sig, ) # TODO (tmanlaibaatar) # This is band-aid solution to export new tracer replacing # shape env sources to flat_args. The real fix should be replacing # shape env sources to original user sources but this is quite # involved because you need to carefully construct new sources using # dynamo and replace all instances of it inside shape env. But it is # lot easier to manipulate after we turn them into strings and only # time we use these guards is during retracing or running exported program, # so it is probably ok to have "not useful" guards on ep for now. ep_guards = [] for guard in ep._guards_code: ep_guards.append(_replace_sources(guard, input_paths)) guards_code = _get_input_guards_for_graph( placeholders, ep.range_constraints, input_paths ) ep_guards_code = _force_ep_signature_match(ep._guards_code, input_paths) ep_guards_code = _force_gm_signature_match(ep_guards_code, sig) guards_code.extend(ep_guards_code) unlift_gm._guards_fn = _convert_guards_code_to_fn(guards_code, input_paths) root_nn_module_stack = torch.fx._utils.first_call_function_nn_module_stack( graph ) with graph.inserting_after(placeholders[-1]): node = graph.call_module("_guards_fn", tuple(placeholders)) node.meta["nn_module_stack"] = root_nn_module_stack unlift_gm.recompile() return unlift_gm
_StatefulGraphModule
python
realpython__materials
asterioids-pygame-project/source_code_step_4/space_rocks/game.py
{ "start": 76, "end": 1266 }
class ____: def __init__(self): self._init_pygame() self.screen = pygame.display.set_mode((800, 600)) self.background = load_sprite("space", False) self.clock = pygame.time.Clock() self.spaceship = GameObject( (400, 300), load_sprite("spaceship"), (0, 0) ) self.asteroid = GameObject((400, 300), load_sprite("asteroid"), (1, 0)) def main_loop(self): while True: self._handle_input() self._process_game_logic() self._draw() def _init_pygame(self): pygame.init() pygame.display.set_caption("Space Rocks") def _handle_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE ): quit() def _process_game_logic(self): self.spaceship.move() self.asteroid.move() def _draw(self): self.screen.blit(self.background, (0, 0)) self.spaceship.draw(self.screen) self.asteroid.draw(self.screen) pygame.display.flip() self.clock.tick(60)
SpaceRocks
python
kamyu104__LeetCode-Solutions
Python/minimum-numbers-of-function-calls-to-make-target-array.py
{ "start": 33, "end": 496 }
class ____(object): def minOperations(self, nums): """ :type nums: List[int] :rtype: int """ def popcount(n): result = 0 while n: n &= n-1 result += 1 return result result, max_len = 0, 1 for num in nums: result += popcount(num) max_len = max(max_len, num.bit_length()) return result + (max_len-1)
Solution
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/obscure_tito.py
{ "start": 335, "end": 694 }
class ____(C): def update(self, parameter): ... def taint_parameter(self, tainted_parameter): ... def test_obscure_tito(): c = C() c.update(_test_source()) return c def test_obscure_return(): c = C() return c.update(_test_source()) def test_obscure_sink(parameter): c = C() c.taint_parameter(parameter)
D
python
openai__openai-python
src/openai/_response.py
{ "start": 18334, "end": 18786 }
class ____(APIResponse[bytes]): def stream_to_file( self, file: str | os.PathLike[str], *, chunk_size: int | None = None, ) -> None: """Streams the output to the given file. Accepts a filename or any path-like object, e.g. pathlib.Path """ with open(file, mode="wb") as f: for data in self.iter_bytes(chunk_size): f.write(data)
StreamedBinaryAPIResponse
python
openai__openai-python
src/openai/_client.py
{ "start": 35432, "end": 39867 }
class ____: _client: OpenAI def __init__(self, client: OpenAI) -> None: self._client = client @cached_property def completions(self) -> completions.CompletionsWithStreamingResponse: from .resources.completions import CompletionsWithStreamingResponse return CompletionsWithStreamingResponse(self._client.completions) @cached_property def chat(self) -> chat.ChatWithStreamingResponse: from .resources.chat import ChatWithStreamingResponse return ChatWithStreamingResponse(self._client.chat) @cached_property def embeddings(self) -> embeddings.EmbeddingsWithStreamingResponse: from .resources.embeddings import EmbeddingsWithStreamingResponse return EmbeddingsWithStreamingResponse(self._client.embeddings) @cached_property def files(self) -> files.FilesWithStreamingResponse: from .resources.files import FilesWithStreamingResponse return FilesWithStreamingResponse(self._client.files) @cached_property def images(self) -> images.ImagesWithStreamingResponse: from .resources.images import ImagesWithStreamingResponse return ImagesWithStreamingResponse(self._client.images) @cached_property def audio(self) -> audio.AudioWithStreamingResponse: from .resources.audio import AudioWithStreamingResponse return AudioWithStreamingResponse(self._client.audio) @cached_property def moderations(self) -> moderations.ModerationsWithStreamingResponse: from .resources.moderations import ModerationsWithStreamingResponse return ModerationsWithStreamingResponse(self._client.moderations) @cached_property def models(self) -> models.ModelsWithStreamingResponse: from .resources.models import ModelsWithStreamingResponse return ModelsWithStreamingResponse(self._client.models) @cached_property def fine_tuning(self) -> fine_tuning.FineTuningWithStreamingResponse: from .resources.fine_tuning import FineTuningWithStreamingResponse return FineTuningWithStreamingResponse(self._client.fine_tuning) @cached_property def vector_stores(self) -> vector_stores.VectorStoresWithStreamingResponse: from .resources.vector_stores import VectorStoresWithStreamingResponse return VectorStoresWithStreamingResponse(self._client.vector_stores) @cached_property def beta(self) -> beta.BetaWithStreamingResponse: from .resources.beta import BetaWithStreamingResponse return BetaWithStreamingResponse(self._client.beta) @cached_property def batches(self) -> batches.BatchesWithStreamingResponse: from .resources.batches import BatchesWithStreamingResponse return BatchesWithStreamingResponse(self._client.batches) @cached_property def uploads(self) -> uploads.UploadsWithStreamingResponse: from .resources.uploads import UploadsWithStreamingResponse return UploadsWithStreamingResponse(self._client.uploads) @cached_property def responses(self) -> responses.ResponsesWithStreamingResponse: from .resources.responses import ResponsesWithStreamingResponse return ResponsesWithStreamingResponse(self._client.responses) @cached_property def realtime(self) -> realtime.RealtimeWithStreamingResponse: from .resources.realtime import RealtimeWithStreamingResponse return RealtimeWithStreamingResponse(self._client.realtime) @cached_property def conversations(self) -> conversations.ConversationsWithStreamingResponse: from .resources.conversations import ConversationsWithStreamingResponse return ConversationsWithStreamingResponse(self._client.conversations) @cached_property def evals(self) -> evals.EvalsWithStreamingResponse: from .resources.evals import EvalsWithStreamingResponse return EvalsWithStreamingResponse(self._client.evals) @cached_property def containers(self) -> containers.ContainersWithStreamingResponse: from .resources.containers import ContainersWithStreamingResponse return ContainersWithStreamingResponse(self._client.containers) @cached_property def videos(self) -> videos.VideosWithStreamingResponse: from .resources.videos import VideosWithStreamingResponse return VideosWithStreamingResponse(self._client.videos)
OpenAIWithStreamedResponse
python
numba__numba
numba/cuda/tests/nocuda/test_import.py
{ "start": 68, "end": 1641 }
class ____(unittest.TestCase): def test_no_impl_import(self): """ Tests that importing cuda doesn't trigger the import of modules containing lowering implementation that would likely install things in the builtins registry and have side effects impacting other targets. """ banlist = ( 'numba.cpython.slicing', 'numba.cpython.tupleobj', 'numba.cpython.enumimpl', 'numba.cpython.hashing', 'numba.cpython.heapq', 'numba.cpython.iterators', 'numba.cpython.numbers', 'numba.cpython.rangeobj', 'numba.cpython.cmathimpl', 'numba.cpython.mathimpl', 'numba.cpython.printimpl', 'numba.cpython.randomimpl', 'numba.core.optional', 'numba.misc.gdb_hook', 'numba.misc.literal', 'numba.misc.cffiimpl', 'numba.np.linalg', 'numba.np.polynomial', 'numba.np.arraymath', 'numba.np.npdatetime', 'numba.np.npyimpl', 'numba.typed.typeddict', 'numba.typed.typedlist', 'numba.experimental.jitclass.base', ) code = "import sys; from numba import cuda; print(list(sys.modules))" out, _ = run_in_subprocess(code) modlist = set(eval(out.strip())) unexpected = set(banlist) & set(modlist) self.assertFalse(unexpected, "some modules unexpectedly imported") if __name__ == '__main__': unittest.main()
TestImport
python
realpython__materials
python-all-attribute/webreader.py
{ "start": 323, "end": 472 }
class ____: def __init__(self, page): self.response = _fetch_page(page) def get_content(self): return self.response.text
WebPage
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_hash.py
{ "start": 904, "end": 1014 }
class ____: def __hash__(self): print("raise some error") raise NotImplementedError
HashWrong6
python
networkx__networkx
networkx/algorithms/approximation/tests/test_traveling_salesman.py
{ "start": 5293, "end": 9438 }
class ____(TestBase): tsp = staticmethod(nx_app.simulated_annealing_tsp) def test_simulated_annealing_directed(self): cycle = self.tsp(self.DG, "greedy", source="D", seed=42) cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_solution(cycle, cost, self.DG_cycle, self.DG_cost) initial_sol = ["D", "B", "A", "C", "D"] cycle = self.tsp(self.DG, initial_sol, source="D", seed=42) cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_solution(cycle, cost, self.DG_cycle, self.DG_cost) initial_sol = ["D", "A", "C", "B", "D"] cycle = self.tsp(self.DG, initial_sol, move="1-0", source="D", seed=42) cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_solution(cycle, cost, self.DG_cycle, self.DG_cost) cycle = self.tsp(self.DG2, "greedy", source="D", seed=42) cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost) cycle = self.tsp(self.DG2, "greedy", move="1-0", source="D", seed=42) cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_solution(cycle, cost, self.DG2_cycle, self.DG2_cost) def test_simulated_annealing_undirected(self): cycle = self.tsp(self.UG, "greedy", source="D", seed=42) cost = sum(self.UG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_solution(cycle, cost, self.UG_cycle, self.UG_cost) cycle = self.tsp(self.UG2, "greedy", source="D", seed=42) cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost) cycle = self.tsp(self.UG2, "greedy", move="1-0", source="D", seed=42) cost = sum(self.UG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_symmetric_solution(cycle, cost, self.UG2_cycle, self.UG2_cost) def test_error_on_input_order_mistake(self): # see issue #4846 https://github.com/networkx/networkx/issues/4846 pytest.raises(TypeError, self.tsp, self.UG, weight="weight") pytest.raises(nx.NetworkXError, self.tsp, self.UG, "weight") def test_not_complete_graph(self): pytest.raises(nx.NetworkXError, self.tsp, self.incompleteUG, "greedy", source=0) pytest.raises(nx.NetworkXError, self.tsp, self.incompleteDG, "greedy", source=0) def test_ignore_selfloops(self): G = nx.complete_graph(5) G.add_edge(3, 3) cycle = self.tsp(G, "greedy") assert len(cycle) - 1 == len(G) == len(set(cycle)) def test_not_weighted_graph(self): self.tsp(self.unweightedUG, "greedy") self.tsp(self.unweightedDG, "greedy") def test_two_nodes(self): G = nx.Graph() G.add_weighted_edges_from({(1, 2, 1)}) cycle = self.tsp(G, "greedy", source=1, seed=42) cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_solution(cycle, cost, [1, 2, 1], 2) cycle = self.tsp(G, [1, 2, 1], source=1, seed=42) cost = sum(G[n][nbr]["weight"] for n, nbr in pairwise(cycle)) validate_solution(cycle, cost, [1, 2, 1], 2) def test_failure_of_costs_too_high_when_iterations_low(self): # Simulated Annealing Version: # set number of moves low and alpha high cycle = self.tsp( self.DG2, "greedy", source="D", move="1-0", alpha=1, N_inner=1, seed=42 ) cost = sum(self.DG2[n][nbr]["weight"] for n, nbr in pairwise(cycle)) assert cost > self.DG2_cost # Try with an incorrect initial guess initial_sol = ["D", "A", "B", "C", "D"] cycle = self.tsp( self.DG, initial_sol, source="D", move="1-0", alpha=0.1, N_inner=1, max_iterations=1, seed=42, ) cost = sum(self.DG[n][nbr]["weight"] for n, nbr in pairwise(cycle)) assert cost > self.DG_cost
TestSimulatedAnnealingTSP
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 826020, "end": 826428 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("OrganizationInvitation", graphql_name="node") """The item at the end of the edge."""
OrganizationInvitationEdge
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 3433, "end": 4348 }
class ____(PrefectOperatorFilterBaseModel): """Filter by flows by deployment""" is_null_: Optional[bool] = Field( default=None, description="If true, only include flows without deployments", ) def _get_filter_list( self, db: "PrefectDBInterface" ) -> Iterable[sa.ColumnExpressionArgument[bool]]: filters: list[sa.ColumnExpressionArgument[bool]] = [] if self.is_null_ is not None: deployments_subquery = ( sa.select(db.Deployment.flow_id).distinct().subquery() ) if self.is_null_: filters.append( db.Flow.id.not_in(sa.select(deployments_subquery.c.flow_id)) ) else: filters.append( db.Flow.id.in_(sa.select(deployments_subquery.c.flow_id)) ) return filters
FlowFilterDeployment
python
kamyu104__LeetCode-Solutions
Python/tree-diameter.py
{ "start": 55, "end": 1092 }
class ____(object): def treeDiameter(self, edges): """ :type edges: List[List[int]] :rtype: int """ def iter_dfs(): result = 0 stk = [(1, (0, -1, [0]))] while stk: step, args = stk.pop() if step == 1: u, p, ret = args for v in reversed(adj[u]): if v == p: continue ret2 = [0] stk.append((2, (ret2, ret))) stk.append((1, (v, u, ret2))) elif step == 2: ret2, ret = args result = max(result, ret[0]+(ret2[0]+1)) ret[0] = max(ret[0], ret2[0]+1) return result adj = [[] for _ in range(len(edges)+1)] for u, v in edges: adj[u].append(v) adj[v].append(u) return iter_dfs() # Time: O(|V| + |E|) # Space: O(|E|) # dfs
Solution
python
apache__avro
lang/py/avro/codecs.py
{ "start": 1860, "end": 2835 }
class ____(abc.ABC): """Abstract base class for all Avro codec classes.""" @staticmethod @abc.abstractmethod def compress(data: bytes) -> Tuple[bytes, int]: """Compress the passed data. :param data: a byte string to be compressed :type data: str :rtype: tuple :return: compressed data and its length """ @staticmethod @abc.abstractmethod def decompress(readers_decoder: avro.io.BinaryDecoder) -> avro.io.BinaryDecoder: """Read compressed data via the passed BinaryDecoder and decompress it. :param readers_decoder: a BinaryDecoder object currently being used for reading an object container file :type readers_decoder: avro.io.BinaryDecoder :rtype: avro.io.BinaryDecoder :return: a newly instantiated BinaryDecoder object that contains the decompressed data which is wrapped by a StringIO """
Codec
python
gevent__gevent
src/gevent/monkey/_patch_thread_lt313.py
{ "start": 224, "end": 3182 }
class ____(BasePatcher): def patch_active_threads(self): from gevent.threading import main_native_thread threading_mod = self.threading_mod for thread in threading_mod._active.values(): if thread == main_native_thread(): continue thread.join = self._make_existing_non_main_thread_join_func(thread, None, threading_mod) def patch_threading_shutdown_on_main_thread_not_already_patched(self): import greenlet from .api import patch_item threading_mod = self.threading_mod main_thread = self.main_thread orig_shutdown = self.orig_shutdown _greenlet = main_thread._greenlet = greenlet.getcurrent() main_thread._gevent_real_tstate_lock = main_thread._tstate_lock assert main_thread._gevent_real_tstate_lock is not None # The interpreter will call threading._shutdown # when the main thread exits and is about to # go away. It is called *in* the main thread. This # is a perfect place to notify other greenlets that # the main thread is done. We do this by overriding the # lock of the main thread during operation, and only restoring # it to the native blocking version at shutdown time # (the interpreter also has a reference to this lock in a # C data structure). main_thread._tstate_lock = threading_mod.Lock() main_thread._tstate_lock.acquire() def _shutdown(): # Release anyone trying to join() me, # and let us switch to them. if not main_thread._tstate_lock: return main_thread._tstate_lock.release() from gevent import sleep try: sleep() except: # pylint:disable=bare-except # A greenlet could have .kill() us # or .throw() to us. I'm the main greenlet, # there's no where else for this to go. from gevent import get_hub get_hub().print_exception(_greenlet, *sys.exc_info()) # Now, this may have resulted in us getting stopped # if some other greenlet actually just ran there. # That's not good, we're not supposed to be stopped # when we enter _shutdown. main_thread._is_stopped = False main_thread._tstate_lock = main_thread._gevent_real_tstate_lock main_thread._gevent_real_tstate_lock = None # The only truly blocking native shutdown lock to # acquire should be our own (hopefully), and the call to # _stop that orig_shutdown makes will discard it. try: orig_shutdown() except LoopExit: # pragma: no cover pass patch_item(threading_mod, '_shutdown', orig_shutdown) patch_item(threading_mod, '_shutdown', _shutdown)
Patcher
python
ansible__ansible
test/lib/ansible_test/_internal/cli/argparsing/parsers.py
{ "start": 20603, "end": 21491 }
class ____(Parser, metaclass=abc.ABCMeta): """Base class for composite argument parsers which parse a type name, a colon and then parse results based on the type given by the type name.""" def get_parsers(self, state: ParserState) -> dict[str, Parser]: # pylint: disable=unused-argument """Return a dictionary of type names and type parsers.""" return self.get_stateless_parsers() @abc.abstractmethod def get_stateless_parsers(self) -> dict[str, Parser]: """Return a dictionary of type names and type parsers.""" def parse(self, state: ParserState) -> t.Any: """Parse the input from the given state and return the result.""" parsers = self.get_parsers(state) with state.delimit(':'): key = ChoicesParser(list(parsers)).parse(state) value = parsers[key].parse(state) return value
TypeParser
python
cython__cython
Cython/Compiler/ParseTreeTransforms.py
{ "start": 132149, "end": 133718 }
class ____(CythonTransform): def visit_ModuleNode(self, node): self.directives = node.directives self.imported_names = set() # hack, see visit_FromImportStatNode() self.scope = node.scope self.visitchildren(node) return node def visit_DefNode(self, node): if (self.scope.is_module_scope and self.directives['auto_cpdef'] and node.name not in self.imported_names and node.is_cdef_func_compatible()): # FIXME: cpdef-ing should be done in analyse_declarations() node = node.as_cfunction(scope=self.scope) return node def visit_CClassDefNode(self, node, pxd_def=None): if pxd_def is None: pxd_def = self.scope.lookup(node.class_name) if pxd_def: if not pxd_def.defined_in_pxd: return node outer_scope = self.scope self.scope = pxd_def.type.scope self.visitchildren(node) if pxd_def: self.scope = outer_scope return node def visit_FromImportStatNode(self, node): # hack to prevent conditional import fallback functions from # being cdpef-ed (global Python variables currently conflict # with imports) if self.scope.is_module_scope: for name, _ in node.items: self.imported_names.add(name) return node def visit_ExprNode(self, node): # ignore lambdas and everything else that appears in expressions return node
AutoCpdefFunctionDefinitions
python
paramiko__paramiko
paramiko/_winapi.py
{ "start": 7308, "end": 7351 }
class ____: TOKEN_QUERY = 0x8
TokenAccess
python
python__mypy
mypyc/options.py
{ "start": 49, "end": 3020 }
class ____: def __init__( self, strip_asserts: bool = False, multi_file: bool = False, verbose: bool = False, separate: bool = False, target_dir: str | None = None, include_runtime_files: bool | None = None, capi_version: tuple[int, int] | None = None, python_version: tuple[int, int] | None = None, strict_dunder_typing: bool = False, group_name: str | None = None, log_trace: bool = False, depends_on_librt_internal: bool = False, experimental_features: bool = False, ) -> None: self.strip_asserts = strip_asserts self.multi_file = multi_file self.verbose = verbose self.separate = separate self.global_opts = not separate self.target_dir = target_dir or "build" self.include_runtime_files = ( include_runtime_files if include_runtime_files is not None else not multi_file ) # The target Python C API version. Overriding this is mostly # useful in IR tests, since there's no guarantee that # binaries are backward compatible even if no recent API # features are used. self.capi_version = capi_version or sys.version_info[:2] self.python_version = python_version # Make possible to inline dunder methods in the generated code. # Typically, the convention is the dunder methods can return `NotImplemented` # even when its return type is just `bool`. # By enabling this option, this convention is no longer valid and the dunder # will assume the return type of the method strictly, which can lead to # more optimization opportunities. self.strict_dunders_typing = strict_dunder_typing # Override the automatic group name derived from the hash of module names. # This affects the names of generated .c, .h and shared library files. # This is only supported when compiling exactly one group, and a shared # library is generated (with shims). This can be used to make the output # file names more predictable. self.group_name = group_name # If enabled, write a trace log of events based on executed operations to # mypyc_trace.txt when compiled module is executed. This is useful for # performance analysis. self.log_trace = log_trace # If enabled, add capsule imports of librt.internal API. This should be used # only for mypy itself, third-party code compiled with mypyc should not use # librt.internal. self.depends_on_librt_internal = depends_on_librt_internal # Some experimental features are only available when building librt in # experimental mode (e.g. use _experimental suffix in librt run test). # These can't be used with a librt wheel installed from PyPI. self.experimental_features = experimental_features
CompilerOptions
python
numpy__numpy
numpy/_core/tests/test_numeric.py
{ "start": 155971, "end": 158804 }
class ____: def test_broadcast_in_args(self): # gh-5881 arrs = [np.empty((6, 7)), np.empty((5, 6, 1)), np.empty((7,)), np.empty((5, 1, 7))] mits = [np.broadcast(*arrs), np.broadcast(np.broadcast(*arrs[:0]), np.broadcast(*arrs[0:])), np.broadcast(np.broadcast(*arrs[:1]), np.broadcast(*arrs[1:])), np.broadcast(np.broadcast(*arrs[:2]), np.broadcast(*arrs[2:])), np.broadcast(arrs[0], np.broadcast(*arrs[1:-1]), arrs[-1])] for mit in mits: assert_equal(mit.shape, (5, 6, 7)) assert_equal(mit.ndim, 3) assert_equal(mit.nd, 3) assert_equal(mit.numiter, 4) for a, ia in zip(arrs, mit.iters): assert_(a is ia.base) def test_broadcast_single_arg(self): # gh-6899 arrs = [np.empty((5, 6, 7))] mit = np.broadcast(*arrs) assert_equal(mit.shape, (5, 6, 7)) assert_equal(mit.ndim, 3) assert_equal(mit.nd, 3) assert_equal(mit.numiter, 1) assert_(arrs[0] is mit.iters[0].base) def test_number_of_arguments(self): arr = np.empty((5,)) for j in range(70): arrs = [arr] * j if j > 64: assert_raises(ValueError, np.broadcast, *arrs) else: mit = np.broadcast(*arrs) assert_equal(mit.numiter, j) def test_broadcast_error_kwargs(self): # gh-13455 arrs = [np.empty((5, 6, 7))] mit = np.broadcast(*arrs) mit2 = np.broadcast(*arrs, **{}) # noqa: PIE804 assert_equal(mit.shape, mit2.shape) assert_equal(mit.ndim, mit2.ndim) assert_equal(mit.nd, mit2.nd) assert_equal(mit.numiter, mit2.numiter) assert_(mit.iters[0].base is mit2.iters[0].base) assert_raises(ValueError, np.broadcast, 1, x=1) def test_shape_mismatch_error_message(self): with pytest.raises(ValueError, match=r"arg 0 with shape \(1, 3\) and " r"arg 2 with shape \(2,\)"): np.broadcast([[1, 2, 3]], [[4], [5]], [6, 7]) @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO") @pytest.mark.xfail(IS_PYPY, reason="PyPy does not modify tp_doc") def test_signatures(self): sig_new = inspect.signature(np.broadcast) assert len(sig_new.parameters) == 1 assert "arrays" in sig_new.parameters assert sig_new.parameters["arrays"].kind == inspect.Parameter.VAR_POSITIONAL sig_reset = inspect.signature(np.broadcast.reset) assert len(sig_reset.parameters) == 1 assert "self" in sig_reset.parameters assert sig_reset.parameters["self"].kind == inspect.Parameter.POSITIONAL_ONLY
TestBroadcast
python
cython__cython
docs/examples/userguide/buffer/matrix_with_buffer.py
{ "start": 139, "end": 1816 }
class ____: ncols: cython.Py_ssize_t shape: cython.Py_ssize_t[2] strides: cython.Py_ssize_t[2] v: vector[cython.float] def __cinit__(self, ncols: cython.Py_ssize_t): self.ncols = ncols def add_row(self): """Adds a row, initially zero-filled.""" self.v.resize(self.v.size() + self.ncols) def __getbuffer__(self, buffer: cython.pointer[Py_buffer], flags: cython.int): itemsize: cython.Py_ssize_t = cython.sizeof(self.v[0]) self.shape[0] = self.v.size() // self.ncols self.shape[1] = self.ncols # Stride 1 is the distance, in bytes, between two items in a row; # this is the distance between two adjacent items in the vector. # Stride 0 is the distance between the first elements of adjacent rows. self.strides[1] = cython.cast(cython.Py_ssize_t, ( cython.cast(cython.p_char, cython.address(self.v[1])) - cython.cast(cython.p_char, cython.address(self.v[0])) )) self.strides[0] = self.ncols * self.strides[1] buffer.buf = cython.cast(cython.p_char, cython.address(self.v[0])) buffer.format = 'f' # float buffer.internal = cython.NULL # see References buffer.itemsize = itemsize buffer.len = self.v.size() * itemsize # product(shape) * itemsize buffer.ndim = 2 buffer.obj = self buffer.readonly = 0 buffer.shape = self.shape buffer.strides = self.strides buffer.suboffsets = cython.NULL # for pointer arrays only def __releasebuffer__(self, buffer: cython.pointer[Py_buffer]): pass
Matrix
python
huggingface__transformers
examples/modular-transformers/modeling_dummy_bert.py
{ "start": 21103, "end": 21811 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states
DummyBertPredictionHeadTransform
python
readthedocs__readthedocs.org
readthedocs/oauth/services/base.py
{ "start": 698, "end": 982 }
class ____(Exception): """Error raised when a service failed to sync.""" INVALID_OR_REVOKED_ACCESS_TOKEN = _( "Our access to your following accounts was revoked: {provider}. " "Please, reconnect them from your social account connections." )
SyncServiceError
python
pdm-project__pdm
src/pdm/models/versions.py
{ "start": 355, "end": 5908 }
class ____: """A loosely semantic version implementation that allows '*' in version part. This class is designed for Python specifier set merging only, hence up to 3 version parts are kept, plus optional prerelease suffix. This is a slightly different purpose than packaging.version.Version which is focused on supporting PEP 440 version identifiers, not specifiers. """ MIN: Version MAX: Version # Pre-release may follow version with {a|b|rc}N # https://docs.python.org/3/faq/general.html#how-does-the-python-version-numbering-scheme-work pre: tuple[str, int] | None = None def __init__(self, version: tuple[VersionBit, ...] | str) -> None: if isinstance(version, str): version_str = re.sub(r"(?<!\.)\*", ".*", version) bits: list[VersionBit] = [] for v in version_str.split(".")[:3]: try: bits.append(int(v)) except ValueError: pre_m = PRE_RELEASE_SEGMENT_RE.match(v) if v == "*": bits.append("*") break # .* is only allowed at the end, per PEP 440 elif pre_m: bits.append(int(pre_m.group("digit"))) pre_type = pre_m.group("type").lower() pre_n = int(pre_m.group("n") or "0") self.pre = (pre_type, pre_n) break # pre release version is only at the end else: raise InvalidPyVersion( f"{version_str}: postreleases are not supported for python version specifiers." ) from None version = tuple(bits) self._version: tuple[VersionBit, ...] = version def complete(self, complete_with: VersionBit = 0, max_bits: int = 3) -> Version: """ Complete the version with the given bit if the version has less than max parts """ assert len(self._version) <= max_bits, self new_tuple = self._version + (max_bits - len(self._version)) * (complete_with,) ret = type(self)(new_tuple) ret.pre = self.pre return ret def bump(self, idx: int = -1) -> Version: """Bump version by incrementing 1 on the given index of version part. If index is not provided: increment the last version bit unless version is a pre-release, in which case, increment the pre-release number. """ version = self._version if idx == -1 and self.pre: ret = type(self)(version).complete() ret.pre = (self.pre[0], self.pre[1] + 1) else: head, value = version[:idx], int(version[idx]) ret = type(self)((*head, value + 1)).complete() ret.pre = None return ret def startswith(self, other: Version) -> bool: """Check if the version begins with another version.""" return self._version[: len(other._version)] == other._version @property def is_wildcard(self) -> bool: """Check if the version ends with a '*'""" return self._version[-1] == "*" @property def is_prerelease(self) -> bool: """Check if the version is a prerelease.""" return self.pre is not None def __str__(self) -> str: parts = [] parts.append(".".join(map(str, self._version))) if self.pre: parts.append("".join(str(x) for x in self.pre)) return "".join(parts) def __repr__(self) -> str: return f"<Version({self})>" def __eq__(self, other: Any) -> bool: if not isinstance(other, Version): return NotImplemented return self._version == other._version and self.pre == other.pre def __lt__(self, other: Any) -> bool: if not isinstance(other, Version): return NotImplemented def comp_key(version: Version) -> list[float]: ret: list[float] = [-1 if v == "*" else v for v in version._version] if version.pre: # Get the ascii value of first character, a < b < r[c] ret += [ord(version.pre[0][0]), version.pre[1]] else: ret += [float("inf")] return ret return comp_key(self) < comp_key(other) def __gt__(self, other: Any) -> bool: return not (self.__lt__(other) or self.__eq__(other)) def __le__(self, other: Any) -> bool: return self.__lt__(other) or self.__eq__(other) def __ge__(self, other: Any) -> bool: return self.__gt__(other) or self.__eq__(other) @overload def __getitem__(self, idx: int) -> VersionBit: ... @overload def __getitem__(self, idx: slice) -> Version: ... def __getitem__(self, idx: int | slice) -> VersionBit | Version: if isinstance(idx, slice): return type(self)(self._version[idx]) else: return self._version[idx] def __setitem__(self, idx: int, value: VersionBit) -> None: if not isinstance(idx, int): raise TypeError("Slice assignment is not supported") version = list(self._version) version[idx] = value self._version = tuple(version) def __hash__(self) -> int: return hash((self._version, self.pre)) @property def is_py2(self) -> bool: return self._version[0] == 2 Version.MIN = Version((-1, -1, -1)) Version.MAX = Version((99, 99, 99))
Version
python
jazzband__tablib
tests/test_tablib.py
{ "start": 38102, "end": 43328 }
class ____(BaseTestCase): FORMAT_CONVERT = { 'yearlong': '%Y', 'monthlong': '%m', 'daylong': '%d', 'hourslong': '%H', 'minuteslong': '%M', 'secondslong': '%S', 'secondslong0': '%S', } def test_ods_export_import_set(self): date = dt.date(2019, 10, 4) date_time = dt.datetime(2019, 10, 4, 12, 30, 8) time = dt.time(14, 30) data.append(('string', '004', 42, 21.55, Decimal('34.5'), date, time, date_time, None, '')) data.headers = ( 'string', 'start0', 'integer', 'float', 'decimal', 'date', 'time', 'date/time', 'None', 'empty', ) _ods = data.ods data.ods = _ods self.assertEqual(data.dict[0]['string'], 'string') self.assertEqual(data.dict[0]['start0'], '004') self.assertEqual(data.dict[0]['integer'], 42) self.assertEqual(data.dict[0]['float'], 21.55) self.assertEqual(data.dict[0]['decimal'], 34.5) self.assertEqual(data.dict[0]['date'], date) self.assertEqual(data.dict[0]['time'], time) self.assertEqual(data.dict[0]['date/time'], date_time) self.assertEqual(data.dict[0]['None'], '') self.assertEqual(data.dict[0]['empty'], '') def test_ods_export_display(self): """Test that exported datetime types are displayed correctly in office software""" date = dt.date(2019, 10, 4) date_time = dt.datetime(2019, 10, 4, 12, 30, 8) time = dt.time(14, 30) data.append((date, time, date_time)) data.headers = ('date', 'time', 'date/time') _ods = data.ods ods_book = opendocument.load(BytesIO(_ods)) styles = {style.getAttribute('name'): style for style in ods_book.styles.childNodes} automatic_styles = { style.getAttribute('name'): style.getAttribute('datastylename') for style in ods_book.automaticstyles.childNodes } def get_format(cell): style = styles[automatic_styles[cell.getAttribute('stylename')]] f = [] for number in style.childNodes: name = number.qname[1] + ''.join(number.attributes.values()) f.append(self.FORMAT_CONVERT.get(name, str(number))) return ''.join(f) cells = ods_book.spreadsheet.getElementsByType(table.TableRow)[1].childNodes self.assertEqual(str(date), str(cells[0])) self.assertEqual('%Y-%m-%d', get_format(cells[0])) self.assertEqual(str(time), str(cells[1])) self.assertEqual('%H:%M:%S', get_format(cells[1])) self.assertEqual(str(date_time), str(cells[2])) self.assertEqual('%Y-%m-%d %H:%M:%S', get_format(cells[2])) def test_ods_import_book(self): ods_source = Path(__file__).parent / 'files' / 'book.ods' with ods_source.open('rb') as fh: dbook = tablib.Databook().load(fh, 'ods') self.assertEqual(len(dbook.sheets()), 2) self.assertEqual(["This", "is", "a", "second", "sheet"], dbook.sheets()[1].headers) def test_ods_import_set_skip_lines(self): data.append(('garbage', 'line', '')) data.append(('', '', '')) data.append(('id', 'name', 'description')) _ods = data.ods new_data = tablib.Dataset().load(_ods, skip_lines=2) self.assertEqual(new_data.headers, ['id', 'name', 'description']) def test_ods_import_set_ragged(self): ods_source = Path(__file__).parent / 'files' / 'ragged.ods' with ods_source.open('rb') as fh: dataset = tablib.Dataset().load(fh, 'ods') self.assertEqual(dataset.pop(), (1, '', True, '')) def test_ods_unknown_value_type(self): # The ods file was trafficked to contain: # <table:table-cell office:value-type="unknown" calcext:value-type="string"> ods_source = Path(__file__).parent / 'files' / 'unknown_value_type.ods' with ods_source.open('rb') as fh: dataset = tablib.Dataset().load(fh, 'ods', headers=False) self.assertEqual(dataset.pop(), ('abcd',)) def test_ods_export_dates(self): """test against odf specification""" date = dt.date(2019, 10, 4) date_time = dt.datetime(2019, 10, 4, 12, 30, 8) time = dt.time(14, 30) data.append((date, time, date_time)) data.headers = ('date', 'time', 'date/time') _ods = data.ods ods_book = opendocument.load(BytesIO(_ods)) cells = ods_book.spreadsheet.getElementsByType(table.TableRow)[1].childNodes # date value self.assertEqual(cells[0].getAttribute('datevalue'), '2019-10-04') # time value duration_exp = re.compile(r"^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?" r"(?:T(?:(\d+)H)?(?:(\d+)M)?(?:([\d.]+)S)?)?$") duration = duration_exp.match(cells[1].getAttribute('timevalue')).groups() self.assertListEqual([0, 0, 0, 14, 30, 0], [int(v or 0) for v in duration]) # datetime value self.assertEqual(cells[2].getAttribute('datevalue'), '2019-10-04T12:30:08')
ODSTests
python
wandb__wandb
wandb/sdk/artifacts/_generated/fetch_artifact_manifest.py
{ "start": 353, "end": 591 }
class ____(GQLResult): current_manifest: Optional[DeferredManifestFragment] = Field( alias="currentManifest" ) FetchArtifactManifest.model_rebuild() FetchArtifactManifestArtifact.model_rebuild()
FetchArtifactManifestArtifact
python
scipy__scipy
scipy/stats/tests/test_mstats_basic.py
{ "start": 2138, "end": 4413 }
class ____: def test_1d(self): a = [1, 2, 3, 4] desired = np.power(1*2*3*4, 1./4.) check_equal_gmean(a, desired, rtol=1e-14) def test_1d_ma(self): # Test a 1d masked array a = ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) desired = 45.2872868812 check_equal_gmean(a, desired) a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1]) desired = np.power(1*2*3, 1./3.) check_equal_gmean(a, desired, rtol=1e-14) def test_1d_ma_value(self): # Test a 1d masked array with a masked value a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], mask=[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) desired = 41.4716627439 check_equal_gmean(a, desired) def test_1d_ma0(self): # Test a 1d masked array with zero element a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 0]) desired = 0 check_equal_gmean(a, desired) def test_1d_ma_inf(self): # Test a 1d masked array with negative element a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, -1]) desired = np.nan with np.errstate(invalid='ignore'): check_equal_gmean(a, desired) @pytest.mark.skipif(not hasattr(np, 'float96'), reason='cannot find float96 so skipping') def test_1d_float96(self): a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1]) desired_dt = np.power(1*2*3, 1./3.).astype(np.float96) check_equal_gmean(a, desired_dt, dtype=np.float96, rtol=1e-14) def test_2d_ma(self): a = ma.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], mask=[[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]]) desired = np.array([1, 2, 3, 4]) check_equal_gmean(a, desired, axis=0, rtol=1e-14) desired = ma.array([np.power(1*2*3*4, 1./4.), np.power(2*3, 1./2.), np.power(1*4, 1./2.)]) check_equal_gmean(a, desired, axis=-1, rtol=1e-14) # Test a 2d masked array a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]] desired = 52.8885199 check_equal_gmean(np.ma.array(a), desired) @skip_xp_invalid_arg
TestGeoMean
python
ray-project__ray
python/ray/serve/tests/test_metrics_2.py
{ "start": 23228, "end": 34087 }
class ____: def test_queued_queries_basic(self, metrics_start_shutdown): signal = SignalActor.options(name="signal123").remote() timeseries = PrometheusTimeseries() serve.run(WaitForSignal.options(max_ongoing_requests=1).bind(), name="app1") # First call should get assigned to a replica # call.remote("WaitForSignal", "app1") caller = CallActor.remote("WaitForSignal", "app1") caller.call.remote() for i in range(5): # call.remote("WaitForSignal", "app1") # c.call.remote() caller.call.remote() wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_deployment_queued_queries", tags={"application": "app1"}, expected=i + 1, timeseries=timeseries, ) # Release signal ray.get(signal.send.remote()) wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_deployment_queued_queries", tags={"application": "app1", "deployment": "WaitForSignal"}, expected=0, timeseries=timeseries, ) def test_queued_queries_multiple_handles(self, metrics_start_shutdown): signal = SignalActor.options(name="signal123").remote() serve.run(WaitForSignal.options(max_ongoing_requests=1).bind(), name="app1") # Send first request call.remote("WaitForSignal", "app1") wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_deployment_queued_queries", tags={"application": "app1", "deployment": "WaitForSignal"}, expected=0, ) # Send second request (which should stay queued) call.remote("WaitForSignal", "app1") wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_deployment_queued_queries", tags={"application": "app1", "deployment": "WaitForSignal"}, expected=1, ) # Send third request (which should stay queued) call.remote("WaitForSignal", "app1") wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_deployment_queued_queries", tags={"application": "app1", "deployment": "WaitForSignal"}, expected=2, ) # Release signal ray.get(signal.send.remote()) wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_deployment_queued_queries", tags={"application": "app1", "deployment": "WaitForSignal"}, expected=0, ) def test_queued_queries_disconnected(self, metrics_start_shutdown): """Check that disconnected queued queries are tracked correctly.""" signal = SignalActor.remote() @serve.deployment( max_ongoing_requests=1, ) async def hang_on_first_request(): await signal.wait.remote() serve.run(hang_on_first_request.bind()) print("Deployed hang_on_first_request deployment.") timeseries = PrometheusTimeseries() wait_for_condition( check_metric_float_eq, timeout=15, metric="ray_serve_num_scheduling_tasks", # Router is eagerly created on HTTP proxy, so there are metrics emitted # from proxy router expected=0, # TODO(zcin): this tag shouldn't be necessary, there shouldn't be a mix of # metrics from new and old sessions. expected_tags={ "SessionName": ray._private.worker.global_worker.node.session_name }, timeseries=timeseries, ) print("ray_serve_num_scheduling_tasks updated successfully.") wait_for_condition( check_metric_float_eq, timeout=15, metric="ray_serve_num_scheduling_tasks_in_backoff", # Router is eagerly created on HTTP proxy, so there are metrics emitted # from proxy router expected=0, # TODO(zcin): this tag shouldn't be necessary, there shouldn't be a mix of # metrics from new and old sessions. expected_tags={ "SessionName": ray._private.worker.global_worker.node.session_name }, timeseries=timeseries, ) print("serve_num_scheduling_tasks_in_backoff updated successfully.") @ray.remote(num_cpus=0) def do_request(): r = httpx.get("http://localhost:8000/", timeout=10) r.raise_for_status() return r # Make a request to block the deployment from accepting other requests. request_refs = [do_request.remote()] wait_for_condition( lambda: ray.get(signal.cur_num_waiters.remote()) == 1, timeout=10 ) print("First request is executing.") wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_num_ongoing_http_requests", expected=1, timeseries=timeseries, ) print("ray_serve_num_ongoing_http_requests updated successfully.") num_queued_requests = 3 request_refs.extend([do_request.remote() for _ in range(num_queued_requests)]) print(f"{num_queued_requests} more requests now queued.") # First request should be processing. All others should be queued. wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_deployment_queued_queries", expected=num_queued_requests, timeseries=timeseries, ) print("ray_serve_deployment_queued_queries updated successfully.") wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_num_ongoing_http_requests", expected=num_queued_requests + 1, timeseries=timeseries, ) print("ray_serve_num_ongoing_http_requests updated successfully.") # There should be 2 scheduling tasks (which is the max, since # 2 = 2 * 1 replica) that are attempting to schedule the hanging requests. wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_num_scheduling_tasks", expected=2, timeseries=timeseries, ) print("ray_serve_num_scheduling_tasks updated successfully.") wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_num_scheduling_tasks_in_backoff", expected=2, timeseries=timeseries, ) print("serve_num_scheduling_tasks_in_backoff updated successfully.") # Disconnect all requests by cancelling the Ray tasks. [ray.cancel(ref, force=True) for ref in request_refs] timeseries.flush() print("Cancelled all HTTP requests.") wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_deployment_queued_queries", expected=0, timeseries=timeseries, ) print("ray_serve_deployment_queued_queries updated successfully.") # Task should get cancelled. wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_num_ongoing_http_requests", expected=0, timeseries=timeseries, ) print("ray_serve_num_ongoing_http_requests updated successfully.") wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_num_scheduling_tasks", expected=0, timeseries=timeseries, ) print("ray_serve_num_scheduling_tasks updated successfully.") wait_for_condition( check_sum_metric_eq, timeout=15, metric_name="ray_serve_num_scheduling_tasks_in_backoff", expected=0, timeseries=timeseries, ) print("serve_num_scheduling_tasks_in_backoff updated successfully.") # Unblock hanging request. ray.get(signal.send.remote()) def test_running_requests_gauge(self, metrics_start_shutdown): signal = SignalActor.options(name="signal123").remote() serve.run( Router.options(num_replicas=2, ray_actor_options={"num_cpus": 0}).bind( [ WaitForSignal.options( name="d1", ray_actor_options={"num_cpus": 0}, max_ongoing_requests=2, num_replicas=3, ).bind(), WaitForSignal.options( name="d2", ray_actor_options={"num_cpus": 0}, max_ongoing_requests=2, num_replicas=3, ).bind(), ], ), name="app1", ) requests_sent = {1: 0, 2: 0} timeseries = PrometheusTimeseries() for i in range(5): index = random.choice([1, 2]) print(f"Sending request to d{index}") call.remote("Router", "app1", index) requests_sent[index] += 1 wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_num_ongoing_requests_at_replicas", tags={"application": "app1", "deployment": "d1"}, expected=requests_sent[1], timeseries=timeseries, ) wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_num_ongoing_requests_at_replicas", tags={"application": "app1", "deployment": "d2"}, expected=requests_sent[2], timeseries=timeseries, ) wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_num_ongoing_requests_at_replicas", tags={"application": "app1", "deployment": "Router"}, expected=i + 1, timeseries=timeseries, ) # Release signal, the number of running requests should drop to 0 ray.get(signal.send.remote()) wait_for_condition( check_sum_metric_eq, metric_name="ray_serve_num_ongoing_requests_at_replicas", tags={"application": "app1"}, expected=0, timeseries=timeseries, ) if __name__ == "__main__": sys.exit(pytest.main(["-v", "-s", __file__]))
TestHandleMetrics
python
pytorch__pytorch
torch/_inductor/codegen/wrapper.py
{ "start": 19840, "end": 20273 }
class ____(WrapperLine): wrapper: PythonWrapperCodegen node: Union[BufferLike, ir.TorchBindObject] def codegen(self, code: IndentedBuffer) -> None: assert self.node.get_name() not in V.graph.removed_buffers code.writeline(self.wrapper.make_buffer_free(self.node)) def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: return converter._generate_free @dataclasses.dataclass
FreeLine
python
getsentry__sentry
tests/sentry/uptime/rdap/test_tasks.py
{ "start": 203, "end": 1062 }
class ____(UptimeTestCase): @mock.patch( "sentry.uptime.rdap.tasks.resolve_rdap_network_details", ) def test(self, mock_fetch_subscription_rdap_info: mock.MagicMock) -> None: test_info: DomainAddressDetails = { "handle": "TEST-HANDLE", "owner_name": "Rick Sanchez", } mock_fetch_subscription_rdap_info.return_value = test_info uptime_subscription = self.create_uptime_subscription( url="https://some.example.com/health", ) fetch_subscription_rdap_info(uptime_subscription.id) uptime_subscription.refresh_from_db() mock_fetch_subscription_rdap_info.assert_called_with("some.example.com") assert uptime_subscription.host_provider_id == "TEST-HANDLE" assert uptime_subscription.host_provider_name == "Rick Sanchez"
RDAPTasksTest
python
spyder-ide__spyder
spyder/plugins/editor/widgets/codeeditor/tests/assets/black_max_line.py
{ "start": 408, "end": 663 }
class ____: def __init__( self, ): super().__init__() self.x = 2 def method3( self, ): pass def method2( self, ): pass def method1( self, ): pass
Class1
python
doocs__leetcode
solution/2600-2699/2611.Mice and Cheese/Solution.py
{ "start": 0, "end": 292 }
class ____: def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int: n = len(reward1) idx = sorted(range(n), key=lambda i: reward1[i] - reward2[i], reverse=True) return sum(reward1[i] for i in idx[:k]) + sum(reward2[i] for i in idx[k:])
Solution
python
langchain-ai__langchain
libs/core/langchain_core/example_selectors/length_based.py
{ "start": 390, "end": 3366 }
class ____(BaseExampleSelector, BaseModel): """Select examples based on length.""" examples: list[dict] """A list of the examples that the prompt template expects.""" example_prompt: PromptTemplate """Prompt template used to format the examples.""" get_text_length: Callable[[str], int] = _get_length_based """Function to measure prompt length. Defaults to word count.""" max_length: int = 2048 """Max length for the prompt, beyond which examples are cut.""" example_text_lengths: list[int] = Field(default_factory=list) """Length of each example.""" def add_example(self, example: dict[str, str]) -> None: """Add new example to list. Args: example: A dictionary with keys as input variables and values as their values. """ self.examples.append(example) string_example = self.example_prompt.format(**example) self.example_text_lengths.append(self.get_text_length(string_example)) async def aadd_example(self, example: dict[str, str]) -> None: """Async add new example to list. Args: example: A dictionary with keys as input variables and values as their values. """ self.add_example(example) @model_validator(mode="after") def post_init(self) -> Self: """Validate that the examples are formatted correctly.""" if self.example_text_lengths: return self string_examples = [self.example_prompt.format(**eg) for eg in self.examples] self.example_text_lengths = [self.get_text_length(eg) for eg in string_examples] return self def select_examples(self, input_variables: dict[str, str]) -> list[dict]: """Select which examples to use based on the input lengths. Args: input_variables: A dictionary with keys as input variables and values as their values. Returns: A list of examples to include in the prompt. """ inputs = " ".join(input_variables.values()) remaining_length = self.max_length - self.get_text_length(inputs) i = 0 examples = [] while remaining_length > 0 and i < len(self.examples): new_length = remaining_length - self.example_text_lengths[i] if new_length < 0: break examples.append(self.examples[i]) remaining_length = new_length i += 1 return examples async def aselect_examples(self, input_variables: dict[str, str]) -> list[dict]: """Async select which examples to use based on the input lengths. Args: input_variables: A dictionary with keys as input variables and values as their values. Returns: A list of examples to include in the prompt. """ return self.select_examples(input_variables)
LengthBasedExampleSelector
python
vyperlang__vyper
vyper/venom/passes/load_elimination.py
{ "start": 1835, "end": 5763 }
class ____(IRAnalysis): InstToLattice = dict[IRInstruction, Lattice] lattice: dict[Effects | str, InstToLattice] cfg: CFGAnalysis eff_bb_lattice: dict[Effects | str, dict[IRBasicBlock, Lattice]] def analyze(self): self.cfg = self.analyses_cache.request_analysis(CFGAnalysis) self.dfg = self.analyses_cache.request_analysis(DFGAnalysis) self.lattice = dict() self.eff_bb_lattice = dict() self._analyze_type(Effects.MEMORY, "mload", "mstore") self._analyze_type(Effects.TRANSIENT, "tload", "tstore") self._analyze_type(Effects.STORAGE, "sload", "sstore") self._analyze_type("dload", "dload", None) self._analyze_type("calldataload", "calldataload", None) def _analyze_type(self, eff: Effects | str, load_opcode: str, store_opcode: str | None): self.inst_to_lattice: LoadAnalysis.InstToLattice = dict() self.bb_to_lattice: dict[IRBasicBlock, Lattice] = dict() worklist = deque(self.cfg.dfs_pre_walk) while len(worklist) > 0: bb = worklist.popleft() change = self._handle_bb(eff, load_opcode, store_opcode, bb) if change: for succ in self.cfg.cfg_out(bb): worklist.append(succ) self.lattice[eff] = self.inst_to_lattice self.eff_bb_lattice[eff] = self.bb_to_lattice def _merge(self, bb: IRBasicBlock) -> Lattice: preds = list(self.cfg.cfg_in(bb)) if len(preds) == 0: return dict() res = self.bb_to_lattice.get(preds[0], dict()).copy() for pred in preds[1:]: other = self.bb_to_lattice.get(pred, dict()) common_keys = other.keys() & res.keys() tmp = res.copy() res = dict() for key in common_keys: res[key] = tmp[key] | other[key] return res def get_memloc(self, op): op = self.dfg._traverse_assign_chain(op) if isinstance(op, IRAbstractMemLoc): return op if isinstance(op, IRLiteral): return op return None def _handle_bb( self, eff: Effects | str, load_opcode: str, store_opcode: str | None, bb: IRBasicBlock ): lattice = self._merge(bb) for inst in bb.instructions: if inst.opcode == load_opcode: self.inst_to_lattice[inst] = lattice.copy() ptr = inst.operands[0] lattice[ptr] = OrderedSet([inst.output]) elif inst.opcode == store_opcode: self.inst_to_lattice[inst] = lattice.copy() # mstore [val, ptr] val, ptr = inst.operands lit = self.get_memloc(ptr) if lit is None: lattice.clear() lattice[ptr] = OrderedSet([val]) continue assert lit is not None # kick out any conflicts for existing_key in lattice.copy().keys(): existing_lit = self.get_memloc(existing_key) if existing_lit is None: # a variable in the lattice. assign this ptr in the lattice # and flush everything else. lattice.clear() lattice[ptr] = OrderedSet([val]) break if store_opcode is not None: if _conflict(store_opcode, lit, existing_lit): del lattice[existing_key] lattice[ptr] = OrderedSet([val]) elif isinstance(eff, Effects) and eff in inst.get_write_effects(): lattice.clear() if bb not in self.bb_to_lattice or self.bb_to_lattice[bb] != lattice: self.bb_to_lattice[bb] = lattice.copy() return True return False
LoadAnalysis
python
joblib__joblib
joblib/hashing.py
{ "start": 1158, "end": 1304 }
class ____(object): """Class used to hash objects that won't normally pickle""" def __init__(self, *args): self.args = args
_MyHash
python
django__django
django/contrib/gis/geos/geometry.py
{ "start": 886, "end": 23439 }
class ____(GEOSBase): _GEOS_CLASSES = None ptr_type = GEOM_PTR destructor = capi.destroy_geom has_cs = False # Only Point, LineString, LinearRing have coordinate sequences def __init__(self, ptr, cls): self._ptr = ptr # Setting the class type (e.g., Point, Polygon, etc.) if type(self) in (GEOSGeometryBase, GEOSGeometry): if cls is None: if GEOSGeometryBase._GEOS_CLASSES is None: # Inner imports avoid import conflicts with GEOSGeometry. from .collections import ( GeometryCollection, MultiLineString, MultiPoint, MultiPolygon, ) from .linestring import LinearRing, LineString from .point import Point from .polygon import Polygon GEOSGeometryBase._GEOS_CLASSES = { 0: Point, 1: LineString, 2: LinearRing, 3: Polygon, 4: MultiPoint, 5: MultiLineString, 6: MultiPolygon, 7: GeometryCollection, } cls = GEOSGeometryBase._GEOS_CLASSES[self.geom_typeid] self.__class__ = cls self._post_init() def _post_init(self): "Perform post-initialization setup." # Setting the coordinate sequence for the geometry (will be None on # geometries that do not have coordinate sequences) self._cs = ( GEOSCoordSeq(capi.get_cs(self.ptr), self.hasz) if self.has_cs else None ) def __copy__(self): """ Return a clone because the copy of a GEOSGeometry may contain an invalid pointer location if the original is garbage collected. """ return self.clone() def __deepcopy__(self, memodict): """ The `deepcopy` routine is used by the `Node` class of django.utils.tree; thus, the protocol routine needs to be implemented to return correct copies (clones) of these GEOS objects, which use C pointers. """ return self.clone() def __str__(self): "EWKT is used for the string representation." return self.ewkt def __repr__(self): "Short-hand representation because WKT may be very large." return "<%s object at %s>" % (self.geom_type, hex(addressof(self.ptr))) # Pickling support def _to_pickle_wkb(self): return bytes(self.wkb) def _from_pickle_wkb(self, wkb): return wkb_r().read(memoryview(wkb)) def __getstate__(self): # The pickled state is simply a tuple of the WKB (in string form) # and the SRID. return self._to_pickle_wkb(), self.srid def __setstate__(self, state): # Instantiating from the tuple state that was pickled. wkb, srid = state ptr = self._from_pickle_wkb(wkb) if not ptr: raise GEOSException("Invalid Geometry loaded from pickled state.") self.ptr = ptr self._post_init() self.srid = srid @classmethod def _from_wkb(cls, wkb): return wkb_r().read(wkb) @staticmethod def from_ewkt(ewkt): ewkt = force_bytes(ewkt) srid = None parts = ewkt.split(b";", 1) if len(parts) == 2: srid_part, wkt = parts match = re.match(rb"SRID=(?P<srid>\-?\d+)", srid_part) if not match: raise ValueError("EWKT has invalid SRID part.") srid = int(match["srid"]) else: wkt = ewkt if not wkt: raise ValueError("Expected WKT but got an empty string.") return GEOSGeometry(GEOSGeometry._from_wkt(wkt), srid=srid) @staticmethod def _from_wkt(wkt): return wkt_r().read(wkt) @classmethod def from_gml(cls, gml_string): return gdal.OGRGeometry.from_gml(gml_string).geos # Comparison operators def __eq__(self, other): """ Equivalence testing, a Geometry may be compared with another Geometry or an EWKT representation. """ if isinstance(other, str): try: other = GEOSGeometry.from_ewkt(other) except (ValueError, GEOSException): return False return ( isinstance(other, GEOSGeometry) and self.srid == other.srid and self.equals_exact(other) ) def __hash__(self): return hash((self.srid, self.wkt)) # ### Geometry set-like operations ### # Thanks to Sean Gillies for inspiration: # http://lists.gispython.org/pipermail/community/2007-July/001034.html # g = g1 | g2 def __or__(self, other): "Return the union of this Geometry and the other." return self.union(other) # g = g1 & g2 def __and__(self, other): "Return the intersection of this Geometry and the other." return self.intersection(other) # g = g1 - g2 def __sub__(self, other): "Return the difference this Geometry and the other." return self.difference(other) # g = g1 ^ g2 def __xor__(self, other): "Return the symmetric difference of this Geometry and the other." return self.sym_difference(other) # #### Coordinate Sequence Routines #### @property def coord_seq(self): "Return a clone of the coordinate sequence for this Geometry." if self.has_cs: return self._cs.clone() # #### Geometry Info #### @property def geom_type(self): "Return a string representing the Geometry type, e.g. 'Polygon'" return capi.geos_type(self.ptr).decode() @property def geom_typeid(self): "Return an integer representing the Geometry type." return capi.geos_typeid(self.ptr) @property def num_geom(self): "Return the number of geometries in the Geometry." return capi.get_num_geoms(self.ptr) @property def num_coords(self): "Return the number of coordinates in the Geometry." return capi.get_num_coords(self.ptr) @property def num_points(self): "Return the number of points, or coordinates, in the Geometry." return self.num_coords @property def dims(self): "Return the dimension of this Geometry (0=point, 1=line, 2=surface)." return capi.get_dims(self.ptr) def normalize(self, clone=False): """ Convert this Geometry to normal form (or canonical form). If the `clone` keyword is set, then the geometry is not modified and a normalized clone of the geometry is returned instead. """ if clone: clone = self.clone() capi.geos_normalize(clone.ptr) return clone capi.geos_normalize(self.ptr) def make_valid(self): """ Attempt to create a valid representation of a given invalid geometry without losing any of the input vertices. """ return GEOSGeometry(capi.geos_makevalid(self.ptr), srid=self.srid) # #### Unary predicates #### @property def empty(self): """ Return a boolean indicating whether the set of points in this Geometry are empty. """ return capi.geos_isempty(self.ptr) @property def hasz(self): "Return whether the geometry has a Z dimension." return capi.geos_hasz(self.ptr) @property def hasm(self): "Return whether the geometry has a M dimension." if geos_version_tuple() < (3, 12): raise GEOSException("GEOSGeometry.hasm requires GEOS >= 3.12.0.") return capi.geos_hasm(self.ptr) @property def ring(self): "Return whether or not the geometry is a ring." return capi.geos_isring(self.ptr) @property def simple(self): "Return false if the Geometry isn't simple." return capi.geos_issimple(self.ptr) @property def valid(self): "Test the validity of this Geometry." return capi.geos_isvalid(self.ptr) @property def valid_reason(self): """ Return a string containing the reason for any invalidity. """ return capi.geos_isvalidreason(self.ptr).decode() # #### Binary predicates. #### def contains(self, other): "Return true if other.within(this) returns true." return capi.geos_contains(self.ptr, other.ptr) def covers(self, other): """ Return True if the DE-9IM Intersection Matrix for the two geometries is T*****FF*, *T****FF*, ***T**FF*, or ****T*FF*. If either geometry is empty, return False. """ return capi.geos_covers(self.ptr, other.ptr) def crosses(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is T*T****** (for a point and a curve,a point and an area or a line and an area) 0******** (for two curves). """ return capi.geos_crosses(self.ptr, other.ptr) def disjoint(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is FF*FF****. """ return capi.geos_disjoint(self.ptr, other.ptr) def equals(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is T*F**FFF*. """ return capi.geos_equals(self.ptr, other.ptr) def equals_exact(self, other, tolerance=0): """ Return true if the two Geometries are exactly equal, up to a specified tolerance. """ return capi.geos_equalsexact(self.ptr, other.ptr, float(tolerance)) def equals_identical(self, other): """ Return true if the two Geometries are point-wise equivalent. """ if geos_version_tuple() < (3, 12): raise GEOSException( "GEOSGeometry.equals_identical() requires GEOS >= 3.12.0." ) return capi.geos_equalsidentical(self.ptr, other.ptr) def intersects(self, other): "Return true if disjoint return false." return capi.geos_intersects(self.ptr, other.ptr) def overlaps(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is T*T***T** (for two points or two surfaces) 1*T***T** (for two curves). """ return capi.geos_overlaps(self.ptr, other.ptr) def relate_pattern(self, other, pattern): """ Return true if the elements in the DE-9IM intersection matrix for the two Geometries match the elements in pattern. """ if not isinstance(pattern, str) or len(pattern) > 9: raise GEOSException("Invalid intersection matrix pattern.") return capi.geos_relatepattern(self.ptr, other.ptr, force_bytes(pattern)) def touches(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is FT*******, F**T***** or F***T****. """ return capi.geos_touches(self.ptr, other.ptr) def within(self, other): """ Return true if the DE-9IM intersection matrix for the two Geometries is T*F**F***. """ return capi.geos_within(self.ptr, other.ptr) # #### SRID Routines #### @property def srid(self): "Get the SRID for the geometry. Return None if no SRID is set." s = capi.geos_get_srid(self.ptr) if s == 0: return None else: return s @srid.setter def srid(self, srid): "Set the SRID for the geometry." capi.geos_set_srid(self.ptr, 0 if srid is None else srid) # #### Output Routines #### @property def ewkt(self): """ Return the EWKT (SRID + WKT) of the Geometry. """ srid = self.srid return "SRID=%s;%s" % (srid, self.wkt) if srid else self.wkt @property def wkt(self): "Return the WKT (Well-Known Text) representation of this Geometry." return wkt_w(dim=3 if self.hasz else 2, trim=True).write(self).decode() @property def hex(self): """ Return the WKB of this Geometry in hexadecimal form. Please note that the SRID is not included in this representation because it is not a part of the OGC specification (use the `hexewkb` property instead). """ # A possible faster, all-python, implementation: # str(self.wkb).encode('hex') return wkb_w(dim=3 if self.hasz else 2).write_hex(self) @property def hexewkb(self): """ Return the EWKB of this Geometry in hexadecimal form. This is an extension of the WKB specification that includes SRID value that are a part of this geometry. """ return ewkb_w(dim=3 if self.hasz else 2).write_hex(self) @property def json(self): """ Return GeoJSON representation of this Geometry. """ return self.ogr.json geojson = json @property def wkb(self): """ Return the WKB (Well-Known Binary) representation of this Geometry as a Python memoryview. SRID and Z values are not included, use the `ewkb` property instead. """ return wkb_w(3 if self.hasz else 2).write(self) @property def ewkb(self): """ Return the EWKB representation of this Geometry as a Python memoryview. This is an extension of the WKB specification that includes any SRID value that are a part of this geometry. """ return ewkb_w(3 if self.hasz else 2).write(self) @property def kml(self): "Return the KML representation of this Geometry." gtype = self.geom_type return "<%s>%s</%s>" % (gtype, self.coord_seq.kml, gtype) @property def prepared(self): """ Return a PreparedGeometry corresponding to this geometry -- it is optimized for the contains, intersects, and covers operations. """ return PreparedGeometry(self) # #### GDAL-specific output routines #### def _ogr_ptr(self): return gdal.OGRGeometry._from_wkb(self.wkb) @property def ogr(self): "Return the OGR Geometry for this Geometry." return gdal.OGRGeometry(self._ogr_ptr(), self.srs) @property def srs(self): "Return the OSR SpatialReference for SRID of this Geometry." if self.srid: try: return gdal.SpatialReference(self.srid) except (gdal.GDALException, gdal.SRSException): pass return None @property def crs(self): "Alias for `srs` property." return self.srs def transform(self, ct, clone=False): """ Requires GDAL. Transform the geometry according to the given transformation object, which may be an integer SRID, and WKT or PROJ string. By default, transform the geometry in-place and return nothing. However if the `clone` keyword is set, don't modify the geometry and return a transformed clone instead. """ srid = self.srid if ct == srid: # short-circuit where source & dest SRIDs match if clone: return self.clone() else: return if isinstance(ct, gdal.CoordTransform): # We don't care about SRID because CoordTransform presupposes # source SRS. srid = None elif srid is None or srid < 0: raise GEOSException( "Calling transform() with no SRID set is not supported." ) # Creating an OGR Geometry, which is then transformed. g = gdal.OGRGeometry(self._ogr_ptr(), srid) g.transform(ct) # Getting a new GEOS pointer ptr = g._geos_ptr() if clone: # User wants a cloned transformed geometry returned. return GEOSGeometry(ptr, srid=g.srid) if ptr: # Reassigning pointer, and performing post-initialization setup # again due to the reassignment. capi.destroy_geom(self.ptr) self.ptr = ptr self._post_init() self.srid = g.srid else: raise GEOSException("Transformed WKB was invalid.") # #### Topology Routines #### def _topology(self, gptr): "Return Geometry from the given pointer." return GEOSGeometry(gptr, srid=self.srid) @property def boundary(self): "Return the boundary as a newly allocated Geometry object." return self._topology(capi.geos_boundary(self.ptr)) def buffer(self, width, quadsegs=8): """ Return a geometry that represents all points whose distance from this Geometry is less than or equal to distance. Calculations are in the Spatial Reference System of this Geometry. The optional third parameter sets the number of segment used to approximate a quarter circle (defaults to 8). (Text from PostGIS documentation at ch. 6.1.3) """ return self._topology(capi.geos_buffer(self.ptr, width, quadsegs)) def buffer_with_style( self, width, quadsegs=8, end_cap_style=1, join_style=1, mitre_limit=5.0 ): """ Same as buffer() but allows customizing the style of the memoryview. End cap style can be round (1), flat (2), or square (3). Join style can be round (1), mitre (2), or bevel (3). Mitre ratio limit only affects mitered join style. """ return self._topology( capi.geos_bufferwithstyle( self.ptr, width, quadsegs, end_cap_style, join_style, mitre_limit ), ) @property def centroid(self): """ The centroid is equal to the centroid of the set of component Geometries of highest dimension (since the lower-dimension geometries contribute zero "weight" to the centroid). """ return self._topology(capi.geos_centroid(self.ptr)) @property def convex_hull(self): """ Return the smallest convex Polygon that contains all the points in the Geometry. """ return self._topology(capi.geos_convexhull(self.ptr)) def difference(self, other): """ Return a Geometry representing the points making up this Geometry that do not make up other. """ return self._topology(capi.geos_difference(self.ptr, other.ptr)) @property def envelope(self): "Return the envelope for this geometry (a polygon)." return self._topology(capi.geos_envelope(self.ptr)) def intersection(self, other): """ Return a Geometry representing the points shared by this Geometry and other. """ return self._topology(capi.geos_intersection(self.ptr, other.ptr)) @property def point_on_surface(self): "Compute an interior point of this Geometry." return self._topology(capi.geos_pointonsurface(self.ptr)) def relate(self, other): """ Return the DE-9IM intersection matrix for this Geometry and the other. """ return capi.geos_relate(self.ptr, other.ptr).decode() def simplify(self, tolerance=0.0, preserve_topology=False): """ Return the Geometry, simplified using the Douglas-Peucker algorithm to the specified tolerance (higher tolerance => less points). If no tolerance provided, defaults to 0. By default, don't preserve topology - e.g. polygons can be split, collapse to lines or disappear holes can be created or disappear, and lines can cross. By specifying preserve_topology=True, the result will have the same dimension and number of components as the input. This is significantly slower. """ if preserve_topology: return self._topology(capi.geos_preservesimplify(self.ptr, tolerance)) else: return self._topology(capi.geos_simplify(self.ptr, tolerance)) def sym_difference(self, other): """ Return a set combining the points in this Geometry not in other, and the points in other not in this Geometry. """ return self._topology(capi.geos_symdifference(self.ptr, other.ptr)) @property def unary_union(self): "Return the union of all the elements of this geometry." return self._topology(capi.geos_unary_union(self.ptr)) def union(self, other): """ Return a Geometry representing all the points in this Geometry and other. """ return self._topology(capi.geos_union(self.ptr, other.ptr)) # #### Other Routines #### @property def area(self): "Return the area of the Geometry." return capi.geos_area(self.ptr, byref(c_double())) def distance(self, other): """ Return the distance between the closest points on this Geometry and the other. Units will be in those of the coordinate system of the Geometry. """ if not isinstance(other, GEOSGeometry): raise TypeError("distance() works only on other GEOS Geometries.") return capi.geos_distance(self.ptr, other.ptr, byref(c_double())) @property def extent(self): """ Return the extent of this geometry as a 4-tuple, consisting of (xmin, ymin, xmax, ymax). """ from .point import Point env = self.envelope if isinstance(env, Point): xmin, ymin = env.tuple xmax, ymax = xmin, ymin else: xmin, ymin = env[0][0] xmax, ymax = env[0][2] return (xmin, ymin, xmax, ymax) @property def length(self): """ Return the length of this Geometry (e.g., 0 for point, or the circumference of a Polygon). """ return capi.geos_length(self.ptr, byref(c_double())) def clone(self): "Clone this Geometry." return GEOSGeometry(capi.geom_clone(self.ptr))
GEOSGeometryBase
python
tensorflow__tensorflow
tensorflow/python/tools/api/generator2/extractor/extractor_test.py
{ "start": 867, "end": 2746 }
class ____(absltest.TestCase): def test_exported_docstring(self): exporter = exported_api.ExportedApi() p = extractor.Parser( exporter, decorator='tf.tf_export', api_name='tf', ) p.process( 'test.py', '''# 1 """this is an exported docstring. API docstring: tf.test """ # 4 ''', ) self.assertEqual( exporter, exported_api.ExportedApi( docs=[ exported_api.ExportedDoc( file_name='test.py', line_no=2, docstring='this is an exported docstring.', modules=('tf.test',), ) ], ), ) def test_exported_docstring_not_at_top_level(self): exporter = exported_api.ExportedApi() p = extractor.Parser( exporter, decorator='tf.tf_export', api_name='tf', ) self.assertRaisesRegex( extractor.BadExportError, 'test.py:3', lambda: p.process( # pylint: disable=g-long-lambda 'test.py', '''# 1 def a(): # 2 """a docstring API docstring: tf.test """ # 5 ''', ), ) def test_exported_symbol(self): exporter = exported_api.ExportedApi() p = extractor.Parser( exporter, decorator='extractor.api_export.tf_export', api_name='tf', ) p.process( 'test.py', """# 1 from extractor import api_export # 2 from extractor import api_export as ae # 3 try: # 4 from extractor.api_export import tf_export # 5 except ImportError: # 6 pass # 7 from extractor.api_export import tf_export as tfe # 8 from extractor.api_export import other_export # 9 _a = api_export.tf_export("a")(foo) # 10 api_export.tf_export("b", v1=["v1_b"])(_b) # 11 tfe("c")(_c) # 12 @ae.tf_export("d") # 13
ParserTest
python
mlflow__mlflow
mlflow/utils/databricks_utils.py
{ "start": 44616, "end": 54490 }
class ____(NamedTuple): is_client_image: bool major: int minor: int @classmethod def parse(cls, databricks_runtime: str | None = None): dbr_version = databricks_runtime or get_databricks_runtime_version() try: dbr_version_splits = dbr_version.split(".", maxsplit=2) if dbr_version_splits[0] == "client": is_client_image = True major = int(dbr_version_splits[1]) minor = int(dbr_version_splits[2]) if len(dbr_version_splits) > 2 else 0 else: is_client_image = False major = int(dbr_version_splits[0]) minor = int(dbr_version_splits[1]) return cls(is_client_image, major, minor) except Exception: raise MlflowException(f"Failed to parse databricks runtime version '{dbr_version}'.") def get_databricks_runtime_major_minor_version(): return DatabricksRuntimeVersion.parse() _dynamic_token_config_provider = None def _init_databricks_dynamic_token_config_provider(entry_point): """ set a custom DatabricksConfigProvider with the hostname and token of the user running the current command (achieved by looking at PythonAccessibleThreadLocals.commandContext, via the already-exposed NotebookUtils.getContext API) """ global _dynamic_token_config_provider notebook_utils = entry_point.getDbutils().notebook() dbr_version = get_databricks_runtime_major_minor_version() dbr_major_minor_version = (dbr_version.major, dbr_version.minor) # the CLI code in client-branch-1.0 is the same as in the 15.0 runtime branch if dbr_version.is_client_image or dbr_major_minor_version >= (13, 2): class DynamicConfigProvider(DatabricksConfigProvider): def get_config(self): logger = entry_point.getLogger() try: from dbruntime.databricks_repl_context import get_context ctx = get_context() if ctx and ctx.apiUrl and ctx.apiToken: return DatabricksConfig.from_token( host=ctx.apiUrl, token=ctx.apiToken, insecure=ctx.sslTrustAll ) except Exception as e: _logger.debug( "Unexpected internal error while constructing `DatabricksConfig` " f"from REPL context: {e}", ) # Invoking getContext() will attempt to find the credentials related to the # current command execution, so it's critical that we execute it on every # get_config(). api_url_option = notebook_utils.getContext().apiUrl() api_url = api_url_option.get() if api_url_option.isDefined() else None # Invoking getNonUcApiToken() will attempt to find the current credentials related # to the current command execution and refresh it if its expired automatically, # so it's critical that we execute it on every get_config(). api_token = None try: api_token = entry_point.getNonUcApiToken() except Exception: # Using apiToken from command context would return back the token which is not # refreshed. fallback_api_token_option = notebook_utils.getContext().apiToken() logger.logUsage( "refreshableTokenNotFound", {"api_url": api_url}, None, ) if fallback_api_token_option.isDefined(): api_token = fallback_api_token_option.get() ssl_trust_all = entry_point.getDriverConf().workflowSslTrustAll() if api_token is None or api_url is None: return None return DatabricksConfig.from_token( host=api_url, token=api_token, insecure=ssl_trust_all ) elif dbr_major_minor_version >= (10, 3): class DynamicConfigProvider(DatabricksConfigProvider): def get_config(self): try: from dbruntime.databricks_repl_context import get_context ctx = get_context() if ctx and ctx.apiUrl and ctx.apiToken: return DatabricksConfig.from_token( host=ctx.apiUrl, token=ctx.apiToken, insecure=ctx.sslTrustAll ) except Exception as e: _logger.debug( "Unexpected internal error while constructing `DatabricksConfig` " f"from REPL context: {e}", ) # Invoking getContext() will attempt to find the credentials related to the # current command execution, so it's critical that we execute it on every # get_config(). api_token_option = notebook_utils.getContext().apiToken() api_url_option = notebook_utils.getContext().apiUrl() ssl_trust_all = entry_point.getDriverConf().workflowSslTrustAll() if not api_token_option.isDefined() or not api_url_option.isDefined(): return None return DatabricksConfig.from_token( host=api_url_option.get(), token=api_token_option.get(), insecure=ssl_trust_all ) else: class DynamicConfigProvider(DatabricksConfigProvider): def get_config(self): # Invoking getContext() will attempt to find the credentials related to the # current command execution, so it's critical that we execute it on every # get_config(). api_token_option = notebook_utils.getContext().apiToken() api_url_option = notebook_utils.getContext().apiUrl() ssl_trust_all = entry_point.getDriverConf().workflowSslTrustAll() if not api_token_option.isDefined() or not api_url_option.isDefined(): return None return DatabricksConfig.from_token( host=api_url_option.get(), token=api_token_option.get(), insecure=ssl_trust_all ) _dynamic_token_config_provider = DynamicConfigProvider() if is_in_databricks_runtime(): try: dbutils = _get_dbutils() _init_databricks_dynamic_token_config_provider(dbutils.entry_point) except _NoDbutilsError: # If there is no dbutils available, it means it is run in databricks driver local suite, # in this case, we don't need to initialize databricks token because # there is no backend mlflow service available. pass def get_databricks_nfs_temp_dir(): entry_point = _get_dbutils().entry_point if getpass.getuser().lower() == "root": return entry_point.getReplNFSTempDir() else: try: # If it is not ROOT user, it means the code is running in Safe-spark. # In this case, we should get temporary directory of current user. # and `getReplNFSTempDir` will be deprecated for this case. return entry_point.getUserNFSTempDir() except Exception: # fallback return entry_point.getReplNFSTempDir() def get_databricks_local_temp_dir(): entry_point = _get_dbutils().entry_point if getpass.getuser().lower() == "root": return entry_point.getReplLocalTempDir() else: try: # If it is not ROOT user, it means the code is running in Safe-spark. # In this case, we should get temporary directory of current user. # and `getReplLocalTempDir` will be deprecated for this case. return entry_point.getUserLocalTempDir() except Exception: # fallback return entry_point.getReplLocalTempDir() def stage_model_for_databricks_model_serving(model_name: str, model_version: str): response = http_request( host_creds=get_databricks_host_creds(), endpoint="/api/2.0/serving-endpoints:stageDeployment", method="POST", raise_on_status=False, json={ "model_name": model_name, "model_version": model_version, }, ) augmented_raise_for_status(response) P = ParamSpec("P") T = TypeVar("T") def databricks_api_disabled(api_name: str = "This API", alternative: str | None = None): """ Decorator that disables an API method when used with Databricks. This decorator checks if the tracking URI is a Databricks URI and raises an error if so. Args: api_name: Name of the API for the error message. alternative: Optional alternative solution to suggest in the error message. Returns: Decorator function that wraps the method to check for Databricks. """ def decorator(func: Callable[P, T]) -> Callable[P, T]: @functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: from mlflow.tracking import get_tracking_uri from mlflow.utils.uri import is_databricks_uri tracking_uri = get_tracking_uri() if not is_databricks_uri(tracking_uri): return func(*args, **kwargs) error_msg = f"{api_name} is not supported in Databricks environments." if alternative: error_msg += f" {alternative}" raise MlflowException( error_msg, error_code=INVALID_PARAMETER_VALUE, ) return wrapper return decorator
DatabricksRuntimeVersion
python
optuna__optuna
optuna/samplers/nsgaii/_crossovers/_spx.py
{ "start": 295, "end": 2191 }
class ____(BaseCrossover): """Simplex Crossover operation used by :class:`~optuna.samplers.NSGAIISampler`. Uniformly samples child individuals from within a single simplex that is similar to the simplex produced by the parent individual. For further information about SPX crossover, please refer to the following paper: - `Shigeyoshi Tsutsui and Shigeyoshi Tsutsui and David E. Goldberg and David E. Goldberg and Kumara Sastry and Kumara Sastry Progress Toward Linkage Learning in Real-Coded GAs with Simplex Crossover. IlliGAL Report. 2000. <https://www.researchgate.net/publication/2388486_Progress_Toward_Linkage_Learning_in_Real-Coded_GAs_with_Simplex_Crossover>`__ Args: epsilon: Expansion rate. If not specified, defaults to ``sqrt(len(search_space) + 2)``. """ n_parents = 3 def __init__(self, epsilon: float | None = None) -> None: self._epsilon = epsilon def crossover( self, parents_params: np.ndarray, rng: np.random.RandomState, study: Study, search_space_bounds: np.ndarray, ) -> np.ndarray: # https://www.researchgate.net/publication/2388486_Progress_Toward_Linkage_Learning_in_Real-Coded_GAs_with_Simplex_Crossover # Section 2 A Brief Review of SPX n = self.n_parents - 1 G = np.mean(parents_params, axis=0) # Equation (1). rs = np.power(rng.rand(n), 1 / (np.arange(n) + 1)) # Equation (2). epsilon = np.sqrt(len(search_space_bounds) + 2) if self._epsilon is None else self._epsilon xks = [G + epsilon * (pk - G) for pk in parents_params] # Equation (3). ck = 0 # Equation (4). for k in range(1, self.n_parents): ck = rs[k - 1] * (xks[k - 1] - xks[k] + ck) child_params = xks[-1] + ck # Equation (5). return child_params
SPXCrossover
python
google__jax
jax/_src/linear_util.py
{ "start": 4082, "end": 4582 }
class ____: __slots__ = ('_store',) def __init__(self): self._store = Store() @property def val(self): return self._store.val def store(self, val): try: self._store.store(val) except StoreException as e: try: okay = bool(self._store._val == val) except: raise e from None else: if not okay: raise StoreException("Store occupied with not-equal value") from None def reset(self): self._store.reset()
EqualStore
python
celery__celery
t/unit/worker/test_strategy.py
{ "start": 521, "end": 1807 }
class ____: def setup_method(self): self.message = Mock(name='message') self.body = { 'args': (1,), 'kwargs': {'foo': 'baz'}, 'utc': False, 'taskset': '123', } def test_message_without_args(self): self.body.pop('args') body, _, _, _ = proto1_to_proto2(self.message, self.body) assert body[:2] == ((), {'foo': 'baz'}) def test_message_without_kwargs(self): self.body.pop('kwargs') body, _, _, _ = proto1_to_proto2(self.message, self.body) assert body[:2] == ((1,), {}) def test_message_kwargs_not_mapping(self): self.body['kwargs'] = (2,) with pytest.raises(InvalidTaskError): proto1_to_proto2(self.message, self.body) def test_message_no_taskset_id(self): self.body.pop('taskset') assert proto1_to_proto2(self.message, self.body) def test_message(self): body, headers, decoded, utc = proto1_to_proto2(self.message, self.body) assert body == ((1,), {'foo': 'baz'}, { 'callbacks': None, 'errbacks': None, 'chord': None, 'chain': None, }) assert headers == dict(self.body, group='123') assert decoded assert not utc
test_proto1_to_proto2
python
sphinx-doc__sphinx
sphinx/ext/napoleon/docstring.py
{ "start": 7301, "end": 39447 }
class ____: """Convert Google style docstrings to reStructuredText. Parameters ---------- docstring : :obj:`str` or :obj:`list` of :obj:`str` The docstring to parse, given either as a string or split into individual lines. config: :obj:`sphinx.ext.napoleon.Config` or :obj:`sphinx.config.Config` The configuration settings to use. If not given, defaults to the config object on `app`; or if `app` is not given defaults to the a new :class:`sphinx.ext.napoleon.Config` object. Other Parameters ---------------- app : :class:`sphinx.application.Sphinx`, optional Application object representing the Sphinx process. what : :obj:`str`, optional A string specifying the type of the object to which the docstring belongs. Valid values: "module", "class", "exception", "function", "method", "attribute". name : :obj:`str`, optional The fully qualified name of the object. obj : module, class, exception, function, method, or attribute The object to which the docstring belongs. options : :class:`sphinx.ext.autodoc.Options`, optional The options given to the directive: an object with attributes inherited_members, undoc_members, show_inheritance and no_index that are True if the flag option of same name was given to the auto directive. Example ------- >>> from sphinx.ext.napoleon import Config >>> config = Config(napoleon_use_param=True, napoleon_use_rtype=True) >>> docstring = '''One line summary. ... ... Extended description. ... ... Args: ... arg1(int): Description of `arg1` ... arg2(str): Description of `arg2` ... Returns: ... str: Description of return value. ... ''' >>> print(GoogleDocstring(docstring, config)) One line summary. <BLANKLINE> Extended description. <BLANKLINE> :param arg1: Description of `arg1` :type arg1: int :param arg2: Description of `arg2` :type arg2: str <BLANKLINE> :returns: Description of return value. :rtype: str <BLANKLINE> """ _name_rgx = re.compile( r'^\s*((?::(?P<role>\S+):)?`(?P<name>~?[a-zA-Z0-9_.-]+)`|' r' (?P<name2>~?[a-zA-Z0-9_.-]+))\s*', re.VERBOSE, ) def __init__( self, docstring: str | list[str], config: SphinxConfig | None = None, app: Sphinx | None = None, what: str = '', name: str = '', obj: Any = None, options: Any = None, ) -> None: self._app = app if config: self._config = config elif app: self._config = app.config else: from sphinx.ext.napoleon import Config self._config = Config() # type: ignore[assignment] if not what: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif callable(obj): what = 'function' else: what = 'object' self._what = what self._name = name self._obj = obj self._opt = options if isinstance(docstring, str): lines = docstring.splitlines() else: lines = docstring self._lines = Deque(map(str.rstrip, lines)) self._parsed_lines: list[str] = [] self._is_in_section = False self._section_indent = 0 if not hasattr(self, '_directive_sections'): self._directive_sections: list[str] = [] if not hasattr(self, '_sections'): self._sections: dict[str, Callable[..., list[str]]] = { 'args': self._parse_parameters_section, 'arguments': self._parse_parameters_section, 'attention': partial(self._parse_admonition, 'attention'), 'attributes': self._parse_attributes_section, 'caution': partial(self._parse_admonition, 'caution'), 'danger': partial(self._parse_admonition, 'danger'), 'error': partial(self._parse_admonition, 'error'), 'example': self._parse_examples_section, 'examples': self._parse_examples_section, 'hint': partial(self._parse_admonition, 'hint'), 'important': partial(self._parse_admonition, 'important'), 'keyword args': self._parse_keyword_arguments_section, 'keyword arguments': self._parse_keyword_arguments_section, 'methods': self._parse_methods_section, 'note': partial(self._parse_admonition, 'note'), 'notes': self._parse_notes_section, 'other parameters': self._parse_other_parameters_section, 'parameters': self._parse_parameters_section, 'receive': self._parse_receives_section, 'receives': self._parse_receives_section, 'return': self._parse_returns_section, 'returns': self._parse_returns_section, 'raise': self._parse_raises_section, 'raises': self._parse_raises_section, 'references': self._parse_references_section, 'see also': self._parse_see_also_section, 'tip': partial(self._parse_admonition, 'tip'), 'todo': partial(self._parse_admonition, 'todo'), 'warning': partial(self._parse_admonition, 'warning'), 'warnings': partial(self._parse_admonition, 'warning'), 'warn': self._parse_warns_section, 'warns': self._parse_warns_section, 'yield': self._parse_yields_section, 'yields': self._parse_yields_section, } self._load_custom_sections() self._parse() def __str__(self) -> str: """Return the parsed docstring in reStructuredText format. Returns ------- unicode Unicode version of the docstring. """ return '\n'.join(self.lines()) def _get_location(self) -> str | None: try: filepath = inspect.getfile(self._obj) if self._obj is not None else None except TypeError: filepath = None name = self._name if filepath is None and name is None: return None elif filepath is None: filepath = '' return f'{filepath}:docstring of {name}' def lines(self) -> list[str]: """Return the parsed lines of the docstring in reStructuredText format. Returns ------- list(str) The lines of the docstring in a list. """ return self._parsed_lines def _consume_indented_block(self, indent: int = 1) -> list[str]: lines = [] line = self._lines.get(0) while not self._is_section_break() and ( not line or self._is_indented(line, indent) ): lines.append(self._lines.next()) line = self._lines.get(0) return lines def _consume_contiguous(self) -> list[str]: lines = [] while self._lines and self._lines.get(0) and not self._is_section_header(): lines.append(self._lines.next()) return lines def _consume_empty(self) -> list[str]: lines = [] line = self._lines.get(0) while self._lines and not line: lines.append(self._lines.next()) line = self._lines.get(0) return lines def _consume_field( self, parse_type: bool = True, prefer_type: bool = False, ) -> tuple[str, str, list[str]]: line = self._lines.next() before, _colon, after = self._partition_field_on_colon(line) _name, _type, _desc = before, '', after if parse_type: match = _google_typed_arg_regex.match(before) if match: _name = match.group(1).strip() _type = match.group(2) _name = self._escape_args_and_kwargs(_name) if prefer_type and not _type: _type, _name = _name, _type if _type and self._config.napoleon_preprocess_types: _type = _convert_type_spec( _type, translations=self._config.napoleon_type_aliases or {}, debug_location=self._get_location(), ) indent = self._get_indent(line) + 1 _descs = [_desc, *self._dedent(self._consume_indented_block(indent))] _descs = self.__class__(_descs, self._config).lines() return _name, _type, _descs def _consume_fields( self, parse_type: bool = True, prefer_type: bool = False, multiple: bool = False ) -> list[tuple[str, str, list[str]]]: self._consume_empty() fields: list[tuple[str, str, list[str]]] = [] while not self._is_section_break(): _name, _type, _desc = self._consume_field(parse_type, prefer_type) if multiple and _name: fields.extend((name.strip(), _type, _desc) for name in _name.split(',')) elif _name or _type or _desc: fields.append((_name, _type, _desc)) return fields def _consume_inline_attribute(self) -> tuple[str, list[str]]: line = self._lines.next() _type, colon, _desc = self._partition_field_on_colon(line) if not colon or not _desc: _type, _desc = _desc, _type _desc += colon _descs = [_desc, *self._dedent(self._consume_to_end())] _descs = self.__class__(_descs, self._config).lines() return _type, _descs def _consume_returns_section( self, preprocess_types: bool = False ) -> list[tuple[str, str, list[str]]]: lines = self._dedent(self._consume_to_next_section()) if lines: before, colon, after = self._partition_field_on_colon(lines[0]) _name, _type, _desc = '', '', lines if colon: if after: _desc = [after, *lines[1:]] else: _desc = lines[1:] _type = before if _type and preprocess_types and self._config.napoleon_preprocess_types: _type = _convert_type_spec( _type, translations=self._config.napoleon_type_aliases or {}, debug_location=self._get_location(), ) _desc = self.__class__(_desc, self._config).lines() return [(_name, _type, _desc)] else: return [] def _consume_usage_section(self) -> list[str]: lines = self._dedent(self._consume_to_next_section()) return lines def _consume_section_header(self) -> str: section = self._lines.next() stripped_section = section.strip(':') if stripped_section.lower() in self._sections: section = stripped_section return section def _consume_to_end(self) -> list[str]: lines = [] while self._lines: lines.append(self._lines.next()) return lines def _consume_to_next_section(self) -> list[str]: self._consume_empty() lines = [] while not self._is_section_break(): lines.append(self._lines.next()) return lines + self._consume_empty() def _dedent(self, lines: list[str], full: bool = False) -> list[str]: if full: return [line.lstrip() for line in lines] else: min_indent = self._get_min_indent(lines) return [line[min_indent:] for line in lines] def _escape_args_and_kwargs(self, name: str) -> str: if name.endswith('_') and getattr( self._config, 'strip_signature_backslash', False ): name = name[:-1] + r'\_' if name[:2] == '**': return r'\*\*' + name[2:] elif name[:1] == '*': return r'\*' + name[1:] else: return name def _fix_field_desc(self, desc: list[str]) -> list[str]: if self._is_list(desc): desc = ['', *desc] elif desc[0].endswith('::'): desc_block = desc[1:] indent = self._get_indent(desc[0]) block_indent = self._get_initial_indent(desc_block) if block_indent > indent: desc = ['', *desc] else: desc = ['', desc[0], *self._indent(desc_block, 4)] return desc def _format_admonition(self, admonition: str, lines: list[str]) -> list[str]: lines = self._strip_empty(lines) if len(lines) == 1: return [f'.. {admonition}:: {lines[0].strip()}', ''] elif lines: lines = self._indent(self._dedent(lines), 3) return [f'.. {admonition}::', '', *lines, ''] else: return [f'.. {admonition}::', ''] def _format_block( self, prefix: str, lines: list[str], padding: str | None = None, ) -> list[str]: if lines: if padding is None: padding = ' ' * len(prefix) result_lines = [] for i, line in enumerate(lines): if i == 0: result_lines.append((prefix + line).rstrip()) elif line: result_lines.append(padding + line) else: result_lines.append('') return result_lines else: return [prefix] def _format_docutils_params( self, fields: list[tuple[str, str, list[str]]], field_role: str = 'param', type_role: str = 'type', ) -> list[str]: lines = [] for _name, _type, _desc in fields: _desc = self._strip_empty(_desc) if any(_desc): _desc = self._fix_field_desc(_desc) field = f':{field_role} {_name}: ' lines.extend(self._format_block(field, _desc)) else: lines.append(f':{field_role} {_name}:') if _type: lines.append(f':{type_role} {_name}: {_type}') return [*lines, ''] def _format_field(self, _name: str, _type: str, _desc: list[str]) -> list[str]: _desc = self._strip_empty(_desc) has_desc = any(_desc) separator = ' -- ' if has_desc else '' if _name: if _type: if '`' in _type: field = f'**{_name}** ({_type}){separator}' else: field = f'**{_name}** (*{_type}*){separator}' else: field = f'**{_name}**{separator}' elif _type: if '`' in _type: field = f'{_type}{separator}' else: field = f'*{_type}*{separator}' else: field = '' if has_desc: _desc = self._fix_field_desc(_desc) if _desc[0]: return [field + _desc[0], *_desc[1:]] else: return [field, *_desc] else: return [field] def _format_fields( self, field_type: str, fields: list[tuple[str, str, list[str]]], ) -> list[str]: field_type = f':{field_type.strip()}:' padding = ' ' * len(field_type) multi = len(fields) > 1 lines: list[str] = [] for _name, _type, _desc in fields: field = self._format_field(_name, _type, _desc) if multi: if lines: lines.extend(self._format_block(padding + ' * ', field)) else: lines.extend(self._format_block(field_type + ' * ', field)) else: lines.extend(self._format_block(field_type + ' ', field)) if lines and lines[-1]: lines.append('') return lines def _get_current_indent(self, peek_ahead: int = 0) -> int: line = self._lines.get(peek_ahead) while line is not self._lines.sentinel: if line: return self._get_indent(line) peek_ahead += 1 line = self._lines.get(peek_ahead) return 0 def _get_indent(self, line: str) -> int: for i, s in enumerate(line): if not s.isspace(): return i return len(line) def _get_initial_indent(self, lines: list[str]) -> int: for line in lines: if line: return self._get_indent(line) return 0 def _get_min_indent(self, lines: list[str]) -> int: min_indent = None for line in lines: if line: indent = self._get_indent(line) if min_indent is None or indent < min_indent: min_indent = indent return min_indent or 0 def _indent(self, lines: list[str], n: int = 4) -> list[str]: return [(' ' * n) + line for line in lines] def _is_indented(self, line: str, indent: int = 1) -> bool: for i, s in enumerate(line): if i >= indent: return True elif not s.isspace(): return False return False def _is_list(self, lines: list[str]) -> bool: if not lines: return False if _bullet_list_regex.match(lines[0]): return True if _enumerated_list_regex.match(lines[0]): return True if len(lines) < 2 or lines[0].endswith('::'): return False indent = self._get_indent(lines[0]) next_indent = indent for line in lines[1:]: if line: next_indent = self._get_indent(line) break return next_indent > indent def _is_section_header(self) -> bool: section = self._lines.get(0).lower() match = _google_section_regex.match(section) if match and section.strip(':') in self._sections: header_indent = self._get_indent(section) section_indent = self._get_current_indent(peek_ahead=1) return section_indent > header_indent elif self._directive_sections: if _directive_regex.match(section): for directive_section in self._directive_sections: if section.startswith(directive_section): return True return False def _is_section_break(self) -> bool: line = self._lines.get(0) return ( not self._lines or self._is_section_header() or ( self._is_in_section and line and not self._is_indented(line, self._section_indent) ) ) def _load_custom_sections(self) -> None: if self._config.napoleon_custom_sections is not None: for entry in self._config.napoleon_custom_sections: if isinstance(entry, str): # if entry is just a label, add to sections list, # using generic section logic. self._sections[entry.lower()] = self._parse_custom_generic_section else: # otherwise, assume entry is container; if entry[1] == 'params_style': self._sections[entry[0].lower()] = ( self._parse_custom_params_style_section ) elif entry[1] == 'returns_style': self._sections[entry[0].lower()] = ( self._parse_custom_returns_style_section ) else: # [0] is new section, [1] is the section to alias. # in the case of key mismatch, just handle as generic section. self._sections[entry[0].lower()] = self._sections.get( entry[1].lower(), self._parse_custom_generic_section ) def _parse(self) -> None: self._parsed_lines = self._consume_empty() if self._name and self._what in {'attribute', 'data', 'property'}: res: list[str] = [] with contextlib.suppress(StopIteration): res = self._parse_attribute_docstring() self._parsed_lines.extend(res) return while self._lines: if self._is_section_header(): try: section = self._consume_section_header() self._is_in_section = True self._section_indent = self._get_current_indent() if _directive_regex.match(section): lines = [section, *self._consume_to_next_section()] else: lines = self._sections[section.lower()](section) finally: self._is_in_section = False self._section_indent = 0 else: if not self._parsed_lines: lines = self._consume_contiguous() + self._consume_empty() else: lines = self._consume_to_next_section() self._parsed_lines.extend(lines) def _parse_admonition(self, admonition: str, section: str) -> list[str]: # type (str, str) -> List[str] lines = self._consume_to_next_section() return self._format_admonition(admonition, lines) def _parse_attribute_docstring(self) -> list[str]: _type, _desc = self._consume_inline_attribute() lines = self._format_field('', '', _desc) if _type: lines.extend(['', f':type: {_type}']) return lines def _parse_attributes_section(self, section: str) -> list[str]: lines = [] for _name, _type, _desc in self._consume_fields(): if not _type: _type = self._lookup_annotation(_name) if self._config.napoleon_use_ivar: field = f':ivar {_name}: ' lines.extend(self._format_block(field, _desc)) if _type: lines.append(f':vartype {_name}: {_type}') else: lines.append('.. attribute:: ' + _name) if self._opt: if 'no-index' in self._opt or 'noindex' in self._opt: lines.append(' :no-index:') lines.append('') fields = self._format_field('', '', _desc) lines.extend(self._indent(fields, 3)) if _type: lines.append('') lines.extend(self._indent([f':type: {_type}'], 3)) lines.append('') if self._config.napoleon_use_ivar: lines.append('') return lines def _parse_examples_section(self, section: str) -> list[str]: labels = { 'example': _('Example'), 'examples': _('Examples'), } use_admonition = self._config.napoleon_use_admonition_for_examples label = labels.get(section.lower(), section) return self._parse_generic_section(label, use_admonition) def _parse_custom_generic_section(self, section: str) -> list[str]: # for now, no admonition for simple custom sections return self._parse_generic_section(section, False) def _parse_custom_params_style_section(self, section: str) -> list[str]: return self._format_fields(section, self._consume_fields()) def _parse_custom_returns_style_section(self, section: str) -> list[str]: fields = self._consume_returns_section(preprocess_types=True) return self._format_fields(section, fields) def _parse_usage_section(self, section: str) -> list[str]: header = ['.. rubric:: Usage:', ''] block = ['.. code-block:: python', ''] lines = self._consume_usage_section() lines = self._indent(lines, 3) return header + block + lines + [''] def _parse_generic_section(self, section: str, use_admonition: bool) -> list[str]: lines = self._strip_empty(self._consume_to_next_section()) lines = self._dedent(lines) if use_admonition: header = f'.. admonition:: {section}' lines = self._indent(lines, 3) else: header = f'.. rubric:: {section}' if lines: return [header, '', *lines, ''] else: return [header, ''] def _parse_keyword_arguments_section(self, section: str) -> list[str]: fields = self._consume_fields() if self._config.napoleon_use_keyword: return self._format_docutils_params( fields, field_role='keyword', type_role='kwtype' ) else: return self._format_fields(_('Keyword Arguments'), fields) def _parse_methods_section(self, section: str) -> list[str]: lines: list[str] = [] for _name, _type, _desc in self._consume_fields(parse_type=False): lines.append(f'.. method:: {_name}') if self._opt: if 'no-index' in self._opt or 'noindex' in self._opt: lines.append(' :no-index:') if _desc: lines.extend(['', *self._indent(_desc, 3)]) lines.append('') return lines def _parse_notes_section(self, section: str) -> list[str]: use_admonition = self._config.napoleon_use_admonition_for_notes return self._parse_generic_section(_('Notes'), use_admonition) def _parse_other_parameters_section(self, section: str) -> list[str]: if self._config.napoleon_use_param: # Allow to declare multiple parameters at once (ex: x, y: int) fields = self._consume_fields(multiple=True) return self._format_docutils_params(fields) else: fields = self._consume_fields() return self._format_fields(_('Other Parameters'), fields) def _parse_parameters_section(self, section: str) -> list[str]: if self._config.napoleon_use_param: # Allow to declare multiple parameters at once (ex: x, y: int) fields = self._consume_fields(multiple=True) return self._format_docutils_params(fields) else: fields = self._consume_fields() return self._format_fields(_('Parameters'), fields) def _parse_raises_section(self, section: str) -> list[str]: fields = self._consume_fields(parse_type=False, prefer_type=True) lines: list[str] = [] for _name, _type, _desc in fields: m = self._name_rgx.match(_type) if m and m.group('name'): _type = m.group('name') elif _xref_regex.match(_type): pos = _type.find('`') _type = _type[pos + 1 : -1] _type = ' ' + _type if _type else '' _desc = self._strip_empty(_desc) _descs = ' ' + '\n '.join(_desc) if any(_desc) else '' lines.append(f':raises{_type}:{_descs}') if lines: lines.append('') return lines def _parse_receives_section(self, section: str) -> list[str]: if self._config.napoleon_use_param: # Allow to declare multiple parameters at once (ex: x, y: int) fields = self._consume_fields(multiple=True) return self._format_docutils_params(fields) else: fields = self._consume_fields() return self._format_fields(_('Receives'), fields) def _parse_references_section(self, section: str) -> list[str]: use_admonition = self._config.napoleon_use_admonition_for_references return self._parse_generic_section(_('References'), use_admonition) def _parse_returns_section(self, section: str) -> list[str]: fields = self._consume_returns_section() multi = len(fields) > 1 use_rtype = False if multi else self._config.napoleon_use_rtype lines: list[str] = [] for _name, _type, _desc in fields: if use_rtype: field = self._format_field(_name, '', _desc) else: field = self._format_field(_name, _type, _desc) if multi: if lines: lines.extend(self._format_block(' * ', field)) else: lines.extend(self._format_block(':returns: * ', field)) else: if any(field): # only add :returns: if there's something to say lines.extend(self._format_block(':returns: ', field)) if _type and use_rtype: lines.extend([f':rtype: {_type}', '']) if lines and lines[-1]: lines.append('') return lines def _parse_see_also_section(self, section: str) -> list[str]: return self._parse_admonition('seealso', section) def _parse_warns_section(self, section: str) -> list[str]: return self._format_fields(_('Warns'), self._consume_fields()) def _parse_yields_section(self, section: str) -> list[str]: fields = self._consume_returns_section(preprocess_types=True) return self._format_fields(_('Yields'), fields) def _partition_field_on_colon(self, line: str) -> tuple[str, str, str]: before_colon = [] after_colon = [] colon = '' found_colon = False for i, source in enumerate(_xref_or_code_regex.split(line)): if found_colon: after_colon.append(source) else: m = _single_colon_regex.search(source) if (i % 2) == 0 and m: found_colon = True colon = source[m.start() : m.end()] before_colon.append(source[: m.start()]) after_colon.append(source[m.end() :]) else: before_colon.append(source) return ''.join(before_colon).strip(), colon, ''.join(after_colon).strip() def _strip_empty(self, lines: list[str]) -> list[str]: if lines: start = -1 for i, line in enumerate(lines): if line: start = i break if start == -1: lines = [] end = -1 for i in reversed(range(len(lines))): line = lines[i] if line: end = i break if start > 0 or end + 1 < len(lines): lines = lines[start : end + 1] return lines def _lookup_annotation(self, _name: str) -> str: if self._config.napoleon_attr_annotations: if self._what in {'module', 'class', 'exception'} and self._obj: # cache the class annotations if not hasattr(self, '_annotations'): localns = getattr(self._config, 'autodoc_type_aliases', {}) localns.update( getattr( self._config, 'napoleon_type_aliases', {}, ) or {} ) self._annotations = get_type_hints(self._obj, None, localns) if _name in self._annotations: short_literals = getattr( self._config, 'python_display_short_literal_types', False ) return stringify_annotation( self._annotations[_name], mode='fully-qualified-except-typing', short_literals=short_literals, ) # No annotation found return ''
GoogleDocstring
python
allegroai__clearml
clearml/utilities/process/mp.py
{ "start": 16901, "end": 31945 }
class ____(object): # If we need multiple monitoring contexts (i.e. subprocesses) this will become a dict _main_process = None _main_process_proc_obj = None _main_process_task_id = None _parent_pid = None _sub_process_started = None _at_exit = False _instances: Dict[int, List["BackgroundMonitor"]] = {} def __init__(self, task: Any, wait_period: float, for_model: bool = False) -> None: self._event = ForkEvent() self._done_ev = ForkEvent() self._start_ev = ForkEvent() self._task_pid = os.getpid() self._thread = None self._thread_pid = None self._wait_timeout = wait_period self._subprocess = None if not for_model and task.is_main_task() else False self._task_id = task.id self._task_obj_id = id(task.id) def start(self) -> None: if not self._thread: self._thread = True self._event.clear() self._done_ev.clear() if self._subprocess is False: # start the thread we are in threading mode. self._start() else: # append to instances if self not in self._get_instances(): self._get_instances().append(self) def wait(self, timeout: Optional[float] = None) -> None: if not self._done_ev: return if not self.is_subprocess_mode() or self.is_subprocess_mode_and_parent_process(): self._done_ev.wait(timeout=timeout) def _start(self) -> None: # if we already started do nothing if isinstance(self._thread, Thread): if self._thread_pid == os.getpid(): return # make sure we start the metrics thread pools before starting the daemon thread # workaround for: https://github.com/python/cpython/issues/113964 from ...backend_interface.metrics.interface import Metrics # noinspection PyProtectedMember Metrics._initialize_upload_pools() self._thread_pid = os.getpid() self._thread = Thread(target=self._daemon) self._thread.daemon = True self._thread.start() def stop(self) -> None: if not self._thread: return if not self._is_subprocess_mode_and_not_parent_process() and ( not self.is_subprocess_mode() or self.is_subprocess_alive() ): self._event.set() if isinstance(self._thread, Thread): # should we wait for the thread to finish # noinspection PyBroadException try: # there is a race here, and if someone else closes the # thread it can become True/None and we will fail, it is fine self._thread.join() except BaseException: pass try: self._get_instances().remove(self) except ValueError: pass self._thread = False def daemon(self) -> None: while True: if self._event.wait(self._wait_timeout): break self._daemon_step() def _daemon(self) -> None: self._start_ev.set() try: self.daemon() finally: self.post_execution() self._thread = False def post_execution(self) -> None: self._done_ev.set() def set_subprocess_mode(self) -> None: # called just before launching the daemon in a subprocess if not self._subprocess: self._subprocess = True if not isinstance(self._done_ev, SafeEvent): self._done_ev = SafeEvent() if not isinstance(self._start_ev, SafeEvent): self._start_ev = SafeEvent() if not isinstance(self._event, SafeEvent): self._event = SafeEvent() def _daemon_step(self) -> None: pass @classmethod def start_all(cls, task: Any, wait_for_subprocess: bool = True) -> None: # noinspection PyProtectedMember execute_in_subprocess = task._report_subprocess_enabled if not execute_in_subprocess: for d in BackgroundMonitor._instances.get(id(task.id), []): d._start() elif not BackgroundMonitor._main_process: cls._parent_pid = os.getpid() cls._sub_process_started = SafeEvent() cls._sub_process_started.clear() cls._main_process_task_id = task.id # setup for d in BackgroundMonitor._instances.get(id(task.id), []): d.set_subprocess_mode() # ToDo: solve for standalone spawn subprocess # prefer os.fork, because multipprocessing.Process add atexit callback, which might later be invalid. cls.__start_subprocess_os_fork(task_obj_id=id(task.id)) # if ForkContext is not None and isinstance(get_context(), ForkContext): # cls.__start_subprocess_forkprocess(task_obj_id=id(task.id)) # else: # cls.__start_subprocess_os_fork(task_obj_id=id(task.id)) # wait until subprocess is up if wait_for_subprocess: cls._sub_process_started.wait() @classmethod def __start_subprocess_os_fork(cls, task_obj_id: int) -> None: process_args = (task_obj_id, cls._sub_process_started, os.getpid()) BackgroundMonitor._main_process = os.fork() # check if we are the child process if BackgroundMonitor._main_process == 0: # update to the child process pid BackgroundMonitor._main_process = os.getpid() BackgroundMonitor._main_process_proc_obj = psutil.Process(BackgroundMonitor._main_process) cls._background_process_start(*process_args) # force to leave the subprocess leave_process(0) return # update main process object (we are now in the parent process, and we update on the child's subprocess pid) # noinspection PyBroadException try: BackgroundMonitor._main_process_proc_obj = psutil.Process(BackgroundMonitor._main_process) except Exception: # if we fail for some reason, do not crash, switch to thread mode when you can BackgroundMonitor._main_process_proc_obj = None @classmethod def __start_subprocess_forkprocess(cls, task_obj_id: int) -> None: _main_process = Process( target=cls._background_process_start, args=(task_obj_id, cls._sub_process_started, os.getpid()), ) _main_process.daemon = True # Hack allow to create daemon subprocesses (even though python doesn't like it) un_daemonize = False # noinspection PyBroadException try: from multiprocessing import current_process if current_process()._config.get("daemon"): # noqa un_daemonize = current_process()._config.get("daemon") # noqa current_process()._config["daemon"] = False # noqa except BaseException: pass # try to start the background process, if we fail retry again, or crash for i in range(4): try: _main_process.start() break except BaseException: if i < 3: sleep(1) continue raise BackgroundMonitor._main_process = _main_process.pid BackgroundMonitor._main_process_proc_obj = psutil.Process(BackgroundMonitor._main_process) if un_daemonize: # noinspection PyBroadException try: from multiprocessing import current_process current_process()._config["daemon"] = un_daemonize # noqa except BaseException: pass @classmethod def _background_process_start( cls, task_obj_id: int, event_start: Optional[SafeEvent] = None, parent_pid: Optional[int] = None, ) -> None: # noinspection PyProtectedMember is_debugger_running = bool(getattr(sys, "gettrace", None) and sys.gettrace()) # make sure we update the pid to our own cls._main_process = os.getpid() cls._main_process_proc_obj = psutil.Process(cls._main_process) # noinspection PyBroadException try: from ... import Task if Task._Task__current_task and Task._Task__current_task._Task__exit_hook: # noqa Task._Task__current_task._Task__exit_hook.register_signal_and_exception_hooks() # noqa # noinspection PyProtectedMember from ...binding.environ_bind import PatchOsFork PatchOsFork.unpatch_fork() PatchOsFork.unpatch_process_run() except: # noqa # Do not change the exception we need to catch base exception as well pass # if a debugger is running, wait for it to attach to the subprocess if is_debugger_running: sleep(3) instances = BackgroundMonitor._instances.get(task_obj_id, []) # launch all the threads for d in instances: d._start() if cls._sub_process_started: cls._sub_process_started.set() if event_start: event_start.set() # wait until we are signaled for i in instances: # DO NOT CHANGE, we need to catch base exception, if the process gte's killed try: while i._thread is None or (i._thread and i._thread.is_alive()): # thread is still not up if i._thread is None: sleep(0.1) continue # noinspection PyBroadException try: p = psutil.Process(parent_pid) parent_alive = p.is_running() and p.status() != psutil.STATUS_ZOMBIE except Exception: parent_alive = False # if parent process is not here we should just leave! if not parent_alive: return # DO NOT CHANGE, we need to catch base exception, if the process gte's killed try: # timeout so we can detect if the parent process got killed. i._thread.join(timeout=30.0) except: # noqa break except: # noqa pass # we are done, leave process return def is_alive(self) -> bool: if not self.is_subprocess_mode(): return isinstance(self._thread, Thread) and self._thread.is_alive() if self.get_at_exit_state(): return self.is_subprocess_alive() and self._thread return self.is_subprocess_alive() and self._thread and self._start_ev.is_set() and not self._done_ev.is_set() @classmethod def _fast_is_subprocess_alive(cls) -> bool: if not cls._main_process_proc_obj: return False # we have to assume the process actually exists, so we optimize for # just getting the object and status. # noinspection PyBroadException try: return ( cls._main_process_proc_obj.is_running() and cls._main_process_proc_obj.status() != psutil.STATUS_ZOMBIE ) except Exception: return False @classmethod def is_subprocess_alive(cls, task: Optional["Task"] = None) -> bool: if not cls._main_process or (task and cls._main_process_task_id != task.id): return False # noinspection PyBroadException try: p = psutil.Process(cls._main_process) return p.is_running() and p.status() != psutil.STATUS_ZOMBIE except Exception: current_pid = cls._main_process if not current_pid: return False try: parent = psutil.Process(cls._parent_pid) except psutil.Error: # could not find parent process id return for child in parent.children(recursive=True): # kill ourselves last (if we need to) if child.pid == current_pid: return child.is_running() and child.status() != psutil.STATUS_ZOMBIE return False def is_subprocess_mode(self) -> bool: return ( self._subprocess is not False and bool(self._main_process) and self._task_id == self._main_process_task_id ) def _get_instances(self) -> List["BackgroundMonitor"]: return self._instances.setdefault(self._task_obj_id, []) def _is_subprocess_mode_and_not_parent_process(self) -> bool: return self.is_subprocess_mode() and self._parent_pid != os.getpid() def is_subprocess_mode_and_parent_process(self) -> bool: return self.is_subprocess_mode() and self._parent_pid == os.getpid() def _is_thread_mode_and_not_main_process(self) -> bool: if self.is_subprocess_mode(): return False from ... import Task # noinspection PyProtectedMember return Task._Task__is_subprocess() @classmethod def is_subprocess_enabled(cls, task: Optional["Task"] = None) -> bool: return bool(cls._main_process) and (not task or task.id == cls._main_process_task_id) @classmethod def clear_main_process(cls, task: "Task") -> None: if BackgroundMonitor._main_process_task_id != task.id: return cls.wait_for_sub_process(task) BackgroundMonitor._main_process = None BackgroundMonitor._main_process_proc_obj = None BackgroundMonitor._main_process_task_id = None BackgroundMonitor._parent_pid = None BackgroundMonitor._sub_process_started = None BackgroundMonitor._instances = {} SingletonThreadPool.clear() @classmethod def wait_for_sub_process(cls, task: Any, timeout: Optional[float] = None) -> None: if not cls.is_subprocess_enabled(task=task): return for d in BackgroundMonitor._instances.get(id(task.id), []): d.stop() tic = time() while cls.is_subprocess_alive(task=task) and (not timeout or time() - tic < timeout): sleep(0.03) @classmethod def set_at_exit_state(cls, state: bool = True) -> None: cls._at_exit = bool(state) @classmethod def get_at_exit_state(cls) -> bool: return cls._at_exit def leave_process(status: int = 0) -> None: """ Exit current process with status-code (status) :param status: int exit code """ try: sys.exit(status or 0) except: # noqa # ipython/jupyter notebook will not allow to call sys.exit # we have to call the low level function os._exit(status or 0) # noqa
BackgroundMonitor
python
scrapy__scrapy
tests/test_downloadermiddleware.py
{ "start": 1985, "end": 4354 }
class ____(TestManagerBase): """Tests default behavior with default settings""" @deferred_f_from_coro_f async def test_request_response(self): req = Request("http://example.com/index.html") resp = Response(req.url, status=200) async with self.get_mwman() as mwman: ret = await self._download(mwman, req, resp) assert isinstance(ret, Response), "Non-response returned" @deferred_f_from_coro_f async def test_3xx_and_invalid_gzipped_body_must_redirect(self): """Regression test for a failure when redirecting a compressed request. This happens when httpcompression middleware is executed before redirect middleware and attempts to decompress a non-compressed body. In particular when some website returns a 30x response with header 'Content-Encoding: gzip' giving as result the error below: BadGzipFile: Not a gzipped file (...) """ req = Request("http://example.com") body = b"<p>You are being redirected</p>" resp = Response( req.url, status=302, body=body, headers={ "Content-Length": str(len(body)), "Content-Type": "text/html", "Content-Encoding": "gzip", "Location": "http://example.com/login", }, ) async with self.get_mwman() as mwman: ret = await self._download(mwman, req, resp) assert isinstance(ret, Request), f"Not redirected: {ret!r}" assert to_bytes(ret.url) == resp.headers["Location"], ( "Not redirected to location header" ) @deferred_f_from_coro_f async def test_200_and_invalid_gzipped_body_must_fail(self): req = Request("http://example.com") body = b"<p>You are being redirected</p>" resp = Response( req.url, status=200, body=body, headers={ "Content-Length": str(len(body)), "Content-Type": "text/html", "Content-Encoding": "gzip", "Location": "http://example.com/login", }, ) with pytest.raises(BadGzipFile): async with self.get_mwman() as mwman: await self._download(mwman, req, resp)
TestDefaults
python
PyCQA__pylint
tests/functional/n/name/name_preset_snake_case.py
{ "start": 269, "end": 607 }
class ____: # [invalid-name] def __init__(self, arg_x): self._my_secret_x = arg_x @property def my_public_x(self): return self._my_secret_x * 2 def __eq__(self, other): return isinstance(other, MyClass) and self.my_public_x == other.my_public_x def sayHello(): # [invalid-name] pass
MyClass
python
gevent__gevent
src/gevent/tests/test__hub.py
{ "start": 3175, "end": 4018 }
class ____(greentest.TestCase): def test(self): waiter = Waiter() self.assertEqual(str(waiter), '<Waiter greenlet=None>') waiter.switch(25) self.assertEqual(str(waiter), '<Waiter greenlet=None value=25>') self.assertEqual(waiter.get(), 25) waiter = Waiter() waiter.throw(ZeroDivisionError) assert re.match('^<Waiter greenlet=None exc_info=.*ZeroDivisionError.*$', str(waiter)), str(waiter) self.assertRaises(ZeroDivisionError, waiter.get) waiter = Waiter() g = gevent.spawn(waiter.get) g.name = 'AName' gevent.sleep(0) str_waiter = str(waiter) self.assertTrue(str_waiter.startswith('<Waiter greenlet=<Greenlet "AName'), str_waiter) g.kill() @greentest.skipOnCI("Racy on CI")
TestWaiter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format10.py
{ "start": 315, "end": 1779 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format10.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "line"}) chart.axis_ids = [54795648, 56296960] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5", "trendline": { "type": "linear", "line": { "color": "red", "width": 1, "dash_type": "long_dash", }, }, } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
joblib__joblib
joblib/_memmapping_reducer.py
{ "start": 3809, "end": 12379 }
class ____: """A variant of weakref.WeakKeyDictionary for unhashable numpy arrays. This datastructure will be used with numpy arrays as obj keys, therefore we do not use the __get__ / __set__ methods to avoid any conflict with the numpy fancy indexing syntax. """ def __init__(self): self._data = {} def get(self, obj): ref, val = self._data[id(obj)] if ref() is not obj: # In case of race condition with on_destroy: could never be # triggered by the joblib tests with CPython. raise KeyError(obj) return val def set(self, obj, value): key = id(obj) try: ref, _ = self._data[key] if ref() is not obj: # In case of race condition with on_destroy: could never be # triggered by the joblib tests with CPython. raise KeyError(obj) except KeyError: # Insert the new entry in the mapping along with a weakref # callback to automatically delete the entry from the mapping # as soon as the object used as key is garbage collected. def on_destroy(_): del self._data[key] ref = weakref.ref(obj, on_destroy) self._data[key] = ref, value def __getstate__(self): raise PicklingError("_WeakArrayKeyMap is not pickleable") ############################################################################### # Support for efficient transient pickling of numpy data structures def _get_backing_memmap(a): """Recursively look up the original np.memmap instance base if any.""" b = getattr(a, "base", None) if b is None: # TODO: check scipy sparse datastructure if scipy is installed # a nor its descendants do not have a memmap base return None elif isinstance(b, mmap): # a is already a real memmap instance. return a else: # Recursive exploration of the base ancestry return _get_backing_memmap(b) def _get_temp_dir(pool_folder_name, temp_folder=None): """Get the full path to a subfolder inside the temporary folder. Parameters ---------- pool_folder_name : str Sub-folder name used for the serialization of a pool instance. temp_folder: str, optional Folder to be used by the pool for memmapping large arrays for sharing memory with worker processes. If None, this will try in order: - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable, - /dev/shm if the folder exists and is writable: this is a RAMdisk filesystem available by default on modern Linux distributions, - the default system temporary folder that can be overridden with TMP, TMPDIR or TEMP environment variables, typically /tmp under Unix operating systems. Returns ------- pool_folder : str full path to the temporary folder use_shared_mem : bool whether the temporary folder is written to the system shared memory folder or some other temporary folder. """ use_shared_mem = False if temp_folder is None: temp_folder = os.environ.get("JOBLIB_TEMP_FOLDER", None) if temp_folder is None: if os.path.exists(SYSTEM_SHARED_MEM_FS) and hasattr(os, "statvfs"): try: shm_stats = os.statvfs(SYSTEM_SHARED_MEM_FS) available_nbytes = shm_stats.f_bsize * shm_stats.f_bavail if available_nbytes > SYSTEM_SHARED_MEM_FS_MIN_SIZE: # Try to see if we have write access to the shared mem # folder only if it is reasonably large (that is 2GB or # more). temp_folder = SYSTEM_SHARED_MEM_FS pool_folder = os.path.join(temp_folder, pool_folder_name) if not os.path.exists(pool_folder): os.makedirs(pool_folder) use_shared_mem = True except (IOError, OSError): # Missing rights in the /dev/shm partition, fallback to regular # temp folder. temp_folder = None if temp_folder is None: # Fallback to the default tmp folder, typically /tmp temp_folder = tempfile.gettempdir() temp_folder = os.path.abspath(os.path.expanduser(temp_folder)) pool_folder = os.path.join(temp_folder, pool_folder_name) return pool_folder, use_shared_mem def has_shareable_memory(a): """Return True if a is backed by some mmap buffer directly or not.""" return _get_backing_memmap(a) is not None def _strided_from_memmap( filename, dtype, mode, offset, order, shape, strides, total_buffer_len, unlink_on_gc_collect, ): """Reconstruct an array view on a memory mapped file.""" if mode == "w+": # Do not zero the original data when unpickling mode = "r+" if strides is None: # Simple, contiguous memmap return make_memmap( filename, dtype=dtype, shape=shape, mode=mode, offset=offset, order=order, unlink_on_gc_collect=unlink_on_gc_collect, ) else: # For non-contiguous data, memmap the total enclosing buffer and then # extract the non-contiguous view with the stride-tricks API base = make_memmap( filename, dtype=dtype, shape=total_buffer_len, offset=offset, mode=mode, order=order, unlink_on_gc_collect=unlink_on_gc_collect, ) return as_strided(base, shape=shape, strides=strides) def _reduce_memmap_backed(a, m): """Pickling reduction for memmap backed arrays. a is expected to be an instance of np.ndarray (or np.memmap) m is expected to be an instance of np.memmap on the top of the ``base`` attribute ancestry of a. ``m.base`` should be the real python mmap object. """ # offset that comes from the striding differences between a and m util.debug( "[MEMMAP REDUCE] reducing a memmap-backed array (shape, {}, pid: {})".format( a.shape, os.getpid() ) ) try: from numpy.lib.array_utils import byte_bounds except (ModuleNotFoundError, ImportError): # Backward-compat for numpy < 2.0 from numpy import byte_bounds a_start, a_end = byte_bounds(a) m_start = byte_bounds(m)[0] offset = a_start - m_start # offset from the backing memmap offset += m.offset # 1D arrays are both F and C contiguous, so only set the flag in # higher dimensions. See https://github.com/joblib/joblib/pull/1704. if m.ndim > 1 and m.flags["F_CONTIGUOUS"]: order = "F" else: # The backing memmap buffer is necessarily contiguous hence C if not # Fortran order = "C" if a.flags["F_CONTIGUOUS"] or a.flags["C_CONTIGUOUS"]: # If the array is a contiguous view, no need to pass the strides strides = None total_buffer_len = None else: # Compute the total number of items to map from which the strided # view will be extracted. strides = a.strides total_buffer_len = (a_end - a_start) // a.itemsize return ( _strided_from_memmap, ( m.filename, a.dtype, m.mode, offset, order, a.shape, strides, total_buffer_len, False, ), ) def reduce_array_memmap_backward(a): """reduce a np.array or a np.memmap from a child process""" m = _get_backing_memmap(a) if isinstance(m, np.memmap) and m.filename not in JOBLIB_MMAPS: # if a is backed by a memmaped file, reconstruct a using the # memmaped file. return _reduce_memmap_backed(a, m) else: # a is either a regular (not memmap-backed) numpy array, or an array # backed by a shared temporary file created by joblib. In the latter # case, in order to limit the lifespan of these temporary files, we # serialize the memmap as a regular numpy array, and decref the # file backing the memmap (done implicitly in a previously registered # finalizer, see ``unlink_on_gc_collect`` for more details) return (loads, (dumps(np.asarray(a), protocol=HIGHEST_PROTOCOL),))
_WeakArrayKeyMap
python
viewflow__viewflow
tests/contrib/__init__.py
{ "start": 310, "end": 1794 }
class ____(TransactionTestCase): SETTINGS = "cookbook.workflow101.config" def setUp(self): """Start celery worker connection the the test database""" env = os.environ.copy() database_url = env["DATABASE_URL"] env["DATABASE_URL"] = "{}/{}".format( database_url[: database_url.rfind("/")], connection.settings_dict["NAME"] ) cmd = [ "celery", "--app", self.SETTINGS, "worker", "--loglevel", "DEBUG", "-E", "-c", "1", ] self.process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env ) self.assertIsNone(self.process.poll()) def tearDown(self): self.process.send_signal(signal.SIGTERM) if "-v3" in sys.argv: stdout, stderr = self.process.communicate() print(" CELERY STDOUT ".center(80, "=")) print(stdout.decode()) print(" CELERY STDERR ".center(80, "="), file=sys.stderr) print(stderr.decode(), file=sys.stderr) def wait_for_task(self, process, flow_task, status=None): for _ in range(100): try: return process.task_set.filter(flow_task=flow_task, status=status).get() except Task.DoesNotExist: time.sleep(0.05) assert False, "Task {} not found".format(flow_task)
CeleryTestCase
python
huggingface__transformers
src/transformers/models/dpr/modeling_dpr.py
{ "start": 8989, "end": 13321 }
class ____(DPRPretrainedContextEncoder): def __init__(self, config: DPRConfig): super().__init__(config) self.config = config self.ctx_encoder = DPREncoder(config) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[Tensor] = None, attention_mask: Optional[Tensor] = None, token_type_ids: Optional[Tensor] = None, inputs_embeds: Optional[Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[DPRContextEncoderOutput, tuple[Tensor, ...]]: r""" input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be formatted with [CLS] and [SEP] tokens as follows: (a) For sequence pairs (for a pair title+text for example): ``` tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 ``` (b) For single sequences (for a question for example): ``` tokens: [CLS] the dog is hairy . [SEP] token_type_ids: 0 0 0 0 0 0 0 ``` DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right rather than the left. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) Examples: ```python >>> from transformers import DPRContextEncoder, DPRContextEncoderTokenizer >>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base") >>> model = DPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base") >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"] >>> embeddings = model(input_ids).pooler_output ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: attention_mask = ( torch.ones(input_shape, device=device) if input_ids is None else (input_ids != self.config.pad_token_id) ) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) outputs = self.ctx_encoder( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) if not return_dict: return outputs[1:] return DPRContextEncoderOutput( pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions ) @auto_docstring( custom_intro=""" The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations. """ )
DPRContextEncoder
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_0.py
{ "start": 48, "end": 578 }
class ____[_T]: buf: list[_T] def append(self, t: _T): self.buf.append(t) # simple case, replace _T in signature and body def second[_T](var: tuple[_T]) -> _T: y: _T = var[1] return y # one diagnostic for each variable, comments are preserved def many_generics[ _T, # first generic _U, # second generic ](args): return args # neither of these are currently renamed from typing import Literal, cast def f[_T](v): cast("_T", v) cast("Literal['_T']") cast("list[_T]", v)
Generic
python
xlwings__xlwings
xlwings/constants.py
{ "start": 88421, "end": 88627 }
class ____: xlDataFieldScope = 2 # from enum XlPivotConditionScope xlFieldsScope = 1 # from enum XlPivotConditionScope xlSelectionScope = 0 # from enum XlPivotConditionScope
PivotConditionScope
python
huggingface__transformers
src/transformers/models/sam3/image_processing_sam3_fast.py
{ "start": 1824, "end": 16146 }
class ____(ImagesKwargs, total=False): r""" mask_size (`dict[str, int]`, *optional*): The size `{"height": int, "width": int}` to resize the segmentation maps to. """ mask_size: dict[str, int] def _compute_stability_score(masks: "torch.Tensor", mask_threshold: float, stability_score_offset: int): # One mask is always contained inside the other. # Save memory by preventing unnecessary cast to torch.int64 intersections = ( (masks > (mask_threshold + stability_score_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32) ) unions = (masks > (mask_threshold - stability_score_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32) stability_scores = intersections / unions return stability_scores def _mask_to_rle(input_mask: "torch.Tensor"): """ Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools. """ # Put in fortran order and flatten height and width batch_size, height, width = input_mask.shape input_mask = input_mask.permute(0, 2, 1).flatten(1) # Compute change indices diff = input_mask[:, 1:] ^ input_mask[:, :-1] change_indices = diff.nonzero() # Encode run length out = [] for i in range(batch_size): cur_idxs = change_indices[change_indices[:, 0] == i, 1] + 1 if len(cur_idxs) == 0: # No changes => either all 0 or all 1 # If the entire mask is 0, RLE is [height*width] or if the entire mask is 1, RLE is [0, height*width]. if input_mask[i, 0] == 0: out.append({"size": [height, width], "counts": [height * width]}) else: out.append({"size": [height, width], "counts": [0, height * width]}) continue btw_idxs = cur_idxs[1:] - cur_idxs[:-1] counts = [] if input_mask[i, 0] == 0 else [0] counts += [cur_idxs[0].item()] + btw_idxs.tolist() + [height * width - cur_idxs[-1].item()] out.append({"size": [height, width], "counts": counts}) return out def _batched_mask_to_box(masks: "torch.Tensor"): """ Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which corresponds the following required indices: - LEFT: left hand side of the bounding box - TOP: top of the bounding box - RIGHT: right of the bounding box - BOTTOM: bottom of the bounding box Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape is channel_1 x channel_2 x ... x 4. Args: - masks (`torch.Tensor` of shape `(batch, nb_mask, height, width)`) """ # torch.max below raises an error on empty inputs, just skip in this case if torch.numel(masks) == 0: return torch.zeros(*masks.shape[:-2], 4, device=masks.device) # Normalize shape to Cxheightxwidth shape = masks.shape height, width = shape[-2:] # Get top and bottom edges in_height, _ = torch.max(masks, dim=-1) in_height_coords = in_height * torch.arange(height, device=in_height.device)[None, :] bottom_edges, _ = torch.max(in_height_coords, dim=-1) in_height_coords = in_height_coords + height * (~in_height) top_edges, _ = torch.min(in_height_coords, dim=-1) # Get left and right edges in_width, _ = torch.max(masks, dim=-2) in_width_coords = in_width * torch.arange(width, device=in_width.device)[None, :] right_edges, _ = torch.max(in_width_coords, dim=-1) in_width_coords = in_width_coords + width * (~in_width) left_edges, _ = torch.min(in_width_coords, dim=-1) # If the mask is empty the right edge will be to the left of the left edge. # Replace these boxes with [0, 0, 0, 0] empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) out = out * (~empty_filter).unsqueeze(-1) # Return to original shape out = out.reshape(*shape[:-2], 4) return out def _is_box_near_crop_edge(boxes, crop_box, orig_box, atol=20.0): """Filter masks at the edge of a crop, but not at the edge of the original image.""" crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) left, top, _, _ = crop_box offset = torch.tensor([[left, top, left, top]], device=boxes.device) # Check if boxes has a channel dimension if len(boxes.shape) == 3: offset = offset.unsqueeze(1) boxes = (boxes + offset).float() near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) return torch.any(near_crop_edge, dim=1) def _pad_masks(masks, crop_box: list[int], orig_height: int, orig_width: int): left, top, right, bottom = crop_box if left == 0 and top == 0 and right == orig_width and bottom == orig_height: return masks # Coordinate transform masks pad_x, pad_y = orig_width - (right - left), orig_height - (bottom - top) pad = (left, pad_x - left, top, pad_y - top) return torch.nn.functional.pad(masks, pad, value=0) def _generate_crop_boxes( image, target_size: int, # Is it tuple here? crop_n_layers: int = 0, overlap_ratio: float = 512 / 1500, points_per_crop: Optional[int] = 32, crop_n_points_downscale_factor: Optional[list[int]] = 1, ) -> tuple[list[list[int]], list[int]]: """ Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer. Args: image (Union[`numpy.ndarray`, `PIL.Image`, `torch.Tensor`]): Image to generate crops for. target_size (`int`): Size of the smallest crop. crop_n_layers (`int`, *optional*): If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. overlap_ratio (`int`, *optional*): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. points_per_crop (`int`, *optional*): Number of points to sam3ple per crop. crop_n_points_downscale_factor (`int`, *optional*): The number of points-per-side sam3pled in layer n is scaled down by crop_n_points_downscale_factor**n. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the input image. If not provided, it will be inferred. """ if isinstance(image, list): raise ValueError("Only one image is allowed for crop generation.") original_size = image.shape[-2:] points_grid = [] for i in range(crop_n_layers + 1): n_points = int(points_per_crop / (crop_n_points_downscale_factor**i)) points_grid.append(_build_point_grid(n_points)) crop_boxes, layer_idxs = _generate_per_layer_crops(crop_n_layers, overlap_ratio, original_size) cropped_images, point_grid_per_crop = _generate_crop_images( crop_boxes, image, points_grid, layer_idxs, target_size, original_size ) crop_boxes = torch.tensor(crop_boxes) crop_boxes = crop_boxes.float() points_per_crop = torch.stack(point_grid_per_crop) points_per_crop = points_per_crop.unsqueeze(0).permute(0, 2, 1, 3) cropped_images = torch.stack(cropped_images) input_labels = torch.ones_like(points_per_crop[:, :, :, 0], dtype=torch.int64) return crop_boxes, points_per_crop, cropped_images, input_labels def _generate_per_layer_crops(crop_n_layers, overlap_ratio, original_size): """ Generates 2 ** (layers idx + 1) crops for each crop_n_layers. Crops are in the XYWH format : The XYWH format consists of the following required indices: - X: X coordinate of the top left of the bounding box - Y: Y coordinate of the top left of the bounding box - W: width of the bounding box - H: height of the bounding box """ crop_boxes, layer_idxs = [], [] im_height, im_width = original_size short_side = min(im_height, im_width) # Original image crop_boxes.append([0, 0, im_width, im_height]) layer_idxs.append(0) for i_layer in range(crop_n_layers): n_crops_per_side = 2 ** (i_layer + 1) overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) crop_width = int(math.ceil((overlap * (n_crops_per_side - 1) + im_width) / n_crops_per_side)) crop_height = int(math.ceil((overlap * (n_crops_per_side - 1) + im_height) / n_crops_per_side)) crop_box_x0 = [int((crop_width - overlap) * i) for i in range(n_crops_per_side)] crop_box_y0 = [int((crop_height - overlap) * i) for i in range(n_crops_per_side)] for left, top in product(crop_box_x0, crop_box_y0): box = [left, top, min(left + crop_width, im_width), min(top + crop_height, im_height)] crop_boxes.append(box) layer_idxs.append(i_layer + 1) return crop_boxes, layer_idxs def _build_point_grid(n_per_side: int) -> torch.Tensor: """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" offset = 1 / (2 * n_per_side) points_one_side = torch.linspace(offset, 1 - offset, n_per_side) points_x = torch.tile(points_one_side[None, :], (n_per_side, 1)) points_y = torch.tile(points_one_side[:, None], (1, n_per_side)) points = torch.stack([points_x, points_y], dim=-1).reshape(-1, 2) return points def _generate_crop_images( crop_boxes, image, points_grid, layer_idxs, target_size, original_size, input_data_format=None ): """ Takes as an input bounding boxes that are used to crop the image. Based in the crops, the corresponding points are also passed. """ cropped_images = [] total_points_per_crop = [] for i, crop_box in enumerate(crop_boxes): left, top, right, bottom = crop_box cropped_im = image[:, top:bottom, left:right] cropped_images.append(cropped_im) cropped_im_size = cropped_im.shape[-2:] points_scale = torch.tensor(cropped_im_size).flip(dims=(0,)).unsqueeze(0) points = points_grid[layer_idxs[i]] * points_scale normalized_points = _normalize_coordinates(target_size, points, original_size) total_points_per_crop.append(normalized_points) return cropped_images, total_points_per_crop def _normalize_coordinates( target_size: int, coords: torch.Tensor, original_size: tuple[int, int], is_bounding_box=False ) -> torch.Tensor: """ Expects a numpy array of length 2 in the final dimension. Requires the original image size in (height, width) format. """ old_height, old_width = original_size scale = target_size * 1.0 / max(old_height, old_width) new_height, new_width = old_height * scale, old_width * scale new_width = int(new_width + 0.5) new_height = int(new_height + 0.5) coords = deepcopy(coords).float() if is_bounding_box: coords = coords.reshape(-1, 2, 2) coords[..., 0] = coords[..., 0] * (new_width / old_width) coords[..., 1] = coords[..., 1] * (new_height / old_height) if is_bounding_box: coords = coords.reshape(-1, 4) return coords def _rle_to_mask(rle: dict[str, Any]) -> torch.Tensor: """Compute a binary mask from an uncompressed RLE.""" height, width = rle["size"] mask = torch.empty(height * width, dtype=bool) idx = 0 parity = False for count in rle["counts"]: mask[idx : idx + count] = parity idx += count parity = not parity mask = mask.reshape(width, height) return mask.transpose(0, 1) # Reshape to original shape def _post_process_for_mask_generation(rle_masks, iou_scores, mask_boxes, amg_crops_nms_thresh=0.7): """ Perform NMS (Non Maximum Suppression) on the outputs. Args: rle_masks (`torch.Tensor`): binary masks in the RLE format iou_scores (`torch.Tensor` of shape (nb_masks, 1)): iou_scores predicted by the model mask_boxes (`torch.Tensor`): The bounding boxes corresponding to segmentation masks amg_crops_nms_thresh (`float`, *optional*, defaults to 0.7): NMS threshold. """ keep_by_nms = batched_nms( boxes=mask_boxes.float(), scores=iou_scores, idxs=torch.zeros(mask_boxes.shape[0]), iou_threshold=amg_crops_nms_thresh, ) iou_scores = iou_scores[keep_by_nms] rle_masks = [rle_masks[i] for i in keep_by_nms] mask_boxes = mask_boxes[keep_by_nms] masks = [_rle_to_mask(rle) for rle in rle_masks] return masks, iou_scores, rle_masks, mask_boxes def _scale_boxes(boxes, target_sizes): """ Scale batch of bounding boxes to the target sizes. Args: boxes (`torch.Tensor` of shape `(batch_size, num_boxes, 4)`): Bounding boxes to scale. Each box is expected to be in (x1, y1, x2, y2) format. target_sizes (`list[tuple[int, int]]` or `torch.Tensor` of shape `(batch_size, 2)`): Target sizes to scale the boxes to. Each target size is expected to be in (height, width) format. Returns: `torch.Tensor` of shape `(batch_size, num_boxes, 4)`: Scaled bounding boxes. """ if isinstance(target_sizes, (list, tuple)): image_height = torch.tensor([i[0] for i in target_sizes]) image_width = torch.tensor([i[1] for i in target_sizes]) elif isinstance(target_sizes, torch.Tensor): image_height, image_width = target_sizes.unbind(1) else: raise TypeError("`target_sizes` must be a list, tuple or torch.Tensor") scale_factor = torch.stack([image_width, image_height, image_width, image_height], dim=1) scale_factor = scale_factor.unsqueeze(1).to(boxes.device) boxes = boxes * scale_factor return boxes @auto_docstring
Sam3FastImageProcessorKwargs
python
getsentry__sentry
src/sentry/integrations/perforce/repository.py
{ "start": 532, "end": 2915 }
class ____(IntegrationRepositoryProvider): """Repository provider for Perforce integration.""" name = "Perforce" repo_provider = "perforce" def get_repository_data( self, organization: Organization, config: dict[str, Any] ) -> Mapping[str, Any]: """ Validate and return repository data. Args: organization: Organization instance config: Repository configuration from user Returns: Repository configuration dictionary """ return {} def build_repository_config( self, organization: RpcOrganization, data: dict[str, Any] ) -> RepositoryConfig: """ Build repository configuration for database storage. Args: organization: Organization RPC object data: Repository data Returns: Repository configuration """ return { "name": "", "external_id": "", "url": "", "config": {}, "integration_id": 0, } def compare_commits( self, repo: Repository, start_sha: str | None, end_sha: str ) -> Sequence[Mapping[str, Any]]: """ Compare commits (changelists) between two versions. Args: repo: Repository instance start_sha: Starting changelist number (or None for initial) end_sha: Ending changelist number Returns: List of changelist dictionaries """ return [] def _format_commits( self, changelists: list[dict[str, Any]], depot_path: str ) -> Sequence[Mapping[str, Any]]: """ Format Perforce changelists into Sentry commit format. Args: changelists: List of changelist dictionaries from P4 depot_path: Depot path Returns: List of commits in Sentry format """ return [] def pull_request_url(self, repo: Repository, pull_request: PullRequest) -> str: """ Get URL for pull request. Perforce doesn't have native PRs, but might integrate with Swarm. """ return "" def repository_external_slug(self, repo: Repository) -> str: """Get external slug for repository.""" return repo.config.get("depot_path", repo.name)
PerforceRepositoryProvider
python
simplejson__simplejson
simplejson/tests/test_default.py
{ "start": 58, "end": 221 }
class ____(TestCase): def test_default(self): self.assertEqual( json.dumps(type, default=repr), json.dumps(repr(type)))
TestDefault
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_run.py
{ "start": 14735, "end": 17604 }
class ____: def test_template_fields(self): operator = CloudRunCreateServiceOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, service=SERVICE, service_name=SERVICE_NAME, ) _assert_common_template_fields(operator.template_fields) assert "service_name" in operator.template_fields @mock.patch(CLOUD_RUN_SERVICE_HOOK_PATH) def test_execute(self, hook_mock): hook_mock.return_value.create_service.return_value = SERVICE operator = CloudRunCreateServiceOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, service=SERVICE, service_name=SERVICE_NAME, ) operator.execute(context=mock.MagicMock()) hook_mock.return_value.create_service.assert_called_once_with( service=SERVICE, service_name=SERVICE_NAME, region=REGION, project_id=PROJECT_ID, ) @mock.patch(CLOUD_RUN_SERVICE_HOOK_PATH) def test_execute_already_exists(self, hook_mock): hook_mock.return_value.create_service.side_effect = AlreadyExists("Service already exists") hook_mock.return_value.get_service.return_value = SERVICE operator = CloudRunCreateServiceOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, service=SERVICE, service_name=SERVICE_NAME, ) operator.execute(context=mock.MagicMock()) hook_mock.return_value.create_service.assert_called_once_with( service=SERVICE, service_name=SERVICE_NAME, region=REGION, project_id=PROJECT_ID, ) hook_mock.return_value.get_service.assert_called_once_with( service_name=SERVICE_NAME, region=REGION, project_id=PROJECT_ID, ) @mock.patch(CLOUD_RUN_SERVICE_HOOK_PATH) def test_execute_when_other_error(self, hook_mock): error_message = "An error occurred. Exiting." hook_mock.return_value.create_service.side_effect = GoogleCloudError(error_message, errors=None) operator = CloudRunCreateServiceOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, service=SERVICE, service_name=SERVICE_NAME, ) with pytest.raises(expected_exception=GoogleCloudError) as context: operator.execute(context=mock.MagicMock()) assert error_message == context.value.message hook_mock.return_value.create_service.assert_called_once_with( service=SERVICE, service_name=SERVICE_NAME, region=REGION, project_id=PROJECT_ID, )
TestCloudRunCreateServiceOperator
python
gevent__gevent
src/greentest/3.10/test_threading.py
{ "start": 35184, "end": 41210 }
class ____(BaseTestCase): def _run_and_join(self, script): script = """if 1: import sys, os, time, threading # a thread, which waits for the main program to terminate def joiningfunc(mainthread): mainthread.join() print('end of thread') # stdout is fully buffered because not a tty, we have to flush # before exit. sys.stdout.flush() \n""" + script rc, out, err = assert_python_ok("-c", script) data = out.decode().replace('\r', '') self.assertEqual(data, "end of main\nend of thread\n") def test_1_join_on_shutdown(self): # The usual case: on exit, wait for a non-daemon thread script = """if 1: import os t = threading.Thread(target=joiningfunc, args=(threading.current_thread(),)) t.start() time.sleep(0.1) print('end of main') """ self._run_and_join(script) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_2_join_in_forked_process(self): # Like the test above, but from a forked interpreter script = """if 1: from test import support childpid = os.fork() if childpid != 0: # parent process support.wait_process(childpid, exitcode=0) sys.exit(0) # child process t = threading.Thread(target=joiningfunc, args=(threading.current_thread(),)) t.start() print('end of main') """ self._run_and_join(script) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_3_join_in_forked_from_thread(self): # Like the test above, but fork() was called from a worker thread # In the forked process, the main Thread object must be marked as stopped. script = """if 1: from test import support main_thread = threading.current_thread() def worker(): childpid = os.fork() if childpid != 0: # parent process support.wait_process(childpid, exitcode=0) sys.exit(0) # child process t = threading.Thread(target=joiningfunc, args=(main_thread,)) print('end of main') t.start() t.join() # Should not block: main_thread is already stopped w = threading.Thread(target=worker) w.start() """ self._run_and_join(script) @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_4_daemon_threads(self): # Check that a daemon thread cannot crash the interpreter on shutdown # by manipulating internal structures that are being disposed of in # the main thread. script = """if True: import os import random import sys import time import threading thread_has_run = set() def random_io(): '''Loop for a while sleeping random tiny amounts and doing some I/O.''' while True: with open(os.__file__, 'rb') as in_f: stuff = in_f.read(200) with open(os.devnull, 'wb') as null_f: null_f.write(stuff) time.sleep(random.random() / 1995) thread_has_run.add(threading.current_thread()) def main(): count = 0 for _ in range(40): new_thread = threading.Thread(target=random_io) new_thread.daemon = True new_thread.start() count += 1 while len(thread_has_run) < count: time.sleep(0.001) # Trigger process shutdown sys.exit(0) main() """ rc, out, err = assert_python_ok('-c', script) self.assertFalse(err) @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") @unittest.skipIf(sys.platform in platforms_to_skip, "due to known OS bug") def test_reinit_tls_after_fork(self): # Issue #13817: fork() would deadlock in a multithreaded program with # the ad-hoc TLS implementation. def do_fork_and_wait(): # just fork a child process and wait it pid = os.fork() if pid > 0: support.wait_process(pid, exitcode=50) else: os._exit(50) # start a bunch of threads that will fork() child processes threads = [] for i in range(16): t = threading.Thread(target=do_fork_and_wait) threads.append(t) t.start() for t in threads: t.join() @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()") def test_clear_threads_states_after_fork(self): # Issue #17094: check that threads states are cleared after fork() # start a bunch of threads threads = [] for i in range(16): t = threading.Thread(target=lambda : time.sleep(0.3)) threads.append(t) t.start() pid = os.fork() if pid == 0: # check that threads states have been cleared if len(sys._current_frames()) == 1: os._exit(51) else: os._exit(52) else: support.wait_process(pid, exitcode=51) for t in threads: t.join()
ThreadJoinOnShutdown
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/solids.py
{ "start": 1428, "end": 2862 }
class ____(graphene.ObjectType): name = graphene.NonNull(graphene.String) description = graphene.String() type = graphene.NonNull(GrapheneDagsterType) metadata_entries = non_null_list(GrapheneMetadataEntry) class Meta: name = "InputDefinition" def __init__(self, represented_job: RepresentedJob, solid_def_name: str, input_def_name: str): self._represented_job = check.inst_param( represented_job, "represented_pipeline", RepresentedJob ) check.str_param(solid_def_name, "solid_def_name") check.str_param(input_def_name, "input_def_name") node_def_snap = self._represented_job.get_node_def_snap(solid_def_name) self._input_def_snap = node_def_snap.get_input_snap(input_def_name) super().__init__( name=self._input_def_snap.name, description=self._input_def_snap.description, ) def resolve_type(self, _graphene_info: ResolveInfo) -> GrapheneDagsterTypeUnion: return to_dagster_type( self._represented_job.job_snapshot.dagster_type_namespace_snapshot.get_dagster_type_snap, self._represented_job.job_snapshot.config_schema_snapshot.get_config_snap, self._input_def_snap.dagster_type_key, ) def resolve_metadata_entries(self, _graphene_info): return list(iterate_metadata_entries(self._input_def_snap.metadata))
GrapheneInputDefinition
python
django__django
tests/user_commands/management/commands/required_option.py
{ "start": 54, "end": 349 }
class ____(BaseCommand): def add_arguments(self, parser): parser.add_argument("-n", "--need-me", required=True) parser.add_argument("-t", "--need-me-too", required=True, dest="needme2") def handle(self, *args, **options): self.stdout.write(",".join(options))
Command
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_rich_string05.py
{ "start": 315, "end": 1123 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("rich_string05.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_column("A:A", 30) bold = workbook.add_format({"bold": 1}) italic = workbook.add_format({"italic": 1}) worksheet.write("A1", "Foo", bold) worksheet.write("A2", "Bar", italic) worksheet.write_rich_string( "A3", "This is ", bold, "bold", " and this is ", italic, "italic" ) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
google__pytype
pytype/tests/test_typing2.py
{ "start": 26915, "end": 33984 }
class ____(test_base.BaseTest): """Tests for typing.Literal in source code.""" def test_basic(self): ty = self.Infer(""" from typing_extensions import Literal x1: Literal["hello"] x2: Literal[b"hello"] x3: Literal[u"hello"] x4: Literal[0] x5: Literal[True] x6: Literal[None] """) self.assertTypesMatchPytd( ty, """ from typing import Literal x1: Literal['hello'] x2: Literal[b'hello'] x3: Literal['hello'] x4: Literal[0] x5: Literal[True] x6: None """, ) def test_basic_enum(self): ty = self.Infer(""" import enum from typing_extensions import Literal class Color(enum.Enum): RED = "RED" x: Literal[Color.RED] """) self.assertTypesMatchPytd( ty, """ import enum from typing import Literal x: Literal[Color.RED] class Color(enum.Enum): RED: Literal["RED"] """, ) @test_base.skip("Pytype loads N.A and treats it as a literal.") def test_not_an_enum(self): self.CheckWithErrors(""" from typing_extensions import Literal class N: A = 1 x: Literal[N.A] # bad-annotation """) def test_missing_enum_member(self): self.CheckWithErrors(""" import enum from typing_extensions import Literal class M(enum.Enum): A = 1 x: Literal[M.B] # attribute-error """) def test_union(self): ty = self.Infer(""" from typing_extensions import Literal def f(x: Literal["x", "y"]): pass """) self.assertTypesMatchPytd( ty, """ from typing import Literal, Union def f(x: Literal['x', 'y']) -> None: ... """, ) def test_unnest(self): ty = self.Infer(""" from typing_extensions import Literal X = Literal["X"] def f(x: Literal[X, Literal[None], Literal[Literal["Y"]]]): pass """) self.assertTypesMatchPytd( ty, """ from typing import Literal, Optional, Union X = Literal['X'] def f(x: Optional[Literal['X', 'Y']]) -> None: ... """, ) def test_invalid(self): errors = self.CheckWithErrors(""" from typing_extensions import Literal x1: Literal[0, ...] # invalid-annotation[e1] x2: Literal[str, 4.2] # invalid-annotation[e2] """) self.assertErrorRegexes( errors, { "e1": r"Bad parameter '...' at index 1", "e2": ( r"Bad parameter 'str' at index 0\n" r"\s*Bad parameter 'float' at index 1" ), }, ) def test_variable(self): errors = self.CheckWithErrors(""" from typing_extensions import Literal x: Literal[0] = 0 y: Literal[0] = 1 # annotation-type-mismatch[e] """) self.assertErrorRegexes( errors, {"e": r"Annotation: Literal\[0\].*Assignment: Literal\[1\]"} ) def test_parameter(self): errors = self.CheckWithErrors(""" from typing_extensions import Literal def f(x: Literal[True]): pass f(True) f(False) # wrong-arg-types[e] """) self.assertErrorRegexes( errors, {"e": r"Expected.*Literal\[True\].*Actual.*Literal\[False\]"} ) def test_union_parameter(self): errors = self.CheckWithErrors(""" from typing_extensions import Literal def f(x: Literal["x", "z"]): pass f("x") f("y") # wrong-arg-types[e] f("z") """) self.assertErrorRegexes( errors, {"e": r"Expected.*Literal\['x', 'z'\].*Actual.*Literal\['y'\]"} ) def test_mixed_union(self): # "hello" is a ConcreteValue, M.A is an Instance. There was a crash when # comparing another ConcreteValue against the Instance variant. self.CheckWithErrors(""" import enum from typing_extensions import Literal class M(enum.Enum): A = 1 def use(x: Literal["hello", M.A]) -> None: ... use(None) # wrong-arg-types """) def test_return(self): errors = self.CheckWithErrors(""" from typing_extensions import Literal def f() -> Literal["hello"]: if __random__: return "hello" else: return "goodbye" # bad-return-type[e] """) self.assertErrorRegexes( errors, {"e": r"Expected.*Literal\['hello'\].*Actual.*Literal\['goodbye'\]"}, ) def test_match_non_literal(self): self.CheckWithErrors(""" from typing_extensions import Literal x: Literal["x"] def f(x: str): pass def g(x: int): pass f(x) g(x) # wrong-arg-types """) def test_match_enum(self): self.CheckWithErrors(""" from typing_extensions import Literal import enum class M(enum.Enum): A = 1 B = 2 x: Literal[M.A] def f(x: Literal[M.A]) -> None: pass f(M.A) f(x) f(M.B) # wrong-arg-types """) def test_iterate(self): # TODO(b/63407497): Enabling --strict-parameter-checks leads to a cryptic # wrong-arg-types error on line 5 in which the actual type is # "Union[str, Literal['x']]". self.options.tweak(strict_parameter_checks=False) self.Check(""" from typing_extensions import Literal def f(x: Literal["x", "y"]): pass for x in ["x", "y"]: f(x) """) def test_overloads(self): ty = self.Infer(""" from typing import Optional, overload from typing_extensions import Literal @overload def f(x: Literal[False]) -> str: ... @overload def f(x: Literal[True]) -> Optional[str]: ... def f(x) -> Optional[str]: if x: return None return "" """) self.assertTypesMatchPytd( ty, """ from typing import Literal, Optional, overload @overload def f(x: Literal[False]) -> str: ... @overload def f(x: Literal[True]) -> Optional[str]: ... """, ) def test_list_of_literals(self): self.CheckWithErrors(""" import dataclasses from typing import List from typing_extensions import Literal Strings = Literal['hello', 'world'] @dataclasses.dataclass class A: x: List[Strings] A(x=['hello', 'world']) A(x=['oops']) # wrong-arg-types """) def test_list_of_list_of_literals(self): self.CheckWithErrors(""" import dataclasses from typing import List from typing_extensions import Literal Strings = Literal['hello', 'world'] @dataclasses.dataclass class A: x: List[List[Strings]] A(x=[['hello', 'world']]) A(x=[['oops']]) # wrong-arg-types """) def test_lots_of_literals(self): ty = self.Infer(""" from typing import Literal X: Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 'A'] """) self.assertTypesMatchPytd( ty, """ from typing import Literal X: Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 'A'] """, )
LiteralTest
python
coleifer__peewee
tests/schema.py
{ "start": 31910, "end": 32741 }
class ____(ModelDatabaseTestCase): database = get_in_memory_db() requires = [TMKV] def test_create_table_as_sql(self): query = (TMKV .select(TMKV.key, TMKV.value.alias('val')) .where(TMKV.extra < 4)) ctx = TMKV._schema._create_table_as('tmkv_new', query) self.assertSQL(ctx, ( 'CREATE TABLE IF NOT EXISTS "tmkv_new" AS ' 'SELECT "t1"."key", "t1"."value" AS "val" FROM "tmkv" AS "t1" ' 'WHERE ("t1"."extra" < ?)'), [4]) ctx = TMKV._schema._create_table_as(('alt', 'tmkv_new'), query) self.assertSQL(ctx, ( 'CREATE TABLE IF NOT EXISTS "alt"."tmkv_new" AS ' 'SELECT "t1"."key", "t1"."value" AS "val" FROM "tmkv" AS "t1" ' 'WHERE ("t1"."extra" < ?)'), [4])
TestCreateTableAsSQL
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/compression_ops_test.py
{ "start": 2973, "end": 6746 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(element=_test_objects())) + combinations.times( test_base.v2_eager_only_combinations(), combinations.combine(element=_test_v2_eager_only_objects()))) def testCompression(self, element): element = element._obj compressed = compression_ops.compress(element) uncompressed = compression_ops.uncompress( compressed, structure.type_spec_from_value(element)) self.assertValuesEqual(element, self.evaluate(uncompressed)) @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(element=_test_objects())) + combinations.times( test_base.v2_eager_only_combinations(), combinations.combine(element=_test_v2_eager_only_objects()))) def testDatasetCompression(self, element): element = element._obj dataset = dataset_ops.Dataset.from_tensors(element) element_spec = dataset.element_spec dataset = dataset.map(lambda *x: compression_ops.compress(x)) dataset = dataset.map(lambda x: compression_ops.uncompress(x, element_spec)) self.assertDatasetProduces(dataset, [element]) @combinations.generate( combinations.times(test_base.default_test_combinations())) def testCompressionOutputDTypeMismatch(self): element = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" compressed = compression_ops.compress(element) with self.assertRaisesRegex(errors.FailedPreconditionError, "but got a tensor of type string"): uncompressed = compression_ops.uncompress( compressed, structure.type_spec_from_value(0)) self.evaluate(uncompressed) @combinations.generate( combinations.times(test_base.default_test_combinations())) def testCompressionInputShapeMismatch(self): element = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" compressed = compression_ops.compress(element) compressed = [compressed, compressed] error = ( errors.InvalidArgumentError if context.executing_eagerly() else ValueError) with self.assertRaises(error): uncompressed = compression_ops.uncompress( compressed, structure.type_spec_from_value(0)) self.evaluate(uncompressed) @combinations.generate( combinations.times(test_base.default_test_combinations())) def testCompressionInputDTypeMismatch(self): uncompressed = list(range(10)) with self.assertRaises(TypeError): uncompressed = compression_ops.uncompress( uncompressed, structure.type_spec_from_value(uncompressed)) self.evaluate(uncompressed) @combinations.generate( combinations.times(test_base.default_test_combinations())) def testCompressionVariantMismatch(self): # Use a dataset as a variant. dataset = dataset_ops.Dataset.range(10) variant = dataset._variant_tensor with self.assertRaises(errors.InvalidArgumentError): uncompressed = compression_ops.uncompress(variant, dataset.element_spec) self.evaluate(uncompressed) # Only test eager mode since nested datasets are not allowed in graph mode. @combinations.generate( combinations.times(test_base.eager_only_combinations())) def testDatasetVariantMismatch(self): # Use a nested dataset as an example of a variant. dataset = dataset_ops.Dataset.from_tensors(dataset_ops.Dataset.range(10)) with self.assertRaises(TypeError): dataset = dataset.map( lambda x: compression_ops.uncompress(x, dataset.element_spec)) self.getDatasetOutput(dataset) if __name__ == "__main__": test.main()
CompressionOpsTest
python
great-expectations__great_expectations
docs/docusaurus/versioned_docs/version-0.18/snippets/expect_column_max_to_be_between_custom.py
{ "start": 1540, "end": 3696 }
class ____(ColumnAggregateMetricProvider): # </snippet> """MetricProvider Class for Custom Aggregate Max MetricProvider""" # <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py metric_name"> metric_name = "column.custom_max" # </snippet> # <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py _pandas"> @column_aggregate_value(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): """Pandas Max Implementation""" return column.max() # </snippet> # <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py sql_def"> @metric_value(engine=SqlAlchemyExecutionEngine) def _sqlalchemy( cls, execution_engine: SqlAlchemyExecutionEngine, metric_domain_kwargs, metric_value_kwargs, metrics, runtime_configuration, ): # </snippet> # <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py sql_selectable"> ( selectable, compute_domain_kwargs, accessor_domain_kwargs, ) = execution_engine.get_compute_domain( metric_domain_kwargs, MetricDomainTypes.COLUMN ) column_name = accessor_domain_kwargs["column"] column = sa.column(column_name) # </snippet> # <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py sql_query"> query = sa.select(sa.func.max(column)).select_from(selectable) result = execution_engine.execute_query(query).fetchone() return result[0] # </snippet> # <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py _spark"> @column_aggregate_partial(engine=SparkDFExecutionEngine) def _spark(cls, column, _table, _column_name, **kwargs): """Spark Max Implementation""" return F.max(column) # </snippet> # <snippet name="docs/docusaurus/docs/snippets/expect_column_max_to_be_between_custom.py ExpectColumnMaxToBeBetween class_def">
ColumnCustomMax
python
openai__openai-python
src/openai/types/responses/response_code_interpreter_call_code_done_event.py
{ "start": 217, "end": 806 }
class ____(BaseModel): code: str """The final code snippet output by the code interpreter.""" item_id: str """The unique identifier of the code interpreter tool call item.""" output_index: int """The index of the output item in the response for which the code is finalized.""" sequence_number: int """The sequence number of this event, used to order streaming events.""" type: Literal["response.code_interpreter_call_code.done"] """The type of the event. Always `response.code_interpreter_call_code.done`."""
ResponseCodeInterpreterCallCodeDoneEvent
python
Netflix__metaflow
metaflow/plugins/cards/card_server.py
{ "start": 952, "end": 2963 }
class ____(Thread): """ A thread that watches for new runs and sends the run_id to the card server when a new run is detected. It observes the `latest_run` file in the `.metaflow/<flowname>` directory. """ def __init__(self, flow_name, connection: Connection): super().__init__() self.daemon = True self._connection = connection self._flow_name = flow_name self._watch_file = self._initialize_watch_file() if self._watch_file is None: _ClickLogger( "Warning: Could not initialize watch file location.", fg="yellow" ) self._current_run_id = self.get_run_id() def _initialize_watch_file(self): local_root = LocalStorage.datastore_root if local_root is None: local_root = LocalStorage.get_datastore_root_from_config( lambda _: None, create_on_absent=False ) return ( os.path.join(local_root, self._flow_name, "latest_run") if local_root else None ) def get_run_id(self): # Try to reinitialize watch file if needed if not self._watch_file: self._watch_file = self._initialize_watch_file() # Early return if watch file is still None or doesn't exist if not (self._watch_file and os.path.exists(self._watch_file)): return None try: with open(self._watch_file, "r") as f: return f.read().strip() except (IOError, OSError) as e: _ClickLogger( "Warning: Could not read run ID from watch file: %s" % e, fg="yellow" ) return None def watch(self): while True: run_id = self.get_run_id() if run_id != self._current_run_id: self._current_run_id = run_id self._connection.send(run_id) time.sleep(2) def run(self): self.watch()
RunWatcher
python
sympy__sympy
sympy/vector/integrals.py
{ "start": 533, "end": 6837 }
class ____(Basic): """ Represents integral of a scalar or vector field over a Parametric Region Examples ======== >>> from sympy import cos, sin, pi >>> from sympy.vector import CoordSys3D, ParametricRegion, ParametricIntegral >>> from sympy.abc import r, t, theta, phi >>> C = CoordSys3D('C') >>> curve = ParametricRegion((3*t - 2, t + 1), (t, 1, 2)) >>> ParametricIntegral(C.x, curve) 5*sqrt(10)/2 >>> length = ParametricIntegral(1, curve) >>> length sqrt(10) >>> semisphere = ParametricRegion((2*sin(phi)*cos(theta), 2*sin(phi)*sin(theta), 2*cos(phi)),\ (theta, 0, 2*pi), (phi, 0, pi/2)) >>> ParametricIntegral(C.z, semisphere) 8*pi >>> ParametricIntegral(C.j + C.k, ParametricRegion((r*cos(theta), r*sin(theta)), r, theta)) 0 """ def __new__(cls, field, parametricregion): coord_set = _get_coord_systems(field) if len(coord_set) == 0: coord_sys = CoordSys3D('C') elif len(coord_set) > 1: raise ValueError else: coord_sys = next(iter(coord_set)) if parametricregion.dimensions == 0: return S.Zero base_vectors = coord_sys.base_vectors() base_scalars = coord_sys.base_scalars() parametricfield = field r = Vector.zero for i in range(len(parametricregion.definition)): r += base_vectors[i]*parametricregion.definition[i] if len(coord_set) != 0: for i in range(len(parametricregion.definition)): parametricfield = parametricfield.subs(base_scalars[i], parametricregion.definition[i]) if parametricregion.dimensions == 1: parameter = parametricregion.parameters[0] r_diff = diff(r, parameter) lower, upper = parametricregion.limits[parameter][0], parametricregion.limits[parameter][1] if isinstance(parametricfield, Vector): integrand = simplify(r_diff.dot(parametricfield)) else: integrand = simplify(r_diff.magnitude()*parametricfield) result = integrate(integrand, (parameter, lower, upper)) elif parametricregion.dimensions == 2: u, v = cls._bounds_case(parametricregion.parameters, parametricregion.limits) r_u = diff(r, u) r_v = diff(r, v) normal_vector = simplify(r_u.cross(r_v)) if isinstance(parametricfield, Vector): integrand = parametricfield.dot(normal_vector) else: integrand = parametricfield*normal_vector.magnitude() integrand = simplify(integrand) lower_u, upper_u = parametricregion.limits[u][0], parametricregion.limits[u][1] lower_v, upper_v = parametricregion.limits[v][0], parametricregion.limits[v][1] result = integrate(integrand, (u, lower_u, upper_u), (v, lower_v, upper_v)) else: variables = cls._bounds_case(parametricregion.parameters, parametricregion.limits) coeff = Matrix(parametricregion.definition).jacobian(variables).det() integrand = simplify(parametricfield*coeff) l = [(var, parametricregion.limits[var][0], parametricregion.limits[var][1]) for var in variables] result = integrate(integrand, *l) if not isinstance(result, Integral): return result else: return super().__new__(cls, field, parametricregion) @classmethod def _bounds_case(cls, parameters, limits): V = list(limits.keys()) E = [] for p in V: lower_p = limits[p][0] upper_p = limits[p][1] lower_p = lower_p.atoms() upper_p = upper_p.atoms() E.extend((p, q) for q in V if p != q and (lower_p.issuperset({q}) or upper_p.issuperset({q}))) if not E: return parameters else: return topological_sort((V, E), key=default_sort_key) @property def field(self): return self.args[0] @property def parametricregion(self): return self.args[1] def vector_integrate(field, *region): """ Compute the integral of a vector/scalar field over a a region or a set of parameters. Examples ======== >>> from sympy.vector import CoordSys3D, ParametricRegion, vector_integrate >>> from sympy.abc import x, y, t >>> C = CoordSys3D('C') >>> region = ParametricRegion((t, t**2), (t, 1, 5)) >>> vector_integrate(C.x*C.i, region) 12 Integrals over some objects of geometry module can also be calculated. >>> from sympy.geometry import Point, Circle, Triangle >>> c = Circle(Point(0, 2), 5) >>> vector_integrate(C.x**2 + C.y**2, c) 290*pi >>> triangle = Triangle(Point(-2, 3), Point(2, 3), Point(0, 5)) >>> vector_integrate(3*C.x**2*C.y*C.i + C.j, triangle) -8 Integrals over some simple implicit regions can be computed. But in most cases, it takes too long to compute over them. This is due to the expressions of parametric representation becoming large. >>> from sympy.vector import ImplicitRegion >>> c2 = ImplicitRegion((x, y), (x - 2)**2 + (y - 1)**2 - 9) >>> vector_integrate(1, c2) 6*pi Integral of fields with respect to base scalars: >>> vector_integrate(12*C.y**3, (C.y, 1, 3)) 240 >>> vector_integrate(C.x**2*C.z, C.x) C.x**3*C.z/3 >>> vector_integrate(C.x*C.i - C.y*C.k, C.x) (Integral(C.x, C.x))*C.i + (Integral(-C.y, C.x))*C.k >>> _.doit() C.x**2/2*C.i + (-C.x*C.y)*C.k """ if len(region) == 1: if isinstance(region[0], ParametricRegion): return ParametricIntegral(field, region[0]) if isinstance(region[0], ImplicitRegion): region = parametric_region_list(region[0])[0] return vector_integrate(field, region) if isinstance(region[0], GeometryEntity): regions_list = parametric_region_list(region[0]) result = 0 for reg in regions_list: result += vector_integrate(field, reg) return result return integrate(field, *region)
ParametricIntegral
python
tensorflow__tensorflow
tensorflow/python/autograph/operators/py_builtins_test.py
{ "start": 1480, "end": 1595 }
class ____: def overridden_method(self, x): return x + 20 @test_util.run_all_in_graph_and_eager_modes
TestBase
python
django__django
tests/admin_docs/tests.py
{ "start": 462, "end": 643 }
class ____(SimpleTestCase): pass @override_settings(ROOT_URLCONF="admin_docs.urls") @modify_settings(INSTALLED_APPS={"append": "django.contrib.admindocs"})
AdminDocsSimpleTestCase
python
pyca__cryptography
tests/hazmat/asn1/test_serialization.py
{ "start": 6554, "end": 18605 }
class ____: def test_ok_sequence_single_field(self) -> None: @asn1.sequence @_comparable_dataclass class Example: foo: int assert_roundtrips([(Example(foo=9), b"\x30\x03\x02\x01\x09")]) def test_ok_sequence_multiple_fields(self) -> None: @asn1.sequence @_comparable_dataclass class Example: foo: int bar: int assert_roundtrips( [(Example(foo=9, bar=6), b"\x30\x06\x02\x01\x09\x02\x01\x06")] ) def test_ok_nested_sequence(self) -> None: @asn1.sequence @_comparable_dataclass class Child: foo: int @asn1.sequence @_comparable_dataclass class Parent: foo: Child assert_roundtrips( [(Parent(foo=Child(foo=9)), b"\x30\x05\x30\x03\x02\x01\x09")] ) def test_ok_sequence_multiple_types(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: bool b: int c: bytes d: str assert_roundtrips( [ ( Example(a=True, b=9, c=b"c", d="d"), b"\x30\x0c\x01\x01\xff\x02\x01\x09\x04\x01c\x0c\x01d", ) ] ) def test_ok_sequenceof_simple_type(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: typing.List[int] assert_roundtrips( [ ( Example(a=[1, 2, 3, 4]), b"\x30\x0e\x30\x0c\x02\x01\x01\x02\x01\x02\x02\x01\x03\x02\x01\x04", ) ] ) def test_ok_sequenceof_user_defined_type(self) -> None: @asn1.sequence @_comparable_dataclass class MyType: a: int b: bool @asn1.sequence @_comparable_dataclass class Example: a: typing.List[MyType] assert_roundtrips( [ ( Example(a=[MyType(a=1, b=True), MyType(a=2, b=False)]), b"\x30\x12\x30\x10\x30\x06\x02\x01\x01\x01\x01\xff\x30\x06\x02\x01\x02\x01\x01\x00", ) ] ) def test_ok_sequenceof_size_restriction(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[typing.List[int], asn1.Size(min=1, max=4)] assert_roundtrips( [ ( Example(a=[1, 2, 3, 4]), b"\x30\x0e\x30\x0c\x02\x01\x01\x02\x01\x02\x02\x01\x03\x02\x01\x04", ) ] ) def test_ok_sequenceof_size_restriction_no_max(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[typing.List[int], asn1.Size(min=1, max=None)] assert_roundtrips( [ ( Example(a=[1, 2, 3, 4]), b"\x30\x0e\x30\x0c\x02\x01\x01\x02\x01\x02\x02\x01\x03\x02\x01\x04", ) ] ) def test_ok_sequenceof_size_restriction_exact(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[typing.List[int], asn1.Size.exact(4)] assert_roundtrips( [ ( Example(a=[1, 2, 3, 4]), b"\x30\x0e\x30\x0c\x02\x01\x01\x02\x01\x02\x02\x01\x03\x02\x01\x04", ) ] ) def test_fail_sequenceof_size_too_big(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[typing.List[int], asn1.Size(min=1, max=2)] with pytest.raises( ValueError, match=re.escape("SEQUENCE OF has size 4, expected size in [1, 2]"), ): asn1.decode_der( Example, b"\x30\x0e\x30\x0c\x02\x01\x01\x02\x01\x02\x02\x01\x03\x02\x01\x04", ) with pytest.raises( ValueError, ): asn1.encode_der(Example(a=[1, 2, 3, 4])) def test_fail_sequenceof_size_too_small(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[typing.List[int], asn1.Size(min=5, max=6)] with pytest.raises( ValueError, match=re.escape("SEQUENCE OF has size 4, expected size in [5, 6]"), ): asn1.decode_der( Example, b"\x30\x0e\x30\x0c\x02\x01\x01\x02\x01\x02\x02\x01\x03\x02\x01\x04", ) with pytest.raises( ValueError, ): asn1.encode_der(Example(a=[1, 2, 3, 4])) def test_fail_sequenceof_size_not_exact(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[typing.List[int], asn1.Size.exact(5)] with pytest.raises( ValueError, match=re.escape("SEQUENCE OF has size 4, expected size in [5, 5]"), ): asn1.decode_der( Example, b"\x30\x0e\x30\x0c\x02\x01\x01\x02\x01\x02\x02\x01\x03\x02\x01\x04", ) with pytest.raises( ValueError, ): asn1.encode_der(Example(a=[1, 2, 3, 4])) def test_ok_sequence_with_optionals(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: typing.Union[bool, None] b: int c: bytes d: typing.Union[None, str] assert_roundtrips( [ # All fields are present ( Example(a=True, b=9, c=b"c", d="d"), b"\x30\x0c\x01\x01\xff\x02\x01\x09\x04\x01c\x0c\x01d", ), # All optional fields are missing ( Example(a=None, b=9, c=b"c", d=None), b"\x30\x06\x02\x01\x09\x04\x01c", ), # Some optional fields are missing ( Example(a=True, b=9, c=b"c", d=None), b"\x30\x09\x01\x01\xff\x02\x01\x09\x04\x01c", ), ] ) def test_ok_sequence_with_nested_optionals(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: typing.Union[typing.Union[bool, None], None] b: int c: bytes d: typing.Union[None, typing.Union[None, str]] assert_roundtrips( [ # All fields are present ( Example(a=True, b=9, c=b"c", d="d"), b"\x30\x0c\x01\x01\xff\x02\x01\x09\x04\x01c\x0c\x01d", ), # All optional fields are missing ( Example(a=None, b=9, c=b"c", d=None), b"\x30\x06\x02\x01\x09\x04\x01c", ), # Some optional fields are missing ( Example(a=True, b=9, c=b"c", d=None), b"\x30\x09\x01\x01\xff\x02\x01\x09\x04\x01c", ), ] ) def test_ok_sequence_all_types_optional(self) -> None: @asn1.sequence @_comparable_dataclass class MyField: a: int @asn1.sequence @_comparable_dataclass class Example: a: typing.Union[MyField, None] b: typing.Union[int, None] c: typing.Union[bytes, None] d: typing.Union[asn1.PrintableString, None] e: typing.Union[asn1.UtcTime, None] f: typing.Union[asn1.GeneralizedTime, None] g: typing.Union[typing.List[int], None] assert_roundtrips( [ ( Example( a=None, b=None, c=None, d=None, e=None, f=None, g=None ), b"\x30\x00", ) ] ) def test_ok_sequence_with_default_annotations(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[bool, asn1.Default(True)] b: int c: bytes d: Annotated[str, asn1.Default("d")] assert_roundtrips( [ # No DEFAULT fields contain their default value ( Example(a=False, b=9, c=b"c", d="x"), b"\x30\x0c\x01\x01\x00\x02\x01\x09\x04\x01c\x0c\x01x", ), # All DEFAULT fields contain their default value ( Example(a=True, b=9, c=b"c", d="d"), b"\x30\x06\x02\x01\x09\x04\x01c", ), # Some DEFAULT fields contain their default value ( Example(a=False, b=9, c=b"c", d="d"), b"\x30\x09\x01\x01\x00\x02\x01\x09\x04\x01c", ), ] ) def test_fail_decode_default_value_present(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[bool, asn1.Default(True)] with pytest.raises( ValueError, match="invalid DER: DEFAULT value was explicitly encoded", ): asn1.decode_der(Example, b"\x30\x03\x01\x01\xff") def test_ok_optional_fields_with_implicit_encoding(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[typing.Union[int, None], asn1.Implicit(0)] b: Annotated[typing.Union[int, None], asn1.Implicit(1)] assert_roundtrips( [ (Example(a=9, b=9), b"\x30\x06\x80\x01\x09\x81\x01\x09"), (Example(a=9, b=None), b"\x30\x03\x80\x01\x09"), (Example(a=None, b=9), b"\x30\x03\x81\x01\x09"), (Example(a=None, b=None), b"\x30\x00"), ] ) def test_ok_optional_fields_with_explicit_encoding(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[typing.Union[int, None], asn1.Explicit(0)] b: Annotated[typing.Union[int, None], asn1.Explicit(1)] assert_roundtrips( [ ( Example(a=9, b=9), b"\x30\x0a\xa0\x03\x02\x01\x09\xa1\x03\x02\x01\x09", ), ( Example(a=9, b=None), b"\x30\x05\xa0\x03\x02\x01\x09", ), ( Example(a=None, b=9), b"\x30\x05\xa1\x03\x02\x01\x09", ), ( Example(a=None, b=None), b"\x30\x00", ), ] ) def test_fail_unexpected_fields_with_implicit_encoding(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[int, asn1.Implicit(0)] with pytest.raises( ValueError, match=re.escape( "error parsing asn1 value: ParseError { kind: UnexpectedTag" ), ): asn1.decode_der(Example, b"\x30\x03\x82\x01\x09") def test_fail_unexpected_fields_with_explicit_encoding(self) -> None: @asn1.sequence @_comparable_dataclass class Example: a: Annotated[int, asn1.Explicit(0)] with pytest.raises( ValueError, match=re.escape( "error parsing asn1 value: ParseError { kind: UnexpectedTag" ), ): asn1.decode_der(Example, b"\x30\x05\xa2\x03\x02\x01\x09")
TestSequence
python
doocs__leetcode
solution/3200-3299/3289.The Two Sneaky Numbers of Digitville/Solution2.py
{ "start": 0, "end": 384 }
class ____: def getSneakyNumbers(self, nums: List[int]) -> List[int]: n = len(nums) - 2 xx = nums[n] ^ nums[n + 1] for i in range(n): xx ^= i ^ nums[i] k = xx.bit_length() - 1 ans = [0, 0] for x in nums: ans[x >> k & 1] ^= x for i in range(n): ans[i >> k & 1] ^= i return ans
Solution
python
pydantic__pydantic
pydantic/errors.py
{ "start": 4496, "end": 4816 }
class ____(PydanticUserError): """An error raised during failures to generate a `CoreSchema` for some type. Attributes: message: Description of the error. """ def __init__(self, message: str) -> None: super().__init__(message, code='schema-for-unknown-type')
PydanticSchemaGenerationError
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/core/monitoring_job/event_stream.py
{ "start": 5088, "end": 6540 }
class ____(AirflowEvent): task_instance: TaskInstance metadata: dict[str, MetadataValue] @property def timestamp(self) -> float: return self.task_instance.end_date.timestamp() def persist_state( self, context: OpExecutionContext, airflow_data: AirflowDefinitionsData, airflow_instance: AirflowInstance, ) -> None: corresponding_run = get_dagster_run_for_airflow_repr(context, self.task_instance) externally_managed_runs = get_externally_managed_runs_from_handle( context, self.task_instance.task_handle, self.task_instance.run_id ) per_key_metadata = ( merge_dicts( *(_per_asset_metadata_from_run(context, run) for run in externally_managed_runs) ) if externally_managed_runs else {} ) for asset in airflow_data.mapped_asset_keys_by_task_handle[self.task_instance.task_handle]: # IMPROVEME: Add metadata to the materialization event. _report_materialization( context=context, corresponding_run=corresponding_run, materialization=AssetMaterialization( asset_key=asset, metadata=merge_dicts(per_key_metadata.get(asset, {}), self.metadata), ), airflow_event=self.task_instance, ) @record
TaskInstanceCompleted
python
vyperlang__vyper
vyper/semantics/types/primitives.py
{ "start": 8120, "end": 10549 }
class ____(NumericT): """ General integer type. All signed and unsigned ints from uint8 thru int256 Attributes ---------- bits : int Number of bits the value occupies in memory is_signed : bool Is the value signed? """ typeclass = "integer" _valid_literal = (vy_ast.Int,) _equality_attrs = ("is_signed", "bits") ast_type = int def __init__(self, is_signed, bits): super().__init__() self._is_signed = is_signed self._bits = bits @cached_property def _id(self): u = "u" if not self.is_signed else "" return f"{u}int{self.bits}" @cached_property def ast_bounds(self) -> Tuple[int, int]: return int_bounds(self.is_signed, self.bits) @cached_property def _invalid_ops(self): invalid_ops = (vy_ast.Not, vy_ast.Div) if not self.is_signed: return invalid_ops + (vy_ast.USub,) return invalid_ops def validate_numeric_op(self, node) -> None: try: super().validate_numeric_op(node) except VyperException as e: raise _add_div_hint(node, e) from None @classmethod # TODO maybe cache these three classmethods def signeds(cls) -> Tuple["IntegerT", ...]: return tuple(cls(is_signed=True, bits=i * 8) for i in RANGE_1_32) @classmethod def unsigneds(cls) -> Tuple["IntegerT", ...]: return tuple(cls(is_signed=False, bits=i * 8) for i in RANGE_1_32) @classmethod def all(cls) -> Tuple["IntegerT", ...]: return cls.signeds() + cls.unsigneds() @cached_property def abi_type(self) -> ABIType: return ABI_GIntM(self.bits, self.is_signed) def compare_type(self, other: VyperType) -> bool: # this function is performance sensitive # originally: # if not super().compare_type(other): # return False # return self.is_signed == other.is_signed and self.bits == other.bits return ( # noqa: E721 self.__class__ == other.__class__ and self.is_signed == other.is_signed # type: ignore and self.bits == other.bits # type: ignore ) # helper function for readability. # returns a uint<N> type. def UINT(bits): return IntegerT(False, bits) # helper function for readability. # returns an int<N> type. def SINT(bits): return IntegerT(True, bits)
IntegerT
python
tensorflow__tensorflow
tensorflow/python/data/experimental/ops/prefetching_ops.py
{ "start": 9750, "end": 11621 }
class ____(dataset_ops.UnaryDataset): """A `Dataset` that maps a function over elements in its using a GPU.""" def __init__(self, input_dataset, map_func, use_inter_op_parallelism=True): """See `Dataset.map()` for details.""" self._input_dataset = input_dataset self._use_inter_op_parallelism = use_inter_op_parallelism self._map_func = structured_function.StructuredFunctionWrapper( map_func, self._transformation_name(), dataset=input_dataset, defun_kwargs={"experimental_ints_on_device": True}) variant_tensor = ged_ops.experimental_map_dataset( self._input_dataset._variant_tensor, # pylint: disable=protected-access self._map_func.function.captured_inputs, f=self._map_func.function, use_inter_op_parallelism=self._use_inter_op_parallelism, **self._flat_structure) super(_MapOnGpuDataset, self).__init__(input_dataset, variant_tensor) def _functions(self): return [self._map_func] @property def element_spec(self): return self._map_func.output_structure def _transformation_name(self): return "map_on_gpu()" def map_on_gpu(map_func): """Maps `map_func` across the elements of this dataset. NOTE: This is a highly experimental version of `tf.data.Dataset.map` that runs `map_func` on GPU. It must be used after applying the `tf.data.experimental.copy_to_device` transformation with a GPU device argument. Args: map_func: A function mapping a nested structure of tensors (having shapes and types defined by `self.output_shapes` and `self.output_types`) to another nested structure of tensors. Returns: A `Dataset` transformation function, which can be passed to `tf.data.Dataset.apply`. """ def _apply_fn(dataset): return _MapOnGpuDataset(dataset, map_func) return _apply_fn
_MapOnGpuDataset
python
chroma-core__chroma
chromadb/auth/token_authn/__init__.py
{ "start": 3594, "end": 8316 }
class ____(ServerAuthenticationProvider): """ Server authentication provider for token-based auth. The provider will - On initialization, read the users from the file specified in `chroma_server_authn_credentials_file`. This file must be a well-formed YAML file with a top-level array called `users`. Each user must have an `id` field and a `tokens` (string array) field. - On each request, check the token in the header specified by `chroma_auth_token_transport_header`. If the configured header is "Authorization", the token is expected to be a bearer token. - If the token is valid, the server will return the user identity associated with the token. """ def __init__(self, system: System) -> None: super().__init__(system) self._settings = system.settings if system.settings.chroma_auth_token_transport_header: _check_allowed_token_headers( system.settings.chroma_auth_token_transport_header ) self._token_transport_header = TokenTransportHeader( system.settings.chroma_auth_token_transport_header ) else: self._token_transport_header = TokenTransportHeader.AUTHORIZATION self._token_user_mapping: Dict[str, User] = {} creds = self.read_creds_or_creds_file() # If we only get one cred, assume it's just a valid token. if len(creds) == 1: self._token_user_mapping[creds[0]] = User( id="anonymous", tenant="*", databases=["*"], role="anonymous", tokens=[creds[0]], ) return self._users = cast(List[User], yaml.safe_load("\n".join(creds))["users"]) for user in self._users: if "tokens" not in user: raise ValueError("User missing tokens") if "tenant" not in user: user["tenant"] = "*" if "databases" not in user: user["databases"] = ["*"] for token in user["tokens"]: _check_token(token) if ( token in self._token_user_mapping and self._token_user_mapping[token] != user ): raise ValueError( f"Token {token} already in use: wanted to use it for " f"user {user['id']} but it's already in use by " f"user {self._token_user_mapping[token]}" ) self._token_user_mapping[token] = user @trace_method( "TokenAuthenticationServerProvider.authenticate", OpenTelemetryGranularity.ALL ) @override def authenticate_or_raise(self, headers: Dict[str, str]) -> UserIdentity: try: if self._token_transport_header.value.lower() not in headers.keys(): raise AuthError( f"Authorization header '{self._token_transport_header.value}' not found" ) token = headers[self._token_transport_header.value.lower()] if self._token_transport_header == TokenTransportHeader.AUTHORIZATION: if not token.startswith("Bearer "): raise AuthError("Bearer not found in Authorization header") token = re.sub(r"^Bearer ", "", token) token = token.strip() _check_token(token) if token not in self._token_user_mapping: raise AuthError("Invalid credentials: Token not found}") user_identity = UserIdentity( user_id=self._token_user_mapping[token]["id"], tenant=self._token_user_mapping[token]["tenant"], databases=self._token_user_mapping[token]["databases"], ) return user_identity except AuthError as e: logger.debug( f"TokenAuthenticationServerProvider.authenticate failed: {repr(e)}" ) except Exception as e: tb = traceback.extract_tb(e.__traceback__) # Get the last call stack last_call_stack = tb[-1] line_number = last_call_stack.lineno filename = last_call_stack.filename logger.debug( "TokenAuthenticationServerProvider.authenticate failed: " f"Failed to authenticate {type(e).__name__} at {filename}:{line_number}" ) time.sleep( random.uniform(0.001, 0.005) ) # add some jitter to avoid timing attacks raise ChromaAuthError()
TokenAuthenticationServerProvider
python
spack__spack
lib/spack/spack/enums.py
{ "start": 174, "end": 403 }
class ____(enum.Flag): """Enum flag to facilitate querying status from the DB""" INSTALLED = enum.auto() DEPRECATED = enum.auto() MISSING = enum.auto() ANY = INSTALLED | DEPRECATED | MISSING
InstallRecordStatus
python
kamyu104__LeetCode-Solutions
Python/minimum-time-to-finish-the-race.py
{ "start": 66, "end": 1082 }
class ____(object): def minimumFinishTime(self, tires, changeTime, numLaps): """ :type tires: List[List[int]] :type changeTime: int :type numLaps: int :rtype: int """ def ceil_log2(x): return (x-1).bit_length() dp = [float("inf")]*ceil_log2(changeTime+1) # dp[i]: min time to complete i+1 laps without changing a tire for f, r in tires: total = curr = f cnt = 0 while curr < changeTime+f: # at worst (f, r) = (1, 2) => 2^(cnt-1) < changeTime+1 => cnt < ceil(log2(changeTime+1)) dp[cnt] = min(dp[cnt], total) curr *= r total += curr cnt += 1 dp2 = [float("inf")]*numLaps # dp2[i]: min time to complete i+1 laps with changing zero or more tires for i in xrange(numLaps): dp2[i] = min((dp2[i-j-1]+changeTime if i-j-1 >= 0 else 0)+dp[j] for j in xrange(min(i+1, len(dp)))) return dp2[-1]
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/del1.py
{ "start": 885, "end": 1162 }
class ____: @property def x(self) -> str: ... @x.setter def x(self, value: str) -> None: ... @x.deleter def x(self) -> None: ... c = ClassC() c.x = "x" reveal_type(c.x, expected_text="Literal['x']") del c.x reveal_type(c.x, expected_text="str")
ClassC
python
ray-project__ray
rllib/models/preprocessors.py
{ "start": 9038, "end": 10612 }
class ____(Preprocessor): """Preprocesses each tuple element, then flattens it all into a vector. RLlib models will unpack the flattened output before _build_layers_v2(). """ @override(Preprocessor) def _init_shape(self, obs_space: gym.Space, options: dict) -> List[int]: assert isinstance(self._obs_space, gym.spaces.Tuple) size = 0 self.preprocessors = [] for i in range(len(self._obs_space.spaces)): space = self._obs_space.spaces[i] logger.debug("Creating sub-preprocessor for {}".format(space)) preprocessor_class = get_preprocessor(space) if preprocessor_class is not None: preprocessor = preprocessor_class(space, self._options) size += preprocessor.size else: preprocessor = None size += int(np.prod(space.shape)) self.preprocessors.append(preprocessor) return (size,) @override(Preprocessor) def transform(self, observation: TensorType) -> np.ndarray: self.check_shape(observation) array = np.zeros(self.shape, dtype=np.float32) self.write(observation, array, 0) return array @override(Preprocessor) def write(self, observation: TensorType, array: np.ndarray, offset: int) -> None: assert len(observation) == len(self.preprocessors), observation for o, p in zip(observation, self.preprocessors): p.write(o, array, offset) offset += p.size @OldAPIStack
TupleFlatteningPreprocessor
python
tensorflow__tensorflow
tensorflow/python/keras/constraints.py
{ "start": 2881, "end": 4229 }
class ____(Constraint): """MaxNorm weight constraint. Constrains the weights incident to each hidden unit to have a norm less than or equal to a desired value. Also available via the shortcut function `tf.keras.constraints.max_norm`. Args: max_value: the maximum norm value for the incoming weights. axis: integer, axis along which to calculate weight norms. For instance, in a `Dense` layer the weight matrix has shape `(input_dim, output_dim)`, set `axis` to `0` to constrain each weight vector of length `(input_dim,)`. In a `Conv2D` layer with `data_format="channels_last"`, the weight tensor has shape `(rows, cols, input_depth, output_depth)`, set `axis` to `[0, 1, 2]` to constrain the weights of each filter tensor of size `(rows, cols, input_depth)`. """ def __init__(self, max_value=2, axis=0): self.max_value = max_value self.axis = axis @doc_controls.do_not_generate_docs def __call__(self, w): norms = backend.sqrt( math_ops.reduce_sum(math_ops.square(w), axis=self.axis, keepdims=True)) desired = backend.clip(norms, 0, self.max_value) return w * (desired / (backend.epsilon() + norms)) @doc_controls.do_not_generate_docs def get_config(self): return {'max_value': self.max_value, 'axis': self.axis}
MaxNorm
python
openai__openai-python
src/openai/types/realtime/realtime_conversation_item_assistant_message_param.py
{ "start": 284, "end": 914 }
class ____(TypedDict, total=False): audio: str """ Base64-encoded audio bytes, these will be parsed as the format specified in the session output audio type configuration. This defaults to PCM 16-bit 24kHz mono if not specified. """ text: str """The text content.""" transcript: str """ The transcript of the audio content, this will always be present if the output type is `audio`. """ type: Literal["output_text", "output_audio"] """ The content type, `output_text` or `output_audio` depending on the session `output_modalities` configuration. """
Content
python
ray-project__ray
python/ray/serve/_private/deployment_state.py
{ "start": 2644, "end": 2770 }
class ____(Enum): NONE = 1 SUCCEEDED = 2 APP_FAILURE = 3 ACTOR_CRASHED = 4 @dataclass
ReplicaHealthCheckResponse
python
fsspec__filesystem_spec
fsspec/implementations/cache_mapper.py
{ "start": 1900, "end": 2421 }
class ____(AbstractCacheMapper): """Cache mapper that uses a hash of the remote URL.""" def __call__(self, path: str) -> str: return hashlib.sha256(path.encode()).hexdigest() def create_cache_mapper(same_names: bool) -> AbstractCacheMapper: """Factory method to create cache mapper for backward compatibility with ``CachingFileSystem`` constructor using ``same_names`` kwarg. """ if same_names: return BasenameCacheMapper() else: return HashCacheMapper()
HashCacheMapper
python
pypa__warehouse
warehouse/macaroons/models.py
{ "start": 607, "end": 4446 }
class ____(db.Model): __tablename__ = "macaroons" __table_args__ = ( UniqueConstraint( "description", "user_id", name="_user_macaroons_description_uc" ), CheckConstraint( "(user_id::text IS NULL) <> (oidc_publisher_id::text IS NULL)", name="_user_xor_oidc_publisher_macaroon", ), ) # Macaroons come in two forms: they either belong to a user, or they # authenticate for one or more projects. # * In the user case, a Macaroon has an associated user, and *might* have # additional project scope restrictions as part of its caveats. # * In the project case, a Macaroon does *not* have an explicit associated # project. Instead, depending on how its used (its request context), # it identifies one of the projects scoped in its caveats. user_id: Mapped[UUID | None] = mapped_column( PG_UUID(as_uuid=True), ForeignKey("users.id"), index=True, ) oidc_publisher_id: Mapped[UUID | None] = mapped_column( PG_UUID(as_uuid=True), ForeignKey("oidc_publishers.id"), index=True, ) # Store some information about the Macaroon to give users some mechanism # to differentiate between them. description: Mapped[str] created: Mapped[datetime_now] last_used: Mapped[datetime | None] # FIXME: Deprecated in favor of `Macaroon.caveats()`. # Human-readable "permissions" for this macaroon, corresponding to the # body of the permissions ("V1") caveat. permissions_caveat: Mapped[dict] = mapped_column( JSONB, server_default=sql.text("'{}'") ) # The caveats that were attached to this Macaroon when we generated it. _caveats: Mapped[list] = mapped_column( "caveats", JSONB, server_default=sql.text("'{}'"), comment=( "The list of caveats that were attached to this Macaroon when we " "generated it. Users can add additional caveats at any time without " "communicating those additional caveats to us, which would not be " "reflected in this data, and thus this field must only be used for " "informational purposes and must not be used during the authorization " "or authentication process. Older Macaroons may be missing caveats as " "previously only the legacy permissions caveat were stored." ), ) @property def caveats(self) -> list[Caveat]: return [caveats_deserialize(c) for c in self._caveats] @caveats.setter def caveats(self, caveats: list[Caveat]): self._caveats = [list(caveats_serialize(c)) for c in caveats] # Additional state associated with this macaroon. # For OIDC publisher-issued macaroons, this will contain a subset of OIDC claims. additional: Mapped[dict | None] = mapped_column(JSONB) # It might be better to move this default into the database, that way we # make it less likely that something does it incorrectly (since the # default would be to generate a random key). However, it appears the # PostgreSQL pgcrypto extension uses OpenSSL RAND_bytes if available # instead of urandom. This is less than optimal, and we would generally # prefer to just always use urandom. Thus we'll do this ourselves here # in our application. key: Mapped[bytes] = mapped_column(default=_generate_key) # Intentionally not using a back references here, since we express # relationships in terms of the "other" side of the relationship. user: Mapped[User | None] = orm.relationship(lazy=True, viewonly=True) # TODO: Can't annotate this as "OIDCPublisher" because that would create a # circular import. oidc_publisher = orm.relationship("OIDCPublisher", lazy=True, viewonly=True)
Macaroon