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
getsentry__sentry
src/sentry/utils/prompts.py
{ "start": 2252, "end": 3579 }
class ____: """ Used to configure available 'prompts' (frontend modals or UI that may be dismissed or have some other action recorded about it). This config declares what prompts are available And what fields may be required. required_fields available: [organization_id, project_id] """ def __init__(self, prompts: dict[str, _PromptConfig]): self.prompts = prompts def add(self, name: str, config: _PromptConfig) -> None: if self.has(name): raise Exception(f"Prompt key {name} is already in use") if "required_fields" not in config: raise Exception("'required_fields' must be present in the config dict") self.prompts[name] = config def has(self, name: str) -> bool: return name in self.prompts def get(self, name: str) -> _PromptConfig: return self.prompts[name] def required_fields(self, name: str) -> list[str]: return self.prompts[name]["required_fields"] prompt_config = PromptsConfig(DEFAULT_PROMPTS) def get_prompt_activities_for_user( organization_ids: Sequence[int], user_id: int, features: Sequence[str] ) -> QuerySet[PromptsActivity]: return PromptsActivity.objects.filter( organization_id__in=organization_ids, feature__in=features, user_id=user_id )
PromptsConfig
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 30914, "end": 35212 }
class ____(BaseDataset): """ Feature: Datasets can use the scale/offset filter Note: loss of precision caused by scaleoffset only becomes visible when closing and reopening the File. Can't close/reopen the shared self.f in pytest-run-parallel. """ def test_float_fails_without_options(self): """ Ensure that a scale factor is required for scaleoffset compression of floating point data """ with self.assertRaises(ValueError): dset = self.f.create_dataset(make_name(), (20, 30), dtype=float, scaleoffset=True) def test_non_integer(self): """ Check when scaleoffset is negetive""" with self.assertRaises(ValueError): dset = self.f.create_dataset(make_name(), (20, 30), dtype=float, scaleoffset=-0.1) def test_unsupport_dtype(self): """ Check when dtype is unsupported type""" with self.assertRaises(TypeError): dset = self.f.create_dataset(make_name(), (20, 30), dtype=bool, scaleoffset=True) def test_float(self): """ Scaleoffset filter works for floating point data """ scalefac = 4 shape = (100, 300) range = 20 * 10 ** scalefac testdata = (np.random.rand(*shape) - 0.5) * range fname = self.mktemp() with h5py.File(fname, 'w') as f: dset = f.create_dataset( 'foo', shape, dtype=np.float64, scaleoffset=scalefac ) # Dataset reports that scaleoffset is in use assert dset.scaleoffset is not None # Dataset round-trips dset[...] = testdata with h5py.File(fname, 'r') as f: readdata = f['foo'][...] # Test that data round-trips to requested precision self.assertArrayEqual(readdata, testdata, precision=10 ** (-scalefac)) # Test that the filter is actually active (i.e. compression is lossy) assert not (readdata == testdata).all() def test_int(self): """ Scaleoffset filter works for integer data with default precision """ nbits = 12 shape = (100, 300) testdata = np.random.randint(0, 2 ** nbits - 1, size=shape, dtype=np.int64) fname = self.mktemp() with h5py.File(fname, 'w') as f: # Create dataset; note omission of nbits (for library-determined precision) dset = f.create_dataset('foo', shape, dtype=np.int64, scaleoffset=True) # Dataset reports scaleoffset enabled assert dset.scaleoffset is not None # Data round-trips correctly and identically dset[...] = testdata with h5py.File(fname, 'r') as f: readdata = f['foo'][...] self.assertArrayEqual(readdata, testdata) def test_int_with_minbits(self): """ Scaleoffset filter works for integer data with specified precision """ nbits = 12 shape = (100, 300) testdata = np.random.randint(0, 2 ** nbits, size=shape, dtype=np.int64) fname = self.mktemp() with h5py.File(fname, 'w') as f: dset = f.create_dataset('foo', shape, dtype=np.int64, scaleoffset=nbits) # Dataset reports scaleoffset enabled with correct precision self.assertTrue(dset.scaleoffset == 12) # Data round-trips correctly dset[...] = testdata with h5py.File(fname, 'r') as f: readdata = f['foo'][...] self.assertArrayEqual(readdata, testdata) def test_int_with_minbits_lossy(self): """ Scaleoffset filter works for integer data with specified precision """ nbits = 12 shape = (100, 300) testdata = np.random.randint(0, 2 ** (nbits + 1) - 1, size=shape, dtype=np.int64) fname = self.mktemp() with h5py.File(fname, 'w') as f: dset = f.create_dataset('foo', shape, dtype=np.int64, scaleoffset=nbits) # Dataset reports scaleoffset enabled with correct precision self.assertTrue(dset.scaleoffset == 12) # Data can be written and read dset[...] = testdata with h5py.File(fname, 'r') as f: readdata = f['foo'][...] # Compression is lossy assert not (readdata == testdata).all()
TestCreateScaleOffset
python
pytorch__pytorch
torch/_dynamo/variables/higher_order_ops.py
{ "start": 129501, "end": 131113 }
class ____(WrapHigherOrderVariable): def __init__(self, hop, source) -> None: super().__init__(hop, source) def _call_function( self, tx: "InstructionTranslator", args: list[VariableTracker], kwargs: dict[str, VariableTracker], ) -> VariableTracker: func_var = args[0] if isinstance(func_var, torch._dynamo.variables.UserFunctionVariable): func = func_var.fn elif isinstance( func_var, torch._dynamo.variables.functions.FunctoolsPartialVariable ): func = func_var.as_python_constant() else: raise RuntimeError( f"DynamoBypassingWrapperHigherOrderVariable: Unsupported function {type(func_var)}" ) ( p_args, _, example_value, _body_r, gmod, _, body_graph_output_vts, ) = self.create_wrapped_node( tx, args[1], args[2:], kwargs, str(func), ) # Alternatively, we could've stored only the function's fqn and # reconstructed, but that requires the function to be a global. gmod_meta_key = "_dynamo_bypassing_wrapper_fn" gmod.meta[gmod_meta_key] = func return _call_function_with_auto_output_flattening( tx, self.value, (gmod_meta_key,) + tuple(p_args), {}, example_value, _body_r, body_graph_output_vts, )
DynamoBypassingWrapperHigherOrderVariable
python
django__django
tests/forms_tests/tests/test_formsets.py
{ "start": 72027, "end": 72088 }
class ____(FormsetAsTagTests): pass
Jinja2FormsetAsTagTests
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 775897, "end": 776379 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "created_at", "pull_request") actor = sgqlc.types.Field(Actor, graphql_name="actor") created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ) pull_request = sgqlc.types.Field( sgqlc.types.non_null("PullRequest"), graphql_name="pullRequest" )
HeadRefRestoredEvent
python
huggingface__transformers
tests/kernels/test_kernels.py
{ "start": 1499, "end": 8953 }
class ____(TestCasePlus): @classmethod def setUpClass(cls): cls.model_id = "unsloth/Llama-3.2-1B-Instruct" cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_id) cls.model_kernelized = AutoModelForCausalLM.from_pretrained( cls.model_id, use_kernels=True, device_map=torch_device ) cls.model_not_kernelized = AutoModelForCausalLM.from_pretrained( cls.model_id, use_kernels=False, device_map=torch_device ) cls.input = "Hello" @classmethod def tearDownClass(cls): for attr in [ "model_kernelized", "model_not_kernelized", "tokenizer", ]: if hasattr(cls, attr): try: delattr(cls, attr) except Exception: pass # Clear any temporary kernel module cache entries populated by tests try: keys_to_remove = [ k for k, v in list(_KERNEL_MODULE_MAPPING.items()) if v is None or isinstance(v, types.ModuleType) ] for k in keys_to_remove: _KERNEL_MODULE_MAPPING.pop(k, None) except Exception: pass def tearDown(self): # Free accelerator memory/cache and trigger GC cleanup(torch_device, gc_collect=True) @require_torch_accelerator def test_forward(self): tokenized_input = self.tokenizer(self.input, return_tensors="pt").input_ids.to(self.model_kernelized.device) output_ = self.model_kernelized.generate(tokenized_input, max_new_tokens=10, do_sample=False) output = self.tokenizer.decode(output_[0], skip_special_tokens=True) self.EXPECTED_OUTPUT = set() self.EXPECTED_OUTPUT.add("Hello, I'm looking for a reliable and trustworthy online") self.assertTrue(output in self.EXPECTED_OUTPUT) def test_getter_use_kernels(self): self.assertTrue(self.model_kernelized.use_kernels) self.assertFalse(self.model_not_kernelized.use_kernels) def assert_kernelized_forward_is_different(self, kernelized_model, not_kernelized_model): """ Iterate over modules and check if the forward method is different between the kernelized and not kernelized models. Break on first difference, else continue. Finally, assert that at least one forward is different. """ found_difference = False for (name1, module1), (name2, module2) in zip( kernelized_model.named_modules(), not_kernelized_model.named_modules() ): # Only compare modules with the same name if name1 != name2: continue # Check if both modules have a 'forward' attribute if hasattr(module1, "forward") and hasattr(module2, "forward"): # Compare the code objects of the forward methods code1 = getattr(module1.forward, "__code__", None) code2 = getattr(module2.forward, "__code__", None) if code1 is not None and code2 is not None: if code1 is not code2: found_difference = True break self.assertTrue( found_difference, "No module's forward method was different between kernelized and not kernelized models.", ) def assert_kernelized_forward_is_the_same(self, model_1, model_2): """ Iterate over modules and check if the forward method is the same between the kernelized and not kernelized models. Break on first difference, else continue. Finally, assert that at least one forward is the same. """ no_difference = True for (name1, module1), (name2, module2) in zip(model_1.named_modules(), model_2.named_modules()): # Only compare modules with the same name if name1 != name2: continue # Check if both modules have a 'forward' attribute if hasattr(module1, "forward") and hasattr(module2, "forward"): # Compare the code objects of the forward methods code1 = getattr(module1.forward, "__code__", None) code2 = getattr(module2.forward, "__code__", None) if code1 is not None and code2 is not None: if code1 != code2: no_difference = False break self.assertTrue( no_difference, "All module's forward methods were the same between the two models", ) def test_kernelize(self): model = copy.deepcopy(self.model_not_kernelized) kernelize(model, mode=Mode.INFERENCE, device=Device(type=model.device.type)) # type: ignore[arg-type] self.assert_kernelized_forward_is_different(model, self.model_not_kernelized) self.assert_kernelized_forward_is_the_same(model, self.model_kernelized) del model def test_setter_use_kernels(self): model = copy.deepcopy(self.model_not_kernelized) model.use_kernels = True self.assertTrue(model.use_kernels) self.assert_kernelized_forward_is_different(model, self.model_not_kernelized) self.assert_kernelized_forward_is_the_same(model, self.model_kernelized) del model def test_unkernelize(self): model = copy.deepcopy(self.model_kernelized) with self.assertLogs("transformers.modeling_utils", level="WARNING") as cm: model.use_kernels = False self.assertTrue( any( "Disabling kernels at runtime is a no-op as there is no 'unkernelize' routine; keeping current kernels active." in msg for msg in cm.output ) ) self.assertFalse(model.use_kernels) del model def test_kernels_mapping(self): kernel_config = KernelConfig(kernel_mapping={"RMSNorm": "kernels-community/layer_norm:LlamaRMSNorm"}) model = AutoModelForCausalLM.from_pretrained( "unsloth/Llama-3.2-1B-Instruct", use_kernels=True, device_map=torch_device, kernel_config=kernel_config ) EXPECTED_OUTPUT = set() EXPECTED_OUTPUT.add("Hello, I'm looking for a reliable and trustworthy online") tokenized_input = self.tokenizer(self.input, return_tensors="pt").input_ids.to(model.device) output = model.generate(tokenized_input, max_new_tokens=10, do_sample=False) output = self.tokenizer.decode(output[0], skip_special_tokens=True) self.assertTrue(output in EXPECTED_OUTPUT) del model def test_faulty_kernel_mapping_layer_name(self): kernel_config = KernelConfig(kernel_mapping={"RMSNorm1": "kernels-community/layer_norm:LlamaRMSNorm"}) with self.assertRaises(ValueError): _ = AutoModelForCausalLM.from_pretrained( "unsloth/Llama-3.2-1B-Instruct", use_kernels=True, device_map=torch_device, kernel_config=kernel_config ) def test_faulty_kernel_mapping_type(self): kernel_config = KernelConfig(kernel_mapping={"RMSNorm": 1}) with self.assertRaises(ValueError): _ = AutoModelForCausalLM.from_pretrained( "unsloth/Llama-3.2-1B-Instruct", use_kernels=True, device_map=torch_device, kernel_config=kernel_config ) @require_kernels
TestHubKernels
python
wandb__wandb
wandb/automations/_generated/enums.py
{ "start": 149, "end": 239 }
class ____(str, Enum): INFO = "INFO" WARN = "WARN" ERROR = "ERROR"
AlertSeverity
python
spack__spack
lib/spack/spack/environment/depfile.py
{ "start": 1153, "end": 1787 }
class ____: """Contains a spec, a subset of its dependencies, and a flag whether it should be buildcache only/never/auto.""" def __init__( self, target: spack.spec.Spec, prereqs: List[spack.spec.Spec], buildcache: UseBuildCache ): self.target = MakefileSpec(target) self.prereqs = list(MakefileSpec(x) for x in prereqs) if buildcache == UseBuildCache.ONLY: self.buildcache_flag = "--use-buildcache=only" elif buildcache == UseBuildCache.NEVER: self.buildcache_flag = "--use-buildcache=never" else: self.buildcache_flag = ""
DepfileNode
python
scipy__scipy
scipy/stats/tests/test_stats.py
{ "start": 153881, "end": 154284 }
class ____: scalar_testcase = 4. testcase = [1., 2., 3., 4.] testmathworks = [1.165, 0.6268, 0.0751, 0.3516, -0.6965] def test_empty_1d(self, xp): x = xp.asarray([]) with eager_warns(SmallSampleWarning, match=too_small_1d_not_omit, xp=xp): res = self.stat_fun(x) xp_assert_equal(res, xp.asarray(xp.nan)) @make_xp_test_case(stats.skew)
SkewKurtosisTest
python
tensorflow__tensorflow
tensorflow/python/eager/polymorphic_function/function_type_utils.py
{ "start": 6093, "end": 17425 }
class ____(object): """Specification of how to bind arguments to a function. Deprecated. Please use FunctionType instead. """ @classmethod def from_function_and_signature( cls, python_function, input_signature, is_pure=False, jit_compile=None ): """Creates a FunctionSpec instance given a python function and signature. Args: python_function: a function to inspect input_signature: a signature of the function (None, if variable) is_pure: if True all input arguments (including variables and constants) will be converted to tensors and no variable changes allowed. jit_compile: see `tf.function` Returns: instance of FunctionSpec """ function_type, default_values = make_function_type( python_function, input_signature) # Get the function's name. Remove functools.partial wrappers if necessary. while isinstance(python_function, functools.partial): python_function = python_function.func name = getattr(python_function, "__name__", "f") return FunctionSpec( function_type, default_values, is_pure=is_pure, jit_compile=jit_compile, name=name, ) @classmethod def from_fullargspec_and_signature( cls, fullargspec, input_signature, is_pure=False, name=None, jit_compile=None, ): """Construct FunctionSpec from legacy FullArgSpec format.""" function_type, default_values = to_function_type(fullargspec) if input_signature: input_signature = tuple(input_signature) _validate_signature(input_signature) function_type = function_type_lib.add_type_constraints( function_type, input_signature, default_values ) return FunctionSpec( function_type, default_values, is_pure, name, jit_compile ) def __init__( self, function_type, default_values, is_pure=False, name=None, jit_compile=None, ): """Constructs a FunctionSpec describing a python function. Args: function_type: A FunctionType describing the python function signature. default_values: Dictionary mapping parameter names to default values. is_pure: if True all input arguments (including variables and constants) will be converted to tensors and no variable changes allowed. name: Name of the function jit_compile: see `tf.function`. """ self._function_type = function_type self._default_values = default_values self._fullargspec = to_fullargspec(function_type, default_values) self._is_pure = is_pure self._jit_compile = jit_compile # TODO(edloper): Include name when serializing for SavedModel? self._name = name or "f" self._input_signature = to_input_signature(function_type) @property def default_values(self): """Returns dict mapping parameter names to default values.""" return self._default_values @property def function_type(self): """Returns a FunctionType representing the Python function signature.""" return self._function_type @property def fullargspec(self): return self._fullargspec # TODO(fmuham): Replace usages with FunctionType and remove. @property def input_signature(self): return self._input_signature # TODO(fmuham): Replace usages with FunctionType and remove. @property def flat_input_signature(self): return tuple(nest.flatten(self.input_signature, expand_composites=True)) @property def is_pure(self): return self._is_pure @property def jit_compile(self): return self._jit_compile # TODO(fmuham): Replace usages and remove. @property def arg_names(self): return to_arg_names(self.function_type) def signature_summary(self, default_values=False): """Returns a string summarizing this function's signature. Args: default_values: If true, then include default values in the signature. Returns: A `string`. """ summary = f"{self._function_type!r}" if default_values: summary += "\nDefaults:" if self.default_values: for name, value in self.default_values.items(): summary += f"\n {name}: {value!r}" else: summary += "\n None" return summary def make_function_type(python_function, input_signature): """Generates a FunctionType for python_function.""" _validate_signature(input_signature) function_type = function_type_lib.FunctionType.from_callable( python_function ) default_values = function_type_lib.FunctionType.get_default_values( python_function ) if input_signature is not None: input_signature = tuple(input_signature) function_type = function_type_lib.add_type_constraints( function_type, input_signature, default_values ) return function_type, default_values def make_canonicalized_monomorphic_type( args: Any, kwargs: Any, capture_types: Any, polymorphic_type, ) -> Tuple[function_type_lib.FunctionType, trace_type.InternalTracingContext]: """Generates function type given the function arguments.""" kwargs = { function_type_lib.sanitize_arg_name(name): value for name, value in kwargs.items() } function_type, type_context = ( function_type_lib.canonicalize_to_monomorphic( args, kwargs, {}, capture_types, polymorphic_type ) ) return function_type, type_context def canonicalize_function_inputs( args, kwargs, function_type, default_values=None, is_pure=False ): """Canonicalizes `args` and `kwargs`. Canonicalize the inputs to the Python function using FunctionType. In particular, we parse the varargs and kwargs that the original function was called with into a tuple corresponding to the Python function's positional (named) arguments and a dictionary corresponding to its kwargs. Missing default arguments are added. If the FunctionType has an type constraints, then they are used to convert arguments to tensors; otherwise, any inputs containing numpy arrays are converted to tensors. Args: args: The varargs this object was called with. kwargs: The keyword args this function was called with. function_type: FunctionType to canonicalize against. default_values: Default values to use. is_pure: Force variable inputs to Tensors. Returns: A canonicalized ordering of the inputs, as well as full and filtered (Tensors and Variables only) versions of their concatenated flattened representations, represented by a tuple in the form (args, kwargs, flat_args, filtered_flat_args). Here: `args` is a full list of bound arguments, and `kwargs` contains only true keyword arguments, as opposed to named arguments called in a keyword-like fashion. Raises: ValueError: If a keyword in `kwargs` cannot be matched with a positional argument when an input signature is specified, or when the inputs do not conform to the input signature. """ default_values = {} if not default_values else default_values if is_pure: args, kwargs = _convert_variables_to_tensors(args, kwargs) bound_arguments = bind_function_inputs( args, kwargs, function_type, default_values ) return bound_arguments def bind_function_inputs(args, kwargs, function_type, default_values): """Bind `args` and `kwargs` into a canonicalized signature args, kwargs.""" sanitized_kwargs = { function_type_lib.sanitize_arg_name(k): v for k, v in kwargs.items() } if len(kwargs) != len(sanitized_kwargs): raise ValueError( "Name collision after sanitization. Please rename " "tf.function input parameters. Original: " f"{sorted(kwargs.keys())}, Sanitized: " f"{sorted(sanitized_kwargs.keys())}" ) try: bound_arguments = function_type.bind_with_defaults( args, sanitized_kwargs, default_values ) except Exception as e: raise TypeError( f"Binding inputs to tf.function failed due to `{e}`. " f"Received args: {args} and kwargs: {sanitized_kwargs} for signature:" f" {function_type}." ) from e return bound_arguments def _validate_signature(signature): """Checks the input_signature to be valid.""" if signature is None: return if not isinstance(signature, (tuple, list)): raise TypeError( "input_signature must be either a tuple or a list, got " f"{type(signature)}." ) # TODO(xjun): Allow VariableSpec once we figure out API for de-aliasing. variable_specs = _get_variable_specs(signature) if variable_specs: raise TypeError( f"input_signature doesn't support VariableSpec, got {variable_specs}" ) if any( not isinstance(arg, tensor.TensorSpec) for arg in nest.flatten(signature, expand_composites=True) ): bad_args = [ arg for arg in nest.flatten(signature, expand_composites=True) if not isinstance(arg, tensor.TensorSpec) ] raise TypeError( "input_signature must be a possibly nested sequence of " f"TensorSpec objects, got invalid args {bad_args} with " f"types {list(six.moves.map(type, bad_args))}." ) def _to_tensor_or_tensor_spec(x): return ( x if isinstance(x, (tensor.Tensor, tensor.TensorSpec)) else ops.convert_to_tensor(x) ) def _convert_variables_to_tensors(args, kwargs): args = [_to_tensor_or_tensor_spec(x) for x in args] kwargs = {kw: _to_tensor_or_tensor_spec(x) for kw, x in kwargs.items()} return tuple(args), kwargs def _get_variable_specs(args): """Returns `VariableSpecs` from `args`.""" variable_specs = [] for arg in nest.flatten(args): if not isinstance(arg, type_spec.TypeSpec): continue if isinstance(arg, resource_variable_ops.VariableSpec): variable_specs.append(arg) elif not isinstance(arg, tensor.TensorSpec): # arg is a CompositeTensor spec. variable_specs.extend(_get_variable_specs(arg._component_specs)) # pylint: disable=protected-access return variable_specs def derive_from_graph(func_graph): """Derives a FunctionType from FuncGraph.""" # TODO(fmuham): Include structure info from structured_inputs input_signature = ( tuple(trace_type.from_value(i) for i in func_graph.inputs), {}, ) # TODO(fmuham): Include output structure info from structured_outputs output_signature = tuple(trace_type.from_value(o) for o in func_graph.outputs) return function_type_lib.from_structured_signature( input_signature, output_signature, func_graph.function_captures.capture_types, ) # TODO(fmuham): Replace usages with TraceType and remove. def is_same_structure(structure1, structure2, check_values=False): """Check two structures for equality, optionally of types and of values.""" try: nest.assert_same_structure(structure1, structure2, expand_composites=True) except (ValueError, TypeError): return False if check_values: flattened1 = nest.flatten(structure1, expand_composites=True) flattened2 = nest.flatten(structure2, expand_composites=True) # First check the types to avoid AttributeErrors. if any(type(f1) is not type(f2) for f1, f2 in zip(flattened1, flattened2)): return False return flattened1 == flattened2 return True
FunctionSpec
python
huggingface__transformers
src/transformers/pipelines/pt_utils.py
{ "start": 129, "end": 502 }
class ____(Dataset): def __init__(self, dataset, process, params): self.dataset = dataset self.process = process self.params = params def __len__(self): return len(self.dataset) def __getitem__(self, i): item = self.dataset[i] processed = self.process(item, **self.params) return processed
PipelineDataset
python
getsentry__sentry
src/sentry/integrations/msteams/actions/form.py
{ "start": 377, "end": 1961 }
class ____(forms.Form): team = forms.ChoiceField(choices=(), widget=forms.Select()) channel = forms.CharField(widget=forms.TextInput()) channel_id = forms.HiddenInput() def __init__(self, *args, **kwargs): self._team_list = [(i.id, i.name) for i in kwargs.pop("integrations")] super().__init__(*args, **kwargs) if self._team_list: self.fields["team"].initial = self._team_list[0][0] set_field_choices(self.fields["team"], self._team_list) def clean(self) -> dict[str, Any] | None: cleaned_data = super().clean() if cleaned_data is None: return None integration_id = cleaned_data.get("team") channel = cleaned_data.get("channel", "") integration = integration_service.get_integration( integration_id=integration_id, status=ObjectStatus.ACTIVE ) if not integration: raise forms.ValidationError(_("Team is a required field."), code="invalid") channel_id = find_channel_id(integration, channel) if channel_id is None and integration_id is not None: params = { "channel": channel, "team": dict(self._team_list).get(int(integration_id)), } raise forms.ValidationError( _('The channel or user "%(channel)s" could not be found in the %(team)s Team.'), code="invalid", params=params, ) cleaned_data["channel_id"] = channel_id return cleaned_data
MsTeamsNotifyServiceForm
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0067_change_max_length_feature_id.py
{ "start": 149, "end": 542 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0066_make_imported_file_slug_nullable"), ] operations = [ migrations.AlterField( model_name="feature", name="feature_id", field=models.CharField(max_length=255, unique=True, verbose_name="Feature identifier"), ), ]
Migration
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/operands.py
{ "start": 4241, "end": 4642 }
class ____(SubsetAutomationCondition): @property def name(self) -> str: return "run_in_progress" async def compute_subset(self, context: AutomationContext) -> EntitySubset: # pyright: ignore[reportIncompatibleMethodOverride] return await context.asset_graph_view.compute_run_in_progress_subset(key=context.key) @whitelist_for_serdes @record
RunInProgressAutomationCondition
python
getsentry__sentry
tests/sentry/lang/dart/test_plugin_logic.py
{ "start": 129, "end": 5686 }
class ____(TestCase): def setUp(self) -> None: self.plugin = DartPlugin() self.data = { "project": self.project.id, "sdk": {"name": "sentry.dart.flutter"}, "debug_meta": {"images": [{"debug_id": "b8e43a-f242-3d73-a453-aeb6a777ef75"}]}, "exception": { "values": [ { "type": "xyz", "value": "Error: something bad happened with xyz", } ] }, "stacktrace": { "frames": [ { "abs_path": "package:myapp/main.dart", "filename": "main.dart", "platform": "native", } ] }, } def test_can_configure_for_project(self) -> None: """Test that the plugin cannot be configured for projects.""" assert not self.plugin.can_configure_for_project(self.project) def test_get_event_preprocessors_no_dart_sdk(self) -> None: """Test that no preprocessors are returned for non-Dart SDKs.""" data = {**self.data, "sdk": {"name": "sentry.python"}} preprocessors = self.plugin.get_event_preprocessors(data) assert len(preprocessors) == 0 def test_get_event_preprocessors_no_debug_images(self) -> None: """Test that no preprocessors are returned when there are no debug images.""" data = {**self.data} del data["debug_meta"] preprocessors = self.plugin.get_event_preprocessors(data) assert len(preprocessors) == 0 def test_get_event_preprocessors_no_native_frames(self) -> None: """Test that no preprocessors are returned when there are no native frames.""" # Remove native platform from frames data = {**self.data} data["stacktrace"]["frames"][0]["platform"] = "dart" preprocessors = self.plugin.get_event_preprocessors(data) assert len(preprocessors) == 0 def test_get_event_preprocessors_with_dart_flutter_native_frames(self) -> None: """Test that deobfuscate_exception_type is returned for Dart/Flutter events with native frames.""" # Add native frames to trigger deobfuscation data = { "project": self.project.id, "sdk": {"name": "sentry.dart.flutter"}, "debug_meta": {"images": [{"debug_id": "b8e43a-f242-3d73-a453-aeb6a777ef75"}]}, "exception": { "values": [ { "type": "xyz", "value": "Error: something bad happened", "stacktrace": { "frames": [ { "abs_path": "package:myapp/main.dart", "filename": "main.dart", "platform": "native", # This is what triggers deobfuscation } ] }, } ] }, } preprocessors = self.plugin.get_event_preprocessors(data) assert len(preprocessors) == 1 # Verify the preprocessor is deobfuscate_exception_type from sentry.lang.dart.utils import deobfuscate_exception_type assert preprocessors[0] == deobfuscate_exception_type def test_get_event_preprocessors_dart_sdk(self) -> None: """Test that preprocessors work for sentry.dart SDK (not just flutter).""" data = { **self.data, "sdk": {"name": "sentry.dart"}, "exception": { "values": [ { "type": "xyz", "value": "Error", "stacktrace": {"frames": [{"platform": "native"}]}, } ] }, } preprocessors = self.plugin.get_event_preprocessors(data) assert len(preprocessors) == 1 def test_get_event_preprocessors_multiple_stacktraces(self) -> None: """Test that preprocessors are returned when native frames exist in any stacktrace.""" data = { "project": self.project.id, "sdk": {"name": "sentry.dart.flutter"}, "debug_meta": {"images": [{"debug_id": "b8e43a-f242-3d73-a453-aeb6a777ef75"}]}, "stacktrace": { "frames": [ {"platform": "dart"}, # Non-native frame ] }, "exception": { "values": [ { "type": "xyz", "value": "Error", "stacktrace": { "frames": [ {"platform": "dart"}, # Non-native frame ] }, }, { "type": "abc", "value": "Another error", "stacktrace": { "frames": [ {"platform": "native"}, # Native frame - should trigger ] }, }, ] }, } preprocessors = self.plugin.get_event_preprocessors(data) assert len(preprocessors) == 1
DartPluginTest
python
numba__numba
numba/cuda/tests/cudapy/test_gufunc_scalar.py
{ "start": 366, "end": 5382 }
class ____(CUDATestCase): def test_gufunc_scalar_output(self): # function type: # - has no void return type # - array argument is one dimension fewer than the source array # - scalar output is passed as a 1-element array. # # signature: (n)->() # - the function takes an array of n-element and output a scalar. @guvectorize(['void(int32[:], int32[:])'], '(n)->()', target='cuda') def sum_row(inp, out): tmp = 0. for i in range(inp.shape[0]): tmp += inp[i] out[0] = tmp # inp is (10000, 3) # out is (10000) # The outer (leftmost) dimension must match or numpy broadcasting # is performed. But, broadcasting on CUDA arrays is not supported. inp = np.arange(300, dtype=np.int32).reshape(100, 3) # invoke on CUDA with manually managed memory out1 = np.empty(100, dtype=inp.dtype) out2 = np.empty(100, dtype=inp.dtype) dev_inp = cuda.to_device( inp) # alloc and copy input data dev_out1 = cuda.to_device(out1, copy=False) # alloc only sum_row(dev_inp, out=dev_out1) # invoke the gufunc dev_out2 = sum_row(dev_inp) # invoke the gufunc dev_out1.copy_to_host(out1) # retrieve the result dev_out2.copy_to_host(out2) # retrieve the result # verify result for i in range(inp.shape[0]): self.assertTrue(out1[i] == inp[i].sum()) self.assertTrue(out2[i] == inp[i].sum()) def test_gufunc_scalar_output_bug(self): # Issue 2812: Error due to using input argument types as output argument @guvectorize(['void(int32, int32[:])'], '()->()', target='cuda') def twice(inp, out): out[0] = inp * 2 self.assertEqual(twice(10), 20) arg = np.arange(10).astype(np.int32) self.assertPreciseEqual(twice(arg), arg * 2) def test_gufunc_scalar_input_saxpy(self): @guvectorize(['void(float32, float32[:], float32[:], float32[:])'], '(),(t),(t)->(t)', target='cuda') def saxpy(a, x, y, out): for i in range(out.shape[0]): out[i] = a * x[i] + y[i] A = np.float32(2) X = np.arange(10, dtype=np.float32).reshape(5, 2) Y = np.arange(10, dtype=np.float32).reshape(5, 2) out = saxpy(A, X, Y) for j in range(5): for i in range(2): exp = A * X[j, i] + Y[j, i] self.assertTrue(exp == out[j, i]) X = np.arange(10, dtype=np.float32) Y = np.arange(10, dtype=np.float32) out = saxpy(A, X, Y) for j in range(10): exp = A * X[j] + Y[j] self.assertTrue(exp == out[j], (exp, out[j])) A = np.arange(5, dtype=np.float32) X = np.arange(10, dtype=np.float32).reshape(5, 2) Y = np.arange(10, dtype=np.float32).reshape(5, 2) out = saxpy(A, X, Y) for j in range(5): for i in range(2): exp = A[j] * X[j, i] + Y[j, i] self.assertTrue(exp == out[j, i], (exp, out[j, i])) def test_gufunc_scalar_cast(self): @guvectorize(['void(int32, int32[:], int32[:])'], '(),(t)->(t)', target='cuda') def foo(a, b, out): for i in range(b.size): out[i] = a * b[i] a = np.int64(2) # type does not match signature (int32) b = np.arange(10).astype(np.int32) out = foo(a, b) np.testing.assert_equal(out, a * b) # test error a = np.array(a) da = cuda.to_device(a) self.assertEqual(da.dtype, np.int64) with self.assertRaises(TypeError) as raises: foo(da, b) self.assertIn("does not support .astype()", str(raises.exception)) def test_gufunc_old_style_scalar_as_array(self): # Example from issue #2579 @guvectorize(['void(int32[:],int32[:],int32[:])'], '(n),()->(n)', target='cuda') def gufunc(x, y, res): for i in range(x.shape[0]): res[i] = x[i] + y[0] # Case 1 a = np.array([1, 2, 3, 4], dtype=np.int32) b = np.array([2], dtype=np.int32) res = np.zeros(4, dtype=np.int32) expected = res.copy() expected = a + b gufunc(a, b, out=res) np.testing.assert_almost_equal(expected, res) # Case 2 a = np.array([1, 2, 3, 4] * 2, dtype=np.int32).reshape(2, 4) b = np.array([2, 10], dtype=np.int32) res = np.zeros((2, 4), dtype=np.int32) expected = res.copy() expected[0] = a[0] + b[0] expected[1] = a[1] + b[1] gufunc(a, b, res) np.testing.assert_almost_equal(expected, res) if __name__ == '__main__': unittest.main()
TestGUFuncScalar
python
sympy__sympy
sympy/codegen/ast.py
{ "start": 36289, "end": 36530 }
class ____(_SizedIntType): """ Represents a signed integer type. """ __slots__ = () @property def min(self): return -2**(self.nbits-1) @property def max(self): return 2**(self.nbits-1) - 1
SignedIntType
python
numpy__numpy
numpy/distutils/fcompiler/none.py
{ "start": 129, "end": 758 }
class ____(FCompiler): compiler_type = 'none' description = 'Fake Fortran compiler' executables = {'compiler_f77': None, 'compiler_f90': None, 'compiler_fix': None, 'linker_so': None, 'linker_exe': None, 'archiver': None, 'ranlib': None, 'version_cmd': None, } def find_executables(self): pass if __name__ == '__main__': from distutils import log log.set_verbosity(2) print(customized_fcompiler(compiler='none').get_version())
NoneFCompiler
python
django__django
tests/gis_tests/gdal_tests/test_srs.py
{ "start": 8393, "end": 15785 }
class ____(SimpleTestCase): def test01_wkt(self): "Testing initialization on valid OGC WKT." for s in srlist: SpatialReference(s.wkt) def test02_bad_wkt(self): "Testing initialization on invalid WKT." for bad in bad_srlist: try: srs = SpatialReference(bad) srs.validate() except (SRSException, GDALException): pass else: self.fail('Should not have initialized on bad WKT "%s"!') def test03_get_wkt(self): "Testing getting the WKT." for s in srlist: srs = SpatialReference(s.wkt) # GDAL 3 strips UNIT part in the last occurrence. self.assertEqual( s.wkt.replace(',UNIT["Meter",1]', ""), srs.wkt.replace(',UNIT["Meter",1]', ""), ) def test04_proj(self): """PROJ import and export.""" proj_parts = [ "+proj=longlat", "+ellps=WGS84", "+towgs84=0,0,0,0,0,0,0", "+datum=WGS84", "+no_defs", ] srs1 = SpatialReference(srlist[0].wkt) srs2 = SpatialReference("+proj=longlat +datum=WGS84 +no_defs") self.assertTrue(all(part in proj_parts for part in srs1.proj.split())) self.assertTrue(all(part in proj_parts for part in srs2.proj.split())) def test05_epsg(self): "Test EPSG import." for s in srlist: if s.epsg: srs1 = SpatialReference(s.wkt) srs2 = SpatialReference(s.epsg) srs3 = SpatialReference(str(s.epsg)) srs4 = SpatialReference("EPSG:%d" % s.epsg) for srs in (srs1, srs2, srs3, srs4): for attr, expected in s.attr: self.assertEqual(expected, srs[attr]) def test07_boolean_props(self): "Testing the boolean properties." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.projected, srs.projected) self.assertEqual(s.geographic, srs.geographic) def test08_angular_linear(self): "Testing the linear and angular units routines." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.ang_name, srs.angular_name) self.assertEqual(s.lin_name, srs.linear_name) self.assertAlmostEqual(s.ang_units, srs.angular_units, 9) self.assertAlmostEqual(s.lin_units, srs.linear_units, 9) def test09_authority(self): "Testing the authority name & code routines." for s in srlist: if hasattr(s, "auth"): srs = SpatialReference(s.wkt) for target, tup in s.auth.items(): self.assertEqual(tup[0], srs.auth_name(target)) self.assertEqual(tup[1], srs.auth_code(target)) def test10_attributes(self): "Testing the attribute retrieval routines." for s in srlist: srs = SpatialReference(s.wkt) for tup in s.attr: att = tup[0] # Attribute to test exp = tup[1] # Expected result self.assertEqual(exp, srs[att]) def test11_wellknown(self): "Testing Well Known Names of Spatial References." for s in well_known: srs = SpatialReference(s.wk) self.assertEqual(s.name, srs.name) for tup in s.attrs: if len(tup) == 2: key = tup[0] exp = tup[1] elif len(tup) == 3: key = tup[:2] exp = tup[2] self.assertEqual(srs[key], exp) def test12_coordtransform(self): "Testing initialization of a CoordTransform." target = SpatialReference("WGS84") CoordTransform(SpatialReference(srlist[0].wkt), target) def test13_attr_value(self): "Testing the attr_value() method." s1 = SpatialReference("WGS84") with self.assertRaises(TypeError): s1.__getitem__(0) with self.assertRaises(TypeError): s1.__getitem__(("GEOGCS", "foo")) self.assertEqual("WGS 84", s1["GEOGCS"]) self.assertEqual("WGS_1984", s1["DATUM"]) self.assertEqual("EPSG", s1["AUTHORITY"]) self.assertEqual(4326, int(s1["AUTHORITY", 1])) self.assertIsNone(s1["FOOBAR"]) def test_unicode(self): wkt = ( 'PROJCS["DHDN / Soldner 39 Langschoß",' 'GEOGCS["DHDN",DATUM["Deutsches_Hauptdreiecksnetz",' 'SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],' 'AUTHORITY["EPSG","6314"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4314"]],PROJECTION["Cassini_Soldner"],' 'PARAMETER["latitude_of_origin",50.66738711],' 'PARAMETER["central_meridian",6.28935703],' 'PARAMETER["false_easting",0],PARAMETER["false_northing",0],' 'UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",NORTH],AXIS["Y",EAST],' 'AUTHORITY["mj10777.de","187939"]]' ) srs = SpatialReference(wkt) srs_list = [srs, srs.clone()] srs.import_wkt(wkt) for srs in srs_list: self.assertEqual(srs.name, "DHDN / Soldner 39 Langschoß") self.assertEqual(srs.wkt, wkt) self.assertIn("Langschoß", srs.pretty_wkt) if GDAL_VERSION < (3, 9): self.assertIn("Langschoß", srs.xml) def test_axis_order(self): wgs84_trad = SpatialReference(4326, axis_order=AxisOrder.TRADITIONAL) wgs84_auth = SpatialReference(4326, axis_order=AxisOrder.AUTHORITY) # Coordinate interpretation may depend on the srs axis predicate. pt = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774) pt_trad = pt.transform(wgs84_trad, clone=True) self.assertAlmostEqual(pt_trad.x, -104.609, 3) self.assertAlmostEqual(pt_trad.y, 38.255, 3) pt_auth = pt.transform(wgs84_auth, clone=True) self.assertAlmostEqual(pt_auth.x, 38.255, 3) self.assertAlmostEqual(pt_auth.y, -104.609, 3) # clone() preserves the axis order. pt_auth = pt.transform(wgs84_auth.clone(), clone=True) self.assertAlmostEqual(pt_auth.x, 38.255, 3) self.assertAlmostEqual(pt_auth.y, -104.609, 3) def test_axis_order_invalid(self): msg = "SpatialReference.axis_order must be an AxisOrder instance." with self.assertRaisesMessage(ValueError, msg): SpatialReference(4326, axis_order="other") def test_esri(self): srs = SpatialReference("NAD83") pre_esri_wkt = srs.wkt srs.to_esri() self.assertNotEqual(srs.wkt, pre_esri_wkt) self.assertIn('DATUM["D_North_American_1983"', srs.wkt) srs.from_esri() self.assertIn('DATUM["North_American_Datum_1983"', srs.wkt) def test_srid(self): """The srid property returns top-level authority code.""" for s in srlist: if hasattr(s, "epsg"): srs = SpatialReference(s.wkt) self.assertEqual(srs.srid, s.epsg)
SpatialRefTest
python
google__jax
jax/experimental/mosaic/gpu/utils.py
{ "start": 31306, "end": 35827 }
class ____: base_address: ir.Value offset: ir.Value phases: ir.Value num_barriers: int @staticmethod def initialize( barrier_memref: ir.Value, arrival_count: int = 1 ) -> "BarrierRef": barrier_ty = ir.MemRefType(barrier_memref.type) [num_barriers] = barrier_ty.shape if num_barriers > 32: raise NotImplementedError("Only up to 32 barriers per group supported") i32 = ir.IntegerType.get_signless(32) i64 = ir.IntegerType.get_signless(64) address = memref_ptr( barrier_memref, memory_space=WORKGROUP_NVPTX_ADDRESS_SPACE ) phases = memref.alloca(ir.MemRefType.get((), i32), [], []) memref.store(c(0, i32), phases, []) with single_thread(scope=ThreadSubset.BLOCK): for i in range(num_barriers): nvvm.mbarrier_init( getelementptr(address, [i], i64), c(arrival_count, i32), ) return BarrierRef(address, c(0, i32), phases, num_barriers) def __iter__(self) -> Iterator["BarrierRef"]: if self.num_barriers == 1: yield self else: for offset in range(self.num_barriers): yield self[offset] def __getitem__(self, offset: ir.Value | int) -> "BarrierRef": i32 = ir.IntegerType.get_signless(32) if isinstance(offset, int): if offset >= self.num_barriers: raise IndexError(f"Barrier offset {offset} is out of bounds") offset = c(offset, i32) elif ir.IndexType.isinstance(offset.type): offset = arith.index_castui(i32, offset) elif offset.type != i32: raise ValueError(f"Expected a dynamic index or an integer, got {offset}") return BarrierRef( self.base_address, arith.addi(self.offset, offset), self.phases, 1, ) def wait_parity(self, parity, orders_tensor_core=False): i32 = ir.IntegerType.get_signless(32) ticks = arith.constant(i32, 10000000) parity = arith.extui(i32, parity) nvvm.mbarrier_try_wait_parity(self.get_ptr(), parity, ticks) if orders_tensor_core: llvm.inline_asm( ir.Type.parse("!llvm.void"), [], "tcgen05.fence::after_thread_sync;", "", has_side_effects=True, ) def wait(self, orders_tensor_core: bool = False): parities = memref.load(self.phases, []) parity, new_parities = self.update_parities(parities) memref.store(new_parities, self.phases, []) self.wait_parity(parity, orders_tensor_core) def update_parities(self, parities: ir.Value) -> tuple[ir.Value, ir.Value]: i32 = ir.IntegerType.get_signless(32) bitmask = arith.shli(c(1, i32), self.offset) parity = arith.cmpi( arith.CmpIPredicate.ne, arith.andi(parities, bitmask), c(0, i32) ) return parity, arith.xori(parities, bitmask) def arrive( self, arrival_count: int = 1, can_complete: bool = True, orders_tensor_core: bool = False, predicate: ir.Value | None = None, ): i64 = ir.IntegerType.get_signless(64) if orders_tensor_core: llvm.inline_asm( ir.Type.parse("!llvm.void"), [], "tcgen05.fence::before_thread_sync;", "", has_side_effects=True, ) if can_complete: pred_ptx = pred_constraint = "" if predicate is not None: pred_ptx = "@$2" pred_constraint = ",b" llvm.inline_asm( ir.IntegerType.get_signless(64), [self.get_ptr()] + ([predicate] if predicate is not None else []), f"{pred_ptx} mbarrier.arrive.release.cta.shared::cta.b64 $0, [$1]," f" {arrival_count};", "=l,r" + pred_constraint, has_side_effects=True, ) else: if predicate is not None: raise NotImplementedError( "Predicate not supported for no-complete arrive" ) count = c(arrival_count, ir.IntegerType.get_signless(32)) nvvm.mbarrier_arrive_nocomplete(i64, self.get_ptr(), count) def arrive_expect_tx( self, bytes: int | ir.Value, predicate: ir.Value | None = None ): if isinstance(bytes, int): bytes = c(bytes, ir.IntegerType.get_signless(32)) elif ir.IndexType.isinstance(bytes.type): i32 = ir.IntegerType.get_signless(32) bytes = arith.index_cast(i32, bytes) nvvm.mbarrier_arrive_expect_tx(self.get_ptr(), bytes, predicate=predicate) def get_ptr(self): i64 = ir.IntegerType.get_signless(64) return getelementptr(self.base_address, [self.offset], i64) @dataclasses.dataclass(frozen=True)
BarrierRef
python
getsentry__sentry
src/sentry/web/frontend/analytics.py
{ "start": 79, "end": 337 }
class ____(analytics.Event): organization_id: int project_id: int is_lazy: bool has_performance: bool has_replay: bool has_debug: bool sdk_version: str | None tmpl: str analytics.register(JsSdkLoaderRendered)
JsSdkLoaderRendered
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_redirects.py
{ "start": 416, "end": 3386 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.pip = Project.objects.create( **{ "repo_type": "git", "name": "Pip", "default_branch": "", "project_url": "http://pip.rtfd.org", "repo": "https://github.com/fail/sauce", "default_version": LATEST, "privacy_level": "public", "description": "wat", "documentation_type": "sphinx", } ) Redirect.objects.create( project=cls.pip, redirect_type="page", from_url="/install.html", to_url="/install.html#custom-fragment", ) def test_redirect_fragment(self): redirect = Redirect.objects.get(project=self.pip) path = redirect.get_redirect_path("/install.html") expected_path = "/en/latest/install.html#custom-fragment" self.assertEqual(path, expected_path) def test_redirects_order(self): self.pip.redirects.all().delete() redirect_a = get( Redirect, project=self.pip, from_url="/a/", to_url="/z/", redirect_type=EXACT_REDIRECT, ) redirect_b = get( Redirect, project=self.pip, from_url="/b/", to_url="/z/", redirect_type=EXACT_REDIRECT, ) redirect_c = get( Redirect, project=self.pip, from_url="/c/", to_url="/z/", redirect_type=EXACT_REDIRECT, ) def _refresh(): redirect_a.refresh_from_db() redirect_b.refresh_from_db() redirect_c.refresh_from_db() _refresh() self.assertEqual(self.pip.redirects.count(), 3) self.assertEqual(redirect_c.position, 0) self.assertEqual(redirect_b.position, 1) self.assertEqual(redirect_a.position, 2) # Move redirect to the top redirect_a.position = 0 redirect_a.save() _refresh() self.assertEqual(redirect_a.position, 0) self.assertEqual(redirect_c.position, 1) self.assertEqual(redirect_b.position, 2) # Move redirect to the bottom redirect_c.position = 5 redirect_c.save() _refresh() self.assertEqual(redirect_a.position, 0) self.assertEqual(redirect_b.position, 1) self.assertEqual(redirect_c.position, 2) # Delete redirect redirect_a.delete() redirect_b.refresh_from_db() redirect_c.refresh_from_db() self.assertEqual(redirect_b.position, 0) self.assertEqual(redirect_c.position, 1) redirect_c.delete() redirect_b.refresh_from_db() self.assertEqual(redirect_b.position, 0) redirect_b.delete() @override_settings(PUBLIC_DOMAIN="readthedocs.org")
CustomRedirectTests
python
geekcomputers__Python
turtle_shapes_made.py
{ "start": 16, "end": 1269 }
class ____: def __init__(self, color, pensize): self.turtle = turtle.Turtle() self.turtle.color(color) self.turtle.pensize(pensize) def draw_rectangle(self, width, height): for _ in range(2): self.turtle.forward(width) self.turtle.left(90) self.turtle.forward(height) self.turtle.left(90) def draw_triangle(self, length): for _ in range(3): self.turtle.forward(length) self.turtle.left(120) def main(): scrn = turtle.Screen() scrn.bgcolor("lavender") # Draw Rectangle rectangle_drawer = ShapeDrawer("blue", 3) rectangle_drawer.draw_rectangle(180, 75) # Draw Triangle triangle_drawer = ShapeDrawer("hot pink", 4) triangle_drawer.turtle.penup() triangle_drawer.turtle.goto(-90, -75) triangle_drawer.turtle.pendown() triangle_drawer.draw_triangle(100) # Add more drawings as needed # ... # Example: Draw a circle circle_drawer = ShapeDrawer("green", 2) circle_drawer.turtle.penup() circle_drawer.turtle.goto(0, 0) circle_drawer.turtle.pendown() circle_drawer.turtle.circle(50) scrn.exitonclick() if __name__ == "__main__": main()
ShapeDrawer
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constrainedTypeVar13.py
{ "start": 595, "end": 884 }
class ____: ... _T3 = TypeVar("_T3", A, B, C) _P = ParamSpec("_P") _Ts = TypeVarTuple("_Ts") def func1(val1: _T1) -> _T1: if isinstance(val1, str): return "" return 0 def func2(val1: _T1) -> list[_T1]: if isinstance(val1, str): return [""] return [0]
C
python
encode__django-rest-framework
tests/test_pagination.py
{ "start": 22912, "end": 36098 }
class ____: def test_invalid_cursor(self): request = Request(factory.get('/', {'cursor': '123'})) with pytest.raises(exceptions.NotFound): self.pagination.paginate_queryset(self.queryset, request) def test_use_with_ordering_filter(self): class MockView: filter_backends = (filters.OrderingFilter,) ordering_fields = ['username', 'created'] ordering = 'created' request = Request(factory.get('/', {'ordering': 'username'})) ordering = self.pagination.get_ordering(request, [], MockView()) assert ordering == ('username',) request = Request(factory.get('/', {'ordering': '-username'})) ordering = self.pagination.get_ordering(request, [], MockView()) assert ordering == ('-username',) request = Request(factory.get('/', {'ordering': 'invalid'})) ordering = self.pagination.get_ordering(request, [], MockView()) assert ordering == ('created',) def test_use_with_ordering_filter_without_ordering_default_value(self): class MockView: filter_backends = (filters.OrderingFilter,) ordering_fields = ['username', 'created'] request = Request(factory.get('/')) ordering = self.pagination.get_ordering(request, [], MockView()) # it gets the value of `ordering` provided by CursorPagination assert ordering == ('created',) request = Request(factory.get('/', {'ordering': 'username'})) ordering = self.pagination.get_ordering(request, [], MockView()) assert ordering == ('username',) request = Request(factory.get('/', {'ordering': 'invalid'})) ordering = self.pagination.get_ordering(request, [], MockView()) assert ordering == ('created',) def test_cursor_pagination(self): (previous, current, next, previous_url, next_url) = self.get_pages('/') assert previous is None assert current == [1, 1, 1, 1, 1] assert next == [1, 2, 3, 4, 4] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [1, 1, 1, 1, 1] assert current == [1, 2, 3, 4, 4] assert next == [4, 4, 5, 6, 7] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [1, 2, 3, 4, 4] assert current == [4, 4, 5, 6, 7] assert next == [7, 7, 7, 7, 7] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [4, 4, 4, 5, 6] # Paging artifact assert current == [7, 7, 7, 7, 7] assert next == [7, 7, 7, 8, 9] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [7, 7, 7, 7, 7] assert current == [7, 7, 7, 8, 9] assert next == [9, 9, 9, 9, 9] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [7, 7, 7, 8, 9] assert current == [9, 9, 9, 9, 9] assert next is None (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [7, 7, 7, 7, 7] assert current == [7, 7, 7, 8, 9] assert next == [9, 9, 9, 9, 9] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [4, 4, 5, 6, 7] assert current == [7, 7, 7, 7, 7] assert next == [8, 9, 9, 9, 9] # Paging artifact (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [1, 2, 3, 4, 4] assert current == [4, 4, 5, 6, 7] assert next == [7, 7, 7, 7, 7] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [1, 1, 1, 1, 1] assert current == [1, 2, 3, 4, 4] assert next == [4, 4, 5, 6, 7] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous is None assert current == [1, 1, 1, 1, 1] assert next == [1, 2, 3, 4, 4] assert isinstance(self.pagination.to_html(), str) def test_cursor_pagination_current_page_empty_forward(self): # Regression test for #6504 self.pagination.base_url = "/" # We have a cursor on the element at position 100, but this element doesn't exist # anymore. cursor = pagination.Cursor(reverse=False, offset=0, position=100) url = self.pagination.encode_cursor(cursor) self.pagination.base_url = "/" # Loading the page with this cursor doesn't crash (previous, current, next, previous_url, next_url) = self.get_pages(url) # The previous url doesn't crash either (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) # And point to things that are not completely off. assert previous == [7, 7, 7, 8, 9] assert current == [9, 9, 9, 9, 9] assert next == [] assert previous_url is not None assert next_url is not None def test_cursor_pagination_current_page_empty_reverse(self): # Regression test for #6504 self.pagination.base_url = "/" # We have a cursor on the element at position 100, but this element doesn't exist # anymore. cursor = pagination.Cursor(reverse=True, offset=0, position=100) url = self.pagination.encode_cursor(cursor) self.pagination.base_url = "/" # Loading the page with this cursor doesn't crash (previous, current, next, previous_url, next_url) = self.get_pages(url) # The previous url doesn't crash either (previous, current, next, previous_url, next_url) = self.get_pages(next_url) # And point to things that are not completely off. assert previous == [7, 7, 7, 7, 8] assert current == [] assert next is None assert previous_url is not None assert next_url is None def test_cursor_pagination_with_page_size(self): (previous, current, next, previous_url, next_url) = self.get_pages('/?page_size=20') assert previous is None assert current == [1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 7, 7, 7, 7] assert next == [7, 7, 7, 8, 9, 9, 9, 9, 9, 9] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 7, 7, 7, 7] assert current == [7, 7, 7, 8, 9, 9, 9, 9, 9, 9] assert next is None def test_cursor_pagination_with_page_size_over_limit(self): (previous, current, next, previous_url, next_url) = self.get_pages('/?page_size=30') assert previous is None assert current == [1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 7, 7, 7, 7] assert next == [7, 7, 7, 8, 9, 9, 9, 9, 9, 9] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 7, 7, 7, 7] assert current == [7, 7, 7, 8, 9, 9, 9, 9, 9, 9] assert next is None def test_cursor_pagination_with_page_size_zero(self): (previous, current, next, previous_url, next_url) = self.get_pages('/?page_size=0') assert previous is None assert current == [1, 1, 1, 1, 1] assert next == [1, 2, 3, 4, 4] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [1, 1, 1, 1, 1] assert current == [1, 2, 3, 4, 4] assert next == [4, 4, 5, 6, 7] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [1, 2, 3, 4, 4] assert current == [4, 4, 5, 6, 7] assert next == [7, 7, 7, 7, 7] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [4, 4, 4, 5, 6] # Paging artifact assert current == [7, 7, 7, 7, 7] assert next == [7, 7, 7, 8, 9] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [7, 7, 7, 7, 7] assert current == [7, 7, 7, 8, 9] assert next == [9, 9, 9, 9, 9] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [7, 7, 7, 8, 9] assert current == [9, 9, 9, 9, 9] assert next is None (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [7, 7, 7, 7, 7] assert current == [7, 7, 7, 8, 9] assert next == [9, 9, 9, 9, 9] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [4, 4, 5, 6, 7] assert current == [7, 7, 7, 7, 7] assert next == [8, 9, 9, 9, 9] # Paging artifact (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [1, 2, 3, 4, 4] assert current == [4, 4, 5, 6, 7] assert next == [7, 7, 7, 7, 7] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [1, 1, 1, 1, 1] assert current == [1, 2, 3, 4, 4] assert next == [4, 4, 5, 6, 7] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous is None assert current == [1, 1, 1, 1, 1] assert next == [1, 2, 3, 4, 4] def test_cursor_pagination_with_page_size_negative(self): (previous, current, next, previous_url, next_url) = self.get_pages('/?page_size=-5') assert previous is None assert current == [1, 1, 1, 1, 1] assert next == [1, 2, 3, 4, 4] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [1, 1, 1, 1, 1] assert current == [1, 2, 3, 4, 4] assert next == [4, 4, 5, 6, 7] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [1, 2, 3, 4, 4] assert current == [4, 4, 5, 6, 7] assert next == [7, 7, 7, 7, 7] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [4, 4, 4, 5, 6] # Paging artifact assert current == [7, 7, 7, 7, 7] assert next == [7, 7, 7, 8, 9] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [7, 7, 7, 7, 7] assert current == [7, 7, 7, 8, 9] assert next == [9, 9, 9, 9, 9] (previous, current, next, previous_url, next_url) = self.get_pages(next_url) assert previous == [7, 7, 7, 8, 9] assert current == [9, 9, 9, 9, 9] assert next is None (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [7, 7, 7, 7, 7] assert current == [7, 7, 7, 8, 9] assert next == [9, 9, 9, 9, 9] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [4, 4, 5, 6, 7] assert current == [7, 7, 7, 7, 7] assert next == [8, 9, 9, 9, 9] # Paging artifact (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [1, 2, 3, 4, 4] assert current == [4, 4, 5, 6, 7] assert next == [7, 7, 7, 7, 7] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous == [1, 1, 1, 1, 1] assert current == [1, 2, 3, 4, 4] assert next == [4, 4, 5, 6, 7] (previous, current, next, previous_url, next_url) = self.get_pages(previous_url) assert previous is None assert current == [1, 1, 1, 1, 1] assert next == [1, 2, 3, 4, 4] def test_get_paginated_response_schema(self): unpaginated_schema = { 'type': 'object', 'item': { 'properties': { 'test-property': { 'type': 'integer', }, }, }, } assert self.pagination.get_paginated_response_schema(unpaginated_schema) == { 'type': 'object', 'required': ['results'], 'properties': { 'next': { 'type': 'string', 'nullable': True, 'format': 'uri', 'example': 'http://api.example.org/accounts/?cursor=cD00ODY%3D"' }, 'previous': { 'type': 'string', 'nullable': True, 'format': 'uri', 'example': 'http://api.example.org/accounts/?cursor=cj0xJnA9NDg3' }, 'results': unpaginated_schema, }, }
CursorPaginationTestsMixin
python
mahmoud__glom
glom/core.py
{ "start": 12494, "end": 13544 }
class ____(GlomError): """This :exc:`GlomError` subtype is raised when an assignment fails, stemming from an :func:`~glom.assign` call or other :class:`~glom.Assign` usage. One example would be assigning to an out-of-range position in a list:: >>> assign(["short", "list"], Path(5), 'too far') # doctest: +SKIP Traceback (most recent call last): ... PathAssignError: could not assign 5 on object at Path(), got error: IndexError(... Other assignment failures could be due to assigning to an ``@property`` or exception being raised inside a ``__setattr__()``. """ def __init__(self, exc, path, dest_name): self.exc = exc self.path = path self.dest_name = dest_name def get_message(self): return ('could not assign %r on object at %r, got error: %r' % (self.dest_name, self.path, self.exc)) def __repr__(self): cn = self.__class__.__name__ return f'{cn}({self.exc!r}, {self.path!r}, {self.dest_name!r})'
PathAssignError
python
getsentry__sentry
tests/sentry/workflow_engine/detectors/test_error_detector.py
{ "start": 446, "end": 4778 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.project = self.create_project() self.environment = Environment.objects.create( organization_id=self.project.organization_id, name="production" ) self.context = { "organization": self.project.organization, "project": self.project, "request": self.make_request(), } self.valid_data = { "name": "Test Detector", "type": "error", "fingerprinting_rules": """message:"hello world 1" -> hw1 title="HW1""", "resolve_age": 30, } self.existing_error_detector = Detector.objects.create( name="Existing Detector", type="error", project_id=self.project.id, config={} ) @patch("sentry.workflow_engine.endpoints.validators.error_detector.create_audit_entry") def test_create_with_valid_data(self, mock_audit: MagicMock) -> None: validator = ErrorDetectorValidator( data=self.valid_data, context=self.context, ) assert validator.is_valid(), validator.errors with self.tasks(): detector = validator.save() # Verify detector in DB detector = Detector.objects.get(id=detector.id) assert detector.name == "Test Detector" assert detector.type == "error" assert detector.project_id == self.project.id assert detector.workflow_condition_group is None # Verify audit log mock_audit.assert_called_once_with( request=self.context["request"], organization=self.project.organization, target_object=detector.id, event=audit_log.get_event_id("DETECTOR_ADD"), data=detector.get_audit_log_data(), ) def test_invalid_detector_type(self) -> None: data = {**self.valid_data, "type": "metric_issue"} validator = ErrorDetectorValidator(data=data, context=self.context) assert not validator.is_valid() assert validator.errors.get("type") == [ ErrorDetail(string="Detector type must be error", code="invalid") ] def test_invalid_fingerprinting_rules(self) -> None: data = {**self.valid_data, "fingerprinting_rules": "hello"} validator = ErrorDetectorValidator(data=data, context=self.context) assert not validator.is_valid() assert validator.errors.get("fingerprintingRules") == [ ErrorDetail(string="""Invalid syntax near "hello" (line 1, column 1)""", code="invalid") ] def test_invalid_resolve_duration(self) -> None: data = {**self.valid_data, "resolve_age": "-1"} validator = ErrorDetectorValidator(data=data, context=self.context) assert not validator.is_valid() assert validator.errors.get("resolveAge") == [ ErrorDetail(string="Resolve age must be a non-negative number", code="invalid") ] def test_invalid_condition_group(self) -> None: data = { **self.valid_data, "condition_group": { "logic_type": "any", "conditions": [ { "type": "eq", "comparison": 100, "condition_result": "high", } ], }, } validator = ErrorDetectorValidator(data=data, context=self.context) assert not validator.is_valid() assert validator.errors.get("conditionGroup") == [ ErrorDetail( string="Condition group is not supported for error detectors", code="invalid" ) ] def test_update_existing_with_valid_data(self) -> None: data = {**self.valid_data, "name": "Updated Detector"} validator = ErrorDetectorValidator( data=data, context=self.context, instance=self.existing_error_detector ) assert validator.is_valid() with self.tasks(): detector = validator.save() assert detector.name == "Updated Detector" assert detector.type == "error" assert detector.project_id == self.project.id assert detector.workflow_condition_group is None
TestErrorDetectorValidator
python
walkccc__LeetCode
solutions/2832. Maximal Range That Each Element Is Maximum in It/2832.py
{ "start": 0, "end": 391 }
class ____: def maximumLengthOfRanges(self, nums: list[int]) -> list[int]: ans = [0] * len(nums) stack = [] # a decreasing stack for i in range(len(nums) + 1): while stack and (i == len(nums) or nums[stack[-1]] < nums[i]): index = stack.pop() left = stack[-1] if stack else -1 ans[index] = i - left - 1 stack.append(i) return ans
Solution
python
xlwings__xlwings
xlwings/_xlwindows.py
{ "start": 53983, "end": 54602 }
class ____(base_classes.Collection): def __init__(self, xl): self.xl = xl @property def api(self): return self.xl def __call__(self, key): try: return self._wrap(xl=self.xl.Item(key)) except pywintypes.com_error: raise KeyError(key) def __len__(self): return self.xl.Count def __iter__(self): for xl in self.xl: yield self._wrap(xl=xl) def __contains__(self, key): try: self.xl.Item(key) return True except pywintypes.com_error: return False
Collection
python
run-llama__llama_index
llama-index-integrations/callbacks/llama-index-callbacks-promptlayer/llama_index/callbacks/promptlayer/base.py
{ "start": 453, "end": 4905 }
class ____(BaseCallbackHandler): """Callback handler for sending to promptlayer.com.""" pl_tags: Optional[List[str]] return_pl_id: bool = False def __init__(self, pl_tags: List[str] = [], return_pl_id: bool = False) -> None: try: from promptlayer.utils import get_api_key, promptlayer_api_request self._promptlayer_api_request = promptlayer_api_request self._promptlayer_api_key = get_api_key() except ImportError: raise ImportError( "Please install PromptLAyer with `pip install promptlayer`" ) self.pl_tags = pl_tags self.return_pl_id = return_pl_id super().__init__(event_starts_to_ignore=[], event_ends_to_ignore=[]) def start_trace(self, trace_id: Optional[str] = None) -> None: return def end_trace( self, trace_id: Optional[str] = None, trace_map: Optional[Dict[str, List[str]]] = None, ) -> None: return event_map: Dict[str, Dict[str, Any]] = {} def add_event(self, event_id: str, **kwargs: Any) -> None: self.event_map[event_id] = { "kwargs": kwargs, "request_start_time": datetime.datetime.now().timestamp(), } def get_event( self, event_id: str, ) -> Dict[str, Any]: return self.event_map[event_id] or {} def on_event_start( self, event_type: CBEventType, payload: Optional[Dict[str, Any]] = None, event_id: str = "", parent_id: str = "", **kwargs: Any, ) -> str: if event_type == CBEventType.LLM and payload is not None: self.add_event( event_id=event_id, **payload.get(EventPayload.SERIALIZED, {}) ) return event_id def on_event_end( self, event_type: CBEventType, payload: Optional[Dict[str, Any]] = None, event_id: str = "", **kwargs: Any, ) -> None: if event_type != CBEventType.LLM or payload is None: return request_end_time = datetime.datetime.now().timestamp() prompt = str(payload.get(EventPayload.PROMPT)) completion = payload.get(EventPayload.COMPLETION) response = payload.get(EventPayload.RESPONSE) function_name = PROMPT_LAYER_CHAT_FUNCTION_NAME event_data = self.get_event(event_id=event_id) resp: Union[str, Dict] extra_args = {} resp = None if response: messages = cast(List[ChatMessage], payload.get(EventPayload.MESSAGES, [])) resp = response.message.dict() assert isinstance(resp, dict) usage_dict: Dict[str, int] = {} try: usage = response.raw.get("usage", None) # type: ignore if isinstance(usage, dict): usage_dict = { "prompt_tokens": usage.get("prompt_tokens", 0), "completion_tokens": usage.get("completion_tokens", 0), "total_tokens": usage.get("total_tokens", 0), } elif isinstance(usage, BaseModel): usage_dict = usage.dict() except Exception: pass extra_args = { "messages": [message.dict() for message in messages], "usage": usage_dict, } ## promptlayer needs tool_calls toplevel. if "tool_calls" in response.message.additional_kwargs: resp["tool_calls"] = [ tool_call.dict() for tool_call in resp["additional_kwargs"]["tool_calls"] ] del resp["additional_kwargs"]["tool_calls"] if completion: function_name = PROMPT_LAYER_COMPLETION_FUNCTION_NAME resp = str(completion) if resp: _pl_request_id = self._promptlayer_api_request( function_name, "openai", [prompt], { **extra_args, **event_data["kwargs"], }, self.pl_tags, [resp], event_data["request_start_time"], request_end_time, self._promptlayer_api_key, return_pl_id=self.return_pl_id, )
PromptLayerHandler
python
doocs__leetcode
solution/2000-2099/2070.Most Beautiful Item for Each Query/Solution2.py
{ "start": 0, "end": 445 }
class ____: def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]: items.sort() prices = [p for p, _ in items] n = len(items) mx = [items[0][1]] for i in range(1, n): mx.append(max(mx[i - 1], items[i][1])) ans = [] for q in queries: j = bisect_right(prices, q) - 1 ans.append(0 if j < 0 else mx[j]) return ans
Solution
python
simonw__datasette
datasette/utils/__init__.py
{ "start": 31499, "end": 34298 }
class ____(Exception): pass @documented def parse_metadata(content: str) -> dict: "Detects if content is JSON or YAML and parses it appropriately." # content can be JSON or YAML try: return json.loads(content) except json.JSONDecodeError: try: return yaml.safe_load(content) except yaml.YAMLError: raise BadMetadataError("Metadata is not valid JSON or YAML") def _gather_arguments(fn, kwargs): parameters = inspect.signature(fn).parameters.keys() call_with = [] for parameter in parameters: if parameter not in kwargs: raise TypeError( "{} requires parameters {}, missing: {}".format( fn, tuple(parameters), set(parameters) - set(kwargs.keys()) ) ) call_with.append(kwargs[parameter]) return call_with def call_with_supported_arguments(fn, **kwargs): call_with = _gather_arguments(fn, kwargs) return fn(*call_with) async def async_call_with_supported_arguments(fn, **kwargs): call_with = _gather_arguments(fn, kwargs) return await fn(*call_with) def actor_matches_allow(actor, allow): if allow is True: return True if allow is False: return False if actor is None and allow and allow.get("unauthenticated") is True: return True if allow is None: return True actor = actor or {} for key, values in allow.items(): if values == "*" and key in actor: return True if not isinstance(values, list): values = [values] actor_values = actor.get(key) if actor_values is None: continue if not isinstance(actor_values, list): actor_values = [actor_values] actor_values = set(actor_values) if actor_values.intersection(values): return True return False def resolve_env_secrets(config, environ): """Create copy that recursively replaces {"$env": "NAME"} with values from environ""" if isinstance(config, dict): if list(config.keys()) == ["$env"]: return environ.get(list(config.values())[0]) elif list(config.keys()) == ["$file"]: with open(list(config.values())[0]) as fp: return fp.read() else: return { key: resolve_env_secrets(value, environ) for key, value in config.items() } elif isinstance(config, list): return [resolve_env_secrets(value, environ) for value in config] else: return config def display_actor(actor): for key in ("display", "name", "username", "login", "id"): if actor.get(key): return actor[key] return str(actor)
BadMetadataError
python
huggingface__transformers
tests/models/deepseek_vl/test_image_processing_deepseek_vl.py
{ "start": 2961, "end": 6119 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = DeepseekVLImageProcessor if is_vision_available() else None fast_image_processing_class = DeepseekVLImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = DeepseekVLImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "image_mean")) self.assertTrue(hasattr(image_processing, "image_std")) self.assertTrue(hasattr(image_processing, "do_normalize")) self.assertTrue(hasattr(image_processing, "do_resize")) self.assertTrue(hasattr(image_processing, "size")) def test_image_processor_from_dict_with_kwargs(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {"height": 18, "width": 18}) image_processor = image_processing_class.from_dict(self.image_processor_dict, size=42) self.assertEqual(image_processor.size, {"height": 42, "width": 42}) @require_vision @require_torch def test_slow_fast_equivalence_batched(self): if not self.test_slow_image_processor or not self.test_fast_image_processor: self.skipTest(reason="Skipping slow/fast equivalence test") if self.image_processing_class is None or self.fast_image_processing_class is None: self.skipTest(reason="Skipping slow/fast equivalence test as one of the image processors is not defined") if hasattr(self.image_processor_tester, "do_center_crop") and self.image_processor_tester.do_center_crop: self.skipTest( reason="Skipping as do_center_crop is True and center_crop functions are not equivalent for fast and slow processors" ) dummy_images = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) image_processor_slow = self.image_processing_class(**self.image_processor_dict) image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) encoding_slow = image_processor_slow(dummy_images, return_tensors=None) encoding_fast = image_processor_fast(dummy_images, return_tensors=None) # Overwrite as the outputs are not always all of the same shape (kept for BC) for i in range(len(encoding_slow.pixel_values)): self._assert_slow_fast_tensors_equivalence( torch.from_numpy(encoding_slow.pixel_values[i]), encoding_fast.pixel_values[i] ) # Ignore copy @unittest.skip(reason="Not supported") def test_call_numpy_4_channels(self): pass
DeepseekVLImageProcessingTest
python
altair-viz__altair
altair/utils/selection.py
{ "start": 281, "end": 1599 }
class ____: """ Represents the state of an alt.selection_point() when neither the fields nor encodings arguments are specified. The value field is a list of zero-based indices into the selected dataset. Note: These indices only apply to the input DataFrame for charts that do not include aggregations (e.g. a scatter chart). """ name: str value: list[int] store: Store @staticmethod def from_vega(name: str, signal: dict[str, dict] | None, store: Store): """ Construct an IndexSelection from the raw Vega signal and dataset values. Parameters ---------- name: str The selection's name signal: dict or None The value of the Vega signal corresponding to the selection store: list The value of the Vega dataset corresponding to the selection. This dataset is named "{name}_store" in the Vega view. Returns ------- IndexSelection """ if signal is None: indices = [] else: points = signal.get("vlPoint", {}).get("or", []) indices = [p["_vgsid_"] - 1 for p in points] return IndexSelection(name=name, value=indices, store=store) @dataclass(frozen=True, eq=True)
IndexSelection
python
gevent__gevent
src/greentest/3.14/test__interpreters.py
{ "start": 26671, "end": 31449 }
class ____(TestBase): def setUp(self): super().setUp() self.id = _interpreters.create() def add_module(self, modname, text): import tempfile tempdir = tempfile.mkdtemp() self.addCleanup(lambda: os_helper.rmtree(tempdir)) _interpreters.run_string(self.id, dedent(f""" import sys sys.path.insert(0, {tempdir!r}) """)) return script_helper.make_script(tempdir, modname, text) def run_script(self, text, *, fails=False): r, w = os.pipe() try: script = dedent(f""" import os, sys os.write({w}, b'0') # This raises an exception: {{}} # Nothing from here down should ever run. os.write({w}, b'1') class NeverError(Exception): pass raise NeverError # never raised """).format(dedent(text)) if fails: err = _interpreters.run_string(self.id, script) self.assertIsNot(err, None) return err else: err = _interpreters.run_string(self.id, script) self.assertIs(err, None) return None except: raise # re-raise else: msg = os.read(r, 100) self.assertEqual(msg, b'0') finally: os.close(r) os.close(w) def _assert_run_failed(self, exctype, msg, script): if isinstance(exctype, str): exctype_name = exctype exctype = None else: exctype_name = exctype.__name__ # Run the script. excinfo = self.run_script(script, fails=True) # Check the wrapper exception. self.assertEqual(excinfo.type.__name__, exctype_name) if msg is None: self.assertEqual(excinfo.formatted.split(':')[0], exctype_name) else: self.assertEqual(excinfo.formatted, '{}: {}'.format(exctype_name, msg)) return excinfo def assert_run_failed(self, exctype, script): self._assert_run_failed(exctype, None, script) def assert_run_failed_msg(self, exctype, msg, script): self._assert_run_failed(exctype, msg, script) def test_exit(self): with self.subTest('sys.exit(0)'): # XXX Should an unhandled SystemExit(0) be handled as not-an-error? self.assert_run_failed(SystemExit, """ sys.exit(0) """) with self.subTest('sys.exit()'): self.assert_run_failed(SystemExit, """ import sys sys.exit() """) with self.subTest('sys.exit(42)'): self.assert_run_failed_msg(SystemExit, '42', """ import sys sys.exit(42) """) with self.subTest('SystemExit'): self.assert_run_failed_msg(SystemExit, '42', """ raise SystemExit(42) """) # XXX Also check os._exit() (via a subprocess)? def test_plain_exception(self): self.assert_run_failed_msg(Exception, 'spam', """ raise Exception("spam") """) def test_invalid_syntax(self): script = dedent(""" x = 1 + 2 y = 2 + 4 z = 4 + 8 # missing close paren print("spam" if x + y + z < 20: ... """) with self.subTest('script'): with self.assertRaises(SyntaxError): _interpreters.run_string(self.id, script) with self.subTest('module'): modname = 'spam_spam_spam' filename = self.add_module(modname, script) self.assert_run_failed(SyntaxError, f""" import {modname} """) def test_NameError(self): self.assert_run_failed(NameError, """ res = spam + eggs """) # XXX check preserved suggestions def test_AttributeError(self): self.assert_run_failed(AttributeError, """ object().spam """) # XXX check preserved suggestions def test_ExceptionGroup(self): self.assert_run_failed(ExceptionGroup, """ raise ExceptionGroup('exceptions', [ Exception('spam'), ImportError('eggs'), ]) """) def test_user_defined_exception(self): self.assert_run_failed_msg('MyError', 'spam', """ class MyError(Exception): pass raise MyError('spam') """)
RunFailedTests
python
doocs__leetcode
solution/2700-2799/2707.Extra Characters in a String/Solution2.py
{ "start": 0, "end": 161 }
class ____: __slots__ = ['children', 'is_end'] def __init__(self): self.children: List[Node | None] = [None] * 26 self.is_end = False
Node
python
bokeh__bokeh
src/bokeh/core/serialization.py
{ "start": 4015, "end": 4923 }
class ____: id: ID data: bytes | memoryview @property def ref(self) -> Ref: return Ref(id=self.id) def to_bytes(self) -> bytes: return self.data.tobytes() if isinstance(self.data, memoryview) else self.data def to_compressed_bytes(self) -> bytes: level = settings.compression_level() # we do not want the result to be different depending on mtime, since that is # irrelevant and also makes things harder to test, but Python 3.11 and 3.12 have # bug where using mtime=0 results in the Gzip header OS field varies by platforam # instead of getting set to a fixed value of 255. So, for now use mtime=1 instead. return gzip.compress(self.to_bytes(), mtime=1, compresslevel=level) def to_base64(self) -> str: return base64.b64encode(self.to_compressed_bytes()).decode("utf-8") T = TypeVar("T") @dataclass
Buffer
python
spack__spack
lib/spack/spack/config.py
{ "start": 73036, "end": 75256 }
class ____(spack.error.ConfigError): """Raised when a configuration format does not match its schema.""" def __init__( self, validation_error, data: YamlConfigDict, filename: Optional[str] = None, line: Optional[int] = None, ) -> None: # spack yaml has its own file/line marks -- try to find them # we prioritize these over the inputs self.validation_error = validation_error mark = self._get_mark(validation_error, data) if mark: filename = mark.name line = mark.line + 1 self.filename = filename # record this for ruamel.yaml # construct location location = "<unknown file>" if filename: location = f"{filename}" if line is not None: location += f":{line:d}" message = f"{location}: {validation_error.message}" super().__init__(message) def _get_mark(self, validation_error, data): """Get the file/line mark fo a validation error from a Spack YAML file.""" # Try various places, starting with instance and parent for obj in (validation_error.instance, validation_error.parent): mark = get_mark_from_yaml_data(obj) if mark: return mark def get_path(path, data): if path: return get_path(path[1:], data[path[0]]) else: return data # Try really hard to get the parent (which sometimes is not # set) This digs it out of the validated structure if it's not # on the validation_error. path = validation_error.path if path: parent = get_path(list(path)[:-1], data) if path[-1] in parent: if isinstance(parent, dict): keylist = list(parent.keys()) elif isinstance(parent, list): keylist = parent idx = keylist.index(path[-1]) mark = getattr(keylist[idx], "_start_mark", None) if mark: return mark # give up and return None if nothing worked return None
ConfigFormatError
python
pytorch__pytorch
torch/testing/_internal/common_utils.py
{ "start": 83985, "end": 84499 }
class ____: def __init__(self, sync_debug_mode): self.mode = sync_debug_mode def __enter__(self): self.debug_mode_restore = torch.cuda.get_sync_debug_mode() torch.cuda.set_sync_debug_mode(self.mode) def __exit__(self, exception_type, exception_value, traceback): torch.cuda.set_sync_debug_mode(self.debug_mode_restore) # Context manager for setting torch.__future__.set_swap_module_params_on_conversion # and automatically resetting it to its original value
CudaSyncGuard
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-days-to-disconnect-island.py
{ "start": 7630, "end": 9080 }
class ____(object): def minDays(self, grid): """ :type grid: List[List[int]] :rtype: int """ DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] def floodfill(grid, i, j, lookup): stk = [(i, j)] lookup[i][j] = 1 while stk: i, j = stk.pop() for di, dj in DIRECTIONS: ni, nj = i+di, j+dj if not (0 <= ni < R and 0 <= nj < C and grid[ni][nj] and not lookup[ni][nj]): continue lookup[ni][nj] = 1 stk.append((ni, nj)) def count_islands(grid): lookup = [[0]*C for _ in xrange(R)] island_cnt = 0 for i in xrange(R): for j in xrange(C): if grid[i][j] == 0 or lookup[i][j]: continue island_cnt += 1 floodfill(grid, i, j, lookup) return island_cnt R, C = len(grid), len(grid[0]) if count_islands(grid) != 1: return 0 for i in xrange(R): for j in xrange(C): if grid[i][j] == 0: continue grid[i][j] = 0 island_cnt = count_islands(grid) grid[i][j] = 1 if island_cnt != 1: return 1 return 2
Solution3
python
spack__spack
lib/spack/spack/spec.py
{ "start": 25002, "end": 29588 }
class ____: """DependencySpecs represent an edge in the DAG, and contain dependency types and information on the virtuals being provided. Dependencies can be one (or more) of several types: - build: needs to be in the PATH at build time. - link: is linked to and added to compiler flags. - run: needs to be in the PATH for the package to run. Args: parent: starting node of the edge spec: ending node of the edge. depflag: represents dependency relationships. virtuals: virtual packages provided from child to parent node. """ __slots__ = "parent", "spec", "depflag", "virtuals", "direct", "when", "propagation" def __init__( self, parent: "Spec", spec: "Spec", *, depflag: dt.DepFlag, virtuals: Tuple[str, ...], direct: bool = False, propagation: PropagationPolicy = PropagationPolicy.NONE, when: Optional["Spec"] = None, ): if direct is False and propagation != PropagationPolicy.NONE: raise InvalidEdgeError("only direct dependencies can be propagated") self.parent = parent self.spec = spec self.depflag = depflag self.virtuals = tuple(sorted(set(virtuals))) self.direct = direct self.propagation = propagation self.when = when or Spec() def update_deptypes(self, depflag: dt.DepFlag) -> bool: """Update the current dependency types""" old = self.depflag new = depflag | old if new == old: return False self.depflag = new return True def update_virtuals(self, virtuals: Union[str, Iterable[str]]) -> bool: """Update the list of provided virtuals""" old = self.virtuals if isinstance(virtuals, str): union = {virtuals, *self.virtuals} else: union = {*virtuals, *self.virtuals} if len(union) == len(old): return False self.virtuals = tuple(sorted(union)) return True def copy(self, *, keep_virtuals: bool = True, keep_parent: bool = True) -> "DependencySpec": """Return a copy of this edge""" parent = self.parent if keep_parent else Spec() virtuals = self.virtuals if keep_virtuals else () return DependencySpec( parent, self.spec, depflag=self.depflag, virtuals=virtuals, propagation=self.propagation, direct=self.direct, when=self.when, ) def _cmp_iter(self): yield self.parent.name if self.parent else None yield self.spec.name if self.spec else None yield self.depflag yield self.virtuals yield self.direct yield self.propagation yield self.when def __str__(self) -> str: return self.format() def __repr__(self) -> str: keywords = [f"depflag={self.depflag}", f"virtuals={self.virtuals}"] if self.direct: keywords.append(f"direct={self.direct}") if self.when != Spec(): keywords.append(f"when={self.when}") if self.propagation != PropagationPolicy.NONE: keywords.append(f"propagation={self.propagation}") keywords_str = ", ".join(keywords) return f"DependencySpec({self.parent.format()!r}, {self.spec.format()!r}, {keywords_str})" def format(self, *, unconditional: bool = False) -> str: """Returns a string, using the spec syntax, representing this edge Args: unconditional: if True, removes any condition statement from the representation """ parent_str, child_str = self.parent.format(), self.spec.format() virtuals_str = f"virtuals={','.join(self.virtuals)}" if self.virtuals else "" when_str = "" if not unconditional and self.when != Spec(): when_str = f"when='{self.when}'" dep_sigil = "%" if self.direct else "^" if self.propagation == PropagationPolicy.PREFERENCE: dep_sigil = "%%" edge_attrs = [x for x in (virtuals_str, when_str) if x] if edge_attrs: return f"{parent_str} {dep_sigil}[{' '.join(edge_attrs)}] {child_str}" return f"{parent_str} {dep_sigil}{child_str}" def flip(self) -> "DependencySpec": """Flips the dependency and keeps its type. Drops all othe information.""" return DependencySpec( parent=self.spec, spec=self.parent, depflag=self.depflag, virtuals=() )
DependencySpec
python
ipython__ipython
IPython/core/prefilter.py
{ "start": 18206, "end": 19761 }
class ____(PrefilterChecker): priority = Integer(1000).tag(config=True) function_name_regexp = CRegExp(re_fun_name, help="RegExp to identify potential function names." ).tag(config=True) exclude_regexp = CRegExp(re_exclude_auto, help="RegExp to exclude strings with this start from autocalling." ).tag(config=True) def check(self, line_info): "Check if the initial word/function is callable and autocall is on." if not self.shell.autocall: return None oinfo = line_info.ofind(self.shell) # This can mutate state via getattr if not oinfo.found: return None ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf'] ifun = line_info.ifun line = line_info.line if ifun.lower() in ignored_funs and (line.startswith(ifun + "'") or line.startswith(ifun + '"')): return None if ( callable(oinfo.obj) and (not self.exclude_regexp.match(line_info.the_rest)) and self.function_name_regexp.match(line_info.ifun) and ( line_info.raw_the_rest.startswith(" ") or not line_info.raw_the_rest.strip() ) ): return self.prefilter_manager.get_handler_by_name("auto") else: return None #----------------------------------------------------------------------------- # Prefilter handlers #-----------------------------------------------------------------------------
AutocallChecker
python
ray-project__ray
python/ray/serve/tests/test_config_files/get_multi_deployment_signal_app.py
{ "start": 110, "end": 385 }
class ____: def __init__(self, b: DeploymentHandle): self.b = b self.signal = ray.get_actor("signal_A", namespace="default_test_namespace") async def __call__(self): await self.signal.wait.remote() return os.getpid() @serve.deployment
A
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/scanner.py
{ "start": 76040, "end": 82103 }
class ____: def __init__(self): # type: (Any) -> None self.comments = {} # type: ignore self.unused = [] # type: ignore def add_eol_comment(self, comment, column, line): # type: (Any, Any, Any) -> Any # info = inspect.getframeinfo(inspect.stack()[1][0]) if comment.count('\n') == 1: assert comment[-1] == '\n' else: assert '\n' not in comment self.comments[line] = retval = EOLComment(comment[:-1], line, column) self.unused.append(line) return retval def add_blank_line(self, comment, column, line): # type: (Any, Any, Any) -> Any # info = inspect.getframeinfo(inspect.stack()[1][0]) assert comment.count('\n') == 1 and comment[-1] == '\n' assert line not in self.comments self.comments[line] = retval = BlankLineComment(comment[:-1], line, column) self.unused.append(line) return retval def add_full_line_comment(self, comment, column, line): # type: (Any, Any, Any) -> Any # info = inspect.getframeinfo(inspect.stack()[1][0]) assert comment.count('\n') == 1 and comment[-1] == '\n' # if comment.startswith('# C12'): # raise # this raises in line 2127 fro 330 self.comments[line] = retval = FullLineComment(comment[:-1], line, column) self.unused.append(line) return retval def __getitem__(self, idx): # type: (Any) -> Any return self.comments[idx] def __str__(self): # type: () -> Any return ( 'ParsedComments:\n ' + '\n '.join( ( _F('{lineno:2} {x}', lineno=lineno, x=x.info()) for lineno, x in self.comments.items() ) ) + '\n' ) def last(self): # type: () -> str lineno, x = list(self.comments.items())[-1] return _F('{lineno:2} {x}\n', lineno=lineno, x=x.info()) # type: ignore def any_unprocessed(self): # type: () -> bool # ToDo: might want to differentiate based on lineno return len(self.unused) > 0 # for lno, comment in reversed(self.comments.items()): # if comment.used == ' ': # return True # return False def unprocessed(self, use=False): # type: (Any) -> Any while len(self.unused) > 0: first = self.unused.pop(0) if use else self.unused[0] info = inspect.getframeinfo(inspect.stack()[1][0]) xprintf('using', first, self.comments[first].value, info.function, info.lineno) yield first, self.comments[first] if use: self.comments[first].set_used() def assign_pre(self, token): # type: (Any) -> Any token_line = token.start_mark.line info = inspect.getframeinfo(inspect.stack()[1][0]) xprintf('assign_pre', token_line, self.unused, info.function, info.lineno) gobbled = False while self.unused and self.unused[0] < token_line: gobbled = True first = self.unused.pop(0) xprintf('assign_pre < ', first) self.comments[first].set_used() token.add_comment_pre(first) return gobbled def assign_eol(self, tokens): # type: (Any) -> Any try: comment_line = self.unused[0] except IndexError: return if not isinstance(self.comments[comment_line], EOLComment): return idx = 1 while tokens[-idx].start_mark.line > comment_line or isinstance( tokens[-idx], ValueToken ): idx += 1 xprintf('idx1', idx) if ( len(tokens) > idx and isinstance(tokens[-idx], ScalarToken) and isinstance(tokens[-(idx + 1)], ScalarToken) ): return try: if isinstance(tokens[-idx], ScalarToken) and isinstance( tokens[-(idx + 1)], KeyToken ): try: eol_idx = self.unused.pop(0) self.comments[eol_idx].set_used() xprintf('>>>>>a', idx, eol_idx, KEYCMNT) tokens[-idx].add_comment_eol(eol_idx, KEYCMNT) except IndexError: raise NotImplementedError return except IndexError: xprintf('IndexError1') pass try: if isinstance(tokens[-idx], ScalarToken) and isinstance( tokens[-(idx + 1)], (ValueToken, BlockEntryToken) ): try: eol_idx = self.unused.pop(0) self.comments[eol_idx].set_used() tokens[-idx].add_comment_eol(eol_idx, VALUECMNT) except IndexError: raise NotImplementedError return except IndexError: xprintf('IndexError2') pass for t in tokens: xprintf('tt-', t) xprintf('not implemented EOL', type(tokens[-idx])) import sys sys.exit(0) def assign_post(self, token): # type: (Any) -> Any token_line = token.start_mark.line info = inspect.getframeinfo(inspect.stack()[1][0]) xprintf('assign_post', token_line, self.unused, info.function, info.lineno) gobbled = False while self.unused and self.unused[0] < token_line: gobbled = True first = self.unused.pop(0) xprintf('assign_post < ', first) self.comments[first].set_used() token.add_comment_post(first) return gobbled def str_unprocessed(self): # type: () -> Any return ''.join( ( _F(' {ind:2} {x}\n', ind=ind, x=x.info()) for ind, x in self.comments.items() if x.used == ' ' ) )
ScannedComments
python
pytorch__pytorch
test/functorch/test_eager_transforms.py
{ "start": 79794, "end": 81783 }
class ____(TestCase): def _test_against_reference(self, f, inputs): def foo(inputs): return f(*inputs) expected = torch.autograd.functional.hessian(f, inputs) result = hessian(foo)(inputs) self.assertEqual(result, expected) def test_hessian_vectorize_correctness_simple(self, device): def f(x): return (3 * x**2).sum() x = torch.randn(2, 3, 5, device=device) self._test_against_reference(f, (x,)) def test_hessian_vectorize_correctness_multi_input(self, device): def f(x, y, z): return ((x.relu() * x) @ y.sin() @ z).sum() x = torch.randn(2, 3, device=device) y = torch.randn(3, 5, device=device) z = torch.randn(5, 5, device=device) self._test_against_reference(f, (x, y, z)) def test_hessian_vectorize_correctness_unrelated_outputs(self, device): # output unrelated to one input def f(x, y): return (x**2).sum() x = torch.randn(2, device=device) y = torch.randn(3, device=device) self._test_against_reference(f, (x, y)) # output unrelated to all inputs def f(x, y): return torch.ones([]) x = torch.randn(2, device=device) y = torch.randn(3, device=device) self._test_against_reference(f, (x, y)) def test_jacfwd_different_levels(self, device): # Test case from: # https://github.com/pytorch/functorch/issues/597 b = 8 n = 100 d = 2 x1 = torch.randn(b, n, d, device=device) x2 = x1 A = 0.1 * torch.randn(b, d, d, device=device) def loss(A, x1, x2): x2_hat = (A @ (x1.T)).T res = x2 - x2_hat res_sqr = res**2 return res_sqr.sum() hess1 = vmap(jacrev(jacrev(loss)))(A, x1, x2) hess2 = vmap(hessian(loss))(A, x1, x2) self.assertEqual(hess2, hess1) @markDynamoStrictTest
TestHessian
python
PrefectHQ__prefect
src/prefect/events/filters.py
{ "start": 7870, "end": 9195 }
class ____(EventDataFilter): occurred: EventOccurredFilter = Field( default_factory=lambda: EventOccurredFilter(), description="Filter criteria for when the events occurred", ) event: Optional[EventNameFilter] = Field( default=None, description="Filter criteria for the event name", ) resource: Optional[EventResourceFilter] = Field( default=None, description="Filter criteria for the resource of the event", ) related: Optional[Union[EventRelatedFilter, list[EventRelatedFilter]]] = Field( default=None, description="Filter criteria for the related resources of the event", ) any_resource: Optional[ Union[EventAnyResourceFilter, list[EventAnyResourceFilter]] ] = Field( default=None, description="Filter criteria for any resource involved in the event", ) id: EventIDFilter = Field( default_factory=lambda: EventIDFilter(id=[]), description="Filter criteria for the events' ID", ) text: Optional[EventTextFilter] = Field( default=None, description="Filter criteria for text search across event content", ) order: EventOrder = Field( default=EventOrder.DESC, description="The order to return filtered events", )
EventFilter
python
tensorflow__tensorflow
tensorflow/compiler/tests/eager_test.py
{ "start": 10983, "end": 23715 }
class ____(xla_test.XLATestCase): def testBasic(self): with self.test_scope(): matmul = def_function.function(math_ops.matmul) t = constant_op.constant([[1.0, 2.0], [3.0, 4.0]]) sq = matmul(t, t, transpose_a=True) self.assertAllEqual(sq.numpy().reshape(-1), [10, 14, 14, 20]) def testConv(self): if 'GPU' in self.device: # TODO(b/32333178) self.skipTest('Current implementation of RandomStandardNormal kernel ' 'is very slow on GPU, and has been denylisted.') with self.test_scope(): data_format = 'channels_last' conv = convolutional.Conv2D( filters=1, kernel_size=2, padding='VALID', data_format=data_format, activation=nn_ops.relu, kernel_initializer=init_ops.ones_initializer(), bias_initializer=init_ops.zeros_initializer()) pool = pooling.MaxPooling2D(2, 2, data_format=data_format) def model(x): x = conv(x) return pool(x) model = def_function.function(model) x = array_ops.ones([1, 4, 4, 1]) y = model(x) self.assertAllEqual(y.numpy(), [[[[4.]]]]) def testReadVariable(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(1.0) @def_function.function def f(): return v.read_value() var = f() self.assertEqual(1.0, var.numpy()) def testResourceVariableNoInlineReadWrite(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(1.0) w = resource_variable_ops.ResourceVariable(0.0) @def_function.function(experimental_attributes={'_noinline': True}) def g(x): w.assign(w.read_value() + x) return v.read_value() + x * w.read_value() @def_function.function(experimental_attributes={'_noinline': True}) def f(): return g(1.0) + g(2.0) + g(3.0) + g(4.0) + g(5.0) # 1 + 1*1 + 1 + 2*3 + 1 + 3*6 + 1 + 4*10 + 1 + 5*15 self.assertEqual(145.0, f().numpy()) self.assertEqual(15.0, w.read_value().numpy()) def testResourceVariableNoInlineReadOnly(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(10.0) @def_function.function(experimental_attributes={'_noinline': True}) def g(): return v.read_value() @def_function.function(experimental_attributes={'_noinline': True}) def f(): return g() + g() + g() + g() + g() self.assertEqual(50.0, f().numpy()) def testResourceVariableNoInlineWriteOnly(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(0.0) @def_function.function(experimental_attributes={'_noinline': True}) def g(x): v.assign(x) @def_function.function(experimental_attributes={'_noinline': True}) def f(): g(1.0) g(2.0) g(3.0) g(4.0) g(5.0) f() self.assertEqual(5.0, v.read_value().numpy()) def testUpdateVariable(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable(1.0) def f(v): v.assign_add(1.0) return v f = def_function.function(f) var = f(v) self.assertEqual(2.0, var.numpy()) def testReturnResourceHandle(self): with self.test_scope(): v = resource_variable_ops.ResourceVariable([[1.0, 2.0], [3.0, 4.0]]) def f(v): return v.handle f = def_function.function(f) handle = f(v) self.assertAllEqual(v.numpy(), resource_variable_ops.read_variable_op( handle, dtypes.float32).numpy()) def testReturnMultipleResourceHandles(self): with self.test_scope(): v1 = resource_variable_ops.ResourceVariable(1.25) v2 = resource_variable_ops.ResourceVariable(2.0) def f(v): return v.handle, 3.0 * v, v2.handle, v + v2 f = def_function.function(f) v1_handle, v1_times_3, v2_handle, variable_sum = f(v1) self.assertAllEqual(v1.numpy(), resource_variable_ops.read_variable_op( v1_handle, dtypes.float32).numpy()) self.assertEqual(3.75, v1_times_3.numpy()) self.assertAllEqual(v2.numpy(), resource_variable_ops.read_variable_op( v2_handle, dtypes.float32).numpy()) self.assertEqual(3.25, variable_sum.numpy()) def testAllArgumentKinds(self): """Test a complex function that takes different argument kinds. tf2xla machinery that translates, compiles, and runs defuns classifies arguments into: compile-time constants, regular tensors, and resources. This test creates a function with a mix of all these kinds. Moreover, the order of function arguments is intentionally mixed up. This also tests the case when the same argument is a compile-time constant as well as used in an operation that normally expects its inputs to be in device memory - addition in this case. """ with self.test_scope(): def foo(c1, r1, v1, c2, v2, r2): # c1 and c2 are compile-time constants # r1 and r2 are regular tensors # v1 and v2 are resource variables a = c1 + r1 b = math_ops.cast(c2, dtypes.float32) + v2 c = array_ops.slice(v1, c1, c2) d = r2 * v2 return a, b, c, d foo = def_function.function(foo) c1 = [0, 0] c2 = array_ops.ones([2], dtype=dtypes.int32) r1 = array_ops.ones([2]) r2 = [[2., 2.], [3., 3.]] v1 = resource_variable_ops.ResourceVariable([[1., 2.], [3., 4.]]) v2 = resource_variable_ops.ResourceVariable([[10., 20.], [30., 40.]]) a, b, c, d = foo(c1, r1, v1, c2, v2, r2) self.assertAllEqual([1, 1], a.numpy()) self.assertAllEqual([[11., 21.], [31., 41.]], b.numpy()) self.assertAllEqual([[1.]], c.numpy()) self.assertAllEqual([[20., 40.], [90., 120.]], d.numpy()) def testDefunInGradientTape(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) @def_function.function def f(x): x = v0 * v0 * x return x x = constant_op.constant(3.0) with backprop.GradientTape() as tape: y = f(x) dy = tape.gradient(y, v0) self.assertEqual(75, y.numpy()) self.assertEqual(30, dy.numpy()) def testGradientTapeInDefun(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) @def_function.function def f(): x = constant_op.constant(1.0) with backprop.GradientTape() as tape: y = v0 * x dy = tape.gradient(y, v0) return dy dy = f() self.assertEqual(1.0, dy.numpy()) def testSliceInDefun(self): with self.test_scope(): @def_function.function def f(x, y): return x[0::2, y:, ...] x = array_ops.ones([2, 3, 4], dtype=dtypes.float32) y = array_ops.ones([], dtype=dtypes.int32) with backprop.GradientTape() as tape: tape.watch(x) tape.watch(y) z = f(x, y) dz = tape.gradient(z, x) self.assertAllEqual(np.ones([1, 2, 4]), z.numpy()) self.assertAllEqual((2, 3, 4), dz.shape.as_list()) def testNestedDefun(self): with self.test_scope(): @def_function.function def times_two(x): return 2. * x @def_function.function def two_x_plus_1(x): return times_two(x) + 1. x = constant_op.constant([2., 3., 4.]) y = two_x_plus_1(x) self.assertAllEqual([5., 7., 9.], y.numpy()) def testNestedDefunWithVariable(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) @def_function.function def g(x): x = v0 * x return x @def_function.function def f(x): x = g(v0 * x) return x x = constant_op.constant(3.0) y = f(x) self.assertEqual(75.0, y.numpy()) def testNestedDefunInGradientTape(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) @def_function.function def g(x): x = v0 * x return x @def_function.function def f(x): x = g(v0 * x) return x x = constant_op.constant(3.0) with backprop.GradientTape() as tape: y = f(x) dy = tape.gradient(y, v0) self.assertEqual(75, y.numpy()) self.assertEqual(30, dy.numpy()) def testNestedDefunInGradientTapeDifferentVars(self): with self.test_scope(): v0 = resource_variable_ops.ResourceVariable(5.0) v1 = resource_variable_ops.ResourceVariable(3.0) @def_function.function def g(x): x = v1 * x return x @def_function.function def f(x): x = g(v0 * x) return x x = constant_op.constant(3.0) with backprop.GradientTape(persistent=True) as tape: y = f(x) dy_v0 = tape.gradient(y, v0) dy_v1 = tape.gradient(y, v1) self.assertEqual(45, y.numpy()) self.assertEqual(9, dy_v0.numpy()) self.assertEqual(15, dy_v1.numpy()) def testWhileInDefun(self): with self.test_scope(): @def_function.function def f(start): c = lambda x: math_ops.less(x, 13.0) b = lambda x: math_ops.add(x, 1.0) return while_loop.while_loop(c, b, [start]) y = f(constant_op.constant(3.0)) self.assertEqual(13.0, y.numpy()) def testAutoGraphWhileInDefun(self): with self.test_scope(): @def_function.function def f(start): x = start while x < 13.0: x += 1.0 return x y = f(constant_op.constant(3.0)) self.assertEqual(13.0, y.numpy()) def testCondInDefun(self): with self.test_scope(): @def_function.function def f(pred, value): fn1 = lambda: math_ops.add(value, 1.0) fn2 = lambda: math_ops.subtract(value, 1.0) return cond.cond(pred, fn1, fn2) plus_one = f(constant_op.constant(True), constant_op.constant(10.0)) minus_one = f(constant_op.constant(False), constant_op.constant(10.0)) self.assertEqual(11.0, plus_one.numpy()) self.assertEqual(9.0, minus_one.numpy()) def testAutoGraphCondInDefun(self): with self.test_scope(): @def_function.function def f(pred, value): if pred: return value + 1.0 else: return value - 1.0 plus_one = f(constant_op.constant(True), constant_op.constant(10.0)) minus_one = f(constant_op.constant(False), constant_op.constant(10.0)) self.assertEqual(11.0, plus_one.numpy()) self.assertEqual(9.0, minus_one.numpy()) def testScanInDefun(self): with self.test_scope(): elems = constant_op.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='data') v = constant_op.constant(2.0, name='v') @def_function.function def f(y): # pylint: disable=unnecessary-lambda return functional_ops.scan( lambda a, x: math_ops.multiply(a, x), y, initializer=v) # pylint: enable=unnecessary-lambda r = f(elems) self.assertAllEqual([2., 4., 12., 48., 240., 1440.], self.evaluate(r)) def testFeedDeviceMemoryToOpExpectingHostMemory(self): @def_function.function def f(dims, value): return array_ops.fill(dims, value) with self.test_scope(): x = constant_op.constant([4], dtype=dtypes.int64) y = f(x, 3) self.assertAllEqual([3, 3, 3, 3], y) def testRequestNotToCompile(self): with self.test_scope(): def f(x): with ops.device('device:CPU:0'): y = 2.0 * x return x, y wholly_compiled_f = def_function.function(f) op_by_op_f = def_function.function(f, jit_compile=False) x = array_ops.identity([0.0, 2.0], name='data') # When function is wholly compiled, all outputs will be on the # device on which it is run. r_x, r_y = wholly_compiled_f(x) self.assertAllEqual([0.0, 2.0], r_x) self.assertAllEqual([0.0, 4.0], r_y) if context.executing_eagerly(): # backing_device is only available for eager tensors. self.assertRegex(r_x.backing_device, self.device) self.assertRegex(r_y.backing_device, self.device) # When function is executed op-by-op, requested devices will be # respected. r_x, r_y = op_by_op_f(x) self.assertAllEqual([0.0, 2.0], r_x) self.assertAllEqual([0.0, 4.0], r_y) if context.executing_eagerly(): # backing_device is only available for eager tensors. self.assertRegex(r_x.backing_device, self.device) self.assertRegex(r_y.backing_device, 'device:CPU:0')
EagerFunctionTest
python
huggingface__transformers
src/transformers/models/focalnet/modeling_focalnet.py
{ "start": 20010, "end": 23414 }
class ____(nn.Module): def __init__(self, config, grid_size): super().__init__() self.num_stages = len(config.depths) self.config = config self.stages = nn.ModuleList( [ FocalNetStage( config=config, index=i_layer, input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)), ) for i_layer in range(self.num_stages) ] ) self.gradient_checkpointing = False def forward( self, hidden_states: torch.Tensor, input_dimensions: tuple[int, int], output_hidden_states: Optional[bool] = False, output_hidden_states_before_downsampling: Optional[bool] = False, return_dict: Optional[bool] = True, ) -> Union[tuple, FocalNetEncoderOutput]: all_hidden_states = () if output_hidden_states else None all_reshaped_hidden_states = () if output_hidden_states else None if output_hidden_states: batch_size, _, hidden_size = hidden_states.shape # rearrange b (h w) c -> b c h w reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size) reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) all_hidden_states += (hidden_states,) all_reshaped_hidden_states += (reshaped_hidden_state,) for i, stage_module in enumerate(self.stages): stage_outputs = stage_module(hidden_states, input_dimensions) hidden_states = stage_outputs[0] hidden_states_before_downsampling = stage_outputs[1] output_dimensions = stage_outputs[2] input_dimensions = (output_dimensions[-2], output_dimensions[-1]) if output_hidden_states and output_hidden_states_before_downsampling: batch_size, _, hidden_size = hidden_states_before_downsampling.shape # rearrange b (h w) c -> b c h w # here we use the original (not downsampled) height and width reshaped_hidden_state = hidden_states_before_downsampling.view( batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size ) reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) all_hidden_states += (hidden_states_before_downsampling,) all_reshaped_hidden_states += (reshaped_hidden_state,) elif output_hidden_states and not output_hidden_states_before_downsampling: batch_size, _, hidden_size = hidden_states.shape # rearrange b (h w) c -> b c h w reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size) reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2) all_hidden_states += (hidden_states,) all_reshaped_hidden_states += (reshaped_hidden_state,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None) return FocalNetEncoderOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, reshaped_hidden_states=all_reshaped_hidden_states, ) @auto_docstring
FocalNetEncoder
python
django-compressor__django-compressor
compressor/css.py
{ "start": 104, "end": 2362 }
class ____(Compressor): output_mimetypes = {"text/css"} def split_contents(self): if self.split_content: return self.split_content self.media_nodes = [] for elem in self.parser.css_elems(): data = None elem_name = self.parser.elem_name(elem) elem_attribs = self.parser.elem_attribs(elem) if ( elem_name == "link" and "rel" in elem_attribs and elem_attribs["rel"].lower() == "stylesheet" ): basename = self.get_basename(elem_attribs["href"]) filename = self.get_filename(basename) data = (SOURCE_FILE, filename, basename, elem) elif elem_name == "style": data = (SOURCE_HUNK, self.parser.elem_content(elem), None, elem) if data: self.split_content.append(data) media = elem_attribs.get("media", None) # Append to the previous node if it had the same media type append_to_previous = ( self.media_nodes and self.media_nodes[-1][0] == media ) # and we are not just precompiling, otherwise create a new node. if append_to_previous and settings.COMPRESS_ENABLED: self.media_nodes[-1][1].split_content.append(data) else: node = self.copy(content=self.parser.elem_str(elem)) node.split_content.append(data) self.media_nodes.append((media, node)) return self.split_content def output(self, *args, **kwargs): if ( settings.COMPRESS_ENABLED or settings.COMPRESS_PRECOMPILERS or kwargs.get("forced", False) ): # Populate self.split_content self.split_contents() if hasattr(self, "media_nodes"): ret = [] for media, subnode in self.media_nodes: subnode.extra_context.update({"media": media}) ret.append(subnode.output(*args, **kwargs)) return "".join(ret) return super().output(*args, **kwargs)
CssCompressor
python
getsentry__sentry
src/sentry/testutils/fixtures.py
{ "start": 2849, "end": 34347 }
class ____: @cached_property def session(self): return Factories.create_session() @cached_property def projectkey(self): return self.create_project_key(project=self.project) @cached_property def user(self) -> User: try: return self.create_user( "admin@localhost", is_superuser=True, is_staff=True, is_sentry_app=False, ) except IntegrityError: with assume_test_silo_mode(SiloMode.CONTROL): return User.objects.get(email="admin@localhost") @cached_property def organization(self): # XXX(dcramer): ensure that your org slug doesnt match your team slug # and the same for your project slug return self.create_organization(name="baz", slug="baz", owner=self.user) @cached_property @assume_test_silo_mode(SiloMode.REGION) def team(self): team = self.create_team(organization=self.organization, name="foo", slug="foo") # XXX: handle legacy team fixture queryset = OrganizationMember.objects.filter(organization=self.organization) for om in queryset: OrganizationMemberTeam.objects.create(team=team, organizationmember=om, is_active=True) return team @cached_property def project(self): return self.create_project(name="Bar", slug="bar", teams=[self.team]) @cached_property def release(self): return self.create_release(project=self.project, version="foo-1.0") @cached_property def environment(self): return self.create_environment(name="development", project=self.project) @cached_property def group(self): return self.create_group(message="\u3053\u3093\u306b\u3061\u306f") @cached_property def event(self): return self.store_event( data={ "event_id": "a" * 32, "message": "\u3053\u3093\u306b\u3061\u306f", "timestamp": before_now(seconds=1).isoformat(), }, project_id=self.project.id, ) @cached_property @assume_test_silo_mode(SiloMode.REGION) def activity(self): return Activity.objects.create( group=self.group, project=self.project, type=ActivityType.NOTE.value, user_id=self.user.id, data={}, ) @cached_property @assume_test_silo_mode(SiloMode.CONTROL) def integration(self): integration = Integration.objects.create( provider=IntegrationProviderSlug.GITHUB.value, name="GitHub", external_id="github:1", metadata={ "access_token": "xxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx", "expires_at": (timezone.now() + timedelta(days=14)).isoformat(), }, ) integration.add_organization(self.organization, self.user) return integration @cached_property @assume_test_silo_mode(SiloMode.CONTROL) def organization_integration(self): return self.integration.add_organization(self.organization, self.user) def create_organization(self, *args, **kwargs): return Factories.create_organization(*args, **kwargs) def create_member(self, *args, **kwargs): return Factories.create_member(*args, **kwargs) def create_member_invite(self, *args, **kwargs): return Factories.create_member_invite(*args, **kwargs) def create_api_key(self, *args, **kwargs): return Factories.create_api_key(*args, **kwargs) def create_auth_provider(self, *args, **kwargs): return Factories.create_auth_provider(*args, **kwargs) def create_auth_identity(self, *args, **kwargs): return Factories.create_auth_identity(*args, **kwargs) def create_user_auth_token(self, *args, **kwargs): return Factories.create_user_auth_token(*args, **kwargs) def create_org_auth_token(self, *args, **kwargs): return Factories.create_org_auth_token(*args, **kwargs) def create_team_membership(self, *args, **kwargs): return Factories.create_team_membership(*args, **kwargs) def create_team(self, organization=None, **kwargs): if organization is None: organization = self.organization return Factories.create_team(organization=organization, **kwargs) def create_environment(self, project=None, **kwargs): if project is None: project = self.project return Factories.create_environment(project=project, **kwargs) def create_project(self, **kwargs) -> Project: if "teams" not in kwargs: kwargs["teams"] = [self.team] return Factories.create_project(**kwargs) def create_project_template(self, **kwargs) -> ProjectTemplate: return Factories.create_project_template(**kwargs) def create_project_bookmark(self, project=None, *args, **kwargs): if project is None: project = self.project return Factories.create_project_bookmark(project, *args, **kwargs) def create_project_key(self, project=None, *args, **kwargs): if project is None: project = self.project return Factories.create_project_key(project, *args, **kwargs) def create_project_rule(self, project=None, *args, **kwargs) -> Rule: if project is None: project = self.project return Factories.create_project_rule(project, *args, **kwargs) def create_slack_project_rule(self, project=None, *args, **kwargs): if project is None: project = self.project return Factories.create_slack_project_rule(project, *args, **kwargs) def create_release(self, project=None, *args, **kwargs): if project is None: project = self.project return Factories.create_release(project, *args, **kwargs) def create_group_release(self, project: Project | None = None, *args, **kwargs) -> GroupRelease: if project is None: project = self.project return Factories.create_group_release(project, *args, **kwargs) def create_release_file(self, release_id=None, file=None, name=None, dist_id=None): if release_id is None: release_id = self.release.id return Factories.create_release_file(release_id, file, name, dist_id) def create_artifact_bundle_zip(self, org=None, release=None, *args, **kwargs): return Factories.create_artifact_bundle_zip(org, release, *args, **kwargs) def create_release_archive(self, org=None, release=None, *args, **kwargs): if org is None: org = self.organization.slug if release is None: release = self.release.version return Factories.create_release_archive(org, release, *args, **kwargs) def create_artifact_bundle(self, org=None, *args, **kwargs): if org is None: org = self.organization return Factories.create_artifact_bundle(org, *args, **kwargs) def create_code_mapping(self, project=None, repo=None, organization_integration=None, **kwargs): if project is None: project = self.project if organization_integration is None: organization_integration = self.organization_integration return Factories.create_code_mapping(project, repo, organization_integration, **kwargs) def create_repo(self, project=None, *args, **kwargs): if project is None: project = self.project return Factories.create_repo(project, *args, **kwargs) def create_commit(self, *args, **kwargs): return Factories.create_commit(*args, **kwargs) def create_commit_author(self, *args, **kwargs): return Factories.create_commit_author(*args, **kwargs) def create_commit_file_change(self, *args, **kwargs): return Factories.create_commit_file_change(*args, **kwargs) def create_pull_request(self, *args, **kwargs): return Factories.create_pull_request(*args, **kwargs) def create_pull_request_comment(self, *args, **kwargs): return Factories.create_pull_request_comment(*args, **kwargs) def create_pull_request_commit(self, *args, **kwargs): return Factories.create_pull_request_commit(*args, **kwargs) def create_release_commit(self, *args, **kwargs): return Factories.create_release_commit(*args, **kwargs) def create_user(self, *args, **kwargs) -> User: return Factories.create_user(*args, **kwargs) def create_useremail(self, *args, **kwargs): return Factories.create_useremail(*args, **kwargs) def create_user_avatar(self, *args, **kwargs): return Factories.create_user_avatar(*args, **kwargs) def create_user_role(self, *args, **kwargs): return Factories.create_user_role(*args, **kwargs) def create_usersocialauth( self, user: User | None = None, provider: str | None = None, uid: str | None = None, extra_data: dict[str, Any] | None = None, ): if not user: user = self.user return Factories.create_usersocialauth( user=user, provider=provider, uid=uid, extra_data=extra_data ) def store_event(self, *args, **kwargs) -> Event: return Factories.store_event(*args, **kwargs) def create_tempest_credentials(self, project: Project, *args, **kwargs) -> TempestCredentials: return Factories.create_tempest_credentials(project, *args, **kwargs) def create_group(self, project=None, *args, **kwargs): if project is None: project = self.project return Factories.create_group(project, *args, **kwargs) def create_group_activity(self, group=None, *args, **kwargs): if group is None: group = self.group return Factories.create_group_activity(group, *args, **kwargs) def create_n_groups_with_hashes( self, number_of_groups: int, project: Project, group_type: int | None = None ) -> list[Group]: groups = [] for _ in range(number_of_groups): if group_type: group = self.create_group( project=project, status=GroupStatus.RESOLVED, type=group_type ) else: group = self.create_group(project=project, status=GroupStatus.RESOLVED) hash = uuid4().hex GroupHash.objects.create(project=group.project, hash=hash, group=group) groups.append(group) return groups def create_file(self, **kwargs): return Factories.create_file(**kwargs) def create_data_forwarder(self, organization=None, *args, **kwargs): if organization is None: organization = self.organization return Factories.create_data_forwarder(organization, *args, **kwargs) def create_data_forwarder_project(self, data_forwarder=None, project=None, **kwargs): if project is None: project = self.project return Factories.create_data_forwarder_project(data_forwarder, project, **kwargs) def create_file_from_path(self, *args, **kwargs): return Factories.create_file_from_path(*args, **kwargs) def create_dif_file(self, project: Project | None = None, *args, **kwargs): if project is None: project = self.project return Factories.create_dif_file(project, *args, **kwargs) def create_dif_from_path(self, project=None, *args, **kwargs): if project is None: project = self.project return Factories.create_dif_from_path(project=project, *args, **kwargs) def add_user_permission(self, *args, **kwargs): return Factories.add_user_permission(*args, **kwargs) def create_sentry_app(self, *args, **kwargs): return Factories.create_sentry_app(*args, **kwargs) def create_sentry_app_avatar(self, *args, **kwargs): return Factories.create_sentry_app_avatar(*args, **kwargs) def create_internal_integration(self, *args, **kwargs): return Factories.create_internal_integration(*args, **kwargs) def create_internal_integration_token(self, *args, **kwargs): return Factories.create_internal_integration_token(*args, **kwargs) def create_sentry_app_installation(self, *args, **kwargs): return Factories.create_sentry_app_installation(*args, **kwargs) def create_sentry_app_installation_for_provider(self, *args, **kwargs): return Factories.create_sentry_app_installation_for_provider(*args, **kwargs) def create_stacktrace_link_schema(self, *args, **kwargs): return Factories.create_stacktrace_link_schema(*args, **kwargs) def create_issue_link_schema(self, *args, **kwargs): return Factories.create_issue_link_schema(*args, **kwargs) def create_alert_rule_action_schema(self, *args, **kwargs): return Factories.create_alert_rule_action_schema(*args, **kwargs) def create_sentry_app_feature(self, *args, **kwargs): return Factories.create_sentry_app_feature(*args, **kwargs) def create_doc_integration(self, *args, **kwargs): return Factories.create_doc_integration(*args, **kwargs) def create_doc_integration_features(self, *args, **kwargs): return Factories.create_doc_integration_features(*args, **kwargs) def create_doc_integration_avatar(self, *args, **kwargs): return Factories.create_doc_integration_avatar(*args, **kwargs) def create_service_hook(self, *args, **kwargs): return Factories.create_service_hook(*args, **kwargs) def create_userreport(self, *args, **kwargs): return Factories.create_userreport(*args, **kwargs) def create_platform_external_issue(self, *args, **kwargs): return Factories.create_platform_external_issue(*args, **kwargs) def create_integration_external_issue(self, *args, **kwargs): return Factories.create_integration_external_issue(*args, **kwargs) def create_integration_external_project(self, *args, **kwargs): return Factories.create_integration_external_project(*args, **kwargs) def create_incident(self, organization=None, projects=None, *args, **kwargs): if not organization: organization = self.organization if projects is None: projects = [self.project] return Factories.create_incident(organization, projects, *args, **kwargs) def create_incident_activity(self, *args, **kwargs): return Factories.create_incident_activity(*args, **kwargs) def create_incident_trigger(self, incident, alert_rule_trigger, status): return Factories.create_incident_trigger(incident, alert_rule_trigger, status=status) def create_alert_rule(self, organization=None, projects=None, *args, **kwargs) -> AlertRule: if not organization: organization = self.organization if projects is None: projects = [self.project] return Factories.create_alert_rule(organization, projects, *args, **kwargs) def create_alert_rule_trigger(self, alert_rule=None, *args, **kwargs): if not alert_rule: alert_rule = self.create_alert_rule() return Factories.create_alert_rule_trigger(alert_rule, *args, **kwargs) def create_alert_rule_trigger_action( self, alert_rule_trigger=None, target_identifier=None, triggered_for_incident=None, *args, **kwargs, ): if not alert_rule_trigger: alert_rule_trigger = self.create_alert_rule_trigger() if not target_identifier: target_identifier = str(self.user.id) if triggered_for_incident is not None: Factories.create_incident_trigger(triggered_for_incident, alert_rule_trigger) return Factories.create_alert_rule_trigger_action( alert_rule_trigger, target_identifier=target_identifier, **kwargs ) def create_notification_action(self, organization=None, projects=None, **kwargs): return Factories.create_notification_action( organization=organization, projects=projects, **kwargs ) def create_notification_settings_provider(self, *args, **kwargs): return Factories.create_notification_settings_provider(*args, **kwargs) def create_user_option(self, *args, **kwargs): return Factories.create_user_option(*args, **kwargs) def create_monitor(self, **kwargs): if "owner_user_id" not in kwargs: kwargs["owner_user_id"] = self.user.id if "project" not in kwargs: project_id = self.project.id else: project_id = kwargs.pop("project").id if "organization" in kwargs: organization = kwargs.pop("organization") else: organization = self.organization return Monitor.objects.create( organization_id=organization.id, project_id=project_id, config={ "schedule": "* * * * *", "schedule_type": ScheduleType.CRONTAB, "checkin_margin": None, "max_runtime": None, }, **kwargs, ) def create_monitor_environment(self, **kwargs): return MonitorEnvironment.objects.create(**kwargs) def create_monitor_incident(self, **kwargs): return MonitorIncident.objects.create(**kwargs) def create_monitor_checkin(self, **kwargs): return MonitorCheckIn.objects.create(**kwargs) def create_external_user(self, user=None, organization=None, integration=None, **kwargs): if not user: user = self.user if not organization: organization = self.organization # Force creation. if not integration: integration = self.integration return Factories.create_external_user( user=user, organization=organization, integration_id=integration.id, **kwargs ) def create_external_team(self, team=None, integration=None, **kwargs): if not team: team = self.team if not integration: integration = self.integration return Factories.create_external_team( team=team, organization=team.organization, integration_id=integration.id, **kwargs ) def create_data_access_grant(self, **kwargs): return Factories.create_data_access_grant(**kwargs) def create_codeowners(self, project=None, code_mapping=None, **kwargs): if not project: project = self.project if not code_mapping: self.repo = self.create_repo(self.project) code_mapping = self.create_code_mapping(self.project, self.repo) return Factories.create_codeowners(project=project, code_mapping=code_mapping, **kwargs) def create_slack_integration( self, organization: Organization, external_id: str = "TXXXXXXX1", user: RpcUser | User | None = None, identity_external_id: str = "UXXXXXXX1", **kwargs: Any, ): if user is None: with assume_test_silo_mode(SiloMode.REGION): user = organization.get_default_owner() integration = Factories.create_slack_integration( organization=organization, external_id=external_id, **kwargs ) idp = Factories.create_identity_provider(integration=integration) Factories.create_identity(user, idp, identity_external_id) return integration def create_integration( self, organization: Organization, external_id: str, oi_params: Mapping[str, Any] | None = None, **kwargs: Any, ) -> Integration: """Create an integration and add an organization.""" return Factories.create_integration(organization, external_id, oi_params, **kwargs) def create_provider_integration(self, **integration_params: Any) -> Integration: """Create an integration tied to a provider but no particular organization.""" return Factories.create_provider_integration(**integration_params) def create_provider_integration_for( self, organization: Organization | RpcOrganization, user: User | RpcUser | None, **integration_params: Any, ) -> tuple[Integration, OrganizationIntegration]: """Create an integration tied to a provider, then add an organization.""" return Factories.create_provider_integration_for(organization, user, **integration_params) def create_identity_integration( self, user: User | RpcUser, organization: Organization | RpcOrganization, integration_params: Mapping[Any, Any], identity_params: Mapping[Any, Any], ) -> tuple[Integration, OrganizationIntegration, Identity, IdentityProvider]: return Factories.create_identity_integration( user, organization, integration_params, identity_params ) def create_organization_integration(self, **integration_params: Any) -> OrganizationIntegration: """Create an OrganizationIntegration entity.""" return Factories.create_organization_integration(**integration_params) def create_identity(self, *args, **kwargs): return Factories.create_identity(*args, **kwargs) def create_identity_provider( self, integration: Integration | None = None, config: dict[str, Any] | None = None, **kwargs: Any, ) -> IdentityProvider: return Factories.create_identity_provider(integration=integration, config=config, **kwargs) def create_group_history(self, *args, **kwargs): if "user_id" not in kwargs and "team" not in kwargs and "team_id" not in kwargs: kwargs["user_id"] = self.user.id return Factories.create_group_history(*args, **kwargs) def create_comment(self, *args, **kwargs): return Factories.create_comment(*args, **kwargs) def create_saved_search(self, *args, **kwargs): return Factories.create_saved_search(*args, **kwargs) def create_organization_mapping(self, *args, **kwargs): return Factories.create_org_mapping(*args, **kwargs) def create_basic_auth_header(self, *args, **kwargs) -> bytes: return Factories.create_basic_auth_header(*args, **kwargs) def snooze_rule(self, *args, **kwargs): return Factories.snooze_rule(*args, **kwargs) def create_request_access(self, *args, **kwargs): return Factories.create_request_access(*args, **kwargs) def create_webhook_payload(self, *args, **kwargs): return Factories.create_webhook_payload(*args, **kwargs) def create_dashboard(self, *args, **kwargs): return Factories.create_dashboard(*args, **kwargs) def create_dashboard_widget(self, *args, **kwargs): return Factories.create_dashboard_widget(*args, **kwargs) def create_dashboard_widget_query(self, *args, **kwargs): return Factories.create_dashboard_widget_query(*args, **kwargs) def create_workflow(self, *args, **kwargs) -> Workflow: return Factories.create_workflow(*args, **kwargs) def create_data_source(self, *args, **kwargs) -> DataSource: return Factories.create_data_source(*args, **kwargs) def create_data_condition( self, comparison="10", type=Condition.EQUAL, condition_result=None, condition_group=None, **kwargs, ): if condition_result is None: condition_result = str(DetectorPriorityLevel.HIGH.value) if condition_group is None: condition_group = self.create_data_condition_group() return Factories.create_data_condition( comparison=comparison, type=type, condition_result=condition_result, condition_group=condition_group, **kwargs, ) def create_detector( self, project: Project | None = None, type: str | None = ErrorGroupType.slug, *args, **kwargs, ) -> Detector: if project is None: project = self.create_project(organization=self.organization) return Factories.create_detector(project=project, type=type, *args, **kwargs) def create_detector_state(self, *args, **kwargs) -> DetectorState: return Factories.create_detector_state(*args, **kwargs) def create_data_source_detector(self, *args, **kwargs): return Factories.create_data_source_detector(*args, **kwargs) def create_data_condition_group(self, organization=None, **kwargs): if organization is None: organization = self.organization return Factories.create_data_condition_group(organization=organization, **kwargs) def create_data_condition_group_action(self, *args, **kwargs): return Factories.create_data_condition_group_action(*args, **kwargs) def create_detector_workflow(self, *args, **kwargs): return Factories.create_detector_workflow(*args, **kwargs) def create_detector_group(self, *args, **kwargs): return Factories.create_detector_group(*args, **kwargs) def create_alert_rule_detector(self, *args, **kwargs): # TODO: this is only needed during the ACI migration return Factories.create_alert_rule_detector(*args, **kwargs) def create_action_alert_rule_trigger_action(self, *args, **kwargs): # TODO: this is only needed during the ACI migration return Factories.create_action_alert_rule_trigger_action(*args, **kwargs) def create_alert_rule_workflow(self, *args, **kwargs): # TODO: this is only needed during the ACI migration return Factories.create_alert_rule_workflow(*args, **kwargs) def create_incident_group_open_period(self, *args, **kwargs): # TODO: this is only needed during the ACI migration return Factories.create_incident_group_open_period(*args, **kwargs) def create_workflow_data_condition_group(self, *args, **kwargs): return Factories.create_workflow_data_condition_group(*args, **kwargs) # workflow_engine.models.action def create_action(self, *args, **kwargs): return Factories.create_action(*args, **kwargs) def create_uptime_subscription( self, type: str = "test", subscription_id: str | None = None, status: UptimeSubscription.Status = UptimeSubscription.Status.ACTIVE, url: str | None = None, host_provider_id="TEST", host_provider_name="TEST", url_domain="sentry", url_domain_suffix="io", interval_seconds=60, timeout_ms=100, method="GET", headers=None, body=None, date_updated: None | datetime = None, trace_sampling: bool = False, region_slugs: list[str] | None = None, ) -> UptimeSubscription: if date_updated is None: date_updated = timezone.now() if headers is None: headers = [] if region_slugs is None: region_slugs = [] subscription = Factories.create_uptime_subscription( type=type, subscription_id=subscription_id, status=status, url=url, url_domain=url_domain, url_domain_suffix=url_domain_suffix, host_provider_id=host_provider_id, host_provider_name=host_provider_name, interval_seconds=interval_seconds, timeout_ms=timeout_ms, date_updated=date_updated, method=method, headers=headers, body=body, trace_sampling=trace_sampling, ) for region_slug in region_slugs: self.create_uptime_subscription_region(subscription, region_slug) return subscription def create_uptime_subscription_region( self, subscription: UptimeSubscription, region_slug: str, mode: UptimeSubscriptionRegion.RegionMode = UptimeSubscriptionRegion.RegionMode.ACTIVE, ): Factories.create_uptime_subscription_region(subscription, region_slug, mode) def create_uptime_detector( self, project: Project | None = None, env: Environment | None = None, uptime_subscription: UptimeSubscription | None = None, status: int = ObjectStatus.ACTIVE, enabled: bool = True, mode=UptimeMonitorMode.AUTO_DETECTED_ACTIVE, name: str | None = None, owner: User | Team | None = None, id: int | None = None, recovery_threshold: int = DEFAULT_RECOVERY_THRESHOLD, downtime_threshold: int = DEFAULT_DOWNTIME_THRESHOLD, detector_state: DetectorPriorityLevel = DetectorPriorityLevel.OK, ) -> Detector: if project is None: project = self.project if env is None: env = self.environment actor = Actor.from_object(owner) if owner else None owner_team_id = None owner_user_id = None if actor: if actor.is_team: owner_team_id = actor.id elif actor.is_user: owner_user_id = actor.id if uptime_subscription is None: uptime_subscription = self.create_uptime_subscription() data_source = Factories.create_data_source( type=DATA_SOURCE_UPTIME_SUBSCRIPTION, organization=project.organization, source_id=str(uptime_subscription.id), ) condition_group = Factories.create_data_condition_group( organization=project.organization, ) Factories.create_data_condition( comparison=CHECKSTATUS_FAILURE, type=Condition.EQUAL, condition_result=DetectorPriorityLevel.HIGH, condition_group=condition_group, ) Factories.create_data_condition( comparison=CHECKSTATUS_SUCCESS, type=Condition.EQUAL, condition_result=DetectorPriorityLevel.OK, condition_group=condition_group, ) env_name = env.name if env else None detector = Factories.create_detector( id=id, type=GROUP_TYPE_UPTIME_DOMAIN_CHECK_FAILURE, project=project, name=name, status=status, enabled=enabled, owner_user_id=owner_user_id, owner_team_id=owner_team_id, config={ "environment": env_name, "mode": mode, "recovery_threshold": recovery_threshold, "downtime_threshold": downtime_threshold, }, workflow_condition_group=condition_group, ) Factories.create_data_source_detector( data_source=data_source, detector=detector, ) # Create DetectorState with the provided state # Infer is_triggered based on whether state is HIGH Factories.create_detector_state( detector=detector, state=detector_state, is_triggered=detector_state == DetectorPriorityLevel.HIGH, ) return detector @pytest.fixture(autouse=True) def _init_insta_snapshot(self, insta_snapshot): self.insta_snapshot = insta_snapshot
Fixtures
python
keras-team__keras
keras/src/backend/torch/export.py
{ "start": 246, "end": 4909 }
class ____: def _track_layer(self, layer): raise NotImplementedError( "`track` is not supported for `Layer`s and `Model`s in the torch " "backend. Use `track_and_add_endpoint` instead." ) def add_endpoint(self, name, fn, input_signature, **kwargs): raise NotImplementedError( "`add_endpoint` is not supported for `Layer`s and `Model`s in the " "torch backend. Use `track_and_add_endpoint` instead." ) def track_and_add_endpoint(self, name, resource, input_signature, **kwargs): # Disable false alarms related to lifting parameters. warnings.filterwarnings("ignore", message=".*created when tracing.*") warnings.filterwarnings( "ignore", message=".*Unable to find the path of the module.*" ) if not isinstance(resource, torch.nn.Module): raise TypeError( "`resource` must be an instance of `torch.nn.Module`. " f"Received: resource={resource} (of type {type(resource)})" ) sample_inputs = tree.map_structure( lambda x: convert_spec_to_tensor(x, replace_none_number=1), input_signature, ) sample_inputs = tuple(sample_inputs) # Ref: torch_xla.tf_saved_model_integration # TODO: Utilize `dynamic_shapes` exported = torch.export.export( resource, sample_inputs, dynamic_shapes=None, strict=False ) options = torch_xla.stablehlo.StableHLOExportOptions( override_tracing_arguments=sample_inputs ) stablehlo_model = torch_xla.stablehlo.exported_program_to_stablehlo( exported, options ) state_dict_keys = list(stablehlo_model._bundle.state_dict.keys()) # Remove unused variables. for k in state_dict_keys: if "lifted" not in k: stablehlo_model._bundle.state_dict.pop(k) bundle = copy.deepcopy(stablehlo_model._bundle) bundle.state_dict = { k: tf.Variable(v, trainable=False, name=k) for k, v in bundle.state_dict.items() } bundle.additional_constants = [ tf.Variable(v, trainable=False) for v in bundle.additional_constants ] # Track variables in `bundle` for `write_out`. self._tf_trackable.variables += ( list(bundle.state_dict.values()) + bundle.additional_constants ) # Ref: torch_xla.tf_saved_model_integration.save_stablehlo_graph_as_tf def make_tf_function(func, bundle): from tensorflow.compiler.tf2xla.python import xla as tfxla def _get_shape_with_dynamic(signature): shape = copy.copy(signature.shape) for i in signature.dynamic_dims: shape[i] = None return shape def _extract_call_parameters(args, meta, bundle): call_args = [] if meta.input_pytree_spec is not None: args = tree.flatten(args) for loc in meta.input_locations: if loc.type_ == torch_xla.stablehlo.VariableType.PARAMETER: call_args.append(bundle.state_dict[loc.name]) elif loc.type_ == torch_xla.stablehlo.VariableType.CONSTANT: call_args.append( bundle.additional_constants[loc.position] ) else: call_args.append(args[loc.position]) return call_args def inner(*args): Touts = [sig.dtype for sig in func.meta.output_signature] Souts = [ _get_shape_with_dynamic(sig) for sig in func.meta.output_signature ] call_args = _extract_call_parameters(args, func.meta, bundle) results = tfxla.call_module( tuple(call_args), version=5, Tout=Touts, # dtype information Sout=Souts, # Shape information function_list=[], module=func.bytecode, ) if len(Souts) == 1: results = results[0] return results return inner decorated_fn = tf.function( make_tf_function( stablehlo_model._bundle.stablehlo_funcs[0], bundle ), input_signature=input_signature, ) return decorated_fn
TorchExportArchive
python
walkccc__LeetCode
solutions/931. Minimum Falling Path Sum/931.py
{ "start": 0, "end": 298 }
class ____: def minFallingPathSum(self, A: list[list[int]]) -> int: n = len(A) for i in range(1, n): for j in range(n): mn = math.inf for k in range(max(0, j - 1), min(n, j + 2)): mn = min(mn, A[i - 1][k]) A[i][j] += mn return min(A[-1])
Solution
python
kamyu104__LeetCode-Solutions
Python/shortest-path-in-a-grid-with-obstacles-elimination.py
{ "start": 76, "end": 1479 }
class ____(object): def shortestPath(self, grid, k): """ :type grid: List[List[int]] :type k: int :rtype: int """ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def dot(a, b): return a[0]*b[0]+a[1]*b[1] def g(a, b): return abs(a[0]-b[0])+abs(a[1]-b[1]) def a_star(grid, b, t, k): f, dh = g(b, t), 2 closer, detour = [(b, k)], [] lookup = {} while closer or detour: if not closer: f += dh closer, detour = detour, closer b, k = closer.pop() if b == t: return f if b in lookup and lookup[b] >= k: continue lookup[b] = k for dx, dy in directions: nb = (b[0]+dx, b[1]+dy) if not (0 <= nb[0] < len(grid) and 0 <= nb[1] < len(grid[0]) and (grid[nb[0]][nb[1]] == 0 or k > 0) and (nb not in lookup or lookup[nb] < k)): continue (closer if dot((dx, dy), (t[0]-b[0], t[1]-b[1])) > 0 else detour).append((nb, k-int(grid[nb[0]][nb[1]] == 1))) return -1 return a_star(grid, (0, 0), (len(grid)-1, len(grid[0])-1), k)
Solution
python
Lightning-AI__lightning
src/lightning/pytorch/strategies/deepspeed.py
{ "start": 3014, "end": 42084 }
class ____(DDPStrategy): strategy_name = "deepspeed" DEEPSPEED_ENV_VAR = "PL_DEEPSPEED_CONFIG_PATH" def __init__( self, accelerator: Optional["pl.accelerators.Accelerator"] = None, zero_optimization: bool = True, stage: int = 2, remote_device: Optional[str] = None, offload_optimizer: bool = False, offload_parameters: bool = False, offload_params_device: str = "cpu", nvme_path: str = "/local_nvme", params_buffer_count: int = 5, params_buffer_size: int = 100_000_000, max_in_cpu: int = 1_000_000_000, offload_optimizer_device: str = "cpu", optimizer_buffer_count: int = 4, block_size: int = 1048576, queue_depth: int = 8, single_submit: bool = False, overlap_events: bool = True, thread_count: int = 1, pin_memory: bool = False, sub_group_size: int = 1_000_000_000_000, contiguous_gradients: bool = True, overlap_comm: bool = True, allgather_partitions: bool = True, reduce_scatter: bool = True, allgather_bucket_size: int = 200_000_000, reduce_bucket_size: int = 200_000_000, zero_allow_untested_optimizer: bool = True, logging_batch_size_per_gpu: Union[str, int] = "auto", config: Optional[Union[_PATH, dict[str, Any]]] = None, logging_level: int = logging.WARN, parallel_devices: Optional[list[torch.device]] = None, cluster_environment: Optional[ClusterEnvironment] = None, loss_scale: float = 0, initial_scale_power: int = 16, loss_scale_window: int = 1000, hysteresis: int = 2, min_loss_scale: int = 1, partition_activations: bool = False, cpu_checkpointing: bool = False, contiguous_memory_optimization: bool = False, synchronize_checkpoint_boundary: bool = False, load_full_weights: bool = False, precision_plugin: Optional[Precision] = None, process_group_backend: Optional[str] = None, timeout: Optional[timedelta] = default_pg_timeout, exclude_frozen_parameters: bool = False, ) -> None: """Provides capabilities to run training using the DeepSpeed library, with training optimizations for large billion parameter models. *For more information:* :ref:`deepspeed_advanced`. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. Defaults have been set to enable ZeRO-Offload and some have been taken from the link below. These defaults have been set generally, but may require tuning for optimum performance based on your model size. *For more information:* https://www.deepspeed.ai/docs/config-json/#zero-optimizations-for-fp16-training. Arguments: zero_optimization: Enable ZeRO optimization. This is compatible with either `precision="16-mixed"` or `precision="bf16-mixed"`. stage: Different stages of the ZeRO Optimizer. 0 is disabled, 1 is optimizer state partitioning, 2 is optimizer+gradient state partitioning, 3 is optimizer+gradient_parameter partitioning using the infinity engine. remote_device: Device to instantiate the model on initially (``cpu`` or ``nvme``). Defaults to GPU. offload_optimizer: Enable offloading optimizer memory and computation to CPU or NVMe based on ``offload_optimizer_device``. offload_parameters: When using ZeRO Stage 3, Enable offloading parameter memory and computation to CPU or NVMe based on ``offload_params_device``. offload_params_device: When offloading parameters choose the device to offload to, ``cpu`` or ``nvme``. offload_optimizer_device: When offloading optimizer state choose the device to offload to, ``cpu`` or ``nvme``. params_buffer_count: Number of buffers in buffer pool for parameter offloading when ``offload_params_device`` is ``nvme``. params_buffer_size: Size of buffers in buffer pool for parameter offloading when ``offload_params_device`` is ``nvme``. max_in_cpu: Number of parameter elements to maintain in CPU memory when offloading to NVMe is enabled. nvme_path: Filesystem path for NVMe device for optimizer/parameter state offloading. optimizer_buffer_count: Number of buffers in buffer pool for optimizer state offloading when ``offload_optimizer_device`` is set to ``nvme``. This should be at least the number of states maintained per parameter by the optimizer. For example, Adam optimizer has 4 states (parameter, gradient, momentum, and variance). block_size: When using NVMe Offloading, the I/O block size in bytes. queue_depth: When using NVMe Offloading, the I/O queue depth. single_submit: When using NVMe Offloading, submit requests to storage device as multiple individual requests, as opposed to one block of requests. overlap_events: When using NVMe Offloading, submit requests to storage device in an overlapped fashion without waiting for completion of earlier requests. thread_count: When using NVMe Offloading, Intra-request parallelism for each read/write submitted by a user thread. pin_memory: When using ZeRO stage 3, pin optimizer state memory on CPU. This could boost throughput at the cost of extra memory overhead. sub_group_size: When using ZeRO stage 3, defines the number of parameters within a sub group to offload at a time. Smaller numbers require more communication, but improve memory efficiency. contiguous_gradients: Copies gradients to a continuous buffer as they are produced. Avoids memory fragmentation during backwards. Useful when training large models. overlap_comm: Overlap the reduction (synchronization) of gradients with the backwards computation. This is a speed optimization when training across multiple GPUs/machines. allgather_partitions: All gather updated parameters at the end of training step, instead of using a series of broadcast collectives. reduce_scatter: Use reduce/scatter instead of allreduce to average gradients. allgather_bucket_size: Number of elements to allgather at once. Used to limit the memory required for larger model sizes, with a tradeoff with speed. reduce_bucket_size: Number of elements to reduce at once. Used to limit the memory required for larger model sizes, with a tradeoff with speed. zero_allow_untested_optimizer: Allow untested optimizers to be used with ZeRO. Currently only Adam is a DeepSpeed supported optimizer when using ZeRO. logging_batch_size_per_gpu: Config used in DeepSpeed to calculate verbose timing for logging on a per sample per second basis (only displayed if logging=logging.INFO). If set to "auto", the strategy tries to infer this from the train DataLoader's BatchSampler, else defaults to 1. To obtain accurate logs when using datasets that do not support batch samplers, set this to the actual per gpu batch size (trainer.batch_size). config: Pass in a deepspeed formatted config dict, or path to a deepspeed config: https://www.deepspeed.ai/docs/config-json. All defaults will be ignored if a config is passed in. logging_level: Set logging level for deepspeed. loss_scale: Loss scaling value for FP16 training. 0.0 results in dynamic loss scaling, otherwise static. initial_scale_power: Power of the initial dynamic loss scale value. Loss scale is computed by ``2^initial_scale_power``. loss_scale_window: Window in which to raise/lower the dynamic FP16 loss scaling value. hysteresis: FP16 Delay shift in Dynamic Loss scaling. min_loss_scale: The minimum FP16 dynamic loss scaling value. partition_activations: Enables partition activation when used with ZeRO stage 3 and model parallelism. Still requires you to wrap your forward functions in deepspeed.checkpointing.checkpoint. See `deepspeed tutorial <https://www.deepspeed.ai/tutorials/megatron/#deepspeed-activation-checkpoints-optional>`_. cpu_checkpointing: Offloads partitioned activations to CPU if ``partition_activations`` is enabled. contiguous_memory_optimization: Copies partitioned activations so that they are contiguous in memory. Not supported by all models. synchronize_checkpoint_boundary: Insert :func:`torch.cuda.synchronize` at each checkpoint boundary. load_full_weights: True when loading a single checkpoint file containing the model state dict when using ZeRO Stage 3. This differs from the DeepSpeed checkpoint which contains shards per worker. exclude_frozen_parameters: Exclude frozen parameters when saving checkpoints. """ if not _DEEPSPEED_AVAILABLE: raise MisconfigurationException( "To use the `DeepSpeedStrategy`, you must have DeepSpeed installed." " Install it by running `pip install -U deepspeed`." ) if _TORCH_GREATER_EQUAL_2_6 and not _DEEPSPEED_GREATER_EQUAL_0_16: # Starting with PyTorch 2.6, `torch.load` defaults to `weights_only=True` when loading full checkpoints. # DeepSpeed added support for this behavior in version 0.16.0. import deepspeed deepspeed_version = deepspeed.__version__ raise ImportError( f"PyTorch >= 2.6 requires DeepSpeed >= 0.16.0. " f"Detected DeepSpeed version: {deepspeed_version}. " "Please upgrade by running `pip install -U 'deepspeed>=0.16.0'`." ) super().__init__( accelerator=accelerator, parallel_devices=parallel_devices, cluster_environment=cluster_environment, precision_plugin=precision_plugin, process_group_backend=process_group_backend, ) self._timeout: Optional[timedelta] = timeout self.config = self._load_config(config) if self.config is None: # User has not overridden config, set defaults self.config = self._create_default_config( zero_optimization, zero_allow_untested_optimizer, logging_batch_size_per_gpu, offload_optimizer=offload_optimizer, offload_parameters=offload_parameters, nvme_path=nvme_path, offload_params_device=offload_params_device, params_buffer_count=params_buffer_count, params_buffer_size=params_buffer_size, max_in_cpu=max_in_cpu, pin_memory=pin_memory, offload_optimizer_device=offload_optimizer_device, optimizer_buffer_count=optimizer_buffer_count, block_size=block_size, queue_depth=queue_depth, single_submit=single_submit, overlap_events=overlap_events, thread_count=thread_count, partition_activations=partition_activations, cpu_checkpointing=cpu_checkpointing, contiguous_memory_optimization=contiguous_memory_optimization, synchronize_checkpoint_boundary=synchronize_checkpoint_boundary, stage=stage, contiguous_gradients=contiguous_gradients, overlap_comm=overlap_comm, allgather_partitions=allgather_partitions, reduce_scatter=reduce_scatter, allgather_bucket_size=allgather_bucket_size, reduce_bucket_size=reduce_bucket_size, sub_group_size=sub_group_size, ) import deepspeed self._config_initialized = False deepspeed.utils.logging.logger.setLevel(logging_level) self.remote_device = remote_device self.load_full_weights = load_full_weights self.exclude_frozen_parameters = exclude_frozen_parameters # default FP16 parameters. self.loss_scale = loss_scale self.initial_scale_power = initial_scale_power self.loss_scale_window = loss_scale_window self.hysteresis = hysteresis self.min_loss_scale = min_loss_scale @override def setup_environment(self) -> None: if not isinstance(self.accelerator, CUDAAccelerator): raise RuntimeError( f"The DeepSpeed strategy is only supported on CUDA GPUs but `{self.accelerator.__class__.__name__}`" " is used." ) super().setup_environment() @override def setup_distributed(self) -> None: assert self.parallel_devices is not None _validate_device_index_selection(self.parallel_devices) reset_seed() self.set_world_ranks() self._init_deepspeed_distributed() @override def setup(self, trainer: "pl.Trainer") -> None: self._init_config_if_needed() assert self.accelerator is not None self.accelerator.setup(trainer) assert self.model is not None self.model = self.precision_plugin.convert_module(self.model) self.model = self._setup_model(self.model) if trainer.state.fn == TrainerFn.FITTING: self.setup_optimizers(trainer) self.setup_precision_plugin() if trainer.state.fn == TrainerFn.FITTING: _optimizers_to_device(self.optimizers, self.root_device) self.init_deepspeed() self.barrier() def _init_deepspeed_distributed(self) -> None: import deepspeed assert self.cluster_environment is not None if platform.system() != "Windows": # do not set env variables on windows, allow deepspeed to control setup self._set_node_environment_variables() log.info( "initializing deepspeed distributed: " f"GLOBAL_RANK: {self.global_rank}, " f"MEMBER: {self.global_rank + 1}/{self.world_size}" ) self._process_group_backend = self._get_process_group_backend() deepspeed.init_distributed( self._process_group_backend, distributed_port=self.cluster_environment.main_port, timeout=self._timeout ) def _set_node_environment_variables(self) -> None: assert self.cluster_environment is not None os.environ["MASTER_ADDR"] = self.cluster_environment.main_address os.environ["MASTER_PORT"] = str(self.cluster_environment.main_port) os.environ["RANK"] = str(self.global_rank) os.environ["WORLD_SIZE"] = str(self.world_size) os.environ["LOCAL_RANK"] = str(self.local_rank) @property @override def restore_checkpoint_after_setup(self) -> bool: return True @override def _setup_model_and_optimizers( self, model: Module, optimizers: list[Optimizer] ) -> tuple["deepspeed.DeepSpeedEngine", list[Optimizer]]: """Setup a model and multiple optimizers together. Currently only a single optimizer is supported. Return: The model wrapped into a :class:`deepspeed.DeepSpeedEngine` and a list with a single deepspeed optimizer. """ if len(optimizers) != 1: raise ValueError( f"Currently only one optimizer is supported with DeepSpeed. Got {len(optimizers)} optimizers instead." ) # train_micro_batch_size_per_gpu is used for throughput logging purposes # normally we set this to the batch size, but it is not available here unless the user provides it # as part of the config assert self.config is not None self.config.setdefault("train_micro_batch_size_per_gpu", 1) self.model, optimizer = self._setup_model_and_optimizer(model, optimizers[0]) self._set_deepspeed_activation_checkpointing() return self.model, [optimizer] def _setup_model_and_optimizer( self, model: Module, optimizer: Optional[Optimizer], lr_scheduler: Optional[Union[LRScheduler, ReduceLROnPlateau]] = None, ) -> tuple["deepspeed.DeepSpeedEngine", Optimizer]: """Initialize one model and one optimizer with an optional learning rate scheduler. This calls ``deepspeed.initialize`` internally. """ import deepspeed model_parameters = filter(lambda p: p.requires_grad, model.parameters()) deepspeed_engine, deepspeed_optimizer, _, _ = deepspeed.initialize( args=argparse.Namespace(device_rank=self.root_device.index), config=self.config, model=model, model_parameters=model_parameters, optimizer=optimizer, lr_scheduler=lr_scheduler, dist_init_required=False, ) return deepspeed_engine, deepspeed_optimizer def init_deepspeed(self) -> None: assert self.lightning_module is not None # deepspeed handles gradient clipping internally if is_overridden("configure_gradient_clipping", self.lightning_module, pl.LightningModule): rank_zero_warn( "Since DeepSpeed handles gradient clipping internally, the default" " `LightningModule.configure_gradient_clipping` implementation will not actually clip gradients." " The hook will still be called. Consider setting" " `Trainer(gradient_clip_val=..., gradient_clip_algorithm='norm')`" " which will use the internal mechanism." ) if self.lightning_module.trainer.gradient_clip_algorithm == GradClipAlgorithmType.VALUE: raise MisconfigurationException("DeepSpeed does not support clipping gradients by value.") assert isinstance(self.model, pl.LightningModule) if self.lightning_module.trainer and self.lightning_module.trainer.training: self._initialize_deepspeed_train(self.model) else: self._initialize_deepspeed_inference(self.model) def _init_optimizers(self) -> tuple[Optimizer, Optional[LRSchedulerConfig]]: assert self.lightning_module is not None optimizers, lr_schedulers = _init_optimizers_and_lr_schedulers(self.lightning_module) if len(optimizers) > 1 or len(lr_schedulers) > 1: raise MisconfigurationException( "DeepSpeed currently only supports single optimizer, single optional scheduler." ) return optimizers[0], lr_schedulers[0] if lr_schedulers else None @property def zero_stage_3(self) -> bool: assert isinstance(self.config, dict) zero_optimization = self.config.get("zero_optimization") return zero_optimization is not None and zero_optimization.get("stage") == 3 def _initialize_deepspeed_train(self, model: Module) -> None: optimizer, scheduler = None, None assert isinstance(self.config, dict) if "optimizer" in self.config: rank_zero_info( "You have specified an optimizer and/or scheduler within the DeepSpeed config." " It is recommended to define it in `LightningModule.configure_optimizers`." ) lr_scheduler = None else: ( optimizer, lr_scheduler, ) = self._init_optimizers() if lr_scheduler is not None: scheduler = lr_scheduler.scheduler model, deepspeed_optimizer = self._setup_model_and_optimizer(model, optimizer, scheduler) self._set_deepspeed_activation_checkpointing() # although we set these here, deepspeed manages the specific optimizer logic self.optimizers = [deepspeed_optimizer] deepspeed_scheduler = model.lr_scheduler if deepspeed_scheduler is not None: # disable deepspeed lr scheduling as lightning manages scheduling model.lr_scheduler = None if lr_scheduler is None: lr_scheduler = LRSchedulerConfig(deepspeed_scheduler, interval="step") else: lr_scheduler.scheduler = deepspeed_scheduler self.lr_scheduler_configs = [lr_scheduler] self.model = model @contextmanager @override def tensor_init_context(self, empty_init: Optional[bool] = None) -> Generator[None, None, None]: if self.zero_stage_3: if empty_init is False: raise NotImplementedError( f"`{empty_init=}` is not a valid choice with `DeepSpeedStrategy` when ZeRO stage 3 is enabled." ) yield return with super().tensor_init_context(empty_init=empty_init): yield @contextmanager @override def model_sharded_context(self) -> Generator[None, None, None]: import deepspeed self._init_config_if_needed() with deepspeed.zero.Init( enabled=self.zero_stage_3, remote_device=self.remote_device, config_dict_or_path=self.config, ): yield def _set_deepspeed_activation_checkpointing(self) -> None: import deepspeed assert isinstance(self.config, dict) if self.config.get("activation_checkpointing"): checkpoint_config = self.config["activation_checkpointing"] deepspeed.checkpointing.configure( mpu_=None, partition_activations=checkpoint_config.get("partition_activations"), contiguous_checkpointing=checkpoint_config.get("contiguous_memory_optimization"), checkpoint_in_cpu=checkpoint_config.get("cpu_checkpointing"), profile=checkpoint_config.get("profile"), ) def _initialize_deepspeed_inference(self, model: Module) -> None: import deepspeed assert isinstance(self.config, dict) # todo: this is required for DeepSpeed throughput timers inference_config = {"train_micro_batch_size_per_gpu": 1} if "fp16" in self.config: inference_config.update({"fp16": self.config["fp16"]}) if "bf16" in self.config: inference_config.update({"bf16": self.config["bf16"]}) if self.zero_stage_3: inference_config.update({ "zero_allow_untested_optimizer": self.config["zero_allow_untested_optimizer"], "zero_optimization": self.config["zero_optimization"], }) # Remove all module hooks before initializing new model remove_module_hooks(model) model, _, _, _ = deepspeed.initialize( args=argparse.Namespace(device_rank=self.root_device.index), config=inference_config, model=model, optimizer=None, lr_scheduler=None, model_parameters=[], dist_init_required=False, ) self.model = model @property @override def distributed_sampler_kwargs(self) -> dict[str, int]: return {"num_replicas": self.world_size, "rank": self.global_rank} @override def setup_optimizers(self, trainer: "pl.Trainer") -> None: """Creates optimizers and schedulers. Args: trainer: the Trainer, these optimizers should be connected to """ # Skip initializing optimizers here as DeepSpeed handles optimizers via config. # User may have specified config options instead in configure_optimizers, but this is handled # via `_initialize_deepspeed_train` # empty optimizers, schedulers self.optimizers = [] self.lr_scheduler_configs = [] def _setup_model(self, model: Module) -> Module: # type: ignore[override] return model @property @override def handles_gradient_accumulation(self) -> bool: """Whether the strategy handles gradient accumulation internally.""" return True @property def deepspeed_engine(self) -> "deepspeed.DeepSpeedEngine": return self.model @property def _multi_device(self) -> bool: return self.num_processes > 1 or self.num_nodes > 1 @override def save_checkpoint(self, checkpoint: dict, filepath: _PATH, storage_options: Optional[Any] = None) -> None: """Save model/training states as a checkpoint file through state-dump and file-write. Args: checkpoint: The checkpoint state dictionary filepath: write-target file's path storage_options: not used for ``DeepSpeedStrategy`` as ``CheckpointIO`` is not used Raises: TypeError: If ``storage_options`` arg is passed in """ # broadcast the filepath from rank 0 to ensure all the states are saved in a common filepath filepath = self.broadcast(filepath) if storage_options is not None: raise TypeError( "`Trainer.save_checkpoint(..., storage_options=...)` with `storage_options` arg" f" is not supported for `{self.__class__.__name__}` as `CheckpointIO` is not used." ) if self.zero_stage_3 and self._multi_device and self.is_global_zero: warning_cache.warn( "When saving the DeepSpeed Stage 3 checkpoint, " "each worker will save a shard of the checkpoint within a directory. " "If a single file is required after training, " "see https://lightning.ai/docs/pytorch/stable/advanced/model_parallel.html#" "deepspeed-zero-stage-3-single-file for instructions." ) # Use deepspeed's internal checkpointing function to handle partitioned weights across processes # dump states as a checkpoint dictionary object _exclude_keys = ["state_dict", "optimizer_states"] checkpoint = {k: v for k, v in checkpoint.items() if k not in _exclude_keys} self.deepspeed_engine.save_checkpoint( filepath, client_state=checkpoint, tag="checkpoint", exclude_frozen_parameters=self.exclude_frozen_parameters, ) @override def load_checkpoint(self, checkpoint_path: _PATH, weights_only: Optional[bool] = None) -> dict[str, Any]: if self.load_full_weights and self.zero_stage_3: # Broadcast to ensure we load from the rank 0 checkpoint # This doesn't have to be the case when using deepspeed sharded checkpointing checkpoint_path = self.broadcast(checkpoint_path) return super().load_checkpoint(checkpoint_path, weights_only) _validate_checkpoint_directory(checkpoint_path) # Rely on deepspeed to load the checkpoint and necessary information assert self.lightning_module is not None from lightning.pytorch.trainer.states import TrainerFn is_fitting = self.lightning_module.trainer.state.fn == TrainerFn.FITTING _, client_state = self.deepspeed_engine.load_checkpoint( checkpoint_path, load_optimizer_states=is_fitting, load_lr_scheduler_states=False, load_module_strict=self.lightning_module.strict_loading, ) if client_state is None: raise MisconfigurationException( "DeepSpeed was unable to load the checkpoint. Ensure you passed in a DeepSpeed compatible checkpoint " "or a single checkpoint file with `Trainer(strategy=DeepSpeedStrategy(load_full_weights=True))`." ) return client_state @property @override def lightning_restore_optimizer(self) -> bool: assert self.lightning_module is not None # managed by DeepSpeed if self.load_full_weights and self.zero_stage_3 and self.lightning_module.trainer.state.fn == TrainerFn.FITTING: rank_zero_warn( "A single checkpoint file has been given. This means optimizer states cannot be restored." " If you'd like to restore these states, you must provide a path to the originally saved DeepSpeed" " checkpoint. When using ZeRO 3, the original path should be a directory." ) return False @override def load_model_state_dict(self, checkpoint: Mapping[str, Any], strict: bool = True) -> None: # override to do nothing, deepspeed engine already loaded the weights in `load_checkpoint()` if self.load_full_weights and self.zero_stage_3: self.model_to_device() self._restore_zero_state(checkpoint, strict=strict) def _restore_zero_state(self, ckpt: Mapping[str, Any], strict: bool) -> None: """Overrides the normal load_state_dict behaviour in PyTorch to ensure we gather parameters that may be sharded across processes before loading the state dictionary when using ZeRO stage 3. This is then automatically synced across processes. Args: ckpt: The ckpt file. """ import deepspeed assert self.lightning_module is not None def load(module: torch.nn.Module, prefix: str = "") -> None: missing_keys: list[str] = [] unexpected_keys: list[str] = [] error_msgs: list[str] = [] state_dict = ckpt["state_dict"] # copy state_dict so _load_from_state_dict can modify it metadata = getattr(state_dict, "_metadata", None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {}) # because zero3 puts placeholders in model params, this context # manager gathers (unpartitions) the params of the current layer, then loads from # the state dict and then re-partitions them again with deepspeed.zero.GatheredParameters(list(module.parameters(recurse=False)), modifier_rank=0): if self.is_global_zero: module._load_from_state_dict( state_dict=state_dict, prefix=prefix, local_metadata=local_metadata, strict=strict, missing_keys=missing_keys, unexpected_keys=unexpected_keys, error_msgs=error_msgs, ) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + ".") load(self.lightning_module, prefix="") @override def load_optimizer_state_dict(self, checkpoint: Mapping[str, Any]) -> None: # Override to do nothing, the deepspeed engine already loaded the states in `load_checkpoint()` pass @classmethod @override def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: strategy_registry.register("deepspeed", cls, description="Default DeepSpeed Strategy") strategy_registry.register("deepspeed_stage_1", cls, description="DeepSpeed with ZeRO Stage 1 enabled", stage=1) strategy_registry.register("deepspeed_stage_2", cls, description="DeepSpeed with ZeRO Stage 2 enabled", stage=2) strategy_registry.register( "deepspeed_stage_2_offload", cls, description="DeepSpeed ZeRO Stage 2 and CPU Offload", stage=2, offload_optimizer=True, ) strategy_registry.register("deepspeed_stage_3", cls, description="DeepSpeed ZeRO Stage 3", stage=3) strategy_registry.register( "deepspeed_stage_3_offload", cls, description="DeepSpeed ZeRO Stage 3 and CPU Offload", stage=3, offload_optimizer=True, offload_parameters=True, ) strategy_registry.register( "deepspeed_stage_3_offload_nvme", cls, description="DeepSpeed ZeRO Stage 3 and NVMe Offload", stage=3, offload_optimizer=True, offload_parameters=True, remote_device="nvme", offload_params_device="nvme", offload_optimizer_device="nvme", ) def _load_config(self, config: Optional[Union[_PATH, dict[str, Any]]]) -> Optional[dict[str, Any]]: if config is None and self.DEEPSPEED_ENV_VAR in os.environ: rank_zero_info(f"Loading DeepSpeed config from set {self.DEEPSPEED_ENV_VAR} environment variable") config = os.environ[self.DEEPSPEED_ENV_VAR] if isinstance(config, (str, Path)): if not os.path.isfile(config): raise MisconfigurationException( f"You passed in a path to a DeepSpeed config but the path does not exist: {config}" ) with open(config) as f: config = json.load(f) assert isinstance(config, dict) or config is None return config def _init_config_if_needed(self) -> None: if not self._config_initialized: self._format_config() self._config_initialized = True def _format_config(self) -> None: if self.config is None: raise MisconfigurationException( "To use DeepSpeed you must pass in a DeepSpeed config dict, or a path to a JSON config." " See: https://lightning.ai/docs/pytorch/stable/advanced/model_parallel.html#deepspeed" ) self._format_batch_size_and_grad_accum_config() _format_precision_config( config=self.config, precision=self.precision_plugin.precision, loss_scale=self.loss_scale, loss_scale_window=self.loss_scale_window, min_loss_scale=self.min_loss_scale, initial_scale_power=self.initial_scale_power, hysteresis=self.hysteresis, ) def _create_default_config( self, zero_optimization: bool, zero_allow_untested_optimizer: bool, logging_batch_size_per_gpu: Union[str, int], partition_activations: bool, cpu_checkpointing: bool, contiguous_memory_optimization: bool, synchronize_checkpoint_boundary: bool, offload_optimizer: bool, offload_parameters: bool, nvme_path: str, offload_params_device: str, params_buffer_count: int, params_buffer_size: int, max_in_cpu: int, offload_optimizer_device: str, optimizer_buffer_count: int, pin_memory: bool, block_size: int, queue_depth: int, single_submit: bool, overlap_events: bool, thread_count: int, **zero_kwargs: Any, ) -> dict: cfg = { "activation_checkpointing": { "partition_activations": partition_activations, "cpu_checkpointing": cpu_checkpointing, "contiguous_memory_optimization": contiguous_memory_optimization, "synchronize_checkpoint_boundary": synchronize_checkpoint_boundary, }, "aio": { "block_size": block_size, "queue_depth": queue_depth, "single_submit": single_submit, "overlap_events": overlap_events, "thread_count": thread_count, }, } if zero_optimization: zero_config = zero_kwargs if offload_optimizer: zero_config["offload_optimizer"] = { "device": offload_optimizer_device, "nvme_path": nvme_path, "buffer_count": optimizer_buffer_count, "pin_memory": pin_memory, } if offload_parameters: zero_config["offload_param"] = { "device": offload_params_device, "nvme_path": nvme_path, "buffer_count": params_buffer_count, "buffer_size": params_buffer_size, "max_in_cpu": max_in_cpu, "pin_memory": pin_memory, } cfg = { "zero_allow_untested_optimizer": zero_allow_untested_optimizer, "zero_optimization": zero_config, **cfg, } if logging_batch_size_per_gpu != "auto": cfg = {"train_micro_batch_size_per_gpu": logging_batch_size_per_gpu, **cfg} return cfg def _format_batch_size_and_grad_accum_config(self) -> None: # TODO: Using Fabric, we do not support these variables within the config assert isinstance(self.config, dict) if self.lightning_module is None: return if "gradient_accumulation_steps" in self.config: raise MisconfigurationException( "Do not set `gradient_accumulation_steps` in the DeepSpeed config" " as this will be set with the `accumulate_grad_batches` argument passed via the Lightning Trainer." ) self.config["gradient_accumulation_steps"] = self.lightning_module.trainer.accumulate_grad_batches if "train_micro_batch_size_per_gpu" not in self.config: batch_size = self._auto_select_batch_size() self.config["train_micro_batch_size_per_gpu"] = batch_size if "gradient_clipping" not in self.config: self.config["gradient_clipping"] = self.lightning_module.trainer.gradient_clip_val or 0.0 def _auto_select_batch_size(self) -> int: # train_micro_batch_size_per_gpu is used for throughput logging purposes # by default we try to use the batch size of the loader assert self.lightning_module is not None batch_size = 1 data_source = self.lightning_module.trainer.fit_loop._data_source if data_source.is_defined(): train_dataloader = data_source.dataloader() if hasattr(train_dataloader, "batch_sampler"): batch_size = train_dataloader.batch_sampler.batch_size return batch_size
DeepSpeedStrategy
python
mkdocs__mkdocs
mkdocs/tests/search_tests.py
{ "start": 10571, "end": 24300 }
class ____(unittest.TestCase): def test_html_stripping(self): stripper = search_index.ContentParser() stripper.feed("<h1>Testing</h1><p>Content</p>") self.assertEqual(stripper.stripped_html, "Testing\nContent") def test_content_parser(self): parser = search_index.ContentParser() parser.feed('<h1 id="title">Title</h1>TEST') parser.close() self.assertEqual( parser.data, [search_index.ContentSection(text=["TEST"], id_="title", title="Title")] ) def test_content_parser_no_id(self): parser = search_index.ContentParser() parser.feed("<h1>Title</h1>TEST") parser.close() self.assertEqual( parser.data, [search_index.ContentSection(text=["TEST"], id_=None, title="Title")] ) def test_content_parser_content_before_header(self): parser = search_index.ContentParser() parser.feed("Content Before H1 <h1>Title</h1>TEST") parser.close() self.assertEqual( parser.data, [search_index.ContentSection(text=["TEST"], id_=None, title="Title")] ) def test_content_parser_no_sections(self): parser = search_index.ContentParser() parser.feed("No H1 or H2<span>Title</span>TEST") self.assertEqual(parser.data, []) def test_find_toc_by_id(self): """Test finding the relevant TOC item by the tag ID.""" index = search_index.SearchIndex() md = dedent( """ # Heading 1 ## Heading 2 ### Heading 3 """ ) toc = get_toc(get_markdown_toc(md)) toc_item = index._find_toc_by_id(toc, "heading-1") self.assertEqual(toc_item.url, "#heading-1") self.assertEqual(toc_item.title, "Heading 1") toc_item2 = index._find_toc_by_id(toc, "heading-2") self.assertEqual(toc_item2.url, "#heading-2") self.assertEqual(toc_item2.title, "Heading 2") toc_item3 = index._find_toc_by_id(toc, "heading-3") self.assertEqual(toc_item3.url, "#heading-3") self.assertEqual(toc_item3.title, "Heading 3") def test_create_search_index(self): html_content = """ <h1 id="heading-1">Heading 1</h1> <p>Content 1</p> <h2 id="heading-2">Heading 2</h1> <p>Content 2</p> <h3 id="heading-3">Heading 3</h1> <p>Content 3</p> """ base_cfg = load_config() pages = [ Page( 'Home', File('index.md', base_cfg.docs_dir, base_cfg.site_dir, base_cfg.use_directory_urls), base_cfg, ), Page( 'About', File('about.md', base_cfg.docs_dir, base_cfg.site_dir, base_cfg.use_directory_urls), base_cfg, ), ] md = dedent( """ # Heading 1 ## Heading 2 ### Heading 3 """ ) toc = get_toc(get_markdown_toc(md)) full_content = ''.join(f"Heading{i}Content{i}" for i in range(1, 4)) plugin = search.SearchPlugin() errors, warnings = plugin.load_config({}) for page in pages: # Fake page.read_source() and page.render() page.markdown = md page.toc = toc page.content = html_content index = search_index.SearchIndex(**plugin.config) index.add_entry_from_context(page) self.assertEqual(len(index._entries), 4) loc = page.url self.assertEqual(index._entries[0]['title'], page.title) self.assertEqual(strip_whitespace(index._entries[0]['text']), full_content) self.assertEqual(index._entries[0]['location'], loc) self.assertEqual(index._entries[1]['title'], "Heading 1") self.assertEqual(index._entries[1]['text'], "Content 1") self.assertEqual(index._entries[1]['location'], f"{loc}#heading-1") self.assertEqual(index._entries[2]['title'], "Heading 2") self.assertEqual(strip_whitespace(index._entries[2]['text']), "Content2") self.assertEqual(index._entries[2]['location'], f"{loc}#heading-2") self.assertEqual(index._entries[3]['title'], "Heading 3") self.assertEqual(strip_whitespace(index._entries[3]['text']), "Content3") self.assertEqual(index._entries[3]['location'], f"{loc}#heading-3") def test_search_indexing_options(self): def test_page(title, filename, config): test_page = Page( title, File(filename, config.docs_dir, config.site_dir, config.use_directory_urls), config, ) test_page.content = """ <h1 id="heading-1">Heading 1</h1> <p>Content 1</p> <h2 id="heading-2">Heading 2</h1> <p>Content 2</p> <h3 id="heading-3">Heading 3</h1> <p>Content 3</p>""" test_page.markdown = dedent( """ # Heading 1 ## Heading 2 ### Heading 3""" ) test_page.toc = get_toc(get_markdown_toc(test_page.markdown)) return test_page def validate_full(data, page): self.assertEqual(len(data), 4) for x in data: self.assertTrue(x['title']) self.assertTrue(x['text']) def validate_sections(data, page): # Sanity self.assertEqual(len(data), 4) # Page self.assertEqual(data[0]['title'], page.title) self.assertFalse(data[0]['text']) # Headings for x in data[1:]: self.assertTrue(x['title']) self.assertFalse(x['text']) def validate_titles(data, page): # Sanity self.assertEqual(len(data), 1) for x in data: self.assertFalse(x['text']) for option, validate in { 'full': validate_full, 'sections': validate_sections, 'titles': validate_titles, }.items(): with self.subTest(option): plugin = search.SearchPlugin() # Load plugin config, overriding indexing for test case errors, warnings = plugin.load_config({'indexing': option}) self.assertEqual(errors, []) self.assertEqual(warnings, []) base_cfg = load_config(plugins=['search']) base_cfg.plugins['search'].config.indexing = option pages = [ test_page('Home', 'index.md', base_cfg), test_page('About', 'about.md', base_cfg), ] for page in pages: index = search_index.SearchIndex(**plugin.config) index.add_entry_from_context(page) data = index.generate_search_index() validate(json.loads(data)['docs'], page) @mock.patch('subprocess.Popen', autospec=True) def test_prebuild_index(self, mock_popen): # See https://stackoverflow.com/a/36501078/866026 mock_popen.return_value = mock.Mock() mock_popen_obj = mock_popen.return_value mock_popen_obj.communicate.return_value = ('{"mock": "index"}', None) mock_popen_obj.returncode = 0 index = search_index.SearchIndex(prebuild_index=True) expected = { 'docs': [], 'config': {'prebuild_index': True}, 'index': {'mock': 'index'}, } result = json.loads(index.generate_search_index()) self.assertEqual(mock_popen.call_count, 1) self.assertEqual(mock_popen_obj.communicate.call_count, 1) self.assertEqual(result, expected) @mock.patch('subprocess.Popen', autospec=True) def test_prebuild_index_returns_error(self, mock_popen): # See https://stackoverflow.com/a/36501078/866026 mock_popen.return_value = mock.Mock() mock_popen_obj = mock_popen.return_value mock_popen_obj.communicate.return_value = ('', 'Some Error') mock_popen_obj.returncode = 0 index = search_index.SearchIndex(prebuild_index=True) expected = { 'docs': [], 'config': {'prebuild_index': True}, } with self.assertLogs('mkdocs') as cm: result = json.loads(index.generate_search_index()) self.assertEqual( '\n'.join(cm.output), 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: Some Error', ) self.assertEqual(mock_popen.call_count, 1) self.assertEqual(mock_popen_obj.communicate.call_count, 1) self.assertEqual(result, expected) @mock.patch('subprocess.Popen', autospec=True) def test_prebuild_index_raises_ioerror(self, mock_popen): # See https://stackoverflow.com/a/36501078/866026 mock_popen.return_value = mock.Mock() mock_popen_obj = mock_popen.return_value mock_popen_obj.communicate.side_effect = OSError mock_popen_obj.returncode = 1 index = search_index.SearchIndex(prebuild_index=True) expected = { 'docs': [], 'config': {'prebuild_index': True}, } with self.assertLogs('mkdocs') as cm: result = json.loads(index.generate_search_index()) self.assertEqual( '\n'.join(cm.output), 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: ', ) self.assertEqual(mock_popen.call_count, 1) self.assertEqual(mock_popen_obj.communicate.call_count, 1) self.assertEqual(result, expected) @mock.patch('subprocess.Popen', autospec=True, side_effect=OSError) def test_prebuild_index_raises_oserror(self, mock_popen): # See https://stackoverflow.com/a/36501078/866026 mock_popen.return_value = mock.Mock() mock_popen_obj = mock_popen.return_value mock_popen_obj.communicate.return_value = ('foo', 'bar') mock_popen_obj.returncode = 0 index = search_index.SearchIndex(prebuild_index=True) expected = { 'docs': [], 'config': {'prebuild_index': True}, } with self.assertLogs('mkdocs') as cm: result = json.loads(index.generate_search_index()) self.assertEqual( '\n'.join(cm.output), 'WARNING:mkdocs.contrib.search.search_index:Failed to pre-build search index. Error: ', ) self.assertEqual(mock_popen.call_count, 1) self.assertEqual(mock_popen_obj.communicate.call_count, 0) self.assertEqual(result, expected) @mock.patch('subprocess.Popen', autospec=True) def test_prebuild_index_false(self, mock_popen): # See https://stackoverflow.com/a/36501078/866026 mock_popen.return_value = mock.Mock() mock_popen_obj = mock_popen.return_value mock_popen_obj.communicate.return_value = ('', '') mock_popen_obj.returncode = 0 index = search_index.SearchIndex(prebuild_index=False) expected = { 'docs': [], 'config': {'prebuild_index': False}, } result = json.loads(index.generate_search_index()) self.assertEqual(mock_popen.call_count, 0) self.assertEqual(mock_popen_obj.communicate.call_count, 0) self.assertEqual(result, expected) @unittest.skipUnless(search_index.haslunrpy, 'lunr.py is not installed') @mock.patch('mkdocs.contrib.search.search_index.lunr', autospec=True) def test_prebuild_index_python(self, mock_lunr): mock_lunr.return_value.serialize.return_value = {'mock': 'index'} index = search_index.SearchIndex(prebuild_index='python', lang='en') expected = { 'docs': [], 'config': {'prebuild_index': 'python', 'lang': 'en'}, 'index': {'mock': 'index'}, } result = json.loads(index.generate_search_index()) self.assertEqual(mock_lunr.call_count, 1) self.assertEqual(result, expected) @unittest.skipIf(search_index.haslunrpy, 'lunr.py is installed') def test_prebuild_index_python_missing_lunr(self): # When the lunr.py dependencies are not installed no prebuilt index is created. index = search_index.SearchIndex(prebuild_index='python', lang='en') expected = { 'docs': [], 'config': {'prebuild_index': 'python', 'lang': 'en'}, } with self.assertLogs('mkdocs', level='WARNING'): result = json.loads(index.generate_search_index()) self.assertEqual(result, expected) @mock.patch('subprocess.Popen', autospec=True) def test_prebuild_index_node(self, mock_popen): # See https://stackoverflow.com/a/36501078/866026 mock_popen.return_value = mock.Mock() mock_popen_obj = mock_popen.return_value mock_popen_obj.communicate.return_value = ('{"mock": "index"}', None) mock_popen_obj.returncode = 0 index = search_index.SearchIndex(prebuild_index='node') expected = { 'docs': [], 'config': {'prebuild_index': 'node'}, 'index': {'mock': 'index'}, } result = json.loads(index.generate_search_index()) self.assertEqual(mock_popen.call_count, 1) self.assertEqual(mock_popen_obj.communicate.call_count, 1) self.assertEqual(result, expected)
SearchIndexTests
python
boto__boto3
boto3/dynamodb/transform.py
{ "start": 930, "end": 1333 }
class ____(dict): """A dictionary that discards any items set on it. For use as `memo` in `copy.deepcopy()` when every instance of a repeated object in the deepcopied data structure should result in a separate copy. """ def __setitem__(self, key, value): pass def copy_dynamodb_params(params, **kwargs): return copy.deepcopy(params, memo=_ForgetfulDict())
_ForgetfulDict
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/antlr_asset_selection/generated/AssetSelectionListener.py
{ "start": 251, "end": 10558 }
class ____(ParseTreeListener): # Enter a parse tree produced by AssetSelectionParser#start. def enterStart(self, ctx: AssetSelectionParser.StartContext): pass # Exit a parse tree produced by AssetSelectionParser#start. def exitStart(self, ctx: AssetSelectionParser.StartContext): pass # Enter a parse tree produced by AssetSelectionParser#UpTraversalExpression. def enterUpTraversalExpression(self, ctx: AssetSelectionParser.UpTraversalExpressionContext): pass # Exit a parse tree produced by AssetSelectionParser#UpTraversalExpression. def exitUpTraversalExpression(self, ctx: AssetSelectionParser.UpTraversalExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#AndExpression. def enterAndExpression(self, ctx: AssetSelectionParser.AndExpressionContext): pass # Exit a parse tree produced by AssetSelectionParser#AndExpression. def exitAndExpression(self, ctx: AssetSelectionParser.AndExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#AllExpression. def enterAllExpression(self, ctx: AssetSelectionParser.AllExpressionContext): pass # Exit a parse tree produced by AssetSelectionParser#AllExpression. def exitAllExpression(self, ctx: AssetSelectionParser.AllExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#TraversalAllowedExpression. def enterTraversalAllowedExpression( self, ctx: AssetSelectionParser.TraversalAllowedExpressionContext ): pass # Exit a parse tree produced by AssetSelectionParser#TraversalAllowedExpression. def exitTraversalAllowedExpression( self, ctx: AssetSelectionParser.TraversalAllowedExpressionContext ): pass # Enter a parse tree produced by AssetSelectionParser#DownTraversalExpression. def enterDownTraversalExpression( self, ctx: AssetSelectionParser.DownTraversalExpressionContext ): pass # Exit a parse tree produced by AssetSelectionParser#DownTraversalExpression. def exitDownTraversalExpression(self, ctx: AssetSelectionParser.DownTraversalExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#NotExpression. def enterNotExpression(self, ctx: AssetSelectionParser.NotExpressionContext): pass # Exit a parse tree produced by AssetSelectionParser#NotExpression. def exitNotExpression(self, ctx: AssetSelectionParser.NotExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#OrExpression. def enterOrExpression(self, ctx: AssetSelectionParser.OrExpressionContext): pass # Exit a parse tree produced by AssetSelectionParser#OrExpression. def exitOrExpression(self, ctx: AssetSelectionParser.OrExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#UpAndDownTraversalExpression. def enterUpAndDownTraversalExpression( self, ctx: AssetSelectionParser.UpAndDownTraversalExpressionContext ): pass # Exit a parse tree produced by AssetSelectionParser#UpAndDownTraversalExpression. def exitUpAndDownTraversalExpression( self, ctx: AssetSelectionParser.UpAndDownTraversalExpressionContext ): pass # Enter a parse tree produced by AssetSelectionParser#AttributeExpression. def enterAttributeExpression(self, ctx: AssetSelectionParser.AttributeExpressionContext): pass # Exit a parse tree produced by AssetSelectionParser#AttributeExpression. def exitAttributeExpression(self, ctx: AssetSelectionParser.AttributeExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#FunctionCallExpression. def enterFunctionCallExpression(self, ctx: AssetSelectionParser.FunctionCallExpressionContext): pass # Exit a parse tree produced by AssetSelectionParser#FunctionCallExpression. def exitFunctionCallExpression(self, ctx: AssetSelectionParser.FunctionCallExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#ParenthesizedExpression. def enterParenthesizedExpression( self, ctx: AssetSelectionParser.ParenthesizedExpressionContext ): pass # Exit a parse tree produced by AssetSelectionParser#ParenthesizedExpression. def exitParenthesizedExpression(self, ctx: AssetSelectionParser.ParenthesizedExpressionContext): pass # Enter a parse tree produced by AssetSelectionParser#upTraversal. def enterUpTraversal(self, ctx: AssetSelectionParser.UpTraversalContext): pass # Exit a parse tree produced by AssetSelectionParser#upTraversal. def exitUpTraversal(self, ctx: AssetSelectionParser.UpTraversalContext): pass # Enter a parse tree produced by AssetSelectionParser#downTraversal. def enterDownTraversal(self, ctx: AssetSelectionParser.DownTraversalContext): pass # Exit a parse tree produced by AssetSelectionParser#downTraversal. def exitDownTraversal(self, ctx: AssetSelectionParser.DownTraversalContext): pass # Enter a parse tree produced by AssetSelectionParser#functionName. def enterFunctionName(self, ctx: AssetSelectionParser.FunctionNameContext): pass # Exit a parse tree produced by AssetSelectionParser#functionName. def exitFunctionName(self, ctx: AssetSelectionParser.FunctionNameContext): pass # Enter a parse tree produced by AssetSelectionParser#KeyExpr. def enterKeyExpr(self, ctx: AssetSelectionParser.KeyExprContext): pass # Exit a parse tree produced by AssetSelectionParser#KeyExpr. def exitKeyExpr(self, ctx: AssetSelectionParser.KeyExprContext): pass # Enter a parse tree produced by AssetSelectionParser#TagAttributeExpr. def enterTagAttributeExpr(self, ctx: AssetSelectionParser.TagAttributeExprContext): pass # Exit a parse tree produced by AssetSelectionParser#TagAttributeExpr. def exitTagAttributeExpr(self, ctx: AssetSelectionParser.TagAttributeExprContext): pass # Enter a parse tree produced by AssetSelectionParser#OwnerAttributeExpr. def enterOwnerAttributeExpr(self, ctx: AssetSelectionParser.OwnerAttributeExprContext): pass # Exit a parse tree produced by AssetSelectionParser#OwnerAttributeExpr. def exitOwnerAttributeExpr(self, ctx: AssetSelectionParser.OwnerAttributeExprContext): pass # Enter a parse tree produced by AssetSelectionParser#GroupAttributeExpr. def enterGroupAttributeExpr(self, ctx: AssetSelectionParser.GroupAttributeExprContext): pass # Exit a parse tree produced by AssetSelectionParser#GroupAttributeExpr. def exitGroupAttributeExpr(self, ctx: AssetSelectionParser.GroupAttributeExprContext): pass # Enter a parse tree produced by AssetSelectionParser#KindAttributeExpr. def enterKindAttributeExpr(self, ctx: AssetSelectionParser.KindAttributeExprContext): pass # Exit a parse tree produced by AssetSelectionParser#KindAttributeExpr. def exitKindAttributeExpr(self, ctx: AssetSelectionParser.KindAttributeExprContext): pass # Enter a parse tree produced by AssetSelectionParser#StatusAttributeExpr. def enterStatusAttributeExpr(self, ctx: AssetSelectionParser.StatusAttributeExprContext): pass # Exit a parse tree produced by AssetSelectionParser#StatusAttributeExpr. def exitStatusAttributeExpr(self, ctx: AssetSelectionParser.StatusAttributeExprContext): pass # Enter a parse tree produced by AssetSelectionParser#ColumnAttributeExpr. def enterColumnAttributeExpr(self, ctx: AssetSelectionParser.ColumnAttributeExprContext): pass # Exit a parse tree produced by AssetSelectionParser#ColumnAttributeExpr. def exitColumnAttributeExpr(self, ctx: AssetSelectionParser.ColumnAttributeExprContext): pass # Enter a parse tree produced by AssetSelectionParser#TableNameAttributeExpr. def enterTableNameAttributeExpr(self, ctx: AssetSelectionParser.TableNameAttributeExprContext): pass # Exit a parse tree produced by AssetSelectionParser#TableNameAttributeExpr. def exitTableNameAttributeExpr(self, ctx: AssetSelectionParser.TableNameAttributeExprContext): pass # Enter a parse tree produced by AssetSelectionParser#ColumnTagAttributeExpr. def enterColumnTagAttributeExpr(self, ctx: AssetSelectionParser.ColumnTagAttributeExprContext): pass # Exit a parse tree produced by AssetSelectionParser#ColumnTagAttributeExpr. def exitColumnTagAttributeExpr(self, ctx: AssetSelectionParser.ColumnTagAttributeExprContext): pass # Enter a parse tree produced by AssetSelectionParser#CodeLocationAttributeExpr. def enterCodeLocationAttributeExpr( self, ctx: AssetSelectionParser.CodeLocationAttributeExprContext ): pass # Exit a parse tree produced by AssetSelectionParser#CodeLocationAttributeExpr. def exitCodeLocationAttributeExpr( self, ctx: AssetSelectionParser.CodeLocationAttributeExprContext ): pass # Enter a parse tree produced by AssetSelectionParser#ChangedInBranchAttributeExpr. def enterChangedInBranchAttributeExpr( self, ctx: AssetSelectionParser.ChangedInBranchAttributeExprContext ): pass # Exit a parse tree produced by AssetSelectionParser#ChangedInBranchAttributeExpr. def exitChangedInBranchAttributeExpr( self, ctx: AssetSelectionParser.ChangedInBranchAttributeExprContext ): pass # Enter a parse tree produced by AssetSelectionParser#value. def enterValue(self, ctx: AssetSelectionParser.ValueContext): pass # Exit a parse tree produced by AssetSelectionParser#value. def exitValue(self, ctx: AssetSelectionParser.ValueContext): pass # Enter a parse tree produced by AssetSelectionParser#keyValue. def enterKeyValue(self, ctx: AssetSelectionParser.KeyValueContext): pass # Exit a parse tree produced by AssetSelectionParser#keyValue. def exitKeyValue(self, ctx: AssetSelectionParser.KeyValueContext): pass del AssetSelectionParser
AssetSelectionListener
python
kubernetes-client__python
kubernetes/client/models/v1_device_toleration.py
{ "start": 383, "end": 8723 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'effect': 'str', 'key': 'str', 'operator': 'str', 'toleration_seconds': 'int', 'value': 'str' } attribute_map = { 'effect': 'effect', 'key': 'key', 'operator': 'operator', 'toleration_seconds': 'tolerationSeconds', 'value': 'value' } def __init__(self, effect=None, key=None, operator=None, toleration_seconds=None, value=None, local_vars_configuration=None): # noqa: E501 """V1DeviceToleration - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._effect = None self._key = None self._operator = None self._toleration_seconds = None self._value = None self.discriminator = None if effect is not None: self.effect = effect if key is not None: self.key = key if operator is not None: self.operator = operator if toleration_seconds is not None: self.toleration_seconds = toleration_seconds if value is not None: self.value = value @property def effect(self): """Gets the effect of this V1DeviceToleration. # noqa: E501 Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule and NoExecute. # noqa: E501 :return: The effect of this V1DeviceToleration. # noqa: E501 :rtype: str """ return self._effect @effect.setter def effect(self, effect): """Sets the effect of this V1DeviceToleration. Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule and NoExecute. # noqa: E501 :param effect: The effect of this V1DeviceToleration. # noqa: E501 :type: str """ self._effect = effect @property def key(self): """Gets the key of this V1DeviceToleration. # noqa: E501 Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys. Must be a label name. # noqa: E501 :return: The key of this V1DeviceToleration. # noqa: E501 :rtype: str """ return self._key @key.setter def key(self, key): """Sets the key of this V1DeviceToleration. Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys. Must be a label name. # noqa: E501 :param key: The key of this V1DeviceToleration. # noqa: E501 :type: str """ self._key = key @property def operator(self): """Gets the operator of this V1DeviceToleration. # noqa: E501 Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a ResourceClaim can tolerate all taints of a particular category. # noqa: E501 :return: The operator of this V1DeviceToleration. # noqa: E501 :rtype: str """ return self._operator @operator.setter def operator(self, operator): """Sets the operator of this V1DeviceToleration. Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a ResourceClaim can tolerate all taints of a particular category. # noqa: E501 :param operator: The operator of this V1DeviceToleration. # noqa: E501 :type: str """ self._operator = operator @property def toleration_seconds(self): """Gets the toleration_seconds of this V1DeviceToleration. # noqa: E501 TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system. If larger than zero, the time when the pod needs to be evicted is calculated as <time when taint was adedd> + <toleration seconds>. # noqa: E501 :return: The toleration_seconds of this V1DeviceToleration. # noqa: E501 :rtype: int """ return self._toleration_seconds @toleration_seconds.setter def toleration_seconds(self, toleration_seconds): """Sets the toleration_seconds of this V1DeviceToleration. TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system. If larger than zero, the time when the pod needs to be evicted is calculated as <time when taint was adedd> + <toleration seconds>. # noqa: E501 :param toleration_seconds: The toleration_seconds of this V1DeviceToleration. # noqa: E501 :type: int """ self._toleration_seconds = toleration_seconds @property def value(self): """Gets the value of this V1DeviceToleration. # noqa: E501 Value is the taint value the toleration matches to. If the operator is Exists, the value must be empty, otherwise just a regular string. Must be a label value. # noqa: E501 :return: The value of this V1DeviceToleration. # noqa: E501 :rtype: str """ return self._value @value.setter def value(self, value): """Sets the value of this V1DeviceToleration. Value is the taint value the toleration matches to. If the operator is Exists, the value must be empty, otherwise just a regular string. Must be a label value. # noqa: E501 :param value: The value of this V1DeviceToleration. # noqa: E501 :type: str """ self._value = value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1DeviceToleration): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1DeviceToleration): return True return self.to_dict() != other.to_dict()
V1DeviceToleration
python
streamlit__streamlit
lib/tests/streamlit/elements/lib/options_selector_utils_test.py
{ "start": 13118, "end": 15119 }
class ____: """Test class for create_mappings utility function.""" def test_create_mappings_with_default_format_func(self): # Using default str format_func options = ["apple", "banana", "cherry"] formatted_options, mapping = create_mappings(options) # Check formatted options assert formatted_options == ["apple", "banana", "cherry"] # Check mapping assert mapping == {"apple": 0, "banana": 1, "cherry": 2} def test_create_mappings_with_custom_format_func(self): # Using a custom format function options = ["apple", "banana", "cherry"] formatted_options, mapping = create_mappings( options, lambda x: f"fruit-{x.upper()}" ) # Check formatted options assert formatted_options == ["fruit-APPLE", "fruit-BANANA", "fruit-CHERRY"] # Check mapping assert mapping == {"fruit-APPLE": 0, "fruit-BANANA": 1, "fruit-CHERRY": 2} def test_create_mappings_with_numeric_options(self): # Test with numeric options options = [1, 2, 3, 4] formatted_options, mapping = create_mappings(options) # Check formatted options assert formatted_options == ["1", "2", "3", "4"] # Check mapping assert mapping == {"1": 0, "2": 1, "3": 2, "4": 3} def test_create_mappings_with_mixed_types(self): # Test with a mix of types options = [1, "two", 3.0, None] formatted_options, mapping = create_mappings(options) # Check formatted options assert formatted_options == ["1", "two", "3.0", "None"] # Check mapping assert mapping == {"1": 0, "two": 1, "3.0": 2, "None": 3} def test_create_mappings_with_empty_list(self): # Test with empty list options = [] formatted_options, mapping = create_mappings(options) # Check both results are empty assert formatted_options == [] assert mapping == {}
TestCreateMappings
python
falconry__falcon
tests/asgi/test_buffered_reader.py
{ "start": 1387, "end": 9348 }
class ____: def __init__(self): self._sink = io.BytesIO() async def write(self, data): self._sink.write(data) @property def accumulated(self): return self._sink.getvalue() @pytest.fixture() def reader1(): return reader.BufferedReader(async_iter(SOURCE1), chunk_size=8) @pytest.fixture() def reader2(): return reader.BufferedReader(async_iter(SOURCE2), chunk_size=2048) @pytest.fixture() def reader3(): return reader.BufferedReader(async_iter(SOURCE3), chunk_size=2048) def test_basic_aiter(reader1): assert async_take(reader1) == [ b'Hello, World!', b'\nJust tes', b'ting some iterato', b'r goodne', b'ss.\n', ] async def test_aiter_from_buffer(reader1): assert await reader1.read(4) == b'Hell' collected = [] async for chunk in reader1: collected.append(chunk) assert collected == [ b'o, World!', b'\nJust tes', b'ting some iterato', b'r goodne', b'ss.\n', ] @pytest.mark.parametrize( 'delimiter,expected', [ (b'H', []), (b'Hello', []), (b'o', [b'Hell']), (b'ting', [b'Hello, World!', b'\nJust tes']), ( b'404', [ b'Hello, World!', b'\nJust tes', b'ting some iterato', b'r goodne', b'ss.\n', ], ), ], ) def test_delimit(reader1, delimiter, expected): delimited = reader1.delimit(delimiter) assert async_take(delimited) == expected async def test_exhaust(reader1): await reader1.exhaust() assert await reader1.peek() == b'' @pytest.mark.parametrize('size', [1, 2, 3, 5, 7, 8]) async def test_peek(reader1, size): assert await reader1.peek(size) == b'Hello, World'[:size] assert reader1.tell() == 0 async def test_peek_at_eof(): source = chop_data(b'Hello!') stream = reader.BufferedReader(source) assert await stream.peek(16) == b'Hello!' async def test_pipe(reader1): sink = AsyncSink() await reader1.pipe(sink) assert sink.accumulated == DATA1 assert reader1.eof assert reader1.tell() == len(sink.accumulated) async def test_pipe_until_delimiter_not_found(reader1): sink = AsyncSink() await reader1.pipe_until(b'404', sink) assert sink.accumulated == DATA1 @pytest.mark.parametrize( 'sizes,expected', [ ((0, 1, 2, 5), [b'', b'H', b'el', b'lo, W']), ( (20, 21, 22, 23, 25), [ b'Hello, World!\nJust t', b'esting some iterator ', b'goodness.\n', b'', b'', ], ), ((1, 50), [b'H', b'ello, World!\nJust testing some iterator goodness.\n']), ((50, 1), [b'Hello, World!\nJust testing some iterator goodness.', b'\n']), ], ) async def test_read(reader1, sizes, expected): results = [] for size in sizes: results.append(await reader1.read(size)) assert results == expected @pytest.mark.parametrize('start_size', [1, 16777216]) @pytest.mark.slow async def test_varying_read_size(reader2, start_size): size = start_size result = io.BytesIO() while True: chunk = await reader2.read(size) if not chunk: break result.write(chunk) size += 7 assert result.getvalue() == DATA2 @pytest.mark.parametrize('peek', [0, 1, 8]) async def test_readall(reader1, peek): if peek: await reader1.peek(peek) assert await reader1.readall() == DATA1 assert reader1.eof @pytest.mark.parametrize('fork', [False, True]) @pytest.mark.parametrize( 'offset,delimiter,size,expected', [ (0, b', ', 4, b'Hell'), (0, b', ', 5, b'Hello'), (0, b', ', -1, b'Hello'), (20, b' ', 4, b'esti'), (20, b' ', 5, b'estin'), (20, b' ', 6, b'esting'), (20, b' ', 20, b'esting'), (20, b' ', None, b'esting'), (0, b'Hell', 13, b''), (1, b'ell', 13, b''), (2, b'll', 13, b''), (3, b'l', 13, b''), (2, b'l', 13, b''), (0, b'good', 13, b'Hello, World!'), (7, b'good', 19, b'World!\nJust testing'), (7, b'good', 33, b'World!\nJust testing some iterator'), (7, b'good', 34, b'World!\nJust testing some iterator '), (7, b'good', 1337, b'World!\nJust testing some iterator '), (7, b'good', -1, b'World!\nJust testing some iterator '), ], ) async def test_read_until(reader1, offset, delimiter, size, expected, fork): if offset: await reader1.read(offset) if fork: assert await reader1.delimit(delimiter).read(size) == expected else: assert await reader1.read_until(delimiter, size) == expected async def test_read_until_with_buffer_edge_case(reader1): assert await reader1.read(12) == b'Hello, World' assert await reader1.peek(1) == b'!' assert await reader1.read_until(b'404', 1) == b'!' assert await reader1.read(13) == b'\nJust testing' def test_placeholder_methods(reader1): with pytest.raises(OSError): reader1.fileno() assert not reader1.isatty() assert reader1.readable() assert not reader1.seekable() assert not reader1.writable() async def test_iteration_started(reader1): async for chunk in reader1: with pytest.raises(OperationNotAllowed): async for nested in reader1: pass async def test_invalid_delimiter_length(reader1): with pytest.raises(ValueError): await reader1.read_until(b'') with pytest.raises(ValueError): await reader1.pipe_until(b'') with pytest.raises(ValueError): await reader1.delimit(b'').read() @pytest.mark.parametrize( 'size1,size2', [ (11003077, 22000721), (13372477, 51637898), ], ) @pytest.mark.slow async def test_irregular_large_read_until(reader2, size1, size2): delimiter = b'--boundary1234567890--' await reader2.pipe_until(delimiter, consume_delimiter=True) await reader2.pipe_until(delimiter, consume_delimiter=True) expected = b'123456789ABCDEF\n' * 64 * 1024 * 62 assert await reader2.read_until(delimiter, 1337) == expected[:1337] chunk1 = await reader2.read_until(delimiter, size1) assert len(chunk1) == size1 chunk2 = await reader2.read_until(delimiter, size2) assert len(chunk2) == size2 remainder = await reader2.read_until(delimiter, 62 * 1024 * 1024) assert chunk1 + chunk2 + remainder == expected[1337:] @pytest.mark.parametrize('chunk_size', list(range(46, 63))) async def test_read_until_shared_boundary(chunk_size): source = chop_data( b'-boundary-like-' * 4 + b'--some junk--\n' + b'\n' * 1024, min_size=chunk_size, max_size=chunk_size, ) stream = reader.BufferedReader(source, chunk_size) assert await stream.read_until(b'-boundary-like---') == (b'-boundary-like-' * 3) assert await stream.peek(17) == b'-boundary-like---' # NOTE(vytas): This is woefully unoptimized, and this test highlights that. # Work in progress. async def test_small_reads(reader3): ops = 0 read = 0 last = b'' size = 0 while True: size = max(1, (size + ops) % 1337) chunk = await reader3.read(size) if not chunk: break ops += 1 read += len(chunk) last = chunk assert ops == 4833 assert read == len(DATA3) assert last.endswith(b'4') @pytest.mark.slow async def test_small_reads_with_delimiter(reader3): ops = 0 read = 0 size = 0 while True: size = max(1, (size + ops) % 1337) chunk = await reader3.read_until(b'33', size) assert chunk.strip(b'1') == b'' if not chunk: break ops += 1 read += len(chunk) assert read == 1024 * 1024
AsyncSink
python
apache__airflow
airflow-core/tests/unit/utils/test_process_utils.py
{ "start": 8807, "end": 9450 }
class ____: @mock.patch("os.setpgid") def test_not_session_leader(self, mock_set_pid): pid = os.getpid() with mock.patch("os.getsid", autospec=True) as mock_get_sid: mock_get_sid.return_value = pid + 1 set_new_process_group() assert mock_set_pid.call_count == 1 @mock.patch("os.setpgid") def test_session_leader(self, mock_set_pid): pid = os.getpid() with mock.patch("os.getsid", autospec=True) as mock_get_sid: mock_get_sid.return_value = pid set_new_process_group() assert mock_set_pid.call_count == 0
TestSetNewProcessGroup
python
getsentry__sentry
tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py
{ "start": 291, "end": 2686 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.user = self.create_user(is_staff=True, is_superuser=True) self.canary_environment = Environment.objects.create( organization_id=self.organization.id, name="canary" ) self.production_environment = Environment.objects.create( organization_id=self.organization.id, name="production" ) self.login_as(user=self.user) self.basic_threshold = ReleaseThreshold.objects.create( threshold_type=0, trigger_type=0, value=100, window_in_seconds=1800, project=self.project, environment=self.canary_environment, ) def test_invalid_threshold_id(self) -> None: url = reverse( "sentry-api-0-project-release-thresholds-details", kwargs={ "organization_id_or_slug": self.organization.slug, "project_id_or_slug": self.project.slug, "release_threshold": 123, }, ) response = self.client.get(url) assert response.status_code == 404 def test_invalid_project(self) -> None: url = reverse( "sentry-api-0-project-release-thresholds-details", kwargs={ "organization_id_or_slug": self.organization.slug, "project_id_or_slug": "kingdom_of_the_crystal_skull", "release_threshold": self.basic_threshold.id, }, ) response = self.client.get(url) assert response.status_code == 404 def test_valid(self) -> None: url = reverse( "sentry-api-0-project-release-thresholds-details", kwargs={ "organization_id_or_slug": self.organization.slug, "project_id_or_slug": self.project.slug, "release_threshold": self.basic_threshold.id, }, ) response = self.client.get(url) assert response.status_code == 200 assert response.data["id"] == str(self.basic_threshold.id) assert response.data["threshold_type"] == "total_error_count" assert response.data["trigger_type"] == "over" assert response.data["value"] == 100 assert response.data["window_in_seconds"] == 1800
ReleaseThresholdDetailsGETTest
python
walkccc__LeetCode
solutions/260. Single Number III/260.py
{ "start": 0, "end": 331 }
class ____: def singleNumber(self, nums: list[int]) -> list[int]: xors = functools.reduce(operator.xor, nums) lowbit = xors & -xors ans = [0, 0] # Seperate `nums` into two groups by `lowbit`. for num in nums: if num & lowbit: ans[0] ^= num else: ans[1] ^= num return ans
Solution
python
openai__openai-python
src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py
{ "start": 1573, "end": 1837 }
class ____(BaseModel): token: str """The token that was used to generate the log probability.""" bytes: List[int] """The bytes that were used to generate the log probability.""" logprob: float """The log probability of the token."""
Logprob
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/time.py
{ "start": 3400, "end": 3974 }
class ____(NamedConfig[Literal["numpy.timedelta64"], TimeConfig]): """ The JSON representation of the ``TimeDelta64`` data type in Zarr V3. References ---------- This representation is defined in the numpy.timedelta64 [specification document](https://zarr-specs.readthedocs.io/en/latest/spec/v3/datatypes.html#numpy-timedelta64). Examples -------- ```python { "name": "numpy.timedelta64", "configuration": { "unit": "ms", "scale_factor": 1 } } ``` """
TimeDelta64JSON_V3
python
doocs__leetcode
solution/3200-3299/3254.Find the Power of K-Size Subarrays I/Solution.py
{ "start": 0, "end": 304 }
class ____: def resultsArray(self, nums: List[int], k: int) -> List[int]: n = len(nums) f = [1] * n for i in range(1, n): if nums[i] == nums[i - 1] + 1: f[i] = f[i - 1] + 1 return [nums[i] if f[i] >= k else -1 for i in range(k - 1, n)]
Solution
python
fluentpython__example-code-2e
10-dp-1class-func/classic_strategy.py
{ "start": 1309, "end": 1468 }
class ____(NamedTuple): product: str quantity: int price: Decimal def total(self) -> Decimal: return self.price * self.quantity
LineItem
python
sqlalchemy__sqlalchemy
test/orm/test_collection.py
{ "start": 3226, "end": 52868 }
class ____(OrderedDictFixture, fixtures.ORMTest): class Entity: def __init__(self, a=None, b=None, c=None): self.a = a self.b = b self.c = c def __repr__(self): return str((id(self), self.a, self.b, self.c)) class SimpleComparableEntity: def __init__(self, a=None, b=None): self.a = a self.b = b def __hash__(self): return hash(self.a) + hash(self.b) def __eq__(self, other): return other.a == self.a and other.b == self.b def __repr__(self): return str((id(self), self.a, self.b, self.c)) @classmethod def setup_test_class(cls): instrumentation.register_class(cls.Entity) @classmethod def teardown_test_class(cls): instrumentation.unregister_class(cls.Entity) _entity_id = 1 @classmethod def entity_maker(cls): cls._entity_id += 1 return cls.Entity(cls._entity_id) @classmethod def dictable_entity(cls, a=None, b=None, c=None): id_ = cls._entity_id = cls._entity_id + 1 return cls.Entity(a or str(id_), b or "value %s" % id, c) def _test_adapter(self, typecallable, creator=None, to_set=None): if creator is None: creator = self.entity_maker class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() adapter = collections.collection_adapter(obj.attr) direct = obj.attr if to_set is None: def to_set(col): return set(col) def assert_eq(): self.assert_(to_set(direct) == canary.data) self.assert_(set(adapter) == canary.data) def assert_ne(): self.assert_(to_set(direct) != canary.data) e1, e2 = creator(), creator() adapter.append_with_event(e1) assert_eq() adapter.append_without_event(e2) assert_ne() canary.data.add(e2) assert_eq() adapter.remove_without_event(e2) assert_ne() canary.data.remove(e2) assert_eq() adapter.remove_with_event(e1) assert_eq() self._test_empty_init(typecallable, creator=creator) def _test_empty_init(self, typecallable, creator=None): if creator is None: creator = self.entity_maker class Foo: pass instrumentation.register_class(Foo) _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) obj = Foo() e1 = creator() e2 = creator() implicit_collection = obj.attr is_true("attr" not in obj.__dict__) adapter = collections.collection_adapter(implicit_collection) is_true(adapter.empty) assert_raises_message( sa_exc.InvalidRequestError, "This is a special 'empty'", adapter.append_without_event, e1, ) adapter.append_with_event(e1) is_false(adapter.empty) is_true("attr" in obj.__dict__) adapter.append_without_event(e2) eq_(set(adapter), {e1, e2}) def _test_list(self, typecallable, creator=None): if creator is None: creator = self.entity_maker class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() adapter = collections.collection_adapter(obj.attr) direct = obj.attr control = list() def assert_eq(): eq_(set(direct), canary.data) eq_(set(adapter), canary.data) eq_(direct, control) # assume append() is available for list tests e = creator() direct.append(e) control.append(e) assert_eq() if hasattr(direct, "pop"): direct.pop() control.pop() assert_eq() if hasattr(direct, "__setitem__"): e = creator() direct.append(e) control.append(e) e = creator() direct[0] = e control[0] = e assert_eq() if reduce( and_, [ hasattr(direct, a) for a in ("__delitem__", "insert", "__len__") ], True, ): values = [creator(), creator(), creator(), creator()] direct[slice(0, 1)] = values control[slice(0, 1)] = values assert_eq() values = [creator(), creator()] direct[slice(0, -1, 2)] = values control[slice(0, -1, 2)] = values assert_eq() values = [creator()] direct[slice(0, -1)] = values control[slice(0, -1)] = values assert_eq() values = [creator(), creator(), creator()] control[:] = values direct[:] = values def invalid(): direct[slice(0, 6, 2)] = [creator()] assert_raises(ValueError, invalid) if hasattr(direct, "__delitem__"): e = creator() direct.append(e) control.append(e) del direct[-1] del control[-1] assert_eq() if hasattr(direct, "__getslice__"): for e in [creator(), creator(), creator(), creator()]: direct.append(e) control.append(e) del direct[:-3] del control[:-3] assert_eq() del direct[0:1] del control[0:1] assert_eq() del direct[::2] del control[::2] assert_eq() if hasattr(direct, "remove"): e = creator() direct.append(e) control.append(e) direct.remove(e) control.remove(e) assert_eq() if hasattr(direct, "__setitem__") or hasattr(direct, "__setslice__"): values = [creator(), creator()] direct[:] = values control[:] = values assert_eq() # test slice assignment where we slice assign to self, # currently a no-op, issue #4990 # note that in py2k, the bug does not exist but it recreates # the collection which breaks our fixtures here with canary.defer_dupe_check(): direct[:] = direct control[:] = control assert_eq() # we dont handle assignment of self to slices, as this # implies duplicate entries. behavior here is not well defined # and perhaps should emit a warning # direct[0:1] = list(direct) # control[0:1] = list(control) # assert_eq() # test slice assignment where # slice size goes over the number of items values = [creator(), creator()] direct[1:3] = values control[1:3] = values assert_eq() values = [creator(), creator()] direct[0:1] = values control[0:1] = values assert_eq() values = [creator()] direct[0:] = values control[0:] = values assert_eq() values = [creator()] direct[:1] = values control[:1] = values assert_eq() values = [creator()] direct[-1::2] = values control[-1::2] = values assert_eq() values = [creator()] * len(direct[1::2]) direct[1::2] = values control[1::2] = values assert_eq() values = [creator(), creator()] direct[-1:-3] = values control[-1:-3] = values assert_eq() values = [creator(), creator()] direct[-2:-1] = values control[-2:-1] = values assert_eq() values = [creator()] direct[0:0] = values control[0:0] = values assert_eq() if hasattr(direct, "__delitem__") or hasattr(direct, "__delslice__"): for i in range(1, 4): e = creator() direct.append(e) control.append(e) del direct[-1:] del control[-1:] assert_eq() del direct[1:2] del control[1:2] assert_eq() del direct[:] del control[:] assert_eq() if hasattr(direct, "clear"): for i in range(1, 4): e = creator() direct.append(e) control.append(e) direct.clear() control.clear() assert_eq() if hasattr(direct, "extend"): values = [creator(), creator(), creator()] direct.extend(values) control.extend(values) assert_eq() if hasattr(direct, "__iadd__"): values = [creator(), creator(), creator()] direct += values control += values assert_eq() direct += [] control += [] assert_eq() values = [creator(), creator()] obj.attr += values control += values assert_eq() if hasattr(direct, "__imul__"): direct *= 2 control *= 2 assert_eq() obj.attr *= 2 control *= 2 assert_eq() def _test_list_bulk(self, typecallable, creator=None): if creator is None: creator = self.entity_maker class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() direct = obj.attr e1 = creator() obj.attr.append(e1) like_me = typecallable() e2 = creator() like_me.append(e2) self.assert_(obj.attr is direct) obj.attr = like_me self.assert_(obj.attr is not direct) self.assert_(obj.attr is not like_me) self.assert_(set(obj.attr) == {e2}) self.assert_(e1 in canary.removed) self.assert_(e2 in canary.added) e3 = creator() real_list = [e3] obj.attr = real_list self.assert_(obj.attr is not real_list) self.assert_(set(obj.attr) == {e3}) self.assert_(e2 in canary.removed) self.assert_(e3 in canary.added) e4 = creator() try: obj.attr = {e4} self.assert_(False) except TypeError: self.assert_(e4 not in canary.data) self.assert_(e3 in canary.data) e5 = creator() e6 = creator() e7 = creator() obj.attr = [e5, e6, e7] self.assert_(e5 in canary.added) self.assert_(e6 in canary.added) self.assert_(e7 in canary.added) obj.attr = [e6, e7] self.assert_(e5 in canary.removed) self.assert_(e6 in canary.added) self.assert_(e7 in canary.added) self.assert_(e6 not in canary.removed) self.assert_(e7 not in canary.removed) def _test_list_dataclasses(self, typecallable): creator = self.SimpleComparableEntity @dataclasses.dataclass class Foo: attr: List[Any] = dataclasses.field(default_factory=list) canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() direct = obj.attr e1 = creator(a=1, b=2) collections.collection_adapter(direct).append_with_event(e1) like_me = typecallable() like_me.append(e1) eq_(dataclasses.asdict(obj), {"attr": like_me}) def test_list(self): self._test_adapter(list) self._test_list(list) self._test_list_bulk(list) self._test_list_dataclasses(list) def test_list_setitem_with_slices(self): # this is a "list" that has no __setslice__ # or __delslice__ methods. The __setitem__ # and __delitem__ must therefore accept # slice objects (i.e. as in py3k) class ListLike: def __init__(self): self.data = list() def append(self, item): self.data.append(item) def remove(self, item): self.data.remove(item) def insert(self, index, item): self.data.insert(index, item) def pop(self, index=-1): return self.data.pop(index) def extend(self): assert False def __len__(self): return len(self.data) def __setitem__(self, key, value): self.data[key] = value def __getitem__(self, key): return self.data[key] def __delitem__(self, key): del self.data[key] def __iter__(self): return iter(self.data) __hash__ = object.__hash__ def __eq__(self, other): return self.data == other def __repr__(self): return "ListLike(%s)" % repr(self.data) self._test_adapter(ListLike) self._test_list(ListLike) self._test_list_bulk(ListLike) def test_list_subclass(self): class MyList(list): pass self._test_adapter(MyList) self._test_list(MyList) self._test_list_bulk(MyList) self._test_list_dataclasses(MyList) self.assert_(getattr(MyList, "_sa_instrumented") == id(MyList)) def test_list_duck(self): class ListLike: def __init__(self): self.data = list() def append(self, item): self.data.append(item) def remove(self, item): self.data.remove(item) def insert(self, index, item): self.data.insert(index, item) def pop(self, index=-1): return self.data.pop(index) def extend(self): assert False def __iter__(self): return iter(self.data) __hash__ = object.__hash__ def __eq__(self, other): return self.data == other def __repr__(self): return "ListLike(%s)" % repr(self.data) self._test_adapter(ListLike) self._test_list(ListLike) self._test_list_bulk(ListLike) self.assert_(getattr(ListLike, "_sa_instrumented") == id(ListLike)) def test_list_emulates(self): class ListIsh: __emulates__ = list def __init__(self): self.data = list() def append(self, item): self.data.append(item) def remove(self, item): self.data.remove(item) def insert(self, index, item): self.data.insert(index, item) def pop(self, index=-1): return self.data.pop(index) def extend(self): assert False def __iter__(self): return iter(self.data) __hash__ = object.__hash__ def __eq__(self, other): return self.data == other def __repr__(self): return "ListIsh(%s)" % repr(self.data) self._test_adapter(ListIsh) self._test_list(ListIsh) self._test_list_bulk(ListIsh) self.assert_(getattr(ListIsh, "_sa_instrumented") == id(ListIsh)) def _test_set_wo_mutation(self, typecallable, creator=None): if creator is None: creator = self.entity_maker class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() e = creator() obj.attr.add(e) assert e in canary.added assert e not in canary.appended_wo_mutation obj.attr.add(e) assert e in canary.added assert e in canary.appended_wo_mutation e = creator() obj.attr.update({e}) assert e in canary.added assert e not in canary.appended_wo_mutation obj.attr.update({e}) assert e in canary.added assert e in canary.appended_wo_mutation def _test_set(self, typecallable, creator=None): if creator is None: creator = self.entity_maker class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() adapter = collections.collection_adapter(obj.attr) direct = obj.attr control = set() def assert_eq(): eq_(set(direct), canary.data) eq_(set(adapter), canary.data) eq_(direct, control) def addall(*values): for item in values: direct.add(item) control.add(item) assert_eq() def zap(): for item in list(direct): direct.remove(item) control.clear() addall(creator()) e = creator() addall(e) addall(e) if hasattr(direct, "remove"): e = creator() addall(e) direct.remove(e) control.remove(e) assert_eq() e = creator() try: direct.remove(e) except KeyError: assert_eq() self.assert_(e not in canary.removed) else: self.assert_(False) if hasattr(direct, "discard"): e = creator() addall(e) direct.discard(e) control.discard(e) assert_eq() e = creator() direct.discard(e) self.assert_(e not in canary.removed) assert_eq() if hasattr(direct, "update"): zap() e = creator() addall(e) values = {e, creator(), creator()} direct.update(values) control.update(values) assert_eq() if hasattr(direct, "__ior__"): zap() e = creator() addall(e) values = {e, creator(), creator()} direct |= values control |= values assert_eq() # cover self-assignment short-circuit values = {e, creator(), creator()} obj.attr |= values control |= values assert_eq() values = frozenset([e, creator()]) obj.attr |= values control |= values assert_eq() with expect_raises(TypeError): control |= [e, creator()] with expect_raises(TypeError): direct |= [e, creator()] addall(creator(), creator()) direct.clear() control.clear() assert_eq() # note: the clear test previously needs # to have executed in order for this to # pass in all cases; else there's the possibility # of non-deterministic behavior. addall(creator()) direct.pop() control.pop() assert_eq() if hasattr(direct, "difference_update"): zap() e = creator() addall(creator(), creator()) values = {creator()} direct.difference_update(values) control.difference_update(values) assert_eq() values.update({e, creator()}) direct.difference_update(values) control.difference_update(values) assert_eq() if hasattr(direct, "__isub__"): zap() e = creator() addall(creator(), creator()) values = {creator()} direct -= values control -= values assert_eq() values.update({e, creator()}) direct -= values control -= values assert_eq() values = {creator()} obj.attr -= values control -= values assert_eq() values = frozenset([creator()]) obj.attr -= values control -= values assert_eq() with expect_raises(TypeError): control -= [e, creator()] with expect_raises(TypeError): direct -= [e, creator()] if hasattr(direct, "intersection_update"): zap() e = creator() addall(e, creator(), creator()) values = set(control) direct.intersection_update(values) control.intersection_update(values) assert_eq() values.update({e, creator()}) direct.intersection_update(values) control.intersection_update(values) assert_eq() if hasattr(direct, "__iand__"): zap() e = creator() addall(e, creator(), creator()) values = set(control) direct &= values control &= values assert_eq() values.update({e, creator()}) direct &= values control &= values assert_eq() values.update({creator()}) obj.attr &= values control &= values assert_eq() with expect_raises(TypeError): control &= [e, creator()] with expect_raises(TypeError): direct &= [e, creator()] if hasattr(direct, "symmetric_difference_update"): zap() e = creator() addall(e, creator(), creator()) values = {e, creator()} direct.symmetric_difference_update(values) control.symmetric_difference_update(values) assert_eq() e = creator() addall(e) values = {e} direct.symmetric_difference_update(values) control.symmetric_difference_update(values) assert_eq() values = set() direct.symmetric_difference_update(values) control.symmetric_difference_update(values) assert_eq() if hasattr(direct, "__ixor__"): zap() e = creator() addall(e, creator(), creator()) values = {e, creator()} direct ^= values control ^= values assert_eq() e = creator() addall(e) values = {e} direct ^= values control ^= values assert_eq() values = set() direct ^= values control ^= values assert_eq() values = {creator()} obj.attr ^= values control ^= values assert_eq() with expect_raises(TypeError): control ^= [e, creator()] with expect_raises(TypeError): direct ^= [e, creator()] def _test_set_bulk(self, typecallable, creator=None): if creator is None: creator = self.entity_maker class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() direct = obj.attr e1 = creator() obj.attr.add(e1) like_me = typecallable() e2 = creator() like_me.add(e2) self.assert_(obj.attr is direct) obj.attr = like_me self.assert_(obj.attr is not direct) self.assert_(obj.attr is not like_me) self.assert_(obj.attr == {e2}) self.assert_(e1 in canary.removed) self.assert_(e2 in canary.added) e3 = creator() real_set = {e3} obj.attr = real_set self.assert_(obj.attr is not real_set) self.assert_(obj.attr == {e3}) self.assert_(e2 in canary.removed) self.assert_(e3 in canary.added) e4 = creator() try: obj.attr = [e4] self.assert_(False) except TypeError: self.assert_(e4 not in canary.data) self.assert_(e3 in canary.data) def _test_set_dataclasses(self, typecallable): creator = self.SimpleComparableEntity @dataclasses.dataclass class Foo: attr: MutableSet[Any] = dataclasses.field(default_factory=set) canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() direct = obj.attr e1 = creator(a=1, b=2) collections.collection_adapter(direct).append_with_event(e1) like_me = typecallable() like_me.add(e1) eq_(dataclasses.asdict(obj), {"attr": like_me}) def test_set(self): self._test_adapter(set) self._test_set(set) self._test_set_bulk(set) self._test_set_wo_mutation(set) self._test_set_dataclasses(set) def test_set_subclass(self): class MySet(set): pass self._test_adapter(MySet) self._test_set(MySet) self._test_set_bulk(MySet) self._test_set_dataclasses(MySet) self.assert_(getattr(MySet, "_sa_instrumented") == id(MySet)) def test_set_duck(self): class SetLike: def __init__(self): self.data = set() def add(self, item): self.data.add(item) def remove(self, item): self.data.remove(item) def discard(self, item): self.data.discard(item) def clear(self): self.data.clear() def pop(self): return self.data.pop() def update(self, other): self.data.update(other) def __iter__(self): return iter(self.data) __hash__ = object.__hash__ def __eq__(self, other): return self.data == other self._test_adapter(SetLike) self._test_set(SetLike) self._test_set_bulk(SetLike) self._test_set_dataclasses(SetLike) self.assert_(getattr(SetLike, "_sa_instrumented") == id(SetLike)) def test_set_emulates(self): class SetIsh: __emulates__ = set def __init__(self): self.data = set() def add(self, item): self.data.add(item) def remove(self, item): self.data.remove(item) def discard(self, item): self.data.discard(item) def pop(self): return self.data.pop() def update(self, other): self.data.update(other) def __iter__(self): return iter(self.data) def clear(self): self.data.clear() __hash__ = object.__hash__ def __eq__(self, other): return self.data == other self._test_adapter(SetIsh) self._test_set(SetIsh) self._test_set_bulk(SetIsh) self._test_set_dataclasses(SetIsh) self.assert_(getattr(SetIsh, "_sa_instrumented") == id(SetIsh)) def _test_dict_wo_mutation(self, typecallable, creator=None): if creator is None: creator = self.dictable_entity class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() e = creator() obj.attr[e.a] = e assert e in canary.added assert e not in canary.appended_wo_mutation with canary.defer_dupe_check(): # __setitem__ sets every time obj.attr[e.a] = e assert e in canary.added assert e not in canary.appended_wo_mutation if hasattr(obj.attr, "update"): e = creator() obj.attr.update({e.a: e}) assert e in canary.added assert e not in canary.appended_wo_mutation obj.attr.update({e.a: e}) assert e in canary.added assert e in canary.appended_wo_mutation e = creator() obj.attr.update(**{e.a: e}) assert e in canary.added assert e not in canary.appended_wo_mutation obj.attr.update(**{e.a: e}) assert e in canary.added assert e in canary.appended_wo_mutation if hasattr(obj.attr, "setdefault"): e = creator() obj.attr.setdefault(e.a, e) assert e in canary.added assert e not in canary.appended_wo_mutation obj.attr.setdefault(e.a, e) assert e in canary.added assert e in canary.appended_wo_mutation def _test_dict(self, typecallable, creator=None): if creator is None: creator = self.dictable_entity class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() adapter = collections.collection_adapter(obj.attr) direct = obj.attr control = dict() def assert_eq(): self.assert_(set(direct.values()) == canary.data) self.assert_(set(adapter) == canary.data) self.assert_(direct == control) def addall(*values): for item in values: direct.set(item) control[item.a] = item assert_eq() def zap(): for item in list(adapter): direct.remove(item) control.clear() # assume an 'set' method is available for tests addall(creator()) if hasattr(direct, "__setitem__"): e = creator() direct[e.a] = e control[e.a] = e assert_eq() e = creator(e.a, e.b) direct[e.a] = e control[e.a] = e assert_eq() if hasattr(direct, "__delitem__"): e = creator() addall(e) del direct[e.a] del control[e.a] assert_eq() e = creator() try: del direct[e.a] except KeyError: self.assert_(e not in canary.removed) if hasattr(direct, "clear"): addall(creator(), creator(), creator()) direct.clear() control.clear() assert_eq() direct.clear() control.clear() assert_eq() if hasattr(direct, "pop"): e = creator() addall(e) direct.pop(e.a) control.pop(e.a) assert_eq() e = creator() try: direct.pop(e.a) except KeyError: self.assert_(e not in canary.removed) if hasattr(direct, "popitem"): zap() e = creator() addall(e) direct.popitem() control.popitem() assert_eq() if hasattr(direct, "setdefault"): e = creator() val_a = direct.setdefault(e.a, e) val_b = control.setdefault(e.a, e) assert_eq() self.assert_(val_a is val_b) val_a = direct.setdefault(e.a, e) val_b = control.setdefault(e.a, e) assert_eq() self.assert_(val_a is val_b) if hasattr(direct, "update"): e = creator() d = {ee.a: ee for ee in [e, creator(), creator()]} addall(e, creator()) direct.update(d) control.update(d) assert_eq() kw = {ee.a: ee for ee in [e, creator()]} direct.update(**kw) control.update(**kw) assert_eq() def _test_dict_bulk(self, typecallable, creator=None): if creator is None: creator = self.dictable_entity class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() direct = obj.attr e1 = creator() collections.collection_adapter(direct).append_with_event(e1) like_me = typecallable() e2 = creator() like_me.set(e2) self.assert_(obj.attr is direct) obj.attr = like_me self.assert_(obj.attr is not direct) self.assert_(obj.attr is not like_me) self.assert_(set(collections.collection_adapter(obj.attr)) == {e2}) self.assert_(e1 in canary.removed) self.assert_(e2 in canary.added) # key validity on bulk assignment is a basic feature of # MappedCollection but is not present in basic, @converter-less # dict collections. e3 = creator() real_dict = dict(keyignored1=e3) obj.attr = real_dict self.assert_(obj.attr is not real_dict) self.assert_("keyignored1" not in obj.attr) eq_(set(collections.collection_adapter(obj.attr)), {e3}) self.assert_(e2 in canary.removed) self.assert_(e3 in canary.added) obj.attr = typecallable() eq_(list(collections.collection_adapter(obj.attr)), []) e4 = creator() try: obj.attr = [e4] self.assert_(False) except TypeError: self.assert_(e4 not in canary.data) def test_dict(self): assert_raises_message( sa_exc.ArgumentError, "Type InstrumentedDict must elect an appender " "method to be a collection class", self._test_adapter, dict, self.dictable_entity, to_set=lambda c: set(c.values()), ) assert_raises_message( sa_exc.ArgumentError, "Type InstrumentedDict must elect an appender method " "to be a collection class", self._test_dict, dict, ) def _test_dict_dataclasses(self, typecallable): creator = self.SimpleComparableEntity @dataclasses.dataclass class Foo: attr: MutableMapping[Any, Any] = dataclasses.field( default_factory=dict ) canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() direct = obj.attr e1 = creator(a=1, b=2) collections.collection_adapter(direct).append_with_event(e1) like_me = typecallable() like_me.set(e1) eq_(dataclasses.asdict(obj), {"attr": like_me}) def test_dict_subclass(self): class MyDict(dict): @collection.appender @collection.internally_instrumented def set(self, item, _sa_initiator=None): self.__setitem__(item.a, item, _sa_initiator=_sa_initiator) @collection.remover @collection.internally_instrumented def _remove(self, item, _sa_initiator=None): self.__delitem__(item.a, _sa_initiator=_sa_initiator) self._test_adapter( MyDict, self.dictable_entity, to_set=lambda c: set(c.values()) ) self._test_dict(MyDict) self._test_dict_bulk(MyDict) self._test_dict_wo_mutation(MyDict) self._test_dict_dataclasses(MyDict) self.assert_(getattr(MyDict, "_sa_instrumented") == id(MyDict)) def test_dict_subclass2(self): class MyEasyDict(collections.KeyFuncDict): def __init__(self, *args): super().__init__(lambda e: e.a, *args) self._test_adapter( MyEasyDict, self.dictable_entity, to_set=lambda c: set(c.values()) ) self._test_dict(MyEasyDict) self._test_dict_bulk(MyEasyDict) self._test_dict_wo_mutation(MyEasyDict) self._test_dict_dataclasses(MyEasyDict) self.assert_(getattr(MyEasyDict, "_sa_instrumented") == id(MyEasyDict)) def test_dict_subclass3(self, ordered_dict_mro): class MyOrdered(ordered_dict_mro): def __init__(self, *dict_args): collections.KeyFuncDict.__init__( self, lambda e: e.a, *dict_args ) util.OrderedDict.__init__(self) self._test_adapter( MyOrdered, self.dictable_entity, to_set=lambda c: set(c.values()) ) self._test_dict(MyOrdered) self._test_dict_bulk(MyOrdered) self._test_dict_wo_mutation(MyOrdered) self._test_dict_dataclasses(MyOrdered) self.assert_(getattr(MyOrdered, "_sa_instrumented") == id(MyOrdered)) def test_dict_duck(self): class DictLike: def __init__(self, *args): self.data = dict(*args) @collection.appender @collection.replaces(1) def set(self, item): current = self.data.get(item.a, None) self.data[item.a] = item return current @collection.remover def _remove(self, item): del self.data[item.a] def __setitem__(self, key, value): self.data[key] = value def __getitem__(self, key): return self.data[key] def __delitem__(self, key): del self.data[key] def values(self): return list(self.data.values()) def __contains__(self, key): return key in self.data @collection.iterator def itervalues(self): return iter(self.data.values()) __hash__ = object.__hash__ def __eq__(self, other): return self.data == other def __repr__(self): return "DictLike(%s)" % repr(self.data) self._test_adapter( DictLike, self.dictable_entity, to_set=lambda c: set(c.values()) ) self._test_dict(DictLike) self._test_dict_bulk(DictLike) self._test_dict_wo_mutation(DictLike) self._test_dict_dataclasses(DictLike) self.assert_(getattr(DictLike, "_sa_instrumented") == id(DictLike)) def test_dict_emulates(self): class DictIsh: __emulates__ = dict def __init__(self, *args): self.data = dict(*args) @collection.appender @collection.replaces(1) def set(self, item): current = self.data.get(item.a, None) self.data[item.a] = item return current @collection.remover def _remove(self, item): del self.data[item.a] def __setitem__(self, key, value): self.data[key] = value def __getitem__(self, key): return self.data[key] def __delitem__(self, key): del self.data[key] def values(self): return list(self.data.values()) def __contains__(self, key): return key in self.data @collection.iterator def itervalues(self): return iter(self.data.values()) __hash__ = object.__hash__ def __eq__(self, other): return self.data == other def __repr__(self): return "DictIsh(%s)" % repr(self.data) self._test_adapter( DictIsh, self.dictable_entity, to_set=lambda c: set(c.values()) ) self._test_dict(DictIsh) self._test_dict_bulk(DictIsh) self._test_dict_wo_mutation(DictIsh) self._test_dict_dataclasses(DictIsh) self.assert_(getattr(DictIsh, "_sa_instrumented") == id(DictIsh)) def _test_object(self, typecallable, creator=None): if creator is None: creator = self.entity_maker class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=typecallable, useobject=True, ) canary.listen(d) obj = Foo() adapter = collections.collection_adapter(obj.attr) direct = obj.attr control = set() def assert_eq(): self.assert_(set(direct) == canary.data) self.assert_(set(adapter) == canary.data) self.assert_(direct == control) # There is no API for object collections. We'll make one up # for the purposes of the test. e = creator() direct.push(e) control.add(e) assert_eq() direct.zark(e) control.remove(e) assert_eq() e = creator() direct.maybe_zark(e) control.discard(e) assert_eq() e = creator() direct.push(e) control.add(e) assert_eq() e = creator() direct.maybe_zark(e) control.discard(e) assert_eq() def test_object_duck(self): class MyCollection: def __init__(self): self.data = set() @collection.appender def push(self, item): self.data.add(item) @collection.remover def zark(self, item): self.data.remove(item) @collection.removes_return() def maybe_zark(self, item): if item in self.data: self.data.remove(item) return item @collection.iterator def __iter__(self): return iter(self.data) __hash__ = object.__hash__ def __eq__(self, other): return self.data == other self._test_adapter(MyCollection) self._test_object(MyCollection) self.assert_( getattr(MyCollection, "_sa_instrumented") == id(MyCollection) ) def test_object_emulates(self): class MyCollection2: __emulates__ = None def __init__(self): self.data = set() # looks like a list def append(self, item): assert False @collection.appender def push(self, item): self.data.add(item) @collection.remover def zark(self, item): self.data.remove(item) @collection.removes_return() def maybe_zark(self, item): if item in self.data: self.data.remove(item) return item @collection.iterator def __iter__(self): return iter(self.data) __hash__ = object.__hash__ def __eq__(self, other): return self.data == other self._test_adapter(MyCollection2) self._test_object(MyCollection2) self.assert_( getattr(MyCollection2, "_sa_instrumented") == id(MyCollection2) ) def test_recipes(self): class Custom: def __init__(self): self.data = [] @collection.appender @collection.adds("entity") def put(self, entity): self.data.append(entity) @collection.remover @collection.removes(1) def remove(self, entity): self.data.remove(entity) @collection.adds(1) def push(self, *args): self.data.append(args[0]) @collection.removes("entity") def yank(self, entity, arg): self.data.remove(entity) @collection.replaces(2) def replace(self, arg, entity, **kw): self.data.insert(0, entity) return self.data.pop() @collection.removes_return() def pop(self, key): return self.data.pop() @collection.iterator def __iter__(self): return iter(self.data) class Foo: pass canary = Canary() instrumentation.register_class(Foo) d = _register_attribute( Foo, "attr", uselist=True, typecallable=Custom, useobject=True ) canary.listen(d) obj = Foo() adapter = collections.collection_adapter(obj.attr) direct = obj.attr control = list() def assert_eq(): self.assert_(set(direct) == canary.data) self.assert_(set(adapter) == canary.data) self.assert_(list(direct) == control) creator = self.entity_maker e1 = creator() direct.put(e1) control.append(e1) assert_eq() e2 = creator() direct.put(entity=e2) control.append(e2) assert_eq() direct.remove(e2) control.remove(e2) assert_eq() direct.remove(entity=e1) control.remove(e1) assert_eq() e3 = creator() direct.push(e3) control.append(e3) assert_eq() direct.yank(e3, "blah") control.remove(e3) assert_eq() e4, e5, e6, e7 = creator(), creator(), creator(), creator() direct.put(e4) direct.put(e5) control.append(e4) control.append(e5) dr1 = direct.replace("foo", e6, bar="baz") control.insert(0, e6) cr1 = control.pop() assert_eq() self.assert_(dr1 is cr1) dr2 = direct.replace(arg=1, entity=e7) control.insert(0, e7) cr2 = control.pop() assert_eq() self.assert_(dr2 is cr2) dr3 = direct.pop("blah") cr3 = control.pop() assert_eq() self.assert_(dr3 is cr3) def test_lifecycle(self): class Foo: pass canary = Canary() creator = self.entity_maker instrumentation.register_class(Foo) d = _register_attribute(Foo, "attr", uselist=True, useobject=True) canary.listen(d) obj = Foo() col1 = obj.attr e1 = creator() obj.attr.append(e1) e2 = creator() bulk1 = [e2] # empty & sever col1 from obj obj.attr = bulk1 # as of [ticket:3913] the old collection # remains unchanged self.assert_(len(col1) == 1) self.assert_(len(canary.data) == 1) self.assert_(obj.attr is not col1) self.assert_(obj.attr is not bulk1) self.assert_(obj.attr == bulk1) e3 = creator() col1.append(e3) self.assert_(e3 not in canary.data) self.assert_(collections.collection_adapter(col1) is None) obj.attr[0] = e3 self.assert_(e3 in canary.data)
CollectionsTest
python
django__django
django/db/backends/mysql/base.py
{ "start": 3467, "end": 16345 }
class ____(BaseDatabaseWrapper): vendor = "mysql" # This dictionary maps Field objects to their associated MySQL column # types, as strings. Column-type strings can contain format strings; # they'll be interpolated against the values of Field.__dict__ before being # output. If a column type is set to None, it won't be included in the # output. _data_types = { "AutoField": "integer AUTO_INCREMENT", "BigAutoField": "bigint AUTO_INCREMENT", "BinaryField": "longblob", "BooleanField": "bool", "CharField": "varchar(%(max_length)s)", "DateField": "date", "DateTimeField": "datetime(6)", "DecimalField": "numeric(%(max_digits)s, %(decimal_places)s)", "DurationField": "bigint", "FileField": "varchar(%(max_length)s)", "FilePathField": "varchar(%(max_length)s)", "FloatField": "double precision", "IntegerField": "integer", "BigIntegerField": "bigint", "IPAddressField": "char(15)", "GenericIPAddressField": "char(39)", "JSONField": "json", "PositiveBigIntegerField": "bigint UNSIGNED", "PositiveIntegerField": "integer UNSIGNED", "PositiveSmallIntegerField": "smallint UNSIGNED", "SlugField": "varchar(%(max_length)s)", "SmallAutoField": "smallint AUTO_INCREMENT", "SmallIntegerField": "smallint", "TextField": "longtext", "TimeField": "time(6)", "UUIDField": "char(32)", } @cached_property def data_types(self): _data_types = self._data_types.copy() if self.features.has_native_uuid_field: _data_types["UUIDField"] = "uuid" return _data_types # For these data types MySQL and MariaDB don't support full width database # indexes. _limited_data_types = ( "tinyblob", "blob", "mediumblob", "longblob", "tinytext", "text", "mediumtext", "longtext", "json", ) operators = { "exact": "= %s", "iexact": "LIKE %s", "contains": "LIKE BINARY %s", "icontains": "LIKE %s", "gt": "> %s", "gte": ">= %s", "lt": "< %s", "lte": "<= %s", "startswith": "LIKE BINARY %s", "endswith": "LIKE BINARY %s", "istartswith": "LIKE %s", "iendswith": "LIKE %s", } # The patterns below are used to generate SQL pattern lookup clauses when # the right-hand side of the lookup isn't a raw string (it might be an # expression or the result of a bilateral transformation). In those cases, # special characters for LIKE operators (e.g. \, *, _) should be escaped on # database side. # # Note: we use str.format() here for readability as '%' is used as a # wildcard for the LIKE operator. pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\\', '\\\\'), '%%', '\%%'), '_', '\_')" pattern_ops = { "contains": "LIKE BINARY CONCAT('%%', {}, '%%')", "icontains": "LIKE CONCAT('%%', {}, '%%')", "startswith": "LIKE BINARY CONCAT({}, '%%')", "istartswith": "LIKE CONCAT({}, '%%')", "endswith": "LIKE BINARY CONCAT('%%', {})", "iendswith": "LIKE CONCAT('%%', {})", } isolation_levels = { "read uncommitted", "read committed", "repeatable read", "serializable", } Database = Database SchemaEditorClass = DatabaseSchemaEditor # Classes instantiated in __init__(). client_class = DatabaseClient creation_class = DatabaseCreation features_class = DatabaseFeatures introspection_class = DatabaseIntrospection ops_class = DatabaseOperations validation_class = DatabaseValidation def get_database_version(self): return self.mysql_version def get_connection_params(self): kwargs = { "conv": django_conversions, "charset": "utf8mb4", } settings_dict = self.settings_dict if settings_dict["USER"]: kwargs["user"] = settings_dict["USER"] if settings_dict["NAME"]: kwargs["database"] = settings_dict["NAME"] if settings_dict["PASSWORD"]: kwargs["password"] = settings_dict["PASSWORD"] if settings_dict["HOST"].startswith("/"): kwargs["unix_socket"] = settings_dict["HOST"] elif settings_dict["HOST"]: kwargs["host"] = settings_dict["HOST"] if settings_dict["PORT"]: kwargs["port"] = int(settings_dict["PORT"]) # We need the number of potentially affected rows after an # "UPDATE", not the number of changed rows. kwargs["client_flag"] = CLIENT.FOUND_ROWS # Validate the transaction isolation level, if specified. options = settings_dict["OPTIONS"].copy() isolation_level = options.pop("isolation_level", "read committed") if isolation_level: isolation_level = isolation_level.lower() if isolation_level not in self.isolation_levels: raise ImproperlyConfigured( "Invalid transaction isolation level '%s' specified.\n" "Use one of %s, or None." % ( isolation_level, ", ".join("'%s'" % s for s in sorted(self.isolation_levels)), ) ) self.isolation_level = isolation_level kwargs.update(options) return kwargs @async_unsafe def get_new_connection(self, conn_params): connection = Database.connect(**conn_params) return connection def init_connection_state(self): super().init_connection_state() assignments = [] if self.features.is_sql_auto_is_null_enabled: # SQL_AUTO_IS_NULL controls whether an AUTO_INCREMENT column on # a recently inserted row will return when the field is tested # for NULL. Disabling this brings this aspect of MySQL in line # with SQL standards. assignments.append("SET SQL_AUTO_IS_NULL = 0") if self.isolation_level: assignments.append( "SET SESSION TRANSACTION ISOLATION LEVEL %s" % self.isolation_level.upper() ) if assignments: with self.cursor() as cursor: cursor.execute("; ".join(assignments)) @async_unsafe def create_cursor(self, name=None): cursor = self.connection.cursor() return CursorWrapper(cursor) def _rollback(self): try: BaseDatabaseWrapper._rollback(self) except Database.NotSupportedError: pass def _set_autocommit(self, autocommit): with self.wrap_database_errors: self.connection.autocommit(autocommit) def disable_constraint_checking(self): """ Disable foreign key checks, primarily for use in adding rows with forward references. Always return True to indicate constraint checks need to be re-enabled. """ with self.cursor() as cursor: cursor.execute("SET foreign_key_checks=0") return True def enable_constraint_checking(self): """ Re-enable foreign key checks after they have been disabled. """ # Override needs_rollback in case constraint_checks_disabled is # nested inside transaction.atomic. self.needs_rollback, needs_rollback = False, self.needs_rollback try: with self.cursor() as cursor: cursor.execute("SET foreign_key_checks=1") finally: self.needs_rollback = needs_rollback def check_constraints(self, table_names=None): """ Check each table name in `table_names` for rows with invalid foreign key references. This method is intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to determine if rows with invalid references were entered while constraint checks were off. """ with self.cursor() as cursor: if table_names is None: table_names = self.introspection.table_names(cursor) for table_name in table_names: primary_key_column_name = self.introspection.get_primary_key_column( cursor, table_name ) if not primary_key_column_name: continue relations = self.introspection.get_relations(cursor, table_name) for column_name, ( referenced_column_name, referenced_table_name, _, ) in relations.items(): cursor.execute( """ SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING LEFT JOIN `%s` as REFERRED ON (REFERRING.`%s` = REFERRED.`%s`) WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL """ % ( primary_key_column_name, column_name, table_name, referenced_table_name, column_name, referenced_column_name, column_name, referenced_column_name, ) ) for bad_row in cursor.fetchall(): raise IntegrityError( "The row in table '%s' with primary key '%s' has an " "invalid foreign key: %s.%s contains a value '%s' that " "does not have a corresponding value in %s.%s." % ( table_name, bad_row[0], table_name, column_name, bad_row[1], referenced_table_name, referenced_column_name, ) ) def is_usable(self): try: self.connection.ping() except Database.Error: return False else: return True @cached_property def display_name(self): return "MariaDB" if self.mysql_is_mariadb else "MySQL" @cached_property def data_type_check_constraints(self): if self.features.supports_column_check_constraints: check_constraints = { "PositiveBigIntegerField": "`%(column)s` >= 0", "PositiveIntegerField": "`%(column)s` >= 0", "PositiveSmallIntegerField": "`%(column)s` >= 0", } return check_constraints return {} @cached_property def mysql_server_data(self): with self.temporary_connection() as cursor: # Select some server variables and test if the time zone # definitions are installed. CONVERT_TZ returns NULL if 'UTC' # timezone isn't loaded into the mysql.time_zone table. cursor.execute( """ SELECT VERSION(), @@sql_mode, @@default_storage_engine, @@sql_auto_is_null, @@lower_case_table_names, CONVERT_TZ('2001-01-01 01:00:00', 'UTC', 'UTC') IS NOT NULL """ ) row = cursor.fetchone() return { "version": row[0], "sql_mode": row[1], "default_storage_engine": row[2], "sql_auto_is_null": bool(row[3]), "lower_case_table_names": bool(row[4]), "has_zoneinfo_database": bool(row[5]), } @cached_property def mysql_server_info(self): return self.mysql_server_data["version"] @cached_property def mysql_version(self): match = server_version_re.match(self.mysql_server_info) if not match: raise Exception( "Unable to determine MySQL version from version string %r" % self.mysql_server_info ) return tuple(int(x) for x in match.groups()) @cached_property def mysql_is_mariadb(self): return "mariadb" in self.mysql_server_info.lower() @cached_property def sql_mode(self): sql_mode = self.mysql_server_data["sql_mode"] return set(sql_mode.split(",") if sql_mode else ())
DatabaseWrapper
python
huggingface__transformers
src/transformers/models/hubert/modular_hubert.py
{ "start": 11526, "end": 11573 }
class ____(Wav2Vec2ForCTC): pass
HubertForCTC
python
django-import-export__django-import-export
tests/core/tests/resources.py
{ "start": 871, "end": 1002 }
class ____(resources.ModelResource): class Meta: model = Book store_instance = True
BookResourceWithStoreInstance
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 8186, "end": 8268 }
class ____(UUIDProject): artist = models.CharField(max_length=30)
UUIDArtProject
python
getsentry__sentry
tests/sentry/core/endpoints/test_project_details.py
{ "start": 59056, "end": 67152 }
class ____(APITestCase): endpoint = "sentry-api-0-project-details" method = "put" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.options_dict = { "sentry:resolve_age": 1, "sentry:scrub_data": False, "sentry:scrub_defaults": False, } self.other_project = self.create_project() for key, value in self.options_dict.items(): self.other_project.update_option(key=key, value=value) self.teams = [self.create_team(), self.create_team(), self.create_team()] for team in self.teams: ProjectTeam.objects.create(team=team, project=self.other_project) self.environments = [ self.create_environment(project=self.other_project), self.create_environment(project=self.other_project), ] self.ownership = ProjectOwnership.objects.create( project=self.other_project, raw='{"hello":"hello"}', schema={"hello": "hello"} ) Rule.objects.create(project=self.other_project, label="rule1") Rule.objects.create(project=self.other_project, label="rule2") Rule.objects.create(project=self.other_project, label="rule3") # there is a default rule added to project self.rules = Rule.objects.filter(project_id=self.other_project.id).order_by("label") def assert_other_project_settings_not_changed(self): # other_project should not have changed. This should check that. self.assert_settings_copied(self.other_project) def assert_settings_copied(self, project): for key, value in self.options_dict.items(): assert project.get_option(key) == value project_teams = ProjectTeam.objects.filter(project_id=project.id, team__in=self.teams) assert len(project_teams) == len(self.teams) project_env = EnvironmentProject.objects.filter( project_id=project.id, environment__in=self.environments ) assert len(project_env) == len(self.environments) ownership = ProjectOwnership.objects.get(project_id=project.id) assert ownership.raw == self.ownership.raw assert ownership.schema == self.ownership.schema rules = Rule.objects.filter(project_id=project.id).order_by("label") for rule, other_rule in zip(rules, self.rules): assert rule.label == other_rule.label def assert_settings_not_copied(self, project, teams=()): for key in self.options_dict.keys(): assert project.get_option(key) is None project_teams = ProjectTeam.objects.filter(project_id=project.id, team__in=teams) assert len(project_teams) == len(teams) project_envs = EnvironmentProject.objects.filter(project_id=project.id) assert len(project_envs) == 0 assert not ProjectOwnership.objects.filter(project_id=project.id).exists() # default rule rules = Rule.objects.filter(project_id=project.id) assert len(rules) == 1 assert rules[0].label == "Send a notification for high priority issues" def test_simple(self) -> None: project = self.create_project() self.get_success_response( project.organization.slug, project.slug, copy_from_project=self.other_project.id ) self.assert_settings_copied(project) self.assert_other_project_settings_not_changed() def test_additional_params_in_payload(self) -> None: # Right now these are overwritten with the copied project's settings project = self.create_project() data = { "copy_from_project": self.other_project.id, "sentry:resolve_age": 2, "sentry:scrub_data": True, "sentry:scrub_defaults": True, } self.get_success_response(project.organization.slug, project.slug, **data) self.assert_settings_copied(project) self.assert_other_project_settings_not_changed() def test_project_from_another_org(self) -> None: project = self.create_project(fire_project_created=True) other_project = self.create_project( organization=self.create_organization(), fire_project_created=True ) resp = self.get_error_response( project.organization.slug, project.slug, copy_from_project=other_project.id, status_code=400, ) assert resp.data == {"copy_from_project": ["Project to copy settings from not found."]} self.assert_settings_not_copied(project) self.assert_settings_not_copied(other_project) def test_project_does_not_exist(self) -> None: project = self.create_project(fire_project_created=True) resp = self.get_error_response( project.organization.slug, project.slug, copy_from_project=1234567890, status_code=400 ) assert resp.data == {"copy_from_project": ["Project to copy settings from not found."]} self.assert_settings_not_copied(project) def test_user_does_not_have_access_to_copy_from_project(self) -> None: user = self.create_user() self.login_as(user=user) team = self.create_team(members=[user]) project = self.create_project(teams=[team], fire_project_created=True) with unguarded_write(using=router.db_for_write(OrganizationMember)): OrganizationMember.objects.filter( user_id=user.id, organization=self.organization ).update(role="admin") self.organization.flags.allow_joinleave = False self.organization.save() resp = self.get_error_response( project.organization.slug, project.slug, copy_from_project=self.other_project.id, status_code=400, ) assert resp.data == { "copy_from_project": [ "Project settings cannot be copied from a project you do not have access to." ] } self.assert_other_project_settings_not_changed() self.assert_settings_not_copied(project, teams=[team]) def test_project_coping_from_has_team_user_lacks_write_access(self) -> None: user = self.create_user() self.login_as(user=user) team = self.create_team(members=[user]) project = self.create_project(teams=[team], fire_project_created=True) with unguarded_write(using=router.db_for_write(OrganizationMember)): OrganizationMember.objects.filter( user_id=user.id, organization=self.organization ).update(role="admin") self.other_project.add_team(team) # adding team user lacks write access to self.other_project.add_team(self.create_team()) self.organization.flags.allow_joinleave = False self.organization.save() resp = self.get_error_response( project.organization.slug, project.slug, copy_from_project=self.other_project.id, status_code=400, ) assert resp.data == { "copy_from_project": [ "Project settings cannot be copied from a project with a team you do not have write access to." ] } self.assert_other_project_settings_not_changed() self.assert_settings_not_copied(project, teams=[team]) @mock.patch("sentry.models.project.Project.copy_settings_from") def test_copy_project_settings_fails(self, mock_copy_settings_from: mock.MagicMock) -> None: mock_copy_settings_from.return_value = False project = self.create_project(fire_project_created=True) resp = self.get_error_response( project.organization.slug, project.slug, copy_from_project=self.other_project.id, status_code=409, ) assert resp.data["detail"] == "Copy project settings failed." self.assert_settings_not_copied(project) self.assert_other_project_settings_not_changed()
CopyProjectSettingsTest
python
viewflow__viewflow
viewflow/workflow/admin.py
{ "start": 1648, "end": 2443 }
class ____(admin.ModelAdmin): """List all of viewflow tasks.""" icon = '<i class="material-icons">assignment_turned_in</i>' actions = None date_hierarchy = "created" list_display = [ "pk", "created", "process", "status", "owner", "owner_permission", "token", "started", "finished", ] list_display_links = ["pk", "created", "process"] list_filter = ["status", "process__flow_class"] readonly_fields = [ "process", "status", "flow_task", "started", "finished", "previous", "token", "owner", ] def has_add_permission(self, request, obj=None): """Disable manually task creation.""" return False
TaskAdmin
python
huggingface__transformers
src/transformers/models/camembert/modeling_camembert.py
{ "start": 23653, "end": 25041 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.activation = nn.Tanh() def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] pooled_output = self.dense(first_token_tensor) pooled_output = self.activation(pooled_output) return pooled_output @auto_docstring( custom_intro=""" The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of cross-attention is added between the self-attention layers, following the architecture described in [Attention is all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass. """ )
CamembertPooler
python
catalyst-team__catalyst
catalyst/contrib/data/dataset_ml.py
{ "start": 119, "end": 645 }
class ____(Dataset, ABC): """ Base class for datasets adapted for metric learning train stage. """ @abstractmethod def get_labels(self) -> List[int]: """ Dataset for metric learning must provide label of each sample for forming positive and negative pairs during the training based on these labels. Raises: NotImplementedError: You should implement it # noqa: DAR402 """ raise NotImplementedError()
MetricLearningTrainDataset
python
django-mptt__django-mptt
mptt/forms.py
{ "start": 1993, "end": 2656 }
class ____(forms.ChoiceField): """A ChoiceField for specifying position relative to another node.""" FIRST_CHILD = "first-child" LAST_CHILD = "last-child" LEFT = "left" RIGHT = "right" DEFAULT_CHOICES = ( (FIRST_CHILD, _("First child")), (LAST_CHILD, _("Last child")), (LEFT, _("Left sibling")), (RIGHT, _("Right sibling")), ) def __init__(self, *args, **kwargs): if "choices" not in kwargs: kwargs["choices"] = self.DEFAULT_CHOICES super().__init__(*args, **kwargs) # Forms #######################################################################
TreeNodePositionField
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 153085, "end": 153540 }
class ____: _col_type = None "The concrete range class these tests are for." _col_str = None "The corresponding PG type name." _epsilon = None """A small value used to generate range variants""" def _data_str(self): """return string form of a sample range""" raise NotImplementedError() def _data_obj(self): """return Range form of the same range""" raise NotImplementedError()
_RangeTests
python
eth-brownie__brownie
brownie/network/contract.py
{ "start": 66795, "end": 67575 }
class ____(_ContractMethod): """ A public payable or non-payable contract method. Attributes ---------- abi : dict Contract ABI specific to this method. signature : str Bytes4 method signature. """ def __call__(self, *args: Any, silent: bool = False) -> TransactionReceiptType: """ Broadcast a transaction that calls this contract method. Arguments --------- *args Contract method inputs. You can optionally provide a dictionary of transaction properties as the last arg. Returns ------- TransactionReceipt Object representing the broadcasted transaction. """ return self.transact(*args, silent=silent)
ContractTx
python
astropy__astropy
astropy/samp/tests/test_hub_proxy.py
{ "start": 181, "end": 1183 }
class ____: def setup_method(self, method): self.hub = SAMPHubServer(web_profile=False, mode="multiple", pool_size=1) self.hub.start() self.proxy = SAMPHubProxy() self.proxy.connect(hub=self.hub, pool_size=1) def teardown_method(self, method): if self.proxy.is_connected: self.proxy.disconnect() self.hub.stop() def test_is_connected(self): assert self.proxy.is_connected def test_disconnect(self): self.proxy.disconnect() def test_ping(self): self.proxy.ping() def test_registration(self): result = self.proxy.register(self.proxy.lockfile["samp.secret"]) self.proxy.unregister(result["samp.private-key"]) def test_custom_lockfile(tmp_path): lockfile = str(tmp_path / ".samptest") hub = SAMPHubServer(web_profile=False, lockfile=lockfile, pool_size=1) hub.start() proxy = SAMPHubProxy() proxy.connect(hub=hub, pool_size=1) hub.stop()
TestHubProxy
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/unary.py
{ "start": 2316, "end": 22246 }
class ____(Expr): """Class representing unary functions of an expression.""" __slots__ = ("name", "options") _non_child = ("dtype", "name", "options") # Note: log, and pow are handled via translation to binops _OP_MAPPING: ClassVar[dict[str, plc.unary.UnaryOperator]] = { "sin": plc.unary.UnaryOperator.SIN, "cos": plc.unary.UnaryOperator.COS, "tan": plc.unary.UnaryOperator.TAN, "arcsin": plc.unary.UnaryOperator.ARCSIN, "arccos": plc.unary.UnaryOperator.ARCCOS, "arctan": plc.unary.UnaryOperator.ARCTAN, "sinh": plc.unary.UnaryOperator.SINH, "cosh": plc.unary.UnaryOperator.COSH, "tanh": plc.unary.UnaryOperator.TANH, "arcsinh": plc.unary.UnaryOperator.ARCSINH, "arccosh": plc.unary.UnaryOperator.ARCCOSH, "arctanh": plc.unary.UnaryOperator.ARCTANH, "exp": plc.unary.UnaryOperator.EXP, "sqrt": plc.unary.UnaryOperator.SQRT, "cbrt": plc.unary.UnaryOperator.CBRT, "ceil": plc.unary.UnaryOperator.CEIL, "floor": plc.unary.UnaryOperator.FLOOR, "abs": plc.unary.UnaryOperator.ABS, "bit_invert": plc.unary.UnaryOperator.BIT_INVERT, "not": plc.unary.UnaryOperator.NOT, "negate": plc.unary.UnaryOperator.NEGATE, } _supported_misc_fns = frozenset( { "as_struct", "drop_nulls", "fill_null", "fill_null_with_strategy", "mask_nans", "null_count", "rank", "round", "set_sorted", "top_k", "unique", "value_counts", } ) _supported_cum_aggs = frozenset( { "cum_min", "cum_max", "cum_prod", "cum_sum", } ) _supported_fns = frozenset().union( _supported_misc_fns, _supported_cum_aggs, _OP_MAPPING.keys() ) def __init__( self, dtype: DataType, name: str, options: tuple[Any, ...], *children: Expr ) -> None: self.dtype = dtype self.name = name self.options = options self.children = children self.is_pointwise = self.name not in ( "as_struct", "cum_max", "cum_min", "cum_prod", "cum_sum", "drop_nulls", "rank", "top_k", "unique", ) if self.name not in UnaryFunction._supported_fns: raise NotImplementedError(f"Unary function {name=}") # pragma: no cover if self.name in UnaryFunction._supported_cum_aggs: (reverse,) = self.options if reverse: raise NotImplementedError( "reverse=True is not supported for cumulative aggregations" ) if self.name == "fill_null_with_strategy" and self.options[1] not in {0, None}: raise NotImplementedError( "Filling null values with limit specified is not yet supported." ) if self.name == "rank": method, _, _ = self.options if method not in {"average", "min", "max", "dense", "ordinal"}: raise NotImplementedError( f"ranking with {method=} is not yet supported" ) def do_evaluate( self, df: DataFrame, *, context: ExecutionContext = ExecutionContext.FRAME ) -> Column: """Evaluate this expression given a dataframe for context.""" if self.name == "mask_nans": (child,) = self.children return child.evaluate(df, context=context).mask_nans(stream=df.stream) if self.name == "null_count": (column,) = (child.evaluate(df, context=context) for child in self.children) return Column( plc.Column.from_scalar( plc.Scalar.from_py( column.null_count, self.dtype.plc_type, stream=df.stream ), 1, stream=df.stream, ), dtype=self.dtype, ) arg: plc.Column | plc.Scalar if self.name == "round": ( decimal_places, round_mode, ) = self.options (values,) = (child.evaluate(df, context=context) for child in self.children) return Column( plc.round.round( values.obj, decimal_places, ( plc.round.RoundingMethod.HALF_EVEN if round_mode == "half_to_even" else plc.round.RoundingMethod.HALF_UP ), stream=df.stream, ), dtype=self.dtype, ).sorted_like(values) # pragma: no cover elif self.name == "unique": (maintain_order,) = self.options (values,) = (child.evaluate(df, context=context) for child in self.children) # Only one column, so keep_any is the same as keep_first # for stable distinct keep = plc.stream_compaction.DuplicateKeepOption.KEEP_ANY if values.is_sorted: maintain_order = True (compacted,) = plc.stream_compaction.unique( plc.Table([values.obj]), [0], keep, plc.types.NullEquality.EQUAL, stream=df.stream, ).columns() else: distinct = ( plc.stream_compaction.stable_distinct if maintain_order else plc.stream_compaction.distinct ) (compacted,) = distinct( plc.Table([values.obj]), [0], keep, plc.types.NullEquality.EQUAL, plc.types.NanEquality.ALL_EQUAL, stream=df.stream, ).columns() column = Column(compacted, dtype=self.dtype) if maintain_order: column = column.sorted_like(values) return column elif self.name == "set_sorted": (column,) = (child.evaluate(df, context=context) for child in self.children) (asc,) = self.options order = ( plc.types.Order.ASCENDING if asc == "ascending" else plc.types.Order.DESCENDING ) null_order = plc.types.NullOrder.BEFORE if column.null_count > 0 and (n := column.size) > 1: # PERF: This invokes four stream synchronisations! has_nulls_first = not plc.copying.get_element( column.obj, 0, stream=df.stream ).is_valid(df.stream) has_nulls_last = not plc.copying.get_element( column.obj, n - 1, stream=df.stream ).is_valid(df.stream) if (order == plc.types.Order.DESCENDING and has_nulls_first) or ( order == plc.types.Order.ASCENDING and has_nulls_last ): null_order = plc.types.NullOrder.AFTER return column.set_sorted( is_sorted=plc.types.Sorted.YES, order=order, null_order=null_order, ) elif self.name == "value_counts": (sort, _, _, normalize) = self.options count_agg = [plc.aggregation.count(plc.types.NullPolicy.INCLUDE)] gb_requests = [ plc.groupby.GroupByRequest( child.evaluate(df, context=context).obj, count_agg ) for child in self.children ] (keys_table, (counts_table,)) = plc.groupby.GroupBy( df.table, null_handling=plc.types.NullPolicy.INCLUDE ).aggregate(gb_requests) if sort: sort_indices = plc.sorting.stable_sorted_order( counts_table, [plc.types.Order.DESCENDING], [plc.types.NullOrder.BEFORE], stream=df.stream, ) counts_table = plc.copying.gather( counts_table, sort_indices, plc.copying.OutOfBoundsPolicy.DONT_CHECK, stream=df.stream, ) keys_table = plc.copying.gather( keys_table, sort_indices, plc.copying.OutOfBoundsPolicy.DONT_CHECK, stream=df.stream, ) keys_col = keys_table.columns()[0] counts_col = counts_table.columns()[0] if normalize: total_counts = plc.reduce.reduce( counts_col, plc.aggregation.sum(), plc.DataType(plc.TypeId.UINT64), stream=df.stream, ) counts_col = plc.binaryop.binary_operation( counts_col, total_counts, plc.binaryop.BinaryOperator.DIV, plc.DataType(plc.TypeId.FLOAT64), stream=df.stream, ) elif counts_col.type().id() == plc.TypeId.INT32: counts_col = plc.unary.cast( counts_col, plc.DataType(plc.TypeId.UINT32), stream=df.stream ) plc_column = plc.Column( self.dtype.plc_type, counts_col.size(), None, None, 0, 0, [keys_col, counts_col], ) return Column(plc_column, dtype=self.dtype) elif self.name == "drop_nulls": (column,) = (child.evaluate(df, context=context) for child in self.children) if column.null_count == 0: return column return Column( plc.stream_compaction.drop_nulls( plc.Table([column.obj]), [0], 1, stream=df.stream ).columns()[0], dtype=self.dtype, ) elif self.name == "fill_null": column = self.children[0].evaluate(df, context=context) if column.null_count == 0: return column fill_value = self.children[1] if isinstance(fill_value, Literal): arg = plc.Scalar.from_py( fill_value.value, fill_value.dtype.plc_type, stream=df.stream ) else: evaluated = fill_value.evaluate(df, context=context) arg = ( evaluated.obj_scalar(stream=df.stream) if evaluated.is_scalar else evaluated.obj ) if isinstance(arg, plc.Scalar) and dtypes.can_cast( column.dtype.plc_type, arg.type() ): # pragma: no cover arg = ( Column( plc.Column.from_scalar(arg, 1, stream=df.stream), dtype=fill_value.dtype, ) .astype(column.dtype, stream=df.stream) .obj.to_scalar(stream=df.stream) ) return Column( plc.replace.replace_nulls(column.obj, arg, stream=df.stream), dtype=self.dtype, ) elif self.name == "fill_null_with_strategy": column = self.children[0].evaluate(df, context=context) strategy, limit = self.options if ( column.null_count == 0 or limit == 0 or ( column.null_count == column.size and strategy not in {"zero", "one"} ) ): return column replacement: plc.replace.ReplacePolicy | plc.Scalar if strategy == "forward": replacement = plc.replace.ReplacePolicy.PRECEDING elif strategy == "backward": replacement = plc.replace.ReplacePolicy.FOLLOWING elif strategy == "min": replacement = plc.reduce.reduce( column.obj, plc.aggregation.min(), column.dtype.plc_type, stream=df.stream, ) elif strategy == "max": replacement = plc.reduce.reduce( column.obj, plc.aggregation.max(), column.dtype.plc_type, stream=df.stream, ) elif strategy == "mean": replacement = plc.reduce.reduce( column.obj, plc.aggregation.mean(), plc.DataType(plc.TypeId.FLOAT64), stream=df.stream, ) elif strategy == "zero": replacement = plc.scalar.Scalar.from_py( 0, dtype=column.dtype.plc_type, stream=df.stream ) elif strategy == "one": replacement = plc.scalar.Scalar.from_py( 1, dtype=column.dtype.plc_type, stream=df.stream ) else: assert_never(strategy) # pragma: no cover if strategy == "mean": return Column( plc.replace.replace_nulls( plc.unary.cast( column.obj, plc.DataType(plc.TypeId.FLOAT64), stream=df.stream, ), replacement, stream=df.stream, ), dtype=self.dtype, ).astype(self.dtype, stream=df.stream) return Column( plc.replace.replace_nulls(column.obj, replacement, stream=df.stream), dtype=self.dtype, ) elif self.name == "as_struct": children = [ child.evaluate(df, context=context).obj for child in self.children ] return Column( plc.Column( data_type=self.dtype.plc_type, size=children[0].size(), data=None, mask=None, null_count=0, offset=0, children=children, ), dtype=self.dtype, ) elif self.name == "rank": (column,) = (child.evaluate(df, context=context) for child in self.children) method_str, descending, _ = self.options method = { "average": plc.aggregation.RankMethod.AVERAGE, "min": plc.aggregation.RankMethod.MIN, "max": plc.aggregation.RankMethod.MAX, "dense": plc.aggregation.RankMethod.DENSE, "ordinal": plc.aggregation.RankMethod.FIRST, }[method_str] order = ( plc.types.Order.DESCENDING if descending else plc.types.Order.ASCENDING ) ranked: plc.Column = plc.sorting.rank( column.obj, method, order, plc.types.NullPolicy.EXCLUDE, plc.types.NullOrder.BEFORE if descending else plc.types.NullOrder.AFTER, percentage=False, stream=df.stream, ) # Min/Max/Dense/Ordinal -> IDX_DTYPE # See https://github.com/pola-rs/polars/blob/main/crates/polars-ops/src/series/ops/rank.rs if method_str in {"min", "max", "dense", "ordinal"}: dest = self.dtype.plc_type.id() src = ranked.type().id() if dest == plc.TypeId.UINT32 and src != plc.TypeId.UINT32: ranked = plc.unary.cast( ranked, plc.DataType(plc.TypeId.UINT32), stream=df.stream ) elif ( dest == plc.TypeId.UINT64 and src != plc.TypeId.UINT64 ): # pragma: no cover ranked = plc.unary.cast( ranked, plc.DataType(plc.TypeId.UINT64), stream=df.stream ) return Column(ranked, dtype=self.dtype) elif self.name == "top_k": (column, k) = ( child.evaluate(df, context=context) for child in self.children ) (reverse,) = self.options return Column( plc.sorting.top_k( column.obj, cast(Literal, self.children[1]).value, plc.types.Order.ASCENDING if reverse else plc.types.Order.DESCENDING, stream=df.stream, ), dtype=self.dtype, ) elif self.name in self._OP_MAPPING: column = self.children[0].evaluate(df, context=context) if column.dtype.plc_type.id() != self.dtype.id(): arg = plc.unary.cast(column.obj, self.dtype.plc_type, stream=df.stream) else: arg = column.obj return Column( plc.unary.unary_operation( arg, self._OP_MAPPING[self.name], stream=df.stream ), dtype=self.dtype, ) elif self.name in UnaryFunction._supported_cum_aggs: column = self.children[0].evaluate(df, context=context) plc_col = column.obj col_type = column.dtype.plc_type # cum_sum casts # Int8, UInt8, Int16, UInt16 -> Int64 for overflow prevention # Bool -> UInt32 # cum_prod casts integer dtypes < int64 and bool to int64 # See: # https://github.com/pola-rs/polars/blob/main/crates/polars-ops/src/series/ops/cum_agg.rs if ( self.name == "cum_sum" and col_type.id() in { plc.TypeId.INT8, plc.TypeId.UINT8, plc.TypeId.INT16, plc.TypeId.UINT16, } ) or ( self.name == "cum_prod" and plc.traits.is_integral(col_type) and plc.types.size_of(col_type) <= 4 ): plc_col = plc.unary.cast( plc_col, plc.DataType(plc.TypeId.INT64), stream=df.stream ) elif ( self.name == "cum_sum" and column.dtype.plc_type.id() == plc.TypeId.BOOL8 ): plc_col = plc.unary.cast( plc_col, plc.DataType(plc.TypeId.UINT32), stream=df.stream ) if self.name == "cum_sum": agg = plc.aggregation.sum() elif self.name == "cum_prod": agg = plc.aggregation.product() elif self.name == "cum_min": agg = plc.aggregation.min() elif self.name == "cum_max": agg = plc.aggregation.max() return Column( plc.reduce.scan( plc_col, agg, plc.reduce.ScanType.INCLUSIVE, stream=df.stream ), dtype=self.dtype, ) raise NotImplementedError( f"Unimplemented unary function {self.name=}" ) # pragma: no cover; init trips first
UnaryFunction
python
tensorflow__tensorflow
tensorflow/python/tools/api/generator/create_python_api.py
{ "start": 3355, "end": 33441 }
class ____(object): """Builds a map from module name to imports included in that module.""" def __init__(self, output_package, api_version, lazy_loading=_LAZY_LOADING, use_relative_imports=False): self._output_package = output_package # Maps API module to API symbol name to set of tuples of the form # (module name, priority). # The same symbol can be imported from multiple locations. Higher # "priority" indicates that import location is preferred over others. self._module_imports = collections.defaultdict( lambda: collections.defaultdict(set)) self._dest_import_to_id = collections.defaultdict(int) # Names that start with underscore in the root module. self._underscore_names_in_root = set() self._api_version = api_version # Controls whether or not exported symbols are lazily loaded or statically # imported. self._lazy_loading = lazy_loading self._use_relative_imports = use_relative_imports def _check_already_imported(self, symbol_id, api_name): if (api_name in self._dest_import_to_id and symbol_id != self._dest_import_to_id[api_name] and symbol_id != -1): raise SymbolExposedTwiceError( f'Trying to export multiple symbols with same name: {api_name}') self._dest_import_to_id[api_name] = symbol_id def add_import(self, symbol, source_module_name, source_name, dest_module_name, dest_name): """Adds this import to module_imports. Args: symbol: TensorFlow Python symbol. source_module_name: (string) Module to import from. source_name: (string) Name of the symbol to import. dest_module_name: (string) Module name to add import to. dest_name: (string) Import the symbol using this name. Raises: SymbolExposedTwiceError: Raised when an import with the same dest_name has already been added to dest_module_name. """ # modules_with_exports.py is only used during API generation and # won't be available when actually importing tensorflow. if source_module_name.endswith('python.modules_with_exports'): source_module_name = symbol.__module__ import_str = self.format_import(source_module_name, source_name, dest_name) # Check if we are trying to expose two different symbols with same name. full_api_name = dest_name if dest_module_name: full_api_name = dest_module_name + '.' + full_api_name symbol_id = -1 if not symbol else id(symbol) self._check_already_imported(symbol_id, full_api_name) if not dest_module_name and dest_name.startswith('_'): self._underscore_names_in_root.add(dest_name) # The same symbol can be available in multiple modules. # We store all possible ways of importing this symbol and later pick just # one. priority = 0 if symbol: # Give higher priority to source module if it matches # symbol's original module. if hasattr(symbol, '__module__'): priority = int(source_module_name == symbol.__module__) # Give higher priority if symbol name matches its __name__. if hasattr(symbol, '__name__'): priority += int(source_name == symbol.__name__) self._module_imports[dest_module_name][full_api_name].add( (import_str, priority)) def _import_submodules(self): """Add imports for all destination modules in self._module_imports.""" # Import all required modules in their parent modules. # For e.g. if we import 'foo.bar.Value'. Then, we also # import 'bar' in 'foo'. imported_modules = set(self._module_imports.keys()) for module in imported_modules: if not module: continue module_split = module.split('.') parent_module = '' # we import submodules in their parent_module for submodule_index in range(len(module_split)): if submodule_index > 0: submodule = module_split[submodule_index - 1] parent_module += '.' + submodule if parent_module else submodule import_from = self._output_package if self._lazy_loading: import_from += '.' + '.'.join(module_split[:submodule_index + 1]) self.add_import( symbol=None, source_module_name='', source_name=import_from, dest_module_name=parent_module, dest_name=module_split[submodule_index]) else: if self._use_relative_imports: import_from = '.' elif submodule_index > 0: import_from += '.' + '.'.join(module_split[:submodule_index]) self.add_import( symbol=None, source_module_name=import_from, source_name=module_split[submodule_index], dest_module_name=parent_module, dest_name=module_split[submodule_index]) def build(self): """Get a map from destination module to __init__.py code for that module. Returns: A dictionary where key: (string) destination module (for e.g. tf or tf.consts). value: (string) text that should be in __init__.py files for corresponding modules. """ self._import_submodules() module_text_map = {} footer_text_map = {} for dest_module, dest_name_to_imports in self._module_imports.items(): # Sort all possible imports for a symbol and pick the first one. imports_list = [ get_canonical_import(imports) for _, imports in dest_name_to_imports.items() ] if self._lazy_loading: module_text_map[ dest_module] = _LAZY_LOADING_MODULE_TEXT_TEMPLATE % '\n'.join( sorted(imports_list)) else: module_text_map[dest_module] = '\n'.join(sorted(imports_list)) # Expose exported symbols with underscores in root module since we import # from it using * import. Don't need this for lazy_loading because the # underscore symbols are already included in __all__ when passed in and # handled by TFModuleWrapper. root_module_footer = '' if not self._lazy_loading: underscore_names_str = ', '.join( '\'%s\'' % name for name in sorted(self._underscore_names_in_root)) root_module_footer = """ _names_with_underscore = [%s] __all__ = [_s for _s in dir() if not _s.startswith('_')] __all__.extend([_s for _s in _names_with_underscore]) """ % underscore_names_str # Add module wrapper if we need to print deprecation messages # or if we use lazy loading. if self._api_version == 1 or self._lazy_loading: for dest_module, _ in self._module_imports.items(): deprecation = 'False' has_lite = 'False' if self._api_version == 1: # Add 1.* deprecations. if not dest_module.startswith(_COMPAT_MODULE_PREFIX): deprecation = 'True' # Workaround to make sure not load lite from lite/__init__.py if (not dest_module and 'lite' in self._module_imports and self._lazy_loading): has_lite = 'True' if self._lazy_loading: public_apis_name = '_PUBLIC_APIS' else: public_apis_name = 'None' footer_text_map[dest_module] = _DEPRECATION_FOOTER % ( dest_module, public_apis_name, deprecation, has_lite) return module_text_map, footer_text_map, root_module_footer def format_import(self, source_module_name, source_name, dest_name): """Formats import statement. Args: source_module_name: (string) Source module to import from. source_name: (string) Source symbol name to import. dest_name: (string) Destination alias name. Returns: An import statement string. """ if self._lazy_loading: return " '%s': ('%s', '%s')," % (dest_name, source_module_name, source_name) else: if source_module_name: if source_name == dest_name: return 'from %s import %s' % (source_module_name, source_name) else: return 'from %s import %s as %s' % (source_module_name, source_name, dest_name) else: if source_name == dest_name: return 'import %s' % source_name else: return 'import %s as %s' % (source_name, dest_name) def get_destination_modules(self): return set(self._module_imports.keys()) def copy_imports(self, from_dest_module, to_dest_module): self._module_imports[to_dest_module] = ( self._module_imports[from_dest_module].copy()) def add_nested_compat_imports(module_builder, compat_api_versions, output_package): """Adds compat.vN.compat.vK modules to module builder. To avoid circular imports, we want to add __init__.py files under compat.vN.compat.vK and under compat.vN.compat.vK.compat. For all other imports, we point to corresponding modules under compat.vK. Args: module_builder: `_ModuleInitCodeBuilder` instance. compat_api_versions: Supported compatibility versions. output_package: Base output python package where generated API will be added. """ imported_modules = module_builder.get_destination_modules() # Copy over all imports in compat.vK to compat.vN.compat.vK and # all imports in compat.vK.compat to compat.vN.compat.vK.compat. for v in compat_api_versions: for sv in compat_api_versions: subcompat_module = _SUBCOMPAT_MODULE_TEMPLATE % (v, sv) compat_module = _COMPAT_MODULE_TEMPLATE % sv module_builder.copy_imports(compat_module, subcompat_module) module_builder.copy_imports('%s.compat' % compat_module, '%s.compat' % subcompat_module) # Prefixes of modules under compatibility packages, for e.g. "compat.v1.". compat_prefixes = tuple( _COMPAT_MODULE_TEMPLATE % v + '.' for v in compat_api_versions) # Above, we only copied function, class and constant imports. Here # we also add imports for child modules. for imported_module in imported_modules: if not imported_module.startswith(compat_prefixes): continue module_split = imported_module.split('.') # Handle compat.vN.compat.vK.compat.foo case. That is, # import compat.vK.compat.foo in compat.vN.compat.vK.compat. if len(module_split) > 3 and module_split[2] == 'compat': src_module = '.'.join(module_split[:3]) src_name = module_split[3] assert src_name != 'v1' and src_name != 'v2', imported_module else: # Handle compat.vN.compat.vK.foo case. src_module = '.'.join(module_split[:2]) src_name = module_split[2] if src_name == 'compat': continue # compat.vN.compat.vK.compat is handled separately for compat_api_version in compat_api_versions: module_builder.add_import( symbol=None, source_module_name='%s.%s' % (output_package, src_module), source_name=src_name, dest_module_name='compat.v%d.%s' % (compat_api_version, src_module), dest_name=src_name) def _get_name_and_module(full_name): """Split full_name into module and short name. Args: full_name: Full name of symbol that includes module. Returns: Full module name and short symbol name. """ name_segments = full_name.split('.') return '.'.join(name_segments[:-1]), name_segments[-1] def _join_modules(module1, module2): """Concatenate 2 module components. Args: module1: First module to join. module2: Second module to join. Returns: Given two modules aaa.bbb and ccc.ddd, returns a joined module aaa.bbb.ccc.ddd. """ if not module1: return module2 if not module2: return module1 return '%s.%s' % (module1, module2) def add_imports_for_symbol(module_code_builder, symbol, source_module_name, source_name, api_name, api_version, output_module_prefix=''): """Add imports for the given symbol to `module_code_builder`. Args: module_code_builder: `_ModuleInitCodeBuilder` instance. symbol: A symbol. source_module_name: Module that we can import the symbol from. source_name: Name we can import the symbol with. api_name: API name. Currently, must be `tensorflow`. api_version: API version. output_module_prefix: Prefix to prepend to destination module. """ if api_version == 1: names_attr = API_ATTRS_V1[api_name].names constants_attr = API_ATTRS_V1[api_name].constants else: names_attr = API_ATTRS[api_name].names constants_attr = API_ATTRS[api_name].constants # If symbol is _tf_api_constants attribute, then add the constants. if source_name == constants_attr: for exports, name in symbol: for export in exports: dest_module, dest_name = _get_name_and_module(export) dest_module = _join_modules(output_module_prefix, dest_module) module_code_builder.add_import(None, source_module_name, name, dest_module, dest_name) # If symbol has _tf_api_names attribute, then add import for it. if (hasattr(symbol, '__dict__') and names_attr in symbol.__dict__): # Generate import statements for symbols. for export in getattr(symbol, names_attr): # pylint: disable=protected-access dest_module, dest_name = _get_name_and_module(export) dest_module = _join_modules(output_module_prefix, dest_module) module_code_builder.add_import(symbol, source_module_name, source_name, dest_module, dest_name) def get_api_init_text(packages, packages_to_ignore, output_package, api_name, api_version, compat_api_versions=None, lazy_loading=_LAZY_LOADING, use_relative_imports=False): """Get a map from destination module to __init__.py code for that module. Args: packages: Base python packages containing python with target tf_export decorators. packages_to_ignore: python packages to be ignored when checking for tf_export decorators. output_package: Base output python package where generated API will be added. api_name: API you want to generate Currently, only `tensorflow`. api_version: API version you want to generate (1 or 2). compat_api_versions: Additional API versions to generate under compat/ directory. lazy_loading: Boolean flag. If True, a lazy loading `__init__.py` file is produced and if `False`, static imports are used. use_relative_imports: True if we should use relative imports when importing submodules. Returns: A dictionary where key: (string) destination module (for e.g. tf or tf.consts). value: (string) text that should be in __init__.py files for corresponding modules. """ if compat_api_versions is None: compat_api_versions = [] module_code_builder = _ModuleInitCodeBuilder(output_package, api_version, lazy_loading, use_relative_imports) # Traverse over everything imported above. Specifically, # we want to traverse over TensorFlow Python modules. def in_packages(m): return any(package in m for package in packages) for module in list(sys.modules.values()): # Only look at tensorflow modules. if (not module or not hasattr(module, '__name__') or module.__name__ is None or not in_packages(module.__name__)): continue if packages_to_ignore and any([p for p in packages_to_ignore if p in module.__name__]): continue # Do not generate __init__.py files for contrib modules for now. if (('.contrib.' in module.__name__ or module.__name__.endswith('.contrib')) and '.lite' not in module.__name__): continue for module_contents_name in dir(module): if (module.__name__ + '.' + module_contents_name in _SYMBOLS_TO_SKIP_EXPLICITLY): continue attr = getattr(module, module_contents_name) _, attr = tf_decorator.unwrap(attr) add_imports_for_symbol(module_code_builder, attr, module.__name__, module_contents_name, api_name, api_version) for compat_api_version in compat_api_versions: add_imports_for_symbol(module_code_builder, attr, module.__name__, module_contents_name, api_name, compat_api_version, _COMPAT_MODULE_TEMPLATE % compat_api_version) if compat_api_versions: add_nested_compat_imports(module_code_builder, compat_api_versions, output_package) return module_code_builder.build() def get_module(dir_path, relative_to_dir): """Get module that corresponds to path relative to relative_to_dir. Args: dir_path: Path to directory. relative_to_dir: Get module relative to this directory. Returns: Name of module that corresponds to the given directory. """ dir_path = dir_path[len(relative_to_dir):] # Convert path separators to '/' for easier parsing below. dir_path = dir_path.replace(os.sep, '/') return dir_path.replace('/', '.').strip('.') def get_module_docstring(module_name, package, api_name): """Get docstring for the given module. This method looks for docstring in the following order: 1. Checks if module has a docstring specified in doc_srcs. 2. Checks if module has a docstring source module specified in doc_srcs. If it does, gets docstring from that module. 3. Checks if module with module_name exists under base package. If it does, gets docstring from that module. 4. Returns a default docstring. Args: module_name: module name relative to tensorflow (excluding 'tensorflow.' prefix) to get a docstring for. package: Base python package containing python with target tf_export decorators. api_name: API you want to generate Currently, only `tensorflow`. Returns: One-line docstring to describe the module. """ # Get the same module doc strings for any version. That is, for module # 'compat.v1.foo' we can get docstring from module 'foo'. for version in _API_VERSIONS: compat_prefix = _COMPAT_MODULE_TEMPLATE % version if module_name.startswith(compat_prefix): module_name = module_name[len(compat_prefix):].strip('.') # Module under base package to get a docstring from. docstring_module_name = module_name doc_sources = doc_srcs.get_doc_sources(api_name) if module_name in doc_sources: docsrc = doc_sources[module_name] if docsrc.docstring: return docsrc.docstring if docsrc.docstring_module_name: docstring_module_name = docsrc.docstring_module_name if package != 'tf_keras': docstring_module_name = package + '.' + docstring_module_name if (docstring_module_name in sys.modules and sys.modules[docstring_module_name].__doc__): return sys.modules[docstring_module_name].__doc__ return 'Public API for tf.%s namespace.' % module_name def create_primary_api_files(output_files, packages, packages_to_ignore, root_init_template, output_dir, output_package, api_name, api_version, compat_api_versions, compat_init_templates, lazy_loading=_LAZY_LOADING, use_relative_imports=False): """Creates __init__.py files for the Python API. Args: output_files: List of __init__.py file paths to create. packages: Base python packages containing python with target tf_export decorators. packages_to_ignore: python packages to be ignored when checking for tf_export decorators. root_init_template: Template for top-level __init__.py file. "# API IMPORTS PLACEHOLDER" comment in the template file will be replaced with imports. output_dir: output API root directory. output_package: Base output package where generated API will be added. api_name: API you want to generate Currently, only `tensorflow`. api_version: API version to generate (`v1` or `v2`). compat_api_versions: Additional API versions to generate in compat/ subdirectory. compat_init_templates: List of templates for top level compat init files in the same order as compat_api_versions. lazy_loading: Boolean flag. If True, a lazy loading `__init__.py` file is produced and if `False`, static imports are used. use_relative_imports: True if we should use relative imports when import submodules. Raises: ValueError: if output_files list is missing a required file. """ module_name_to_file_path = {} for output_file in output_files: module_name = get_module(os.path.dirname(output_file), output_dir) module_name_to_file_path[module_name] = os.path.normpath(output_file) # Create file for each expected output in genrule. for module, file_path in module_name_to_file_path.items(): if not os.path.isdir(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) open(file_path, 'a').close() ( module_text_map, deprecation_footer_map, root_module_footer, ) = get_api_init_text(packages, packages_to_ignore, output_package, api_name, api_version, compat_api_versions, lazy_loading, use_relative_imports) # Add imports to output files. missing_output_files = [] # Root modules are "" and "compat.v*". root_module = '' compat_module_to_template = { _COMPAT_MODULE_TEMPLATE % v: t for v, t in zip(compat_api_versions, compat_init_templates) } for v in compat_api_versions: compat_module_to_template.update({ _SUBCOMPAT_MODULE_TEMPLATE % (v, vs): t for vs, t in zip(compat_api_versions, compat_init_templates) }) for module, text in module_text_map.items(): # Make sure genrule output file list is in sync with API exports. if module not in module_name_to_file_path: module_file_path = '"%s/__init__.py"' % (module.replace('.', '/')) missing_output_files.append(module_file_path) continue contents = '' if module == root_module and root_init_template: # Read base init file for root module with open(root_init_template, 'r') as root_init_template_file: contents = root_init_template_file.read() contents = contents.replace('# API IMPORTS PLACEHOLDER', text) contents = contents.replace('# __all__ PLACEHOLDER', root_module_footer) elif module in compat_module_to_template: # Read base init file for compat module with open(compat_module_to_template[module], 'r') as init_template_file: contents = init_template_file.read() contents = contents.replace('# API IMPORTS PLACEHOLDER', text) else: contents = ( _GENERATED_FILE_HEADER % get_module_docstring(module, packages[0], api_name) + text + _GENERATED_FILE_FOOTER) if module in deprecation_footer_map: if '# WRAPPER_PLACEHOLDER' in contents: contents = contents.replace('# WRAPPER_PLACEHOLDER', deprecation_footer_map[module]) else: contents += deprecation_footer_map[module] with open(module_name_to_file_path[module], 'w') as fp: fp.write(contents) if missing_output_files: missing_files = ',\n'.join(sorted(missing_output_files)) raise ValueError( f'Missing outputs for genrule:\n{missing_files}. Be sure to add these ' 'targets to tensorflow/python/tools/api/generator/api_init_files_v1.bzl' ' and tensorflow/python/tools/api/generator/api_init_files.bzl ' '(tensorflow repo), or tf_keras/api/api_init_files.bzl (tf_keras repo)') def create_proxy_api_files(output_files, proxy_module_root, output_dir): """Creates __init__.py files in proxy format for the Python API. Args: output_files: List of __init__.py file paths to create. proxy_module_root: Module root for proxy-import format. If specified, proxy files with content like `from proxy_module_root.proxy_module import *` will be created to enable import resolution under TensorFlow. output_dir: output API root directory. """ for file_path in output_files: module = get_module(os.path.dirname(file_path), output_dir) if not os.path.isdir(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) contents = f'from {proxy_module_root}.{module} import *' with open(file_path, 'w') as fp: fp.write(contents) def main(): parser = argparse.ArgumentParser() parser.add_argument( 'outputs', metavar='O', type=str, nargs='+', help='If a single file is passed in, then we assume it contains a ' 'semicolon-separated list of Python files that we expect this script to ' 'output. If multiple files are passed in, then we assume output files ' 'are listed directly as arguments.') parser.add_argument( '--packages', default=_DEFAULT_PACKAGE, type=str, help='Base packages that import modules containing the target tf_export ' 'decorators.') parser.add_argument( '--packages_to_ignore', default='', type=str, help='Packages to exclude from the api generation. This is used to hide ' 'certain packages from this script when multiple copy of code exists, ' 'eg tf_keras. It is useful to avoid the SymbolExposedTwiceError.' ) parser.add_argument( '--root_init_template', default='', type=str, help='Template for top level __init__.py file. ' '"#API IMPORTS PLACEHOLDER" comment will be replaced with imports.') parser.add_argument( '--apidir', type=str, required=True, help='Directory where generated output files are placed. ' 'gendir should be a prefix of apidir. Also, apidir ' 'should be a prefix of every directory in outputs.') parser.add_argument( '--apiname', required=True, type=str, choices=API_ATTRS.keys(), help='The API you want to generate.') parser.add_argument( '--apiversion', default=2, type=int, choices=_API_VERSIONS, help='The API version you want to generate.') parser.add_argument( '--compat_apiversions', default=[], type=int, action='append', help='Additional versions to generate in compat/ subdirectory. ' 'If set to 0, then no additional version would be generated.') parser.add_argument( '--compat_init_templates', default=[], type=str, action='append', help='Templates for top-level __init__ files under compat modules. ' 'The list of init file templates must be in the same order as ' 'list of versions passed with compat_apiversions.') parser.add_argument( '--output_package', default='tensorflow', type=str, help='Root output package.') parser.add_argument( '--loading', default='default', type=str, choices=['lazy', 'static', 'default'], help='Controls how the generated __init__.py file loads the exported ' 'symbols. \'lazy\' means the symbols are loaded when first used. ' '\'static\' means all exported symbols are loaded in the ' '__init__.py file. \'default\' uses the value of the ' '_LAZY_LOADING constant in create_python_api.py.') parser.add_argument( '--use_relative_imports', default=False, type=bool, help='Whether to import submodules using relative imports or absolute ' 'imports') parser.add_argument( '--proxy_module_root', default=None, type=str, help='Module root for proxy-import format. If specified, proxy files with ' 'content like `from proxy_module_root.proxy_module import *` will be ' 'created to enable import resolution under TensorFlow.') args = parser.parse_args() if len(args.outputs) == 1: # If we only get a single argument, then it must be a file containing # list of outputs. with open(args.outputs[0]) as output_list_file: outputs = [line.strip() for line in output_list_file.read().split(';')] else: outputs = args.outputs # Populate `sys.modules` with modules containing tf_export(). packages = args.packages.split(',') for package in packages: importlib.import_module(package) packages_to_ignore = args.packages_to_ignore.split(',') # Determine if the modules shall be loaded lazily or statically. if args.loading == 'default': lazy_loading = _LAZY_LOADING elif args.loading == 'lazy': lazy_loading = True elif args.loading == 'static': lazy_loading = False else: # This should never happen (tm). raise ValueError(f'Invalid value for --loading flag: {args.loading}. Must ' 'be one of lazy, static, default.') if args.proxy_module_root is None: create_primary_api_files(outputs, packages, packages_to_ignore, args.root_init_template, args.apidir, args.output_package, args.apiname, args.apiversion, args.compat_apiversions, args.compat_init_templates, lazy_loading, args.use_relative_imports) else: create_proxy_api_files(outputs, args.proxy_module_root, args.apidir) if __name__ == '__main__': main()
_ModuleInitCodeBuilder
python
ray-project__ray
python/ray/train/torch/xla/config.py
{ "start": 422, "end": 4242 }
class ____(TorchConfig): """ Configuration for torch XLA setup. See https://pytorch.org/xla/release/1.13/index.html for more info. Currently, only "neuron_cores" accelerator (AwsNeuronXLABackend) is supported with xrt runtime. """ neuron_parallel_compile: bool = False @property def backend_cls(self): return _TorchAwsNeuronXLABackend def _kill_xrt_server(): import subprocess subprocess.call(["pkill", "-f", "xrt_run_server"]) def _set_xla_env_vars(): # https://pytorch.org/docs/1.13/elastic/run.html#environment-variables context = ray.train.get_context() os.environ["LOCAL_RANK"] = str(context.get_local_rank()) os.environ["RANK"] = str(context.get_world_rank()) os.environ["LOCAL_WORLD_SIZE"] = str(context.get_local_world_size()) os.environ["WORLD_SIZE"] = str(context.get_world_size()) os.environ["GROUP_RANK"] = str(context.get_node_rank()) os.environ["GROUP_WORLD_SIZE"] = str( context.get_world_size() / context.get_local_world_size() ) os.environ["ROLE_RANK"] = str(context.get_world_rank()) os.environ["ROLE_WORLD_RANK"] = str(context.get_world_rank()) os.environ["ROLE_WORLD_SIZE"] = str(context.get_world_size()) # EFA and XLA setup # https://github.com/aws/libfabric/blob/master/prov/efa/src/rxr/rxr_init.c # https://github.com/aws-neuron/aws-neuron-samples/blob/master/torch-neuronx/training/dp_bert_hf_pretrain/run_dp_bert_large_hf_pretrain_bf16_s128.sh # noqa os.environ["FI_PROVIDER"] = "efa" os.environ["FI_EFA_USE_DEVICE_RDMA"] = "1" os.environ["FI_EFA_FORK_SAFE"] = "1" os.environ["XLA_TRANSFER_SEED_ASYNC"] = "1" os.environ["NCCL_ASYNC_ERROR_HANDLING"] = "1" def _setup_xla_torch_process_group(): try: import torch.distributed as dist import torch_xla.core.xla_model as xm # noqa F401 import torch_xla.distributed.xla_backend # noqa F401 dist.init_process_group("xla") except ImportError: raise ImportError("torch_xla must be installed to use torch_xla backend.") # The following env vars enable Neuron graph extraction for parallel compilation # Note: model outputs are invalid and should be ignored while these env vars are set def _set_neuron_parallel_compile_env_vars(): os.environ["NEURON_PARALLEL_COMPILE"] = "1" os.environ["NEURON_EXTRACT_GRAPHS_ONLY"] = "1" os.environ["NEURON_FALL_BACK_TO_NULL_NEFF"] = "1" # Compile previously extracted Neuron graphs def _neuron_compile_extracted_graphs(): try: from libneuronxla.neuron_cc_cache import CacheUrl from libneuronxla.neuron_parallel_compile import parallel_compile except ImportError: raise ImportError( "libneuronxla must be installed to use Neuron parallel compilation." ) # Only 1 worker per node should run parallel_compile() if os.environ.get("LOCAL_RANK") == "0": logger.info("Compiling extracted graphs on local rank0 worker") parallel_compile_workdir = ( f"/tmp/{os.environ.get('USER','no-user')}/parallel_compile_workdir/" ) if os.path.exists(parallel_compile_workdir): shutil.rmtree(parallel_compile_workdir) os.makedirs(parallel_compile_workdir, exist_ok=True) # Users can set the cache directory using --cache_dir in NEURON_CC_FLAGS or by # using NEURON_COMPILE_CACHE_URL. --cache_dir takes precedence. explicit_cache_dir = None if neuron_cc_flags := os.environ.get("NEURON_CC_FLAGS"): if s := re.search(r"--cache_dir[= ](\S+)", neuron_cc_flags): explicit_cache_dir = s.group(1) parallel_compile( parallel_compile_workdir, CacheUrl.get_cache_url(explicit_cache_dir), )
TorchXLAConfig
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/components/simple_pipes_script_asset.py
{ "start": 939, "end": 1746 }
class ____(Scaffolder[SimplePipesScriptScaffoldParams]): @classmethod def get_scaffold_params(cls) -> type[SimplePipesScriptScaffoldParams]: return SimplePipesScriptScaffoldParams def scaffold(self, request: ScaffoldRequest[SimplePipesScriptScaffoldParams]) -> None: scaffold_component(request, request.params.model_dump()) Path(request.target_path, request.params.filename).write_text( _SCRIPT_TEMPLATE.format(asset_key=request.params.asset_key) ) _SCRIPT_TEMPLATE = """ from dagster_pipes import open_dagster_pipes context = open_dagster_pipes() context.log.info("Materializing asset {asset_key} from pipes") context.report_asset_materialization(asset_key="{asset_key}") """ @scaffold_with(SimplePipesScriptScaffolder)
SimplePipesScriptScaffolder
python
pytorch__pytorch
torch/distributed/elastic/timer/local_timer.py
{ "start": 1381, "end": 2141 }
class ____(RequestQueue): """ A ``RequestQueue`` backed by python ``multiprocessing.Queue`` """ def __init__(self, mp_queue: mp.Queue): super().__init__() self._mp_queue = mp_queue def size(self) -> int: return self._mp_queue.qsize() def get(self, size, timeout: float) -> list[TimerRequest]: requests = [] wait = timeout for _ in range(size): start = time.time() try: r = self._mp_queue.get(block=True, timeout=wait) except Empty: break requests.append(r) wait = wait - (time.time() - start) if wait <= 0: break return requests
MultiprocessingRequestQueue
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/hybrid.py
{ "start": 44019, "end": 44128 }
class ____(Protocol[_T]): def __call__(self, cls: Any) -> Comparator[_T]: ...
_HybridComparatorCallableType
python
run-llama__llama_index
llama-index-core/llama_index/core/indices/multi_modal/retriever.py
{ "start": 1046, "end": 15301 }
class ____(MultiModalRetriever): """ Multi Modal Vector index retriever. Args: index (MultiModalVectorStoreIndex): Multi Modal vector store index for images and texts. similarity_top_k (int): number of top k results to return. vector_store_query_mode (str): vector store query mode See reference for VectorStoreQueryMode for full list of supported modes. filters (Optional[MetadataFilters]): metadata filters, defaults to None alpha (float): weight for sparse/dense retrieval, only used for hybrid query mode. doc_ids (Optional[List[str]]): list of documents to constrain search. vector_store_kwargs (dict): Additional vector store specific kwargs to pass through to the vector store at query time. """ def __init__( self, index: "MultiModalVectorStoreIndex", similarity_top_k: int = DEFAULT_SIMILARITY_TOP_K, image_similarity_top_k: int = DEFAULT_SIMILARITY_TOP_K, vector_store_query_mode: VectorStoreQueryMode = VectorStoreQueryMode.DEFAULT, filters: Optional[MetadataFilters] = None, alpha: Optional[float] = None, node_ids: Optional[List[str]] = None, doc_ids: Optional[List[str]] = None, sparse_top_k: Optional[int] = None, callback_manager: Optional[CallbackManager] = None, **kwargs: Any, ) -> None: """Initialize params.""" self._index = index self._vector_store = self._index.vector_store # separate image vector store for image retrieval self._image_vector_store = self._index.image_vector_store assert isinstance(self._index.image_embed_model, BaseEmbedding) self._image_embed_model = index._image_embed_model self._embed_model = index._embed_model self._docstore = self._index.docstore self._similarity_top_k = similarity_top_k self._image_similarity_top_k = image_similarity_top_k self._vector_store_query_mode = VectorStoreQueryMode(vector_store_query_mode) self._alpha = alpha self._node_ids = node_ids self._doc_ids = doc_ids self._filters = filters self._sparse_top_k = sparse_top_k self._kwargs: Dict[str, Any] = kwargs.get("vector_store_kwargs", {}) self.callback_manager = callback_manager or Settings.callback_manager @property def similarity_top_k(self) -> int: """Return similarity top k.""" return self._similarity_top_k @similarity_top_k.setter def similarity_top_k(self, similarity_top_k: int) -> None: """Set similarity top k.""" self._similarity_top_k = similarity_top_k @property def image_similarity_top_k(self) -> int: """Return image similarity top k.""" return self._image_similarity_top_k @image_similarity_top_k.setter def image_similarity_top_k(self, image_similarity_top_k: int) -> None: """Set image similarity top k.""" self._image_similarity_top_k = image_similarity_top_k def _build_vector_store_query( self, query_bundle_with_embeddings: QueryBundle, similarity_top_k: int ) -> VectorStoreQuery: return VectorStoreQuery( query_embedding=query_bundle_with_embeddings.embedding, similarity_top_k=similarity_top_k, node_ids=self._node_ids, doc_ids=self._doc_ids, query_str=query_bundle_with_embeddings.query_str, mode=self._vector_store_query_mode, alpha=self._alpha, filters=self._filters, sparse_top_k=self._sparse_top_k, ) def _retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: res = [] # If text vector store is not empty, retrieve text nodes # If text vector store is empty, please create index without text vector store if self._vector_store is not None: res.extend(self._text_retrieve(query_bundle)) # If image vector store is not empty, retrieve text nodes # If image vector store is empty, please create index without image vector store if self._image_vector_store is not None: res.extend(self._text_to_image_retrieve(query_bundle)) return res def _text_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: if not self._index.is_text_vector_store_empty: if self._vector_store.is_embedding_query: if ( query_bundle.embedding is None and len(query_bundle.embedding_strs) > 0 ): query_bundle.embedding = ( self._embed_model.get_agg_embedding_from_queries( query_bundle.embedding_strs ) ) return self._get_nodes_with_embeddings( query_bundle, self._similarity_top_k, self._vector_store ) else: return [] def text_retrieve(self, str_or_query_bundle: QueryType) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle(str_or_query_bundle) return self._text_retrieve(str_or_query_bundle) def _text_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: if not self._index.is_image_vector_store_empty: if self._image_vector_store.is_embedding_query: # change the embedding for query bundle to Multi Modal Text encoder query_bundle.embedding = ( self._image_embed_model.get_agg_embedding_from_queries( query_bundle.embedding_strs ) ) return self._get_nodes_with_embeddings( query_bundle, self._image_similarity_top_k, self._image_vector_store ) else: return [] def text_to_image_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle(str_or_query_bundle) return self._text_to_image_retrieve(str_or_query_bundle) def _image_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: if not self._index.is_image_vector_store_empty: if self._image_vector_store.is_embedding_query: # change the embedding for query bundle to Multi Modal Image encoder for image input assert isinstance(self._index.image_embed_model, MultiModalEmbedding) query_bundle.embedding = self._image_embed_model.get_image_embedding( query_bundle.embedding_image[0] ) return self._get_nodes_with_embeddings( query_bundle, self._image_similarity_top_k, self._image_vector_store ) else: return [] def image_to_image_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle( query_str="", image_path=str_or_query_bundle ) return self._image_to_image_retrieve(str_or_query_bundle) def _get_nodes_with_embeddings( self, query_bundle_with_embeddings: QueryBundle, similarity_top_k: int, vector_store: BasePydanticVectorStore, ) -> List[NodeWithScore]: query = self._build_vector_store_query( query_bundle_with_embeddings, similarity_top_k ) query_result = vector_store.query(query, **self._kwargs) return self._build_node_list_from_query_result(query_result) def _build_node_list_from_query_result( self, query_result: VectorStoreQueryResult ) -> List[NodeWithScore]: if query_result.nodes is None: # NOTE: vector store does not keep text and returns node indices. # Need to recover all nodes from docstore if query_result.ids is None: raise ValueError( "Vector store query result should return at " "least one of nodes or ids." ) assert isinstance(self._index.index_struct, IndexDict) node_ids = [ self._index.index_struct.nodes_dict[idx] for idx in query_result.ids ] nodes = self._docstore.get_nodes(node_ids) query_result.nodes = nodes else: # NOTE: vector store keeps text, returns nodes. # Only need to recover image or index nodes from docstore for i in range(len(query_result.nodes)): source_node = query_result.nodes[i].source_node if (not self._vector_store.stores_text) or ( source_node is not None and source_node.node_type != ObjectType.TEXT ): node_id = query_result.nodes[i].node_id if self._docstore.document_exists(node_id): query_result.nodes[i] = self._docstore.get_node( # type: ignore[index] node_id ) log_vector_store_query_result(query_result) node_with_scores: List[NodeWithScore] = [] for ind, node in enumerate(query_result.nodes): score: Optional[float] = None if query_result.similarities is not None: score = query_result.similarities[ind] node_with_scores.append(NodeWithScore(node=node, score=score)) return node_with_scores # Async Retrieval Methods async def _aretrieve(self, query_bundle: QueryBundle) -> List[NodeWithScore]: # Run the two retrievals in async, and return their results as a concatenated list results: List[NodeWithScore] = [] tasks = [ self._atext_retrieve(query_bundle), self._atext_to_image_retrieve(query_bundle), ] task_results = await asyncio.gather(*tasks) for task_result in task_results: results.extend(task_result) return results async def _atext_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: if not self._index.is_text_vector_store_empty: if self._vector_store.is_embedding_query: # change the embedding for query bundle to Multi Modal Text encoder query_bundle.embedding = ( await self._embed_model.aget_agg_embedding_from_queries( query_bundle.embedding_strs ) ) return await self._aget_nodes_with_embeddings( query_bundle, self._similarity_top_k, self._vector_store ) else: return [] async def atext_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle(str_or_query_bundle) return await self._atext_retrieve(str_or_query_bundle) async def _atext_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: if not self._index.is_image_vector_store_empty: if self._image_vector_store.is_embedding_query: # change the embedding for query bundle to Multi Modal Text encoder query_bundle.embedding = ( await self._image_embed_model.aget_agg_embedding_from_queries( query_bundle.embedding_strs ) ) return await self._aget_nodes_with_embeddings( query_bundle, self._image_similarity_top_k, self._image_vector_store ) else: return [] async def atext_to_image_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): str_or_query_bundle = QueryBundle(str_or_query_bundle) return await self._atext_to_image_retrieve(str_or_query_bundle) async def _aget_nodes_with_embeddings( self, query_bundle_with_embeddings: QueryBundle, similarity_top_k: int, vector_store: BasePydanticVectorStore, ) -> List[NodeWithScore]: query = self._build_vector_store_query( query_bundle_with_embeddings, similarity_top_k ) query_result = await vector_store.aquery(query, **self._kwargs) return self._build_node_list_from_query_result(query_result) async def _aimage_to_image_retrieve( self, query_bundle: QueryBundle, ) -> List[NodeWithScore]: if not self._index.is_image_vector_store_empty: if self._image_vector_store.is_embedding_query: # change the embedding for query bundle to Multi Modal Image encoder for image input assert isinstance(self._index.image_embed_model, MultiModalEmbedding) # Using the first imaage in the list for image retrieval query_bundle.embedding = ( await self._image_embed_model.aget_image_embedding( query_bundle.embedding_image[0] ) ) return await self._aget_nodes_with_embeddings( query_bundle, self._image_similarity_top_k, self._image_vector_store ) else: return [] async def aimage_to_image_retrieve( self, str_or_query_bundle: QueryType ) -> List[NodeWithScore]: if isinstance(str_or_query_bundle, str): # leave query_str as empty since we are using image_path for image retrieval str_or_query_bundle = QueryBundle( query_str="", image_path=str_or_query_bundle ) return await self._aimage_to_image_retrieve(str_or_query_bundle)
MultiModalVectorIndexRetriever
python
pydantic__pydantic
tests/mypy/modules/plugin_fail_baseConfig.py
{ "start": 4505, "end": 4720 }
class ____(BaseModel): x: int y: str class Config: alias_generator = None frozen = True extra = Extra.forbid frozenmodel = FrozenModel(x=1, y='b') frozenmodel.y = 'a'
FrozenModel
python
readthedocs__readthedocs.org
readthedocs/invitations/apps.py
{ "start": 137, "end": 344 }
class ____(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "readthedocs.invitations" def ready(self): import readthedocs.invitations.signals # noqa
InvitationsConfig
python
sphinx-doc__sphinx
sphinx/writers/text.py
{ "start": 14529, "end": 45229 }
class ____(SphinxTranslator): builder: TextBuilder def __init__(self, document: nodes.document, builder: TextBuilder) -> None: super().__init__(document, builder) newlines = self.config.text_newlines if newlines == 'windows': self.nl = '\r\n' elif newlines == 'native': self.nl = os.linesep else: self.nl = '\n' self.sectionchars = self.config.text_sectionchars self.add_secnumbers = self.config.text_add_secnumbers self.secnumber_suffix = self.config.text_secnumber_suffix self.states: list[list[tuple[int, str | list[str]]]] = [[]] self.stateindent = [0] self.list_counter: list[int] = [] self.sectionlevel = 0 self.lineblocklevel = 0 self.table: Table self.in_production_list = False self.context: list[str] = [] """Heterogeneous stack. Used by visit_* and depart_* functions in conjunction with the tree traversal. Make sure that the pops correspond to the pushes. """ def add_text(self, text: str) -> None: self.states[-1].append((-1, text)) def new_state(self, indent: int = STDINDENT) -> None: self.states.append([]) self.stateindent.append(indent) def end_state( self, wrap: bool = True, end: Sequence[str] | None = ('',), first: str | None = None, ) -> None: content = self.states.pop() maxindent = sum(self.stateindent) indent = self.stateindent.pop() result: list[tuple[int, list[str]]] = [] toformat: list[str] = [] def do_format() -> None: if not toformat: return if wrap: res = my_wrap(''.join(toformat), width=MAXWIDTH - maxindent) else: res = ''.join(toformat).splitlines() if end: res += end result.append((indent, res)) for itemindent, item in content: if itemindent == -1: toformat.append(item) # type: ignore[arg-type] else: do_format() result.append((indent + itemindent, item)) # type: ignore[arg-type] toformat = [] do_format() if first is not None and result: # insert prefix into first line (ex. *, [1], See also, etc.) newindent = result[0][0] - indent if result[0][1] == ['']: result.insert(0, (newindent, [first])) else: text = first + result[0][1].pop(0) result.insert(0, (newindent, [text])) self.states[-1].extend(result) def visit_document(self, node: Element) -> None: self.new_state(0) def depart_document(self, node: Element) -> None: self.end_state() self.body = self.nl.join( line and (' ' * indent + line) for indent, lines in self.states[0] for line in lines ) # XXX header/footer? def visit_section(self, node: Element) -> None: self._title_char = self.sectionchars[self.sectionlevel] self.sectionlevel += 1 def depart_section(self, node: Element) -> None: self.sectionlevel -= 1 def visit_topic(self, node: Element) -> None: self.new_state(0) def depart_topic(self, node: Element) -> None: self.end_state() visit_sidebar = visit_topic depart_sidebar = depart_topic def visit_rubric(self, node: Element) -> None: self.new_state(0) self.add_text('-[ ') def depart_rubric(self, node: Element) -> None: self.add_text(' ]-') self.end_state() def visit_compound(self, node: Element) -> None: pass def depart_compound(self, node: Element) -> None: pass def visit_glossary(self, node: Element) -> None: pass def depart_glossary(self, node: Element) -> None: pass def visit_title(self, node: Element) -> None: if isinstance(node.parent, nodes.Admonition): self.add_text(node.astext() + ': ') raise nodes.SkipNode self.new_state(0) def get_section_number_string(self, node: Element) -> str: if isinstance(node.parent, nodes.section): anchorname = '#' + node.parent['ids'][0] numbers = self.builder.secnumbers.get(anchorname) if numbers is None: numbers = self.builder.secnumbers.get('') if numbers is not None: return '.'.join(map(str, numbers)) + self.secnumber_suffix return '' def depart_title(self, node: Element) -> None: if isinstance(node.parent, nodes.section): char = self._title_char else: char = '^' text = '' text = ''.join(x[1] for x in self.states.pop() if x[0] == -1) # type: ignore[misc] if self.add_secnumbers: text = self.get_section_number_string(node) + text self.stateindent.pop() title = ['', text, '%s' % (char * column_width(text)), ''] if len(self.states) == 2 and len(self.states[-1]) == 0: # remove an empty line before title if it is first section title in the document title.pop(0) self.states[-1].append((0, title)) def visit_subtitle(self, node: Element) -> None: pass def depart_subtitle(self, node: Element) -> None: pass def visit_attribution(self, node: Element) -> None: self.add_text('-- ') def depart_attribution(self, node: Element) -> None: pass ############################################################# # Domain-specific object descriptions ############################################################# # Top-level nodes ################# def visit_desc(self, node: Element) -> None: pass def depart_desc(self, node: Element) -> None: pass def visit_desc_signature(self, node: Element) -> None: self.new_state(0) def depart_desc_signature(self, node: Element) -> None: # XXX: wrap signatures in a way that makes sense self.end_state(wrap=False, end=None) def visit_desc_signature_line(self, node: Element) -> None: pass def depart_desc_signature_line(self, node: Element) -> None: self.add_text('\n') def visit_desc_content(self, node: Element) -> None: self.new_state() self.add_text(self.nl) def depart_desc_content(self, node: Element) -> None: self.end_state() def visit_desc_inline(self, node: Element) -> None: pass def depart_desc_inline(self, node: Element) -> None: pass # Nodes for high-level structure in signatures ############################################## def visit_desc_name(self, node: Element) -> None: pass def depart_desc_name(self, node: Element) -> None: pass def visit_desc_addname(self, node: Element) -> None: pass def depart_desc_addname(self, node: Element) -> None: pass def visit_desc_type(self, node: Element) -> None: pass def depart_desc_type(self, node: Element) -> None: pass def visit_desc_returns(self, node: Element) -> None: self.add_text(' -> ') def depart_desc_returns(self, node: Element) -> None: pass def _visit_sig_parameter_list( self, node: Element, parameter_group: type[Element], sig_open_paren: str, sig_close_paren: str, ) -> None: """Visit a signature parameters or type parameters list. The *parameter_group* value is the type of a child node acting as a required parameter or as a set of contiguous optional parameters. """ self.add_text(sig_open_paren) self.is_first_param = True self.optional_param_level = 0 self.params_left_at_level = 0 self.param_group_index = 0 # Counts as what we call a parameter group are either a required parameter, or a # set of contiguous optional ones. self.list_is_required_param = [ isinstance(c, parameter_group) for c in node.children ] self.required_params_left = sum(self.list_is_required_param) self.param_separator = ', ' self.multi_line_parameter_list = node.get('multi_line_parameter_list', False) self.trailing_comma = node.get('multi_line_trailing_comma', False) if self.multi_line_parameter_list: self.param_separator = self.param_separator.rstrip() self.context.append(sig_close_paren) def _depart_sig_parameter_list(self, node: Element) -> None: sig_close_paren = self.context.pop() self.add_text(sig_close_paren) def visit_desc_parameterlist(self, node: Element) -> None: self._visit_sig_parameter_list(node, addnodes.desc_parameter, '(', ')') def depart_desc_parameterlist(self, node: Element) -> None: self._depart_sig_parameter_list(node) def visit_desc_type_parameter_list(self, node: Element) -> None: self._visit_sig_parameter_list(node, addnodes.desc_type_parameter, '[', ']') def depart_desc_type_parameter_list(self, node: Element) -> None: self._depart_sig_parameter_list(node) def visit_desc_parameter(self, node: Element) -> None: on_separate_line = self.multi_line_parameter_list if on_separate_line and not ( self.is_first_param and self.optional_param_level > 0 ): self.new_state() if self.is_first_param: self.is_first_param = False elif not on_separate_line and not self.required_params_left: self.add_text(self.param_separator) if self.optional_param_level == 0: self.required_params_left -= 1 else: self.params_left_at_level -= 1 self.add_text(node.astext()) is_required = self.list_is_required_param[self.param_group_index] if on_separate_line: len_lirp = len(self.list_is_required_param) is_last_group = self.param_group_index + 1 == len_lirp next_is_required = ( not is_last_group and self.list_is_required_param[self.param_group_index + 1] ) opt_param_left_at_level = self.params_left_at_level > 0 if ( opt_param_left_at_level or is_required and (is_last_group or next_is_required) ): if not is_last_group or opt_param_left_at_level or self.trailing_comma: self.add_text(self.param_separator) self.end_state(wrap=False, end=None) elif self.required_params_left: self.add_text(self.param_separator) if is_required: self.param_group_index += 1 raise nodes.SkipNode def visit_desc_type_parameter(self, node: Element) -> None: self.visit_desc_parameter(node) def visit_desc_optional(self, node: Element) -> None: self.params_left_at_level = sum( isinstance(c, addnodes.desc_parameter) for c in node.children ) self.optional_param_level += 1 self.max_optional_param_level = self.optional_param_level if self.multi_line_parameter_list: # If the first parameter is optional, start a new line and open the bracket. if self.is_first_param: self.new_state() self.add_text('[') # Else, if there remains at least one required parameter, append the # parameter separator, open a new bracket, and end the line. elif self.required_params_left: self.add_text(self.param_separator) self.add_text('[') self.end_state(wrap=False, end=None) # Else, open a new bracket, append the parameter separator, and end the # line. else: self.add_text('[') self.add_text(self.param_separator) self.end_state(wrap=False, end=None) else: self.add_text('[') def depart_desc_optional(self, node: Element) -> None: self.optional_param_level -= 1 level = self.optional_param_level if self.multi_line_parameter_list: max_level = self.max_optional_param_level len_lirp = len(self.list_is_required_param) is_last_group = self.param_group_index + 1 == len_lirp # If it's the first time we go down one level, add the separator before the # bracket, except if this is the last parameter and the parameter list # should not feature a trailing comma. if level == max_level - 1 and ( not is_last_group or level > 0 or self.trailing_comma ): self.add_text(self.param_separator) self.add_text(']') # End the line if we have just closed the last bracket of this group of # optional parameters. if level == 0: self.end_state(wrap=False, end=None) else: self.add_text(']') if level == 0: self.param_group_index += 1 def visit_desc_annotation(self, node: Element) -> None: pass def depart_desc_annotation(self, node: Element) -> None: pass ############################################## def visit_figure(self, node: Element) -> None: self.new_state() def depart_figure(self, node: Element) -> None: self.end_state() def visit_caption(self, node: Element) -> None: pass def depart_caption(self, node: Element) -> None: pass def visit_productionlist(self, node: Element) -> None: self.new_state() self.in_production_list = True def depart_productionlist(self, node: Element) -> None: self.in_production_list = False self.end_state(wrap=False) def visit_production(self, node: Element) -> None: pass def depart_production(self, node: Element) -> None: pass def visit_footnote(self, node: Element) -> None: label = cast('nodes.label', node[0]) self._footnote = label.astext().strip() self.new_state(len(self._footnote) + 3) def depart_footnote(self, node: Element) -> None: self.end_state(first='[%s] ' % self._footnote) def visit_citation(self, node: Element) -> None: if len(node) and isinstance(node[0], nodes.label): self._citlabel = node[0].astext() else: self._citlabel = '' self.new_state(len(self._citlabel) + 3) def depart_citation(self, node: Element) -> None: self.end_state(first='[%s] ' % self._citlabel) def visit_label(self, node: Element) -> None: raise nodes.SkipNode def visit_legend(self, node: Element) -> None: pass def depart_legend(self, node: Element) -> None: pass # XXX: option list could use some better styling def visit_option_list(self, node: Element) -> None: pass def depart_option_list(self, node: Element) -> None: pass def visit_option_list_item(self, node: Element) -> None: self.new_state(0) def depart_option_list_item(self, node: Element) -> None: self.end_state() def visit_option_group(self, node: Element) -> None: self._firstoption = True def depart_option_group(self, node: Element) -> None: self.add_text(' ') def visit_option(self, node: Element) -> None: if self._firstoption: self._firstoption = False else: self.add_text(', ') def depart_option(self, node: Element) -> None: pass def visit_option_string(self, node: Element) -> None: pass def depart_option_string(self, node: Element) -> None: pass def visit_option_argument(self, node: Element) -> None: self.add_text(node['delimiter']) def depart_option_argument(self, node: Element) -> None: pass def visit_description(self, node: Element) -> None: pass def depart_description(self, node: Element) -> None: pass def visit_tabular_col_spec(self, node: Element) -> None: raise nodes.SkipNode def visit_colspec(self, node: Element) -> None: self.table.colwidth.append(node['colwidth']) raise nodes.SkipNode def visit_tgroup(self, node: Element) -> None: pass def depart_tgroup(self, node: Element) -> None: pass def visit_thead(self, node: Element) -> None: pass def depart_thead(self, node: Element) -> None: pass def visit_tbody(self, node: Element) -> None: self.table.set_separator() def depart_tbody(self, node: Element) -> None: pass def visit_row(self, node: Element) -> None: if self.table.lines: self.table.add_row() def depart_row(self, node: Element) -> None: pass def visit_entry(self, node: Element) -> None: self.entry = Cell( rowspan=node.get('morerows', 0) + 1, colspan=node.get('morecols', 0) + 1, ) self.new_state(0) def depart_entry(self, node: Element) -> None: text = self.nl.join(self.nl.join(x[1]) for x in self.states.pop()) self.stateindent.pop() self.entry.text = text self.table.add_cell(self.entry) del self.entry def visit_table(self, node: Element) -> None: if hasattr(self, 'table'): msg = 'Nested tables are not supported.' raise NotImplementedError(msg) self.new_state(0) self.table = Table() def depart_table(self, node: Element) -> None: self.add_text(str(self.table)) del self.table self.end_state(wrap=False) def visit_acks(self, node: Element) -> None: bullet_list = cast('nodes.bullet_list', node[0]) list_items = cast('Iterable[nodes.list_item]', bullet_list) self.new_state(0) self.add_text(', '.join(n.astext() for n in list_items) + '.') self.end_state() raise nodes.SkipNode def visit_image(self, node: Element) -> None: if 'alt' in node.attributes: self.add_text(_('[image: %s]') % node['alt']) self.add_text(_('[image]')) raise nodes.SkipNode def visit_transition(self, node: Element) -> None: indent = sum(self.stateindent) self.new_state(0) self.add_text('=' * (MAXWIDTH - indent)) self.end_state() raise nodes.SkipNode def visit_bullet_list(self, node: Element) -> None: self.list_counter.append(-1) def depart_bullet_list(self, node: Element) -> None: self.list_counter.pop() def visit_enumerated_list(self, node: Element) -> None: self.list_counter.append(node.get('start', 1) - 1) def depart_enumerated_list(self, node: Element) -> None: self.list_counter.pop() def visit_definition_list(self, node: Element) -> None: self.list_counter.append(-2) def depart_definition_list(self, node: Element) -> None: self.list_counter.pop() def visit_list_item(self, node: Element) -> None: if self.list_counter[-1] == -1: # bullet list self.new_state(2) elif self.list_counter[-1] == -2: # definition list pass else: # enumerated list self.list_counter[-1] += 1 self.new_state(len(str(self.list_counter[-1])) + 2) def depart_list_item(self, node: Element) -> None: if self.list_counter[-1] == -1: self.end_state(first='* ') elif self.list_counter[-1] == -2: pass else: self.end_state(first='%s. ' % self.list_counter[-1]) def visit_definition_list_item(self, node: Element) -> None: self._classifier_count_in_li = len(list(node.findall(nodes.classifier))) def depart_definition_list_item(self, node: Element) -> None: pass def visit_term(self, node: Element) -> None: self.new_state(0) def depart_term(self, node: Element) -> None: if not self._classifier_count_in_li: self.end_state(end=None) def visit_classifier(self, node: Element) -> None: self.add_text(' : ') def depart_classifier(self, node: Element) -> None: self._classifier_count_in_li -= 1 if not self._classifier_count_in_li: self.end_state(end=None) def visit_definition(self, node: Element) -> None: self.new_state() def depart_definition(self, node: Element) -> None: self.end_state() def visit_field_list(self, node: Element) -> None: pass def depart_field_list(self, node: Element) -> None: pass def visit_field(self, node: Element) -> None: pass def depart_field(self, node: Element) -> None: pass def visit_field_name(self, node: Element) -> None: self.new_state(0) def depart_field_name(self, node: Element) -> None: self.add_text(':') self.end_state(end=None) def visit_field_body(self, node: Element) -> None: self.new_state() def depart_field_body(self, node: Element) -> None: self.end_state() def visit_centered(self, node: Element) -> None: pass def depart_centered(self, node: Element) -> None: pass def visit_hlist(self, node: Element) -> None: pass def depart_hlist(self, node: Element) -> None: pass def visit_hlistcol(self, node: Element) -> None: pass def depart_hlistcol(self, node: Element) -> None: pass def visit_admonition(self, node: Element) -> None: self.new_state(0) def depart_admonition(self, node: Element) -> None: self.end_state() def _visit_admonition(self, node: Element) -> None: self.new_state(2) def _depart_admonition(self, node: Element) -> None: label = admonitionlabels[node.tagname] indent = sum(self.stateindent) + len(label) if ( len(self.states[-1]) == 1 and self.states[-1][0][0] == 0 and MAXWIDTH - indent >= sum(len(s) for s in self.states[-1][0][1]) ): # short text: append text after admonition label self.stateindent[-1] += len(label) self.end_state(first=label + ': ') else: # long text: append label before the block self.states[-1].insert(0, (0, [self.nl])) self.end_state(first=label + ':') visit_attention = _visit_admonition depart_attention = _depart_admonition visit_caution = _visit_admonition depart_caution = _depart_admonition visit_danger = _visit_admonition depart_danger = _depart_admonition visit_error = _visit_admonition depart_error = _depart_admonition visit_hint = _visit_admonition depart_hint = _depart_admonition visit_important = _visit_admonition depart_important = _depart_admonition visit_note = _visit_admonition depart_note = _depart_admonition visit_tip = _visit_admonition depart_tip = _depart_admonition visit_warning = _visit_admonition depart_warning = _depart_admonition visit_seealso = _visit_admonition depart_seealso = _depart_admonition def visit_versionmodified(self, node: Element) -> None: self.new_state(0) def depart_versionmodified(self, node: Element) -> None: self.end_state() def visit_literal_block(self, node: Element) -> None: self.new_state() def depart_literal_block(self, node: Element) -> None: self.end_state(wrap=False) def visit_doctest_block(self, node: Element) -> None: self.new_state(0) def depart_doctest_block(self, node: Element) -> None: self.end_state(wrap=False) def visit_line_block(self, node: Element) -> None: self.new_state() self.lineblocklevel += 1 def depart_line_block(self, node: Element) -> None: self.lineblocklevel -= 1 self.end_state(wrap=False, end=None) if not self.lineblocklevel: self.add_text('\n') def visit_line(self, node: Element) -> None: pass def depart_line(self, node: Element) -> None: self.add_text('\n') def visit_block_quote(self, node: Element) -> None: self.new_state() def depart_block_quote(self, node: Element) -> None: self.end_state() def visit_compact_paragraph(self, node: Element) -> None: pass def depart_compact_paragraph(self, node: Element) -> None: pass def visit_paragraph(self, node: Element) -> None: if ( not isinstance(node.parent, nodes.Admonition) or isinstance(node.parent, addnodes.seealso) ): # fmt: skip self.new_state(0) def depart_paragraph(self, node: Element) -> None: if ( not isinstance(node.parent, nodes.Admonition) or isinstance(node.parent, addnodes.seealso) ): # fmt: skip self.end_state() def visit_target(self, node: Element) -> None: raise nodes.SkipNode def visit_index(self, node: Element) -> None: raise nodes.SkipNode def visit_toctree(self, node: Element) -> None: raise nodes.SkipNode def visit_substitution_definition(self, node: Element) -> None: raise nodes.SkipNode def visit_pending_xref(self, node: Element) -> None: pass def depart_pending_xref(self, node: Element) -> None: pass def visit_reference(self, node: Element) -> None: if self.add_secnumbers: numbers = node.get('secnumber') if numbers is not None: self.add_text('.'.join(map(str, numbers)) + self.secnumber_suffix) def depart_reference(self, node: Element) -> None: pass def visit_number_reference(self, node: Element) -> None: text = nodes.Text(node.get('title', '#')) self.visit_Text(text) raise nodes.SkipNode def visit_download_reference(self, node: Element) -> None: pass def depart_download_reference(self, node: Element) -> None: pass def visit_emphasis(self, node: Element) -> None: self.add_text('*') def depart_emphasis(self, node: Element) -> None: self.add_text('*') def visit_literal_emphasis(self, node: Element) -> None: self.add_text('*') def depart_literal_emphasis(self, node: Element) -> None: self.add_text('*') def visit_strong(self, node: Element) -> None: self.add_text('**') def depart_strong(self, node: Element) -> None: self.add_text('**') def visit_literal_strong(self, node: Element) -> None: if self.in_production_list: return self.add_text('**') def depart_literal_strong(self, node: Element) -> None: if self.in_production_list: return self.add_text('**') def visit_abbreviation(self, node: Element) -> None: self.add_text('') def depart_abbreviation(self, node: Element) -> None: if explanation := node.get('explanation', ''): self.add_text(f' ({explanation})') def visit_manpage(self, node: Element) -> None: return self.visit_literal_emphasis(node) def depart_manpage(self, node: Element) -> None: return self.depart_literal_emphasis(node) def visit_title_reference(self, node: Element) -> None: self.add_text('*') def depart_title_reference(self, node: Element) -> None: self.add_text('*') def visit_literal(self, node: Element) -> None: if self.in_production_list: return self.add_text('"') def depart_literal(self, node: Element) -> None: if self.in_production_list: return self.add_text('"') def visit_subscript(self, node: Element) -> None: self.add_text('_') def depart_subscript(self, node: Element) -> None: pass def visit_superscript(self, node: Element) -> None: self.add_text('^') def depart_superscript(self, node: Element) -> None: pass def visit_footnote_reference(self, node: Element) -> None: self.add_text('[%s]' % node.astext()) raise nodes.SkipNode def visit_citation_reference(self, node: Element) -> None: self.add_text('[%s]' % node.astext()) raise nodes.SkipNode def visit_Text(self, node: Text) -> None: self.add_text(node.astext()) def depart_Text(self, node: Text) -> None: pass def visit_generated(self, node: Element) -> None: pass def depart_generated(self, node: Element) -> None: pass def visit_inline(self, node: Element) -> None: if 'xref' in node['classes'] or 'term' in node['classes']: self.add_text('*') def depart_inline(self, node: Element) -> None: if 'xref' in node['classes'] or 'term' in node['classes']: self.add_text('*') def visit_container(self, node: Element) -> None: pass def depart_container(self, node: Element) -> None: pass def visit_problematic(self, node: Element) -> None: self.add_text('>>') def depart_problematic(self, node: Element) -> None: self.add_text('<<') def visit_system_message(self, node: Element) -> None: self.new_state(0) self.add_text('<SYSTEM MESSAGE: %s>' % node.astext()) self.end_state() raise nodes.SkipNode def visit_comment(self, node: Element) -> None: raise nodes.SkipNode def visit_meta(self, node: Element) -> None: # only valid for HTML raise nodes.SkipNode def visit_raw(self, node: Element) -> None: if 'text' in node.get('format', '').split(): self.new_state(0) self.add_text(node.astext()) self.end_state(wrap=False) raise nodes.SkipNode def visit_math(self, node: nodes.math) -> None: pass def depart_math(self, node: nodes.math) -> None: pass def visit_math_block(self, node: nodes.math_block) -> None: self.new_state() def depart_math_block(self, node: nodes.math_block) -> None: self.end_state()
TextTranslator
python
django-haystack__django-haystack
test_haystack/mocks.py
{ "start": 700, "end": 807 }
class ____(BaseRouter): def for_write(self, **hints): return ["multi1", "multi2"]
MockMultiRouter
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/impl.py
{ "start": 2840, "end": 3145 }
class ____: """This represents a user error encountered during the IPC call. This indicates a business logic error, rather than a protocol. Consider this a "task failed successfully" use case. """ serializable_error_info: SerializableErrorInfo message: Optional[str]
IPCErrorMessage
python
wandb__wandb
wandb/vendor/pygments/lexers/ruby.py
{ "start": 805, "end": 16899 }
class ____(ExtendedRegexLexer): """ For `Ruby <http://www.ruby-lang.org>`_ source code. """ name = 'Ruby' aliases = ['rb', 'ruby', 'duby'] filenames = ['*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec', '*.rbx', '*.duby', 'Gemfile'] mimetypes = ['text/x-ruby', 'application/x-ruby'] flags = re.DOTALL | re.MULTILINE def heredoc_callback(self, match, ctx): # okay, this is the hardest part of parsing Ruby... # match: 1 = <<-?, 2 = quote? 3 = name 4 = quote? 5 = rest of line start = match.start(1) yield start, Operator, match.group(1) # <<-? yield match.start(2), String.Heredoc, match.group(2) # quote ", ', ` yield match.start(3), String.Delimiter, match.group(3) # heredoc name yield match.start(4), String.Heredoc, match.group(4) # quote again heredocstack = ctx.__dict__.setdefault('heredocstack', []) outermost = not bool(heredocstack) heredocstack.append((match.group(1) == '<<-', match.group(3))) ctx.pos = match.start(5) ctx.end = match.end(5) # this may find other heredocs for i, t, v in self.get_tokens_unprocessed(context=ctx): yield i, t, v ctx.pos = match.end() if outermost: # this is the outer heredoc again, now we can process them all for tolerant, hdname in heredocstack: lines = [] for match in line_re.finditer(ctx.text, ctx.pos): if tolerant: check = match.group().strip() else: check = match.group().rstrip() if check == hdname: for amatch in lines: yield amatch.start(), String.Heredoc, amatch.group() yield match.start(), String.Delimiter, match.group() ctx.pos = match.end() break else: lines.append(match) else: # end of heredoc not found -- error! for amatch in lines: yield amatch.start(), Error, amatch.group() ctx.end = len(ctx.text) del heredocstack[:] def gen_rubystrings_rules(): def intp_regex_callback(self, match, ctx): yield match.start(1), String.Regex, match.group(1) # begin nctx = LexerContext(match.group(3), 0, ['interpolated-regex']) for i, t, v in self.get_tokens_unprocessed(context=nctx): yield match.start(3)+i, t, v yield match.start(4), String.Regex, match.group(4) # end[mixounse]* ctx.pos = match.end() def intp_string_callback(self, match, ctx): yield match.start(1), String.Other, match.group(1) nctx = LexerContext(match.group(3), 0, ['interpolated-string']) for i, t, v in self.get_tokens_unprocessed(context=nctx): yield match.start(3)+i, t, v yield match.start(4), String.Other, match.group(4) # end ctx.pos = match.end() states = {} states['strings'] = [ # easy ones (r'\:@{0,2}[a-zA-Z_]\w*[!?]?', String.Symbol), (words(RUBY_OPERATORS, prefix=r'\:@{0,2}'), String.Symbol), (r":'(\\\\|\\'|[^'])*'", String.Symbol), (r"'(\\\\|\\'|[^'])*'", String.Single), (r':"', String.Symbol, 'simple-sym'), (r'([a-zA-Z_]\w*)(:)(?!:)', bygroups(String.Symbol, Punctuation)), # Since Ruby 1.9 (r'"', String.Double, 'simple-string'), (r'(?<!\.)`', String.Backtick, 'simple-backtick'), ] # double-quoted string and symbol for name, ttype, end in ('string', String.Double, '"'), \ ('sym', String.Symbol, '"'), \ ('backtick', String.Backtick, '`'): states['simple-'+name] = [ include('string-intp-escaped'), (r'[^\\%s#]+' % end, ttype), (r'[\\#]', ttype), (end, ttype, '#pop'), ] # braced quoted strings for lbrace, rbrace, bracecc, name in \ ('\\{', '\\}', '{}', 'cb'), \ ('\\[', '\\]', '\\[\\]', 'sb'), \ ('\\(', '\\)', '()', 'pa'), \ ('<', '>', '<>', 'ab'): states[name+'-intp-string'] = [ (r'\\[\\' + bracecc + ']', String.Other), (lbrace, String.Other, '#push'), (rbrace, String.Other, '#pop'), include('string-intp-escaped'), (r'[\\#' + bracecc + ']', String.Other), (r'[^\\#' + bracecc + ']+', String.Other), ] states['strings'].append((r'%[QWx]?' + lbrace, String.Other, name+'-intp-string')) states[name+'-string'] = [ (r'\\[\\' + bracecc + ']', String.Other), (lbrace, String.Other, '#push'), (rbrace, String.Other, '#pop'), (r'[\\#' + bracecc + ']', String.Other), (r'[^\\#' + bracecc + ']+', String.Other), ] states['strings'].append((r'%[qsw]' + lbrace, String.Other, name+'-string')) states[name+'-regex'] = [ (r'\\[\\' + bracecc + ']', String.Regex), (lbrace, String.Regex, '#push'), (rbrace + '[mixounse]*', String.Regex, '#pop'), include('string-intp'), (r'[\\#' + bracecc + ']', String.Regex), (r'[^\\#' + bracecc + ']+', String.Regex), ] states['strings'].append((r'%r' + lbrace, String.Regex, name+'-regex')) # these must come after %<brace>! states['strings'] += [ # %r regex (r'(%r([\W_]))((?:\\\2|(?!\2).)*)(\2[mixounse]*)', intp_regex_callback), # regular fancy strings with qsw (r'%[qsw]([\W_])((?:\\\1|(?!\1).)*)\1', String.Other), (r'(%[QWx]([\W_]))((?:\\\2|(?!\2).)*)(\2)', intp_string_callback), # special forms of fancy strings after operators or # in method calls with braces (r'(?<=[-+/*%=<>&!^|~,(])(\s*)(%([\t ])(?:(?:\\\3|(?!\3).)*)\3)', bygroups(Text, String.Other, None)), # and because of fixed width lookbehinds the whole thing a # second time for line startings... (r'^(\s*)(%([\t ])(?:(?:\\\3|(?!\3).)*)\3)', bygroups(Text, String.Other, None)), # all regular fancy strings without qsw (r'(%([^a-zA-Z0-9\s]))((?:\\\2|(?!\2).)*)(\2)', intp_string_callback), ] return states tokens = { 'root': [ (r'\A#!.+?$', Comment.Hashbang), (r'#.*?$', Comment.Single), (r'=begin\s.*?\n=end.*?$', Comment.Multiline), # keywords (words(( 'BEGIN', 'END', 'alias', 'begin', 'break', 'case', 'defined?', 'do', 'else', 'elsif', 'end', 'ensure', 'for', 'if', 'in', 'next', 'redo', 'rescue', 'raise', 'retry', 'return', 'super', 'then', 'undef', 'unless', 'until', 'when', 'while', 'yield'), suffix=r'\b'), Keyword), # start of function, class and module names (r'(module)(\s+)([a-zA-Z_]\w*' r'(?:::[a-zA-Z_]\w*)*)', bygroups(Keyword, Text, Name.Namespace)), (r'(def)(\s+)', bygroups(Keyword, Text), 'funcname'), (r'def(?=[*%&^`~+-/\[<>=])', Keyword, 'funcname'), (r'(class)(\s+)', bygroups(Keyword, Text), 'classname'), # special methods (words(( 'initialize', 'new', 'loop', 'include', 'extend', 'raise', 'attr_reader', 'attr_writer', 'attr_accessor', 'attr', 'catch', 'throw', 'private', 'module_function', 'public', 'protected', 'true', 'false', 'nil'), suffix=r'\b'), Keyword.Pseudo), (r'(not|and|or)\b', Operator.Word), (words(( 'autoload', 'block_given', 'const_defined', 'eql', 'equal', 'frozen', 'include', 'instance_of', 'is_a', 'iterator', 'kind_of', 'method_defined', 'nil', 'private_method_defined', 'protected_method_defined', 'public_method_defined', 'respond_to', 'tainted'), suffix=r'\?'), Name.Builtin), (r'(chomp|chop|exit|gsub|sub)!', Name.Builtin), (words(( 'Array', 'Float', 'Integer', 'String', '__id__', '__send__', 'abort', 'ancestors', 'at_exit', 'autoload', 'binding', 'callcc', 'caller', 'catch', 'chomp', 'chop', 'class_eval', 'class_variables', 'clone', 'const_defined?', 'const_get', 'const_missing', 'const_set', 'constants', 'display', 'dup', 'eval', 'exec', 'exit', 'extend', 'fail', 'fork', 'format', 'freeze', 'getc', 'gets', 'global_variables', 'gsub', 'hash', 'id', 'included_modules', 'inspect', 'instance_eval', 'instance_method', 'instance_methods', 'instance_variable_get', 'instance_variable_set', 'instance_variables', 'lambda', 'load', 'local_variables', 'loop', 'method', 'method_missing', 'methods', 'module_eval', 'name', 'object_id', 'open', 'p', 'print', 'printf', 'private_class_method', 'private_instance_methods', 'private_methods', 'proc', 'protected_instance_methods', 'protected_methods', 'public_class_method', 'public_instance_methods', 'public_methods', 'putc', 'puts', 'raise', 'rand', 'readline', 'readlines', 'require', 'scan', 'select', 'self', 'send', 'set_trace_func', 'singleton_methods', 'sleep', 'split', 'sprintf', 'srand', 'sub', 'syscall', 'system', 'taint', 'test', 'throw', 'to_a', 'to_s', 'trace_var', 'trap', 'untaint', 'untrace_var', 'warn'), prefix=r'(?<!\.)', suffix=r'\b'), Name.Builtin), (r'__(FILE|LINE)__\b', Name.Builtin.Pseudo), # normal heredocs (r'(?<!\w)(<<-?)(["`\']?)([a-zA-Z_]\w*)(\2)(.*?\n)', heredoc_callback), # empty string heredocs (r'(<<-?)("|\')()(\2)(.*?\n)', heredoc_callback), (r'__END__', Comment.Preproc, 'end-part'), # multiline regex (after keywords or assignments) (r'(?:^|(?<=[=<>~!:])|' r'(?<=(?:\s|;)when\s)|' r'(?<=(?:\s|;)or\s)|' r'(?<=(?:\s|;)and\s)|' r'(?<=\.index\s)|' r'(?<=\.scan\s)|' r'(?<=\.sub\s)|' r'(?<=\.sub!\s)|' r'(?<=\.gsub\s)|' r'(?<=\.gsub!\s)|' r'(?<=\.match\s)|' r'(?<=(?:\s|;)if\s)|' r'(?<=(?:\s|;)elsif\s)|' r'(?<=^when\s)|' r'(?<=^index\s)|' r'(?<=^scan\s)|' r'(?<=^sub\s)|' r'(?<=^gsub\s)|' r'(?<=^sub!\s)|' r'(?<=^gsub!\s)|' r'(?<=^match\s)|' r'(?<=^if\s)|' r'(?<=^elsif\s)' r')(\s*)(/)', bygroups(Text, String.Regex), 'multiline-regex'), # multiline regex (in method calls or subscripts) (r'(?<=\(|,|\[)/', String.Regex, 'multiline-regex'), # multiline regex (this time the funny no whitespace rule) (r'(\s+)(/)(?![\s=])', bygroups(Text, String.Regex), 'multiline-regex'), # lex numbers and ignore following regular expressions which # are division operators in fact (grrrr. i hate that. any # better ideas?) # since pygments 0.7 we also eat a "?" operator after numbers # so that the char operator does not work. Chars are not allowed # there so that you can use the ternary operator. # stupid example: # x>=0?n[x]:"" (r'(0_?[0-7]+(?:_[0-7]+)*)(\s*)([/?])?', bygroups(Number.Oct, Text, Operator)), (r'(0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*)(\s*)([/?])?', bygroups(Number.Hex, Text, Operator)), (r'(0b[01]+(?:_[01]+)*)(\s*)([/?])?', bygroups(Number.Bin, Text, Operator)), (r'([\d]+(?:_\d+)*)(\s*)([/?])?', bygroups(Number.Integer, Text, Operator)), # Names (r'@@[a-zA-Z_]\w*', Name.Variable.Class), (r'@[a-zA-Z_]\w*', Name.Variable.Instance), (r'\$\w+', Name.Variable.Global), (r'\$[!@&`\'+~=/\\,;.<>_*$?:"^-]', Name.Variable.Global), (r'\$-[0adFiIlpvw]', Name.Variable.Global), (r'::', Operator), include('strings'), # chars (r'\?(\\[MC]-)*' # modifiers r'(\\([\\abefnrstv#"\']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})|\S)' r'(?!\w)', String.Char), (r'[A-Z]\w+', Name.Constant), # this is needed because ruby attributes can look # like keywords (class) or like this: ` ?!? (words(RUBY_OPERATORS, prefix=r'(\.|::)'), bygroups(Operator, Name.Operator)), (r'(\.|::)([a-zA-Z_]\w*[!?]?|[*%&^`~+\-/\[<>=])', bygroups(Operator, Name)), (r'[a-zA-Z_]\w*[!?]?', Name), (r'(\[|\]|\*\*|<<?|>>?|>=|<=|<=>|=~|={3}|' r'!~|&&?|\|\||\.{1,3})', Operator), (r'[-+/*%=<>&!^|~]=?', Operator), (r'[(){};,/?:\\]', Punctuation), (r'\s+', Text) ], 'funcname': [ (r'\(', Punctuation, 'defexpr'), (r'(?:([a-zA-Z_]\w*)(\.))?' r'([a-zA-Z_]\w*[!?]?|\*\*?|[-+]@?|' r'[/%&|^`~]|\[\]=?|<<|>>|<=?>|>=?|===?)', bygroups(Name.Class, Operator, Name.Function), '#pop'), default('#pop') ], 'classname': [ (r'\(', Punctuation, 'defexpr'), (r'<<', Operator, '#pop'), (r'[A-Z_]\w*', Name.Class, '#pop'), default('#pop') ], 'defexpr': [ (r'(\))(\.|::)?', bygroups(Punctuation, Operator), '#pop'), (r'\(', Operator, '#push'), include('root') ], 'in-intp': [ (r'\{', String.Interpol, '#push'), (r'\}', String.Interpol, '#pop'), include('root'), ], 'string-intp': [ (r'#\{', String.Interpol, 'in-intp'), (r'#@@?[a-zA-Z_]\w*', String.Interpol), (r'#\$[a-zA-Z_]\w*', String.Interpol) ], 'string-intp-escaped': [ include('string-intp'), (r'\\([\\abefnrstv#"\']|x[a-fA-F0-9]{1,2}|[0-7]{1,3})', String.Escape) ], 'interpolated-regex': [ include('string-intp'), (r'[\\#]', String.Regex), (r'[^\\#]+', String.Regex), ], 'interpolated-string': [ include('string-intp'), (r'[\\#]', String.Other), (r'[^\\#]+', String.Other), ], 'multiline-regex': [ include('string-intp'), (r'\\\\', String.Regex), (r'\\/', String.Regex), (r'[\\#]', String.Regex), (r'[^\\/#]+', String.Regex), (r'/[mixounse]*', String.Regex, '#pop'), ], 'end-part': [ (r'.+', Comment.Preproc, '#pop') ] } tokens.update(gen_rubystrings_rules()) def analyse_text(text): return shebang_matches(text, r'ruby(1\.\d)?')
RubyLexer
python
scrapy__scrapy
tests/test_spidermiddleware.py
{ "start": 7158, "end": 7284 }
class ____: def process_spider_output(self, response, result): yield from result
ProcessSpiderOutputSimpleMiddleware
python
chardet__chardet
chardet/big5prober.py
{ "start": 1309, "end": 1697 }
class ____(MultiByteCharSetProber): def __init__(self) -> None: super().__init__() self.coding_sm = CodingStateMachine(BIG5_SM_MODEL) self.distribution_analyzer = Big5DistributionAnalysis() self.reset() @property def charset_name(self) -> str: return "Big5" @property def language(self) -> str: return "Chinese"
Big5Prober
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_pgf.py
{ "start": 6776, "end": 13573 }
class ____: """ The LatexManager opens an instance of the LaTeX application for determining the metrics of text elements. The LaTeX environment can be modified by setting fonts and/or a custom preamble in `.rcParams`. """ @staticmethod def _build_latex_header(): latex_header = [ _DOCUMENTCLASS, # Include TeX program name as a comment for cache invalidation. # TeX does not allow this to be the first line. rf"% !TeX program = {mpl.rcParams['pgf.texsystem']}", # Test whether \includegraphics supports interpolate option. r"\usepackage{graphicx}", _get_preamble(), r"\begin{document}", r"\typeout{pgf_backend_query_start}", ] return "\n".join(latex_header) @classmethod def _get_cached_or_new(cls): """ Return the previous LatexManager if the header and tex system did not change, or a new instance otherwise. """ return cls._get_cached_or_new_impl(cls._build_latex_header()) @classmethod @functools.lru_cache(1) def _get_cached_or_new_impl(cls, header): # Helper for _get_cached_or_new. return cls() def _stdin_writeln(self, s): if self.latex is None: self._setup_latex_process() self.latex.stdin.write(s) self.latex.stdin.write("\n") self.latex.stdin.flush() def _expect(self, s): s = list(s) chars = [] while True: c = self.latex.stdout.read(1) chars.append(c) if chars[-len(s):] == s: break if not c: self.latex.kill() self.latex = None raise LatexError("LaTeX process halted", "".join(chars)) return "".join(chars) def _expect_prompt(self): return self._expect("\n*") def __init__(self): # create a tmp directory for running latex, register it for deletion self._tmpdir = TemporaryDirectory() self.tmpdir = self._tmpdir.name self._finalize_tmpdir = weakref.finalize(self, self._tmpdir.cleanup) # test the LaTeX setup to ensure a clean startup of the subprocess self._setup_latex_process(expect_reply=False) stdout, stderr = self.latex.communicate("\n\\makeatletter\\@@end\n") if self.latex.returncode != 0: raise LatexError( f"LaTeX errored (probably missing font or error in preamble) " f"while processing the following input:\n" f"{self._build_latex_header()}", stdout) self.latex = None # Will be set up on first use. # Per-instance cache. self._get_box_metrics = functools.lru_cache(self._get_box_metrics) def _setup_latex_process(self, *, expect_reply=True): # Open LaTeX process for real work; register it for deletion. On # Windows, we must ensure that the subprocess has quit before being # able to delete the tmpdir in which it runs; in order to do so, we # must first `kill()` it, and then `communicate()` with or `wait()` on # it. try: self.latex = subprocess.Popen( [mpl.rcParams["pgf.texsystem"], "-halt-on-error"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding="utf-8", cwd=self.tmpdir) except FileNotFoundError as err: raise RuntimeError( f"{mpl.rcParams['pgf.texsystem']!r} not found; install it or change " f"rcParams['pgf.texsystem'] to an available TeX implementation" ) from err except OSError as err: raise RuntimeError( f"Error starting {mpl.rcParams['pgf.texsystem']!r}") from err def finalize_latex(latex): latex.kill() try: latex.communicate() except RuntimeError: latex.wait() self._finalize_latex = weakref.finalize( self, finalize_latex, self.latex) # write header with 'pgf_backend_query_start' token self._stdin_writeln(self._build_latex_header()) if expect_reply: # read until 'pgf_backend_query_start' token appears self._expect("*pgf_backend_query_start") self._expect_prompt() def get_width_height_descent(self, text, prop): """ Get the width, total height, and descent (in TeX points) for a text typeset by the current LaTeX environment. """ return self._get_box_metrics(_escape_and_apply_props(text, prop)) def _get_box_metrics(self, tex): """ Get the width, total height and descent (in TeX points) for a TeX command's output in the current LaTeX environment. """ # This method gets wrapped in __init__ for per-instance caching. self._stdin_writeln( # Send textbox to TeX & request metrics typeout. # \sbox doesn't handle catcode assignments inside its argument, # so repeat the assignment of the catcode of "^" and "%" outside. r"{\catcode`\^=\active\catcode`\%%=\active\sbox0{%s}" r"\typeout{\the\wd0,\the\ht0,\the\dp0}}" % tex) try: answer = self._expect_prompt() except LatexError as err: # Here and below, use '{}' instead of {!r} to avoid doubling all # backslashes. raise ValueError("Error measuring {}\nLaTeX Output:\n{}" .format(tex, err.latex_output)) from err try: # Parse metrics from the answer string. Last line is prompt, and # next-to-last-line is blank line from \typeout. width, height, offset = answer.splitlines()[-3].split(",") except Exception as err: raise ValueError("Error measuring {}\nLaTeX Output:\n{}" .format(tex, answer)) from err w, h, o = float(width[:-2]), float(height[:-2]), float(offset[:-2]) # The height returned from LaTeX goes from base to top; # the height Matplotlib expects goes from bottom to top. return w, h + o, o @functools.lru_cache(1) def _get_image_inclusion_command(): man = LatexManager._get_cached_or_new() man._stdin_writeln( r"\includegraphics[interpolate=true]{%s}" # Don't mess with backslashes on Windows. % cbook._get_data_path("images/matplotlib.png").as_posix()) try: man._expect_prompt() return r"\includegraphics" except LatexError: # Discard the broken manager. LatexManager._get_cached_or_new_impl.cache_clear() return r"\pgfimage"
LatexManager
python
google__jax
tests/pallas/pallas_test.py
{ "start": 79430, "end": 87042 }
class ____(PallasBaseTest): INTERPRET = False def test_basic_runtime_assert(self): # TODO(justinfu): Move to non-interpret checkify class. if not jtu.test_device_matches(["tpu"]): self.skipTest("Runtime check only implemented on TPU.") # Run this test manually, since we cannot recover from a halt. self.skipTest("Cannot recover from halt.") def kernel(x_ref, y_ref): y_ref[...] = x_ref[...] checkify.check(True, "first check passed") checkify.check(False, "second check failed") input_ = jnp.arange(4, dtype=jnp.int32) out_shape = jax.ShapeDtypeStruct(input_.shape, input_.dtype) with pl.enable_debug_checks(True): pallas_call = pl.pallas_call(kernel, out_shape=out_shape) pallas_call(input_) # This should log "second check failed" def test_runtime_assert_is_noop_when_not_enabled(self): # TODO(justinfu): Move to non-interpret checkify class. if not jtu.test_device_matches(["tpu"]): self.skipTest("Runtime check only implemented on TPU.") def kernel(x_ref, y_ref): y_ref[...] = x_ref[...] pl.debug_check(False, "failed check") # This check always fails. input_ = jnp.arange(4, dtype=jnp.int32) out_shape = jax.ShapeDtypeStruct(input_.shape, input_.dtype) with pl.enable_debug_checks(False): pallas_call = pl.pallas_call(kernel, out_shape=out_shape) result = pallas_call(input_) np.testing.assert_allclose(result, input_) def test_no_checkify(self,): if jtu.test_device_matches(["gpu"]): self.skipTest("Not supported on GPU.") def kernel(y_ref): y_ref[...] = jnp.zeros_like(y_ref[...]) out_shape = jax.ShapeDtypeStruct((2, 2), jnp.float32) pallas_call = self.pallas_call(kernel, out_shape=out_shape) checked_call = checkify.checkify(pallas_call) err, result = checked_call() err.throw() # Should not raise. np.testing.assert_allclose(result, jnp.zeros_like(result)) def test_does_not_clobber_previous_error(self,): if jtu.test_device_matches(["gpu"]): self.skipTest("Not supported on GPU.") def kernel(y_ref): y_ref[...] = jnp.zeros_like(y_ref[...]) checkify.check(False, "error in kernel") out_shape = jax.ShapeDtypeStruct((2, 2), jnp.float32) pallas_call = self.pallas_call(kernel, out_shape=out_shape) def error_before_call(): checkify.check(False, "error before call") return pallas_call() checked_call = checkify.checkify(error_before_call) err, result = checked_call() with self.assertRaisesRegex( checkify.JaxRuntimeError, "error before call"): err.throw() np.testing.assert_allclose(result, jnp.zeros_like(result)) @parameterized.parameters((False,), (True,)) def test_trivial_check(self, assert_cond): if jtu.test_device_matches(["gpu"]): self.skipTest("Not supported on GPU.") def kernel(x_ref, y_ref): y_ref[...] = x_ref[...] checkify.check(assert_cond, "pallas check failed") input = jnp.arange(4, dtype=jnp.int32) out_shape = jax.ShapeDtypeStruct(input.shape, input.dtype) pallas_call = self.pallas_call(kernel, out_shape=out_shape) checked_call = checkify.checkify(pallas_call) err, result = checked_call(input) if not assert_cond: with self.assertRaisesRegex( checkify.JaxRuntimeError, "pallas check failed"): err.throw() np.testing.assert_allclose(result, input) def test_nan_error(self): if not self.INTERPRET: self.skipTest("Not supported in non-interpret mode.") def kernel(x_ref, y_ref): y_ref[...] = jnp.log(x_ref[...]) input = jnp.arange(4, dtype=jnp.float32) - 2 out_shape = jax.ShapeDtypeStruct(input.shape, input.dtype) pallas_call = self.pallas_call(kernel, out_shape=out_shape) checked_call = checkify.checkify(pallas_call, errors=checkify.nan_checks) err, result = checked_call(input) with self.assertRaisesRegex( checkify.JaxRuntimeError, "nan generated by primitive: log"): err.throw() is_nan = jnp.isnan(result) np.testing.assert_allclose(is_nan, input < 0) def test_nan_error_with_assertion(self): # TODO(b/346842088): Fix check asserts clobbering other errors. self.skipTest('Known failure.') # Test NaN error is not clobbered by an assertion failure def kernel(x_ref, y_ref): y_ref[...] = jnp.log(x_ref[...]) checkify.check(False, "do not raise") input = jnp.arange(4, dtype=jnp.float32) - 10 out_shape = jax.ShapeDtypeStruct(input.shape, input.dtype) pallas_call = self.pallas_call(kernel, out_shape=out_shape) checked_call = checkify.checkify(pallas_call, errors=checkify.all_checks) err, _ = checked_call(input) with self.assertRaisesRegex( checkify.JaxRuntimeError, "nan generated by primitive: log"): err.throw() @parameterized.parameters((5, 0), (8, 3), (4, 3)) def test_checkify_returns_first_error_in_grid( self, num_loops, fail_iteration): if not self.INTERPRET: self.skipTest("Not supported in non-interpret mode.") # Check that checkify returns the first error that occurs # TODO(justinfu): This test doesn't make sense on GPU, where threads run # in parallel. Update checkify to return a grid of errors. def kernel(x_ref, _): value = jnp.squeeze(x_ref[...]) checkify.check( value < fail_iteration, "failed on loop {itr}", itr=value) input_arr = jnp.arange(num_loops, dtype=jnp.float32) in_specs = [pl.BlockSpec((1,), lambda x: (x,))] out_specs = pl.BlockSpec((1,), lambda x: (x,)) out_shape = jax.ShapeDtypeStruct((1,), dtype=jnp.float32) pallas_call = self.pallas_call(kernel, grid=(num_loops,), in_specs=in_specs, out_specs=out_specs, out_shape=out_shape) checked_call = checkify.checkify(pallas_call, errors=checkify.user_checks) err, _ = checked_call(input_arr) with self.assertRaisesRegex( checkify.JaxRuntimeError, f"failed on loop {fail_iteration}"): err.throw() def test_checkify_on_oob_grid_access(self): if not self.INTERPRET: self.skipTest("Not supported in non-interpret mode.") if config.enable_x64.value: self.skipTest("Not supported in x64 mode.") def kernel(x_ref, o_ref): o_ref[...] = x_ref[...] input_arr = jnp.arange(18, dtype=jnp.float32) in_specs = [pl.BlockSpec((8,), lambda x: (x,))] out_specs = pl.BlockSpec((8,), lambda x: (x,)) out_shape = jax.ShapeDtypeStruct((18,), dtype=jnp.float32) pallas_call = self.pallas_call(kernel, grid=(3,), in_specs=in_specs, out_specs=out_specs, out_shape=out_shape) checked_call = checkify.checkify(pallas_call, errors=checkify.index_checks) err, result = checked_call(input_arr) with self.assertRaisesRegex(checkify.JaxRuntimeError, (r"out-of-bounds indexing for array of shape \(18,\): index 16 " r"is out of bounds for axis 0 with size 18")): err.throw() np.testing.assert_array_equal(result, input_arr)
PallasCheckifyTest
python
pytorch__pytorch
benchmarks/gpt_fast/mixtral_moe_model.py
{ "start": 7275, "end": 8233 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.w1 = nn.Parameter( torch.empty(config.num_experts, config.intermediate_size, config.dim) ) self.w2 = nn.Parameter( torch.empty(config.num_experts, config.dim, config.intermediate_size) ) self.w3 = nn.Parameter( torch.empty(config.num_experts, config.intermediate_size, config.dim) ) def forward(self, x: Tensor, expert_indices: Tensor) -> Tensor: w1_weights = self.w1[expert_indices] # [T, A, D, D] w3_weights = self.w3[expert_indices] # [T, A, D, D] w2_weights = self.w2[expert_indices] # [T, A, D, D] x1 = F.silu(torch.einsum("ti,taoi -> tao", x, w1_weights)) x3 = torch.einsum("ti, taoi -> tao", x, w3_weights) expert_outs = torch.einsum("tao, taio -> tai", (x1 * x3), w2_weights) return expert_outs
ConditionalFeedForward
python
langchain-ai__langchain
libs/core/langchain_core/outputs/chat_generation.py
{ "start": 391, "end": 2296 }
class ____(Generation): """A single chat generation output. A subclass of `Generation` that represents the response from a chat model that generates chat messages. The `message` attribute is a structured representation of the chat message. Most of the time, the message will be of type `AIMessage`. Users working with chat models will usually access information via either `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via callbacks). """ text: str = "" """The text contents of the output message. !!! warning SHOULD NOT BE SET DIRECTLY! """ message: BaseMessage """The message output by the chat model.""" # Override type to be ChatGeneration, ignore mypy error as this is intentional type: Literal["ChatGeneration"] = "ChatGeneration" # type: ignore[assignment] """Type is used exclusively for serialization purposes.""" @model_validator(mode="after") def set_text(self) -> Self: """Set the text attribute to be the contents of the message. Args: values: The values of the object. Returns: The values of the object with the text attribute set. Raises: ValueError: If the message is not a string or a list. """ text = "" if isinstance(self.message.content, str): text = self.message.content # Assumes text in content blocks in OpenAI format. # Uses first text block. elif isinstance(self.message.content, list): for block in self.message.content: if isinstance(block, str): text = block break if isinstance(block, dict) and "text" in block: text = block["text"] break self.text = text return self
ChatGeneration
python
apache__airflow
dev/breeze/src/airflow_breeze/global_constants.py
{ "start": 8885, "end": 8972 }
class ____(SelectiveTestType): AIRFLOW_CTL = "AirflowCTL"
SelectiveAirflowCtlTestType