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
scikit-learn__scikit-learn
sklearn/utils/tests/test_validation.py
{ "start": 70629, "end": 82823 }
class ____(BaseEstimator): def fit(self, X, y=None): validate_data(self, X, reset=True) return self def transform(self, X): return X def get_feature_names_out(self, input_features=None): return _check_feature_names_in(self, input_features) def test_check_feature_names_in(): """Check behavior of check_feature_names_in for arrays.""" X = np.array([[0.0, 1.0, 2.0]]) est = PassthroughTransformer().fit(X) names = est.get_feature_names_out() assert_array_equal(names, ["x0", "x1", "x2"]) incorrect_len_names = ["x10", "x1"] with pytest.raises(ValueError, match="input_features should have length equal to"): est.get_feature_names_out(incorrect_len_names) # remove n_feature_in_ del est.n_features_in_ with pytest.raises(ValueError, match="Unable to generate feature names"): est.get_feature_names_out() def test_check_feature_names_in_pandas(): """Check behavior of check_feature_names_in for pandas dataframes.""" pd = pytest.importorskip("pandas") names = ["a", "b", "c"] df = pd.DataFrame([[0.0, 1.0, 2.0]], columns=names) est = PassthroughTransformer().fit(df) names = est.get_feature_names_out() assert_array_equal(names, ["a", "b", "c"]) with pytest.raises(ValueError, match="input_features is not equal to"): est.get_feature_names_out(["x1", "x2", "x3"]) def test_check_response_method_unknown_method(): """Check the error message when passing an unknown response method.""" err_msg = ( "RandomForestRegressor has none of the following attributes: unknown_method." ) with pytest.raises(AttributeError, match=err_msg): _check_response_method(RandomForestRegressor(), "unknown_method") @pytest.mark.parametrize( "response_method", ["decision_function", "predict_proba", "predict"] ) def test_check_response_method_not_supported_response_method(response_method): """Check the error message when a response method is not supported by the estimator.""" err_msg = ( f"EstimatorWithFit has none of the following attributes: {response_method}." ) with pytest.raises(AttributeError, match=err_msg): _check_response_method(EstimatorWithFit(), response_method) def test_check_response_method_list_str(): """Check that we can pass a list of ordered method.""" method_implemented = ["predict_proba"] my_estimator = _MockEstimatorOnOffPrediction(method_implemented) X = "mocking_data" # raise an error when no methods are defined response_method = ["decision_function", "predict"] err_msg = ( "_MockEstimatorOnOffPrediction has none of the following attributes: " f"{', '.join(response_method)}." ) with pytest.raises(AttributeError, match=err_msg): _check_response_method(my_estimator, response_method)(X) # check that we don't get issue when one of the method is defined response_method = ["decision_function", "predict_proba"] method_name_predicting = _check_response_method(my_estimator, response_method)(X) assert method_name_predicting == "predict_proba" # check the order of the methods returned method_implemented = ["predict_proba", "predict"] my_estimator = _MockEstimatorOnOffPrediction(method_implemented) response_method = ["decision_function", "predict", "predict_proba"] method_name_predicting = _check_response_method(my_estimator, response_method)(X) assert method_name_predicting == "predict" def test_boolean_series_remains_boolean(): """Regression test for gh-25145""" pd = importorskip("pandas") res = check_array(pd.Series([True, False]), ensure_2d=False) expected = np.array([True, False]) assert res.dtype == expected.dtype assert_array_equal(res, expected) @pytest.mark.parametrize("input_values", [[0, 1, 0, 1, 0, np.nan], [0, 1, 0, 1, 0, 1]]) def test_pandas_array_returns_ndarray(input_values): """Check pandas array with extensions dtypes returns a numeric ndarray. Non-regression test for gh-25637. """ pd = importorskip("pandas") input_series = pd.array(input_values, dtype="Int32") result = check_array( input_series, dtype=None, ensure_2d=False, allow_nd=False, ensure_all_finite=False, ) assert np.issubdtype(result.dtype.kind, np.floating) assert_allclose(result, input_values) @skip_if_array_api_compat_not_configured def test_check_array_array_api_has_non_finite(): """Checks that Array API arrays checks non-finite correctly.""" xp = pytest.importorskip("array_api_strict") X_nan = xp.asarray([[xp.nan, 1, 0], [0, xp.nan, 3]], dtype=xp.float32) with config_context(array_api_dispatch=True): with pytest.raises(ValueError, match="Input contains NaN."): check_array(X_nan) X_inf = xp.asarray([[xp.inf, 1, 0], [0, xp.inf, 3]], dtype=xp.float32) with config_context(array_api_dispatch=True): with pytest.raises(ValueError, match="infinity or a value too large"): check_array(X_inf) @pytest.mark.parametrize( "extension_dtype, regular_dtype", [ ("boolean", "bool"), ("Int64", "int64"), ("Float64", "float64"), ("category", "object"), ], ) @pytest.mark.parametrize("include_object", [True, False]) def test_check_array_multiple_extensions( extension_dtype, regular_dtype, include_object ): """Check pandas extension arrays give the same result as non-extension arrays.""" pd = pytest.importorskip("pandas") X_regular = pd.DataFrame( { "a": pd.Series([1, 0, 1, 0], dtype=regular_dtype), "c": pd.Series([9, 8, 7, 6], dtype="int64"), } ) if include_object: X_regular["b"] = pd.Series(["a", "b", "c", "d"], dtype="object") X_extension = X_regular.assign(a=X_regular["a"].astype(extension_dtype)) X_regular_checked = check_array(X_regular, dtype=None) X_extension_checked = check_array(X_extension, dtype=None) assert_array_equal(X_regular_checked, X_extension_checked) def test_num_samples_dataframe_protocol(): """Use the DataFrame interchange protocol to get n_samples from polars.""" pl = pytest.importorskip("polars") df = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) assert _num_samples(df) == 3 @pytest.mark.parametrize( "sparse_container", CSR_CONTAINERS + CSC_CONTAINERS + COO_CONTAINERS + DIA_CONTAINERS, ) @pytest.mark.parametrize("output_format", ["csr", "csc", "coo"]) def test_check_array_dia_to_int32_indexed_csr_csc_coo(sparse_container, output_format): """Check the consistency of the indices dtype with sparse matrices/arrays.""" X = sparse_container([[0, 1], [1, 0]], dtype=np.float64) # Explicitly set the dtype of the indexing arrays if hasattr(X, "offsets"): # DIA matrix X.offsets = X.offsets.astype(np.int32) elif hasattr(X, "row") and hasattr(X, "col"): # COO matrix X.row = X.row.astype(np.int32) elif hasattr(X, "indices") and hasattr(X, "indptr"): # CSR or CSC matrix X.indices = X.indices.astype(np.int32) X.indptr = X.indptr.astype(np.int32) X_checked = check_array(X, accept_sparse=output_format) if output_format == "coo": assert X_checked.row.dtype == np.int32 assert X_checked.col.dtype == np.int32 else: # output_format in ["csr", "csc"] assert X_checked.indices.dtype == np.int32 assert X_checked.indptr.dtype == np.int32 @pytest.mark.parametrize("sequence", [[np.array(1), np.array(2)], [[1, 2], [3, 4]]]) def test_to_object_array(sequence): out = _to_object_array(sequence) assert isinstance(out, np.ndarray) assert out.dtype.kind == "O" assert out.ndim == 1 def test_column_or_1d(): EXAMPLES = [ ("binary", ["spam", "egg", "spam"]), ("binary", [0, 1, 0, 1]), ("continuous", np.arange(10) / 20.0), ("multiclass", [1, 2, 3]), ("multiclass", [0, 1, 2, 2, 0]), ("multiclass", [[1], [2], [3]]), ("multilabel-indicator", [[0, 1, 0], [0, 0, 1]]), ("multiclass-multioutput", [[1, 2, 3]]), ("multiclass-multioutput", [[1, 1], [2, 2], [3, 1]]), ("multiclass-multioutput", [[5, 1], [4, 2], [3, 1]]), ("multiclass-multioutput", [[1, 2, 3]]), ("continuous-multioutput", np.arange(30).reshape((-1, 3))), ] for y_type, y in EXAMPLES: if y_type in ["binary", "multiclass", "continuous"]: assert_array_equal(column_or_1d(y), np.ravel(y)) else: with pytest.raises(ValueError): column_or_1d(y) def test__is_polars_df(): """Check that _is_polars_df return False for non-dataframe objects.""" class LooksLikePolars: def __init__(self): self.columns = ["a", "b"] self.schema = ["a", "b"] assert not _is_polars_df(LooksLikePolars()) def test_check_array_writeable_np(): """Check the behavior of check_array when a writeable array is requested without copy if possible, on numpy arrays. """ X = np.random.uniform(size=(10, 10)) out = check_array(X, copy=False, force_writeable=True) # X is already writeable, no copy is needed assert np.may_share_memory(out, X) assert out.flags.writeable X.flags.writeable = False out = check_array(X, copy=False, force_writeable=True) # X is not writeable, a copy is made assert not np.may_share_memory(out, X) assert out.flags.writeable def test_check_array_writeable_mmap(): """Check the behavior of check_array when a writeable array is requested without copy if possible, on a memory-map. A common situation is when a meta-estimators run in parallel using multiprocessing with joblib, which creates read-only memory-maps of large arrays. """ X = np.random.uniform(size=(10, 10)) mmap = create_memmap_backed_data(X, mmap_mode="w+") out = check_array(mmap, copy=False, force_writeable=True) # mmap is already writeable, no copy is needed assert np.may_share_memory(out, mmap) assert out.flags.writeable mmap = create_memmap_backed_data(X, mmap_mode="r") out = check_array(mmap, copy=False, force_writeable=True) # mmap is read-only, a copy is made assert not np.may_share_memory(out, mmap) assert out.flags.writeable def test_check_array_writeable_df(): """Check the behavior of check_array when a writeable array is requested without copy if possible, on a dataframe. """ pd = pytest.importorskip("pandas") X = np.random.uniform(size=(10, 10)) df = pd.DataFrame(X, copy=False) out = check_array(df, copy=False, force_writeable=True) # df is backed by a writeable array, no copy is needed assert np.may_share_memory(out, df) assert out.flags.writeable X.flags.writeable = False df = pd.DataFrame(X, copy=False) out = check_array(df, copy=False, force_writeable=True) # df is backed by a read-only array, a copy is made assert not np.may_share_memory(out, df) assert out.flags.writeable @skip_if_array_api_compat_not_configured def test_check_array_on_sparse_inputs_with_array_api_enabled(): X_sp = sp.csr_array([[0, 1, 0], [1, 0, 1]]) with config_context(array_api_dispatch=True): assert sp.issparse(check_array(X_sp, accept_sparse=True)) with pytest.raises(TypeError): check_array(X_sp) @pytest.mark.parametrize( ["X", "estimator", "expected_error_message"], [ ( np.array([[[1, 2], [3, 4]], [[1, 2], [3, 4]]]), RandomForestRegressor(), "Found array with dim 3, while dim <= 2 is required by " "RandomForestRegressor.", ), ( np.array([[[1, 2], [3, 4]], [[1, 2], [3, 4]]]), None, "Found array with dim 3, while dim <= 2 is required.", ), ], ) def test_check_array_allow_nd_errors(X, estimator, expected_error_message): with pytest.raises(ValueError, match=expected_error_message): check_array(X, estimator=estimator)
PassthroughTransformer
python
Pylons__pyramid
tests/test_request.py
{ "start": 24063, "end": 24256 }
class ____: raise_exc = None def __init__(self, route=None, raise_exc=False): self.route = route def get_route(self, route_name): return self.route
DummyRoutesMapper
python
simonw__sqlite-utils
sqlite_utils/utils.py
{ "start": 13692, "end": 17099 }
class ____: def __init__(self, *args): self.args = args def __iter__(self): yield from self.args[0] def update(self, value): pass @contextlib.contextmanager def progressbar(*args, **kwargs): silent = kwargs.pop("silent") if silent: yield NullProgressBar(*args) else: with click.progressbar(*args, **kwargs) as bar: yield bar def _compile_code(code, imports, variable="value"): globals = {"r": recipes, "recipes": recipes} # If user defined a convert() function, return that try: exec(code, globals) return globals["convert"] except (AttributeError, SyntaxError, NameError, KeyError, TypeError): pass # Try compiling their code as a function instead body_variants = [code] # If single line and no 'return', try adding the return if "\n" not in code and not code.strip().startswith("return "): body_variants.insert(0, "return {}".format(code)) code_o = None for variant in body_variants: new_code = ["def fn({}):".format(variable)] for line in variant.split("\n"): new_code.append(" {}".format(line)) try: code_o = compile("\n".join(new_code), "<string>", "exec") break except SyntaxError: # Try another variant, e.g. for 'return row["column"] = 1' continue if code_o is None: raise SyntaxError("Could not compile code") for import_ in imports: globals[import_.split(".")[0]] = __import__(import_) exec(code_o, globals) return globals["fn"] def chunks(sequence: Iterable, size: int) -> Iterable[Iterable]: """ Iterate over chunks of the sequence of the given size. :param sequence: Any Python iterator :param size: The size of each chunk """ iterator = iter(sequence) for item in iterator: yield itertools.chain([item], itertools.islice(iterator, size - 1)) def hash_record(record: Dict, keys: Optional[Iterable[str]] = None): """ ``record`` should be a Python dictionary. Returns a sha1 hash of the keys and values in that record. If ``keys=`` is provided, uses just those keys to generate the hash. Example usage:: from sqlite_utils.utils import hash_record hashed = hash_record({"name": "Cleo", "twitter": "CleoPaws"}) # Or with the keys= option: hashed = hash_record( {"name": "Cleo", "twitter": "CleoPaws", "age": 7}, keys=("name", "twitter") ) :param record: Record to generate a hash for :param keys: Subset of keys to use for that hash """ to_hash = record if keys is not None: to_hash = {key: record[key] for key in keys} return hashlib.sha1( json.dumps(to_hash, separators=(",", ":"), sort_keys=True, default=repr).encode( "utf8" ) ).hexdigest() def _flatten(d): for key, value in d.items(): if isinstance(value, dict): for key2, value2 in _flatten(value): yield key + "_" + key2, value2 else: yield key, value def flatten(row: dict) -> dict: """ Turn a nested dict e.g. ``{"a": {"b": 1}}`` into a flat dict: ``{"a_b": 1}`` :param row: A Python dictionary, optionally with nested dictionaries """ return dict(_flatten(row))
NullProgressBar
python
doocs__leetcode
solution/2000-2099/2061.Number of Spaces Cleaning Robot Cleaned/Solution2.py
{ "start": 0, "end": 526 }
class ____: def numberOfCleanRooms(self, room: List[List[int]]) -> int: dirs = (0, 1, 0, -1, 0) i = j = k = 0 ans = 0 vis = set() while (i, j, k) not in vis: vis.add((i, j, k)) ans += room[i][j] == 0 room[i][j] = -1 x, y = i + dirs[k], j + dirs[k + 1] if 0 <= x < len(room) and 0 <= y < len(room[0]) and room[x][y] != 1: i, j = x, y else: k = (k + 1) % 4 return ans
Solution
python
kamyu104__LeetCode-Solutions
Python/maximum-compatibility-score-sum.py
{ "start": 101, "end": 2187 }
class ____(object): def maxCompatibilitySum(self, students, mentors): """ :type students: List[List[int]] :type mentors: List[List[int]] :rtype: int """ # Template translated from: # https://github.com/kth-competitive-programming/kactl/blob/main/content/graph/WeightedMatching.h def hungarian(a): # Time: O(n^2 * m), Space: O(n + m) if not a: return 0, [] n, m = len(a)+1, len(a[0])+1 u, v, p, ans = [0]*n, [0]*m, [0]*m, [0]*(n-1) for i in xrange(1, n): p[0] = i j0 = 0 # add "dummy" worker 0 dist, pre = [float("inf")]*m, [-1]*m done = [False]*(m+1) while True: # dijkstra done[j0] = True i0, j1, delta = p[j0], None, float("inf") for j in xrange(1, m): if done[j]: continue cur = a[i0-1][j-1]-u[i0]-v[j] if cur < dist[j]: dist[j], pre[j] = cur, j0 if dist[j] < delta: delta, j1 = dist[j], j for j in xrange(m): if done[j]: u[p[j]] += delta v[j] -= delta else: dist[j] -= delta j0 = j1 if not p[j0]: break while j0: # update alternating path j1 = pre[j0] p[j0], j0 = p[j1], j1 for j in xrange(1, m): if p[j]: ans[p[j]-1] = j-1 return -v[0], ans # min cost def score(s, m): return sum(int(a == b) for a, b in itertools.izip(s, m)) return -hungarian([[-score(s, m) for m in mentors] for s in students])[0] # Time: O(m * (n + 2^m)) # Space: O(2^m) # dp solution
Solution
python
pytorch__pytorch
torch/ao/quantization/fx/tracer.py
{ "start": 219, "end": 477 }
class ____(torch.fx.proxy.ScopeContextManager): def __init__( self, scope: Scope, current_module: torch.nn.Module, current_module_path: str ): super().__init__(scope, Scope(current_module_path, type(current_module)))
ScopeContextManager
python
PyCQA__pylint
tests/functional/i/import_outside_toplevel.py
{ "start": 452, "end": 970 }
class ____: import tokenize # [import-outside-toplevel] def j(self): import trace # [import-outside-toplevel] def k(flag): if flag: import tabnanny # [import-outside-toplevel] def j(): from collections import defaultdict # [import-outside-toplevel] def m(): from math import sin as sign, cos as cosplay # [import-outside-toplevel] # Test allow-any-import-level setting def n(): import astroid def o(): import notastroid # [import-error, import-outside-toplevel]
C
python
davidhalter__jedi
test/completion/dynamic_arrays.py
{ "start": 1606, "end": 2876 }
class ____(): pass lst = [1] lst.append(1.0) lst += [C()] s = set(lst) s.add("") s += [D()] lst = list(s) lst.append({}) lst += [E()] #? dict() int() float() str() C() D() E() lst[0] # ----------------- # functions # ----------------- def arr_append(arr4, a): arr4.append(a) def add_to_arr(arr2, a): arr2.append(a) return arr2 def app(a): arr3.append(a) arr3 = [1.0] res = add_to_arr(arr3, 1) arr_append(arr3, 'str') app(set()) #? float() str() int() set() arr3[10] #? float() str() int() set() res[10] # ----------------- # returns, special because the module dicts are not correct here. # ----------------- def blub(): a = [] a.append(1.0) #? float() a[0] return a #? float() blub()[0] # list with default def blub(): a = list([1]) a.append(1.0) return a #? int() float() blub()[0] # empty list def blub(): a = list() a.append(1.0) return a #? float() blub()[0] # with if def blub(): if 1: a = [] a.append(1.0) return a #? float() blub()[0] # with else clause def blub(): if random.choice([0, 1]): 1 else: a = [] a.append(1) return a #? int() blub()[0] # ----------------- # returns, the same for classes # -----------------
E
python
ansible__ansible
test/units/_internal/templating/test_access.py
{ "start": 1465, "end": 3403 }
class ____(ExampleMaskingSingletonTagAccessNotifier1): ... def test_ansibleaccesscontext_untagged(): # accessing untagged objects should always succeed, be a no-op, and return the original value for v in untagged_values: AnsibleAccessContext.current().access(v) def test_ansibleaccesscontext_notify(): tagged_values = [AnsibleTagHelper.tag(v, [ExampleSingletonTag(), ExampleTagWithContent(content_str='replacement')]) for v in untagged_values] instance_access_list = [] singleton_access_list = [] with ExampleTagWithContentAccessNotifier(instance_access_list): with ExampleSingletonTagAccessNotifier(singleton_access_list): for tv in tagged_values: AnsibleAccessContext.current().access(tv) assert [v.obj for v in instance_access_list] == [v.obj for v in singleton_access_list] == tagged_values def test_mixed_mask_unmask(): """Ensure that only the innermost instance of each type of a masking access context is notified, while non-masking contexts are always notified.""" value = ExampleSingletonTag().tag('blah') access_log = [] with (ExampleSingletonTagAccessNotifier(access_log) as outer_nonmasked, ExampleMaskingSingletonTagAccessNotifier1(access_log), # masked ExampleMaskingSingletonTagAccessNotifier2(access_log), ExampleMaskingSingletonTagAccessNotifier1(access_log) as inner_masked_1, ExampleMaskingSingletonTagAccessNotifier2(access_log) as inner_masked_2, ExampleSingletonTagAccessNotifier(access_log) as inner_nonmasked, ): AnsibleAccessContext.current().access(value) assert len(access_log) == 4 assert access_log == [ LoggedAccess(inner_nonmasked, value), LoggedAccess(inner_masked_2, value), LoggedAccess(inner_masked_1, value), LoggedAccess(outer_nonmasked, value) ]
ExampleMaskingSingletonTagAccessNotifier2
python
django__django
tests/custom_managers/models.py
{ "start": 473, "end": 579 }
class ____(models.Manager): def get_fun_people(self): return self.filter(fun=True)
PersonManager
python
ipython__ipython
tests/test_pretty.py
{ "start": 1034, "end": 1127 }
class ____(object): def _repr_pretty_(self, p, cycle): p.text("Dummy1(...)")
Dummy1
python
plotly__plotly.py
plotly/graph_objs/bar/selected/_textfont.py
{ "start": 233, "end": 2400 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "bar.selected" _path_str = "bar.selected.textfont" _valid_props = {"color"} @property def color(self): """ Sets the text font color of selected points. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def _prop_descriptions(self): return """\ color Sets the text font color of selected points. """ def __init__(self, arg=None, color=None, **kwargs): """ Construct a new Textfont object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.bar.selected.Textfont` color Sets the text font color of selected points. Returns ------- Textfont """ super().__init__("textfont") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.bar.selected.Textfont constructor must be a dict or an instance of :class:`plotly.graph_objs.bar.selected.Textfont`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Textfont
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_macro01.py
{ "start": 339, "end": 2230 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("macro01.xlsm") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() workbook.add_vba_project(self.vba_dir + "vbaProject01.bin") worksheet.write("A1", 123) workbook.close() self.assertExcelEqual() def test_create_file_in_memory(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename, {"in_memory": True}) worksheet = workbook.add_worksheet() workbook.add_vba_project(self.vba_dir + "vbaProject01.bin") worksheet.write("A1", 123) workbook.close() self.assertExcelEqual() def test_create_file_bytes_io(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() with open(self.vba_dir + "vbaProject01.bin", "rb") as vba_file: vba_data = BytesIO(vba_file.read()) workbook.add_vba_project(vba_data, True) worksheet.write("A1", 123) workbook.close() self.assertExcelEqual() def test_create_file_bytes_io_in_memory(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename, {"in_memory": True}) worksheet = workbook.add_worksheet() with open(self.vba_dir + "vbaProject01.bin", "rb") as vba_file: vba_data = BytesIO(vba_file.read()) workbook.add_vba_project(vba_data, True) worksheet.write("A1", 123) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-of-a-path-with-special-roads.py
{ "start": 116, "end": 1322 }
class ____(object): def minimumCost(self, start, target, specialRoads): """ :type start: List[int] :type target: List[int] :type specialRoads: List[List[int]] :rtype: int """ start, target = tuple(start), tuple(target) adj = collections.defaultdict(list, {target:[]}) for x1, y1, x2, y2, c in specialRoads: adj[x1, y1].append((x2, y2, c)) dist = {start:0} lookup = set() while len(lookup) != len(dist): d, x1, y1 = min((dist[x1, y1], x1, y1) for x1, y1 in dist.iterkeys() if (x1, y1) not in lookup) lookup.add((x1, y1)) if (x1, y1) == target: return d for x2, y2, c in adj[x1, y1]: if not ((x2, y2) not in dist or dist[x2, y2] > d+c): continue dist[x2, y2] = d+c for x2, y2 in adj.iterkeys(): if not ((x2, y2) not in dist or dist[x2, y2] > d+abs(x2-x1)+abs(y2-y1)): continue dist[x2, y2] = d+abs(x2-x1)+abs(y2-y1) # Time: O(n^2 * logn) # Space: O(n^2) import collections import heapq # dijkstra's algorithm
Solution
python
Farama-Foundation__Gymnasium
gymnasium/error.py
{ "start": 1681, "end": 1780 }
class ____(Error): """Raised when given an invalid value for a probability."""
InvalidProbability
python
great-expectations__great_expectations
great_expectations/datasource/fluent/spark_datasource.py
{ "start": 6142, "end": 12551 }
class ____(DataAsset, Generic[_SparkDataFrameT]): """ A DataAsset that represents a Spark DataFrame. """ # instance attributes type: Literal["dataframe"] = "dataframe" class Config: extra = pydantic.Extra.forbid @override def test_connection(self) -> None: ... @override def get_batch_parameters_keys( self, partitioner: Optional[ColumnPartitioner] = None ) -> tuple[str, ...]: return tuple( "dataframe", ) def _get_reader_method(self) -> str: raise NotImplementedError( """Spark DataFrameAsset does not implement "_get_reader_method()" method, because DataFrame is already available.""" # noqa: E501 # FIXME CoP ) def _get_reader_options_include(self) -> set[str]: raise NotImplementedError( """Spark DataFrameAsset does not implement "_get_reader_options_include()" method, because DataFrame is already available.""" # noqa: E501 # FIXME CoP ) @override def build_batch_request( self, options: Optional[BatchParameters] = None, batch_slice: Optional[BatchSlice] = None, partitioner: Optional[ColumnPartitioner] = None, ) -> BatchRequest: """A batch request that can be used to obtain batches for this DataAsset. Args: options: This should have 1 key, 'dataframe', whose value is the datafame to validate. batch_slice: This is not currently supported and must be None for this data asset. partitioner: This is not currently supported and must be None for this data asset. Returns: A BatchRequest object that can be used to obtain a batch from an Asset by calling the get_batch method. """ if batch_slice is not None: raise BuildBatchRequestError( message="batch_slice is not currently supported for this DataAsset " "and must be None." ) if partitioner is not None: raise BuildBatchRequestError( message="partitioner is not currently supported for this DataAsset " "and must be None." ) if not (options is not None and "dataframe" in options and len(options) == 1): raise BuildBatchRequestError(message="options must contain exactly 1 key, 'dataframe'.") if not self.is_spark_data_frame(options["dataframe"]): raise BuildBatchRequestError( message="Cannot build batch request without a Spark DataFrame." ) return BatchRequest( datasource_name=self.datasource.name, data_asset_name=self.name, options=options, ) @override def _validate_batch_request(self, batch_request: BatchRequest) -> None: """Validates the batch_request has the correct form. Args: batch_request: A batch request object to be validated. """ if not ( batch_request.datasource_name == self.datasource.name and batch_request.data_asset_name == self.name and batch_request.options and len(batch_request.options) == 1 and "dataframe" in batch_request.options and self.is_spark_data_frame(batch_request.options["dataframe"]) ): expect_batch_request_form = BatchRequest[None]( datasource_name=self.datasource.name, data_asset_name=self.name, options={}, batch_slice=batch_request._batch_slice_input, # type: ignore[attr-defined] # FIXME CoP ) raise gx_exceptions.InvalidBatchRequestError( # noqa: TRY003 # FIXME CoP "BatchRequest should have form:\n" f"{pf(expect_batch_request_form.dict())}\n" f"but actually has form:\n{pf(batch_request.dict())}\n" ) @override def get_batch_identifiers_list(self, batch_request: BatchRequest) -> List[dict]: return [IDDict(batch_request.options)] @override def get_batch(self, batch_request: BatchRequest) -> Batch: self._validate_batch_request(batch_request) batch_spec = RuntimeDataBatchSpec(batch_data=batch_request.options["dataframe"]) execution_engine: SparkDFExecutionEngine = self.datasource.get_execution_engine() data, markers = execution_engine.get_batch_data_and_markers(batch_spec=batch_spec) # batch_definition (along with batch_spec and markers) is only here to satisfy a # legacy constraint when computing usage statistics in a validator. We hope to remove # it in the future. batch_definition = LegacyBatchDefinition( datasource_name=self.datasource.name, data_connector_name=_DATA_CONNECTOR_NAME, data_asset_name=self.name, batch_identifiers=make_batch_identifier(batch_request.options), batch_spec_passthrough=None, ) batch_metadata: BatchMetadata = self._get_batch_metadata_from_batch_request( batch_request=batch_request, ignore_options=("dataframe",) ) return Batch( datasource=self.datasource, data_asset=self, batch_request=batch_request, data=data, metadata=batch_metadata, batch_markers=markers, batch_spec=batch_spec, batch_definition=batch_definition, ) @public_api def add_batch_definition_whole_dataframe(self, name: str) -> BatchDefinition: """ Add a BatchDefinition that represents the entire DataFrame. Args: name: The name of the Batch Definition. Returns: A BatchDefinition object that represents the entire DataFrame. """ return self.add_batch_definition( name=name, partitioner=None, ) @staticmethod def is_spark_data_frame(df: Any) -> TypeGuard[Union[DataFrame, ConnectDataFrame]]: """Check that a given object is a Spark DataFrame. This could either be a regular Spark DataFrame or a Spark Connect DataFrame. """ data_frame_types = [DataFrame, ConnectDataFrame] return any((cls and isinstance(df, cls)) for cls in data_frame_types) @public_api
DataFrameAsset
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py
{ "start": 8098, "end": 8302 }
class ____(Missing): # noqa F821 # MYPY: error: Name "Missing" is not defined [name-defined] def from_orm(self) -> None: pass CoverageTester().from_orm() @dataclass(config={})
CoverageTester
python
pytorch__pytorch
test/test_static_runtime.py
{ "start": 5443, "end": 5744 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.sub1 = SubModule() self.sub2 = SubModule2() self.a = 3 self.b = 4 def forward(self, x): self.b = 20 return self.sub1(x) + self.a + self.b + self.sub2(x)
TestModule
python
HypothesisWorks__hypothesis
hypothesis-python/tests/ghostwriter/test_ghostwriter_cli.py
{ "start": 6317, "end": 7480 }
class ____: @classmethod def to_json(cls, json: Union[dict,list]) -> str: return json.dumps(json) @classmethod def from_json(cls, json: str) -> Union[dict,list]: return json.loads(json) """ def test_roundtrip_correct_pairs(tmp_path): (tmp_path / "mycode.py").write_text(ROUNDTRIP_CODE_TO_TEST, encoding="utf-8") result = run("hypothesis write mycode", cwd=tmp_path) assert result.returncode == 0 for scope1, scope2 in itertools.product( ["mycode.MyClass", "mycode.OtherClass", "mycode"], repeat=2 ): round_trip_code = f"""value0 = {scope1}.to_json(json=json) value1 = {scope2}.from_json(json=value0)""" if scope1 == scope2: assert round_trip_code in result.stdout else: assert round_trip_code not in result.stdout def test_empty_module_is_not_error(tmp_path): (tmp_path / "mycode.py").write_text("# Nothing to see here\n", encoding="utf-8") result = run("hypothesis write mycode", cwd=tmp_path) assert result.returncode == 0 assert "Error: " not in result.stderr assert "# Found no testable functions" in result.stdout
OtherClass
python
coleifer__peewee
tests/db_tests.py
{ "start": 16588, "end": 16738 }
class ____(TestModel): content = TextField() ts = DateTimeField() status = IntegerField() class Meta: table_name = 'notes'
Note
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-sagemaker-endpoint/llama_index/llms/sagemaker_endpoint/utils.py
{ "start": 202, "end": 1674 }
class ____(BaseModel, metaclass=abc.ABCMeta): content_type: str = Field( description="The MIME type of the input data in the request body.", ) accept: str = Field( description="The desired MIME type of the inference response from the model container.", ) @classmethod def __subclasshook__(cls, subclass: type) -> bool: return ( hasattr(subclass, "content_type") and hasattr(subclass, "accept") and hasattr(subclass, "serialize_input") and callable(subclass.serialize_input) and hasattr(subclass, "deserialize_output") and callable(subclass.deserialize_output) and hasattr(subclass, "deserialize_streaming_output") and callable(subclass.deserialize_streaming_output) and hasattr(subclass, "remove_prefix") and callable(subclass.remove_prefix) or NotImplemented ) @abc.abstractmethod def serialize_input(self, request: str, model_kwargs: dict) -> bytes: raise NotImplementedError @abc.abstractmethod def deserialize_output(self, response: "StreamingBody") -> str: raise NotImplementedError @abc.abstractmethod def deserialize_streaming_output(self, response: bytes) -> str: raise NotImplementedError @abc.abstractmethod def remove_prefix(self, response: str, prompt: str) -> str: raise NotImplementedError
BaseIOHandler
python
weaviate__weaviate-python-client
integration/test_collection_batch.py
{ "start": 637, "end": 809 }
class ____: array: list def squeeze(self) -> "MockNumpyTorch": return self def tolist(self) -> list: return self.array @dataclass
MockNumpyTorch
python
pytorch__pytorch
torch/utils/hooks.py
{ "start": 3193, "end": 10212 }
class ____: """ A wrapper class to implement nn.Module backward hooks. It handles: - Ignoring non-Tensor inputs and replacing them by None before calling the user hook - Generating the proper Node to capture a set of Tensor's gradients - Linking the gradients captures for the outputs with the gradients captured for the input - Calling the user hook once both output and input gradients are available """ def __init__(self, module, user_hooks, user_pre_hooks) -> None: self.user_hooks = user_hooks self.user_pre_hooks = user_pre_hooks self.module = module self.grad_outputs = None self.n_outputs = -1 self.output_tensors_index = None self.n_inputs = -1 self.input_tensors_index = None def _pack_with_none(self, indices, values, size): res = [None] * size for idx, val in zip(indices, values, strict=True): res[idx] = val return tuple(res) def _unpack_none(self, indices, values): res = [values[idx] for idx in indices] return tuple(res) def _set_user_hook(self, grad_fn) -> None: def hook(grad_input, _): if self.grad_outputs is None: # This happens because the gradient in your nn.Module flows to # the Module's input without " passing through the Module's # output, e.g. when you're doing double backward. return res = self._pack_with_none(self.input_tensors_index, grad_input, self.n_inputs) for hook in self.user_hooks: out = hook(self.module, res, self.grad_outputs) if out is None: continue if len(out) != len(res): raise RuntimeError("Backward hook returned an invalid number of grad_input, " f"got {len(out)}, but expected {len(res)}") res = out # pyrefly: ignore [bad-assignment] self.grad_outputs = None return self._unpack_none(self.input_tensors_index, res) grad_fn.register_hook(hook) def _apply_on_tensors(self, fn, args): # Can be used to apply the given function to the tensors contained in the # args. Will return updated args and the tensors indices tensors_idx = [] tensors = [] requires_grad = False for i, arg in enumerate(args): if isinstance(arg, torch.Tensor): tensors_idx.append(i) tensors.append(arg) requires_grad |= arg.requires_grad if not (requires_grad and torch.is_grad_enabled()): return args, None new_tensors = torch.nn.modules._functions.BackwardHookFunction.apply(*tensors) if len(new_tensors) == 0: raise RuntimeError("Cannot set Module backward hook for a Module with no input Tensors.") grad_fns = [t.grad_fn for t in new_tensors if t.grad_fn is not None and t.grad_fn.name() == "BackwardHookFunctionBackward"] if len(grad_fns) == 0: raise RuntimeError("Error while setting up backward hooks. Please open " "an issue with a code sample to reproduce this.") fn(grad_fns[0]) arg_list = list(args) for idx, val in zip(tensors_idx, new_tensors, strict=True): arg_list[idx] = val if type(args) is tuple: out = tuple(arg_list) else: out = type(args)(*arg_list) return out, tensors_idx def setup_input_hook(self, args): def fn(grad_fn) -> None: self._set_user_hook(grad_fn) res, input_idx = self._apply_on_tensors(fn, args) self.n_inputs = len(args) self.input_tensors_index = input_idx return res def setup_output_hook(self, args): def fn(grad_fn) -> None: def hook(_, grad_output): self.grad_outputs = self._pack_with_none(self.output_tensors_index, grad_output, self.n_outputs) if self.user_pre_hooks: expected_len = len(self.grad_outputs) for user_pre_hook in self.user_pre_hooks: hook_grad_outputs = user_pre_hook(self.module, self.grad_outputs) if hook_grad_outputs is None: continue actual_len = len(hook_grad_outputs) if actual_len != expected_len: raise RuntimeError("Backward pre hook returned an invalid number of grad_output, " f"got {actual_len}, but expected {expected_len}") self.grad_outputs = hook_grad_outputs # We need to be able to clear self.grad_outputs but also return it local_grad_outputs = self.grad_outputs # Special case if no input required gradients, this hook should call the user # hook directly if self.input_tensors_index is None: warnings.warn("Full backward hook is firing when gradients are computed " "with respect to module outputs since no inputs require gradients. See " "https://docs.pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.register_full_backward_hook " # noqa: B950 "for more details.", stacklevel=5) grad_inputs = self._pack_with_none([], [], self.n_inputs) for user_hook in self.user_hooks: res = user_hook(self.module, grad_inputs, self.grad_outputs) if res is not None and not (isinstance(res, tuple) and all(el is None for el in res)): raise RuntimeError("Backward hook for Modules where no input requires " "gradient should always return None or None for all gradients.") self.grad_outputs = None if local_grad_outputs is not None: if self.output_tensors_index is None: raise AssertionError("output_tensors_index should not be None when grad_outputs is not None") return tuple(local_grad_outputs[i] for i in self.output_tensors_index) grad_fn.register_hook(hook) is_tuple = True if not isinstance(args, tuple): args = (args,) is_tuple = False res, output_idx = self._apply_on_tensors(fn, args) self.n_outputs = len(args) self.output_tensors_index = output_idx if not is_tuple: res = res[0] return res
BackwardHook
python
rq__rq
rq/connections.py
{ "start": 74, "end": 455 }
class ____(Exception): pass def parse_connection(connection: Redis) -> tuple[type[Redis], type[RedisConnection], dict]: connection_pool_kwargs = connection.connection_pool.connection_kwargs.copy() connection_pool_class = connection.connection_pool.connection_class return connection.__class__, connection_pool_class, connection_pool_kwargs
NoRedisConnectionException
python
sympy__sympy
sympy/integrals/manualintegrate.py
{ "start": 20183, "end": 20340 }
class ____(AtomicRule): a: Expr d: Expr def eval(self) -> Expr: return elliptic_e(self.variable, self.d/self.a)*sqrt(self.a)
EllipticERule
python
cython__cython
tests/run/pep563_annotations.py
{ "start": 916, "end": 1227 }
class ____(object): """ >>> sorted(DecoratedStarship.__annotations__.items()) [('captain', 'str'), ('damage', 'cython.int')] """ captain: str = 'Picard' # instance variable with default damage: cython.int # instance variable without default
DecoratedStarship
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/metadata.py
{ "start": 2794, "end": 3145 }
class ____(graphene.ObjectType): floatValue = graphene.Field(graphene.Float) floatRepr = graphene.NonNull( graphene.String, description="String representation of the float to support nan/inf/-inf", ) class Meta: interfaces = (GrapheneMetadataEntry,) name = "FloatMetadataEntry"
GrapheneFloatMetadataEntry
python
apache__thrift
lib/py/src/server/TServer.py
{ "start": 5998, "end": 8436 }
class ____(TServer): """Server with a fixed size pool of threads which service requests.""" def __init__(self, *args, **kwargs): TServer.__init__(self, *args) self.clients = queue.Queue() self.threads = 10 self.daemon = kwargs.get("daemon", False) def setNumThreads(self, num): """Set the number of worker threads that should be created""" self.threads = num def serveThread(self): """Loop around getting clients from the shared queue and process them.""" while True: try: client = self.clients.get() self.serveClient(client) except Exception as x: logger.exception(x) def serveClient(self, client): """Process input/output from a client for as long as possible""" itrans = self.inputTransportFactory.getTransport(client) iprot = self.inputProtocolFactory.getProtocol(itrans) # for THeaderProtocol, we must use the same protocol instance for input # and output so that the response is in the same dialect that the # server detected the request was in. if isinstance(self.inputProtocolFactory, THeaderProtocolFactory): otrans = None oprot = iprot else: otrans = self.outputTransportFactory.getTransport(client) oprot = self.outputProtocolFactory.getProtocol(otrans) try: while True: self.processor.process(iprot, oprot) except TTransport.TTransportException: pass except Exception as x: logger.exception(x) itrans.close() if otrans: otrans.close() def serve(self): """Start a fixed number of worker threads and put client into a queue""" for i in range(self.threads): try: t = threading.Thread(target=self.serveThread) t.daemon = self.daemon t.start() except Exception as x: logger.exception(x) # Pump the socket for clients self.serverTransport.listen() while True: try: client = self.serverTransport.accept() if not client: continue self.clients.put(client) except Exception as x: logger.exception(x)
TThreadPoolServer
python
kamyu104__LeetCode-Solutions
Python/closest-node-to-path-in-tree.py
{ "start": 5417, "end": 6115 }
class ____(object): def closestNode(self, n, edges, query): """ :type n: int :type edges: List[List[int]] :type query: List[List[int]] :rtype: List[int] """ adj = [[] for _ in xrange(n)] for u, v in edges: adj[u].append(v), adj[v].append(u) tree_infos = TreeInfos2(adj) return [max((tree_infos.lca(x, y) for x, y in ((start, end), (start, node), (end, node))), key=lambda x: tree_infos.D[x]) for start, end, node in query] # Time: O(n + q * h) # Space: O(n) from functools import partial # Template: # https://github.com/kamyu104/GoogleKickStart-2021/blob/main/Round%20H/dependent_events2.py
Solution2
python
huggingface__transformers
src/transformers/core_model_loading.py
{ "start": 4565, "end": 5840 }
class ____(ConversionOps): """Concatenate tensors along `dim`.""" def __init__(self, dim: int = 0): self.dim = dim @torch.no_grad def convert( self, input_dict: dict[str, list[torch.Tensor]], source_patterns: list[str], target_patterns: list[str], **kwargs, ) -> dict[str, torch.Tensor]: target_pattern = self.get_target_pattern(target_patterns) all_tensors = [] # Very important to keep the relative order of the source patterms here, so we iterate over them not the # input directly as it's unordered! for source_pattern in source_patterns: tensors = input_dict[source_pattern] if isinstance(tensors, list): all_tensors.extend(tensors) else: all_tensors.append(tensors) return {target_pattern: torch.cat(all_tensors, dim=self.dim)} def get_target_pattern(self, target_patterns: list[str]) -> str: # Here we always return the target pattern if len(target_patterns) > 1: raise ValueError("Undefined Operation encountered!") return target_patterns[0] @property def reverse_op(self) -> ConversionOps: return Chunk(self.dim)
Concatenate
python
scrapy__scrapy
tests/mockserver/http_base.py
{ "start": 478, "end": 4361 }
class ____(ABC): listen_http: bool = True listen_https: bool = True @property @abstractmethod def module_name(self) -> str: raise NotImplementedError def __init__(self) -> None: if not self.listen_http and not self.listen_https: raise ValueError("At least one of listen_http and listen_https must be set") self.proc: Popen | None = None self.host: str = "127.0.0.1" self.http_port: int | None = None self.https_port: int | None = None def __enter__(self): self.proc = Popen( [sys.executable, "-u", "-m", self.module_name, *self.get_additional_args()], stdout=PIPE, env=get_script_run_env(), ) if self.listen_http: http_address = self.proc.stdout.readline().strip().decode("ascii") http_parsed = urlparse(http_address) self.http_port = http_parsed.port if self.listen_https: https_address = self.proc.stdout.readline().strip().decode("ascii") https_parsed = urlparse(https_address) self.https_port = https_parsed.port return self def __exit__(self, exc_type, exc_value, traceback): if self.proc: self.proc.kill() self.proc.communicate() def get_additional_args(self) -> list[str]: return [] def port(self, is_secure: bool = False) -> int: if not is_secure and not self.listen_http: raise ValueError("This server doesn't provide HTTP") if is_secure and not self.listen_https: raise ValueError("This server doesn't provide HTTPS") port = self.https_port if is_secure else self.http_port assert port is not None return port def url(self, path: str, is_secure: bool = False) -> str: port = self.port(is_secure) scheme = "https" if is_secure else "http" return f"{scheme}://{self.host}:{port}{path}" def main_factory( resource_class: type[resource.Resource], *, listen_http: bool = True, listen_https: bool = True, ) -> Callable[[], None]: if not listen_http and not listen_https: raise ValueError("At least one of listen_http and listen_https must be set") def main() -> None: from twisted.internet import reactor root = resource_class() factory = Site(root) if listen_http: http_port = reactor.listenTCP(0, factory) if listen_https: parser = argparse.ArgumentParser() parser.add_argument("--keyfile", help="SSL key file") parser.add_argument("--certfile", help="SSL certificate file") parser.add_argument( "--cipher-string", default=None, help="SSL cipher string (optional)", ) args = parser.parse_args() context_factory_kw = {} if args.keyfile: context_factory_kw["keyfile"] = args.keyfile if args.certfile: context_factory_kw["certfile"] = args.certfile if args.cipher_string: context_factory_kw["cipher_string"] = args.cipher_string context_factory = ssl_context_factory(**context_factory_kw) https_port = reactor.listenSSL(0, factory, context_factory) def print_listening(): if listen_http: http_host = http_port.getHost() http_address = f"http://{http_host.host}:{http_host.port}" print(http_address) if listen_https: https_host = https_port.getHost() https_address = f"https://{https_host.host}:{https_host.port}" print(https_address) reactor.callWhenRunning(print_listening) reactor.run() return main
BaseMockServer
python
TheAlgorithms__Python
graphs/breadth_first_search_zero_one_shortest_path.py
{ "start": 353, "end": 452 }
class ____: """Weighted directed graph edge.""" destination_vertex: int weight: int
Edge
python
getsentry__sentry
tests/relay_integration/lang/java/test_plugin.py
{ "start": 31649, "end": 31878 }
class ____ { fun helloThere() { InnerClassOfSomeService().helloInner() } class InnerClassOfSomeService { fun helloInner() { AnotherClassInSameFile().helloOther() } } }
SomeService
python
faif__python-patterns
patterns/behavioral/state.py
{ "start": 931, "end": 1239 }
class ____(State): def __init__(self, radio: Radio) -> None: self.radio = radio self.stations = ["81.3", "89.1", "103.9"] self.pos = 0 self.name = "FM" def toggle_amfm(self) -> None: print("Switching to AM") self.radio.state = self.radio.amstate
FmState
python
paramiko__paramiko
paramiko/ssh_exception.py
{ "start": 6773, "end": 6942 }
class ____(SSHException): """ Raised when hostname canonicalization fails & fallback is disabled. .. versionadded:: 2.7 """ pass
CouldNotCanonicalize
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_emr_step.py
{ "start": 5347, "end": 7807 }
class ____: def setup_method(self): self.sensor = EmrStepSensor( task_id="test_task", poke_interval=0, job_flow_id="j-8989898989", step_id="s-VK57YR1Z9Z5N", aws_conn_id="aws_default", ) def test_step_completed(self, mocked_hook_client): mocked_hook_client.describe_step.side_effect = [ DESCRIBE_JOB_STEP_RUNNING_RETURN, DESCRIBE_JOB_STEP_COMPLETED_RETURN, ] with patch.object(S3Hook, "parse_s3_url", return_value="valid_uri"): self.sensor.execute(MagicMock()) assert mocked_hook_client.describe_step.call_count == 2 calls = [mock.call(ClusterId="j-8989898989", StepId="s-VK57YR1Z9Z5N")] * 2 mocked_hook_client.describe_step.assert_has_calls(calls) def test_step_cancelled(self, mocked_hook_client): mocked_hook_client.describe_step.side_effect = [ DESCRIBE_JOB_STEP_RUNNING_RETURN, DESCRIBE_JOB_STEP_CANCELLED_RETURN, ] with pytest.raises(AirflowException, match="EMR job failed"): self.sensor.execute(MagicMock()) def test_step_failed(self, mocked_hook_client): mocked_hook_client.describe_step.side_effect = [ DESCRIBE_JOB_STEP_RUNNING_RETURN, DESCRIBE_JOB_STEP_FAILED_RETURN, ] with pytest.raises(AirflowException, match="EMR job failed"): self.sensor.execute(MagicMock()) def test_step_interrupted(self, mocked_hook_client): mocked_hook_client.describe_step.side_effect = [ DESCRIBE_JOB_STEP_RUNNING_RETURN, DESCRIBE_JOB_STEP_INTERRUPTED_RETURN, ] with pytest.raises(AirflowException): self.sensor.execute(MagicMock()) def test_sensor_defer(self): """Test the execute method raise TaskDeferred if running sensor in deferrable mode""" sensor = EmrStepSensor( task_id="test_task", poke_interval=0, job_flow_id="j-8989898989", step_id="s-VK57YR1Z9Z5N", aws_conn_id="aws_default", deferrable=True, ) with patch.object(EmrStepSensor, "poke", return_value=False): with pytest.raises(TaskDeferred) as exc: sensor.execute(context=None) assert isinstance(exc.value.trigger, EmrStepSensorTrigger), "Trigger is not a EmrStepSensorTrigger"
TestEmrStepSensor
python
joke2k__faker
tests/providers/test_internet.py
{ "start": 31231, "end": 31626 }
class ____: """Test en_PH internet provider methods""" num_samples = 100 def test_domain_name(self, faker, num_samples): for i in range(num_samples): domain = faker.domain_name() validate_domain(domain) def test_slug(self, faker): num_of_samples = 100 for _ in range(num_of_samples): assert faker.slug() != ""
TestEnPh
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/columns_height.py
{ "start": 122, "end": 719 }
class ____(App[None]): CSS = """ Horizontal { border: solid red; height: auto; } Static { border: solid green; width: auto; } #fill_parent { height: 100%; } #static { height: 16; } """ def compose(self) -> ComposeResult: yield Horizontal( Static("As tall as container", id="fill_parent"), Static("This has default\nheight\nbut a\nfew lines"), Static("I have a static height", id="static"), ) if __name__ == "__main__": HeightApp().run()
HeightApp
python
pallets__werkzeug
src/werkzeug/routing/converters.py
{ "start": 4900, "end": 5659 }
class ____(NumberConverter): """This converter only accepts integer values:: Rule("/page/<int:page>") By default it only accepts unsigned, positive values. The ``signed`` parameter will enable signed, negative values. :: Rule("/page/<int(signed=True):page>") :param map: The :class:`Map`. :param fixed_digits: The number of fixed digits in the URL. If you set this to ``4`` for example, the rule will only match if the URL looks like ``/0001/``. The default is variable length. :param min: The minimal value. :param max: The maximal value. :param signed: Allow signed (negative) values. .. versionadded:: 0.15 The ``signed`` parameter. """ regex = r"\d+"
IntegerConverter
python
huggingface__transformers
src/transformers/models/beit/modeling_beit.py
{ "start": 41125, "end": 41714 }
class ____(nn.Module): def __init__(self, pool_scale: int, in_channels: int, channels: int) -> None: super().__init__() self.layers = [ nn.AdaptiveAvgPool2d(pool_scale), BeitConvModule(in_channels, channels, kernel_size=1), ] for i, layer in enumerate(self.layers): self.add_module(str(i), layer) def forward(self, input: torch.Tensor) -> torch.Tensor: hidden_state = input for layer in self.layers: hidden_state = layer(hidden_state) return hidden_state
BeitPyramidPoolingBlock
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/index_select_test.py
{ "start": 708, "end": 1486 }
class ____(op_bench.TorchBenchmarkBase): def init(self, M, N, K, dim, device): max_val = N numpy.random.seed((1 << 32) - 1) index_dim = numpy.random.randint(0, N) self.inputs = { "input_one": torch.rand(M, N, K, device=device), "dim": dim, "index": torch.tensor( numpy.random.randint(0, max_val, index_dim), device=device ), } self.set_module_name("index_select") def forward(self, input_one, dim, index): return torch.index_select(input_one, dim, index) op_bench.generate_pt_test( index_select_configs_short + index_select_configs_long, IndexSelectBenchmark ) if __name__ == "__main__": op_bench.benchmark_runner.main()
IndexSelectBenchmark
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 94720, "end": 95841 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) alert: Optional[SqlTaskAlert] = Field( None, description="If alert, indicates that this job must refresh a SQL alert." ) dashboard: Optional[SqlTaskDashboard] = Field( None, description=( "If dashboard, indicates that this job must refresh a SQL dashboard." ), ) parameters: Optional[Dict[str, Any]] = Field( default=None, description=( "Parameters to be used for each run of this job. The SQL alert task does" " not support custom parameters." ), examples=[{"age": 35, "name": "John Doe"}], ) query: Optional[SqlTaskQuery] = Field( None, description="If query, indicates that this job must execute a SQL query." ) warehouse_id: str = Field( ..., description=( "The canonical identifier of the SQL warehouse. Only serverless and pro SQL" " warehouses are supported." ), )
SqlTask
python
getsentry__sentry
src/sentry/users/api/endpoints/user_authenticator_details.py
{ "start": 1141, "end": 10582 }
class ____(UserEndpoint): publish_status = { "DELETE": ApiPublishStatus.PRIVATE, "GET": ApiPublishStatus.PRIVATE, "PUT": ApiPublishStatus.PRIVATE, } owner = ApiOwner.ENTERPRISE permission_classes = (OrganizationUserPermission,) def _get_device_for_rename( self, authenticator: Authenticator, interface_device_id: str | None ) -> dict[str, Any] | None: devices = authenticator.config for device in devices["devices"]: # this is for devices registered with webauthn, since the stored data is not a string, we need to decode it if isinstance(device["binding"], AuthenticatorData): if decode_credential_id(device) == interface_device_id: return device elif device["binding"]["keyHandle"] == interface_device_id: return device return None def _rename_device( self, authenticator: Authenticator, interface_device_id: str | None, new_name: str ) -> Response: device = self._get_device_for_rename(authenticator, interface_device_id) if not device: return Response(status=status.HTTP_400_BAD_REQUEST) device["name"] = new_name authenticator.save() return Response(status=status.HTTP_204_NO_CONTENT) def _regenerate_recovery_code( self, authenticator: Authenticator, request: Request, user: User ) -> Response: interface = authenticator.interface if isinstance(interface, RecoveryCodeInterface) and interface.interface_id == "recovery": interface.regenerate_codes() capture_security_activity( account=user, type="recovery-codes-regenerated", actor=request.user, ip_address=request.META["REMOTE_ADDR"], context={"authenticator": authenticator}, send_email=True, ) return Response(serialize(interface, serializer=get_interface_serializer(interface))) @sudo_required def get(self, request: Request, user: User, auth_id: str) -> Response: """ Get Authenticator Interface ``````````````````````````` Retrieves authenticator interface details for user depending on user enrollment status :pparam string user_id: user id or "me" for current user :pparam string auth_id: authenticator model id :auth: required """ try: authenticator = Authenticator.objects.get(user=user, id=auth_id) except (ValueError, Authenticator.DoesNotExist): return Response(status=status.HTTP_404_NOT_FOUND) interface = authenticator.interface # User is enrolled to auth interface: # - display interface details # - show enrolled specific details like: # - created at, last used dates # - phone number for SMS # - recovery codes response = serialize(interface, serializer=get_interface_serializer(interface)) if interface.interface_id == "recovery": assert isinstance( interface, RecoveryCodeInterface ), "Interace must be RecoveryCodeInterface to get unused codes" response["codes"] = interface.get_unused_codes() if interface.interface_id == "u2f": assert isinstance( interface, U2fInterface ), "Interace must be U2fInterface to get registered devices" response["devices"] = interface.get_registered_devices() return Response(response) @sudo_required def put( self, request: Request, user: User, auth_id: str, interface_device_id: str | None = None ) -> Response: """ Modify authenticator interface `````````````````````````````` Currently, only supports regenerating recovery codes :pparam string user_id: user id or 'me' for current user :pparam int auth_id: authenticator model id :auth required: """ # TODO: temporary solution for both renaming and regenerating recovery code. # Need to find new home for regenerating recovery codes as it doesn't really do what put is supposed to do try: authenticator = Authenticator.objects.get(user=user, id=auth_id) except (ValueError, Authenticator.DoesNotExist): return Response(status=status.HTTP_404_NOT_FOUND) if request.data.get("name"): return self._rename_device( authenticator, interface_device_id, str(request.data.get("name")) ) else: return self._regenerate_recovery_code(authenticator, request, user) @sudo_required def delete( self, request: Request, user: User, auth_id: str, interface_device_id: str | None = None ) -> Response: """ Remove authenticator ```````````````````` :pparam string user_id: user id or 'me' for current user :pparam string auth_id: authenticator model id :pparam string interface_device_id: some interfaces (u2f) allow multiple devices :auth required: """ try: authenticator = Authenticator.objects.get(user=user, id=auth_id) except (ValueError, Authenticator.DoesNotExist): return Response(status=status.HTTP_404_NOT_FOUND) interface = authenticator.interface # Remove a single device and not entire authentication method if interface.interface_id == "u2f" and interface_device_id is not None: assert isinstance( interface, U2fInterface ), "Interace must be U2fInterface to get registered devices" device_name = interface.get_device_name(interface_device_id) # Can't remove if this is the last device, will return False if so if not interface.remove_u2f_device(interface_device_id): return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) assert interface.authenticator, "Interface must have an authenticator to save" interface.authenticator.save() capture_security_activity( account=user, type="mfa-removed", actor=request.user, ip_address=request.META["REMOTE_ADDR"], context={"authenticator": authenticator, "device_name": device_name}, send_email=True, ) return Response(status=status.HTTP_204_NO_CONTENT) # We should only be able to delete the last auth method through the # _admin portal, which is indicated by staff. After the option is # removed, this will only check for is_active_staff. if has_staff_option(request.user): check_remaining_auth = not is_active_staff(request) else: check_remaining_auth = not is_active_superuser(request) if check_remaining_auth: # if the user's organization requires 2fa, # don't delete the last auth method enrolled_methods = Authenticator.objects.all_interfaces_for_user( user, ignore_backup=True ) last_2fa_method = len(enrolled_methods) == 1 require_2fa = user.has_org_requiring_2fa() if require_2fa and last_2fa_method: return Response( {"detail": "Cannot delete authenticator because organization requires 2FA"}, status=status.HTTP_403_FORBIDDEN, ) interfaces = Authenticator.objects.all_interfaces_for_user(user) with transaction.atomic(using=router.db_for_write(Authenticator)): authenticator.delete() # if we delete an actual authenticator and all that # remains are backup interfaces, then we kill them in the # process. if not interface.is_backup_interface: backup_interfaces = [x for x in interfaces if x.is_backup_interface] if len(backup_interfaces) == len(interfaces): for iface in backup_interfaces: assert iface.authenticator, "Interface must have an authenticator to delete" iface.authenticator.delete() # wait to generate entries until all pending writes # have been sent to db for iface in backup_interfaces: capture_security_activity( account=request.user, type="mfa-removed", actor=request.user, ip_address=request.META["REMOTE_ADDR"], context={"authenticator": iface.authenticator}, send_email=False, ) capture_security_activity( account=user, type="mfa-removed", actor=request.user, ip_address=request.META["REMOTE_ADDR"], context={"authenticator": authenticator}, send_email=not interface.is_backup_interface, ) request.session.pop(MFA_SESSION_KEY, None) return Response(status=status.HTTP_204_NO_CONTENT)
UserAuthenticatorDetailsEndpoint
python
ray-project__ray
doc/source/ray-core/doc_code/anti_pattern_global_variables.py
{ "start": 666, "end": 1089 }
class ____: def __init__(self, global_var_actor): self.global_var_actor = global_var_actor def f(self): return ray.get(self.global_var_actor.get_global_var.remote()) + 3 global_var_actor = GlobalVarActor.remote() actor = Actor.remote(global_var_actor) ray.get(global_var_actor.set_global_var.remote(4)) # This returns 7 correctly. assert ray.get(actor.f.remote()) == 7 # __better_approach_end__
Actor
python
scipy__scipy
scipy/differentiate/tests/test_differentiate.py
{ "start": 507, "end": 18221 }
class ____: def f(self, x): return special.ndtr(x) @pytest.mark.parametrize('x', [0.6, np.linspace(-0.05, 1.05, 10)]) def test_basic(self, x, xp): # Invert distribution CDF and compare against distribution `ppf` default_dtype = xp.asarray(1.).dtype res = derivative(self.f, xp.asarray(x, dtype=default_dtype)) ref = xp.asarray(stats.norm().pdf(x), dtype=default_dtype) xp_assert_close(res.df, ref) # This would be nice, but doesn't always work out. `error` is an # estimate, not a bound. if not is_torch(xp): xp_assert_less(xp.abs(res.df - ref), res.error) @pytest.mark.parametrize('case', stats._distr_params.distcont) def test_accuracy(self, case): distname, params = case dist = getattr(stats, distname)(*params) x = dist.median() + 0.1 res = derivative(dist.cdf, x) ref = dist.pdf(x) xp_assert_close(res.df, ref, atol=1e-10) @pytest.mark.parametrize('order', [1, 6]) @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)]) def test_vectorization(self, order, shape, xp): # Test for correct functionality, output shapes, and dtypes for various # input shapes. x = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6 n = np.size(x) state = {} @np.vectorize def _derivative_single(x): return derivative(self.f, x, order=order) def f(x, *args, **kwargs): state['nit'] += 1 state['feval'] += 1 if (x.size == n or x.ndim <=1) else x.shape[-1] return self.f(x, *args, **kwargs) state['nit'] = -1 state['feval'] = 0 res = derivative(f, xp.asarray(x, dtype=xp.float64), order=order) refs = _derivative_single(x).ravel() ref_x = [ref.x for ref in refs] xp_assert_close(xp.reshape(res.x, (-1,)), xp.asarray(ref_x)) ref_df = [ref.df for ref in refs] xp_assert_close(xp.reshape(res.df, (-1,)), xp.asarray(ref_df)) ref_error = [ref.error for ref in refs] xp_assert_close(xp.reshape(res.error, (-1,)), xp.asarray(ref_error), atol=1e-12) ref_success = [bool(ref.success) for ref in refs] xp_assert_equal(xp.reshape(res.success, (-1,)), xp.asarray(ref_success)) ref_flag = [np.int32(ref.status) for ref in refs] xp_assert_equal(xp.reshape(res.status, (-1,)), xp.asarray(ref_flag)) ref_nfev = [np.int32(ref.nfev) for ref in refs] xp_assert_equal(xp.reshape(res.nfev, (-1,)), xp.asarray(ref_nfev)) if is_numpy(xp): # can't expect other backends to be exactly the same assert xp.max(res.nfev) == state['feval'] ref_nit = [np.int32(ref.nit) for ref in refs] xp_assert_equal(xp.reshape(res.nit, (-1,)), xp.asarray(ref_nit)) if is_numpy(xp): # can't expect other backends to be exactly the same assert xp.max(res.nit) == state['nit'] def test_flags(self, xp): # Test cases that should produce different status flags; show that all # can be produced simultaneously. rng = np.random.default_rng(5651219684984213) def f(xs, js): f.nit += 1 funcs = [lambda x: x - 2.5, # converges lambda x: xp.exp(x)*rng.random(), # error increases lambda x: xp.exp(x), # reaches maxiter due to order=2 lambda x: xp.full_like(x, xp.nan)] # stops due to NaN res = [funcs[int(j)](x) for x, j in zip(xs, xp.reshape(js, (-1,)))] return xp.stack(res) f.nit = 0 args = (xp.arange(4, dtype=xp.int64),) res = derivative(f, xp.ones(4, dtype=xp.float64), tolerances=dict(rtol=1e-14), order=2, args=args) ref_flags = xp.asarray([eim._ECONVERGED, _EERRORINCREASE, eim._ECONVERR, eim._EVALUEERR], dtype=xp.int32) xp_assert_equal(res.status, ref_flags) def test_flags_preserve_shape(self, xp): # Same test as above but using `preserve_shape` option to simplify. rng = np.random.default_rng(5651219684984213) def f(x): out = [x - 2.5, # converges xp.exp(x)*rng.random(), # error increases xp.exp(x), # reaches maxiter due to order=2 xp.full_like(x, xp.nan)] # stops due to NaN return xp.stack(out) res = derivative(f, xp.asarray(1, dtype=xp.float64), tolerances=dict(rtol=1e-14), order=2, preserve_shape=True) ref_flags = xp.asarray([eim._ECONVERGED, _EERRORINCREASE, eim._ECONVERR, eim._EVALUEERR], dtype=xp.int32) xp_assert_equal(res.status, ref_flags) def test_preserve_shape(self, xp): # Test `preserve_shape` option def f(x): out = [x, xp.sin(3*x), x+xp.sin(10*x), xp.sin(20*x)*(x-1)**2] return xp.stack(out) x = xp.asarray(0.) ref = xp.asarray([xp.asarray(1), 3*xp.cos(3*x), 1+10*xp.cos(10*x), 20*xp.cos(20*x)*(x-1)**2 + 2*xp.sin(20*x)*(x-1)]) res = derivative(f, x, preserve_shape=True) xp_assert_close(res.df, ref) def test_convergence(self, xp): # Test that the convergence tolerances behave as expected x = xp.asarray(1., dtype=xp.float64) f = special.ndtr ref = float(stats.norm.pdf(1.)) tolerances0 = dict(atol=0, rtol=0) tolerances = tolerances0.copy() tolerances['atol'] = 1e-3 res1 = derivative(f, x, tolerances=tolerances, order=4) assert abs(res1.df - ref) < 1e-3 tolerances['atol'] = 1e-6 res2 = derivative(f, x, tolerances=tolerances, order=4) assert abs(res2.df - ref) < 1e-6 assert abs(res2.df - ref) < abs(res1.df - ref) tolerances = tolerances0.copy() tolerances['rtol'] = 1e-3 res1 = derivative(f, x, tolerances=tolerances, order=4) assert abs(res1.df - ref) < 1e-3 * ref tolerances['rtol'] = 1e-6 res2 = derivative(f, x, tolerances=tolerances, order=4) assert abs(res2.df - ref) < 1e-6 * ref assert abs(res2.df - ref) < abs(res1.df - ref) def test_step_parameters(self, xp): # Test that step factors have the expected effect on accuracy x = xp.asarray(1., dtype=xp.float64) f = special.ndtr ref = float(stats.norm.pdf(1.)) res1 = derivative(f, x, initial_step=0.5, maxiter=1) res2 = derivative(f, x, initial_step=0.05, maxiter=1) assert abs(res2.df - ref) < abs(res1.df - ref) res1 = derivative(f, x, step_factor=2, maxiter=1) res2 = derivative(f, x, step_factor=20, maxiter=1) assert abs(res2.df - ref) < abs(res1.df - ref) # `step_factor` can be less than 1: `initial_step` is the minimum step kwargs = dict(order=4, maxiter=1, step_direction=0) res = derivative(f, x, initial_step=0.5, step_factor=0.5, **kwargs) ref = derivative(f, x, initial_step=1, step_factor=2, **kwargs) xp_assert_close(res.df, ref.df, rtol=5e-15) # This is a similar test for one-sided difference kwargs = dict(order=2, maxiter=1, step_direction=1) res = derivative(f, x, initial_step=1, step_factor=2, **kwargs) ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs) xp_assert_close(res.df, ref.df, rtol=5e-15) kwargs['step_direction'] = -1 res = derivative(f, x, initial_step=1, step_factor=2, **kwargs) ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs) xp_assert_close(res.df, ref.df, rtol=5e-15) def test_step_direction(self, xp): # test that `step_direction` works as expected def f(x): y = xp.exp(x) y = xpx.at(y)[(x < 0) + (x > 2)].set(xp.nan) return y x = xp.linspace(0, 2, 10) step_direction = xp.zeros_like(x) step_direction = xpx.at(step_direction)[x < 0.6].set(1) step_direction = xpx.at(step_direction)[x > 1.4].set(-1) res = derivative(f, x, step_direction=step_direction) xp_assert_close(res.df, xp.exp(x)) assert xp.all(res.success) def test_vectorized_step_direction_args(self, xp): # test that `step_direction` and `args` are vectorized properly def f(x, p): return x ** p def df(x, p): return p * x ** (p - 1) x = xp.reshape(xp.asarray([1, 2, 3, 4]), (-1, 1, 1)) hdir = xp.reshape(xp.asarray([-1, 0, 1]), (1, -1, 1)) p = xp.reshape(xp.asarray([2, 3]), (1, 1, -1)) res = derivative(f, x, step_direction=hdir, args=(p,)) ref = xp.broadcast_to(df(x, p), res.df.shape) ref = xp.asarray(ref, dtype=xp.asarray(1.).dtype) xp_assert_close(res.df, ref) def test_initial_step(self, xp): # Test that `initial_step` works as expected and is vectorized def f(x): return xp.exp(x) x = xp.asarray(0., dtype=xp.float64) step_direction = xp.asarray([-1, 0, 1]) h0 = xp.reshape(xp.logspace(-3, 0, 10), (-1, 1)) res = derivative(f, x, initial_step=h0, order=2, maxiter=1, step_direction=step_direction) err = xp.abs(res.df - f(x)) # error should be smaller for smaller step sizes assert xp.all(err[:-1, ...] < err[1:, ...]) # results of vectorized call should match results with # initial_step taken one at a time for i in range(h0.shape[0]): ref = derivative(f, x, initial_step=h0[i, 0], order=2, maxiter=1, step_direction=step_direction) xp_assert_close(res.df[i, :], ref.df, rtol=1e-14) def test_maxiter_callback(self, xp): # Test behavior of `maxiter` parameter and `callback` interface x = xp.asarray(0.612814, dtype=xp.float64) maxiter = 3 def f(x): res = special.ndtr(x) return res default_order = 8 res = derivative(f, x, maxiter=maxiter, tolerances=dict(rtol=1e-15)) assert not xp.any(res.success) assert xp.all(res.nfev == default_order + 1 + (maxiter - 1)*2) assert xp.all(res.nit == maxiter) def callback(res): callback.iter += 1 callback.res = res assert hasattr(res, 'x') assert float(res.df) not in callback.dfs callback.dfs.add(float(res.df)) assert res.status == eim._EINPROGRESS if callback.iter == maxiter: raise StopIteration callback.iter = -1 # callback called once before first iteration callback.res = None callback.dfs = set() res2 = derivative(f, x, callback=callback, tolerances=dict(rtol=1e-15)) # terminating with callback is identical to terminating due to maxiter # (except for `status`) for key in res.keys(): if key == 'status': assert res[key] == eim._ECONVERR assert res2[key] == eim._ECALLBACK elif key == 'error': # switched from equality check to accommodate # macosx-x86_64/Accelerate xp_assert_close(res2[key], res[key], atol=1e-14) xp_assert_close(callback.res[key], res[key], atol=1e-14) else: assert res2[key] == callback.res[key] == res[key] @pytest.mark.parametrize("hdir", (-1, 0, 1)) @pytest.mark.parametrize("x", (0.65, [0.65, 0.7])) @pytest.mark.parametrize("dtype", ('float32', 'float64')) def test_dtype(self, hdir, x, dtype, xp): # Test that dtypes are preserved dtype = getattr(xp, dtype) x = xp.asarray(x, dtype=dtype) def f(x): assert x.dtype == dtype return xp.exp(x) def callback(res): assert res.x.dtype == dtype assert res.df.dtype == dtype assert res.error.dtype == dtype res = derivative(f, x, order=4, step_direction=hdir, callback=callback) assert res.x.dtype == dtype assert res.df.dtype == dtype assert res.error.dtype == dtype eps = xp.finfo(dtype).eps # not sure why torch is less accurate here; might be worth investigating rtol = eps**0.5 * 50 if is_torch(xp) else eps**0.5 xp_assert_close(res.df, xp.exp(res.x), rtol=rtol) def test_input_validation(self, xp): # Test input validation for appropriate error messages one = xp.asarray(1) message = '`f` must be callable.' with pytest.raises(ValueError, match=message): derivative(None, one) message = 'Abscissae and function output must be real numbers.' with pytest.raises(ValueError, match=message): derivative(lambda x: x, xp.asarray(-4+1j)) message = "When `preserve_shape=False`, the shape of the array..." with pytest.raises(ValueError, match=message): derivative(lambda x: [1, 2, 3], xp.asarray([-2, -3])) message = 'Tolerances and step parameters must be non-negative...' with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, tolerances=dict(atol=-1)) with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, tolerances=dict(rtol='ekki')) with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, step_factor=object()) message = '`maxiter` must be a positive integer.' with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, maxiter=1.5) with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, maxiter=0) message = '`order` must be a positive integer' with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, order=1.5) with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, order=0) message = '`preserve_shape` must be True or False.' with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, preserve_shape='herring') message = '`callback` must be callable.' with pytest.raises(ValueError, match=message): derivative(lambda x: x, one, callback='shrubbery') def test_special_cases(self, xp): # Test edge cases and other special cases # Test that integers are not passed to `f` # (otherwise this would overflow) def f(x): assert xp.isdtype(x.dtype, 'real floating') return x ** 99 - 1 if not is_torch(xp): # torch defaults to float32 res = derivative(f, xp.asarray(7), tolerances=dict(rtol=1e-10)) assert res.success xp_assert_close(res.df, xp.asarray(99*7.**98)) # Test invalid step size and direction res = derivative(xp.exp, xp.asarray(1), step_direction=xp.nan) xp_assert_equal(res.df, xp.asarray(xp.nan)) xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32)) res = derivative(xp.exp, xp.asarray(1), initial_step=0) xp_assert_equal(res.df, xp.asarray(xp.nan)) xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32)) # Test that if success is achieved in the correct number # of iterations if function is a polynomial. Ideally, all polynomials # of order 0-2 would get exact result with 0 refinement iterations, # all polynomials of order 3-4 would be differentiated exactly after # 1 iteration, etc. However, it seems that `derivative` needs an # extra iteration to detect convergence based on the error estimate. for n in range(6): x = xp.asarray(1.5, dtype=xp.float64) def f(x): return 2*x**n ref = 2*n*x**(n-1) res = derivative(f, x, maxiter=1, order=max(1, n)) xp_assert_close(res.df, ref, rtol=1e-15) xp_assert_equal(res.error, xp.asarray(xp.nan, dtype=xp.float64)) res = derivative(f, x, order=max(1, n)) assert res.success assert res.nit == 2 xp_assert_close(res.df, ref, rtol=1e-15) # Test scalar `args` (not in tuple) def f(x, c): return c*x - 1 res = derivative(f, xp.asarray(2), args=xp.asarray(3)) xp_assert_close(res.df, xp.asarray(3.)) # no need to run a test on multiple backends if it's xfailed @pytest.mark.skip_xp_backends(np_only=True) @pytest.mark.xfail @pytest.mark.parametrize("case", ( # function, evaluation point (lambda x: (x - 1) ** 3, 1), (lambda x: np.where(x > 1, (x - 1) ** 5, (x - 1) ** 3), 1) )) def test_saddle_gh18811(self, case, xp): # With default settings, `derivative` will not always converge when # the true derivative is exactly zero. This tests that specifying a # (tight) `atol` alleviates the problem. See discussion in gh-18811. atol = 1e-16 res = derivative(*case, step_direction=[-1, 0, 1], atol=atol) assert np.all(res.success) xp_assert_close(res.df, 0, atol=atol)
TestDerivative
python
eventlet__eventlet
eventlet/dagpool.py
{ "start": 1418, "end": 26180 }
class ____: """ A DAGPool is a pool that constrains greenthreads, not by max concurrency, but by data dependencies. This is a way to implement general DAG dependencies. A simple dependency tree (flowing in either direction) can straightforwardly be implemented using recursion and (e.g.) :meth:`GreenThread.imap() <eventlet.greenthread.GreenThread.imap>`. What gets complicated is when a given node depends on several other nodes as well as contributing to several other nodes. With DAGPool, you concurrently launch all applicable greenthreads; each will proceed as soon as it has all required inputs. The DAG is implicit in which items are required by each greenthread. Each greenthread is launched in a DAGPool with a key: any value that can serve as a Python dict key. The caller also specifies an iterable of other keys on which this greenthread depends. This iterable may be empty. The greenthread callable must accept (key, results), where: key is its own key results is an iterable of (key, value) pairs. A newly-launched DAGPool greenthread is entered immediately, and can perform any necessary setup work. At some point it will iterate over the (key, value) pairs from the passed 'results' iterable. Doing so blocks the greenthread until a value is available for each of the keys specified in its initial dependencies iterable. These (key, value) pairs are delivered in chronological order, *not* the order in which they are initially specified: each value will be delivered as soon as it becomes available. The value returned by a DAGPool greenthread becomes the value for its key, which unblocks any other greenthreads waiting on that key. If a DAGPool greenthread terminates with an exception instead of returning a value, attempting to retrieve the value raises :class:`PropagateError`, which binds the key of the original greenthread and the original exception. Unless the greenthread attempting to retrieve the value handles PropagateError, that exception will in turn be wrapped in a PropagateError of its own, and so forth. The code that ultimately handles PropagateError can follow the chain of PropagateError.exc attributes to discover the flow of that exception through the DAG of greenthreads. External greenthreads may also interact with a DAGPool. See :meth:`wait_each`, :meth:`waitall`, :meth:`post`. It is not recommended to constrain external DAGPool producer greenthreads in a :class:`GreenPool <eventlet.greenpool.GreenPool>`: it may be hard to provably avoid deadlock. .. automethod:: __init__ .. automethod:: __getitem__ """ _Coro = collections.namedtuple("_Coro", ("greenthread", "pending")) def __init__(self, preload={}): """ DAGPool can be prepopulated with an initial dict or iterable of (key, value) pairs. These (key, value) pairs are of course immediately available for any greenthread that depends on any of those keys. """ try: # If a dict is passed, copy it. Don't risk a subsequent # modification to passed dict affecting our internal state. iteritems = preload.items() except AttributeError: # Not a dict, just an iterable of (key, value) pairs iteritems = preload # Load the initial dict self.values = dict(iteritems) # track greenthreads self.coros = {} # The key to blocking greenthreads is the Event. self.event = Event() def waitall(self): """ waitall() blocks the calling greenthread until there is a value for every DAGPool greenthread launched by :meth:`spawn`. It returns a dict containing all :class:`preload data <DAGPool>`, all data from :meth:`post` and all values returned by spawned greenthreads. See also :meth:`wait`. """ # waitall() is an alias for compatibility with GreenPool return self.wait() def wait(self, keys=_MISSING): """ *keys* is an optional iterable of keys. If you omit the argument, it waits for all the keys from :class:`preload data <DAGPool>`, from :meth:`post` calls and from :meth:`spawn` calls: in other words, all the keys of which this DAGPool is aware. wait() blocks the calling greenthread until all of the relevant keys have values. wait() returns a dict whose keys are the relevant keys, and whose values come from the *preload* data, from values returned by DAGPool greenthreads or from :meth:`post` calls. If a DAGPool greenthread terminates with an exception, wait() will raise :class:`PropagateError` wrapping that exception. If more than one greenthread terminates with an exception, it is indeterminate which one wait() will raise. If an external greenthread posts a :class:`PropagateError` instance, wait() will raise that PropagateError. If more than one greenthread posts PropagateError, it is indeterminate which one wait() will raise. See also :meth:`wait_each_success`, :meth:`wait_each_exception`. """ # This is mostly redundant with wait_each() functionality. return dict(self.wait_each(keys)) def wait_each(self, keys=_MISSING): """ *keys* is an optional iterable of keys. If you omit the argument, it waits for all the keys from :class:`preload data <DAGPool>`, from :meth:`post` calls and from :meth:`spawn` calls: in other words, all the keys of which this DAGPool is aware. wait_each() is a generator producing (key, value) pairs as a value becomes available for each requested key. wait_each() blocks the calling greenthread until the next value becomes available. If the DAGPool was prepopulated with values for any of the relevant keys, of course those can be delivered immediately without waiting. Delivery order is intentionally decoupled from the initial sequence of keys: each value is delivered as soon as it becomes available. If multiple keys are available at the same time, wait_each() delivers each of the ready ones in arbitrary order before blocking again. The DAGPool does not distinguish between a value returned by one of its own greenthreads and one provided by a :meth:`post` call or *preload* data. The wait_each() generator terminates (raises StopIteration) when all specified keys have been delivered. Thus, typical usage might be: :: for key, value in dagpool.wait_each(keys): # process this ready key and value # continue processing now that we've gotten values for all keys By implication, if you pass wait_each() an empty iterable of keys, it returns immediately without yielding anything. If the value to be delivered is a :class:`PropagateError` exception object, the generator raises that PropagateError instead of yielding it. See also :meth:`wait_each_success`, :meth:`wait_each_exception`. """ # Build a local set() and then call _wait_each(). return self._wait_each(self._get_keyset_for_wait_each(keys)) def wait_each_success(self, keys=_MISSING): """ wait_each_success() filters results so that only success values are yielded. In other words, unlike :meth:`wait_each`, wait_each_success() will not raise :class:`PropagateError`. Not every provided (or defaulted) key will necessarily be represented, though naturally the generator will not finish until all have completed. In all other respects, wait_each_success() behaves like :meth:`wait_each`. """ for key, value in self._wait_each_raw(self._get_keyset_for_wait_each(keys)): if not isinstance(value, PropagateError): yield key, value def wait_each_exception(self, keys=_MISSING): """ wait_each_exception() filters results so that only exceptions are yielded. Not every provided (or defaulted) key will necessarily be represented, though naturally the generator will not finish until all have completed. Unlike other DAGPool methods, wait_each_exception() simply yields :class:`PropagateError` instances as values rather than raising them. In all other respects, wait_each_exception() behaves like :meth:`wait_each`. """ for key, value in self._wait_each_raw(self._get_keyset_for_wait_each(keys)): if isinstance(value, PropagateError): yield key, value def _get_keyset_for_wait_each(self, keys): """ wait_each(), wait_each_success() and wait_each_exception() promise that if you pass an iterable of keys, the method will wait for results from those keys -- but if you omit the keys argument, the method will wait for results from all known keys. This helper implements that distinction, returning a set() of the relevant keys. """ if keys is not _MISSING: return set(keys) else: # keys arg omitted -- use all the keys we know about return set(self.coros.keys()) | set(self.values.keys()) def _wait_each(self, pending): """ When _wait_each() encounters a value of PropagateError, it raises it. In all other respects, _wait_each() behaves like _wait_each_raw(). """ for key, value in self._wait_each_raw(pending): yield key, self._value_or_raise(value) @staticmethod def _value_or_raise(value): # Most methods attempting to deliver PropagateError should raise that # instead of simply returning it. if isinstance(value, PropagateError): raise value return value def _wait_each_raw(self, pending): """ pending is a set() of keys for which we intend to wait. THIS SET WILL BE DESTRUCTIVELY MODIFIED: as each key acquires a value, that key will be removed from the passed 'pending' set. _wait_each_raw() does not treat a PropagateError instance specially: it will be yielded to the caller like any other value. In all other respects, _wait_each_raw() behaves like wait_each(). """ while True: # Before even waiting, show caller any (key, value) pairs that # are already available. Copy 'pending' because we want to be able # to remove items from the original set while iterating. for key in pending.copy(): value = self.values.get(key, _MISSING) if value is not _MISSING: # found one, it's no longer pending pending.remove(key) yield (key, value) if not pending: # Once we've yielded all the caller's keys, done. break # There are still more keys pending, so wait. self.event.wait() def spawn(self, key, depends, function, *args, **kwds): """ Launch the passed *function(key, results, ...)* as a greenthread, passing it: - the specified *key* - an iterable of (key, value) pairs - whatever other positional args or keywords you specify. Iterating over the *results* iterable behaves like calling :meth:`wait_each(depends) <DAGPool.wait_each>`. Returning from *function()* behaves like :meth:`post(key, return_value) <DAGPool.post>`. If *function()* terminates with an exception, that exception is wrapped in :class:`PropagateError` with the greenthread's *key* and (effectively) posted as the value for that key. Attempting to retrieve that value will raise that PropagateError. Thus, if the greenthread with key 'a' terminates with an exception, and greenthread 'b' depends on 'a', when greenthread 'b' attempts to iterate through its *results* argument, it will encounter PropagateError. So by default, an uncaught exception will propagate through all the downstream dependencies. If you pass :meth:`spawn` a key already passed to spawn() or :meth:`post`, spawn() raises :class:`Collision`. """ if key in self.coros or key in self.values: raise Collision(key) # The order is a bit tricky. First construct the set() of keys. pending = set(depends) # It's important that we pass to _wait_each() the same 'pending' set() # that we store in self.coros for this key. The generator-iterator # returned by _wait_each() becomes the function's 'results' iterable. newcoro = greenthread.spawn(self._wrapper, function, key, self._wait_each(pending), *args, **kwds) # Also capture the same (!) set in the new _Coro object for this key. # We must be able to observe ready keys being removed from the set. self.coros[key] = self._Coro(newcoro, pending) def _wrapper(self, function, key, results, *args, **kwds): """ This wrapper runs the top-level function in a DAGPool greenthread, posting its return value (or PropagateError) to the DAGPool. """ try: # call our passed function result = function(key, results, *args, **kwds) except Exception as err: # Wrap any exception it may raise in a PropagateError. result = PropagateError(key, err) finally: # function() has returned (or terminated with an exception). We no # longer need to track this greenthread in self.coros. Remove it # first so post() won't complain about a running greenthread. del self.coros[key] try: # as advertised, try to post() our return value self.post(key, result) except Collision: # if we've already post()ed a result, oh well pass # also, in case anyone cares... return result def spawn_many(self, depends, function, *args, **kwds): """ spawn_many() accepts a single *function* whose parameters are the same as for :meth:`spawn`. The difference is that spawn_many() accepts a dependency dict *depends*. A new greenthread is spawned for each key in the dict. That dict key's value should be an iterable of other keys on which this greenthread depends. If the *depends* dict contains any key already passed to :meth:`spawn` or :meth:`post`, spawn_many() raises :class:`Collision`. It is indeterminate how many of the other keys in *depends* will have successfully spawned greenthreads. """ # Iterate over 'depends' items, relying on self.spawn() not to # context-switch so no one can modify 'depends' along the way. for key, deps in depends.items(): self.spawn(key, deps, function, *args, **kwds) def kill(self, key): """ Kill the greenthread that was spawned with the specified *key*. If no such greenthread was spawned, raise KeyError. """ # let KeyError, if any, propagate self.coros[key].greenthread.kill() # once killed, remove it del self.coros[key] def post(self, key, value, replace=False): """ post(key, value) stores the passed *value* for the passed *key*. It then causes each greenthread blocked on its results iterable, or on :meth:`wait_each(keys) <DAGPool.wait_each>`, to check for new values. A waiting greenthread might not literally resume on every single post() of a relevant key, but the first post() of a relevant key ensures that it will resume eventually, and when it does it will catch up with all relevant post() calls. Calling post(key, value) when there is a running greenthread with that same *key* raises :class:`Collision`. If you must post(key, value) instead of letting the greenthread run to completion, you must first call :meth:`kill(key) <DAGPool.kill>`. The DAGPool implicitly post()s the return value from each of its greenthreads. But a greenthread may explicitly post() a value for its own key, which will cause its return value to be discarded. Calling post(key, value, replace=False) (the default *replace*) when a value for that key has already been posted, by any means, raises :class:`Collision`. Calling post(key, value, replace=True) when a value for that key has already been posted, by any means, replaces the previously-stored value. However, that may make it complicated to reason about the behavior of greenthreads waiting on that key. After a post(key, value1) followed by post(key, value2, replace=True), it is unspecified which pending :meth:`wait_each([key...]) <DAGPool.wait_each>` calls (or greenthreads iterating over *results* involving that key) will observe *value1* versus *value2*. It is guaranteed that subsequent wait_each([key...]) calls (or greenthreads spawned after that point) will observe *value2*. A successful call to post(key, :class:`PropagateError(key, ExceptionSubclass) <PropagateError>`) ensures that any subsequent attempt to retrieve that key's value will raise that PropagateError instance. """ # First, check if we're trying to post() to a key with a running # greenthread. # A DAGPool greenthread is explicitly permitted to post() to its # OWN key. coro = self.coros.get(key, _MISSING) if coro is not _MISSING and coro.greenthread is not greenthread.getcurrent(): # oh oh, trying to post a value for running greenthread from # some other greenthread raise Collision(key) # Here, either we're posting a value for a key with no greenthread or # we're posting from that greenthread itself. # Has somebody already post()ed a value for this key? # Unless replace == True, this is a problem. if key in self.values and not replace: raise Collision(key) # Either we've never before posted a value for this key, or we're # posting with replace == True. # update our database self.values[key] = value # and wake up pending waiters self.event.send() # The comment in Event.reset() says: "it's better to create a new # event rather than reset an old one". Okay, fine. We do want to be # able to support new waiters, so create a new Event. self.event = Event() def __getitem__(self, key): """ __getitem__(key) (aka dagpool[key]) blocks until *key* has a value, then delivers that value. """ # This is a degenerate case of wait_each(). Construct a tuple # containing only this 'key'. wait_each() will yield exactly one (key, # value) pair. Return just its value. for _, value in self.wait_each((key,)): return value def get(self, key, default=None): """ get() returns the value for *key*. If *key* does not yet have a value, get() returns *default*. """ return self._value_or_raise(self.values.get(key, default)) def keys(self): """ Return a snapshot tuple of keys for which we currently have values. """ # Explicitly return a copy rather than an iterator: don't assume our # caller will finish iterating before new values are posted. return tuple(self.values.keys()) def items(self): """ Return a snapshot tuple of currently-available (key, value) pairs. """ # Don't assume our caller will finish iterating before new values are # posted. return tuple((key, self._value_or_raise(value)) for key, value in self.values.items()) def running(self): """ Return number of running DAGPool greenthreads. This includes greenthreads blocked while iterating through their *results* iterable, that is, greenthreads waiting on values from other keys. """ return len(self.coros) def running_keys(self): """ Return keys for running DAGPool greenthreads. This includes greenthreads blocked while iterating through their *results* iterable, that is, greenthreads waiting on values from other keys. """ # return snapshot; don't assume caller will finish iterating before we # next modify self.coros return tuple(self.coros.keys()) def waiting(self): """ Return number of waiting DAGPool greenthreads, that is, greenthreads still waiting on values from other keys. This explicitly does *not* include external greenthreads waiting on :meth:`wait`, :meth:`waitall`, :meth:`wait_each`. """ # n.b. if Event would provide a count of its waiters, we could say # something about external greenthreads as well. # The logic to determine this count is exactly the same as the general # waiting_for() call. return len(self.waiting_for()) # Use _MISSING instead of None as the default 'key' param so we can permit # None as a supported key. def waiting_for(self, key=_MISSING): """ waiting_for(key) returns a set() of the keys for which the DAGPool greenthread spawned with that *key* is still waiting. If you pass a *key* for which no greenthread was spawned, waiting_for() raises KeyError. waiting_for() without argument returns a dict. Its keys are the keys of DAGPool greenthreads still waiting on one or more values. In the returned dict, the value of each such key is the set of other keys for which that greenthread is still waiting. This method allows diagnosing a "hung" DAGPool. If certain greenthreads are making no progress, it's possible that they are waiting on keys for which there is no greenthread and no :meth:`post` data. """ # We may have greenthreads whose 'pending' entry indicates they're # waiting on some keys even though values have now been posted for # some or all of those keys, because those greenthreads have not yet # regained control since values were posted. So make a point of # excluding values that are now available. available = set(self.values.keys()) if key is not _MISSING: # waiting_for(key) is semantically different than waiting_for(). # It's just that they both seem to want the same method name. coro = self.coros.get(key, _MISSING) if coro is _MISSING: # Hmm, no running greenthread with this key. But was there # EVER a greenthread with this key? If not, let KeyError # propagate. self.values[key] # Oh good, there's a value for this key. Either the # greenthread finished, or somebody posted a value. Just say # the greenthread isn't waiting for anything. return set() else: # coro is the _Coro for the running greenthread with the # specified key. return coro.pending - available # This is a waiting_for() call, i.e. a general query rather than for a # specific key. # Start by iterating over (key, coro) pairs in self.coros. Generate # (key, pending) pairs in which 'pending' is the set of keys on which # the greenthread believes it's waiting, minus the set of keys that # are now available. Filter out any pair in which 'pending' is empty, # that is, that greenthread will be unblocked next time it resumes. # Make a dict from those pairs. return {key: pending for key, pending in ((key, (coro.pending - available)) for key, coro in self.coros.items()) if pending}
DAGPool
python
dagster-io__dagster
python_modules/dagster/dagster/components/definitions.py
{ "start": 569, "end": 5762 }
class ____(Generic[T_Defs]): """An object that can be invoked to load a set of definitions.""" load_fn: Callable[..., T_Defs] has_context_arg: bool def __call__(self, context: Optional[ComponentLoadContext] = None) -> T_Defs: """Load a set of definitions using the load_fn provided at construction time. Args: context (Optional[ComponentLoadContext]): Optional context for loading definitions. Returns: T_Defs: The loaded definitions. """ if self.has_context_arg: if context is None: raise DagsterInvariantViolationError( "Function requires a ComponentLoadContext but none was provided" ) result = self.load_fn(context) else: result = self.load_fn() if not isinstance(result, (Definitions, RepositoryDefinition)): raise DagsterInvariantViolationError( "Function must return a Definitions or RepositoryDefinition object" ) return result @public def definitions( fn: Union[Callable[[], Definitions], Callable[[ComponentLoadContext], Definitions]], ) -> Callable[..., Definitions]: """Decorator that marks a function as an entry point for loading Dagster definitions. This decorator provides a lazy loading mechanism for Definitions objects, which is the preferred approach over directly instantiating Definitions at module import time. It enables Dagster's tools to discover and load definitions on-demand without executing the definition creation logic during module imports. The user can also import this function and import it for test cases. The decorated function must return a Definitions object and can optionally accept a ComponentLoadContext parameter, populated when loaded in the context of autoloaded defs folders in the dg project layout. Args: fn: A function that returns a Definitions object. The function can either: - Accept no parameters: ``() -> Definitions`` - Accept a ComponentLoadContext: ``(ComponentLoadContext) -> Definitions`` Returns: A callable that will invoke the original function and return its Definitions object when called by Dagster's loading mechanisms or directly by the user. Raises: DagsterInvariantViolationError: If the function signature doesn't match the expected patterns (no parameters or exactly one ComponentLoadContext parameter). Examples: Basic usage without context: .. code-block:: python import dagster as dg @dg.definitions def my_definitions(): @dg.asset def sales_data(): return [1, 2, 3] return dg.Definitions(assets=[sales_data]) Usage with ComponentLoadContext for autoloaded definitions: .. code-block:: python import dagster as dg @dg.definitions def my_definitions(context: dg.ComponentLoadContext): @dg.asset def sales_data(): # Can use context for environment-specific logic return load_data_from(context.path) return dg.Definitions(assets=[sales_data]) The decorated function can be imported and used by Dagster tools: .. code-block:: python # my_definitions.py @dg.definitions def defs(): return dg.Definitions(assets=[my_asset]) # dg dev -f my_definitions.py Note: When used in autoloaded defs folders, the ComponentLoadContext provides access to environment variables and other contextual information for dynamic definition loading. See Also: - :py:class:`dagster.Definitions`: The object that should be returned by the decorated function - :py:class:`dagster.ComponentLoadContext`: Context object for autoloaded definitions """ sig = inspect.signature(fn) has_context_arg = False if len(sig.parameters) > 0: first_param = next(iter(sig.parameters.values())) if first_param.annotation == ComponentLoadContext: has_context_arg = True if len(sig.parameters) > 1: raise DagsterInvariantViolationError( "Function must accept either no parameters or exactly one ComponentLoadContext parameter" ) else: raise DagsterInvariantViolationError( "Function must accept either no parameters or exactly one ComponentLoadContext parameter" ) lazy_defs = LazyDefinitions[Definitions](load_fn=fn, has_context_arg=has_context_arg) return cast("Callable[..., Definitions]", lazy_defs) # For backwards compatibility with existing test cases def lazy_repository(fn: Callable[[], RepositoryDefinition]) -> Callable[[], RepositoryDefinition]: lazy_defs = LazyDefinitions[RepositoryDefinition](load_fn=fn, has_context_arg=False) return cast("Callable[[], RepositoryDefinition]", lazy_defs)
LazyDefinitions
python
keras-team__keras
keras/src/backend/common/variables_test.py
{ "start": 33705, "end": 46492 }
class ____(test_case.TestCase): """Test the dtype to verify that the behavior matches JAX.""" ALL_DTYPES = [ x for x in dtypes.ALLOWED_DTYPES if x not in ( "string", "complex128", # Remove 64-bit dtypes. "float64", "uint64", "int64", ) + dtypes.FLOAT8_TYPES # Remove float8 dtypes for the following tests ] + [None] INT_DTYPES = [x for x in dtypes.INT_TYPES if x not in ("uint64", "int64")] FLOAT_DTYPES = [x for x in dtypes.FLOAT_TYPES if x not in ("float64",)] COMPLEX_DTYPES = ["complex32", "complex64"] if backend.backend() == "torch": ALL_DTYPES = [ x for x in ALL_DTYPES if x not in ("uint16", "uint32", "complex64") ] INT_DTYPES = [x for x in INT_DTYPES if x not in ("uint16", "uint32")] elif backend.backend() == "tensorflow": # TODO(hongyu): Re-enable uint32 tests once we determine how to handle # dtypes.result_type(uint32, int*) -> int64 promotion. # Since TF variables require int64 to be placed on the GPU, we # exclusively enable the int64 dtype for TF. However, JAX does not # natively support int64, which prevents us from comparing the dtypes. ALL_DTYPES = [x for x in ALL_DTYPES if x not in ("uint32",)] INT_DTYPES = [x for x in INT_DTYPES if x not in ("uint32",)] elif backend.backend() == "openvino": ALL_DTYPES = [x for x in ALL_DTYPES if x not in ("complex64",)] NON_COMPLEX_DTYPES = [ x for x in ALL_DTYPES if x and x not in ["complex32", "complex64"] ] @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_eq(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.equal(x1_jax, x2_jax).dtype) self.assertDType(x1 == x2, expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_ne(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.not_equal(x1_jax, x2_jax).dtype) self.assertDType(x1 != x2, expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(NON_COMPLEX_DTYPES, 2)) ) def test_lt(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.less(x1_jax, x2_jax).dtype) self.assertDType(x1 < x2, expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(NON_COMPLEX_DTYPES, 2)) ) def test_le(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.less_equal(x1_jax, x2_jax).dtype) self.assertDType(x1 <= x2, expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(NON_COMPLEX_DTYPES, 2)) ) def test_gt(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.greater(x1_jax, x2_jax).dtype) self.assertDType(x1 > x2, expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(NON_COMPLEX_DTYPES, 2)) ) def test_ge(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype( jnp.greater_equal(x1_jax, x2_jax).dtype ) self.assertDType(x1 >= x2, expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_add(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.add(x1_jax, x2_jax).dtype) self.assertDType(x1 + x2, expected_dtype) self.assertDType(x1.__radd__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_sub(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.add(x1_jax, x2_jax).dtype) self.assertDType(x1 - x2, expected_dtype) self.assertDType(x1.__rsub__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_mul(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.add(x1_jax, x2_jax).dtype) self.assertDType(x1 * x2, expected_dtype) self.assertDType(x1.__rmul__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(NON_COMPLEX_DTYPES, 2)) ) def test_truediv(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype( jnp.true_divide(x1_jax, x2_jax).dtype ) self.assertDType(x1 / x2, expected_dtype) self.assertDType(x1.__rtruediv__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(NON_COMPLEX_DTYPES, 2)) ) @skip_if_backend( "openvino", "`floor_divide` is not supported with openvino backend" ) def test_floordiv(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype( jnp.floor_divide(x1_jax, x2_jax).dtype ) self.assertDType(x1 // x2, expected_dtype) self.assertDType(x1.__rfloordiv__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(NON_COMPLEX_DTYPES, 2)) ) def test_mod(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.mod(x1_jax, x2_jax).dtype) self.assertDType(x1 % x2, expected_dtype) self.assertDType(x1.__rmod__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_pow(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.power(x1_jax, x2_jax).dtype) self.assertDType(x1**x2, expected_dtype) self.assertDType(x1.__rpow__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_matmul(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.matmul(x1_jax, x2_jax).dtype) self.assertDType(x1 @ x2, expected_dtype) self.assertDType(x1.__rmatmul__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_and(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype( jnp.logical_and(x1_jax, x2_jax).dtype ) self.assertDType(x1 & x2, expected_dtype) self.assertDType(x1.__rand__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_or(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype(jnp.logical_or(x1_jax, x2_jax).dtype) self.assertDType(x1 | x2, expected_dtype) self.assertDType(x1.__ror__(x2), expected_dtype) @parameterized.named_parameters( named_product(dtypes=itertools.combinations(ALL_DTYPES, 2)) ) def test_xor(self, dtypes): import jax.numpy as jnp dtype1, dtype2 = dtypes x1 = backend.Variable("ones", shape=(1,), dtype=dtype1, trainable=False) x2 = backend.Variable("ones", shape=(1,), dtype=dtype2, trainable=False) x1_jax = jnp.ones((1,), dtype=dtype1) x2_jax = jnp.ones((1,), dtype=dtype2) expected_dtype = standardize_dtype( jnp.logical_xor(x1_jax, x2_jax).dtype ) self.assertDType(x1 ^ x2, expected_dtype) self.assertDType(x1.__rxor__(x2), expected_dtype) @pytest.mark.skipif( backend.backend() != "torch", reason="Tests for standardize_shape with Torch backend", )
VariableOpsDTypeTest
python
google__pytype
pytype/pytd/optimize.py
{ "start": 12408, "end": 13881 }
class ____(visitors.Visitor): """Find common super classes. Optionally also uses abstract base classes. E.g., this changes def f(x: Union[list, tuple], y: Union[frozenset, set]) -> Union[int, float] to def f(x: Sequence, y: Set) -> Real """ def __init__(self, hierarchy): super().__init__() self.hierarchy = hierarchy def VisitUnionType(self, union): """Given a union type, try to find a simplification by using superclasses. This is a lossy optimization that tries to map a list of types to a common base type. For example, int and bool are both base classes of int, so it would convert "Union[int, bool]" to "int". Arguments: union: A union type. Returns: A simplified type, if available. """ intersection = self.hierarchy.ExpandSuperClasses(str(union.type_list[0])) for t in union.type_list[1:]: intersection.intersection_update( self.hierarchy.ExpandSuperClasses(str(t)) ) # Remove "redundant" superclasses, by removing everything from the tree # that's not a leaf. I.e., we don't need "object" if we have more # specialized types. new_type_list = tuple( pytd.NamedType(cls) for cls in intersection if not self.hierarchy.HasSubClassInSet(cls, intersection) ) if not new_type_list: return union # if types don't intersect, leave them alone return pytd_utils.JoinTypes(new_type_list)
FindCommonSuperClasses
python
weaviate__weaviate-python-client
weaviate/exceptions.py
{ "start": 11591, "end": 11855 }
class ____(WeaviateBaseError): """Is raised when the connection to Weaviate fails.""" def __init__(self, message: str = "") -> None: msg = f"""Connection to Weaviate failed. Details: {message}""" super().__init__(msg)
WeaviateConnectionError
python
scrapy__scrapy
scrapy/extensions/feedexport.py
{ "start": 8831, "end": 10326 }
class ____(BlockingFeedStorage): def __init__( self, uri: str, project_id: str | None, acl: str | None, *, feed_options: dict[str, Any] | None = None, ): self.project_id: str | None = project_id self.acl: str | None = acl u = urlparse(uri) assert u.hostname self.bucket_name: str = u.hostname self.blob_name: str = u.path[1:] # remove first "/" if feed_options and feed_options.get("overwrite", True) is False: logger.warning( "GCS does not support appending to files. To " "suppress this warning, remove the overwrite " "option from your FEEDS setting or set it to True." ) @classmethod def from_crawler( cls, crawler: Crawler, uri: str, *, feed_options: dict[str, Any] | None = None, ) -> Self: return cls( uri, crawler.settings["GCS_PROJECT_ID"], crawler.settings["FEED_STORAGE_GCS_ACL"] or None, feed_options=feed_options, ) def _store_in_thread(self, file: IO[bytes]) -> None: file.seek(0) from google.cloud.storage import Client # noqa: PLC0415 client = Client(project=self.project_id) bucket = client.get_bucket(self.bucket_name) blob = bucket.blob(self.blob_name) blob.upload_from_file(file, predefined_acl=self.acl)
GCSFeedStorage
python
wandb__wandb
wandb/sdk/lib/filesystem.py
{ "start": 14451, "end": 19824 }
class ____: """Tracks statistics about file linking operations.""" n_symlink: int = 0 n_hardlink: int = 0 n_copy: int = 0 n_copy_downgraded: int = 0 def record( self, mode: Literal["symlink", "hardlink", "copy"], downgraded: bool = False, ) -> None: """Record a file operation. Args: mode: Type of operation - "symlink", "hardlink", or "copy". downgraded: Whether policy was downgraded from "live" to "now". """ if mode == "symlink": self.n_symlink += 1 elif mode == "hardlink": self.n_hardlink += 1 elif mode == "copy": self.n_copy += 1 if downgraded: self.n_copy_downgraded += 1 def emit_warnings(self) -> None: """Emit appropriate warnings based on recorded operations.""" from wandb import termwarn if self.n_symlink: termwarn( f"Symlinked {self.n_symlink} file{'s' if self.n_symlink > 1 else ''} " "into the W&B run directory; call wandb.save again to sync new files." ) if self.n_hardlink: termwarn( f"Linked {self.n_hardlink} file{'s' if self.n_hardlink > 1 else ''} " "into the W&B run directory (hardlinks); call wandb.save again to sync new files." ) if self.n_copy: if self.n_copy_downgraded: termwarn( f"Copied {self.n_copy} file{'s' if self.n_copy > 1 else ''} " "(cross-volume or links unavailable). " "Downgrading policy to 'now' for those files because live updates " "won't propagate from the originals. Re-run wandb.save to resync, " "or place your run directory on the same drive to enable hardlinks." ) else: termwarn( f"Copied {self.n_copy} file{'s' if self.n_copy > 1 else ''} " "into the W&B run directory; call wandb.save again to sync new files." ) def validate_glob_path(glob_path: PurePath, base_path: PurePath) -> None: """Validate that glob path is within base path. Args: glob_path: The glob pattern path to validate. base_path: The base path that should contain the glob. Raises: ValueError: If validation fails. """ if not str(glob_path).startswith(str(base_path)): raise ValueError("Glob may not walk above the base path") if glob_path == base_path: raise ValueError("Glob cannot be the same as the base path") relative_glob = glob_path.relative_to(base_path) if relative_glob.parts and relative_glob.parts[0] == "*": raise ValueError("Glob may not start with '*' relative to the base path") def are_paths_on_same_drive(path1: Path, path2: Path) -> bool: """Check if two paths are on the same drive. This check is only relevant on Windows, since the concept of drives only exists on Windows. """ if platform.system() != "Windows": return True try: path1_drive = path1.resolve().drive path2_drive = path2.resolve().drive except OSError: # If either path is not a valid Windows path, an OSError is raised. return False return path1_drive == path2_drive def unlink_path(path: Path) -> None: """Best-effort removal of a pre-existing file/symlink/dir. Args: path: Path to remove. """ with contextlib.suppress(FileNotFoundError): if path.is_symlink() or path.is_file(): path.unlink() def link_or_copy_with_policy( settings: Settings, src: Path, dst: Path, requested_policy: PolicyName, stats: LinkStats, ) -> PolicyName: """Link or copy a file using the best available method. Tries strategies in order: symlink -> hardlink -> copy. Updates stats and returns the effective policy. Args: settings: wandb settings object with symlink preference. src: Source file path. dst: Destination file path. requested_policy: Requested upload policy ("live", "now", or "end"). stats: Stats object to update with operation type. Returns: Effective policy after any necessary downgrade. """ # Strategy 1: Symlink (if allowed by settings) if settings.symlink: try: dst.symlink_to(src, target_is_directory=src.is_dir()) stats.record("symlink") except (OSError, NotImplementedError): pass else: return requested_policy # Strategy 2: Hardlink (same volume) if are_paths_on_same_drive(src, dst.parent): try: os.link(str(src), str(dst)) stats.record("hardlink") except OSError: pass else: return requested_policy # Strategy 3: Copy (atomic via temp file) tmp = dst.with_name(dst.name + ".tmp~wandb") shutil.copy2(str(src), str(tmp)) os.replace(str(tmp), str(dst)) # Downgrade live->now for copied files since changes won't propagate effective = "now" if requested_policy == "live" else requested_policy stats.record("copy", downgraded=(requested_policy == "live")) return effective
LinkStats
python
graphql-python__graphene
graphene/types/context.py
{ "start": 0, "end": 791 }
class ____: """ Context can be used to make a convenient container for attributes to provide for execution for resolvers of a GraphQL operation like a query. .. code:: python from graphene import Context context = Context(loaders=build_dataloaders(), request=my_web_request) schema.execute('{ hello(name: "world") }', context=context) def resolve_hello(parent, info, name): info.context.request # value set in Context info.context.loaders # value set in Context # ... args: **params (Dict[str, Any]): values to make available on Context instance as attributes. """ def __init__(self, **params): for key, value in params.items(): setattr(self, key, value)
Context
python
huggingface__transformers
src/transformers/models/vitpose_backbone/modeling_vitpose_backbone.py
{ "start": 2922, "end": 4888 }
class ____(nn.Module): """ Construct the position and patch embeddings. """ def __init__(self, config: VitPoseBackboneConfig): super().__init__() self.patch_embeddings = VitPoseBackbonePatchEmbeddings(config) num_patches = self.patch_embeddings.num_patches self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size)) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: embeddings = self.patch_embeddings(pixel_values) # add positional encoding to each token embeddings = embeddings + self.position_embeddings[:, 1:] + self.position_embeddings[:, :1] embeddings = self.dropout(embeddings) return embeddings # Copied from transformers.models.bert.modeling_bert.eager_attention_forward def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], scaling: Optional[float] = None, dropout: float = 0.0, **kwargs: Unpack[TransformersKwargs], ): if scaling is None: scaling = query.size(-1) ** -0.5 # Take the dot product between "query" and "key" to get the raw attention scores. attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling if attention_mask is not None: attention_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) attn_output = torch.matmul(attn_weights, value) attn_output = attn_output.transpose(1, 2).contiguous() return attn_output, attn_weights # Copied from transformers.models.vit.modeling_vit.ViTSelfAttention with ViT->VitPoseBackbone
VitPoseBackboneEmbeddings
python
pytorch__pytorch
torch/_dynamo/backends/debugging.py
{ "start": 13506, "end": 16820 }
class ____: """ This is the output of :func:`torch._dynamo.explain()` There is no reason to create this class directly. """ graphs: list[torch.fx.GraphModule] graph_count: int graph_break_count: int break_reasons: list[GraphCompileReason] op_count: int ops_per_graph: Optional[list[list["Target"]]] = None out_guards: Optional[list[_guards.Guard]] = None compile_times: Optional[str] = None def __str__(self) -> str: output = f"Graph Count: {self.graph_count}\n" output += f"Graph Break Count: {self.graph_break_count}\n" output += f"Op Count: {self.op_count}\n" output += "Break Reasons:\n" for idx, break_reason in enumerate(self.break_reasons): output += f" Break Reason {idx + 1}:\n" output += f" Reason: {break_reason.reason}\n" output += " User Stack:\n" for frame_summary in break_reason.user_stack: output += f" {frame_summary}\n" if self.ops_per_graph is not None: output += "Ops per Graph:\n" for idx, ops in enumerate(self.ops_per_graph): output += f" Ops {idx + 1}:\n" for op in ops: output += f" {op}\n" if self.out_guards is not None: output += "Out Guards:\n" for i, guard in enumerate(self.out_guards): output += f" Guard {i + 1}:\n" output += f" {str(guard)}" if self.compile_times is not None: output += f"Compile Times: {self.compile_times}\n" return output def _explain_graph_detail( gm: torch.fx.GraphModule, graphs: list[torch.fx.GraphModule], op_count: int, ops_per_graph: list[list["Target"]], break_reasons: list[GraphCompileReason], ) -> tuple[ torch.fx.GraphModule, list[torch.fx.GraphModule], int, list[list["Target"]], list[GraphCompileReason], ]: """ This function is a utility which processes a torch.fx.GraphModule and accumulates information about its ops, graph breaks, and other details. It is intended to be used by the ExplainWithBackend class and `torch._dynamo.explain()` to provide details from Dynamo's graph capture. Parameters: gm (torch.fx.GraphModule): The GraphModule to be processed. graphs (list): A list that accumulates all the GraphModules processed. op_count (int): The total count of operations in all GraphModules processed so far. ops_per_graph (list): A list that accumulates the operations of each GraphModule. break_reasons (list): A list that accumulates the reasons for breaks in each GraphModule. Returns: tuple: A tuple containing the processed GraphModule, the updated lists of graphs, operations per graph, and break reasons, and the updated operation count. """ graphs.append(gm) ops = [node.target for node in gm.graph.nodes if node.op == "call_function"] op_count += len(ops) ops_per_graph.append(ops) if gm.compile_subgraph_reason.graph_break: # type: ignore[union-attr] break_reasons.append(gm.compile_subgraph_reason) # type: ignore[arg-type] return gm, graphs, op_count, ops_per_graph, break_reasons
ExplainOutput
python
pypa__warehouse
tests/unit/email/test_init.py
{ "start": 101717, "end": 103974 }
class ____: @pytest.fixture def _organization_rename(self, pyramid_user): self.user = UserFactory.create() EmailFactory.create(user=self.user, verified=True) self.organization_name = "example" self.previous_organization_name = "examplegroup" @pytest.mark.usefixtures("_organization_rename") def test_send_organization_renamed_email( self, db_request, make_email_renderers, send_email, ): subject_renderer, body_renderer, html_renderer = make_email_renderers( "organization-renamed" ) result = email.send_organization_renamed_email( db_request, self.user, organization_name=self.organization_name, previous_organization_name=self.previous_organization_name, ) assert result == { "organization_name": self.organization_name, "previous_organization_name": self.previous_organization_name, } subject_renderer.assert_(**result) body_renderer.assert_(**result) html_renderer.assert_(**result) assert db_request.task.calls == [pretend.call(send_email)] assert send_email.delay.calls == [ pretend.call( f"{self.user.name} <{self.user.email}>", { "sender": None, "subject": subject_renderer.string_response, "body_text": body_renderer.string_response, "body_html": ( f"<html>\n" f"<head></head>\n" f"<body><p>{html_renderer.string_response}</p></body>\n" f"</html>\n" ), }, { "tag": "account:email:sent", "user_id": self.user.id, "additional": { "from_": db_request.registry.settings["mail.sender"], "to": self.user.email, "subject": subject_renderer.string_response, "redact_ip": True, }, }, ) ]
TestOrganizationRenameEmails
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-oci-data-science/tests/test_oci_data_science_utils.py
{ "start": 4150, "end": 5322 }
class ____: """Unit tests for _from_completion_logprobs_dict function.""" def test_conversion(self): """Ensures completion logprobs are converted correctly.""" logprobs = { "tokens": ["Hello", "world"], "token_logprobs": [-0.1, -0.2], "top_logprobs": [ {"Hello": -0.1, "Hi": -1.0}, {"world": -0.2, "earth": -1.2}, ], } expected_result = [ [ LogProb(token="Hello", logprob=-0.1, bytes=[]), LogProb(token="Hi", logprob=-1.0, bytes=[]), ], [ LogProb(token="world", logprob=-0.2, bytes=[]), LogProb(token="earth", logprob=-1.2, bytes=[]), ], ] result = _from_completion_logprobs_dict(logprobs) assert result == expected_result def test_empty_logprobs(self): """Ensures function returns empty list when no logprobs are provided.""" logprobs = {} expected_result = [] result = _from_completion_logprobs_dict(logprobs) assert result == expected_result
TestFromCompletionLogprobs
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 818979, "end": 819156 }
class ____(VegaLiteSchema): """Orient schema wrapper.""" _schema = {"$ref": "#/definitions/Orient"} def __init__(self, *args): super().__init__(*args)
Orient
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0058_update_timestamp_fields.py
{ "start": 120, "end": 427 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0057_add_page_rank"), ] operations = [ migrations.AlterModelOptions( name="environmentvariable", options={"get_latest_by": "modified"}, ), ]
Migration
python
readthedocs__readthedocs.org
readthedocs/storage/rclone.py
{ "start": 265, "end": 3696 }
class ____: """ RClone base class. This class allows you to interact with an rclone remote without a configuration file, the remote declaration and its options are passed in the command itself. This base class allows you to use the local file system as remote. :param remote_type: You can see the full list of supported providers at https://rclone.org/#providers. :param rclone_bin: Binary name or path to the rclone binary. Defaults to ``rclone``. :param default_options: Options passed to the rclone command. :parm env_vars: Environment variables used when executing the rclone command. Useful to pass secrets to the ``rclone` command, since all arguments and options will be logged. """ remote_type = None rclone_bin = "rclone" default_options = [ # Number of file transfers to run in parallel. # Default value is 4. "--transfers=8", # Skip based on checksum (if available) & size, not mod-time & size. "--checksum", "--verbose", # Retry some times before failing # (3 is the default, but making it explicit here) "--retries=3", # Wait 1 second between each retry "--retries-sleep=1s", ] env_vars = {} def _get_target_path(self, path): """ Get the final target path for the remote. .. note:: This doesn't include the remote type, this is just the destination path. """ raise NotImplementedError def get_target(self, path): """ Get the proper target using the current remote type. We start the remote with `:` to create it on the fly, instead of having to create a configuration file. See https://rclone.org/docs/#backend-path-to-dir. :param path: Path to the remote target. """ path = self._get_target_path(path) return f":{self.remote_type}:{path}" def execute(self, subcommand, args, options=None): """ Execute an rclone subcommand. :param subcommand: Name of the subcommand. :param list args: List of positional arguments passed the to command. :param list options: List of options passed to the command. """ options = options or [] command = [ self.rclone_bin, subcommand, *self.default_options, *options, "--", *args, ] env = os.environ.copy() env.update(self.env_vars) log.info("Executing rclone command.", command=command) log.debug("Executing rclone commmad.", env=env) result = subprocess.run( command, capture_output=True, env=env, check=True, ) log.debug( "rclone execution finished.", stdout=result.stdout.decode(), stderr=result.stderr.decode(), exit_code=result.returncode, ) return result def sync(self, source, destination): """ Run the `rclone sync` command. See https://rclone.org/commands/rclone_sync/. :params source: Local path to the source directory. :params destination: Remote path to the destination directory. """ return self.execute("sync", args=[source, self.get_target(destination)])
BaseRClone
python
tensorflow__tensorflow
tensorflow/lite/python/convert_phase.py
{ "start": 4584, "end": 8021 }
class ____(Exception): """Raised when an error occurs during model conversion.""" def __init__(self, message): super(ConverterError, self).__init__(message) self.errors = [] self._parse_error_message(message) def append_error(self, error_data: converter_error_data_pb2.ConverterErrorData): self.errors.append(error_data) def _parse_error_message(self, message): """If the message matches a pattern, assigns the associated error code. It is difficult to assign an error code to some errrors in MLIR side, Ex: errors thrown by other components than TFLite or not using mlir::emitError. This function try to detect them by the error message and assign the corresponding error code. Args: message: The error message of this exception. """ error_code_mapping = { "Failed to functionalize Control Flow V1 ops. Consider using Control " "Flow V2 ops instead. See https://www.tensorflow.org/api_docs/python/" "tf/compat/v1/enable_control_flow_v2.": converter_error_data_pb2.ConverterErrorData .ERROR_UNSUPPORTED_CONTROL_FLOW_V1, } for pattern, error_code in error_code_mapping.items(): if pattern in message: error_data = converter_error_data_pb2.ConverterErrorData() error_data.error_message = message error_data.error_code = error_code self.append_error(error_data) return def convert_phase(component, subcomponent=SubComponent.UNSPECIFIED): """The decorator to identify converter component and subcomponent. Args: component: Converter component name. subcomponent: Converter subcomponent name. Returns: Forward the result from the wrapped function. Raises: ValueError: if component and subcomponent name is not valid. """ if component not in Component: raise ValueError("Given component name not found") if subcomponent not in SubComponent: raise ValueError("Given subcomponent name not found") if (subcomponent != SubComponent.UNSPECIFIED and subcomponent.component != component): raise ValueError("component and subcomponent name don't match") def report_error(error_data: converter_error_data_pb2.ConverterErrorData): # Always overwrites the component information, but only overwrites the # subcomponent if it is not available. error_data.component = component.value if not error_data.subcomponent: error_data.subcomponent = subcomponent.name tflite_metrics = metrics.TFLiteConverterMetrics() tflite_metrics.set_converter_error(error_data) def report_error_message(error_message: Text): error_data = converter_error_data_pb2.ConverterErrorData() error_data.error_message = error_message report_error(error_data) def actual_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ConverterError as converter_error: if converter_error.errors: for error_data in converter_error.errors: report_error(error_data) else: report_error_message(str(converter_error)) raise converter_error from None # Re-throws the exception. except Exception as error: report_error_message(str(error)) raise error from None # Re-throws the exception. return wrapper return actual_decorator
ConverterError
python
readthedocs__readthedocs.org
readthedocs/oauth/migrations/0013_create_new_table_for_remote_repository_normalization.py
{ "start": 251, "end": 8439 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("socialaccount", "0003_extra_data_default_dict"), ("projects", "0067_change_max_length_feature_id"), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("oauth", "0012_create_new_table_for_remote_organization_normalization"), ] operations = [ migrations.CreateModel( name="RemoteRepository", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "created", django_extensions.db.fields.CreationDateTimeField( auto_now_add=True, verbose_name="created" ), ), ( "modified", django_extensions.db.fields.ModificationDateTimeField( auto_now=True, verbose_name="modified" ), ), ("name", models.CharField(max_length=255, verbose_name="Name")), ( "full_name", models.CharField(db_index=True, max_length=255, verbose_name="Full Name"), ), ( "description", models.TextField( blank=True, help_text="Description of the project", null=True, verbose_name="Description", ), ), ( "avatar_url", models.URLField(blank=True, null=True, verbose_name="Owner avatar image URL"), ), ( "ssh_url", models.URLField( blank=True, max_length=512, validators=[django.core.validators.URLValidator(schemes=["ssh"])], verbose_name="SSH URL", ), ), ( "clone_url", models.URLField( blank=True, max_length=512, validators=[ django.core.validators.URLValidator( schemes=["http", "https", "ssh", "git", "svn"] ) ], verbose_name="Repository clone URL", ), ), ( "html_url", models.URLField(blank=True, null=True, verbose_name="HTML URL"), ), ( "private", models.BooleanField(default=False, verbose_name="Private repository"), ), ( "vcs", models.CharField( blank=True, choices=[ ("git", "Git"), ("svn", "Subversion"), ("hg", "Mercurial"), ("bzr", "Bazaar"), ], max_length=200, verbose_name="vcs", ), ), ( "default_branch", models.CharField( blank=True, max_length=150, null=True, verbose_name="Default branch of the repository", ), ), ("remote_id", models.CharField(db_index=True, max_length=128)), ( "vcs_provider", models.CharField( choices=[ ("github", "GitHub"), ("gitlab", "GitLab"), ("bitbucket", "Bitbucket"), ], max_length=32, verbose_name="VCS provider", ), ), ( "organization", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name="repositories", to="oauth.RemoteOrganization", verbose_name="Organization", ), ), ( "project", models.OneToOneField( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="remote_repository", to="projects.Project", ), ), ], options={ "verbose_name_plural": "remote repositories", "db_table": "oauth_remoterepository_2020", "ordering": ["full_name"], }, ), migrations.CreateModel( name="RemoteRepositoryRelation", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "created", django_extensions.db.fields.CreationDateTimeField( auto_now_add=True, verbose_name="created" ), ), ( "modified", django_extensions.db.fields.ModificationDateTimeField( auto_now=True, verbose_name="modified" ), ), ( "admin", models.BooleanField(default=False, verbose_name="Has admin privilege"), ), ( "account", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="remote_repository_relations", to="socialaccount.SocialAccount", verbose_name="Connected account", ), ), ( "remote_repository", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="remote_repository_relations", to="oauth.RemoteRepository", ), ), ( "user", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="remote_repository_relations", to=settings.AUTH_USER_MODEL, ), ), ], options={ "unique_together": {("remote_repository", "account")}, }, ), migrations.AddField( model_name="remoterepository", name="users", field=models.ManyToManyField( related_name="oauth_repositories", through="oauth.RemoteRepositoryRelation", to=settings.AUTH_USER_MODEL, verbose_name="Users", ), ), migrations.AlterUniqueTogether( name="remoterepository", unique_together={("remote_id", "vcs_provider")}, ), ]
Migration
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 26099, "end": 27085 }
class ____(Operation): def call(self, x): return backend.numpy.arctan(x) def compute_output_spec(self, x): dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx())) if dtype == "int64": dtype = backend.floatx() else: dtype = dtypes.result_type(dtype, float) sparse = getattr(x, "sparse", False) return KerasTensor(x.shape, dtype=dtype, sparse=sparse) @keras_export(["keras.ops.arctan", "keras.ops.numpy.arctan"]) def arctan(x): """Trigonometric inverse tangent, element-wise. Args: x: Input tensor. Returns: Tensor of the inverse tangent of each element in `x`, in the interval `[-pi/2, pi/2]`. Example: >>> x = keras.ops.convert_to_tensor([0, 1]) >>> keras.ops.arctan(x) array([0., 0.7853982], dtype=float32) """ if any_symbolic_tensors((x,)): return Arctan().symbolic_call(x) return backend.numpy.arctan(x)
Arctan
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP007.py
{ "start": 1371, "end": 3555 }
class ____: ... def myfunc(param: "tuple[Union[int, 'AClass', None], str]"): print(param) from typing import NamedTuple, Union import typing_extensions from typing_extensions import ( NamedTuple as NamedTupleTE, Union as UnionTE, ) # Regression test for https://github.com/astral-sh/ruff/issues/18619 # Don't emit lint for `NamedTuple` a_plain_1: Union[NamedTuple, int] = None a_plain_2: Union[int, NamedTuple] = None a_plain_3: Union[NamedTuple, None] = None a_plain_4: Union[None, NamedTuple] = None a_plain_te_1: UnionTE[NamedTupleTE, int] = None a_plain_te_2: UnionTE[int, NamedTupleTE] = None a_plain_te_3: UnionTE[NamedTupleTE, None] = None a_plain_te_4: UnionTE[None, NamedTupleTE] = None a_plain_typing_1: UnionTE[typing.NamedTuple, int] = None a_plain_typing_2: UnionTE[int, typing.NamedTuple] = None a_plain_typing_3: UnionTE[typing.NamedTuple, None] = None a_plain_typing_4: UnionTE[None, typing.NamedTuple] = None a_string_1: "Union[NamedTuple, int]" = None a_string_2: "Union[int, NamedTuple]" = None a_string_3: "Union[NamedTuple, None]" = None a_string_4: "Union[None, NamedTuple]" = None a_string_te_1: "UnionTE[NamedTupleTE, int]" = None a_string_te_2: "UnionTE[int, NamedTupleTE]" = None a_string_te_3: "UnionTE[NamedTupleTE, None]" = None a_string_te_4: "UnionTE[None, NamedTupleTE]" = None a_string_typing_1: "typing.Union[typing.NamedTuple, int]" = None a_string_typing_2: "typing.Union[int, typing.NamedTuple]" = None a_string_typing_3: "typing.Union[typing.NamedTuple, None]" = None a_string_typing_4: "typing.Union[None, typing.NamedTuple]" = None b_plain_1: Union[NamedTuple] = None b_plain_2: Union[NamedTuple, None] = None b_plain_te_1: UnionTE[NamedTupleTE] = None b_plain_te_2: UnionTE[NamedTupleTE, None] = None b_plain_typing_1: UnionTE[typing.NamedTuple] = None b_plain_typing_2: UnionTE[typing.NamedTuple, None] = None b_string_1: "Union[NamedTuple]" = None b_string_2: "Union[NamedTuple, None]" = None b_string_te_1: "UnionTE[NamedTupleTE]" = None b_string_te_2: "UnionTE[NamedTupleTE, None]" = None b_string_typing_1: "typing.Union[typing.NamedTuple]" = None b_string_typing_2: "typing.Union[typing.NamedTuple, None]" = None
AClass
python
viewflow__viewflow
viewflow/workflow/activation.py
{ "start": 2161, "end": 10938 }
class ____: """ Base class for flow task activations. Activation is responsible for flow task state management and persistence. Each activation status change is restricted by a simple finite state automaton. """ status: fsm.State = fsm.State(STATUS, default=STATUS.NEW) type: str = "node" def __init__(self, task: Any) -> None: """ Instantiate an activation. Args: task (Any): The task instance associated with the activation. """ self.task = task self.process = task.process.coerced def __eq__(self, other: Any) -> bool: if not isinstance(other, Activation): return False return self.task == other.task def __hash__(self) -> int: return hash(self.task) @status.setter() def _set_status(self, value: Any) -> None: """Set the status to the underline task.""" self.task.status = value @status.getter() def _get_status(self) -> Any: """Get the status of the activated task.""" return self.task.status @property def flow_task(self) -> Any: """Get the flow task associated with the activation.""" return self.task.flow_task @property def flow_class(self) -> Any: """Get the flow class associated with the activation.""" return self.flow_task.flow_class def exception_guard(self) -> ContextDecorator: """ Perform activation action inside a transaction. Handle and propagate exception depending on activation context state. """ class ExceptionGuard(ContextDecorator): def __enter__(self): return self def __exit__(self_eg, exc_type, exc_val, exc_tb): if exc_type is not None: if not context.propagate_exception: # Keep error state tb = exc_val.__traceback__ while tb.tb_next: tb = tb.tb_next try: serialized_locals = json.dumps( tb.tb_frame.f_locals, default=lambda obj: str(obj) ) except Exception as ex: serialized_locals = json.dumps( {"_serialization_exception": str(ex)} ) self.task.data["_exception"] = { "title": str(exc_val), "traceback": traceback.format_exc(), "locals": json.loads(serialized_locals), } # Set status self.task.finished = now() self._set_status(STATUS.ERROR) self.task.save() task_failed.send( sender=self.flow_class, process=self.process, task=self.task ) # self.transaction.__exit__(exc_type, exc_val, exc_tb) return True # Suppress the exception else: # self.transaction.__exit__(exc_type, exc_val, exc_tb) return False # Propagate the exception return ExceptionGuard() @classmethod def create( cls, flow_task: Any, prev_activation: "Activation", token: Any, data: Optional[Any] = None, seed: Optional[Any] = None, ) -> "Activation": """ Instantiate and persist a new flow task. Args: flow_task (Any): The flow task instance. prev_activation (Activation): The previous activation instance. token (Any): The token for the new task. data (Optional[Any]): Additional data for the new task. Returns: Activation: The newly created activation instance. """ flow_class = flow_task.flow_class task = flow_class.task_class( process=prev_activation.process, flow_task=flow_task, token=token, ) task.data = data if data is not None else {} task.seed = seed task.save() task.previous.add(prev_activation.task) return cls(task) @status.transition(source=STATUS.NEW) def activate(self) -> None: """Activate the task.""" raise NotImplementedError( f"{self.__class__.__name__} class should override act() method" ) @status.transition(source=STATUS.DONE) def create_next(self) -> None: """Create the next task in the flow.""" raise NotImplementedError( f"{self.__class__.__name__} class should override create_next() method" ) @status.transition(source=STATUS.NEW, target=STATUS.DONE) def complete(self) -> None: """Complete the current task.""" assert connection.in_atomic_block self.task.finished = now() self.task.save() task_finished.send(sender=self.flow_class, process=self.process, task=self.task) def _activate_next(self, activations: Set["Activation"]) -> None: """Activate the next set of tasks.""" while activations: join_activations = {act for act in activations if act.type == "join"} task_activations = activations - join_activations if task_activations: for current_activation in task_activations: if current_activation.activate.can_proceed(): current_activation.activate() if current_activation.complete.can_proceed(): current_activation.complete() activations = { next_activation for current_activation in activations if current_activation.create_next.can_proceed() for next_activation in current_activation.create_next() } activations.update(join_activations) elif join_activations: # process first join activation current_activation = join_activations.pop() if current_activation.activate.can_proceed(): current_activation.activate() if current_activation.complete.can_proceed(): current_activation.complete() activations = set() if current_activation.create_next.can_proceed(): activations = { next_activation for next_activation in current_activation.create_next() } activations.update(join_activations) @status.transition(source=STATUS.DONE) def activate_next(self) -> None: """Activate the next task in the flow.""" assert connection.in_atomic_block activations = set(self.create_next()) self._activate_next(activations) @status.transition( source=STATUS.DONE, target=STATUS.CANCELED, conditions=[leading_tasks_canceled], permission=has_manage_permission, ) def undo(self) -> None: """Undo the current task.""" self.task.finished = now() self.task.save() @status.transition( source=[STATUS.CANCELED, STATUS.ERROR], target=STATUS.REVIVED, permission=has_manage_permission, ) def revive(self) -> Any: """ Recreate and activate cancelled task """ flow_class = self.flow_class task = flow_class.task_class( process=self.process, flow_task=self.flow_task, token=self.task.token, ) task.seed = self.task.seed task.data = self.task.data task.artifact = self.task.artifact task.save() for prev_task in self.task.previous.all(): task.previous.add(prev_task) task.previous.add(self.task) self.task.save(update_fields=["status"]) activations = set([type(self)(task)]) self._activate_next(activations) return task def get_outgoing_transitions(self) -> List[fsm.Transition]: """Get the outgoing transitions for the current status.""" return self.__class__.status.get_outgoing_transitions(self.status) def get_available_transitions(self, user) -> List[fsm.Transition]: """Get the available transitions for the current status and user.""" return self.__class__.status.get_available_transitions(self, self.status, user)
Activation
python
kamyu104__LeetCode-Solutions
Python/minimum-distance-to-type-a-word-using-two-fingers.py
{ "start": 32, "end": 601 }
class ____(object): def minimumDistance(self, word): """ :type word: str :rtype: int """ def distance(a, b): return abs(a//6 - b//6) + abs(a%6 - b%6) dp = [0]*26 for i in xrange(len(word)-1): b, c = ord(word[i])-ord('A'), ord(word[i+1])-ord('A') dp[b] = max(dp[a] - distance(a, c) + distance(b, c) for a in xrange(26)) return sum(distance(ord(word[i])-ord('A'), ord(word[i+1])-ord('A')) for i in xrange(len(word)-1)) - max(dp) # Time: O(52n) # Space: O(52)
Solution
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 286151, "end": 286486 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("DiscussionPollOption", graphql_name="node")
DiscussionPollOptionEdge
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 80187, "end": 80609 }
class ____(BiffRecord): """ This record is part of the Page Settings Block. It contains the top page margin of the current worksheet. Offset Size Contents 0 8 Top page margin in inches (IEEE 754 floating-point value, 64?bit double precision) """ _REC_ID = 0x0028 def __init__(self, margin): self._rec_data = pack('<d', margin)
TopMarginRecord
python
ipython__ipython
IPython/lib/backgroundjobs.py
{ "start": 12687, "end": 15958 }
class ____(threading.Thread): """Base class to build BackgroundJob classes. The derived classes must implement: - Their own __init__, since the one here raises NotImplementedError. The derived constructor must call self._init() at the end, to provide common initialization. - A strform attribute used in calls to __str__. - A call() method, which will make the actual execution call and must return a value to be held in the 'result' field of the job object. """ # Class constants for status, in string and as numerical codes (when # updating jobs lists, we don't want to do string comparisons). This will # be done at every user prompt, so it has to be as fast as possible stat_created = 'Created'; stat_created_c = 0 stat_running = 'Running'; stat_running_c = 1 stat_completed = 'Completed'; stat_completed_c = 2 stat_dead = 'Dead (Exception), call jobs.traceback() for details' stat_dead_c = -1 def __init__(self): """Must be implemented in subclasses. Subclasses must call :meth:`_init` for standard initialisation. """ raise NotImplementedError("This class can not be instantiated directly.") def _init(self): """Common initialization for all BackgroundJob objects""" for attr in ['call','strform']: assert hasattr(self,attr), "Missing attribute <%s>" % attr # The num tag can be set by an external job manager self.num = None self.status = BackgroundJobBase.stat_created self.stat_code = BackgroundJobBase.stat_created_c self.finished = False self.result = '<BackgroundJob has not completed>' # reuse the ipython traceback handler if we can get to it, otherwise # make a new one try: make_tb = get_ipython().InteractiveTB.text except: make_tb = AutoFormattedTB( mode="Context", color_scheme="nocolor", tb_offset=1 ).text # Note that the actual API for text() requires the three args to be # passed in, so we wrap it in a simple lambda. self._make_tb = lambda : make_tb(None, None, None) # Hold a formatted traceback if one is generated. self._tb = None threading.Thread.__init__(self) def __str__(self): return self.strform def __repr__(self): return '<BackgroundJob #%d: %s>' % (self.num, self.strform) def traceback(self): print(self._tb) def run(self): try: self.status = BackgroundJobBase.stat_running self.stat_code = BackgroundJobBase.stat_running_c self.result = self.call() except: self.status = BackgroundJobBase.stat_dead self.stat_code = BackgroundJobBase.stat_dead_c self.finished = None self.result = ('<BackgroundJob died, call jobs.traceback() for details>') self._tb = self._make_tb() else: self.status = BackgroundJobBase.stat_completed self.stat_code = BackgroundJobBase.stat_completed_c self.finished = True
BackgroundJobBase
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/pilot_resize_terminal.py
{ "start": 79, "end": 323 }
class ____(App[None]): """An app with a single label that's 20 x 10.""" def compose(self) -> ComposeResult: yield Label(("12345678901234567890\n" * 10).strip()) if __name__ == "__main__": SingleLabelApp().run()
SingleLabelApp
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/model_query_transitive_extends.py
{ "start": 318, "end": 418 }
class ____(Test1_C): attribute = ... def __init__(self): self.instance = ...
Test1_C1
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/private_variables.py
{ "start": 252, "end": 2714 }
class ____: def __init__(self, private: str = "", public: str = "") -> None: self.__value: str = private self.value: str = public def private_into_sink(self) -> None: _test_sink(self.__value) def public_into_sink(self) -> None: _test_sink(self.value) @staticmethod def expand_subexpression(values: List[Simple]) -> None: # Private variables are expended in all expressions. _test_sink(values[0].__value) def getattr_public(self) -> str: return getattr(self, "value") def getattr_private(self) -> str: return getattr(self, "_Simple__value") def getattr_invalid(self) -> str: # This should not work according to the documentation. # pyre-ignore return getattr(self, "__value") def test_simple() -> None: Simple(private=_test_source()).private_into_sink() def test_private_public_different() -> None: Simple(private=_test_source()).private_into_sink() # Error. Simple(private=_test_source()).public_into_sink() # No error. Simple(public=_test_source()).private_into_sink() # No error. Simple(public=_test_source()).public_into_sink() # Error. def test_expand_subexpression() -> None: Simple.expand_subexpression([Simple(private=_test_source())]) # Error Simple.expand_subexpression([Simple(), Simple(private=_test_source())]) # No error. def test_getattr() -> None: # Expect no error, currently a false positive. _test_sink(Simple(private=_test_source()).getattr_public()) # Expect no error, currently a false positive. _test_sink(Simple(private=_test_source()).getattr_private()) # Expect no error, currently a false positive. _test_sink(Simple(private=_test_source()).getattr_invalid()) # Expect no error, currently a false positive. _test_sink(Simple(public=_test_source()).getattr_public()) # Expect no error, currently a false positive. _test_sink(Simple(public=_test_source()).getattr_private()) # Expect no error, currently a false positive. _test_sink(Simple(public=_test_source()).getattr_invalid()) def test_bypass_private() -> None: _test_sink(Simple(private=_test_source())._Simple__value) # Error. _test_sink(Simple(public=_test_source())._Simple__value) # No error. # pyre-ignore _test_sink(Simple(private=_test_source()).__value) # No error. _test_sink(Simple(public=_test_source()).__value) # No error.
Simple
python
charliermarsh__ruff
scripts/ecosystem_all_check.py
{ "start": 394, "end": 2191 }
class ____(NamedTuple): """A GitHub repository at a specific ref.""" org: str repo: str ref: str | None def main() -> None: ruff_args = sys.argv[1:] checkouts = Path("checkouts") out_dir = Path("ecosystem_all_results") github_search_json = Path("github_search.jsonl") # Somehow it doesn't like plain ruff ruff = Path.cwd().joinpath("ruff") out_dir.mkdir(parents=True, exist_ok=True) repositories = [] for line in github_search_json.read_text().splitlines(): item = json.loads(line) # Pick only the easier case for now. if item["path"] != "pyproject.toml": continue repositories.append( Repository( item["owner"], item["repo"], item.get("ref"), ), ) successes = 0 errors = 0 for repository in tqdm(repositories): project_dir = checkouts.joinpath(f"{repository.org}:{repository.repo}") if not project_dir.is_dir(): tqdm.write(f"Missing {project_dir}") errors += 1 continue try: output = subprocess.run( [ruff, *ruff_args, "."], cwd=project_dir, capture_output=True, text=True, ) except CalledProcessError as e: tqdm.write(f"Ruff failed on {project_dir}: {e}") errors += 1 continue org_repo = f"{repository.org}:{repository.repo}" out_dir.joinpath(f"{org_repo}.stdout.txt").write_text(output.stdout) out_dir.joinpath(f"{org_repo}.stderr.txt").write_text(output.stderr) successes += 1 print(f"Success: {successes} Error {errors}") if __name__ == "__main__": main()
Repository
python
astropy__astropy
astropy/wcs/wcsapi/tests/test_high_level_api.py
{ "start": 5169, "end": 6720 }
class ____(SkyCoordDuplicateWCS): """ WCS which defines ``world_axis_object_components`` which returns Quantity instead of bare Numpy arrays, which can cause issues. This is for a regression test to make sure that we don't return Quantities from ``world_axis_object_components``. """ @property def world_axis_object_components(self): return [ ("test1", "ra", "spherical.lon"), ("test1", "dec", "spherical.lat"), ("test2", 0, "spherical.lon"), ("test2", 1, "spherical.lat"), ] def test_objects_to_values_invalid_type(): wcs = InvalidWCSQuantity() c1, c2 = wcs.pixel_to_world(1, 2, 3, 4) with pytest.raises( TypeError, match=( re.escape( "WCS world_axis_object_components results in values which are not " "scalars or plain Numpy arrays (got <class " "'astropy.coordinates.angles.core.Longitude'>)" ) ), ): high_level_objects_to_values(c1, c2, low_level_wcs=wcs) def test_values_to_objects_invalid_type(): wcs = SkyCoordDuplicateWCS() c1, c2 = wcs.pixel_to_world(1, 2, 3, 4) with pytest.raises( TypeError, match=( re.escape( "Expected world coordinates as scalars or plain Numpy arrays (got " "<class 'astropy.units.quantity.Quantity'>)" ) ), ): values_to_high_level_objects(2 * u.m, 4, 6, 8, low_level_wcs=wcs)
InvalidWCSQuantity
python
scrapy__scrapy
tests/test_squeues_request.py
{ "start": 4383, "end": 4568 }
class ____(TestRequestQueueBase): is_fifo = True @pytest.fixture def q(self, crawler): return FifoMemoryQueue.from_crawler(crawler=crawler)
TestFifoMemoryQueueRequest
python
mlflow__mlflow
tests/models/test_signature.py
{ "start": 12662, "end": 13752 }
class ____(rag_signatures.ChatCompletionResponse): custom_output: CustomOutput | None = None def test_infer_signature_with_optional_and_child_dataclass(): inferred_signature = infer_signature( FlexibleChatCompletionRequest(), FlexibleChatCompletionResponse(), ) custom_input_schema = next( schema for schema in inferred_signature.inputs.to_dict() if schema["name"] == "custom_input" ) assert custom_input_schema["required"] is False assert "id" in custom_input_schema["properties"] assert any( schema for schema in inferred_signature.inputs.to_dict() if schema["name"] == "messages" ) def test_infer_signature_for_pydantic_objects_error(): class Message(pydantic.BaseModel): content: str role: str m = Message(content="test", role="user") with pytest.raises( InvalidDataForSignatureInferenceError, match=r"MLflow does not support inferring model signature from " r"input example with Pydantic objects", ): infer_signature([m])
FlexibleChatCompletionResponse
python
davidhalter__jedi
jedi/inference/value/instance.py
{ "start": 15532, "end": 15840 }
class ____(NameWrapper): @iterator_to_value_set def infer(self): for result_value in self._wrapped_name.infer(): if result_value.api_type == 'function': yield CompiledBoundMethod(result_value) else: yield result_value
CompiledInstanceName
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 41344, "end": 41588 }
class ____(Base): name: Mapped[str] value: Mapped[Optional[Any]] = mapped_column(JSON) tags: Mapped[list[str]] = mapped_column(JSON, server_default="[]", default=list) __table_args__: Any = (sa.UniqueConstraint("name"),)
Variable
python
getsentry__sentry
src/sentry/flags/endpoints/secrets.py
{ "start": 919, "end": 1318 }
class ____(Serializer): def serialize(self, obj, attrs, user, **kwargs) -> FlagWebhookSigningSecretResponse: return { "createdAt": obj.date_added.isoformat(), "createdBy": obj.created_by, "id": obj.id, "provider": obj.provider, "secret": obj.secret[0:6] + "*" * (len(obj.secret) - 6), }
FlagWebhookSigningSecretSerializer
python
getsentry__sentry
src/sentry/flags/providers.py
{ "start": 13210, "end": 16690 }
class ____: provider_name = "statsig" version = "v0" def __init__( self, organization_id: int, signature: str | None, request_timestamp: str | None, ) -> None: self.organization_id = organization_id self.signature = signature self.request_timestamp = request_timestamp # Strip the signature's version prefix. For example, signature format for v0 is "v0+{hash}" prefix_len = len(self.version) + 1 if signature and len(signature) > prefix_len: self.signature = signature[prefix_len:] def handle(self, message: dict[str, Any]) -> list[FlagAuditLogRow]: serializer = StatsigItemSerializer(data=message) if not serializer.is_valid(): raise DeserializationError(serializer.errors) events = serializer.validated_data["data"] audit_logs = [] for event in events: event_name = event["eventName"] if event_name not in SUPPORTED_STATSIG_EVENTS: continue metadata = event.get("metadata") or {} flag = metadata.get("name") statsig_type = metadata.get("type") action = (metadata.get("action") or "").lower() if ( not flag or not statsig_type or statsig_type.lower() not in SUPPORTED_STATSIG_TYPES or action not in ACTION_MAP ): continue action = ACTION_MAP[action] # Prioritize email > id > name for created_by. if created_by := get_path(event, "user", "email"): created_by_type = CREATED_BY_TYPE_MAP["email"] elif created_by := event.get("userID") or get_path(event, "user", "userID"): created_by_type = CREATED_BY_TYPE_MAP["id"] elif created_by := get_path(event, "user", "name"): created_by_type = CREATED_BY_TYPE_MAP["name"] else: created_by, created_by_type = None, None created_at_ms = float(event["timestamp"]) created_at = datetime.datetime.fromtimestamp(created_at_ms / 1000.0, datetime.UTC) tags = {} if projectName := metadata.get("projectName"): tags["projectName"] = projectName if projectID := metadata.get("projectID"): tags["projectID"] = projectID if environments := metadata.get("environments"): tags["environments"] = environments audit_logs.append( FlagAuditLogRow( action=action, created_at=created_at, created_by=created_by, created_by_type=created_by_type, flag=flag, organization_id=self.organization_id, provider=PROVIDER_MAP["statsig"], tags=tags, ) ) return audit_logs def validate(self, message_bytes: bytes) -> bool: if self.request_timestamp is None: return False signature_basestring = f"{self.version}:{self.request_timestamp}:".encode() + message_bytes validator = PayloadSignatureValidator( self.organization_id, self.provider_name, signature_basestring, self.signature ) return validator.validate() """Flagpole provider."""
StatsigProvider
python
numba__numba
numba/core/typing/builtins.py
{ "start": 2754, "end": 3540 }
class ____(ConcreteTemplate): cases = [ signature(types.range_state32_type, types.int32), signature(types.range_state32_type, types.int32, types.int32), signature(types.range_state32_type, types.int32, types.int32, types.int32), signature(types.range_state64_type, types.int64), signature(types.range_state64_type, types.int64, types.int64), signature(types.range_state64_type, types.int64, types.int64, types.int64), signature(types.unsigned_range_state64_type, types.uint64), signature(types.unsigned_range_state64_type, types.uint64, types.uint64), signature(types.unsigned_range_state64_type, types.uint64, types.uint64, types.uint64), ] @infer
Range
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/class_as_data_structure.py
{ "start": 1430, "end": 1590 }
class ____: def __init__(self, foo:int, bar:list): foo = " - ".join([foo, bar]) self.foo = foo self.bar = bar
NoWarningsMoreStatements
python
huggingface__transformers
src/transformers/models/pop2piano/tokenization_pop2piano.py
{ "start": 2090, "end": 32724 }
class ____(PreTrainedTokenizer): """ Constructs a Pop2Piano tokenizer. This tokenizer does not require training. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: vocab (`str`): Path to the vocab file which contains the vocabulary. default_velocity (`int`, *optional*, defaults to 77): Determines the default velocity to be used while creating midi Notes. num_bars (`int`, *optional*, defaults to 2): Determines cutoff_time_idx in for each token. unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"-1"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to 1): The end of sequence token. pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to 0): A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by attention mechanisms or loss computation. bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to 2): The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. """ model_input_names = ["token_ids", "attention_mask"] vocab_files_names = VOCAB_FILES_NAMES def __init__( self, vocab, default_velocity=77, num_bars=2, unk_token="-1", eos_token="1", pad_token="0", bos_token="2", **kwargs, ): unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token self.default_velocity = default_velocity self.num_bars = num_bars # Load the vocab with open(vocab, "rb") as file: self.encoder = json.load(file) # create mappings for encoder self.decoder = {v: k for k, v in self.encoder.items()} super().__init__( unk_token=unk_token, eos_token=eos_token, pad_token=pad_token, bos_token=bos_token, **kwargs, ) @property def vocab_size(self): """Returns the vocabulary size of the tokenizer.""" return len(self.encoder) def get_vocab(self): """Returns the vocabulary of the tokenizer.""" return dict(self.encoder, **self.added_tokens_encoder) def _convert_id_to_token(self, token_id: int) -> list: """ Decodes the token ids generated by the transformer into notes. Args: token_id (`int`): This denotes the ids generated by the transformers to be converted to Midi tokens. Returns: `List`: A list consists of token_type (`str`) and value (`int`). """ token_type_value = self.decoder.get(token_id, f"{self.unk_token}_TOKEN_TIME") token_type_value = token_type_value.split("_") token_type, value = "_".join(token_type_value[1:]), int(token_type_value[0]) return [token_type, value] def _convert_token_to_id(self, token, token_type="TOKEN_TIME") -> int: """ Encodes the Midi tokens to transformer generated token ids. Args: token (`int`): This denotes the token value. token_type (`str`): This denotes the type of the token. There are four types of midi tokens such as "TOKEN_TIME", "TOKEN_VELOCITY", "TOKEN_NOTE" and "TOKEN_SPECIAL". Returns: `int`: returns the id of the token. """ return self.encoder.get(f"{token}_{token_type}", int(self.unk_token)) def relative_batch_tokens_ids_to_notes( self, tokens: np.ndarray, beat_offset_idx: int, bars_per_batch: int, cutoff_time_idx: int, ): """ Converts relative tokens to notes which are then used to generate pretty midi object. Args: tokens (`numpy.ndarray`): Tokens to be converted to notes. beat_offset_idx (`int`): Denotes beat offset index for each note in generated Midi. bars_per_batch (`int`): A parameter to control the Midi output generation. cutoff_time_idx (`int`): Denotes the cutoff time index for each note in generated Midi. """ notes = None for index in range(len(tokens)): _tokens = tokens[index] _start_idx = beat_offset_idx + index * bars_per_batch * 4 _cutoff_time_idx = cutoff_time_idx + _start_idx _notes = self.relative_tokens_ids_to_notes( _tokens, start_idx=_start_idx, cutoff_time_idx=_cutoff_time_idx, ) if len(_notes) == 0: pass elif notes is None: notes = _notes else: notes = np.concatenate((notes, _notes), axis=0) if notes is None: return [] return notes def relative_batch_tokens_ids_to_midi( self, tokens: np.ndarray, beatstep: np.ndarray, beat_offset_idx: int = 0, bars_per_batch: int = 2, cutoff_time_idx: int = 12, ): """ Converts tokens to Midi. This method calls `relative_batch_tokens_ids_to_notes` method to convert batch tokens to notes then uses `notes_to_midi` method to convert them to Midi. Args: tokens (`numpy.ndarray`): Denotes tokens which alongside beatstep will be converted to Midi. beatstep (`np.ndarray`): We get beatstep from feature extractor which is also used to get Midi. beat_offset_idx (`int`, *optional*, defaults to 0): Denotes beat offset index for each note in generated Midi. bars_per_batch (`int`, *optional*, defaults to 2): A parameter to control the Midi output generation. cutoff_time_idx (`int`, *optional*, defaults to 12): Denotes the cutoff time index for each note in generated Midi. """ beat_offset_idx = 0 if beat_offset_idx is None else beat_offset_idx notes = self.relative_batch_tokens_ids_to_notes( tokens=tokens, beat_offset_idx=beat_offset_idx, bars_per_batch=bars_per_batch, cutoff_time_idx=cutoff_time_idx, ) midi = self.notes_to_midi(notes, beatstep, offset_sec=beatstep[beat_offset_idx]) return midi # Taken from the original code # Please see https://github.com/sweetcocoa/pop2piano/blob/fac11e8dcfc73487513f4588e8d0c22a22f2fdc5/midi_tokenizer.py#L257 def relative_tokens_ids_to_notes( self, tokens: np.ndarray, start_idx: float, cutoff_time_idx: Optional[float] = None ): """ Converts relative tokens to notes which will then be used to create Pretty Midi objects. Args: tokens (`numpy.ndarray`): Relative Tokens which will be converted to notes. start_idx (`float`): A parameter which denotes the starting index. cutoff_time_idx (`float`, *optional*): A parameter used while converting tokens to notes. """ words = [self._convert_id_to_token(token) for token in tokens] current_idx = start_idx current_velocity = 0 note_onsets_ready = [None for i in range(sum(k.endswith("NOTE") for k in self.encoder) + 1)] notes = [] for token_type, number in words: if token_type == "TOKEN_SPECIAL": if number == 1: break elif token_type == "TOKEN_TIME": current_idx = token_time_to_note( number=number, cutoff_time_idx=cutoff_time_idx, current_idx=current_idx ) elif token_type == "TOKEN_VELOCITY": current_velocity = number elif token_type == "TOKEN_NOTE": notes = token_note_to_note( number=number, current_velocity=current_velocity, default_velocity=self.default_velocity, note_onsets_ready=note_onsets_ready, current_idx=current_idx, notes=notes, ) else: raise ValueError("Token type not understood!") for pitch, note_onset in enumerate(note_onsets_ready): # force offset if no offset for each pitch if note_onset is not None: if cutoff_time_idx is None: cutoff = note_onset + 1 else: cutoff = max(cutoff_time_idx, note_onset + 1) offset_idx = max(current_idx, cutoff) notes.append([note_onset, offset_idx, pitch, self.default_velocity]) if len(notes) == 0: return [] else: notes = np.array(notes) note_order = notes[:, 0] * 128 + notes[:, 1] notes = notes[note_order.argsort()] return notes def notes_to_midi(self, notes: np.ndarray, beatstep: np.ndarray, offset_sec: int = 0.0): """ Converts notes to Midi. Args: notes (`numpy.ndarray`): This is used to create Pretty Midi objects. beatstep (`numpy.ndarray`): This is the extrapolated beatstep that we get from feature extractor. offset_sec (`int`, *optional*, defaults to 0.0): This represents the offset seconds which is used while creating each Pretty Midi Note. """ requires_backends(self, ["pretty_midi"]) new_pm = pretty_midi.PrettyMIDI(resolution=384, initial_tempo=120.0) new_inst = pretty_midi.Instrument(program=0) new_notes = [] for onset_idx, offset_idx, pitch, velocity in notes: new_note = pretty_midi.Note( velocity=velocity, pitch=pitch, start=beatstep[onset_idx] - offset_sec, end=beatstep[offset_idx] - offset_sec, ) new_notes.append(new_note) new_inst.notes = new_notes new_pm.instruments.append(new_inst) new_pm.remove_invalid_notes() return new_pm def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]: """ Saves the tokenizer's vocabulary dictionary to the provided save_directory. Args: save_directory (`str`): A path to the directory where to saved. It will be created if it doesn't exist. filename_prefix (`Optional[str]`, *optional*): A prefix to add to the names of the files saved by the tokenizer. """ if not os.path.isdir(save_directory): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return # Save the encoder. out_vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"] ) with open(out_vocab_file, "w") as file: file.write(json.dumps(self.encoder)) return (out_vocab_file,) def encode_plus( self, notes: Union[np.ndarray, list[pretty_midi.Note]], truncation_strategy: Optional[TruncationStrategy] = None, max_length: Optional[int] = None, **kwargs, ) -> BatchEncoding: r""" This is the `encode_plus` method for `Pop2PianoTokenizer`. It converts the midi notes to the transformer generated token ids. It only works on a single batch, to process multiple batches please use `batch_encode_plus` or `__call__` method. Args: notes (`numpy.ndarray` of shape `[sequence_length, 4]` or `list` of `pretty_midi.Note` objects): This represents the midi notes. If `notes` is a `numpy.ndarray`: - Each sequence must have 4 values, they are `onset idx`, `offset idx`, `pitch` and `velocity`. If `notes` is a `list` containing `pretty_midi.Note` objects: - Each sequence must have 4 attributes, they are `start`, `end`, `pitch` and `velocity`. truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`], *optional*): Indicates the truncation strategy that is going to be used during truncation. max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see above). Returns: `BatchEncoding` containing the tokens ids. """ requires_backends(self, ["pretty_midi"]) # check if notes is a pretty_midi object or not, if yes then extract the attributes and put them into a numpy # array. if isinstance(notes[0], pretty_midi.Note): notes = np.array( [[each_note.start, each_note.end, each_note.pitch, each_note.velocity] for each_note in notes] ).reshape(-1, 4) # to round up all the values to the closest int values. notes = np.round(notes).astype(np.int32) max_time_idx = notes[:, :2].max() times = [[] for i in range(max_time_idx + 1)] for onset, offset, pitch, velocity in notes: times[onset].append([pitch, velocity]) times[offset].append([pitch, 0]) tokens = [] current_velocity = 0 for i, time in enumerate(times): if len(time) == 0: continue tokens.append(self._convert_token_to_id(i, "TOKEN_TIME")) for pitch, velocity in time: velocity = int(velocity > 0) if current_velocity != velocity: current_velocity = velocity tokens.append(self._convert_token_to_id(velocity, "TOKEN_VELOCITY")) tokens.append(self._convert_token_to_id(pitch, "TOKEN_NOTE")) total_len = len(tokens) # truncation if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length: tokens, _, _ = self.truncate_sequences( ids=tokens, num_tokens_to_remove=total_len - max_length, truncation_strategy=truncation_strategy, **kwargs, ) return BatchEncoding({"token_ids": tokens}) def batch_encode_plus( self, notes: Union[np.ndarray, list[pretty_midi.Note]], truncation_strategy: Optional[TruncationStrategy] = None, max_length: Optional[int] = None, **kwargs, ) -> BatchEncoding: r""" This is the `batch_encode_plus` method for `Pop2PianoTokenizer`. It converts the midi notes to the transformer generated token ids. It works on multiple batches by calling `encode_plus` multiple times in a loop. Args: notes (`numpy.ndarray` of shape `[batch_size, sequence_length, 4]` or `list` of `pretty_midi.Note` objects): This represents the midi notes. If `notes` is a `numpy.ndarray`: - Each sequence must have 4 values, they are `onset idx`, `offset idx`, `pitch` and `velocity`. If `notes` is a `list` containing `pretty_midi.Note` objects: - Each sequence must have 4 attributes, they are `start`, `end`, `pitch` and `velocity`. truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`], *optional*): Indicates the truncation strategy that is going to be used during truncation. max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see above). Returns: `BatchEncoding` containing the tokens ids. """ encoded_batch_token_ids = [] for i in range(len(notes)): encoded_batch_token_ids.append( self.encode_plus( notes[i], truncation_strategy=truncation_strategy, max_length=max_length, **kwargs, )["token_ids"] ) return BatchEncoding({"token_ids": encoded_batch_token_ids}) def __call__( self, notes: Union[ np.ndarray, list[pretty_midi.Note], list[list[pretty_midi.Note]], ], padding: Union[bool, str, PaddingStrategy] = False, truncation: Union[bool, str, TruncationStrategy] = None, max_length: Optional[int] = None, pad_to_multiple_of: Optional[int] = None, return_attention_mask: Optional[bool] = None, return_tensors: Optional[Union[str, TensorType]] = None, verbose: bool = True, **kwargs, ) -> BatchEncoding: r""" This is the `__call__` method for `Pop2PianoTokenizer`. It converts the midi notes to the transformer generated token ids. Args: notes (`numpy.ndarray` of shape `[batch_size, max_sequence_length, 4]` or `list` of `pretty_midi.Note` objects): This represents the midi notes. If `notes` is a `numpy.ndarray`: - Each sequence must have 4 values, they are `onset idx`, `offset idx`, `pitch` and `velocity`. If `notes` is a `list` containing `pretty_midi.Note` objects: - Each sequence must have 4 attributes, they are `start`, `end`, `pitch` and `velocity`. padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. pad_to_multiple_of (`int`, *optional*): If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta). return_attention_mask (`bool`, *optional*): Whether to return the attention mask. If left to the default, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) return_tensors (`str` or [`~file_utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. verbose (`bool`, *optional*, defaults to `True`): Whether or not to print more information and warnings. Returns: `BatchEncoding` containing the token_ids. """ # check if it is batched or not # it is batched if its a list containing a list of `pretty_midi.Notes` where the outer list contains all the # batches and the inner list contains all Notes for a single batch. Otherwise if np.ndarray is passed it will be # considered batched if it has shape of `[batch_size, sequence_length, 4]` or ndim=3. is_batched = notes.ndim == 3 if isinstance(notes, np.ndarray) else isinstance(notes[0], list) # get the truncation and padding strategy padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies( padding=padding, truncation=truncation, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, verbose=verbose, **kwargs, ) if is_batched: # If the user has not explicitly mentioned `return_attention_mask` as False, we change it to True return_attention_mask = True if return_attention_mask is None else return_attention_mask token_ids = self.batch_encode_plus( notes=notes, truncation_strategy=truncation_strategy, max_length=max_length, **kwargs, ) else: token_ids = self.encode_plus( notes=notes, truncation_strategy=truncation_strategy, max_length=max_length, **kwargs, ) # since we already have truncated sequnences we are just left to do padding token_ids = self.pad( token_ids, padding=padding_strategy, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, return_attention_mask=return_attention_mask, return_tensors=return_tensors, verbose=verbose, ) return token_ids def batch_decode( self, token_ids, feature_extractor_output: BatchFeature, return_midi: bool = True, ): r""" This is the `batch_decode` method for `Pop2PianoTokenizer`. It converts the token_ids generated by the transformer to midi_notes and returns them. Args: token_ids (`Union[np.ndarray, torch.Tensor]`): Output token_ids of `Pop2PianoConditionalGeneration` model. feature_extractor_output (`BatchFeature`): Denotes the output of `Pop2PianoFeatureExtractor.__call__`. It must contain `"beatstep"` and `"extrapolated_beatstep"`. Also `"attention_mask_beatsteps"` and `"attention_mask_extrapolated_beatstep"` should be present if they were returned by the feature extractor. return_midi (`bool`, *optional*, defaults to `True`): Whether to return midi object or not. Returns: If `return_midi` is True: - `BatchEncoding` containing both `notes` and `pretty_midi.pretty_midi.PrettyMIDI` objects. If `return_midi` is False: - `BatchEncoding` containing `notes`. """ # check if they have attention_masks(attention_mask, attention_mask_beatsteps, attention_mask_extrapolated_beatstep) or not attention_masks_present = bool( hasattr(feature_extractor_output, "attention_mask") and hasattr(feature_extractor_output, "attention_mask_beatsteps") and hasattr(feature_extractor_output, "attention_mask_extrapolated_beatstep") ) # if we are processing batched inputs then we must need attention_masks if not attention_masks_present and feature_extractor_output["beatsteps"].shape[0] > 1: raise ValueError( "attention_mask, attention_mask_beatsteps and attention_mask_extrapolated_beatstep must be present " "for batched inputs! But one of them were not present." ) # check for length mismatch between inputs_embeds, beatsteps and extrapolated_beatstep if attention_masks_present: # since we know about the number of examples in token_ids from attention_mask if ( sum(feature_extractor_output["attention_mask"][:, 0] == 0) != feature_extractor_output["beatsteps"].shape[0] or feature_extractor_output["beatsteps"].shape[0] != feature_extractor_output["extrapolated_beatstep"].shape[0] ): raise ValueError( "Length mistamtch between token_ids, beatsteps and extrapolated_beatstep! Found " f"token_ids length - {token_ids.shape[0]}, beatsteps shape - {feature_extractor_output['beatsteps'].shape[0]} " f"and extrapolated_beatsteps shape - {feature_extractor_output['extrapolated_beatstep'].shape[0]}" ) if feature_extractor_output["attention_mask"].shape[0] != token_ids.shape[0]: raise ValueError( f"Found attention_mask of length - {feature_extractor_output['attention_mask'].shape[0]} but token_ids of length - {token_ids.shape[0]}" ) else: # if there is no attention mask present then it's surely a single example if ( feature_extractor_output["beatsteps"].shape[0] != 1 or feature_extractor_output["extrapolated_beatstep"].shape[0] != 1 ): raise ValueError( "Length mistamtch of beatsteps and extrapolated_beatstep! Since attention_mask is not present the number of examples must be 1, " f"But found beatsteps length - {feature_extractor_output['beatsteps'].shape[0]}, extrapolated_beatsteps length - {feature_extractor_output['extrapolated_beatstep'].shape[0]}." ) if attention_masks_present: # check for zeros(since token_ids are separated by zero arrays) batch_idx = np.where(feature_extractor_output["attention_mask"][:, 0] == 0)[0] else: batch_idx = [token_ids.shape[0]] notes_list = [] pretty_midi_objects_list = [] start_idx = 0 for index, end_idx in enumerate(batch_idx): each_tokens_ids = token_ids[start_idx:end_idx] # check where the whole example ended by searching for eos_token_id and getting the upper bound each_tokens_ids = each_tokens_ids[:, : np.max(np.where(each_tokens_ids == int(self.eos_token))[1]) + 1] beatsteps = feature_extractor_output["beatsteps"][index] extrapolated_beatstep = feature_extractor_output["extrapolated_beatstep"][index] # if attention mask is present then mask out real array/tensor if attention_masks_present: attention_mask_beatsteps = feature_extractor_output["attention_mask_beatsteps"][index] attention_mask_extrapolated_beatstep = feature_extractor_output[ "attention_mask_extrapolated_beatstep" ][index] beatsteps = beatsteps[: np.max(np.where(attention_mask_beatsteps == 1)[0]) + 1] extrapolated_beatstep = extrapolated_beatstep[ : np.max(np.where(attention_mask_extrapolated_beatstep == 1)[0]) + 1 ] each_tokens_ids = to_numpy(each_tokens_ids) beatsteps = to_numpy(beatsteps) extrapolated_beatstep = to_numpy(extrapolated_beatstep) pretty_midi_object = self.relative_batch_tokens_ids_to_midi( tokens=each_tokens_ids, beatstep=extrapolated_beatstep, bars_per_batch=self.num_bars, cutoff_time_idx=(self.num_bars + 1) * 4, ) for note in pretty_midi_object.instruments[0].notes: note.start += beatsteps[0] note.end += beatsteps[0] notes_list.append(note) pretty_midi_objects_list.append(pretty_midi_object) start_idx += end_idx + 1 # 1 represents the zero array if return_midi: return BatchEncoding({"notes": notes_list, "pretty_midi_objects": pretty_midi_objects_list}) return BatchEncoding({"notes": notes_list}) __all__ = ["Pop2PianoTokenizer"]
Pop2PianoTokenizer
python
facelessuser__soupsieve
tests/test_level3/test_only_of_type.py
{ "start": 57, "end": 662 }
class ____(util.TestCase): """Test only of type selectors.""" def test_only_of_type(self): """Test only of type.""" markup = """ <div id="0"> <p id="1"></p> </div> <span id="2"></span> <span id="3"></span> <p id="4"></p> <span id="5"></span> <span id="6"></span> <div> <p id="7"></p> <p id="8"></p> </div> """ self.assert_selector( markup, "p:only-of-type", ['1', '4'], flags=util.HTML )
TestOnlyOfType
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-google-genai/llama_index/llms/google_genai/base.py
{ "start": 2672, "end": 29868 }
class ____(FunctionCallingLLM): """ Google GenAI LLM. Examples: `pip install llama-index-llms-google-genai` ```python from llama_index.llms.google_genai import GoogleGenAI llm = GoogleGenAI(model="gemini-2.0-flash", api_key="YOUR_API_KEY") resp = llm.complete("Write a poem about a magic backpack") print(resp) ``` """ model: str = Field(default=DEFAULT_MODEL, description="The Gemini model to use.") temperature: float = Field( default=DEFAULT_TEMPERATURE, description="The temperature to use during generation.", ge=0.0, le=2.0, ) context_window: Optional[int] = Field( default=None, description="The context window of the model. If not provided, the default context window 200000 will be used.", ) max_retries: int = Field( default=3, description="The maximum number of API retries.", ge=0, ) is_function_calling_model: bool = Field( default=True, description="Whether the model is a function calling model." ) cached_content: Optional[str] = Field( default=None, description="Cached content to use for the model.", ) built_in_tool: Optional[types.Tool] = Field( default=None, description="Google GenAI tool to use for the model to augment responses.", ) use_file_api: bool = Field( default=True, description="Whether or not to use the FileAPI for large files (>20MB).", ) _max_tokens: int = PrivateAttr() _client: google.genai.Client = PrivateAttr() _generation_config: types.GenerateContentConfigDict = PrivateAttr() _model_meta: types.Model = PrivateAttr() def __init__( self, model: str = DEFAULT_MODEL, api_key: Optional[str] = None, temperature: float = DEFAULT_TEMPERATURE, max_tokens: Optional[int] = None, context_window: Optional[int] = None, max_retries: int = 3, vertexai_config: Optional[VertexAIConfig] = None, http_options: Optional[types.HttpOptions] = None, debug_config: Optional[google.genai.client.DebugConfig] = None, generation_config: Optional[types.GenerateContentConfig] = None, callback_manager: Optional[CallbackManager] = None, is_function_calling_model: bool = True, cached_content: Optional[str] = None, built_in_tool: Optional[types.Tool] = None, use_file_api: bool = True, **kwargs: Any, ): # API keys are optional. The API can be authorised via OAuth (detected # environmentally) or by the GOOGLE_API_KEY environment variable. api_key = api_key or os.getenv("GOOGLE_API_KEY", None) vertexai = ( vertexai_config is not None or os.getenv("GOOGLE_GENAI_USE_VERTEXAI", "false") != "false" ) project = (vertexai_config or {}).get("project") or os.getenv( "GOOGLE_CLOUD_PROJECT", None ) location = (vertexai_config or {}).get("location") or os.getenv( "GOOGLE_CLOUD_LOCATION", None ) config_params: Dict[str, Any] = { "api_key": api_key, } if vertexai_config is not None: config_params.update(vertexai_config) config_params["api_key"] = None config_params["vertexai"] = True elif vertexai: config_params["project"] = project config_params["location"] = location config_params["api_key"] = None config_params["vertexai"] = True if http_options: config_params["http_options"] = http_options if debug_config: config_params["debug_config"] = debug_config client = google.genai.Client(**config_params) model_meta = client.models.get(model=model) super().__init__( model=model, temperature=temperature, context_window=context_window, callback_manager=callback_manager, is_function_calling_model=is_function_calling_model, max_retries=max_retries, cached_content=cached_content, built_in_tool=built_in_tool, use_file_api=use_file_api, **kwargs, ) self.model = model self._client = client self._model_meta = model_meta # store this as a dict and not as a pydantic model so we can more easily # merge it later if generation_config: self._generation_config = generation_config.model_dump() if cached_content: self._generation_config.setdefault("cached_content", cached_content) if built_in_tool is not None: if self._generation_config.get("tools") is None: self._generation_config["tools"] = [] if isinstance(self._generation_config["tools"], list): if len(self._generation_config["tools"]) > 0: raise ValueError( "Providing multiple Google GenAI tools or mixing with custom tools is not supported." ) self._generation_config["tools"].append(built_in_tool) else: config_kwargs = { "temperature": temperature, "max_output_tokens": max_tokens, "cached_content": cached_content, } if built_in_tool: config_kwargs["tools"] = [built_in_tool] self._generation_config = types.GenerateContentConfig( **config_kwargs ).model_dump() self._max_tokens = ( max_tokens or model_meta.output_token_limit or DEFAULT_NUM_OUTPUTS ) @classmethod def class_name(cls) -> str: return "GenAI" @property def metadata(self) -> LLMMetadata: if self.context_window is None: base = self._model_meta.input_token_limit or 200000 total_tokens = base + self._max_tokens else: total_tokens = self.context_window return LLMMetadata( context_window=total_tokens, num_output=self._max_tokens, model_name=self.model, is_chat_model=True, is_function_calling_model=self.is_function_calling_model, ) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: chat_fn = chat_to_completion_decorator(self._chat) return chat_fn(prompt, **kwargs) @llm_completion_callback() async def acomplete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: chat_fn = achat_to_completion_decorator(self._achat) return await chat_fn(prompt, **kwargs) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: chat_fn = stream_chat_to_completion_decorator(self._stream_chat) return chat_fn(prompt, **kwargs) @llm_completion_callback() async def astream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseAsyncGen: chat_fn = astream_chat_to_completion_decorator(self.astream_chat) return await chat_fn(prompt, **kwargs) @llm_retry_decorator def _chat(self, messages: Sequence[ChatMessage], **kwargs: Any): generation_config = { **(self._generation_config or {}), **kwargs.pop("generation_config", {}), } params = {**kwargs, "generation_config": generation_config} next_msg, chat_kwargs = asyncio.run( prepare_chat_params( self.model, messages, self.use_file_api, self._client, **params ) ) chat = self._client.chats.create(**chat_kwargs) response = chat.send_message( next_msg.parts if isinstance(next_msg, types.Content) else next_msg ) if self.use_file_api: asyncio.run( delete_uploaded_files([*chat_kwargs["history"], next_msg], self._client) ) return chat_from_gemini_response(response, []) @llm_retry_decorator async def _achat(self, messages: Sequence[ChatMessage], **kwargs: Any): generation_config = { **(self._generation_config or {}), **kwargs.pop("generation_config", {}), } params = {**kwargs, "generation_config": generation_config} next_msg, chat_kwargs = await prepare_chat_params( self.model, messages, self.use_file_api, self._client, **params ) chat = self._client.aio.chats.create(**chat_kwargs) response = await chat.send_message( next_msg.parts if isinstance(next_msg, types.Content) else next_msg ) if self.use_file_api: await delete_uploaded_files( [*chat_kwargs["history"], next_msg], self._client ) return chat_from_gemini_response(response, []) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: return self._chat(messages, **kwargs) @llm_chat_callback() async def achat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponse: return await self._achat(messages, **kwargs) def _stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: generation_config = { **(self._generation_config or {}), **kwargs.pop("generation_config", {}), } params = {**kwargs, "generation_config": generation_config} next_msg, chat_kwargs = asyncio.run( prepare_chat_params( self.model, messages, self.use_file_api, self._client, **params ) ) chat = self._client.chats.create(**chat_kwargs) response = chat.send_message_stream( next_msg.parts if isinstance(next_msg, types.Content) else next_msg ) def gen() -> ChatResponseGen: content = [] thought_signatures = [] for r in response: if candidates := r.candidates: if not candidates: continue top_candidate = candidates[0] if response_content := top_candidate.content: if parts := response_content.parts: content_delta = parts[0].text llama_resp = chat_from_gemini_response( r, existing_content=content ) llama_resp.delta = llama_resp.delta or content_delta or "" # re-align thought signatures thought_signatures.extend( llama_resp.message.additional_kwargs.get( "thought_signatures", [] ) ) llama_resp.message.additional_kwargs[ "thought_signatures" ] = thought_signatures yield llama_resp if self.use_file_api: asyncio.run( delete_uploaded_files( [*chat_kwargs["history"], next_msg], self._client ) ) return gen() @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: return self._stream_chat(messages, **kwargs) async def _astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: generation_config = { **(self._generation_config or {}), **kwargs.pop("generation_config", {}), } params = {**kwargs, "generation_config": generation_config} next_msg, chat_kwargs = await prepare_chat_params( self.model, messages, self.use_file_api, self._client, **params ) chat = self._client.aio.chats.create(**chat_kwargs) async def gen() -> ChatResponseAsyncGen: content = [] thought_signatures = [] async for r in await chat.send_message_stream( next_msg.parts if isinstance(next_msg, types.Content) else next_msg ): if candidates := r.candidates: if not candidates: continue top_candidate = candidates[0] if response_content := top_candidate.content: if parts := response_content.parts: content_delta = parts[0].text llama_resp = chat_from_gemini_response( r, existing_content=content ) llama_resp.delta = llama_resp.delta or content_delta or "" # re-align thought signatures thought_signatures.extend( llama_resp.message.additional_kwargs.get( "thought_signatures", [] ) ) llama_resp.message.additional_kwargs[ "thought_signatures" ] = thought_signatures yield llama_resp if self.use_file_api: await delete_uploaded_files( [*chat_kwargs["history"], next_msg], self._client ) return gen() @llm_chat_callback() async def astream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseAsyncGen: return await self._astream_chat(messages, **kwargs) def _prepare_chat_with_tools( self, tools: Sequence["BaseTool"], user_msg: Optional[Union[str, ChatMessage]] = None, chat_history: Optional[List[ChatMessage]] = None, verbose: bool = False, allow_parallel_tool_calls: bool = False, tool_required: bool = False, tool_choice: Optional[Union[str, dict]] = None, strict: Optional[bool] = None, **kwargs: Any, ) -> Dict[str, Any]: """Predict and call the tool.""" if tool_choice is None: tool_choice = "any" if tool_required else "auto" if tool_choice == "auto": tool_mode = types.FunctionCallingConfigMode.AUTO elif tool_choice == "none": tool_mode = types.FunctionCallingConfigMode.NONE else: tool_mode = types.FunctionCallingConfigMode.ANY function_calling_config = types.FunctionCallingConfig(mode=tool_mode) if tool_choice not in ["auto", "none"]: if isinstance(tool_choice, dict): raise ValueError("Gemini does not support tool_choice as a dict") # assume that the user wants a tool call to be made # if the tool choice is not in the list of tools, then we will make a tool call to all tools # otherwise, we will make a tool call to the tool choice tool_names = [tool.metadata.name for tool in tools if tool.metadata.name] if tool_choice not in tool_names: function_calling_config.allowed_function_names = tool_names else: function_calling_config.allowed_function_names = [tool_choice] tool_config = types.ToolConfig( function_calling_config=function_calling_config, ) tool_declarations = [] for tool in tools: if tool.metadata.fn_schema: function_declaration = convert_schema_to_function_declaration( self._client, tool ) tool_declarations.append(function_declaration) if isinstance(user_msg, str): user_msg = ChatMessage(role=MessageRole.USER, content=user_msg) messages = chat_history or [] if user_msg: messages.append(user_msg) return { "messages": messages, "tools": ( [types.Tool(function_declarations=tool_declarations)] if tool_declarations else None ), "tool_config": tool_config, **kwargs, } def get_tool_calls_from_response( self, response: ChatResponse, error_on_no_tool_call: bool = True, **kwargs: Any, ) -> List[ToolSelection]: """Predict and call the tool.""" tool_calls = [ block for block in response.message.blocks if isinstance(block, ToolCallBlock) ] if len(tool_calls) < 1: if error_on_no_tool_call: raise ValueError( f"Expected at least one tool call, but got {len(tool_calls)} tool calls." ) else: return [] tool_selections = [] for tool_call in tool_calls: tool_selections.append( ToolSelection( tool_id=tool_call.tool_name, tool_name=tool_call.tool_name, tool_kwargs=cast(Dict[str, Any], tool_call.tool_kwargs), ) ) return tool_selections @dispatcher.span def structured_predict_without_function_calling( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> Model: """Structured predict.""" llm_kwargs = llm_kwargs or {} messages = prompt.format_messages(**prompt_args) contents = [ asyncio.run( chat_message_to_gemini(message, self.use_file_api, self._client) ) for message in messages ] response = self._client.models.generate_content( model=self.model, contents=contents, **{ **llm_kwargs, **{ "config": { "response_mime_type": "application/json", "response_schema": output_cls, } }, }, ) if self.use_file_api: asyncio.run(delete_uploaded_files(contents, self._client)) if isinstance(response.parsed, BaseModel): return response.parsed else: raise ValueError("Response is not a BaseModel") @dispatcher.span def structured_predict( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> Model: """Structured predict.""" llm_kwargs = llm_kwargs or {} if self.pydantic_program_mode == PydanticProgramMode.DEFAULT: generation_config = { **(self._generation_config or {}), **llm_kwargs.pop("generation_config", {}), } # set the specific types needed for the response generation_config["response_mime_type"] = "application/json" generation_config["response_schema"] = output_cls messages = prompt.format_messages(**prompt_args) contents = [ asyncio.run( chat_message_to_gemini(message, self.use_file_api, self._client) ) for message in messages ] response = self._client.models.generate_content( model=self.model, contents=contents, config=generation_config, ) if self.use_file_api: asyncio.run(delete_uploaded_files(contents, self._client)) if isinstance(response.parsed, BaseModel): return response.parsed else: # Try to parse the response text as JSON into the output_cls return output_cls.model_validate_json(response.text) else: return super().structured_predict( output_cls, prompt, llm_kwargs=llm_kwargs, **prompt_args ) @dispatcher.span async def astructured_predict( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> Model: """Structured predict.""" llm_kwargs = llm_kwargs or {} if self.pydantic_program_mode == PydanticProgramMode.DEFAULT: generation_config = { **(self._generation_config or {}), **llm_kwargs.pop("generation_config", {}), } # set the specific types needed for the response generation_config["response_mime_type"] = "application/json" generation_config["response_schema"] = output_cls messages = prompt.format_messages(**prompt_args) contents = await asyncio.gather( *[ chat_message_to_gemini(message, self.use_file_api, self._client) for message in messages ] ) response = await self._client.aio.models.generate_content( model=self.model, contents=contents, config=generation_config, ) if self.use_file_api: await delete_uploaded_files(contents, self._client) if isinstance(response.parsed, BaseModel): return response.parsed else: # Try to parse the response text as JSON into the output_cls return output_cls.model_validate_json(response.text) else: return super().structured_predict( output_cls, prompt, llm_kwargs=llm_kwargs, **prompt_args ) @dispatcher.span def stream_structured_predict( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> Generator[Union[Model, FlexibleModel], None, None]: """Stream structured predict.""" llm_kwargs = llm_kwargs or {} if self.pydantic_program_mode == PydanticProgramMode.DEFAULT: generation_config = { **(self._generation_config or {}), **llm_kwargs.pop("generation_config", {}), } # set the specific types needed for the response generation_config["response_mime_type"] = "application/json" generation_config["response_schema"] = output_cls messages = prompt.format_messages(**prompt_args) contents = [ asyncio.run( chat_message_to_gemini(message, self.use_file_api, self._client) ) for message in messages ] def gen() -> Generator[Union[Model, FlexibleModel], None, None]: flexible_model = create_flexible_model(output_cls) response_gen = self._client.models.generate_content_stream( model=self.model, contents=contents, config=generation_config, ) current_json = "" for chunk in response_gen: if chunk.parsed: yield chunk.parsed elif chunk.candidates: streaming_model, current_json = handle_streaming_flexible_model( current_json, chunk.candidates[0], output_cls, flexible_model, ) if streaming_model: yield streaming_model if self.use_file_api: asyncio.run(delete_uploaded_files(contents, self._client)) return gen() else: return super().stream_structured_predict( output_cls, prompt, llm_kwargs=llm_kwargs, **prompt_args ) @dispatcher.span async def astream_structured_predict( self, output_cls: Type[Model], prompt: PromptTemplate, llm_kwargs: Optional[Dict[str, Any]] = None, **prompt_args: Any, ) -> AsyncGenerator[Union[Model, FlexibleModel], None]: """Stream structured predict.""" llm_kwargs = llm_kwargs or {} if self.pydantic_program_mode == PydanticProgramMode.DEFAULT: generation_config = { **(self._generation_config or {}), **llm_kwargs.pop("generation_config", {}), } # set the specific types needed for the response generation_config["response_mime_type"] = "application/json" generation_config["response_schema"] = output_cls messages = prompt.format_messages(**prompt_args) contents = await asyncio.gather( *[ chat_message_to_gemini(message, self.use_file_api, self._client) for message in messages ] ) async def gen() -> AsyncGenerator[Union[Model, FlexibleModel], None]: flexible_model = create_flexible_model(output_cls) response_gen = await self._client.aio.models.generate_content_stream( model=self.model, contents=contents, config=generation_config, ) current_json = "" async for chunk in response_gen: if chunk.parsed: yield chunk.parsed elif chunk.candidates: streaming_model, current_json = handle_streaming_flexible_model( current_json, chunk.candidates[0], output_cls, flexible_model, ) if streaming_model: yield streaming_model if self.use_file_api: await delete_uploaded_files(contents, self._client) return gen() else: return await super().astream_structured_predict( output_cls, prompt, llm_kwargs=llm_kwargs, **prompt_args )
GoogleGenAI
python
pyca__cryptography
src/cryptography/x509/extensions.py
{ "start": 76968, "end": 77880 }
class ____(ExtensionType): def __init__(self, oid: ObjectIdentifier, value: bytes) -> None: if not isinstance(oid, ObjectIdentifier): raise TypeError("oid must be an ObjectIdentifier") self._oid = oid self._value = value @property def oid(self) -> ObjectIdentifier: # type: ignore[override] return self._oid @property def value(self) -> bytes: return self._value def __repr__(self) -> str: return f"<UnrecognizedExtension(oid={self.oid}, value={self.value!r})>" def __eq__(self, other: object) -> bool: if not isinstance(other, UnrecognizedExtension): return NotImplemented return self.oid == other.oid and self.value == other.value def __hash__(self) -> int: return hash((self.oid, self.value)) def public_bytes(self) -> bytes: return self.value
UnrecognizedExtension
python
joke2k__faker
faker/providers/lorem/fa_IR/__init__.py
{ "start": 68, "end": 15144 }
class ____(LoremProvider): """Implement lorem provider for ``fa_IR`` locale. Word list is based on the source(s) below, and some words have been removed to make the word list appropriate for public testing. Sources: - https://1000mostcommonwords.com/1000-most-common-persian-words/ """ word_list = ( "عنوان", "من", "خود", "که", "او", "بود", "برای", "در", "با", "آن‌ها", "بودن", "در", "یک", "دارند", "این", "از", "توسط", "داغ", "کلمه", "اما", "چه", "برخی", "است", "آن", "شما", "یا", "حال", "تر", "از", "به", "و", "دست", "در", "ما", "می‌توانید", "از", "دیگر", "بود", "که", "انجام", "شان", "زمان", "اگر", "خواهد‌شد", "چگونه", "گفت:", "پا", "هر", "بگو", "می‌کند", "مجموعه", "سه", "می‌خواهم", "هوا", "خوبی", "همچنین", "بازی", "کوچک", "پایان", "قراردادن", "خانه", "به‌عنوان", "دست", "بندر", "بزرگ", "طلسم", "اضافه", "حتی", "زمین", "اینجا", "باید", "بزرگ", "بالا", "ازجمله", "دنبال", "عمل", "بپرسید", "مردها", "تغییر", "رفت", "نور", "نوع", "خاموش", "نیاز", "خانه", "تصویر", "سعی‌کنید", "ما", "دوباره", "حیوانات", "نقطه", "مادر", "جهان", "در‌نزدیکی", "ساخت", "خود", "زمین", "پدر", "هر", "جدید", "کار", "بخش", "را", "دریافت", "محل", "ساخته", "زنده", "کمی", "تنها", "دور", "مرد", "سال", "آمد", "نمایش", "هر", "خوب", "را", "ما", "در", "بسیار", "فقط", "فرم", "حکم", "بزرگ", "می‌گویند", "کمک", "کم", "خط", "متفاوت", "علت", "بسیار", "متوسط", "قبل", "حرکت", "راست", "پسر", "قدیمی", "هم", "همان", "او", "همه", "وجوددارد", "بالا", "استفاده", "راه", "درمورد", "نوشتن", "را", "مانند", "تا", "این‌ها", "او", "طولانی", "را", "ببینید", "او", "دو", "دارد", "نگاه", "تر", "روز", "می‌تواند", "به", "آمده", "انجام", "تعداد", "صدا", "هیچ", "بیشترین", "مردم", "من", "روی", "می‌دانم", "اب", "تماس", "اولین", "که", "پایین", "سمت", "بوده", "ساعت", "سر", "ایستادن", "خود", "صفحه", "باید", "کشور", "یافت", "پاسخ", "مدرسه", "رشد", "مطالعه", "هنوز", "یادگیری", "کارخانه", "پوشش", "آفتاب", "چهار", "بین", "دولت", "چشم", "هرگز", "آخرین", "اجازه", "فکر", "شهرستان", "درخت", "صلیب", "مزرعه", "سخت", "شروع", "زور", "داستان", "اره", "بسیار", "دریا", "اواخر", "اجرا", "نکن", "مطبوعات", "نزدیک", "شب", "واقعی", "زندگی", "کم", "شمال", "کتاب", "حمل", "علم", "خوردن", "اتاق", "دوستان", "ایده", "ماهی", "کوه", "توقف", "پایه", "گوش", "اسب", "برش", "مطمئن", "تماشای", "رنگ", "صورت", "چوب", "اصلی", "باز", "باهم", "بعدی", "سفید", "کودکان", "شروع", "رو", "مثال", "آسان", "مقاله", "گروه", "همیشه", "موسیقی", "آن", "هردو", "علامت", "غالبا", "نامه", "مایل", "رودخانه", "اتومبیل", "پا", "مراقبت", "دوم", "کافی", "ساده", "دختر", "معمول", "جوان", "اماده", "بالا", "همیشه", "قرمز", "لیست", "هرچند", "احساس", "بحث", "پرنده", "بزودی", "بدن", "سگ", "خانواده", "مستقیم", "مطرح", "ترک", "آهنگ", "درب", "محصول", "کوتاه", "کلاس", "باد", "سوال", "کامل", "کشتی", "منطقه", "نیم", "سنگ", "منظور", "آتش", "جنوب", "مشکل", "قطعه", "گفت", "عبور", "بالا", "تمام", "پادشاه", "خیابان", "اینچ", "ضرب", "هیچ", "البته", "اقامت", "چرخ", "کامل", "نیروی", "آبی", "شی", "سطح", "عمیق", "ماه", "جزیره", "پا", "سیستم", "مشغول", "آزمون", "رکورد", "قایق", "مشترک", "طلا", "ممکن", "هواپیما", "جا", "خشک", "خنده", "هزار", "پیش", "فرار", "بررسی", "بازی", "شکل", "برابر", "داغ", "دست", "آورده", "حرارت", "برف", "لاستیک", "را", "بله", "دور", "پر", "شرق", "رنگ", "زبان", "درمیان", "واحد", "قدرت", "شهر", "خوب", "معین", "پرواز", "سقوط", "شود", "فریاد", "تاریک", "ماشین", "یادداشت", "صبر", "برنامه", "شکل", "ستاره", "جعبه", "اسم", "حوزه", "بقیه", "درست", "قادر", "پوند", "انجام", "زیبایی", "درایو", "شامل", "جلو", "آموزش", "هفته", "نهایی", "به", "سبز", "آه", "سریع", "توسعه", "اقیانوس", "گرم", "رایگان", "دقیقه", "قوی", "ویژه", "ذهن", "روشن", "دم", "محصول", "واقع", "فضا", "شنیده", "بهترین", "ساعت", "بهتر", "در", "صد", "پنج", "گام", "اوایل", "غرب", "زمین", "علاقه", "سریع", "فعل", "شش", "جدول", "سفر", "کمتر", "صبح", "ده", "ساده", "چند", "واکه", "جنگ", "دربرابر", "الگوی", "کند", "مرکز", "فرد", "پول", "خدمت", "جاده", "نقشه", "باران", "قانون", "حکومت", "کشیدن", "سرد", "اطلاع", "صدای", "انرژی", "شکار", "احتمالی", "تخت", "برادر", "سوار", "سلول", "باور", "شاید", "ناگهانی", "شمار", "مربع", "دلیل", "طول", "نمایندگی", "هنر", "موضوع", "منطقه", "اندازه", "کنند", "وزن", "عمومی", "یخ", "موضوع", "دایره", "جفت", "تقسیم", "هجاز", "نمد", "بزرگ", "توپ", "هنوز", "موج", "قلب", "ساعت", "حاضر", "سنگین", "رقص", "موتور", "موقعیت", "دست", "گسترده", "بادبان", "ماده", "بخش", "جنگل", "نشستن", "مسابقه", "پنجره", "فروشگاه", "تابستان", "قطار", "خواب", "ثابت", "تنها", "پا", "ورزش", "دیوار", "گرفتن", "کوه", "آرزو", "آسمان", "لذت", "زمستان", "شنبه", "وحشی", "ابزار", "شیشه‌ای", "چمن", "گاو", "کار", "لبه", "علامت", "بازدید", "گذشته", "نرم", "سرگرم", "روشن", "گاز", "ماه", "میلیون", "تحمل", "پایان", "شاد", "امیدوارم", "گل", "پوشاندن", "رفته", "تجارت", "ملودی", "سفر", "دفتر", "دریافت", "ردیف", "دهان", "دقیق", "نماد", "مرگ", "کمترین", "مشکل", "فریاد", "جز", "نوشت", "دانه", "تن", "عضویت", "تمیز", "استراحت", "خانم", "حیاط", "افزایش", "بد", "ضربه", "نفت", "خون", "رشد", "در‌صد", "مخلوط", "تیم", "سیم", "هزینه", "قهوه‌ای", "لباس", "باغ", "برابر", "ارسال", "کنید", "سقوط", "مناسب", "جریان", "عادلانه", "بانک", "ذخیره", "کنترل", "اعشاری", "گوش", "دیگر", "کاملا", "شکست", "مورد", "متوسط", "کشتن", "پسر", "دریاچه", "لحظه‌ای", "مقیاس", "باصدا", "بهار", "مشاهده", "کودک", "مستقیم", "همخوان", "کشور", "شیر", "سرعت", "روش", "عضو", "پرداخت", "سن", "بخش", "لباس", "ابر", "تعجب", "آرام", "سنگ", "کوچک", "صعود", "سرد", "طراحی", "ضعیف", "زیادی", "تجربه", "پایین", "کلید", "اهن", "تک", "چوب", "تخت", "بیست", "پوست", "لبخند", "چینی", "سوراخ", "کودک", "هشت", "روستای", "ملاقات", "ریشه", "خرید", "بالابردن", "حل", "فلز", "چه", "فشار", "هفت", "بند", "سوم", "باید", "مو", "توصیف", "آشپز", "طبقه", "یا", "نتیجه", "رایت", "تپه", "امن", "گربه", "قرن", "در‌نظر", "نوع", "قانون", "بیت", "ساحل", "کپی", "عبارت", "خاموش", "بلند", "شن", "خاک", "رول", "انگشت", "صنعت", "ارزش", "مبارزه", "دروغ", "تحریک", "طبیعی", "نظر", "احساس", "سرمایه", "نه", "صندلی", "خطر", "میوه", "غنی", "ضخامت", "سرباز", "روند", "کار", "عمل", "جداگانه", "دشوار", "دکتر", "لطفا", "محافظت", "ظهر", "محصول", "مدرن", "عنصر", "ضربه", "گوشه", "حزب", "عرضه", "که", "قرار", "حلقه", "شخصیت", "حشرات", "گرفتار", "دوره", "رادیو", "صحبت", "اتم", "انسانی", "تاریخ", "اثر", "برق", "انتظار", "استخوان", "نرده", "ارائه", "توافق", "بنابراین", "ملایم", "زن", "کاپیتان", "لازم", "تیز", "بال", "ایجاد", "همسایه", "شستشو", "خفاش", "نه", "جمعیت", "ذرت", "مقایسه", "شعر", "رشته", "زنگ", "گوشت", "مالیدن", "لوله", "معروف", "دلار", "جریان", "ترس", "نظر", "نازک", "مثلث", "سیاره", "عجله‌ای", "رئیس", "مستعمره", "ساعت", "معدن", "کراوات", "اصلی", "تازه", "جستجو", "ارسال", "زرد", "اسلحه", "اجازه", "چاپ", "مرده", "نقطه", "بیابان", "جریان", "آسانسور", "افزایش", "رسیدن", "کارشناس", "آهنگ", "ساحل", "بخش", "ورق", "ماده", "اتصال", "پست", "وتر", "چربی", "خوشحالم", "اصلی", "سهم", "ایستگاه", "پدر", "نان", "شارژ", "مناسب", "بار", "پیشنهاد", "بخش", "برده", "اردک", "فوری", "بازار", "درجه", "جمعیت", "جوجه", "عزیز", "دشمن", "پاسخ", "نوشابه", "پشتیبانی", "سخنرانی", "طبیعت", "دامنه", "بخار", "حرکت", "راه", "مایع", "دندانها", "پوسته", "گردن", "اکسیژن", "قند", "مرگ", "خوب", "مهارت", "زنان", "فصل", "مغناطیس", "نقره‌ای", "تشکر", "شاخه", "مسابقه", "پسوند", "ویژه", "انجیر", "ترس", "بزرگ", "خواهر", "فولاد", "بحث", "مشابه", "راهنمایی", "تجربه", "نمره", "سیب", "خریداری", "رهبری", "زمین", "کت", "جرم", "کارت", "گروه", "طناب", "لغزش", "برنده", "رویا", "شب", "شرایط", "خوراک", "ابزار", "کل", "اساسی", "بوی", "دره", "دو", "صندلی", "ادامه", "بلوک", "نمودار", "کلاه", "فروش", "موفقیت", "شرکت", "تفریق", "رویداد", "خاص", "معامله", "شنا", "مدت", "همسر", "کفش", "شانه", "گسترش", "ترتیب", "اردوگاه", "اختراع", "پنبه", "متولد", "تعیین", "کوارت", "نه", "کامیون", "سطح", "شانس", "فروشگاه", "کشش", "پرتاب", "درخشش", "خاصیت", "ستون", "مولکول", "اشتباه", "خاکستری", "تکرار", "نیاز", "پهن", "آماده", "نمک", "بینی", "جمع", "خشم", "ادعا", "قاره", ) parts_of_speech: Dict[str, tuple] = {}
Provider
python
kamyu104__LeetCode-Solutions
Python/shortest-common-supersequence.py
{ "start": 37, "end": 1315 }
class ____(object): def shortestCommonSupersequence(self, str1, str2): """ :type str1: str :type str2: str :rtype: str """ dp = [[0 for _ in xrange(len(str2)+1)] for _ in xrange(2)] bt = [[None for _ in xrange(len(str2)+1)] for _ in xrange(len(str1)+1)] for i, c in enumerate(str1): bt[i+1][0] = (i, 0, c) for j, c in enumerate(str2): bt[0][j+1] = (0, j, c) for i in xrange(len(str1)): for j in xrange(len(str2)): if dp[i % 2][j+1] > dp[(i+1) % 2][j]: dp[(i+1) % 2][j+1] = dp[i % 2][j+1] bt[i+1][j+1] = (i, j+1, str1[i]) else: dp[(i+1) % 2][j+1] = dp[(i+1) % 2][j] bt[i+1][j+1] = (i+1, j, str2[j]) if str1[i] != str2[j]: continue if dp[i % 2][j]+1 > dp[(i+1) % 2][j+1]: dp[(i+1) % 2][j+1] = dp[i % 2][j]+1 bt[i+1][j+1] = (i, j, str1[i]) i, j = len(str1), len(str2) result = [] while i != 0 or j != 0: i, j, c = bt[i][j] result.append(c) result.reverse() return "".join(result)
Solution
python
Farama-Foundation__Gymnasium
gymnasium/spaces/space.py
{ "start": 369, "end": 6852 }
class ____(Generic[T_cov]): """Superclass that is used to define observation and action spaces. Spaces are crucially used in Gym to define the format of valid actions and observations. They serve various purposes: * They clearly define how to interact with environments, i.e. they specify what actions need to look like and what observations will look like * They allow us to work with highly structured data (e.g. in the form of elements of :class:`Dict` spaces) and painlessly transform them into flat arrays that can be used in learning code * They provide a method to sample random elements. This is especially useful for exploration and debugging. Different spaces can be combined hierarchically via container spaces (:class:`Tuple` and :class:`Dict`) to build a more expressive space Warning: Custom observation & action spaces can inherit from the ``Space`` class. However, most use-cases should be covered by the existing space classes (e.g. :class:`Box`, :class:`Discrete`, etc...), and container classes (:class:`Tuple` & :class:`Dict`). Note that parametrized probability distributions (through the :meth:`Space.sample()` method), and batching functions (in :class:`gym.vector.VectorEnv`), are only well-defined for instances of spaces provided in gym by default. Moreover, some implementations of Reinforcement Learning algorithms might not handle custom spaces properly. Use custom spaces with care. """ def __init__( self, shape: Sequence[int] | None = None, dtype: npt.DTypeLike | None = None, seed: int | np.random.Generator | None = None, ): """Constructor of :class:`Space`. Args: shape (Optional[Sequence[int]]): If elements of the space are numpy arrays, this should specify their shape. dtype (Optional[Type | str]): If elements of the space are numpy arrays, this should specify their dtype. seed: Optionally, you can use this argument to seed the RNG that is used to sample from the space """ self._shape = None if shape is None else tuple(shape) self.dtype = None if dtype is None else np.dtype(dtype) self._np_random = None if seed is not None: if isinstance(seed, np.random.Generator): self._np_random = seed else: self.seed(seed) @property def np_random(self) -> np.random.Generator: """Lazily seed the PRNG since this is expensive and only needed if sampling from this space. As :meth:`seed` is not guaranteed to set the `_np_random` for particular seeds. We add a check after :meth:`seed` to set a new random number generator. """ if self._np_random is None: self.seed() # As `seed` is not guaranteed (in particular for composite spaces) to set the `_np_random` then we set it randomly. if self._np_random is None: self._np_random, _ = seeding.np_random() return self._np_random @property def shape(self) -> tuple[int, ...] | None: """Return the shape of the space as an immutable property.""" return self._shape @property def is_np_flattenable(self) -> bool: """Checks whether this space can be flattened to a :class:`gymnasium.spaces.Box`.""" raise NotImplementedError def sample(self, mask: Any | None = None, probability: Any | None = None) -> T_cov: """Randomly sample an element of this space. Can be uniform or non-uniform sampling based on boundedness of space. The binary mask and the probability mask can't be used at the same time. Args: mask: A mask used for random sampling, expected ``dtype=np.int8`` and see sample implementation for expected shape. probability: A probability mask used for sampling according to the given probability distribution, expected ``dtype=np.float64`` and see sample implementation for expected shape. Returns: A sampled actions from the space """ raise NotImplementedError def seed(self, seed: int | None = None) -> int | list[int] | dict[str, int]: """Seed the pseudorandom number generator (PRNG) of this space and, if applicable, the PRNGs of subspaces. Args: seed: The seed value for the space. This is expanded for composite spaces to accept multiple values. For further details, please refer to the space's documentation. Returns: The seed values used for all the PRNGs, for composite spaces this can be a tuple or dictionary of values. """ self._np_random, np_random_seed = seeding.np_random(seed) return np_random_seed def contains(self, x: Any) -> bool: """Return boolean specifying if x is a valid member of this space, equivalent to ``sample in space``.""" raise NotImplementedError def __contains__(self, x: Any) -> bool: """Return boolean specifying if x is a valid member of this space.""" return self.contains(x) def __setstate__(self, state: Iterable[tuple[str, Any]] | Mapping[str, Any]): """Used when loading a pickled space. This method was implemented explicitly to allow for loading of legacy states. Args: state: The updated state value """ # Don't mutate the original state state = dict(state) # Allow for loading of legacy states. # See: # https://github.com/openai/gym/pull/2397 -- shape # https://github.com/openai/gym/pull/1913 -- np_random # if "shape" in state: state["_shape"] = state.get("shape") del state["shape"] if "np_random" in state: state["_np_random"] = state["np_random"] del state["np_random"] # Update our state self.__dict__.update(state) def to_jsonable(self, sample_n: Sequence[T_cov]) -> list[Any]: """Convert a batch of samples from this space to a JSONable data type.""" # By default, assume identity is JSONable return list(sample_n) def from_jsonable(self, sample_n: list[Any]) -> list[T_cov]: """Convert a JSONable data type to a batch of samples from this space.""" # By default, assume identity is JSONable return sample_n
Space
python
tox-dev__tox
src/tox/execute/local_sub_process/read_via_thread_unix.py
{ "start": 467, "end": 2049 }
class ____(ReadViaThread): # pragma: win32 no cover def __init__(self, file_no: int, handler: Callable[[bytes], None], name: str, drain: bool) -> None: # noqa: FBT001 super().__init__(file_no, handler, name, drain) def _read_stream(self) -> None: while not self.stop.is_set(): # we need to drain the stream, but periodically give chance for the thread to break if the stop event has # been set (this is so that an interrupt can be handled) if self._read_available() is None: # pragma: no branch break # pragma: no cover def _drain_stream(self) -> None: # no block just poll while True: if self._read_available(timeout=0) is not True: # pragma: no branch break # pragma: no cover def _read_available(self, timeout: float = STOP_EVENT_CHECK_PERIODICITY_IN_MS) -> bool | None: try: ready, __, ___ = select.select([self.file_no], [], [], timeout) if ready: data = os.read(self.file_no, 1024) # read up to 1024 characters # If the end of the file referred to by fd has been reached, an empty bytes object is returned. if data: self.handler(data) return True except OSError as exception: # pragma: no cover # Bad file descriptor or Input/output error if exception.errno in {errno.EBADF, errno.EIO}: return None raise else: return False
ReadViaThreadUnix
python
fluentpython__example-code
11-iface-abc/tombolist.py
{ "start": 84, "end": 504 }
class ____(list): # <2> def pick(self): if self: # <3> position = randrange(len(self)) return self.pop(position) # <4> else: raise LookupError('pop from empty TomboList') load = list.extend # <5> def loaded(self): return bool(self) # <6> def inspect(self): return tuple(sorted(self)) # Tombola.register(TomboList) # <7>
TomboList
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 17463, "end": 17620 }
class ____: def setup(self): self.df = DataFrame(np.random.randn(10000, 1000)) def time_frame_nunique(self): self.df.nunique()
Nunique
python
joerick__pyinstrument
pyinstrument/vendor/decorator.py
{ "start": 10987, "end": 16323 }
class ____(_GeneratorContextManager): def __call__(self, func): """Context manager decorator""" return FunctionMaker.create( func, "with _self_: return _func_(%(shortsignature)s)", dict(_self_=self, _func_=func), __wrapped__=func) init = getfullargspec(_GeneratorContextManager.__init__) n_args = len(init.args) if n_args == 2 and not init.varargs: # (self, genobj) Python 2.7 def __init__(self, g, *a, **k): return _GeneratorContextManager.__init__(self, g(*a, **k)) ContextManager.__init__ = __init__ elif n_args == 2 and init.varargs: # (self, gen, *a, **k) Python 3.4 pass elif n_args == 4: # (self, gen, args, kwds) Python 3.5 def __init__(self, g, *a, **k): return _GeneratorContextManager.__init__(self, g, a, k) ContextManager.__init__ = __init__ _contextmanager = decorator(ContextManager) def contextmanager(func): # Enable Pylint config: contextmanager-decorators=decorator.contextmanager return _contextmanager(func) # ############################ dispatch_on ############################ # def append(a, vancestors): """ Append ``a`` to the list of the virtual ancestors, unless it is already included. """ add = True for j, va in enumerate(vancestors): if issubclass(va, a): add = False break if issubclass(a, va): vancestors[j] = a add = False if add: vancestors.append(a) # inspired from simplegeneric by P.J. Eby and functools.singledispatch def dispatch_on(*dispatch_args): """ Factory of decorators turning a function into a generic function dispatching on the given arguments. """ assert dispatch_args, 'No dispatch args passed' dispatch_str = '(%s,)' % ', '.join(dispatch_args) def check(arguments, wrong=operator.ne, msg=''): """Make sure one passes the expected number of arguments""" if wrong(len(arguments), len(dispatch_args)): raise TypeError('Expected %d arguments, got %d%s' % (len(dispatch_args), len(arguments), msg)) def gen_func_dec(func): """Decorator turning a function into a generic function""" # first check the dispatch arguments argset = set(getfullargspec(func).args) if not set(dispatch_args) <= argset: raise NameError('Unknown dispatch arguments %s' % dispatch_str) typemap = {} def vancestors(*types): """ Get a list of sets of virtual ancestors for the given types """ check(types) ras = [[] for _ in range(len(dispatch_args))] for types_ in typemap: for t, type_, ra in zip(types, types_, ras): if issubclass(t, type_) and type_ not in t.mro(): append(type_, ra) return [set(ra) for ra in ras] def ancestors(*types): """ Get a list of virtual MROs, one for each type """ check(types) lists = [] for t, vas in zip(types, vancestors(*types)): n_vas = len(vas) if n_vas > 1: raise RuntimeError( 'Ambiguous dispatch for %s: %s' % (t, vas)) elif n_vas == 1: va, = vas mro = type('t', (t, va), {}).mro()[1:] else: mro = t.mro() lists.append(mro[:-1]) # discard t and object return lists def register(*types): """ Decorator to register an implementation for the given types """ check(types) def dec(f): check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__) typemap[types] = f return f return dec def dispatch_info(*types): """ An utility to introspect the dispatch algorithm """ check(types) lst = [] for anc in itertools.product(*ancestors(*types)): lst.append(tuple(a.__name__ for a in anc)) return lst def _dispatch(dispatch_args, *args, **kw): types = tuple(type(arg) for arg in dispatch_args) try: # fast path f = typemap[types] except KeyError: pass else: return f(*args, **kw) combinations = itertools.product(*ancestors(*types)) next(combinations) # the first one has been already tried for types_ in combinations: f = typemap.get(types_) if f is not None: return f(*args, **kw) # else call the default implementation return func(*args, **kw) return FunctionMaker.create( func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str, dict(_f_=_dispatch), register=register, default=func, typemap=typemap, vancestors=vancestors, ancestors=ancestors, dispatch_info=dispatch_info, __wrapped__=func) gen_func_dec.__name__ = 'dispatch_on' + dispatch_str return gen_func_dec
ContextManager
python
pennersr__django-allauth
allauth/account/forms.py
{ "start": 26873, "end": 29146 }
class ____(forms.Form): email = EmailField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._has_email = LoginMethod.EMAIL in app_settings.LOGIN_METHODS self._has_phone = LoginMethod.PHONE in app_settings.LOGIN_METHODS if self._has_phone: adapter = get_adapter() self.fields["phone"] = adapter.phone_form_field( required=not self._has_email ) self.fields["email"].required = False # Inconsistent, but kept for backwards compatibility: even if email is not a login # method the email field is added. May be used when login is by username. if self._has_phone and not self._has_email: self.fields.pop("email") def clean(self): cleaned_data = super().clean() adapter = get_adapter() phone = cleaned_data.get("phone") email = cleaned_data.get("email") if email and phone: raise adapter.validation_error("select_only_one") return cleaned_data def clean_phone(self): adapter = get_adapter() phone = self.cleaned_data["phone"] if phone: self._user = adapter.get_user_by_phone(phone) if not self._user and not app_settings.PREVENT_ENUMERATION: raise adapter.validation_error("unknown_phone") if not ratelimit.consume( context.request, action="request_login_code", key=phone.lower() ): raise adapter.validation_error("too_many_login_attempts") return phone def clean_email(self): adapter = get_adapter() email = self.cleaned_data["email"] if email: users = filter_users_by_email(email, is_active=True, prefer_verified=True) if not app_settings.PREVENT_ENUMERATION: if not users: raise adapter.validation_error("unknown_email") if not ratelimit.consume( context.request, action="request_login_code", key=email.lower() ): raise adapter.validation_error("too_many_login_attempts") self._user = users[0] if users else None return email
RequestLoginCodeForm
python
pytorch__pytorch
torch/fx/experimental/migrate_gradual_types/constraint_generator.py
{ "start": 47613, "end": 51315 }
class ____: def __init__(self, traced, graph=None): self.traced = traced # traced or tracer.root self.traced_params = dict(self.traced.named_parameters()) self.constraints = [] self.symbol_dict = {} self.graph = traced.graph if hasattr(traced, "graph") else graph def generate_constraints(self, counter=0): """ Iterate through every node and generate constraints Effect: self.constraints will be populated with the final constraints """ graph = self.graph all_constraints = [] # pyrefly: ignore [missing-attribute] for n in graph.nodes: (constraints, counter) = self.generate_constraints_node(n, counter) all_constraints += constraints return Conj(all_constraints), counter def generate_constraints_node(self, n: Node, counter): """ Generate constraints the given node: Currently supported operations: - Reshape - Add - conv2d """ if n.op == "placeholder": x, counter = gen_tvar(counter) self.symbol_dict[n] = x my_type = n.type if n.type != Dyn and (not isinstance(n.type, TensorType)): if n.type == torch.nn.parameter.Parameter: # since we have a parameter, the shape must be static assert "example_value" in n.meta my_type = TensorType(n.meta["example_value"].size()) else: my_type = Dyn c1 = BinConstraintT(my_type, x, op_precision) c2 = BinConstraintT(x, MAX_TENSOR_RANK, op_leq) return [c1, c2], counter elif n.op == "call_function": if n.target in _INFERENCE_RULES: return _INFERENCE_RULES[n.target]( n, self.symbol_dict, self.constraints, counter ) else: raise RuntimeError( f"No inference rule registered for target {n.target}!" ) elif n.op == "call_module": module_instance = self.traced.get_submodule(n.target) if type(module_instance) in _INFERENCE_RULES: return _INFERENCE_RULES[type(module_instance)]( n, module_instance, self.symbol_dict, self.constraints, counter ) else: raise RuntimeError( f"No inference rule registered for class {type(module_instance)}!" ) elif n.op == "call_method": if n.target in _INFERENCE_RULES: return _INFERENCE_RULES[n.target]( n, self.symbol_dict, self.constraints, counter ) else: raise RuntimeError( f"No inference rule registered for target {n.target}!" ) elif n.op == "get_attr": t = self.traced_params.get(n.target, None) if isinstance(t, torch.Tensor): if len(t.shape) > 0: res = list(t.shape) attr_type = TensorType(res) output, counter = gen_tvar(counter) self.symbol_dict[n] = output return [BinConstraintT(output, attr_type, op_eq)], counter else: # scalar? return [], counter else: return [], counter elif n.op == "output": return [], counter else: raise NotImplementedError(f"Method {n.op} not yet implemented")
ConstraintGenerator
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 14275, "end": 20770 }
class ____(NonStrictDataModel): """ :param key: Entry key :type key: str :param type: System defined type :type type: str :param mode: System defined input/output indication :type mode: str :param uri: Raw data location :type uri: str :param content_size: Raw data length in bytes :type content_size: int :param hash: Hash of entire raw data :type hash: str :param timestamp: Epoch time when artifact was created :type timestamp: int :param type_data: Additional fields defined by the system :type type_data: ArtifactTypeData :param display_data: User-defined list of key/value pairs, sorted :type display_data: Sequence[Sequence[str]] """ _schema = { "properties": { "content_size": { "description": "Raw data length in bytes", "type": "integer", }, "display_data": { "description": "User-defined list of key/value pairs, sorted", "items": {"items": {"type": "string"}, "type": "array"}, "type": "array", }, "hash": {"description": "Hash of entire raw data", "type": "string"}, "key": {"description": "Entry key", "type": "string"}, "mode": { "default": "output", "description": "System defined input/output indication", "enum": ["input", "output"], "type": "string", }, "timestamp": { "description": "Epoch time when artifact was created", "type": "integer", }, "type": {"description": "System defined type", "type": "string"}, "type_data": { "$ref": "#/definitions/artifact_type_data", "description": "Additional fields defined by the system", }, "uri": {"description": "Raw data location", "type": "string"}, }, "required": ["key", "type"], "type": "object", } def __init__( self, key: str, type: str, mode: Optional[str] = "output", uri: Optional[str] = None, content_size: Optional[int] = None, hash: Optional[str] = None, timestamp: Optional[int] = None, type_data: Any = None, display_data: Optional[List[List[str]]] = None, **kwargs: Any ) -> None: super(Artifact, self).__init__(**kwargs) self.key = key self.type = type self.mode = mode self.uri = uri self.content_size = content_size self.hash = hash self.timestamp = timestamp self.type_data = type_data self.display_data = display_data @schema_property("key") def key(self) -> str: return self._property_key @key.setter def key(self, value: str) -> None: if value is None: self._property_key = None return self.assert_isinstance(value, "key", six.string_types) self._property_key = value @schema_property("type") def type(self) -> str: return self._property_type @type.setter def type(self, value: str) -> None: if value is None: self._property_type = None return self.assert_isinstance(value, "type", six.string_types) self._property_type = value @schema_property("mode") def mode(self) -> Optional[str]: return self._property_mode @mode.setter def mode(self, value: Optional[str]) -> None: if value is None: self._property_mode = None return self.assert_isinstance(value, "mode", six.string_types) self._property_mode = value @schema_property("uri") def uri(self) -> Optional[str]: return self._property_uri @uri.setter def uri(self, value: Optional[str]) -> None: if value is None: self._property_uri = None return self.assert_isinstance(value, "uri", six.string_types) self._property_uri = value @schema_property("content_size") def content_size(self) -> Optional[int]: return self._property_content_size @content_size.setter def content_size(self, value: Optional[int]) -> None: if value is None: self._property_content_size = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "content_size", six.integer_types) self._property_content_size = value @schema_property("hash") def hash(self) -> Optional[str]: return self._property_hash @hash.setter def hash(self, value: Optional[str]) -> None: if value is None: self._property_hash = None return self.assert_isinstance(value, "hash", six.string_types) self._property_hash = value @schema_property("timestamp") def timestamp(self) -> Optional[int]: return self._property_timestamp @timestamp.setter def timestamp(self, value: Optional[int]) -> None: if value is None: self._property_timestamp = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "timestamp", six.integer_types) self._property_timestamp = value @schema_property("type_data") def type_data(self) -> Any: return self._property_type_data @type_data.setter def type_data(self, value: Any) -> None: if value is None: self._property_type_data = None return if isinstance(value, dict): value = ArtifactTypeData.from_dict(value) else: self.assert_isinstance(value, "type_data", ArtifactTypeData) self._property_type_data = value @schema_property("display_data") def display_data(self) -> Optional[List[List[str]]]: return self._property_display_data @display_data.setter def display_data(self, value: Optional[List[List[str]]]) -> None: if value is None: self._property_display_data = None return self.assert_isinstance(value, "display_data", (list, tuple)) self.assert_isinstance(value, "display_data", (list, tuple), is_array=True) self._property_display_data = value
Artifact
python
ansible__ansible
test/lib/ansible_test/_internal/host_profiles.py
{ "start": 68222, "end": 68983 }
class ____(SshTargetHostProfile[PosixSshConfig], PosixProfile[PosixSshConfig]): """Host profile for a POSIX SSH instance.""" @property def name(self) -> str: """The name of the host profile.""" return self.config.host def get_controller_target_connections(self) -> list[SshConnection]: """Return SSH connection(s) for accessing the host as a target from the controller.""" settings = SshConnectionDetail( name='target', user=self.config.user, host=self.config.host, port=self.config.port, identity_file=SshKey(self.args).key, python_interpreter=self.python.path, ) return [SshConnection(self.args, settings)]
PosixSshProfile
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 143401, "end": 144548 }
class ____(Response): """ Response of events.next_plot_sample endpoint. """ _service = "events" _action = "next_plot_sample" _version = "2.20" _schema = { "$ref": "#/definitions/plot_sample_response", "definitions": { "plot_sample_response": { "properties": { "event": {"description": "Plot event", "type": ["object", "null"]}, "max_iteration": { "description": "maximal valid iteration for the variant", "type": ["integer", "null"], }, "min_iteration": { "description": "minimal valid iteration for the variant", "type": ["integer", "null"], }, "scroll_id": { "description": "Scroll ID to pass to the next calls to get_plot_sample or next_plot_sample", "type": ["string", "null"], }, }, "type": "object", } }, }
NextPlotSampleResponse
python
getsentry__sentry
src/flagpole/conditions.py
{ "start": 4359, "end": 4654 }
class ____(ConditionBase): value: InOperatorValueTypes operator: str = dataclasses.field(default="in") def _operator_match(self, condition_property: Any, segment_name: str): return self._evaluate_in(condition_property=condition_property, segment_name=segment_name)
InCondition
python
getsentry__sentry
tests/sentry/auth_v2/utils/test_session.py
{ "start": 2538, "end": 9604 }
class ____(TestCase): def setUp(self) -> None: self.request = Mock(spec=Request) self.request.session = MockSession() self.session_builder = SessionBuilder(self.request) def create_mock_user(self, **kwargs): # Default attributes that should all evaluate to False attributes = { "has_verified_primary_email": True, "has_2fa": False, "has_usable_password": True, "has_org_requiring_2fa": False, } properties = { "is_anonymous": False, "is_password_expired": False, } for key, value in kwargs.items(): if key in attributes: attributes[key] = value elif key in properties: properties[key] = value else: raise ValueError(f"Invalid attribute or property: {key}") mock_attributes = {} for key, value in attributes.items(): mock_attributes[f"{key}.return_value"] = value for key, value in properties.items(): mock_attributes[key] = value self.request.user = Mock(**mock_attributes) return self.request.user def test_initialize_does_not_override_flags(self) -> None: """ Ensure that the session builder does not override flags that are already set. """ expected_flags = { "todo_email_verification": False, "todo_2fa_verification": False, "todo_password_reset": False, "todo_2fa_setup": False, } # Set all flags to False for key, value in expected_flags.items(): self.request.session[key] = value # Conditions would usually evaluate flags to all be True, self.request.user = self.create_mock_user( has_verified_primary_email=False, has_2fa=False, is_password_expired=True, has_usable_password=False, has_org_requiring_2fa=True, ) self.session_builder.initialize_auth_flags() # Assert that the flags are not overridden assert self.request.session.data == expected_flags assert len(self.request.session.data) == len(expected_flags.keys()) def test_initialize_no_user(self) -> None: self.request.user = None self.session_builder.initialize_auth_flags() assert len(self.request.session.data) == 0 def test_initialize_anonymous_user(self) -> None: self.create_mock_user(is_anonymous=True) self.session_builder.initialize_auth_flags() assert len(self.request.session.data) == 0 def test_initialize_all_flags_false(self) -> None: self.create_mock_user() self.session_builder.initialize_auth_flags() expected_flags = { "todo_email_verification": False, "todo_2fa_verification": False, "todo_password_reset": False, "todo_2fa_setup": False, } assert self.request.session.data == expected_flags assert len(self.request.session.data) == len(expected_flags.keys()) def test_initialize_all_flags_true(self) -> None: self.request.user = self.create_mock_user( has_verified_primary_email=False, has_2fa=True, is_password_expired=True, has_usable_password=False, has_org_requiring_2fa=True, ) self.session_builder.initialize_auth_flags() expected_flags = { "todo_email_verification": True, "todo_2fa_verification": True, "todo_password_reset": True, "todo_2fa_setup": False, # False because user already has 2FA enabled } assert self.request.session.data == expected_flags assert len(self.request.session.data) == len(expected_flags.keys()) def test_initialize_todo_password_reset(self) -> None: """ todo_password_reset has 2 conditions that trigger it. """ # Case 1:Password is expired and usable self.request.user = self.create_mock_user( is_password_expired=True, has_usable_password=True, ) self.session_builder.initialize_auth_flags() assert self.request.session.data["todo_password_reset"] is True # Reset session self.request.session = MockSession() self.session_builder = SessionBuilder(self.request) # Case 2: Password is not expired and usable self.request.user = self.create_mock_user( is_password_expired=False, has_usable_password=True, ) self.session_builder.initialize_auth_flags() assert self.request.session.data["todo_password_reset"] is False # Reset session self.request.session = MockSession() self.session_builder = SessionBuilder(self.request) # Case 3: Password is not expired and not usable self.request.user = self.create_mock_user( is_password_expired=False, has_usable_password=False, ) self.session_builder.initialize_auth_flags() assert self.request.session["todo_password_reset"] is True def test_initialize_todo_2fa_setup_logic(self) -> None: # Case 1: User has org requiring 2FA but no 2FA enabled -> should be True self.request.user = self.create_mock_user( has_org_requiring_2fa=True, has_2fa=False, ) self.session_builder.initialize_auth_flags() assert self.request.session.data["todo_2fa_setup"] is True # Reset session self.request.session = MockSession() self.session_builder = SessionBuilder(self.request) # Case 2: User has org requiring 2FA and already has 2FA enabled -> should be False self.request.user = self.create_mock_user( has_org_requiring_2fa=True, has_2fa=True, ) self.session_builder.initialize_auth_flags() assert self.request.session.data["todo_2fa_setup"] is False # Reset session self.request.session = MockSession() self.session_builder = SessionBuilder(self.request) # Case 3: User doesn't have org requiring 2FA and no 2FA enabled -> should be False self.request.user = self.create_mock_user( has_org_requiring_2fa=False, has_2fa=False, ) self.session_builder.initialize_auth_flags() assert self.request.session.data["todo_2fa_setup"] is False # Reset session self.request.session = MockSession() self.session_builder = SessionBuilder(self.request) # Case 4: User doesn't have org requiring 2FA but has 2FA enabled -> should be False self.request.user = self.create_mock_user( has_org_requiring_2fa=False, has_2fa=True, ) self.session_builder.initialize_auth_flags() assert self.request.session.data["todo_2fa_setup"] is False
SessionBuilderTest