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
PyCQA__pylint
pylint/checkers/symilar.py
{ "start": 4011, "end": 5207 }
class ____: """The LinesChunk object computes and stores the hash of some consecutive stripped lines of a lineset. """ __slots__ = ("_fileid", "_hash", "_index") def __init__(self, fileid: str, num_line: int, *lines: Iterable[str]) -> None: self._fileid: str = fileid """The name of the file from which the LinesChunk object is generated.""" self._index: Index = Index(num_line) """The index in the stripped lines that is the starting of consecutive lines. """ self._hash: int = sum(hash(lin) for lin in lines) """The hash of some consecutive lines.""" def __eq__(self, o: object) -> bool: if not isinstance(o, LinesChunk): return NotImplemented return self._hash == o._hash def __hash__(self) -> int: return self._hash def __repr__(self) -> str: return ( f"<LinesChunk object for file {self._fileid} ({self._index}, {self._hash})>" ) def __str__(self) -> str: return ( f"LinesChunk object for file {self._fileid}, starting at line {self._index} \n" f"Hash is {self._hash}" )
LinesChunk
python
django__django
tests/model_enums/tests.py
{ "start": 9445, "end": 9652 }
class ____(ipaddress.IPv4Network, models.Choices): LOOPBACK = "127.0.0.0/8", "Loopback" LINK_LOCAL = "169.254.0.0/16", "Link-Local" PRIVATE_USE_A = "10.0.0.0/8", "Private-Use (Class A)"
IPv4Network
python
Textualize__textual
docs/examples/styles/grid_size_both.py
{ "start": 100, "end": 390 }
class ____(App): CSS_PATH = "grid_size_both.tcss" def compose(self): yield Grid( Label("1"), Label("2"), Label("3"), Label("4"), Label("5"), ) if __name__ == "__main__": app = MyApp() app.run()
MyApp
python
huggingface__transformers
src/transformers/generation/candidate_generator.py
{ "start": 58466, "end": 63937 }
class ____(AssistedCandidateGenerator): """ `CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates candidates through the use of **the model itself**, exiting early. Can only be used with models that support early exit, e.g., `facebook/layerskip-llama3.2-1B`. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. [What are input IDs?](../glossary#input-ids) assistant_model (`PreTrainedModel`): The original model. This model must support early exit (i.e. is trained to compute logits in earlier layers). generation_config (`~generation.GenerationConfig`, *optional*): The generation configuration to be used as base parametrization for the generation call. logits_processor (`LogitsProcessorList`): An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`] used to modify the prediction scores of the language modeling head applied at each generation step. model_kwargs (`Dict`): The keyword arguments that will be passed to the main model, and are used as base inputs for the assistant model as well. inputs_tensor (`torch.Tensor`, *optional*): The model input tensor. In encoder-decoder models, this is the encoder input. """ def __init__( self, input_ids: torch.LongTensor, assistant_model: "PreTrainedModel", generation_config: "GenerationConfig", model_kwargs: dict, inputs_tensor: torch.Tensor | None = None, logits_processor: Optional["LogitsProcessorList"] = None, ): super().__init__( input_ids=input_ids, assistant_model=assistant_model, generation_config=generation_config, model_kwargs=model_kwargs, inputs_tensor=inputs_tensor, logits_processor=logits_processor, ) # We have to move early exit out of the generation config, otherwise the assistant will also call `generate` # with early exit self.assistant_early_exit = self.generation_config.assistant_early_exit self.generation_config.assistant_early_exit = None def get_candidates(self, input_ids: torch.LongTensor) -> tuple[torch.LongTensor, torch.FloatTensor | None]: # Temporarily sets the number of hidden layers to the early exit value base_model = getattr(self.assistant_model, self.assistant_model.base_model_prefix) original_num_hidden_layers = base_model.config.num_hidden_layers base_model.config.num_hidden_layers = self.assistant_early_exit candidate_ids, candidate_logits = super().get_candidates(input_ids) base_model.config.num_hidden_layers = original_num_hidden_layers return candidate_ids, candidate_logits def _prepare_attention_mask(model_kwargs: dict[str, Any], new_length: int, is_encoder_decoder: bool) -> dict[str, Any]: """Expands or crops the model's mask for decoding purposes, to the defined length""" mask_key = "decoder_attention_mask" if is_encoder_decoder else "attention_mask" if mask_key not in model_kwargs: return model_kwargs mask = model_kwargs[mask_key] mask_length_diff = new_length - mask.shape[1] if mask_length_diff < 0: model_kwargs[mask_key] = mask[:, :mask_length_diff] elif mask_length_diff > 0: model_kwargs[mask_key] = torch.cat([mask, mask.new_ones((mask.shape[0], mask_length_diff))], dim=-1) # Handle cross attention models if "cross_attention_mask" in model_kwargs: # Mllama case cross_mask = model_kwargs["cross_attention_mask"] if mask_length_diff < 0: model_kwargs["cross_attention_mask"] = cross_mask[:, :mask_length_diff] elif mask_length_diff > 0: new_mask = cross_mask[:, -1:, :, :].repeat(1, mask_length_diff, 1, 1) model_kwargs["cross_attention_mask"] = torch.cat([cross_mask, new_mask], dim=1) elif "image_attention_mask" in model_kwargs: # IDEFICS case cross_mask = model_kwargs["image_attention_mask"] if mask_length_diff < 0: model_kwargs["image_attention_mask"] = cross_mask[:, :mask_length_diff] elif mask_length_diff > 0: new_mask = cross_mask[:, -1:, :].repeat(1, mask_length_diff, 1) model_kwargs["image_attention_mask"] = torch.cat([cross_mask, new_mask], dim=1) return model_kwargs def _prepare_token_type_ids(model_kwargs: dict[str, Any], new_length: int) -> dict[str, Any]: """Expands or crops the model's token_type_ids for decoding purposes, to the defined length""" if "token_type_ids" not in model_kwargs or model_kwargs["token_type_ids"] is None: return model_kwargs token_type_ids = model_kwargs["token_type_ids"] final_token_type = token_type_ids[:, -1].unsqueeze(-1) type_length_diff = new_length - token_type_ids.shape[1] if type_length_diff < 0: token_type_ids = token_type_ids[:, :type_length_diff] elif type_length_diff > 0: token_type_copies = final_token_type.repeat(1, type_length_diff) model_kwargs["token_type_ids"] = torch.cat([model_kwargs["token_type_ids"], token_type_copies], dim=-1) return model_kwargs
EarlyExitCandidateGenerator
python
ray-project__ray
release/llm_tests/benchmark/locust.py
{ "start": 292, "end": 2882 }
class ____: """ Usage Example: ```python config = LoadTestConfig( host="http://localhost:8000", provider="vllm", model="meta-llama/Meta-Llama-3.1-8B-Instruct", api_key="NONE", prompt_tokens=550, max_tokens=150, users=128, run_time="1m", summary_file="./vllm.csv" ) tester = LLMLoadTester(config) results = tester.run() ``` """ def __init__(self, config: LoadTestConfig): self.config = config def _setup_environment(self) -> Environment: setup_logging("INFO", None) # Setup Environment and Runner env = Environment( user_classes=[LLMUser], host=self.config.host, reset_stats=self.config.reset_stats, events=events, ) env.parsed_options = self.config.to_namespace() return env def run(self) -> Dict[str, Any]: try: # Setup environment env = self._setup_environment() env.create_local_runner() # Log test start logging.info(f"Starting test with {self.config.users} users") # Create greenlets for stats stats_printer_greenlet = gevent.spawn(stats_printer(env.stats)) stats_history_greenlet = gevent.spawn(stats_history, env.runner) # Start the test env.runner.start( user_count=self.config.users, spawn_rate=self.config.users, ) # Run for specified duration gevent.sleep(self._parse_time(self.config.run_time)) # Stop the test env.runner.quit() entries = collect_metrics(env) # Wait for greenlets env.runner.greenlet.join() stats_printer_greenlet.kill() stats_history_greenlet.kill() # Print final stats print_stats(env.stats) return entries except Exception as e: logging.error(f"Test failed: {str(e)}") raise @staticmethod def _parse_time(time_str: str) -> int: """Convert time string (e.g., '30s', '1m', '1h') to seconds""" unit = time_str[-1] value = int(time_str[:-1]) if unit == "s": return value elif unit == "m": return value * 60 elif unit == "h": return value * 3600 else: raise ValueError(f"Invalid time unit: {unit}")
LLMLoadTester
python
numpy__numpy
numpy/ma/tests/test_core.py
{ "start": 99528, "end": 104604 }
class ____: # Test class for the application of ufuncs on MaskedArrays. def _create_data(self): # Base data definition. return (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6), array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),) @pytest.fixture(autouse=True, scope="class") def err_status(self): err = np.geterr() np.seterr(divide='ignore', invalid='ignore') yield err np.seterr(**err) def test_testUfuncRegression(self): # Tests new ufuncs on MaskedArrays. for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh', 'absolute', 'fabs', 'negative', 'floor', 'ceil', 'logical_not', 'add', 'subtract', 'multiply', 'divide', 'true_divide', 'floor_divide', 'remainder', 'fmod', 'hypot', 'arctan2', 'equal', 'not_equal', 'less_equal', 'greater_equal', 'less', 'greater', 'logical_and', 'logical_or', 'logical_xor', ]: try: uf = getattr(umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(numpy.ma.core, f) args = self._create_data()[:uf.nin] ur = uf(*args) mr = mf(*args) assert_equal(ur.filled(0), mr.filled(0), f) assert_mask_equal(ur.mask, mr.mask, err_msg=f) def test_reduce(self): # Tests reduce on MaskedArrays. a = self._create_data()[0] assert_(not alltrue(a, axis=0)) assert_(sometrue(a, axis=0)) assert_equal(sum(a[:3], axis=0), 0) assert_equal(product(a, axis=0), 0) assert_equal(add.reduce(a), pi) def test_minmax(self): # Tests extrema on MaskedArrays. a = arange(1, 13).reshape(3, 4) amask = masked_where(a < 5, a) assert_equal(amask.max(), a.max()) assert_equal(amask.min(), 5) assert_equal(amask.max(0), a.max(0)) assert_equal(amask.min(0), [5, 6, 7, 8]) assert_(amask.max(1)[0].mask) assert_(amask.min(1)[0].mask) def test_ndarray_mask(self): # Check that the mask of the result is a ndarray (not a MaskedArray...) a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1]) test = np.sqrt(a) control = masked_array([-1, 0, 1, np.sqrt(2), -1], mask=[1, 0, 0, 0, 1]) assert_equal(test, control) assert_equal(test.mask, control.mask) assert_(not isinstance(test.mask, MaskedArray)) def test_treatment_of_NotImplemented(self): # Check that NotImplemented is returned at appropriate places a = masked_array([1., 2.], mask=[1, 0]) assert_raises(TypeError, operator.mul, a, "abc") assert_raises(TypeError, operator.truediv, a, "abc") class MyClass: __array_priority__ = a.__array_priority__ + 1 def __mul__(self, other): return "My mul" def __rmul__(self, other): return "My rmul" me = MyClass() assert_(me * a == "My mul") assert_(a * me == "My rmul") # and that __array_priority__ is respected class MyClass2: __array_priority__ = 100 def __mul__(self, other): return "Me2mul" def __rmul__(self, other): return "Me2rmul" def __rtruediv__(self, other): return "Me2rdiv" me_too = MyClass2() assert_(a.__mul__(me_too) is NotImplemented) assert_(all(multiply.outer(a, me_too) == "Me2rmul")) assert_(a.__truediv__(me_too) is NotImplemented) assert_(me_too * a == "Me2mul") assert_(a * me_too == "Me2rmul") assert_(a / me_too == "Me2rdiv") def test_no_masked_nan_warnings(self): # check that a nan in masked position does not # cause ufunc warnings m = np.ma.array([0.5, np.nan], mask=[0, 1]) with warnings.catch_warnings(): warnings.filterwarnings("error") # test unary and binary ufuncs exp(m) add(m, 1) m > 0 # test different unary domains sqrt(m) log(m) tan(m) arcsin(m) arccos(m) arccosh(m) # test binary domains divide(m, 2) # also check that allclose uses ma ufuncs, to avoid warning allclose(m, 0.5) def test_masked_array_underflow(self): x = np.arange(0, 3, 0.1) X = np.ma.array(x) with np.errstate(under="raise"): X2 = X / 2.0 np.testing.assert_array_equal(X2, x / 2)
TestUfuncs
python
encode__django-rest-framework
tests/test_viewsets.py
{ "start": 1082, "end": 2457 }
class ____(GenericViewSet): queryset = Action.objects.all() def list(self, request, *args, **kwargs): response = Response() response.view = self return response def retrieve(self, request, *args, **kwargs): response = Response() response.view = self return response @action(detail=False) def list_action(self, request, *args, **kwargs): response = Response() response.view = self return response @action(detail=False, url_name='list-custom') def custom_list_action(self, request, *args, **kwargs): raise NotImplementedError @action(detail=True) def detail_action(self, request, *args, **kwargs): raise NotImplementedError @action(detail=True, url_name='detail-custom') def custom_detail_action(self, request, *args, **kwargs): raise NotImplementedError @action(detail=True, url_path=r'unresolvable/(?P<arg>\w+)', url_name='unresolvable') def unresolvable_detail_action(self, request, *args, **kwargs): raise NotImplementedError @action(detail=False) @decorate def wrapped_list_action(self, request, *args, **kwargs): raise NotImplementedError @action(detail=True) @decorate def wrapped_detail_action(self, request, *args, **kwargs): raise NotImplementedError
ActionViewSet
python
huggingface__transformers
src/transformers/models/glm4_moe/modular_glm4_moe.py
{ "start": 12890, "end": 13061 }
class ____(DeepseekV3ForCausalLM): pass __all__ = [ "Glm4MoeConfig", "Glm4MoePreTrainedModel", "Glm4MoeModel", "Glm4MoeForCausalLM", ]
Glm4MoeForCausalLM
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 191445, "end": 199215 }
class ____(NopKernel): """ There isn't actually a real kernel for concat, we just change the storage for the upstream data. """ @classmethod def create(cls, inputs: Sequence[IRNode], dim: int) -> StorageBox: """ Create the concat kernel from inputs """ device = inputs[0].get_device() dtype = inputs[0].get_dtype() new_size = list(inputs[0].get_size()) offsets_start = [0] offsets_end = [new_size[dim]] assert 0 <= dim < len(new_size) for i in range(1, len(inputs)): input_size = inputs[i].get_size() offsets_start.append(new_size[dim]) assert len(input_size) == len(new_size) assert inputs[i].get_dtype() == dtype assert inputs[i].get_device() == device for j in range(len(new_size)): if j == dim: new_size[j] = new_size[j] + input_size[j] else: new_size[j] = V.graph.sizevars.check_equals_and_simplify( new_size[j], input_size[j] ) offsets_end.append(new_size[dim]) output_stride: Sequence[int] = FlexibleLayout.contiguous_strides(new_size) if config.comprehensive_padding: # Ensure the output stride matches the alignment requirements output_stride = Layout._pad_strides( output_stride, new_size, inputs[0].dtype ) # If any of the inputs is in CL format, use CL format for the output for i in range(len(inputs)): x = inputs[i] if is_storage_and_layout(x): layout = x.get_layout() if isinstance( layout, FixedLayout ) and Layout.is_channels_last_contiguous(layout.size, layout.stride): # use CL stride for the output output_stride = make_channels_last_strides_for(new_size) break any_input_is_storage_and_layout = any(is_storage_and_layout(x) for x in inputs) fx_node_args = V.graph.current_node.args[0] assert isinstance(fx_node_args, list), type(fx_node_args) # If any of the inputs has meta tensor and the meta tensor is in CL format, use CL format for the output if any_input_is_storage_and_layout is False and any( "val" in arg.meta and ( arg.meta["val"].is_contiguous(memory_format=torch.channels_last) or arg.meta["val"].is_contiguous(memory_format=torch.channels_last_3d) ) for arg in fx_node_args ): output_stride = make_channels_last_strides_for(new_size) is_pinned = all( is_storage_and_layout(x) and x.get_layout().is_pinned for x in inputs ) assert device is not None concat_kernel = ConcatKernel( name=None, layout=FixedLayout( device=device, dtype=dtype, size=new_size, stride=output_stride, is_pinned=is_pinned, ), inputs=[], ) kernel = StorageBox(concat_kernel) op_names = [] for i, inp in enumerate(inputs): assert isinstance(inp, (BaseView, MutableBox)), type(inp) input_buffer = cls.realize_into( inp, SliceView.create( kernel, dim, offsets_start[i], offsets_end[i], clamp=False ), ) assert isinstance(input_buffer, Buffer), type(input_buffer) assert isinstance(concat_kernel.inputs, list), type(concat_kernel.inputs) concat_kernel.inputs.append(input_buffer) if isinstance(inp.data, BaseView): input_unwrapped = inp.data.unwrap_view() else: input_unwrapped = inp.data if ( isinstance(input_unwrapped, StorageBox) and input_unwrapped.is_input_buffer() and (dev := inp.get_device()) is not None and is_gpu(dev.type) and not is_dynamic(input_buffer) ): op_names.append(input_buffer.get_operation_name()) if len(op_names) > 1 and V.graph.has_feature(device, BackendFeature.FOREACH): V.graph.register_operation_list(op_names) concat_kernel.name = V.graph.register_buffer(concat_kernel) concat_kernel.inputs = cls.unwrap_storage(concat_kernel.inputs) V.graph.register_operation(concat_kernel) return kernel @classmethod def can_realize_into_without_copy( cls, src: IRNode, dst: Optional[IRNode] = None ) -> bool: if isinstance(src, TensorBox): # unwrap a TensorBox return cls.can_realize_into_without_copy(src.data, dst) assert isinstance(src, (BaseView, StorageBox)), type(src) if isinstance(src.data, MultiTemplateBuffer): if ( not isinstance(src.data.layout, FixedLayout) or not src.data.output_plannable ): return False # we call can_realize_into_without_copy in cat lowering before we've decided # on output format, optimistically assume layout matches if dst is None: return True # otherwise, check equality of layouts if len(src.get_stride()) != len(dst.get_stride()): return False return all( V.graph.sizevars.statically_known_equals(s1, s2) for s1, s2 in zip(src.get_stride(), dst.get_stride()) ) return ( hasattr(src.data, "layout") and isinstance(src.data.layout, FlexibleLayout) and not isinstance(src.data, ExternKernelAlloc) ) @cache_on_self_and_args("ConcatKernel") def get_free_symbol_uses( self, unbacked_only: bool = False ) -> OrderedSet[sympy.Symbol]: return NopKernel.get_free_symbol_uses(self, unbacked_only) @classmethod def realize_into(cls, src: IRNode, dst: IRNode) -> IRNode: # Attempt to turn this into a ReinterpretView rather than assert. # This has concessions around layout, as as_storage_and_layout # can cause us to go from flexible to fixed layout. if not isinstance(dst, ReinterpretView): if is_storage_and_layout(dst): storage, layout = as_storage_and_layout(dst) dst = ReinterpretView(data=storage, layout=layout) assert isinstance(dst, ReinterpretView), type(dst) if isinstance(src, TensorBox): # unwrap a TensorBox return cls.realize_into(src.data, dst) if isinstance(src, StorageBox): src.realize() # ExternKernelAlloc has specific requirements for output layout, should create a copy assert hasattr(src.data, "layout") if cls.can_realize_into_without_copy(src, dst): # pyrefly: ignore [missing-attribute] src.data.layout = NonOwningLayout(dst) return src.data # introduce a copy pw = Pointwise.create( device=src.get_device(), dtype=src.get_dtype(), inner_fn=src.make_loader(), ranges=[ V.graph.sizevars.check_equals_and_simplify(a, b) for a, b in zip(src.get_size(), dst.get_size()) ], ) return cls.realize_into(pw, dst) def should_allocate(self) -> bool: return True @ir_dataclass(frozen=False)
ConcatKernel
python
pytorch__pytorch
torch/ao/quantization/quantizer/x86_inductor_quantizer.py
{ "start": 13443, "end": 14503 }
class ____: r"""Configuration defining the current quantization mode for the quantizer. All possible current quantization modes are listed below: ---------------------------------------------------------------------------------------------------------- | dynamic_state qat_state |--------------------------------------------------------------------------------------------- | None | True | False ---------------------------------------------------------------------------------------------------------- None | quantizer does not receive a non-None `quantization_config` | \ | \ False | quantizer will not do QAT | dynamic | static True | quantizer will do QAT | QAT + dynamic | QAT + static """ qat_state: bool | None dynamic_state: bool | None
_CurrentQuantizationMode
python
pyca__cryptography
src/cryptography/hazmat/primitives/padding.py
{ "start": 1018, "end": 1435 }
class ____: def __init__(self, block_size: int): _byte_padding_check(block_size) self.block_size = block_size def padder(self) -> PaddingContext: return PKCS7PaddingContext(self.block_size) def unpadder(self) -> PaddingContext: return PKCS7UnpaddingContext(self.block_size) PaddingContext.register(PKCS7PaddingContext) PaddingContext.register(PKCS7UnpaddingContext)
PKCS7
python
sympy__sympy
sympy/utilities/autowrap.py
{ "start": 17636, "end": 29225 }
class ____(CodeWrapper): """Wrapper that uses f2py""" def __init__(self, *args, **kwargs): ext_keys = ['include_dirs', 'library_dirs', 'libraries', 'extra_compile_args', 'extra_link_args'] msg = ('The compilation option kwarg {} is not supported with the f2py ' 'backend.') for k in ext_keys: if k in kwargs.keys(): warn(msg.format(k)) kwargs.pop(k, None) super().__init__(*args, **kwargs) @property def command(self): filename = self.filename + '.' + self.generator.code_extension args = ['-c', '-m', self.module_name, filename] command = [sys.executable, "-c", "import numpy.f2py as f2py2e;f2py2e.main()"]+args return command def _prepare_files(self, routine): pass @classmethod def _get_wrapped_function(cls, mod, name): return getattr(mod, name) # Here we define a lookup of backends -> tuples of languages. For now, each # tuple is of length 1, but if a backend supports more than one language, # the most preferable language is listed first. _lang_lookup = {'CYTHON': ('C99', 'C89', 'C'), 'F2PY': ('F95',), 'NUMPY': ('C99', 'C89', 'C'), 'DUMMY': ('F95',)} # Dummy here just for testing def _infer_language(backend): """For a given backend, return the top choice of language""" langs = _lang_lookup.get(backend.upper(), False) if not langs: raise ValueError("Unrecognized backend: " + backend) return langs[0] def _validate_backend_language(backend, language): """Throws error if backend and language are incompatible""" langs = _lang_lookup.get(backend.upper(), False) if not langs: raise ValueError("Unrecognized backend: " + backend) if language.upper() not in langs: raise ValueError(("Backend {} and language {} are " "incompatible").format(backend, language)) @cacheit @doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',)) def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None, flags=None, verbose=False, helpers=None, code_gen=None, **kwargs): """Generates Python callable binaries based on the math expression. Parameters ========== expr The SymPy expression that should be wrapped as a binary routine. language : string, optional If supplied, (options: 'C' or 'F95'), specifies the language of the generated code. If ``None`` [default], the language is inferred based upon the specified backend. backend : string, optional Backend used to wrap the generated code. Either 'f2py' [default], or 'cython'. tempdir : string, optional Path to directory for temporary files. If this argument is supplied, the generated code and the wrapper input files are left intact in the specified path. args : iterable, optional An ordered iterable of symbols. Specifies the argument sequence for the function. flags : iterable, optional Additional option flags that will be passed to the backend. verbose : bool, optional If True, autowrap will not mute the command line backends. This can be helpful for debugging. helpers : 3-tuple or iterable of 3-tuples, optional Used to define auxiliary functions needed for the main expression. Each tuple should be of the form (name, expr, args) where: - name : str, the function name - expr : sympy expression, the function - args : iterable, the function arguments (can be any iterable of symbols) code_gen : CodeGen instance An instance of a CodeGen subclass. Overrides ``language``. include_dirs : [string] A list of directories to search for C/C++ header files (in Unix form for portability). library_dirs : [string] A list of directories to search for C/C++ libraries at link time. libraries : [string] A list of library names (not filenames or paths) to link against. extra_compile_args : [string] Any extra platform- and compiler-specific information to use when compiling the source files in 'sources'. For platforms and compilers where "command line" makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything. extra_link_args : [string] Any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for 'extra_compile_args'. Examples ======== Basic usage: >>> from sympy.abc import x, y, z >>> from sympy.utilities.autowrap import autowrap >>> expr = ((x - y + z)**(13)).expand() >>> binary_func = autowrap(expr) >>> binary_func(1, 4, 2) -1.0 Using helper functions: >>> from sympy.abc import x, t >>> from sympy import Function >>> helper_func = Function('helper_func') # Define symbolic function >>> expr = 3*x + helper_func(t) # Main expression using helper function >>> # Define helper_func(x) = 4*x using f2py backend >>> binary_func = autowrap(expr, args=[x, t], ... helpers=('helper_func', 4*x, [x])) >>> binary_func(2, 5) # 3*2 + helper_func(5) = 6 + 20 26.0 >>> # Same example using cython backend >>> binary_func = autowrap(expr, args=[x, t], backend='cython', ... helpers=[('helper_func', 4*x, [x])]) >>> binary_func(2, 5) # 3*2 + helper_func(5) = 6 + 20 26.0 Type handling example: >>> import numpy as np >>> expr = x + y >>> f_cython = autowrap(expr, backend='cython') >>> f_cython(1, 2) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int) >>> f_cython(np.array([1.0]), np.array([2.0])) array([ 3.]) """ if language: if not isinstance(language, type): _validate_backend_language(backend, language) else: language = _infer_language(backend) # two cases 1) helpers is an iterable of 3-tuples and 2) helpers is a # 3-tuple if iterable(helpers) and len(helpers) != 0 and iterable(helpers[0]): helpers = helpers if helpers else () else: helpers = [helpers] if helpers else () args = list(args) if iterable(args, exclude=set) else args if code_gen is None: code_gen = get_code_generator(language, "autowrap") CodeWrapperClass = { 'F2PY': F2PyCodeWrapper, 'CYTHON': CythonCodeWrapper, 'DUMMY': DummyWrapper }[backend.upper()] code_wrapper = CodeWrapperClass(code_gen, tempdir, flags if flags else (), verbose, **kwargs) helps = [] for name_h, expr_h, args_h in helpers: helps.append(code_gen.routine(name_h, expr_h, args_h)) for name_h, expr_h, args_h in helpers: if expr.has(expr_h): name_h = binary_function(name_h, expr_h, backend='dummy') expr = expr.subs(expr_h, name_h(*args_h)) try: routine = code_gen.routine('autofunc', expr, args) except CodeGenArgumentListError as e: # if all missing arguments are for pure output, we simply attach them # at the end and try again, because the wrappers will silently convert # them to return values anyway. new_args = [] for missing in e.missing_args: if not isinstance(missing, OutputArgument): raise new_args.append(missing.name) routine = code_gen.routine('autofunc', expr, args + new_args) return code_wrapper.wrap_code(routine, helpers=helps) @doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',)) def binary_function(symfunc, expr, **kwargs): """Returns a SymPy function with expr as binary implementation This is a convenience function that automates the steps needed to autowrap the SymPy expression and attaching it to a Function object with implemented_function(). Parameters ========== symfunc : SymPy Function The function to bind the callable to. expr : SymPy Expression The expression used to generate the function. kwargs : dict Any kwargs accepted by autowrap. Examples ======== >>> from sympy.abc import x, y >>> from sympy.utilities.autowrap import binary_function >>> expr = ((x - y)**(25)).expand() >>> f = binary_function('f', expr) >>> type(f) <class 'sympy.core.function.UndefinedFunction'> >>> 2*f(x, y) 2*f(x, y) >>> f(x, y).evalf(2, subs={x: 1, y: 2}) -1.0 """ binary = autowrap(expr, **kwargs) return implemented_function(symfunc, binary) ################################################################# # UFUNCIFY # ################################################################# _ufunc_top = Template("""\ #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" #include ${include_file} static PyMethodDef ${module}Methods[] = { {NULL, NULL, 0, NULL} };""") _ufunc_outcalls = Template("*((double *)out${outnum}) = ${funcname}(${call_args});") _ufunc_body = Template("""\ #ifdef NPY_1_19_API_VERSION static void ${funcname}_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data) #else static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) #endif { npy_intp i; npy_intp n = dimensions[0]; ${declare_args} ${declare_steps} for (i = 0; i < n; i++) { ${outcalls} ${step_increments} } } PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc}; static char ${funcname}_types[${n_types}] = ${types} static void *${funcname}_data[1] = {NULL};""") _ufunc_bottom = Template("""\ #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "${module}", NULL, -1, ${module}Methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_${module}(void) { PyObject *m, *d; ${function_creation} m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); d = PyModule_GetDict(m); ${ufunc_init} return m; } #else PyMODINIT_FUNC init${module}(void) { PyObject *m, *d; ${function_creation} m = Py_InitModule("${module}", ${module}Methods); if (m == NULL) { return; } import_array(); import_umath(); d = PyModule_GetDict(m); ${ufunc_init} } #endif\ """) _ufunc_init_form = Template("""\ ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out}, PyUFunc_None, "${module}", ${docstring}, 0); PyDict_SetItemString(d, "${funcname}", ufunc${ind}); Py_DECREF(ufunc${ind});""") _ufunc_setup = Template("""\ from setuptools.extension import Extension from setuptools import setup from numpy import get_include if __name__ == "__main__": setup(ext_modules=[ Extension('${module}', sources=['${module}.c', '${filename}.c'], include_dirs=[get_include()])]) """)
F2PyCodeWrapper
python
huggingface__transformers
src/transformers/models/modernbert/modular_modernbert.py
{ "start": 1963, "end": 16965 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`ModernBertModel`]. It is used to instantiate an ModernBert model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the ModernBERT-base. e.g. [answerdotai/ModernBERT-base](https://huggingface.co/answerdotai/ModernBERT-base) Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 50368): Vocabulary size of the ModernBert model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`ModernBertModel`] hidden_size (`int`, *optional*, defaults to 768): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 1152): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 22): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer decoder. hidden_activation (`str` or `function`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the decoder. Will default to `"gelu"` if not specified. max_position_embeddings (`int`, *optional*, defaults to 8192): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. initializer_cutoff_factor (`float`, *optional*, defaults to 2.0): The cutoff factor for the truncated_normal_initializer for initializing all weight matrices. norm_eps (`float`, *optional*, defaults to 1e-05): The epsilon used by the rms normalization layers. norm_bias (`bool`, *optional*, defaults to `False`): Whether to use bias in the normalization layers. pad_token_id (`int`, *optional*, defaults to 50283): Padding token id. eos_token_id (`int`, *optional*, defaults to 50282): End of stream token id. bos_token_id (`int`, *optional*, defaults to 50281): Beginning of stream token id. cls_token_id (`int`, *optional*, defaults to 50281): Classification token id. sep_token_id (`int`, *optional*, defaults to 50282): Separation token id. attention_bias (`bool`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. layer_types (`list`, *optional*): Attention pattern for each layer. rope_parameters (`RopeParameters`, *optional*): Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`. local_attention (`int`, *optional*, defaults to 128): The window size for local attention. embedding_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the embeddings. mlp_bias (`bool`, *optional*, defaults to `False`): Whether to use bias in the MLP layers. mlp_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the MLP layers. decoder_bias (`bool`, *optional*, defaults to `True`): Whether to use bias in the decoder layers. classifier_pooling (`str`, *optional*, defaults to `"cls"`): The pooling method for the classifier. Should be either `"cls"` or `"mean"`. In local attention layers, the CLS token doesn't attend to all tokens on long sequences. classifier_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the classifier. classifier_bias (`bool`, *optional*, defaults to `False`): Whether to use bias in the classifier. classifier_activation (`str`, *optional*, defaults to `"gelu"`): The activation function for the classifier. deterministic_flash_attn (`bool`, *optional*, defaults to `False`): Whether to use deterministic flash attention. If `False`, inference will be faster but not deterministic. sparse_prediction (`bool`, *optional*, defaults to `False`): Whether to use sparse prediction for the masked language model instead of returning the full dense logits. sparse_pred_ignore_index (`int`, *optional*, defaults to -100): The index to ignore for the sparse prediction. reference_compile (`bool`, *optional*): Whether to compile the layers of the model which were compiled during pretraining. If `None`, then parts of the model will be compiled if 1) `triton` is installed, 2) the model is not on MPS, 3) the model is not shared between devices, and 4) the model is not resized after initialization. If `True`, then the model may be faster in some scenarios. repad_logits_with_grad (`bool`, *optional*, defaults to `False`): When True, ModernBertForMaskedLM keeps track of the logits' gradient when repadding for output. This only applies when using Flash Attention 2 with passed labels. Otherwise output logits always have a gradient. Examples: ```python >>> from transformers import ModernBertModel, ModernBertConfig >>> # Initializing a ModernBert style configuration >>> configuration = ModernBertConfig() >>> # Initializing a model from the modernbert-base style configuration >>> model = ModernBertModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "modernbert" keys_to_ignore_at_inference = ["past_key_values"] default_theta = {"global": 160_000.0, "local": 10_000.0} def __init__( self, vocab_size: Optional[int] = 50368, hidden_size: Optional[int] = 768, intermediate_size: Optional[int] = 1152, num_hidden_layers: Optional[int] = 22, num_attention_heads: Optional[int] = 12, hidden_activation: Optional[str] = "gelu", max_position_embeddings: Optional[int] = 8192, initializer_range: Optional[float] = 0.02, initializer_cutoff_factor: Optional[float] = 2.0, norm_eps: Optional[int] = 1e-5, norm_bias: Optional[bool] = False, pad_token_id: Optional[int] = 50283, eos_token_id: Optional[int] = 50282, bos_token_id: Optional[int] = 50281, cls_token_id: Optional[int] = 50281, sep_token_id: Optional[int] = 50282, attention_bias: Optional[bool] = False, attention_dropout: Optional[float] = 0.0, layer_types: Optional[list[str]] = None, rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None, local_attention: Optional[int] = 128, embedding_dropout: Optional[float] = 0.0, mlp_bias: Optional[bool] = False, mlp_dropout: Optional[float] = 0.0, decoder_bias: Optional[bool] = True, classifier_pooling: Literal["cls", "mean"] = "cls", classifier_dropout: Optional[float] = 0.0, classifier_bias: Optional[bool] = False, classifier_activation: Optional[str] = "gelu", deterministic_flash_attn: Optional[bool] = False, sparse_prediction: Optional[bool] = False, sparse_pred_ignore_index: Optional[int] = -100, reference_compile: Optional[bool] = None, repad_logits_with_grad: Optional[bool] = False, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.initializer_range = initializer_range self.initializer_cutoff_factor = initializer_cutoff_factor self.norm_eps = norm_eps self.norm_bias = norm_bias self.attention_bias = attention_bias self.attention_dropout = attention_dropout self.hidden_activation = hidden_activation self.local_attention = local_attention self.embedding_dropout = embedding_dropout self.mlp_bias = mlp_bias self.mlp_dropout = mlp_dropout self.decoder_bias = decoder_bias self.classifier_pooling = classifier_pooling self.classifier_dropout = classifier_dropout self.classifier_bias = classifier_bias self.classifier_activation = classifier_activation self.deterministic_flash_attn = deterministic_flash_attn self.sparse_prediction = sparse_prediction self.sparse_pred_ignore_index = sparse_pred_ignore_index self.reference_compile = reference_compile self.repad_logits_with_grad = repad_logits_with_grad if self.classifier_pooling not in ["cls", "mean"]: raise ValueError( f'Invalid value for `classifier_pooling`, should be either "cls" or "mean", but is {self.classifier_pooling}.' ) self.layer_types = layer_types # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub self.global_attn_every_n_layers = kwargs.get("global_attn_every_n_layers", 3) if self.layer_types is None: self.layer_types = [ "sliding_attention" if bool(i % self.global_attn_every_n_layers) else "full_attention" for i in range(self.num_hidden_layers) ] layer_type_validation(self.layer_types, self.num_hidden_layers) self.rope_parameters = rope_parameters super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, cls_token_id=cls_token_id, sep_token_id=sep_token_id, **kwargs, ) def convert_rope_params_to_dict(self, ignore_keys_at_rope_validation=None, **kwargs): rope_scaling = kwargs.pop("rope_scaling", None) # Try to set `rope_scaling` if available, otherwise use `rope_parameters`. If we find `rope_parameters` # as arg in the inputs, we can safely assume that it is in the new format. New naming used -> new format default_rope_params = { "sliding_attention": {"rope_type": "default"}, "full_attention": {"rope_type": "default"}, } self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else default_rope_params if rope_scaling is not None: self.rope_parameters["full_attention"].update(rope_scaling) self.rope_parameters["sliding_attention"].update(rope_scaling) self.rope_parameters["full_attention"].setdefault( "rope_theta", kwargs.pop("global_rope_theta", self.default_theta["global"]) ) self.rope_parameters["sliding_attention"].setdefault( "rope_theta", kwargs.pop("local_rope_theta", self.default_theta["local"]) ) # Standardize and validate the correctness of rotary position embeddings parameters self.standardize_rope_params() self.validate_rope(ignore_keys=ignore_keys_at_rope_validation) return kwargs def to_dict(self): output = super().to_dict() output.pop("reference_compile", None) return output def _unpad_modernbert_input( inputs: torch.Tensor, attention_mask: torch.Tensor, position_ids: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, Optional[torch.Tensor], Optional[torch.Tensor]]: """ Remove padding from input sequences. Args: inputs: (batch, seqlen, ...) or (batch, seqlen) attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. position_ids: (batch, seqlen), int, position ids labels: (batch, seqlen), int, labels Returns: unpadded_inputs: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask. indices: (total_nnz) cu_seqlens: (batch + 1), the cumulative sequence lengths max_seqlen_in_batch: int unpadded_position_ids: (total_nnz) or None unpadded_labels: (total_nnz) or None """ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = int(seqlens_in_batch.max().item()) cu_seqlens = torch.nn.functional.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) if inputs.dim() == 2: unpadded_inputs = inputs.flatten()[indices] else: batch, seqlen, *rest = inputs.shape shape = batch * seqlen unpadded_inputs = inputs.view(shape, *rest)[indices] unpadded_position_ids = position_ids.flatten()[indices] if position_ids is not None else None unpadded_labels = labels.flatten()[indices] if labels is not None else None return unpadded_inputs, indices, cu_seqlens, max_seqlen_in_batch, unpadded_position_ids, unpadded_labels def _pad_modernbert_output( inputs: torch.Tensor, indices: torch.Tensor, batch: int, seqlen: int, ) -> torch.Tensor: """ Add padding to sequences. Args: inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask. indices: (total_nnz) batch: int, batch size seqlen: int, max sequence length Returns: padded_inputs: (batch, seqlen, ...) or (batch, seqlen) """ if inputs.dim() == 1: output = torch.zeros(batch * seqlen, dtype=inputs.dtype, device=inputs.device) output[indices] = inputs padded_inputs = output.view(batch, seqlen) else: _, *rest = inputs.shape output = torch.zeros(batch * seqlen, *rest, dtype=inputs.dtype, device=inputs.device) output[indices] = inputs padded_inputs = output.view(batch, seqlen, *rest) return padded_inputs
ModernBertConfig
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 23806, "end": 23907 }
class ____(DagsterError): """Error raised by invalid metadata parameters."""
DagsterInvalidMetadata
python
getsentry__sentry
src/sentry/integrations/analytics.py
{ "start": 1643, "end": 1809 }
class ____(analytics.Event): provider: str | None id: int organization_id: int @analytics.eventclass("integration.resolve.pr")
IntegrationResolveCommitEvent
python
joke2k__faker
faker/providers/automotive/ar_SA/__init__.py
{ "start": 59, "end": 2274 }
class ____(AutomotiveProvider): """Implement automotive provider for ``ar_SA`` locale. Sources: - https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Saudi_Arabia .. |license_plate_en| replace:: :meth:`license_plate_en()` """ LICENSE_FORMAT_EN = "#### ???" LICENSE_FORMAT_AR = "? ? ? ####" PLATE_CHARS_EN = "ABDEGHJKLNRSTUVXZ" PLATE_CHARS_AR = "أبدعقهحكلنرسطوىصم" PLATE_MAP = { "A": "ا", "B": "ب", "D": "د", "E": "ع", "G": "ق", "H": "ه", "J": "ح", "K": "ك", "L": "ل", "N": "ن", "R": "ر", "S": "س", "T": "ط", "U": "و", "V": "ى", "X": "ص", "Z": "م", "0": "٠", "1": "١", "2": "٢", "3": "٣", "4": "٤", "5": "٥", "6": "٦", "7": "٧", "8": "٨", "9": "٩", } def license_plate_en(self) -> str: """Generate a license plate in Latin/Western characters.""" return self.bothify( self.LICENSE_FORMAT_EN, letters=self.PLATE_CHARS_EN, ) def license_plate_ar(self) -> str: """Generate a license plate in Arabic characters. This method first generates a license plate in Latin/Western characters using |license_plate_en|, and the result is translated internally to generate the Arabic counterpart which serves as this method's return value. """ english_plate = self.license_plate_en() return self._translate_license_plate(english_plate) def _translate_license_plate(self, license_plate: str) -> str: nums = list(reversed(license_plate[0:4])) chars = list(license_plate[5:8]) numerated = re.sub( r"\#", lambda x: self.PLATE_MAP[nums.pop()], self.LICENSE_FORMAT_AR, ) ar_plate = re.sub( r"\?", lambda x: self.PLATE_MAP[chars.pop()], numerated, ) return ar_plate def license_plate(self, ar: bool = True) -> str: return self.license_plate_ar() if ar else self.license_plate_en()
Provider
python
openai__openai-python
src/openai/types/beta/realtime/realtime_response_usage.py
{ "start": 800, "end": 1541 }
class ____(BaseModel): input_token_details: Optional[InputTokenDetails] = None """Details about the input tokens used in the Response.""" input_tokens: Optional[int] = None """ The number of input tokens used in the Response, including text and audio tokens. """ output_token_details: Optional[OutputTokenDetails] = None """Details about the output tokens used in the Response.""" output_tokens: Optional[int] = None """ The number of output tokens sent in the Response, including text and audio tokens. """ total_tokens: Optional[int] = None """ The total number of tokens in the Response including input and output text and audio tokens. """
RealtimeResponseUsage
python
kamyu104__LeetCode-Solutions
Python/longest-subsequence-with-decreasing-adjacent-difference.py
{ "start": 684, "end": 1248 }
class ____(object): def longestSubsequence(self, nums): """ :type nums: List[int] :rtype: int """ result = 2 mx = max(nums) dp = [[0]*mx for _ in xrange(mx)] for x in reversed(nums): x -= 1 for nx in xrange(len(dp[x])): d = abs(nx-x) dp[x][d] = max(dp[x][d], dp[nx][d]+1) for d in xrange(1, len(dp[x])): dp[x][d] = max(dp[x][d], dp[x][d-1]) result = max(result, dp[x][-1]) return result
Solution2
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF012.py
{ "start": 1035, "end": 1295 }
class ____(Struct): mutable_default: list[int] = [] immutable_annotation: Sequence[int] = [] without_annotation = [] class_variable: ClassVar[list[int]] = [] final_variable: Final[list[int]] = [] from pydantic_settings import BaseSettings
E
python
astropy__astropy
astropy/io/ascii/core.py
{ "start": 6488, "end": 6771 }
class ____(ImportError): """ Indicates that a dependency for table reading is not present. An instance of this class is raised whenever an optional reader with certain required dependencies cannot operate because of an ImportError. """
OptionalTableImportError
python
donnemartin__interactive-coding-challenges
stacks_queues/stack_min/test_stack_min.py
{ "start": 18, "end": 1244 }
class ____(unittest.TestCase): def test_stack_min(self): print('Test: Push on empty stack, non-empty stack') stack = StackMin() stack.push(5) self.assertEqual(stack.peek(), 5) self.assertEqual(stack.minimum(), 5) stack.push(1) self.assertEqual(stack.peek(), 1) self.assertEqual(stack.minimum(), 1) stack.push(3) self.assertEqual(stack.peek(), 3) self.assertEqual(stack.minimum(), 1) stack.push(0) self.assertEqual(stack.peek(), 0) self.assertEqual(stack.minimum(), 0) print('Test: Pop on non-empty stack') self.assertEqual(stack.pop(), 0) self.assertEqual(stack.minimum(), 1) self.assertEqual(stack.pop(), 3) self.assertEqual(stack.minimum(), 1) self.assertEqual(stack.pop(), 1) self.assertEqual(stack.minimum(), 5) self.assertEqual(stack.pop(), 5) self.assertEqual(stack.minimum(), sys.maxsize) print('Test: Pop empty stack') self.assertEqual(stack.pop(), None) print('Success: test_stack_min') def main(): test = TestStackMin() test.test_stack_min() if __name__ == '__main__': main()
TestStackMin
python
pennersr__django-allauth
tests/apps/socialaccount/providers/trainingpeaks/tests.py
{ "start": 560, "end": 2955 }
class ____(OAuth2TestsMixin, TestCase): provider_id = TrainingPeaksProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """{ "Id": 123456, "FirstName": "John", "LastName": "Doe", "Email": "user@example.com", "DateOfBirth": "1986-02-01T00:00:00", "CoachedBy": 987654, "Weight": 87.5223617553711 }""", ) # noqa def get_expected_to_str(self): return "user@example.com" def get_login_response_json(self, with_refresh_token=True): rtoken = "" if with_refresh_token: rtoken = ',"refresh_token": "testrf"' return ( """{ "access_token" : "testac", "token_type" : "bearer", "expires_in" : 600, "scope": "scopes granted" %s }""" % rtoken ) def test_default_use_sandbox_uri(self): adapter = TrainingPeaksOAuth2Adapter(None) self.assertTrue(".sandbox." in adapter.authorize_url) self.assertTrue(".sandbox." in adapter.access_token_url) self.assertTrue(".sandbox." in adapter.profile_url) @override_settings( SOCIALACCOUNT_PROVIDERS={"trainingpeaks": {"USE_PRODUCTION": True}} ) def test_use_production_uri(self): adapter = TrainingPeaksOAuth2Adapter(None) self.assertFalse(".sandbox." in adapter.authorize_url) self.assertFalse(".sandbox." in adapter.access_token_url) self.assertFalse(".sandbox." in adapter.profile_url) def test_scope_from_default(self): Request = namedtuple("request", ["GET"]) mock_request = Request(GET={}) scope = self.provider.get_scope_from_request(mock_request) self.assertTrue("athlete:profile" in scope) @override_settings( SOCIALACCOUNT_PROVIDERS={ "trainingpeaks": {"SCOPE": ["athlete:profile", "workouts", "workouts:wod"]} } ) def test_scope_from_settings(self): Request = namedtuple("request", ["GET"]) mock_request = Request(GET={}) scope = self.provider.get_scope_from_request(mock_request) for item in ("athlete:profile", "workouts", "workouts:wod"): self.assertTrue(item in scope)
TrainingPeaksTests
python
getsentry__sentry
src/sentry/incidents/utils/types.py
{ "start": 387, "end": 665 }
class ____: """ values has format: { "value": float, "source_id": str, "subscription_id": str, "timestamp": datetime, } """ entity: str subscription_id: str values: Any timestamp: datetime
AnomalyDetectionUpdate
python
google__pytype
pytype/tools/traces/source.py
{ "start": 243, "end": 626 }
class ____: """Base class for traces.""" op: str symbol: Any types: tuple[pytd.Node, ...] def __new__(cls, op, symbol, types): del op, symbol, types # unused if cls is AbstractTrace: raise TypeError("cannot instantiate AbstractTrace") return super().__new__(cls) def __repr__(self): return f"{self.op} : {self.symbol} <- {self.types}"
AbstractTrace
python
jazzband__django-oauth-toolkit
tests/test_token_endpoint_cors.py
{ "start": 713, "end": 6197 }
class ____(TestCase): """ Test that CORS headers can be managed by OAuthLib. The objective is: http request 'Origin' header should be passed to OAuthLib """ factory = RequestFactory() @classmethod def setUpTestData(cls): cls.test_user = UserModel.objects.create_user("test_user", "test@example.com", "123456") cls.dev_user = UserModel.objects.create_user("dev_user", "dev@example.com", "123456") cls.application = Application.objects.create( name="Test Application", redirect_uris=CLIENT_URI, user=cls.dev_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, client_secret=CLEARTEXT_SECRET, allowed_origins=CLIENT_URI, ) def setUp(self): self.oauth2_settings.ALLOWED_REDIRECT_URI_SCHEMES = ["https"] self.oauth2_settings.PKCE_REQUIRED = False def test_valid_origin_with_https(self): """ Test that /token endpoint has Access-Control-Allow-Origin """ authorization_code = self._get_authorization_code() # exchange authorization code for a valid access token token_request_data = { "grant_type": "authorization_code", "code": authorization_code, "redirect_uri": CLIENT_URI, } auth_headers = get_basic_auth_header(self.application.client_id, CLEARTEXT_SECRET) auth_headers["HTTP_ORIGIN"] = CLIENT_URI response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers) content = json.loads(response.content.decode("utf-8")) self.assertEqual(response.status_code, 200) self.assertEqual(response["Access-Control-Allow-Origin"], CLIENT_URI) token_request_data = { "grant_type": "refresh_token", "refresh_token": content["refresh_token"], "scope": content["scope"], } response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers) self.assertEqual(response.status_code, 200) self.assertEqual(response["Access-Control-Allow-Origin"], CLIENT_URI) def test_valid_origin_no_https(self): """ Test that CORS is not allowed if origin uri does not have https:// schema """ authorization_code = self._get_authorization_code() # exchange authorization code for a valid access token token_request_data = { "grant_type": "authorization_code", "code": authorization_code, "redirect_uri": CLIENT_URI, } auth_headers = get_basic_auth_header(self.application.client_id, CLEARTEXT_SECRET) auth_headers["HTTP_ORIGIN"] = CLIENT_URI_HTTP response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers) self.assertEqual(response.status_code, 200) self.assertFalse(response.has_header("Access-Control-Allow-Origin")) def test_origin_not_from_allowed_origins(self): """ Test that /token endpoint does not have Access-Control-Allow-Origin when request origin is not in Application.allowed_origins """ authorization_code = self._get_authorization_code() # exchange authorization code for a valid access token token_request_data = { "grant_type": "authorization_code", "code": authorization_code, "redirect_uri": CLIENT_URI, } auth_headers = get_basic_auth_header(self.application.client_id, CLEARTEXT_SECRET) auth_headers["HTTP_ORIGIN"] = "https://another_example.org" response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers) self.assertEqual(response.status_code, 200) self.assertFalse(response.has_header("Access-Control-Allow-Origin")) def test_no_origin(self): """ Test that /token endpoint does not have Access-Control-Allow-Origin """ authorization_code = self._get_authorization_code() # exchange authorization code for a valid access token token_request_data = { "grant_type": "authorization_code", "code": authorization_code, "redirect_uri": CLIENT_URI, } auth_headers = get_basic_auth_header(self.application.client_id, CLEARTEXT_SECRET) response = self.client.post(reverse("oauth2_provider:token"), data=token_request_data, **auth_headers) self.assertEqual(response.status_code, 200) # No CORS headers, because request did not have Origin self.assertFalse(response.has_header("Access-Control-Allow-Origin")) def _get_authorization_code(self): self.client.login(username="test_user", password="123456") # retrieve a valid authorization code authcode_data = { "client_id": self.application.client_id, "state": "random_state_string", "scope": "read write", "redirect_uri": "https://example.org", "response_type": "code", "allow": True, } response = self.client.post(reverse("oauth2_provider:authorize"), data=authcode_data) query_dict = parse_qs(urlparse(response["Location"]).query) return query_dict["code"].pop()
TestTokenEndpointCors
python
mlflow__mlflow
mlflow/tracing/utils/__init__.py
{ "start": 2057, "end": 22755 }
class ____(json.JSONEncoder): """ Custom JSON encoder for serializing non-OpenTelemetry compatible objects in a trace or span. Trace may contain types that require custom serialization logic, such as Pydantic models, non-JSON-serializable types, etc. """ def default(self, obj): try: import pydantic if isinstance(obj, pydantic.BaseModel): return obj.model_dump() except ImportError: pass # Some dataclass object defines __str__ method that doesn't return the full object # representation, so we use dict representation instead. # E.g. https://github.com/run-llama/llama_index/blob/29ece9b058f6b9a1cf29bc723ed4aa3a39879ad5/llama-index-core/llama_index/core/chat_engine/types.py#L63-L64 if is_dataclass(obj): try: return asdict(obj) except TypeError: pass # Some object has dangerous side effect in __str__ method, so we use class name instead. if not self._is_safe_to_encode_str(obj): return type(obj) try: return super().default(obj) except TypeError: return str(obj) def _is_safe_to_encode_str(self, obj) -> bool: """Check if it's safe to encode the object as a string.""" try: # These Llama Index objects are not safe to encode as string, because their __str__ # method consumes the stream and make it unusable. # E.g. https://github.com/run-llama/llama_index/blob/54f2da61ba8a573284ab8336f2b2810d948c3877/llama-index-core/llama_index/core/base/response/schema.py#L120-L127 from llama_index.core.base.response.schema import ( AsyncStreamingResponse, StreamingResponse, ) from llama_index.core.chat_engine.types import StreamingAgentChatResponse if isinstance( obj, (AsyncStreamingResponse, StreamingResponse, StreamingAgentChatResponse), ): return False except ImportError: pass return True def dump_span_attribute_value(value: Any) -> str: # NB: OpenTelemetry attribute can store not only string but also a few primitives like # int, float, bool, and list of them. However, we serialize all into JSON string here # for the simplicity in deserialization process. return json.dumps(value, cls=TraceJSONEncoder, ensure_ascii=False) @lru_cache(maxsize=1) def encode_span_id(span_id: int) -> str: """ Encode the given integer span ID to a 16-byte hex string. # https://github.com/open-telemetry/opentelemetry-python/blob/9398f26ecad09e02ad044859334cd4c75299c3cd/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py#L507-L508 # NB: We don't add '0x' prefix to the hex string here for simpler parsing in backend. # Some backend (e.g. Databricks) disallow this prefix. """ return trace_api.format_span_id(span_id) @lru_cache(maxsize=1) def encode_trace_id(trace_id: int) -> str: """ Encode the given integer trace ID to a 32-byte hex string. """ return trace_api.format_trace_id(trace_id) def decode_id(span_or_trace_id: str) -> int: """ Decode the given hex string span or trace ID to an integer. """ return int(span_or_trace_id, 16) def get_mlflow_span_for_otel_span(span: OTelSpan) -> LiveSpan | None: """ Get the active MLflow span for the given OpenTelemetry span. """ from mlflow.tracing.trace_manager import InMemoryTraceManager trace_id = get_otel_attribute(span, SpanAttributeKey.REQUEST_ID) mlflow_span_id = encode_span_id(span.get_span_context().span_id) return InMemoryTraceManager.get_instance().get_span_from_id(trace_id, mlflow_span_id) def build_otel_context(trace_id: int, span_id: int) -> trace_api.SpanContext: """ Build an OpenTelemetry SpanContext object from the given trace and span IDs. """ return trace_api.SpanContext( trace_id=trace_id, span_id=span_id, # NB: This flag is OpenTelemetry's concept to indicate whether the context is # propagated from remote parent or not. We don't support distributed tracing # yet so always set it to False. is_remote=False, ) def aggregate_usage_from_spans(spans: list[LiveSpan]) -> dict[str, int] | None: """Aggregate token usage information from all spans in the trace.""" input_tokens = 0 output_tokens = 0 total_tokens = 0 has_usage_data = False span_id_to_spans = {span.span_id: span for span in spans} children_map: defaultdict[str, list[LiveSpan]] = defaultdict(list) roots: list[LiveSpan] = [] for span in spans: parent_id = span.parent_id if parent_id and parent_id in span_id_to_spans: children_map[parent_id].append(span) else: roots.append(span) def dfs(span: LiveSpan, ancestor_has_usage: bool) -> None: nonlocal input_tokens, output_tokens, total_tokens, has_usage_data usage = span.get_attribute(SpanAttributeKey.CHAT_USAGE) span_has_usage = usage is not None if span_has_usage and not ancestor_has_usage: input_tokens += usage.get(TokenUsageKey.INPUT_TOKENS, 0) output_tokens += usage.get(TokenUsageKey.OUTPUT_TOKENS, 0) total_tokens += usage.get(TokenUsageKey.TOTAL_TOKENS, 0) has_usage_data = True next_ancestor_has_usage = ancestor_has_usage or span_has_usage for child in children_map.get(span.span_id, []): dfs(child, next_ancestor_has_usage) for root in roots: dfs(root, False) # If none of the spans have token usage data, we shouldn't log token usage metadata. if not has_usage_data: return None return { TokenUsageKey.INPUT_TOKENS: input_tokens, TokenUsageKey.OUTPUT_TOKENS: output_tokens, TokenUsageKey.TOTAL_TOKENS: total_tokens, } def get_otel_attribute(span: trace_api.Span, key: str) -> str | None: """ Get the attribute value from the OpenTelemetry span in a decoded format. Args: span: The OpenTelemetry span object. key: The key of the attribute to retrieve. Returns: The attribute value as decoded string. If the attribute is not found or cannot be parsed, return None. """ try: attribute_value = span.attributes.get(key) if attribute_value is None: return None return json.loads(attribute_value) except Exception: _logger.debug(f"Failed to get attribute {key} with from span {span}.", exc_info=True) def _try_get_prediction_context(): # NB: Tracing is enabled in mlflow-skinny, but the pyfunc module cannot be imported as it # relies on numpy, which is not installed in skinny. try: from mlflow.pyfunc.context import get_prediction_context except (ImportError, KeyError): return return get_prediction_context() def maybe_get_request_id(is_evaluate=False) -> str | None: """Get the request ID if the current prediction is as a part of MLflow model evaluation.""" context = _try_get_prediction_context() if not context or (is_evaluate and not context.is_evaluate): return None if not context.request_id and is_evaluate: _logger.warning( f"Missing request_id for context {context}. request_id can't be None when " "is_evaluate=True. This is likely an internal error of MLflow, please file " "a bug report at https://github.com/mlflow/mlflow/issues." ) return None return context.request_id def maybe_get_dependencies_schemas() -> dict[str, Any] | None: if context := _try_get_prediction_context(): return context.dependencies_schemas def maybe_get_logged_model_id() -> str | None: """ Get the logged model ID associated with the current prediction context. """ if context := _try_get_prediction_context(): return context.model_id def exclude_immutable_tags(tags: dict[str, str]) -> dict[str, str]: """Exclude immutable tags e.g. "mlflow.user" from the given tags.""" return {k: v for k, v in tags.items() if k not in IMMUTABLE_TAGS} def generate_mlflow_trace_id_from_otel_trace_id(otel_trace_id: int) -> str: """ Generate an MLflow trace ID from an OpenTelemetry trace ID. Args: otel_trace_id: The OpenTelemetry trace ID as an integer. Returns: The MLflow trace ID string in format "tr-<hex_trace_id>". """ return TRACE_REQUEST_ID_PREFIX + encode_trace_id(otel_trace_id) def generate_trace_id_v4_from_otel_trace_id(otel_trace_id: int, location: str) -> str: """ Generate a trace ID in v4 format from the given OpenTelemetry trace ID. Args: otel_trace_id: The OpenTelemetry trace ID as an integer. location: The location, of the trace. Returns: The MLflow trace ID string in format "trace:/<location>/<hex_trace_id>". """ return construct_trace_id_v4(location, encode_trace_id(otel_trace_id)) def generate_trace_id_v4(span: OTelSpan, location: str) -> str: """ Generate a trace ID for the given span. Args: span: The OpenTelemetry span object. location: The location, of the trace. Returns: Trace ID with format "trace:/<location>/<hex_trace_id>". """ return generate_trace_id_v4_from_otel_trace_id(span.context.trace_id, location) def generate_trace_id_v3(span: OTelSpan) -> str: """ Generate a trace ID for the given span (V3 trace schema). The format will be "tr-<trace_id>" where the trace_id is hex-encoded Otel trace ID. """ return generate_mlflow_trace_id_from_otel_trace_id(span.context.trace_id) def generate_request_id_v2() -> str: """ Generate a request ID for the given span. This should only be used for V2 trace schema where we use a random UUID as request ID. In the V3 schema, "request_id" is renamed to "trace_id" and we use the otel-generated trace ID with encoding. """ return uuid.uuid4().hex def construct_full_inputs(func, *args, **kwargs) -> dict[str, Any]: """ Construct the full input arguments dictionary for the given function, including positional and keyword arguments. """ signature = inspect.signature(func) # this does not create copy. So values should not be mutated directly arguments = signature.bind_partial(*args, **kwargs).arguments if "self" in arguments: arguments.pop("self") return arguments @contextmanager def maybe_set_prediction_context(context: "Context" | None): """ Set the prediction context if the given context is not None. Otherwise no-op. """ if not IS_TRACING_SDK_ONLY and context: from mlflow.pyfunc.context import set_prediction_context with set_prediction_context(context): yield else: yield def set_span_chat_tools(span: LiveSpan, tools: list[ChatTool]): """ Set the `mlflow.chat.tools` attribute on the specified span. This attribute is used in the UI, and also by downstream applications that consume trace data, such as MLflow evaluate. Args: span: The LiveSpan to add the attribute to tools: A list of standardized chat tool definitions (refer to the `spec <../llms/tracing/tracing-schema.html#chat-completion-spans>`_ for details) Example: .. code-block:: python :test: import mlflow from mlflow.tracing import set_span_chat_tools tools = [ { "type": "function", "function": { "name": "add", "description": "Add two numbers", "parameters": { "type": "object", "properties": { "a": {"type": "number"}, "b": {"type": "number"}, }, "required": ["a", "b"], }, }, } ] @mlflow.trace def f(): span = mlflow.get_current_active_span() set_span_chat_tools(span, tools) return 0 f() """ from mlflow.types.chat import ChatTool if not isinstance(tools, list): raise MlflowTracingException( f"Invalid tools type {type(tools)}. Expected a list of ChatTool.", error_code=BAD_REQUEST, ) sanitized_tools = [] for tool in tools: if isinstance(tool, dict): ChatTool.model_validate(tool) sanitized_tools.append(tool) elif isinstance(tool, ChatTool): sanitized_tools.append(tool.model_dump(exclude_unset=True)) span.set_attribute(SpanAttributeKey.CHAT_TOOLS, sanitized_tools) def _calculate_percentile(sorted_data: list[float], percentile: float) -> float: """ Calculate the percentile value from sorted data. Args: sorted_data: A sorted list of numeric values percentile: The percentile to calculate (e.g., 0.25 for 25th percentile) Returns: The percentile value """ if not sorted_data: return 0.0 n = len(sorted_data) index = percentile * (n - 1) lower = int(index) upper = lower + 1 if upper >= n: return sorted_data[-1] # Linear interpolation between two nearest values weight = index - lower return sorted_data[lower] * (1 - weight) + sorted_data[upper] * weight def add_size_stats_to_trace_metadata(trace: Trace): """ Calculate the stats of trace and span sizes and add it as a metadata to the trace. This method modifies the trace object in place by adding a new tag. Note: For simplicity, we calculate the size without considering the size metadata itself. This provides a close approximation without requiring complex calculations. This function must not throw an exception. """ from mlflow.entities import Trace, TraceData try: span_sizes = [] for span in trace.data.spans: span_json = json.dumps(span.to_dict(), cls=TraceJSONEncoder) span_sizes.append(len(span_json.encode("utf-8"))) # NB: To compute the size of the total trace, we need to include the size of the # the trace info and the parent dicts for the spans. To avoid serializing spans # again (which can be expensive), we compute the size of the trace without spans # and combine it with the total size of the spans. empty_trace = Trace(info=trace.info, data=TraceData(spans=[])) metadata_size = len((empty_trace.to_json()).encode("utf-8")) # NB: the third term is the size of comma separators between spans (", "). trace_size_bytes = sum(span_sizes) + metadata_size + (len(span_sizes) - 1) * 2 # Sort span sizes for percentile calculation sorted_span_sizes = sorted(span_sizes) size_stats = { TraceSizeStatsKey.TOTAL_SIZE_BYTES: trace_size_bytes, TraceSizeStatsKey.NUM_SPANS: len(span_sizes), TraceSizeStatsKey.MAX_SPAN_SIZE_BYTES: max(span_sizes), TraceSizeStatsKey.P25_SPAN_SIZE_BYTES: int( _calculate_percentile(sorted_span_sizes, 0.25) ), TraceSizeStatsKey.P50_SPAN_SIZE_BYTES: int( _calculate_percentile(sorted_span_sizes, 0.50) ), TraceSizeStatsKey.P75_SPAN_SIZE_BYTES: int( _calculate_percentile(sorted_span_sizes, 0.75) ), } trace.info.trace_metadata[TraceMetadataKey.SIZE_STATS] = json.dumps(size_stats) # Keep the total size as a separate metadata for backward compatibility trace.info.trace_metadata[TraceMetadataKey.SIZE_BYTES] = str(trace_size_bytes) except Exception: _logger.warning("Failed to add size stats to trace metadata.", exc_info=True) def update_trace_state_from_span_conditionally(trace, root_span): """ Update trace state from span status, but only if the user hasn't explicitly set a different trace status. This utility preserves user-set trace status while maintaining default behavior for traces that haven't been explicitly configured. Used by trace processors when converting traces to an exportable state. Args: trace: The trace object to potentially update root_span: The root span whose status may be used to update the trace state """ from mlflow.entities.trace_state import TraceState # Only update trace state from span status if trace is still IN_PROGRESS # If the trace state is anything else, it means the user explicitly set it # and we should preserve it if trace.info.state == TraceState.IN_PROGRESS: trace.info.state = TraceState.from_otel_status(root_span.status) def get_experiment_id_for_trace(span: OTelReadableSpan) -> str: """ Determine the experiment ID to associate with the trace. The experiment ID can be configured in multiple ways, in order of precedence: 1. An experiment ID specified via the span creation API i.e. MlflowClient().start_trace() 2. An experiment ID specified via `mlflow.tracing.set_destination` 3. An experiment ID of an active run. 4. The default experiment ID Args: span: The OpenTelemetry ReadableSpan to extract experiment ID from. Returns: The experiment ID string to use for the trace. """ from mlflow.tracing.provider import _MLFLOW_TRACE_USER_DESTINATION from mlflow.tracking.fluent import _get_experiment_id, _get_latest_active_run if experiment_id := get_otel_attribute(span, SpanAttributeKey.EXPERIMENT_ID): return experiment_id if destination := _MLFLOW_TRACE_USER_DESTINATION.get(): if exp_id := getattr(destination, "experiment_id", None): return exp_id if run := _get_latest_active_run(): return run.info.experiment_id return _get_experiment_id() def get_active_spans_table_name() -> str | None: """ Get active Unity Catalog spans table name that's set by `mlflow.tracing.set_destination`. """ from mlflow.entities.trace_location import UCSchemaLocation from mlflow.tracing.provider import _MLFLOW_TRACE_USER_DESTINATION if destination := _MLFLOW_TRACE_USER_DESTINATION.get(): if isinstance(destination, UCSchemaLocation): return destination.full_otel_spans_table_name return None def generate_assessment_id() -> str: """ Generates an assessment ID of the form 'a-<uuid4>' in hex string format. Returns: A unique identifier for an assessment that will be logged to a trace tag. """ id = uuid.uuid4().hex return f"{ASSESSMENT_ID_PREFIX}{id}" @contextmanager def _bypass_attribute_guard(span: OTelSpan) -> Generator[None, None, None]: """ OpenTelemetry does not allow setting attributes if the span has end time defined. https://github.com/open-telemetry/opentelemetry-python/blob/d327927d0274a320466feec6fba6d6ddb287dc5a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py#L849-L851 However, we need to set some attributes within `on_end` handler of the span processor, where the span is already marked as ended. This context manager is a hacky workaround to bypass the attribute guard. """ original_end_time = span._end_time span._end_time = None try: yield finally: span._end_time = original_end_time def parse_trace_id_v4(trace_id: str | None) -> tuple[str | None, str | None]: """ Parse the trace ID into location and trace ID components. """ if trace_id is None: return None, None if trace_id.startswith(TRACE_ID_V4_PREFIX): match trace_id.removeprefix(TRACE_ID_V4_PREFIX).split("/"): case [location, tid] if location and tid: return location, tid case _: raise MlflowException.invalid_parameter_value( f"Invalid trace ID format: {trace_id}. " f"Expected format: {TRACE_ID_V4_PREFIX}<location>/<trace_id>" ) return None, trace_id def construct_trace_id_v4(location: str, trace_id: str) -> str: """ Construct a trace ID for the given location and trace ID. """ return f"{TRACE_ID_V4_PREFIX}{location}/{trace_id}"
TraceJSONEncoder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 20538, "end": 21059 }
class ____(sgqlc.types.Enum): """Properties by which Enterprise Server installation connections can be ordered. Enumeration Choices: * `CREATED_AT`: Order Enterprise Server installations by creation time * `CUSTOMER_NAME`: Order Enterprise Server installations by customer name * `HOST_NAME`: Order Enterprise Server installations by host name """ __schema__ = github_schema __choices__ = ("CREATED_AT", "CUSTOMER_NAME", "HOST_NAME")
EnterpriseServerInstallationOrderField
python
getsentry__sentry
tests/sentry/api/endpoints/test_project_alert_rule_task_details.py
{ "start": 379, "end": 3937 }
class ____(APITestCase): def setUp(self) -> None: self.login_as(user=self.user) team = self.create_team() project1 = self.create_project(teams=[team], name="foo", fire_project_created=True) self.create_project(teams=[team], name="bar", fire_project_created=True) self.rule = self.create_alert_rule( name="My Alert Rule", user=self.user, projects=[project1] ) self.uuid = uuid4().hex self.url = reverse( "sentry-api-0-project-alert-rule-task-details", kwargs={ "organization_id_or_slug": project1.organization.slug, "project_id_or_slug": project1.slug, "task_uuid": self.uuid, }, ) def set_value(self, status: str, rule_id: int | None = None) -> None: client = RedisRuleStatus(self.uuid) client.set_value(status, rule_id) def test_status_pending(self) -> None: self.login_as(user=self.user) self.set_value("pending") response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert response.data["status"] == "pending" assert response.data["alertRule"] is None def test_status_failed(self) -> None: self.login_as(user=self.user) self.set_value("failed", self.rule.id) response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert response.data["status"] == "failed" assert response.data["alertRule"] is None def test_status_success(self) -> None: self.set_value("success", self.rule.id) self.login_as(user=self.user) response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert response.data["status"] == "success" rule_data = response.data["alertRule"] assert rule_data["id"] == str(self.rule.id) assert rule_data["name"] == self.rule.name def test_workflow_engine_serializer(self) -> None: self.set_value("success", self.rule.id) self.login_as(user=self.user) self.critical_trigger = self.create_alert_rule_trigger( alert_rule=self.rule, label="critical" ) self.critical_trigger_action = self.create_alert_rule_trigger_action( alert_rule_trigger=self.critical_trigger ) _, _, _, self.detector, _, _, _, _ = migrate_alert_rule(self.rule) self.critical_detector_trigger, _, _ = migrate_metric_data_conditions(self.critical_trigger) self.critical_action, _, _ = migrate_metric_action(self.critical_trigger_action) self.resolve_trigger_data_condition = migrate_resolve_threshold_data_condition(self.rule) with self.feature("organizations:workflow-engine-rule-serializers"): response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert response.data["status"] == "success" rule_data = response.data["alertRule"] assert rule_data["id"] == str(self.rule.id) assert rule_data["name"] == self.rule.name def test_wrong_no_alert_rule(self) -> None: rule_id = self.rule.id self.set_value("success", rule_id) self.rule.delete() self.login_as(user=self.user) response = self.client.get(self.url, format="json") assert response.status_code == 404
ProjectAlertRuleTaskDetailsTest
python
sympy__sympy
sympy/codegen/ast.py
{ "start": 5419, "end": 11601 }
class ____(CodegenAST): """ Base class for the AST types. Explanation =========== Defining fields are set in ``_fields``. Attributes (defined in _fields) are only allowed to contain instances of Basic (unless atomic, see ``String``). The arguments to ``__new__()`` correspond to the attributes in the order defined in ``_fields`. The ``defaults`` class attribute is a dictionary mapping attribute names to their default values. Subclasses should not need to override the ``__new__()`` method. They may define a class or static method named ``_construct_<attr>`` for each attribute to process the value passed to ``__new__()``. Attributes listed in the class attribute ``not_in_args`` are not passed to :class:`~.Basic`. """ __slots__: tuple[str, ...] = () _fields = __slots__ defaults: dict[str, Any] = {} not_in_args: list[str] = [] indented_args = ['body'] @property def is_Atom(self): return len(self._fields) == 0 @classmethod def _get_constructor(cls, attr): """ Get the constructor function for an attribute by name. """ return getattr(cls, '_construct_%s' % attr, lambda x: x) @classmethod def _construct(cls, attr, arg): """ Construct an attribute value from argument passed to ``__new__()``. """ # arg may be ``NoneToken()``, so comparison is done using == instead of ``is`` operator if arg == None: return cls.defaults.get(attr, none) else: if isinstance(arg, Dummy): # SymPy's replace uses Dummy instances return arg else: return cls._get_constructor(attr)(arg) def __new__(cls, *args, **kwargs): # Pass through existing instances when given as sole argument if len(args) == 1 and not kwargs and isinstance(args[0], cls): return args[0] if len(args) > len(cls._fields): raise ValueError("Too many arguments (%d), expected at most %d" % (len(args), len(cls._fields))) attrvals = [] # Process positional arguments for attrname, argval in zip(cls._fields, args): if attrname in kwargs: raise TypeError('Got multiple values for attribute %r' % attrname) attrvals.append(cls._construct(attrname, argval)) # Process keyword arguments for attrname in cls._fields[len(args):]: if attrname in kwargs: argval = kwargs.pop(attrname) elif attrname in cls.defaults: argval = cls.defaults[attrname] else: raise TypeError('No value for %r given and attribute has no default' % attrname) attrvals.append(cls._construct(attrname, argval)) if kwargs: raise ValueError("Unknown keyword arguments: %s" % ' '.join(kwargs)) # Parent constructor basic_args = [ val for attr, val in zip(cls._fields, attrvals) if attr not in cls.not_in_args ] obj = CodegenAST.__new__(cls, *basic_args) # Set attributes for attr, arg in zip(cls._fields, attrvals): setattr(obj, attr, arg) return obj def __eq__(self, other): if not isinstance(other, self.__class__): return False for attr in self._fields: if getattr(self, attr) != getattr(other, attr): return False return True def _hashable_content(self): return tuple([getattr(self, attr) for attr in self._fields]) def __hash__(self): return super().__hash__() def _joiner(self, k, indent_level): return (',\n' + ' '*indent_level) if k in self.indented_args else ', ' def _indented(self, printer, k, v, *args, **kwargs): il = printer._context['indent_level'] def _print(arg): if isinstance(arg, Token): return printer._print(arg, *args, joiner=self._joiner(k, il), **kwargs) else: return printer._print(arg, *args, **kwargs) if isinstance(v, Tuple): joined = self._joiner(k, il).join([_print(arg) for arg in v.args]) if k in self.indented_args: return '(\n' + ' '*il + joined + ',\n' + ' '*(il - 4) + ')' else: return ('({0},)' if len(v.args) == 1 else '({0})').format(joined) else: return _print(v) def _sympyrepr(self, printer, *args, joiner=', ', **kwargs): from sympy.printing.printer import printer_context exclude = kwargs.get('exclude', ()) values = [getattr(self, k) for k in self._fields] indent_level = printer._context.get('indent_level', 0) arg_reprs = [] for i, (attr, value) in enumerate(zip(self._fields, values)): if attr in exclude: continue # Skip attributes which have the default value if attr in self.defaults and value == self.defaults[attr]: continue ilvl = indent_level + 4 if attr in self.indented_args else 0 with printer_context(printer, indent_level=ilvl): indented = self._indented(printer, attr, value, *args, **kwargs) arg_reprs.append(('{1}' if i == 0 else '{0}={1}').format(attr, indented.lstrip())) return "{}({})".format(self.__class__.__name__, joiner.join(arg_reprs)) _sympystr = _sympyrepr def __repr__(self): # sympy.core.Basic.__repr__ uses sstr from sympy.printing import srepr return srepr(self) def kwargs(self, exclude=(), apply=None): """ Get instance's attributes as dict of keyword arguments. Parameters ========== exclude : collection of str Collection of keywords to exclude. apply : callable, optional Function to apply to all values. """ kwargs = {k: getattr(self, k) for k in self._fields if k not in exclude} if apply is not None: return {k: apply(v) for k, v in kwargs.items()} else: return kwargs
Token
python
xlwings__xlwings
xlwings/constants.py
{ "start": 112554, "end": 112679 }
class ____: xlWithinSheet = 1 # from enum XlSearchWithin xlWithinWorkbook = 2 # from enum XlSearchWithin
SearchWithin
python
django__django
django/forms/widgets.py
{ "start": 12016, "end": 12122 }
class ____(Input): input_type = "email" template_name = "django/forms/widgets/email.html"
EmailInput
python
doocs__leetcode
solution/1000-1099/1060.Missing Element in Sorted Array/Solution.py
{ "start": 0, "end": 489 }
class ____: def missingElement(self, nums: List[int], k: int) -> int: def missing(i: int) -> int: return nums[i] - nums[0] - i n = len(nums) if k > missing(n - 1): return nums[n - 1] + k - missing(n - 1) l, r = 0, n - 1 while l < r: mid = (l + r) >> 1 if missing(mid) >= k: r = mid else: l = mid + 1 return nums[l - 1] + k - missing(l - 1)
Solution
python
mlflow__mlflow
mlflow/types/agent.py
{ "start": 2770, "end": 3645 }
class ____(BaseModel): """ Format of a ChatAgent interface request. Args: messages: A list of :py:class:`ChatAgentMessage` that will be passed to the model. context (:py:class:`ChatContext`): The context to be used in the chat endpoint. Includes conversation_id and user_id. **Optional** defaults to ``None`` custom_inputs (Dict[str, Any]): An optional param to provide arbitrary additional context to the model. The dictionary values must be JSON-serializable. **Optional** defaults to ``None`` stream (bool): Whether to stream back responses as they are generated. **Optional**, defaults to ``False`` """ messages: list[ChatAgentMessage] context: ChatContext | None = None custom_inputs: dict[str, Any] | None = None stream: bool | None = False
ChatAgentRequest
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 25695, "end": 26461 }
class ____(PipesLogWriter[T_LogChannel]): """Log writers which collects stdout and stderr of the current process should inherit from this class.""" @abstractmethod def make_channel( self, params: PipesParams, stream: Literal["stdout", "stderr"] ) -> T_LogChannel: pass @contextmanager def open(self, params: PipesParams) -> Iterator[None]: # pyright: ignore[reportIncompatibleMethodOverride] with ExitStack() as stack: stdout_channel = self.make_channel(params, stream="stdout") stderr_channel = self.make_channel(params, stream="stderr") stack.enter_context(stdout_channel.capture()) stack.enter_context(stderr_channel.capture()) yield
PipesStdioLogWriter
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/run.py
{ "start": 366, "end": 773 }
class ____(BaseModel): """Single run metadata model.""" id: str status: DgApiRunStatus created_at: float # Unix timestamp (seconds since epoch) started_at: Optional[float] = None # Unix timestamp (seconds since epoch) ended_at: Optional[float] = None # Unix timestamp (seconds since epoch) job_name: Optional[str] = None class Config: from_attributes = True
DgApiRun
python
PrefectHQ__prefect
src/prefect/server/schemas/graph.py
{ "start": 614, "end": 914 }
class ____(PrefectBaseModel): kind: Literal["flow-run", "task-run"] id: UUID label: str state_type: StateType start_time: DateTime end_time: Optional[DateTime] parents: List[Edge] children: List[Edge] encapsulating: List[Edge] artifacts: List[GraphArtifact]
Node
python
huggingface__transformers
src/transformers/models/t5gemma/modeling_t5gemma.py
{ "start": 32754, "end": 38123 }
class ____(T5GemmaPreTrainedModel): _can_record_outputs = { "attentions": OutputRecorder(T5GemmaSelfAttention, index=1), "cross_attentions": OutputRecorder(T5GemmaCrossAttention, index=1), "hidden_states": T5GemmaDecoderLayer, } def __init__(self, config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.norm = T5GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.gradient_checkpointing = False self.layers = nn.ModuleList( [T5GemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.dropout = nn.Dropout(config.dropout_rate) self.rotary_emb = T5GemmaRotaryEmbedding(config=config) # Initialize weights and apply final processing self.post_init() @check_model_inputs() def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[EncoderDecoderCache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPastAndCrossAttentions: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if encoder_hidden_states is None: raise ValueError("`encoder_hidden_states` must be given in decoder") if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if not self.training and use_cache and past_key_values is None: # We do not pass the config to the cross attn cache to avoid initializing SWA # --> we use full attention between our cross attentions past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache()) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) if attention_mask is None and past_key_values is None: attention_mask = make_default_2d_attention_mask(input_ids, inputs_embeds, self.config.pad_token_id) if not isinstance(self_attn_mask_mapping := attention_mask, dict): mask_kwargs = { "config": self.config, "input_embeds": inputs_embeds, "attention_mask": attention_mask, "cache_position": cache_position, "past_key_values": past_key_values.self_attention_cache if past_key_values is not None else None, "position_ids": position_ids, } self_attn_mask_mapping = { "full_attention": create_causal_mask(**mask_kwargs), "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs), } if not isinstance(cross_attn_mask_mapping := encoder_attention_mask, dict): mask_kwargs = { "config": self.config, "input_embeds": encoder_hidden_states, "attention_mask": encoder_attention_mask, "cache_position": cache_position, "past_key_values": None, "position_ids": None, } cross_attn_mask_mapping = { "full_attention": create_causal_mask( **mask_kwargs, or_mask_function=bidirectional_mask_function(encoder_attention_mask), ), } hidden_states = inputs_embeds normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype) hidden_states = hidden_states * normalizer hidden_states = self.dropout(hidden_states) position_embeddings = self.rotary_emb(hidden_states, position_ids) for layer_module in self.layers[: self.config.num_hidden_layers]: hidden_states = layer_module( hidden_states, position_embeddings, self_attn_mask_mapping[layer_module.attention_type], position_ids, past_key_values, use_cache, cache_position, encoder_hidden_states, cross_attn_mask_mapping["full_attention"], **kwargs, ) hidden_states = self.norm(hidden_states) hidden_states = self.dropout(hidden_states) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=past_key_values, ) @auto_docstring
T5GemmaDecoder
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0037_add_htmlfile.py
{ "start": 121, "end": 534 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0036_remove-auto-doctype"), ] operations = [ migrations.CreateModel( name="HTMLFile", fields=[], options={ "proxy": True, "indexes": [], }, bases=("projects.importedfile",), ), ]
Migration
python
jmcnamara__XlsxWriter
xlsxwriter/test/workbook/test_workbook01.py
{ "start": 343, "end": 1702 }
class ____(unittest.TestCase): """ Test assembling a complete Workbook file. """ def test_assemble_xml_file(self): """Test writing a workbook with 1 worksheet.""" self.maxDiff = None fh = StringIO() workbook = Workbook() workbook._set_filehandle(fh) workbook.add_worksheet() workbook._assemble_xml_file() workbook.fileclosed = 1 exp = _xml_to_list( """ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <fileVersion appName="xl" lastEdited="4" lowestEdited="4" rupBuild="4505"/> <workbookPr defaultThemeVersion="124226"/> <bookViews> <workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660"/> </bookViews> <sheets> <sheet name="Sheet1" sheetId="1" r:id="rId1"/> </sheets> <calcPr calcId="124519" fullCalcOnLoad="1"/> </workbook> """ ) got = _xml_to_list(fh.getvalue()) self.assertEqual(exp, got)
TestAssembleWorkbook
python
huggingface__transformers
src/transformers/models/mobilevitv2/modeling_mobilevitv2.py
{ "start": 30039, "end": 33703 }
class ____(MobileViTV2PreTrainedModel): def __init__(self, config: MobileViTV2Config) -> None: super().__init__(config) self.num_labels = config.num_labels self.mobilevitv2 = MobileViTV2Model(config, expand_output=False) self.segmentation_head = MobileViTV2DeepLabV3(config) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, pixel_values: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, SemanticSegmenterOutput]: r""" labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*): Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy). Examples: ```python >>> import requests >>> import torch >>> from PIL import Image >>> from transformers import AutoImageProcessor, MobileViTV2ForSemanticSegmentation >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256") >>> model = MobileViTV2ForSemanticSegmentation.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256") >>> inputs = image_processor(images=image, return_tensors="pt") >>> with torch.no_grad(): ... outputs = model(**inputs) >>> # logits are of shape (batch_size, num_labels, height, width) >>> logits = outputs.logits ```""" output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None and self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one") outputs = self.mobilevitv2( pixel_values, output_hidden_states=True, # we need the intermediate hidden states return_dict=return_dict, ) encoder_hidden_states = outputs.hidden_states if return_dict else outputs[1] logits = self.segmentation_head(encoder_hidden_states) loss = None if labels is not None: # upsample logits to the images' original size upsampled_logits = nn.functional.interpolate( logits, size=labels.shape[-2:], mode="bilinear", align_corners=False ) loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index) loss = loss_fct(upsampled_logits, labels) if not return_dict: if output_hidden_states: output = (logits,) + outputs[1:] else: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states if output_hidden_states else None, attentions=None, ) __all__ = [ "MobileViTV2ForImageClassification", "MobileViTV2ForSemanticSegmentation", "MobileViTV2Model", "MobileViTV2PreTrainedModel", ]
MobileViTV2ForSemanticSegmentation
python
getsentry__sentry
src/sentry/api/utils.py
{ "start": 2423, "end": 18839 }
class ____(APIException): status_code = HTTP_504_GATEWAY_TIMEOUT def get_datetime_from_stats_period( stats_period: str, now: datetime.datetime | None = None ) -> datetime.datetime: if now is None: now = timezone.now() parsed_stats_period = parse_stats_period(stats_period) if parsed_stats_period is None: raise InvalidParams(f"Invalid statsPeriod: {stats_period!r}") try: return now - parsed_stats_period except OverflowError: raise InvalidParams(f"Invalid statsPeriod: {stats_period!r}") def default_start_end_dates( now: datetime.datetime | None = None, default_stats_period: datetime.timedelta = MAX_STATS_PERIOD, ) -> tuple[datetime.datetime, datetime.datetime]: if now is None: now = timezone.now() return now - default_stats_period, now @overload def get_date_range_from_params( params: Mapping[str, Any], optional: Literal[False] = ..., default_stats_period: datetime.timedelta = ..., ) -> tuple[datetime.datetime, datetime.datetime]: ... @overload def get_date_range_from_params( params: Mapping[str, Any], optional: bool = ..., default_stats_period: datetime.timedelta = ..., ) -> tuple[None, None] | tuple[datetime.datetime, datetime.datetime]: ... def get_date_range_from_params( params: Mapping[str, Any], optional: bool = False, default_stats_period: datetime.timedelta = MAX_STATS_PERIOD, ) -> tuple[None, None] | tuple[datetime.datetime, datetime.datetime]: """ A wrapper function for `get_date_range_from_stats_period` that allows us to alias `statsPeriod` to ensure backward compatibility. If `timeframe` is passed then convert to a time delta and make sure it fits within our min/max period length. Values are in the format <number><period_type>, where period type is one of `s` (seconds), `m` (minutes), `h` (hours) or `d` (days). Similarly, `timeframeStart` and `timeframeEnd` allow for selecting a relative range, for example: 15 days ago through 8 days ago. This uses the same format as `statsPeriod`. :param params: If `start` end `end` are passed, validate them, convert to `datetime` and returns them if valid. :param optional: When True, if no params passed then return `(None, None)`. :param default_stats_period: When set, this becomes the interval upon which default start and end dates are defined :return: A length 2 tuple containing start/end or raises an `InvalidParams` exception """ mutable_params = { k: params[k] for k in ( *("timeframe", "timeframeStart", "timeframeEnd"), *("statsPeriod", "statsPeriodStart", "statsPeriodEnd"), *("start", "end"), ) if k in params } timeframe = mutable_params.get("timeframe") timeframe_start = mutable_params.get("timeframeStart") timeframe_end = mutable_params.get("timeframeEnd") if timeframe is not None: mutable_params["statsPeriod"] = timeframe elif timeframe_start or timeframe_end: if not all([timeframe_start, timeframe_end]): raise InvalidParams("timeframeStart and timeframeEnd are both required") else: mutable_params["statsPeriodStart"] = timeframe_start mutable_params["statsPeriodEnd"] = timeframe_end return get_date_range_from_stats_period( mutable_params, optional=optional, default_stats_period=default_stats_period ) @overload def get_date_range_from_stats_period( params: dict[str, Any], optional: Literal[False] = ..., default_stats_period: datetime.timedelta = ..., ) -> tuple[datetime.datetime, datetime.datetime]: ... @overload def get_date_range_from_stats_period( params: dict[str, Any], optional: bool = ..., default_stats_period: datetime.timedelta = ..., ) -> tuple[None, None] | tuple[datetime.datetime, datetime.datetime]: ... def get_date_range_from_stats_period( params: dict[str, Any], optional: bool = False, default_stats_period: datetime.timedelta = MAX_STATS_PERIOD, ) -> tuple[None, None] | tuple[datetime.datetime, datetime.datetime]: """ Gets a date range from standard date range params we pass to the api. If `statsPeriod` is passed then convert to a time delta and make sure it fits within our min/max period length. Values are in the format <number><period_type>, where period type is one of `s` (seconds), `m` (minutes), `h` (hours) or `d` (days). Similarly, `statsPeriodStart` and `statsPeriodEnd` allow for selecting a relative range, for example: 15 days ago through 8 days ago. This uses the same format as `statsPeriod` :param params: If `start` end `end` are passed, validate them, convert to `datetime` and returns them if valid. :param optional: When True, if no params passed then return `(None, None)`. :param default_stats_period: When set, this becomes the interval upon which default start and end dates are defined :return: A length 2 tuple containing start/end or raises an `InvalidParams` exception """ now = timezone.now() start, end = default_start_end_dates(now, default_stats_period) stats_period = params.get("statsPeriod") stats_period_start = params.get("statsPeriodStart") stats_period_end = params.get("statsPeriodEnd") if stats_period is not None: start = get_datetime_from_stats_period(stats_period, now) elif stats_period_start or stats_period_end: if not stats_period_start or not stats_period_end: raise InvalidParams("statsPeriodStart and statsPeriodEnd are both required") start = get_datetime_from_stats_period(stats_period_start, now) end = get_datetime_from_stats_period(stats_period_end, now) elif params.get("start") or params.get("end"): if not all([params.get("start"), params.get("end")]): raise InvalidParams("start and end are both required") try: start = parse_datetime_string(params["start"]) end = parse_datetime_string(params["end"]) except InvalidQuery as e: raise InvalidParams(str(e)) elif optional: return None, None if start >= end: raise InvalidParams("start must be before end") return start, end def clamp_date_range( range: tuple[datetime.datetime, datetime.datetime], max_timedelta: datetime.timedelta ) -> tuple[datetime.datetime, datetime.datetime]: """ Accepts a date range and a maximum time delta. If the date range is shorter than the max delta, returns the range as-is. If the date range is longer than the max delta, clamps the range range, anchoring to the end. If any of the inputs are invalid (e.g., a negative range) returns the range without modifying it. :param range: A tuple of two `datetime.datetime` objects :param max_timedelta: Maximum allowed range delta :return: A tuple of two `datetime.datetime` objects """ [start, end] = range delta = end - start # Ignore negative max time deltas if max_timedelta < datetime.timedelta(0): return (start, end) # Ignore if delta is within acceptable range if delta < max_timedelta: return (start, end) return (end - max_timedelta, end) # The wide typing allows us to move towards RpcUserOrganizationContext in the future to save RPC calls. # If you can use the wider more correct type, please do. def is_member_disabled_from_limit( request: HttpRequest, organization: RpcUserOrganizationContext | RpcOrganization | Organization | int, ) -> bool: user = request.user # never limit sentry apps if getattr(user, "is_sentry_app", False): return False # don't limit superuser or staff if is_active_superuser(request) or is_active_staff(request): return False # must be a simple user at this point member: RpcOrganizationMember | None if isinstance(organization, RpcUserOrganizationContext): member = organization.member else: member = organization_service.check_membership_by_id( organization_id=extract_id_from(organization), user_id=user.id ) if member is None: return False else: return member.flags.member_limit__restricted def generate_region_url(region_name: str | None = None) -> str: region_url_template: str | None = options.get("system.region-api-url-template") if region_name is None and SiloMode.get_current_mode() == SiloMode.REGION: region_name = get_local_region().name if ( region_name is None and SiloMode.get_current_mode() == SiloMode.MONOLITH and settings.SENTRY_REGION ): region_name = settings.SENTRY_REGION if not region_url_template or not region_name: return options.get("system.url-prefix") return region_url_template.replace("{region}", region_name) def print_and_capture_handler_exception( exception: Exception, handler_context: Mapping[str, Any] | None = None, scope: Scope | None = None, ) -> str | None: """ Logs the given exception locally, then sends it to Sentry, along with the given context data. Returns the id of the captured event. """ sys.stderr.write(traceback.format_exc()) scope = scope or Scope() if handler_context: merge_context_into_scope("Request Handler Data", handler_context, scope) event_id: str | None = capture_exception(exception, scope=scope) return event_id def get_auth_api_token_type(auth: object) -> str | None: if is_api_token_auth(auth): return "api_token" if is_org_auth_token_auth(auth): return "org_auth_token" if is_api_key_auth(auth): return "api_key" return None @contextmanager def handle_query_errors() -> Generator[None]: try: yield except InvalidSearchQuery as error: message = str(error) # Special case the project message since it has so many variants so tagging is messy otherwise if message.endswith("do not exist or are not actively selected."): sentry_sdk.set_tag( "query.error_reason", "Project in query does not exist or not selected" ) else: sentry_sdk.set_tag("query.error_reason", message) raise ParseError(detail=message) except ArithmeticError as error: message = str(error) sentry_sdk.set_tag("query.error_reason", message) raise ParseError(detail=message) except QueryOutsideRetentionError as error: sentry_sdk.set_tag("query.error_reason", "QueryOutsideRetentionError") raise ParseError(detail=str(error)) except QueryIllegalTypeOfArgument: message = "Invalid query. Argument to function is wrong type." sentry_sdk.set_tag("query.error_reason", message) raise ParseError(detail=message) except IncompatibleMetricsQuery as error: message = str(error) sentry_sdk.set_tag("query.error_reason", f"Metric Error: {message}") raise ParseError(detail=message) except SnubaRPCError as error: message = "Internal error. Please try again." arg = error.args[0] if len(error.args) > 0 else None if isinstance(arg, TimeoutError): sentry_sdk.set_tag("query.error_reason", "Timeout") raise TimeoutException(detail=TIMEOUT_RPC_ERROR_MESSAGE) sentry_sdk.capture_exception(error) if hasattr(error, "debug"): raise APIException( detail={ "detail": message, "meta": {"debug_info": {"query": json.loads(error.debug)}}, } ) raise APIException(detail=message) except SnubaError as error: message = "Internal error. Please try again." arg = error.args[0] if len(error.args) > 0 else None if isinstance(error, RateLimitExceeded): sentry_sdk.set_tag("query.error_reason", "RateLimitExceeded") sentry_sdk.capture_exception(error) raise Throttled(detail=RATE_LIMIT_ERROR_MESSAGE) if isinstance( error, ( QueryMemoryLimitExceeded, QueryExecutionTimeMaximum, QueryTooManySimultaneous, ), ) or isinstance( arg, ReadTimeoutError, ): sentry_sdk.set_tag("query.error_reason", "Timeout") raise TimeoutException(detail=TIMEOUT_ERROR_MESSAGE) elif isinstance(error, (UnqualifiedQueryError)): sentry_sdk.set_tag("query.error_reason", str(error)) raise ParseError(detail=str(error)) elif isinstance( error, ( DatasetSelectionError, QueryConnectionFailed, QueryExecutionError, QuerySizeExceeded, SchemaValidationError, QueryMissingColumn, ), ): sentry_sdk.capture_exception(error) message = "Internal error. Your query failed to run." elif isinstance( arg, (MaxRetryError), ): sentry_sdk.capture_message(str(error), level="warning") message = "Internal error. Your query failed to run. This may be temporary please try again later." else: sentry_sdk.capture_exception(error) raise APIException(detail=message) except OperationalError as error: error_message = str(error) is_timeout = "canceling statement due to statement timeout" in error_message if is_timeout: sentry_sdk.set_tag("query.error_reason", "Postgres statement timeout") sentry_sdk.capture_exception(error, level="warning") raise Throttled( detail="Query timeout. Please try with a smaller date range or fewer conditions." ) # Let other OperationalErrors propagate as normal raise def update_snuba_params_with_timestamp( request: HttpRequest, params: SnubaParams, timestamp_key: str = "timestamp", ) -> None: """In some views we only want to query snuba data around a single event or trace. In these cases the frontend can send the timestamp of something in that event or trace and we'll query data near that event only which should be faster than the default 7d or 14d queries""" # during the transition this is optional but it will become required for the trace view sentry_sdk.set_tag("trace_view.used_timestamp", timestamp_key in request.GET) has_dates = params.start is not None and params.end is not None if timestamp_key in request.GET and has_dates: example_timestamp = parse_datetime_string(request.GET[timestamp_key]) # While possible, the majority of traces shouldn't take more than a week # Starting with 3d for now, but potentially something we can increase if this becomes a problem time_buffer = options.get("performance.traces.transaction_query_timebuffer_days") set_span_attribute("trace_view.transactions.time_buffer", time_buffer) example_start = example_timestamp - timedelta(days=time_buffer) example_end = example_timestamp + timedelta(days=time_buffer) # If timestamp is being passed it should always overwrite the statsperiod or start & end # the client should just not pass a timestamp if we need to overwrite this logic for any reason params.start = max(params.start_date, example_start) params.end = min(params.end_date, example_end) retention = quotas.backend.get_event_retention(organization=params.organization) if retention and params.start < timezone.now() - timedelta(days=retention): raise InvalidSearchQuery( "Query dates our outside of retention, try again with a date within retention" ) def reformat_timestamp_ms_to_isoformat(timestamp_ms: str) -> Any: """ `timestamp_ms` arrives from Snuba in a slightly different format (no `T` and no timezone), so we convert to datetime and back to isoformat to keep it standardized with other timestamp fields """ return datetime.datetime.fromisoformat(timestamp_ms).astimezone().isoformat()
TimeoutException
python
pyqtgraph__pyqtgraph
pyqtgraph/dockarea/Container.py
{ "start": 143, "end": 3802 }
class ____(object): #sigStretchChanged = QtCore.Signal() ## can't do this here; not a QObject. def __init__(self, area): object.__init__(self) self.area = area self._container = None self._stretch = (10, 10) self.stretches = weakref.WeakKeyDictionary() def container(self): return self._container def containerChanged(self, c): self._container = c if c is None: self.area = None else: self.area = c.area def type(self): return None def insert(self, new, pos=None, neighbor=None): if not isinstance(new, list): new = [new] for n in new: # remove from existing parent first n.setParent(None) if neighbor is None: if pos == 'before': index = 0 else: index = self.count() else: index = self.indexOf(neighbor) if index == -1: index = 0 if pos == 'after': index += 1 for n in new: #print "insert", n, " -> ", self, index self._insertItem(n, index) #print "change container", n, " -> ", self n.containerChanged(self) index += 1 n.sigStretchChanged.connect(self.childStretchChanged) #print "child added", self self.updateStretch() def apoptose(self, propagate=True): # if there is only one (or zero) item in this container, disappear. # if propagate is True, then also attempt to apoptose parent containers. cont = self._container c = self.count() if c > 1: return if c == 1: ## if there is one item, give it to the parent container (unless this is the top) ch = self.widget(0) if (self.area is not None and self is self.area.topContainer and not isinstance(ch, Container)) or self.container() is None: return self.container().insert(ch, 'before', self) #print "apoptose:", self self.close() if propagate and cont is not None: cont.apoptose() def close(self): self.setParent(None) if self.area is not None and self.area.topContainer is self: self.area.topContainer = None self.containerChanged(None) def childEvent_(self, ev): # NOTE: this method has been renamed to avoid having the same method name as # QSplitter.childEvent() # this causes problems for PyQt6 since SplitContainer inherits from # Container and QSplitter. ch = ev.child() if ev.removed() and hasattr(ch, 'sigStretchChanged'): #print "Child", ev.child(), "removed, updating", self try: ch.sigStretchChanged.disconnect(self.childStretchChanged) except: pass self.updateStretch() @QtCore.Slot() def childStretchChanged(self): #print "child", QtCore.QObject.sender(self), "changed shape, updating", self self.updateStretch() def setStretch(self, x=None, y=None): #print "setStretch", self, x, y self._stretch = (x, y) self.sigStretchChanged.emit() def updateStretch(self): ###Set the stretch values for this container to reflect its contents pass def stretch(self): """Return the stretch factors for this container""" return self._stretch
Container
python
pennersr__django-allauth
allauth/headless/contrib/rest_framework/authentication.py
{ "start": 1125, "end": 1673 }
class ____(authentication.TokenAuthentication): @property def keyword(self) -> str: """ See: ``settings.HEADLESS_JWT_AUTHORIZATION_HEADER_SCHEME``. """ return app_settings.JWT_AUTHORIZATION_HEADER_SCHEME def authenticate_credentials(self, key: str): """ Validates the given access token. """ user_payload = validate_access_token(key) if user_payload is None: raise AuthenticationFailed("Invalid token.") return user_payload
JWTTokenAuthentication
python
spack__spack
lib/spack/spack/util/environment.py
{ "start": 14248, "end": 14754 }
class ____(NameModifier): def execute(self, env: MutableMapping[str, str]): tty.debug(f"DeprioritizeSystemPaths: {self.name}", level=3) environment_value = env.get(self.name, "") directories = environment_value.split(self.separator) if environment_value else [] directories = deprioritize_system_paths( [path_to_os_path(os.path.normpath(x)).pop() for x in directories] ) env[self.name] = self.separator.join(directories)
DeprioritizeSystemPaths
python
encode__django-rest-framework
tests/browsable_api/serializers.py
{ "start": 102, "end": 221 }
class ____(ModelSerializer): class Meta: model = BasicModelWithUsers fields = '__all__'
BasicSerializer
python
ansible__ansible
lib/ansible/module_utils/facts/packages.py
{ "start": 3957, "end": 4483 }
class ____(PkgMgr): CLI = None # type: str | None def __init__(self): self._cli = None super(CLIMgr, self).__init__() def is_available(self, handle_exceptions=True): found = False try: self._cli = get_bin_path(self.CLI) found = True except ValueError: if not handle_exceptions: raise return found def __getattr__(importable_name): return _no_six.deprecate(importable_name, __name__, "with_metaclass")
CLIMgr
python
ray-project__ray
python/ray/data/tests/test_iceberg.py
{ "start": 50097, "end": 52287 }
class ____: """Test various overwrite filter scenarios.""" @pytest.mark.parametrize( "filter_expr,overwrite_col_c,expected_data", [ # Filter matches nothing (behaves like append) ( col("col_c") == 999, [999, 999], { "col_a": [1, 2, 3, 4, 5], "col_b": ["row_1", "row_2", "row_3", "row_4", "row_5"], "col_c": [10, 20, 30, 999, 999], }, ), # Filter matches some rows ( col("col_c") >= 20, [200, 300], { "col_a": [1, 4, 5], "col_b": ["row_1", "row_4", "row_5"], "col_c": [10, 200, 300], }, ), # Filter matches all rows (full overwrite) ( col("col_c") < 100, [40, 50], { "col_a": [4, 5], "col_b": ["row_4", "row_5"], "col_c": [40, 50], }, ), ], ) def test_overwrite_filter_scenarios( self, clean_table, filter_expr, overwrite_col_c, expected_data ): """Test partial overwrite with different filter matching patterns.""" initial_data = _create_typed_dataframe( { "col_a": [1, 2, 3], "col_b": ["row_1", "row_2", "row_3"], "col_c": [10, 20, 30], } ) _write_to_iceberg(initial_data) overwrite_data = _create_typed_dataframe( {"col_a": [4, 5], "col_b": ["row_4", "row_5"], "col_c": overwrite_col_c} ) _write_to_iceberg( overwrite_data, mode=SaveMode.OVERWRITE, overwrite_filter=filter_expr ) result_df = _read_from_iceberg(sort_by="col_a") expected = _create_typed_dataframe(expected_data) assert rows_same(result_df, expected) @pytest.mark.skipif( get_pyarrow_version() < parse_version("14.0.0"), reason="PyIceberg 0.7.0 fails on pyarrow <= 14.0.0", )
TestOverwriteScenarios
python
django__django
tests/model_formsets/models.py
{ "start": 1611, "end": 1833 }
class ____(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) created = models.DateField(editable=False) def __str__(self): return self.name
AuthorMeeting
python
google__jax
tests/debugging_primitives_test.py
{ "start": 35738, "end": 37992 }
class ____(jtu.JaxTestCase): def test_inspect_sharding_is_called_in_jit_sharded(self): if jtu.is_cloud_tpu(): raise unittest.SkipTest("Inspect sharding is not supported on libtpu.") is_called = False def _cb(sd): nonlocal is_called is_called = True self.assertIsInstance(sd, jax.sharding.Sharding) self.assertLen(sd.device_set, len(jax.devices())) def f(x): debugging.inspect_array_sharding(x, callback=_cb) return jnp.square(x) mesh = jax.sharding.Mesh(np.array(jax.devices()), ['dev']) spec = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec('dev')) out_spec = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec()) f = jax.jit(f, in_shardings=spec, out_shardings=out_spec) with jax.set_mesh(mesh): f(np.arange(8, dtype=jnp.int32)) self.assertTrue(is_called) def test_inspect_sharding_is_called_in_jit(self): is_called = False def _cb(sd): nonlocal is_called is_called = True self.assertIsInstance(sd, jax.sharding.Sharding) self.assertLen(sd.device_set, 1) def f_(x): debugging.inspect_array_sharding(x, callback=_cb) return jnp.square(x) f = jax.jit(f_) f(np.arange(8, dtype=jnp.int32)) self.assertTrue(is_called) # Test in grad is_called = False f = jax.jit(jax.grad(lambda x: f_(x).sum())) f(np.arange(8, dtype=jnp.float32)) self.assertTrue(is_called) def test_inspect_sharding_3d_jit(self): def _cb(sd): self.assertIsInstance(sd, jax.sharding.NamedSharding) self.assertLen(sd.device_set, 2) def f_(x): debugging.inspect_array_sharding(x, callback=_cb) return jnp.square(x) f = jax.jit(f_) mesh = jtu.create_mesh((2,), ('x')) s = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec('x')) arr = jax.device_put(np.arange(8).reshape(2, 2, 2), s) f(arr) def _get_output_set(output, num_lines): """Return a set of strings where each string is num_lines.""" output = output().strip().split("\n") return { "\n".join(output[i : i + num_lines]) for i in range(0, len(output), num_lines) } @jtu.thread_unsafe_test_class() # printing isn't thread-safe
InspectShardingTest
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 142186, "end": 144453 }
class ____: def test_sf(self): # reference values were computed via the reference distribution, e.g. # mp.dps = 100; LogLaplace(c=c).sf(x). c = np.array([2.0, 3.0, 5.0]) x = np.array([1e-5, 1e10, 1e15]) ref = [0.99999999995, 5e-31, 5e-76] assert_allclose(stats.loglaplace.sf(x, c), ref, rtol=1e-15) def test_isf(self): # reference values were computed via the reference distribution, e.g. # mp.dps = 100; LogLaplace(c=c).isf(q). c = 3.25 q = [0.8, 0.1, 1e-10, 1e-20, 1e-40] ref = [0.7543222539245642, 1.6408455124660906, 964.4916294395846, 1151387.578354072, 1640845512466.0906] assert_allclose(stats.loglaplace.isf(q, c), ref, rtol=1e-14) @pytest.mark.parametrize('r', [1, 2, 3, 4]) def test_moments_stats(self, r): mom = 'mvsk'[r - 1] c = np.arange(0.5, r + 0.5, 0.5) # r-th non-central moment is infinite if |r| >= c. assert_allclose(stats.loglaplace.moment(r, c), np.inf) # r-th non-central moment is non-finite (inf or nan) if r >= c. assert not np.any(np.isfinite(stats.loglaplace.stats(c, moments=mom))) @pytest.mark.parametrize("c", [0.5, 1.0, 2.0]) @pytest.mark.parametrize("loc, scale", [(-1.2, 3.45)]) @pytest.mark.parametrize("fix_c", [True, False]) @pytest.mark.parametrize("fix_scale", [True, False]) def test_fit_analytic_mle(self, c, loc, scale, fix_c, fix_scale): # Test that the analytical MLE produces no worse result than the # generic (numerical) MLE. rng = np.random.default_rng(6762668991392531563) data = stats.loglaplace.rvs(c, loc=loc, scale=scale, size=100, random_state=rng) kwds = {'floc': loc} if fix_c: kwds['fc'] = c if fix_scale: kwds['fscale'] = scale nfree = 3 - len(kwds) if nfree == 0: error_msg = "All parameters fixed. There is nothing to optimize." with pytest.raises((RuntimeError, ValueError), match=error_msg): stats.loglaplace.fit(data, **kwds) return _assert_less_or_close_loglike(stats.loglaplace, data, **kwds)
TestLogLaplace
python
python__mypy
mypyc/transform/ir_transform.py
{ "start": 821, "end": 6757 }
class ____(OpVisitor[Value | None]): """Identity transform. Subclass and override to perform changes to IR. Subclass IRTransform and override any OpVisitor visit_* methods that perform any IR changes. The default implementations implement an identity transform. A visit method can return None to remove ops. In this case the transform must ensure that no op uses the original removed op as a source after the transform. You can retain old BasicBlock and op references in ops. The transform will automatically patch these for you as needed. """ def __init__(self, builder: LowLevelIRBuilder) -> None: self.builder = builder # Subclasses add additional op mappings here. A None value indicates # that the op/register is deleted. self.op_map: dict[Value, Value | None] = {} def transform_blocks(self, blocks: list[BasicBlock]) -> None: """Transform basic blocks that represent a single function. The result of the transform will be collected at self.builder.blocks. """ block_map: dict[BasicBlock, BasicBlock] = {} op_map = self.op_map empties = set() for block in blocks: new_block = BasicBlock() block_map[block] = new_block self.builder.activate_block(new_block) new_block.error_handler = block.error_handler for op in block.ops: new_op = op.accept(self) if new_op is not op: op_map[op] = new_op # A transform can produce empty blocks which can be removed. if is_empty_block(new_block) and not is_empty_block(block): empties.add(new_block) self.builder.blocks = [block for block in self.builder.blocks if block not in empties] # Update all op/block references to point to the transformed ones. patcher = PatchVisitor(op_map, block_map) for block in self.builder.blocks: for op in block.ops: op.accept(patcher) if block.error_handler is not None: block.error_handler = block_map.get(block.error_handler, block.error_handler) def add(self, op: Op) -> Value: return self.builder.add(op) def visit_goto(self, op: Goto) -> None: self.add(op) def visit_branch(self, op: Branch) -> None: self.add(op) def visit_return(self, op: Return) -> None: self.add(op) def visit_unreachable(self, op: Unreachable) -> None: self.add(op) def visit_assign(self, op: Assign) -> Value | None: if op.src in self.op_map and self.op_map[op.src] is None: # Special case: allow removing register initialization assignments return None return self.add(op) def visit_assign_multi(self, op: AssignMulti) -> Value | None: return self.add(op) def visit_load_error_value(self, op: LoadErrorValue) -> Value | None: return self.add(op) def visit_load_literal(self, op: LoadLiteral) -> Value | None: return self.add(op) def visit_get_attr(self, op: GetAttr) -> Value | None: return self.add(op) def visit_set_attr(self, op: SetAttr) -> Value | None: return self.add(op) def visit_load_static(self, op: LoadStatic) -> Value | None: return self.add(op) def visit_init_static(self, op: InitStatic) -> Value | None: return self.add(op) def visit_tuple_get(self, op: TupleGet) -> Value | None: return self.add(op) def visit_tuple_set(self, op: TupleSet) -> Value | None: return self.add(op) def visit_inc_ref(self, op: IncRef) -> Value | None: return self.add(op) def visit_dec_ref(self, op: DecRef) -> Value | None: return self.add(op) def visit_call(self, op: Call) -> Value | None: return self.add(op) def visit_method_call(self, op: MethodCall) -> Value | None: return self.add(op) def visit_cast(self, op: Cast) -> Value | None: return self.add(op) def visit_box(self, op: Box) -> Value | None: return self.add(op) def visit_unbox(self, op: Unbox) -> Value | None: return self.add(op) def visit_raise_standard_error(self, op: RaiseStandardError) -> Value | None: return self.add(op) def visit_call_c(self, op: CallC) -> Value | None: return self.add(op) def visit_primitive_op(self, op: PrimitiveOp) -> Value | None: return self.add(op) def visit_truncate(self, op: Truncate) -> Value | None: return self.add(op) def visit_extend(self, op: Extend) -> Value | None: return self.add(op) def visit_load_global(self, op: LoadGlobal) -> Value | None: return self.add(op) def visit_int_op(self, op: IntOp) -> Value | None: return self.add(op) def visit_comparison_op(self, op: ComparisonOp) -> Value | None: return self.add(op) def visit_float_op(self, op: FloatOp) -> Value | None: return self.add(op) def visit_float_neg(self, op: FloatNeg) -> Value | None: return self.add(op) def visit_float_comparison_op(self, op: FloatComparisonOp) -> Value | None: return self.add(op) def visit_load_mem(self, op: LoadMem) -> Value | None: return self.add(op) def visit_set_mem(self, op: SetMem) -> Value | None: return self.add(op) def visit_get_element_ptr(self, op: GetElementPtr) -> Value | None: return self.add(op) def visit_set_element(self, op: SetElement) -> Value | None: return self.add(op) def visit_load_address(self, op: LoadAddress) -> Value | None: return self.add(op) def visit_keep_alive(self, op: KeepAlive) -> Value | None: return self.add(op) def visit_unborrow(self, op: Unborrow) -> Value | None: return self.add(op)
IRTransform
python
pyqtgraph__pyqtgraph
pyqtgraph/flowchart/library/Display.py
{ "start": 5530, "end": 6183 }
class ____(CtrlNode): """Generates a plot curve from x/y data""" nodeName = 'PlotCurve' uiTemplate = [ ('color', 'color'), ] def __init__(self, name): CtrlNode.__init__(self, name, terminals={ 'x': {'io': 'in'}, 'y': {'io': 'in'}, 'plot': {'io': 'out'} }) self.item = PlotDataItem() def process(self, x, y, display=True): #print "scatterplot process" if not display: return {'plot': None} self.item.setData(x, y, pen=self.ctrls['color'].color()) return {'plot': self.item}
PlotCurve
python
jazzband__django-redis
django_redis/client/herd.py
{ "start": 529, "end": 799 }
class ____: """ Dummy class for use as marker for herded keys. """ pass def _is_expired(x, herd_timeout: int) -> bool: if x >= herd_timeout: return True val = x + random.randint(1, herd_timeout) return val >= herd_timeout
Marker
python
huggingface__transformers
src/transformers/models/perceiver/modeling_perceiver.py
{ "start": 110381, "end": 111212 }
class ____(nn.Module): """ Module to decode embeddings (for masked language modeling). Args: config ([`PerceiverConfig`]): Model configuration. """ def __init__(self, config: PerceiverConfig) -> None: super().__init__() self.config = config self.vocab_size = config.vocab_size self.bias = nn.Parameter(torch.zeros(self.vocab_size)) def forward(self, hidden_states: torch.Tensor, embedding_layer: torch.Tensor) -> torch.Tensor: batch_size, seq_len, d_model = hidden_states.shape # Flatten batch dim output = torch.matmul(hidden_states.reshape([-1, d_model]), embedding_layer.weight.transpose(0, 1)) output = output + self.bias return output.reshape([batch_size, seq_len, self.vocab_size])
PerceiverEmbeddingDecoder
python
sqlalchemy__sqlalchemy
test/orm/test_deprecations.py
{ "start": 4685, "end": 8170 }
class ____(QueryTest): def test_get(self): User = self.classes.User s = fixture_session() with assertions.expect_deprecated_20(query_get_dep): assert s.query(User).get(19) is None with assertions.expect_deprecated_20(query_get_dep): u = s.query(User).get(7) with assertions.expect_deprecated_20(query_get_dep): u2 = s.query(User).get(7) assert u is u2 s.expunge_all() with assertions.expect_deprecated_20(query_get_dep): u2 = s.query(User).get(7) assert u is not u2 def test_loader_options(self): User = self.classes.User s = fixture_session() with assertions.expect_deprecated_20(query_get_dep): u1 = s.query(User).options(joinedload(User.addresses)).get(8) eq_(len(u1.__dict__["addresses"]), 3) def test_no_criterion_when_already_loaded(self): """test that get()/load() does not use preexisting filter/etc. criterion, even when we're only using the identity map.""" User, Address = self.classes.User, self.classes.Address s = fixture_session() s.get(User, 7) q = s.query(User).join(User.addresses).filter(Address.user_id == 8) with assertions.expect_deprecated_20(query_get_dep): with assertions.expect_raises_message( sa_exc.InvalidRequestError, r"Query.get\(\) being called on a Query with existing " "criterion.", ): q.get(7) def test_no_criterion(self): """test that get()/load() does not use preexisting filter/etc. criterion""" User, Address = self.classes.User, self.classes.Address s = fixture_session() q = s.query(User).join(User.addresses).filter(Address.user_id == 8) with assertions.expect_deprecated_20(query_get_dep): with assertions.expect_raises_message( sa_exc.InvalidRequestError, r"Query.get\(\) being called on a Query with existing " "criterion.", ): q.get(7) with assertions.expect_deprecated_20(query_get_dep): with assertions.expect_raises_message( sa_exc.InvalidRequestError, r"Query.get\(\) being called on a Query with existing " "criterion.", ): s.query(User).filter(User.id == 7).get(19) # order_by()/get() doesn't raise with assertions.expect_deprecated_20(query_get_dep): s.query(User).order_by(User.id).get(8) def test_get_against_col(self): User = self.classes.User s = fixture_session() with assertions.expect_deprecated_20(query_get_dep): with assertions.expect_raises_message( sa_exc.InvalidRequestError, r"get\(\) can only be used against a single mapped class.", ): s.query(User.id).get(5) def test_only_full_mapper_zero(self): User, Address = self.classes.User, self.classes.Address s = fixture_session() q = s.query(User, Address) with assertions.expect_deprecated_20(query_get_dep): with assertions.expect_raises_message( sa_exc.InvalidRequestError, r"get\(\) can only be used against a single mapped class.", ): q.get(5)
GetTest
python
ray-project__ray
rllib/core/models/torch/encoder.py
{ "start": 1296, "end": 2962 }
class ____(TorchModel, Encoder): def __init__(self, config: MLPEncoderConfig) -> None: TorchModel.__init__(self, config) Encoder.__init__(self, config) # Create the neural network. self.net = TorchMLP( input_dim=config.input_dims[0], hidden_layer_dims=config.hidden_layer_dims, hidden_layer_activation=config.hidden_layer_activation, hidden_layer_use_layernorm=config.hidden_layer_use_layernorm, hidden_layer_use_bias=config.hidden_layer_use_bias, hidden_layer_weights_initializer=config.hidden_layer_weights_initializer, hidden_layer_weights_initializer_config=( config.hidden_layer_weights_initializer_config ), hidden_layer_bias_initializer=config.hidden_layer_bias_initializer, hidden_layer_bias_initializer_config=( config.hidden_layer_bias_initializer_config ), output_dim=config.output_layer_dim, output_activation=config.output_layer_activation, output_use_bias=config.output_layer_use_bias, output_weights_initializer=config.output_layer_weights_initializer, output_weights_initializer_config=( config.output_layer_weights_initializer_config ), output_bias_initializer=config.output_layer_bias_initializer, output_bias_initializer_config=config.output_layer_bias_initializer_config, ) @override(Model) def _forward(self, inputs: dict, **kwargs) -> dict: return {ENCODER_OUT: self.net(inputs[Columns.OBS])}
TorchMLPEncoder
python
matplotlib__matplotlib
lib/matplotlib/gridspec.py
{ "start": 11812, "end": 18346 }
class ____(GridSpecBase): """ A grid layout to place subplots within a figure. The location of the grid cells is determined in a similar way to `.SubplotParams` using *left*, *right*, *top*, *bottom*, *wspace* and *hspace*. Indexing a GridSpec instance returns a `.SubplotSpec`. """ def __init__(self, nrows, ncols, figure=None, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratios=None, height_ratios=None): """ Parameters ---------- nrows, ncols : int The number of rows and columns of the grid. figure : `.Figure`, optional Only used for constrained layout to create a proper layoutgrid. left, right, top, bottom : float, optional Extent of the subplots as a fraction of figure width or height. Left cannot be larger than right, and bottom cannot be larger than top. If not given, the values will be inferred from a figure or rcParams at draw time. See also `GridSpec.get_subplot_params`. wspace : float, optional The amount of width reserved for space between subplots, expressed as a fraction of the average axis width. If not given, the values will be inferred from a figure or rcParams when necessary. See also `GridSpec.get_subplot_params`. hspace : float, optional The amount of height reserved for space between subplots, expressed as a fraction of the average axis height. If not given, the values will be inferred from a figure or rcParams when necessary. See also `GridSpec.get_subplot_params`. width_ratios : array-like of length *ncols*, optional Defines the relative widths of the columns. Each column gets a relative width of ``width_ratios[i] / sum(width_ratios)``. If not given, all columns will have the same width. height_ratios : array-like of length *nrows*, optional Defines the relative heights of the rows. Each row gets a relative height of ``height_ratios[i] / sum(height_ratios)``. If not given, all rows will have the same height. """ self.left = left self.bottom = bottom self.right = right self.top = top self.wspace = wspace self.hspace = hspace self.figure = figure super().__init__(nrows, ncols, width_ratios=width_ratios, height_ratios=height_ratios) _AllowedKeys = ["left", "bottom", "right", "top", "wspace", "hspace"] def update(self, *, left=_UNSET, bottom=_UNSET, right=_UNSET, top=_UNSET, wspace=_UNSET, hspace=_UNSET): """ Update the subplot parameters of the grid. Parameters that are not explicitly given are not changed. Setting a parameter to *None* resets it to :rc:`figure.subplot.*`. Parameters ---------- left, right, top, bottom : float or None, optional Extent of the subplots as a fraction of figure width or height. wspace, hspace : float or None, optional Spacing between the subplots as a fraction of the average subplot width / height. """ if left is not _UNSET: self.left = left if bottom is not _UNSET: self.bottom = bottom if right is not _UNSET: self.right = right if top is not _UNSET: self.top = top if wspace is not _UNSET: self.wspace = wspace if hspace is not _UNSET: self.hspace = hspace for figmanager in _pylab_helpers.Gcf.figs.values(): for ax in figmanager.canvas.figure.axes: if ax.get_subplotspec() is not None: ss = ax.get_subplotspec().get_topmost_subplotspec() if ss.get_gridspec() == self: fig = ax.get_figure(root=False) ax._set_position(ax.get_subplotspec().get_position(fig)) def get_subplot_params(self, figure=None): """ Return the `.SubplotParams` for the GridSpec. In order of precedence the values are taken from - non-*None* attributes of the GridSpec - the provided *figure* - :rc:`figure.subplot.*` Note that the ``figure`` attribute of the GridSpec is always ignored. """ if figure is None: kw = {k: mpl.rcParams["figure.subplot."+k] for k in self._AllowedKeys} subplotpars = SubplotParams(**kw) else: subplotpars = copy.copy(figure.subplotpars) subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys}) return subplotpars def locally_modified_subplot_params(self): """ Return a list of the names of the subplot parameters explicitly set in the GridSpec. This is a subset of the attributes of `.SubplotParams`. """ return [k for k in self._AllowedKeys if getattr(self, k)] def tight_layout(self, figure, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None): """ Adjust subplot parameters to give specified padding. Parameters ---------- figure : `.Figure` The figure. renderer : `.RendererBase` subclass, optional The renderer to be used. pad : float Padding between the figure edge and the edges of subplots, as a fraction of the font-size. h_pad, w_pad : float, optional Padding (height/width) between edges of adjacent subplots. Defaults to *pad*. rect : tuple (left, bottom, right, top), default: None (left, bottom, right, top) rectangle in normalized figure coordinates that the whole subplots area (including labels) will fit into. Default (None) is the whole figure. """ if renderer is None: renderer = figure._get_renderer() kwargs = _tight_layout.get_tight_layout_figure( figure, figure.axes, _tight_layout.get_subplotspec_list(figure.axes, grid_spec=self), renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect) if kwargs: self.update(**kwargs)
GridSpec
python
numba__numba
numba/tests/test_ufuncs.py
{ "start": 59781, "end": 60762 }
class ____(_LoopTypesTester): _ufuncs = [np.left_shift] _required_types = 'bBhHiIlLqQ' _skip_types = 'fdFDmMO' + _LoopTypesTester._skip_types def _arg_for_type(self, a_letter_type, index=0): res = super(self.__class__, self)._arg_for_type(a_letter_type, index=index) # Shifting by a negative amount (argument with index 1) is undefined # behavior in C. It is also undefined behavior in numba. In the same # sense, it is also undefined behavior when the shift amount is larger # than the number of bits in the shifted integer. # To avoid problems in the test, the values are clamped (clipped) so # that 0 <= shift_amount < bitcount(shifted_integer) if index == 1: bit_count = res.dtype.itemsize * 8 res = np.clip(res, 0, bit_count - 1) return res TestLoopTypesIntLeftShift.autogenerate()
TestLoopTypesIntLeftShift
python
walkccc__LeetCode
solutions/152. Maximum Product Subarray/152.py
{ "start": 0, "end": 532 }
class ____: def maxProduct(self, nums: list[int]) -> int: ans = nums[0] dpMin = nums[0] # the minimum so far dpMax = nums[0] # the maximum so far for i in range(1, len(nums)): num = nums[i] prevMin = dpMin # dpMin[i - 1] prevMax = dpMax # dpMax[i - 1] if num < 0: dpMin = min(prevMax * num, num) dpMax = max(prevMin * num, num) else: dpMin = min(prevMin * num, num) dpMax = max(prevMax * num, num) ans = max(ans, dpMax) return ans
Solution
python
django__django
tests/template_tests/filter_tests/test_title.py
{ "start": 573, "end": 901 }
class ____(SimpleTestCase): def test_title(self): self.assertEqual(title("a nice title, isn't it?"), "A Nice Title, Isn't It?") def test_unicode(self): self.assertEqual(title("discoth\xe8que"), "Discoth\xe8que") def test_non_string_input(self): self.assertEqual(title(123), "123")
FunctionTests
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_reflection.py
{ "start": 11183, "end": 11435 }
class ____: def __repr__(self): return "☃" def test_can_handle_unicode_repr(): def foo(x): pass assert repr_call(foo, [Snowman()], {}) == "foo(x=☃)" assert repr_call(foo, [], {"x": Snowman()}) == "foo(x=☃)"
BittySnowman
python
scipy__scipy
scipy/fft/tests/test_helper.py
{ "start": 1171, "end": 4091 }
class ____: def test_next_fast_len(self, xp): np.random.seed(1234) def nums(): yield from range(1, 1000) yield 2**5 * 3**5 * 4**5 + 1 for n in nums(): m = next_fast_len(n) _assert_n_smooth(m, 11) assert m == next_fast_len(n, False) m = next_fast_len(n, True) _assert_n_smooth(m, 5) def test_np_integers(self, xp): ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, np.uint64] for ityp in ITYPES: x = ityp(12345) testN = next_fast_len(x) assert_equal(testN, next_fast_len(int(x))) def testnext_fast_len_small(self, xp): hams = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 8, 8: 8, 14: 15, 15: 15, 16: 16, 17: 18, 1021: 1024, 1536: 1536, 51200000: 51200000 } for x, y in hams.items(): assert_equal(next_fast_len(x, True), y) @pytest.mark.xfail(sys.maxsize < 2**32, reason="Hamming Numbers too large for 32-bit", raises=ValueError, strict=True) def testnext_fast_len_big(self, xp): hams = { 510183360: 510183360, 510183360 + 1: 512000000, 511000000: 512000000, 854296875: 854296875, 854296875 + 1: 859963392, 196608000000: 196608000000, 196608000000 + 1: 196830000000, 8789062500000: 8789062500000, 8789062500000 + 1: 8796093022208, 206391214080000: 206391214080000, 206391214080000 + 1: 206624260800000, 470184984576000: 470184984576000, 470184984576000 + 1: 470715894135000, 7222041363087360: 7222041363087360, 7222041363087360 + 1: 7230196133913600, # power of 5 5**23 11920928955078125: 11920928955078125, 11920928955078125 - 1: 11920928955078125, # power of 3 3**34 16677181699666569: 16677181699666569, 16677181699666569 - 1: 16677181699666569, # power of 2 2**54 18014398509481984: 18014398509481984, 18014398509481984 - 1: 18014398509481984, # above this, int(ceil(n)) == int(ceil(n+1)) 19200000000000000: 19200000000000000, 19200000000000000 + 1: 19221679687500000, 288230376151711744: 288230376151711744, 288230376151711744 + 1: 288325195312500000, 288325195312500000 - 1: 288325195312500000, 288325195312500000: 288325195312500000, 288325195312500000 + 1: 288555831593533440, } for x, y in hams.items(): assert_equal(next_fast_len(x, True), y) def test_keyword_args(self, xp): assert next_fast_len(11, real=True) == 12 assert next_fast_len(target=7, real=False) == 7 @skip_xp_backends(np_only=True)
TestNextFastLen
python
tornadoweb__tornado
tornado/test/util_test.py
{ "start": 6467, "end": 7660 }
class ____(unittest.TestCase): def test_no_inherit_future(self): # Two files: the first has "from __future__ import annotations", and it executes the second # which doesn't. The second file should not be affected by the first's __future__ imports. # # The annotations future became available in python 3.7 but has been replaced by PEP 649, so # it should remain supported but off-by-default for the foreseeable future. code1 = textwrap.dedent( """ from __future__ import annotations from tornado.util import exec_in exec_in(code2, globals()) """ ) code2 = textwrap.dedent( """ def f(x: int) -> int: return x + 1 output[0] = f.__annotations__ """ ) # Make a mutable container to pass the result back to the caller output = [None] exec_in(code1, dict(code2=code2, output=output)) # If the annotations future were in effect, these would be strings instead of the int type # object. self.assertEqual(output[0], {"x": int, "return": int})
ExecInTest
python
PyCQA__pylint
tests/functional/b/broad_exception/broad_exception_raised_trystar.py
{ "start": 128, "end": 1255 }
class ____(CustomBroadException): pass def exploding_apple(apple): print(f"{apple} is about to explode") raise Exception("{apple} exploded !") # [broad-exception-raised] def raise_and_catch_star(): try: raise Exception("Oh No!!") # [broad-exception-raised] except* Exception as ex: # [broad-exception-caught] print(ex) def raise_catch_reraise_star(): try: exploding_apple("apple") except* Exception as ex: print(ex) raise ex def raise_catch_raise_star(): try: exploding_apple("apple") except* Exception as ex: print(ex) raise Exception() from None # [broad-exception-raised] def raise_catch_raise_using_alias_star(): try: exploding_apple("apple") except* Exception as ex: print(ex) raise ExceptionAlias() from None # [broad-exception-raised] raise Exception() # [broad-exception-raised] raise BaseException() # [broad-exception-raised] raise CustomBroadException() # [broad-exception-raised] raise IndexError from None raise CustomNarrowException() from None
CustomNarrowException
python
wandb__wandb
wandb/sdk/wandb_config.py
{ "start": 469, "end": 10164 }
class ____: """Config object. Config objects are intended to hold all of the hyperparameters associated with a wandb run and are saved with the run object when `wandb.init` is called. We recommend setting the config once when initializing your run by passing the `config` parameter to `init`: ``` wandb.init(config=my_config_dict) ``` You can create a file called `config-defaults.yaml`, and it will automatically be loaded as each run's config. You can also pass the name of the file as the `config` parameter to `init`: ``` wandb.init(config="my_config.yaml") ``` See https://docs.wandb.com/guides/track/config#file-based-configs. Examples: Basic usage ``` with wandb.init(config={"epochs": 4}) as run: for x in range(run.config.epochs): # train ``` Nested values ``` with wandb.init(config={"train": {"epochs": 4}}) as run: for x in range(run.config["train"]["epochs"]): # train ``` Using absl flags ``` flags.DEFINE_string("model", None, "model to run") # name, default, help with wandb.init() as run: run.config.update(flags.FLAGS) # adds all absl flags to config ``` Argparse flags ```python with wandb.init(config={"epochs": 4}) as run: parser = argparse.ArgumentParser() parser.add_argument( "-b", "--batch-size", type=int, default=8, metavar="N", help="input batch size for training (default: 8)", ) args = parser.parse_args() run.config.update(args) ``` Using TensorFlow flags (deprecated in tensorflow v2) ```python flags = tf.app.flags flags.DEFINE_string("data_dir", "/tmp/data") flags.DEFINE_integer("batch_size", 128, "Batch size.") with wandb.init() as run: run.config.update(flags.FLAGS) ``` """ def __init__(self): object.__setattr__(self, "_items", dict()) object.__setattr__(self, "_locked", dict()) object.__setattr__(self, "_users", dict()) object.__setattr__(self, "_users_inv", dict()) object.__setattr__(self, "_users_cnt", 0) object.__setattr__(self, "_callback", None) object.__setattr__(self, "_settings", None) object.__setattr__(self, "_artifact_callback", None) self._load_defaults() def _set_callback(self, cb): object.__setattr__(self, "_callback", cb) def _set_artifact_callback(self, cb): object.__setattr__(self, "_artifact_callback", cb) def _set_settings(self, settings): object.__setattr__(self, "_settings", settings) def __repr__(self): return str(dict(self)) def keys(self): return [k for k in self._items.keys() if not k.startswith("_")] def _as_dict(self): return self._items def as_dict(self): # TODO: add telemetry, deprecate, then remove return dict(self) def __getitem__(self, key): return self._items[key] def __iter__(self): return iter(self._items) def _check_locked(self, key, ignore_locked=False) -> bool: locked = self._locked.get(key) if locked is not None: locked_user = self._users_inv[locked] if not ignore_locked: wandb.termwarn( f"Config item '{key}' was locked by '{locked_user}' (ignored update)." ) return True return False def __setitem__(self, key, val): if self._check_locked(key): return with wandb.sdk.lib.telemetry.context() as tel: tel.feature.set_config_item = True self._raise_value_error_on_nested_artifact(val, nested=True) key, val = self._sanitize(key, val) self._items[key] = val logger.info("config set %s = %s - %s", key, val, self._callback) if self._callback: self._callback(key=key, val=val) def items(self): return [(k, v) for k, v in self._items.items() if not k.startswith("_")] __setattr__ = __setitem__ def __getattr__(self, key): try: return self.__getitem__(key) except KeyError as ke: raise AttributeError( f"{self.__class__!r} object has no attribute {key!r}" ) from ke def __contains__(self, key): return key in self._items def _update(self, d, allow_val_change=None, ignore_locked=None): parsed_dict = wandb_helper.parse_config(d) locked_keys = set() for key in list(parsed_dict): if self._check_locked(key, ignore_locked=ignore_locked): locked_keys.add(key) sanitized = self._sanitize_dict( parsed_dict, allow_val_change, ignore_keys=locked_keys ) self._items.update(sanitized) return sanitized def update(self, d, allow_val_change=None): sanitized = self._update(d, allow_val_change) if self._callback: self._callback(data=sanitized) def get(self, *args): return self._items.get(*args) def persist(self): """Call the callback if it's set.""" if self._callback: self._callback(data=self._as_dict()) def setdefaults(self, d): d = wandb_helper.parse_config(d) # strip out keys already configured d = {k: v for k, v in d.items() if k not in self._items} d = self._sanitize_dict(d) self._items.update(d) if self._callback: self._callback(data=d) def _get_user_id(self, user) -> int: if user not in self._users: self._users[user] = self._users_cnt self._users_inv[self._users_cnt] = user object.__setattr__(self, "_users_cnt", self._users_cnt + 1) return self._users[user] def update_locked(self, d, user=None, _allow_val_change=None): """Shallow-update config with `d` and lock config updates on d's keys.""" num = self._get_user_id(user) for k, v in d.items(): k, v = self._sanitize(k, v, allow_val_change=_allow_val_change) self._locked[k] = num self._items[k] = v if self._callback: self._callback(data=d) def merge_locked(self, d, user=None, _allow_val_change=None): """Recursively merge-update config with `d` and lock config updates on d's keys.""" num = self._get_user_id(user) callback_d = {} for k, v in d.items(): k, v = self._sanitize(k, v, allow_val_change=_allow_val_change) self._locked[k] = num if ( k in self._items and isinstance(self._items[k], dict) and isinstance(v, dict) ): self._items[k] = config_util.merge_dicts(self._items[k], v) else: self._items[k] = v callback_d[k] = self._items[k] if self._callback: self._callback(data=callback_d) def _load_defaults(self): conf_dict = config_util.dict_from_config_file("config-defaults.yaml") if conf_dict is not None: self.update(conf_dict) def _sanitize_dict( self, config_dict, allow_val_change=None, ignore_keys: Optional[set] = None, ): sanitized = {} self._raise_value_error_on_nested_artifact(config_dict) for k, v in config_dict.items(): if ignore_keys and k in ignore_keys: continue k, v = self._sanitize(k, v, allow_val_change) sanitized[k] = v return sanitized def _sanitize(self, key, val, allow_val_change=None): # TODO: enable WBValues in the config in the future # refuse all WBValues which is all Media and Histograms if isinstance(val, wandb.sdk.data_types.base_types.wb_value.WBValue): raise TypeError("WBValue objects cannot be added to the run config") # Let jupyter change config freely by default if self._settings and self._settings._jupyter and allow_val_change is None: allow_val_change = True # We always normalize keys by stripping '-' key = key.strip("-") if _is_artifact_representation(val): val = self._artifact_callback(key, val) # if the user inserts an artifact into the config if not isinstance(val, wandb.Artifact): val = json_friendly_val(val) if not allow_val_change: if key in self._items and val != self._items[key]: raise config_util.ConfigError( f'Attempted to change value of key "{key}" ' f"from {self._items[key]} to {val}\n" "If you really want to do this, pass" " allow_val_change=True to config.update()" ) return key, val def _raise_value_error_on_nested_artifact(self, v, nested=False): # we can't swap nested artifacts because their root key can be locked by other values # best if we don't allow nested artifacts until we can lock nested keys in the config if isinstance(v, dict) and check_dict_contains_nested_artifact(v, nested): raise ValueError( "Instances of wandb.Artifact can only be top level keys in" " a run's config" )
Config
python
huggingface__transformers
src/transformers/generation/watermarking.py
{ "start": 2799, "end": 11084 }
class ____: r""" Detector for detection of watermark generated text. The detector needs to be given the exact same settings that were given during text generation to replicate the watermark greenlist generation and so detect the watermark. This includes the correct device that was used during text generation, the correct watermarking arguments and the correct tokenizer vocab size. The code was based on the [original repo](https://github.com/jwkirchenbauer/lm-watermarking/tree/main). See [the paper](https://huggingface.co/papers/2306.04634) for more information. Args: model_config (`PreTrainedConfig`): The model config that will be used to get model specific arguments used when generating. device (`str`): The device which was used during watermarked text generation. watermarking_config (Union[`WatermarkingConfig`, `Dict`]): The exact same watermarking config and arguments used when generating text. ignore_repeated_ngrams (`bool`, *optional*, defaults to `False`): Whether to count every unique ngram only once or not. max_cache_size (`int`, *optional*, defaults to 128): The max size to be used for LRU caching of seeding/sampling algorithms called for every token. Examples: ```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig >>> model_id = "openai-community/gpt2" >>> model = AutoModelForCausalLM.from_pretrained(model_id) >>> tok = AutoTokenizer.from_pretrained(model_id) >>> tok.pad_token_id = tok.eos_token_id >>> tok.padding_side = "left" >>> inputs = tok(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt") >>> input_len = inputs["input_ids"].shape[-1] >>> # first generate text with watermark and without >>> watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash") >>> out_watermarked = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20) >>> out = model.generate(**inputs, do_sample=False, max_length=20) >>> # now we can instantiate the detector and check the generated text >>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config) >>> detection_out_watermarked = detector(out_watermarked, return_dict=True) >>> detection_out = detector(out, return_dict=True) >>> detection_out_watermarked.prediction array([ True, True]) >>> detection_out.prediction array([False, False]) ``` """ def __init__( self, model_config: PreTrainedConfig, device: str, watermarking_config: WatermarkingConfig | dict, ignore_repeated_ngrams: bool = False, max_cache_size: int = 128, ): if isinstance(watermarking_config, WatermarkingConfig): watermarking_config = watermarking_config.to_dict() self.bos_token_id = ( model_config.bos_token_id if not model_config.is_encoder_decoder else model_config.decoder_start_token_id ) self.greenlist_ratio = watermarking_config["greenlist_ratio"] self.ignore_repeated_ngrams = ignore_repeated_ngrams self.processor = WatermarkLogitsProcessor( vocab_size=model_config.vocab_size, device=device, **watermarking_config ) # Expensive re-seeding and sampling is cached. self._get_ngram_score_cached = lru_cache(maxsize=max_cache_size)(self._get_ngram_score) def _get_ngram_score(self, prefix: torch.LongTensor, target: int): greenlist_ids = self.processor._get_greenlist_ids(prefix) return target in greenlist_ids def _score_ngrams_in_passage(self, input_ids: torch.LongTensor): batch_size, seq_length = input_ids.shape selfhash = int(self.processor.seeding_scheme == "selfhash") n = self.processor.context_width + 1 - selfhash indices = torch.arange(n).unsqueeze(0) + torch.arange(seq_length - n + 1).unsqueeze(1) ngram_tensors = input_ids[:, indices] num_tokens_scored_batch = np.zeros(batch_size) green_token_count_batch = np.zeros(batch_size) for batch_idx in range(ngram_tensors.shape[0]): frequencies_table = collections.Counter(ngram_tensors[batch_idx]) ngram_to_watermark_lookup = {} for ngram_example in frequencies_table: prefix = ngram_example if selfhash else ngram_example[:-1] target = ngram_example[-1] ngram_to_watermark_lookup[ngram_example] = self._get_ngram_score_cached(prefix, target) if self.ignore_repeated_ngrams: # counts a green/red hit once per unique ngram. # num total tokens scored becomes the number unique ngrams. num_tokens_scored_batch[batch_idx] = len(frequencies_table.keys()) green_token_count_batch[batch_idx] = sum(ngram_to_watermark_lookup.values()) else: num_tokens_scored_batch[batch_idx] = sum(frequencies_table.values()) green_token_count_batch[batch_idx] = sum( freq * outcome for freq, outcome in zip(frequencies_table.values(), ngram_to_watermark_lookup.values()) ) return num_tokens_scored_batch, green_token_count_batch def _compute_z_score(self, green_token_count: np.ndarray, total_num_tokens: np.ndarray) -> np.ndarray: expected_count = self.greenlist_ratio numer = green_token_count - expected_count * total_num_tokens denom = np.sqrt(total_num_tokens * expected_count * (1 - expected_count)) z = numer / denom return z def _compute_pval(self, x, loc=0, scale=1): z = (x - loc) / scale return 1 - (0.5 * (1 + np.sign(z) * (1 - np.exp(-2 * z**2 / np.pi)))) def __call__( self, input_ids: torch.LongTensor, z_threshold: float = 3.0, return_dict: bool = False, ) -> WatermarkDetectorOutput | np.ndarray: """ Args: input_ids (`torch.LongTensor`): The watermark generated text. It is advised to remove the prompt, which can affect the detection. z_threshold (`Dict`, *optional*, defaults to `3.0`): Changing this threshold will change the sensitivity of the detector. Higher z threshold gives less sensitivity and vice versa for lower z threshold. return_dict (`bool`, *optional*, defaults to `False`): Whether to return `~generation.WatermarkDetectorOutput` or not. If not it will return boolean predictions, ma Return: [`~generation.WatermarkDetectorOutput`] or `np.ndarray`: A [`~generation.WatermarkDetectorOutput`] if `return_dict=True` otherwise a `np.ndarray`. """ # Let's assume that if one batch start with `bos`, all batched also do if input_ids[0, 0] == self.bos_token_id: input_ids = input_ids[:, 1:] if input_ids.shape[-1] - self.processor.context_width < 1: raise ValueError( f"Must have at least `1` token to score after the first " f"min_prefix_len={self.processor.context_width} tokens required by the seeding scheme." ) num_tokens_scored, green_token_count = self._score_ngrams_in_passage(input_ids) z_score = self._compute_z_score(green_token_count, num_tokens_scored) prediction = z_score > z_threshold if return_dict: p_value = self._compute_pval(z_score) confidence = 1 - p_value return WatermarkDetectorOutput( num_tokens_scored=num_tokens_scored, num_green_tokens=green_token_count, green_fraction=green_token_count / num_tokens_scored, z_score=z_score, p_value=p_value, prediction=prediction, confidence=confidence, ) return prediction
WatermarkDetector
python
crytic__slither
slither/printers/summary/variable_order.py
{ "start": 211, "end": 1669 }
class ____(AbstractPrinter): ARGUMENT = "variable-order" HELP = "Print the storage order of the state variables" WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#variable-order" def output(self, _filename: str) -> Output: """ _filename is not used Args: _filename(string) """ txt = "" all_tables = [] for contract in self.slither.contracts_derived: txt += f"\n{contract.name}:\n" table = MyPrettyTable(["Name", "Type", "Slot", "Offset", "State"]) for variable in contract.storage_variables_ordered: slot, offset = contract.compilation_unit.storage_layout_of(contract, variable) table.add_row( [variable.canonical_name, str(variable.type), slot, offset, "Storage"] ) for variable in contract.transient_variables_ordered: slot, offset = contract.compilation_unit.storage_layout_of(contract, variable) table.add_row( [variable.canonical_name, str(variable.type), slot, offset, "Transient"] ) all_tables.append((contract.name, table)) txt += str(table) + "\n" self.info(txt) res = self.generate_output(txt) for name, table in all_tables: res.add_pretty_table(table, name) return res
VariableOrder
python
fluentpython__example-code-2e
24-class-metaprog/metabunch/nutshell3e/bunch_test.py
{ "start": 40, "end": 861 }
class ____(Bunch): """ A point has x and y coordinates, defaulting to 0.0, and a color, defaulting to 'gray'—and nothing more, except what Python and the metaclass conspire to add, such as __init__ and __repr__ """ x = 0.0 y = 0.0 color = 'gray' def test_init_defaults(): p = Point() assert repr(p) == 'Point()' def test_init(): p = Point(x=1.2, y=3.4, color='red') assert repr(p) == "Point(x=1.2, y=3.4, color='red')" def test_init_wrong_argument(): with pytest.raises(AttributeError) as exc: p = Point(x=1.2, y=3.4, flavor='coffee') assert "no attribute 'flavor'" in str(exc.value) def test_slots(): p = Point() with pytest.raises(AttributeError) as exc: p.z = 5.6 assert "no attribute 'z'" in str(exc.value)
Point
python
tox-dev__tox
src/tox/tox_env/python/pip/req/args.py
{ "start": 489, "end": 2829 }
class ____(ArgumentParser): def print_usage(self, file: _SupportsWrite[str] | None = None) -> None: """ """ def exit(self, status: int = 0, message: str | None = None) -> NoReturn: # noqa: ARG002, PLR6301 message = "" if message is None else message msg = message.lstrip(": ").rstrip() msg = msg.removeprefix("error: ") raise ValueError(msg) def build_parser() -> ArgumentParser: parser = _OurArgumentParser(add_help=False, prog="", allow_abbrev=False) _global_options(parser) _req_options(parser) return parser def _global_options(parser: ArgumentParser) -> None: parser.add_argument("-i", "--index-url", "--pypi-url", dest="index_url", default=None) parser.add_argument("--extra-index-url", action=AddUniqueAction) parser.add_argument("--no-index", action="store_true", default=False) parser.add_argument("-c", "--constraint", action=AddUniqueAction, dest="constraints") parser.add_argument("-r", "--requirement", action=AddUniqueAction, dest="requirements") parser.add_argument("-e", "--editable", action=AddUniqueAction, dest="editables") parser.add_argument("-f", "--find-links", action=AddUniqueAction) parser.add_argument("--no-binary", action=BinaryAction, nargs="+") parser.add_argument("--only-binary", action=BinaryAction, nargs="+") parser.add_argument("--prefer-binary", action="store_true", default=False) parser.add_argument("--require-hashes", action="store_true", default=False) parser.add_argument("--pre", action="store_true", default=False) parser.add_argument("--trusted-host", action=AddSortedUniqueAction) parser.add_argument( "--use-feature", choices=["2020-resolver", "fast-deps"], action=AddSortedUniqueAction, dest="features_enabled", ) def _req_options(parser: ArgumentParser) -> None: parser.add_argument("--install-option", action=AddSortedUniqueAction) parser.add_argument("--global-option", action=AddSortedUniqueAction) parser.add_argument("--hash", action=AddSortedUniqueAction, type=_validate_hash) _HASH = re.compile(r"sha(256:[a-f0-9]{64}|384:[a-f0-9]{96}|512:[a-f0-9]{128})") def _validate_hash(value: str) -> str: if not _HASH.fullmatch(value): raise ArgumentTypeError(value) return value
_OurArgumentParser
python
django__django
tests/admin_views/admin.py
{ "start": 3759, "end": 3923 }
class ____(forms.ModelForm): extra_form_field = forms.BooleanField(required=False) class Meta: fields = "__all__" model = Article
ArticleForm
python
bokeh__bokeh
src/bokeh/core/property/descriptors.py
{ "start": 6048, "end": 7265 }
class ____(AliasPropertyDescriptor[T]): """ """ alias: DeprecatedAlias[T] def __init__(self, name: str, alias: DeprecatedAlias[T]) -> None: super().__init__(name, alias) major, minor, patch = self.alias.since since = f"{major}.{minor}.{patch}" self.__doc__ = f"""\ This is a backwards compatibility alias for the {self.aliased_name!r} property. .. note:: Property {self.name!r} was deprecated in Bokeh {since} and will be removed in the future. Update your code to use {self.aliased_name!r} instead. """ def _warn(self) -> None: from ...util.deprecation import deprecated deprecated(self.alias.since, self.name, self.aliased_name, self.alias.extra) def __get__(self, obj: HasProps | None, owner: type[HasProps] | None) -> T: if obj is not None: # Warn only when accessing descriptor's value, otherwise there would # be a lot of spurious warnings from parameter resolution, etc. self._warn() return super().__get__(obj, owner) def __set__(self, obj: HasProps | None, value: T) -> None: self._warn() super().__set__(obj, value)
DeprecatedAliasPropertyDescriptor
python
PrefectHQ__prefect
tests/cli/test_transfer.py
{ "start": 4793, "end": 6614 }
class ____: """Test command line argument validation.""" @patch("prefect.cli.transfer.load_profiles") def test_transfer_source_profile_not_found(self, mock_load_profiles: MagicMock): """Test transfer command fails when source profile doesn't exist.""" mock_load_profiles.return_value = ProfilesCollection([]) invoke_and_assert( command=["transfer", "--from", "nonexistent", "--to", "target"], expected_code=1, expected_output_contains="Source profile 'nonexistent' not found", ) @patch("prefect.cli.transfer.load_profiles") def test_transfer_target_profile_not_found( self, mock_load_profiles: MagicMock, mock_profiles: ProfilesCollection ): """Test transfer command fails when target profile doesn't exist.""" # Only include source profile source_profile = Profile(name="source", settings={}) mock_load_profiles.return_value = ProfilesCollection([source_profile]) invoke_and_assert( command=["transfer", "--from", "source", "--to", "nonexistent"], expected_code=1, expected_output_contains="Target profile 'nonexistent' not found", ) @patch("prefect.cli.transfer.load_profiles") def test_transfer_same_source_and_target_profiles( self, mock_load_profiles: MagicMock ): """Test transfer command fails when source and target are the same.""" profile = Profile(name="same", settings={}) mock_load_profiles.return_value = ProfilesCollection([profile]) invoke_and_assert( command=["transfer", "--from", "same", "--to", "same"], expected_code=1, expected_output_contains="Source and target profiles must be different", )
TestTransferArguments
python
pytorch__pytorch
torch/fx/experimental/refinement_types.py
{ "start": 0, "end": 451 }
class ____: def __init__(self, lhs: object, rhs: object): self.lhs = lhs self.rhs = rhs def __str__(self) -> str: return f"{self.lhs} = {self.rhs}" def __repr__(self) -> str: return f"{self.lhs} = {self.rhs}" def __eq__(self, other: object) -> bool: if isinstance(other, Equality): return self.lhs == other.lhs and self.rhs == other.rhs else: return False
Equality
python
pypa__pip
src/pip/_vendor/platformdirs/unix.py
{ "start": 441, "end": 10458 }
class ____(PlatformDirsABC): # noqa: PLR0904 """ On Unix/Linux, we follow the `XDG Basedir Spec <https://specifications.freedesktop.org/basedir-spec/basedir-spec- latest.html>`_. The spec allows overriding directories with environment variables. The examples shown are the default values, alongside the name of the environment variable that overrides them. Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`, `version <platformdirs.api.PlatformDirsABC.version>`, `multipath <platformdirs.api.PlatformDirsABC.multipath>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`. """ @property def user_data_dir(self) -> str: """ :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or ``$XDG_DATA_HOME/$appname/$version`` """ path = os.environ.get("XDG_DATA_HOME", "") if not path.strip(): path = os.path.expanduser("~/.local/share") # noqa: PTH111 return self._append_app_name_and_version(path) @property def _site_data_dirs(self) -> list[str]: path = os.environ.get("XDG_DATA_DIRS", "") if not path.strip(): path = f"/usr/local/share{os.pathsep}/usr/share" return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)] @property def site_data_dir(self) -> str: """ :return: data directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled and ``XDG_DATA_DIRS`` is set and a multi path the response is also a multi path separated by the OS path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version`` """ # XDG default for $XDG_DATA_DIRS; only first, if multipath is False dirs = self._site_data_dirs if not self.multipath: return dirs[0] return os.pathsep.join(dirs) @property def user_config_dir(self) -> str: """ :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or ``$XDG_CONFIG_HOME/$appname/$version`` """ path = os.environ.get("XDG_CONFIG_HOME", "") if not path.strip(): path = os.path.expanduser("~/.config") # noqa: PTH111 return self._append_app_name_and_version(path) @property def _site_config_dirs(self) -> list[str]: path = os.environ.get("XDG_CONFIG_DIRS", "") if not path.strip(): path = "/etc/xdg" return [self._append_app_name_and_version(p) for p in path.split(os.pathsep)] @property def site_config_dir(self) -> str: """ :return: config directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is enabled and ``XDG_CONFIG_DIRS`` is set and a multi path the response is also a multi path separated by the OS path separator), e.g. ``/etc/xdg/$appname/$version`` """ # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False dirs = self._site_config_dirs if not self.multipath: return dirs[0] return os.pathsep.join(dirs) @property def user_cache_dir(self) -> str: """ :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or ``~/$XDG_CACHE_HOME/$appname/$version`` """ path = os.environ.get("XDG_CACHE_HOME", "") if not path.strip(): path = os.path.expanduser("~/.cache") # noqa: PTH111 return self._append_app_name_and_version(path) @property def site_cache_dir(self) -> str: """:return: cache directory shared by users, e.g. ``/var/cache/$appname/$version``""" return self._append_app_name_and_version("/var/cache") @property def user_state_dir(self) -> str: """ :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or ``$XDG_STATE_HOME/$appname/$version`` """ path = os.environ.get("XDG_STATE_HOME", "") if not path.strip(): path = os.path.expanduser("~/.local/state") # noqa: PTH111 return self._append_app_name_and_version(path) @property def user_log_dir(self) -> str: """:return: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it""" path = self.user_state_dir if self.opinion: path = os.path.join(path, "log") # noqa: PTH118 self._optionally_create_directory(path) return path @property def user_documents_dir(self) -> str: """:return: documents directory tied to the user, e.g. ``~/Documents``""" return _get_user_media_dir("XDG_DOCUMENTS_DIR", "~/Documents") @property def user_downloads_dir(self) -> str: """:return: downloads directory tied to the user, e.g. ``~/Downloads``""" return _get_user_media_dir("XDG_DOWNLOAD_DIR", "~/Downloads") @property def user_pictures_dir(self) -> str: """:return: pictures directory tied to the user, e.g. ``~/Pictures``""" return _get_user_media_dir("XDG_PICTURES_DIR", "~/Pictures") @property def user_videos_dir(self) -> str: """:return: videos directory tied to the user, e.g. ``~/Videos``""" return _get_user_media_dir("XDG_VIDEOS_DIR", "~/Videos") @property def user_music_dir(self) -> str: """:return: music directory tied to the user, e.g. ``~/Music``""" return _get_user_media_dir("XDG_MUSIC_DIR", "~/Music") @property def user_desktop_dir(self) -> str: """:return: desktop directory tied to the user, e.g. ``~/Desktop``""" return _get_user_media_dir("XDG_DESKTOP_DIR", "~/Desktop") @property def user_runtime_dir(self) -> str: """ :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or ``$XDG_RUNTIME_DIR/$appname/$version``. For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/user/$(id -u)/$appname/$version`` if exists, otherwise ``/tmp/runtime-$(id -u)/$appname/$version``, if``$XDG_RUNTIME_DIR`` is not set. """ path = os.environ.get("XDG_RUNTIME_DIR", "") if not path.strip(): if sys.platform.startswith(("freebsd", "openbsd", "netbsd")): path = f"/var/run/user/{getuid()}" if not Path(path).exists(): path = f"/tmp/runtime-{getuid()}" # noqa: S108 else: path = f"/run/user/{getuid()}" return self._append_app_name_and_version(path) @property def site_runtime_dir(self) -> str: """ :return: runtime directory shared by users, e.g. ``/run/$appname/$version`` or \ ``$XDG_RUNTIME_DIR/$appname/$version``. Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will fall back to paths associated to the root user instead of a regular logged-in user if it's not set. If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir` instead. For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set. """ path = os.environ.get("XDG_RUNTIME_DIR", "") if not path.strip(): if sys.platform.startswith(("freebsd", "openbsd", "netbsd")): path = "/var/run" else: path = "/run" return self._append_app_name_and_version(path) @property def site_data_path(self) -> Path: """:return: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``""" return self._first_item_as_path_if_multipath(self.site_data_dir) @property def site_config_path(self) -> Path: """:return: config path shared by the users, returns the first item, even if ``multipath`` is set to ``True``""" return self._first_item_as_path_if_multipath(self.site_config_dir) @property def site_cache_path(self) -> Path: """:return: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``""" return self._first_item_as_path_if_multipath(self.site_cache_dir) def iter_config_dirs(self) -> Iterator[str]: """:yield: all user and site configuration directories.""" yield self.user_config_dir yield from self._site_config_dirs def iter_data_dirs(self) -> Iterator[str]: """:yield: all user and site data directories.""" yield self.user_data_dir yield from self._site_data_dirs def _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str: media_dir = _get_user_dirs_folder(env_var) if media_dir is None: media_dir = os.environ.get(env_var, "").strip() if not media_dir: media_dir = os.path.expanduser(fallback_tilde_path) # noqa: PTH111 return media_dir def _get_user_dirs_folder(key: str) -> str | None: """ Return directory from user-dirs.dirs config file. See https://freedesktop.org/wiki/Software/xdg-user-dirs/. """ user_dirs_config_path = Path(Unix().user_config_dir) / "user-dirs.dirs" if user_dirs_config_path.exists(): parser = ConfigParser() with user_dirs_config_path.open() as stream: # Add fake section header, so ConfigParser doesn't complain parser.read_string(f"[top]\n{stream.read()}") if key not in parser["top"]: return None path = parser["top"][key].strip('"') # Handle relative home paths return path.replace("$HOME", os.path.expanduser("~")) # noqa: PTH111 return None __all__ = [ "Unix", ]
Unix
python
dagster-io__dagster
examples/experimental/assets_yaml_dsl/assets_yaml_dsl/domain_specific_dsl/stocks_dsl.py
{ "start": 1210, "end": 1254 }
class ____(NamedTuple): days: int
Forecast
python
protocolbuffers__protobuf
python/google/protobuf/internal/message_listener.py
{ "start": 477, "end": 1894 }
class ____(object): """Listens for modifications made to a message. Meant to be registered via Message._SetListener(). Attributes: dirty: If True, then calling Modified() would be a no-op. This can be used to avoid these calls entirely in the common case. """ def Modified(self): """Called every time the message is modified in such a way that the parent message may need to be updated. This currently means either: (a) The message was modified for the first time, so the parent message should henceforth mark the message as present. (b) The message's cached byte size became dirty -- i.e. the message was modified for the first time after a previous call to ByteSize(). Therefore the parent should also mark its byte size as dirty. Note that (a) implies (b), since new objects start out with a client cached size (zero). However, we document (a) explicitly because it is important. Modified() will *only* be called in response to one of these two events -- not every time the sub-message is modified. Note that if the listener's |dirty| attribute is true, then calling Modified at the moment would be a no-op, so it can be skipped. Performance- sensitive callers should check this attribute directly before calling since it will be true most of the time. """ raise NotImplementedError
MessageListener
python
PyCQA__pylint
pylint/checkers/refactoring/implicit_booleaness_checker.py
{ "start": 714, "end": 16768 }
class ____(checkers.BaseChecker): """Checks for incorrect usage of comparisons or len() inside conditions. Incorrect usage of len() Pep8 states: For sequences, (strings, lists, tuples), use the fact that empty sequences are false. Yes: if not seq: if seq: No: if len(seq): if not len(seq): Problems detected: * if len(sequence): * if not len(sequence): * elif len(sequence): * elif not len(sequence): * while len(sequence): * while not len(sequence): * assert len(sequence): * assert not len(sequence): * bool(len(sequence)) Incorrect usage of empty literal sequences; (), [], {}, For empty sequences, (dicts, lists, tuples), use the fact that empty sequences are false. Yes: if variable: if not variable No: if variable == empty_literal: if variable != empty_literal: Problems detected: * comparison such as variable == empty_literal: * comparison such as variable != empty_literal: """ name = "refactoring" msgs = { "C1802": ( "Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty", "use-implicit-booleaness-not-len", "Empty sequences are considered false in a boolean context. You can either" " remove the call to 'len' (``if not x``) or compare the length against a" " scalar (``if len(x) > 1``).", {"old_names": [("C1801", "len-as-condition")]}, ), "C1803": ( '"%s" can be simplified to "%s", if it is strictly a sequence, as an empty %s is falsey', "use-implicit-booleaness-not-comparison", "Empty sequences are considered false in a boolean context. Following this" " check blindly in weakly typed code base can create hard to debug issues." " If the value can be something else that is falsey but not a sequence (for" " example ``None``, an empty string, or ``0``) the code will not be " "equivalent.", ), "C1804": ( '"%s" can be simplified to "%s", if it is strictly a string, as an empty string is falsey', "use-implicit-booleaness-not-comparison-to-string", "Empty string are considered false in a boolean context. Following this" " check blindly in weakly typed code base can create hard to debug issues." " If the value can be something else that is falsey but not a string (for" " example ``None``, an empty sequence, or ``0``) the code will not be " "equivalent.", { "default_enabled": False, "old_names": [("C1901", "compare-to-empty-string")], }, ), "C1805": ( '"%s" can be simplified to "%s", if it is strictly an int, as 0 is falsey', "use-implicit-booleaness-not-comparison-to-zero", "0 is considered false in a boolean context. Following this" " check blindly in weakly typed code base can create hard to debug issues." " If the value can be something else that is falsey but not an int (for" " example ``None``, an empty string, or an empty sequence) the code will not be " "equivalent.", {"default_enabled": False, "old_names": [("C2001", "compare-to-zero")]}, ), } options = () _operators = {"!=", "==", "is not", "is"} @utils.only_required_for_messages("use-implicit-booleaness-not-len") def visit_call(self, node: nodes.Call) -> None: # a len(S) call is used inside a test condition # could be if, while, assert or if expression statement # e.g. `if len(S):` if not utils.is_call_of_name(node, "len"): return # the len() call could also be nested together with other # boolean operations, e.g. `if z or len(x):` parent = node.parent while isinstance(parent, nodes.BoolOp): parent = parent.parent # we're finally out of any nested boolean operations so check if # this len() call is part of a test condition if not utils.is_test_condition(node, parent): return len_arg = node.args[0] if isinstance(len_arg, (nodes.ListComp, nodes.SetComp, nodes.DictComp)): # The node is a comprehension as in len([x for x in ...]) self.add_message( "use-implicit-booleaness-not-len", node=node, confidence=HIGH, ) return try: instance = next(len_arg.infer()) except astroid.InferenceError: # Probably undefined-variable, abort check return mother_classes = self.base_names_of_instance(instance) affected_by_pep8 = any( t in mother_classes for t in ("str", "tuple", "list", "set") ) if "range" in mother_classes or ( affected_by_pep8 and not self.instance_has_bool(instance) ): self.add_message( "use-implicit-booleaness-not-len", node=node, confidence=INFERENCE, ) @staticmethod def instance_has_bool(class_def: nodes.ClassDef) -> bool: try: class_def.getattr("__bool__") return True except astroid.AttributeInferenceError: ... return False @utils.only_required_for_messages("use-implicit-booleaness-not-len") def visit_unaryop(self, node: nodes.UnaryOp) -> None: """`not len(S)` must become `not S` regardless if the parent block is a test condition or something else (boolean expression) e.g. `if not len(S):`. """ if ( isinstance(node, nodes.UnaryOp) and node.op == "not" and utils.is_call_of_name(node.operand, "len") ): self.add_message( "use-implicit-booleaness-not-len", node=node, confidence=HIGH ) @utils.only_required_for_messages( "use-implicit-booleaness-not-comparison", "use-implicit-booleaness-not-comparison-to-string", "use-implicit-booleaness-not-comparison-to-zero", ) def visit_compare(self, node: nodes.Compare) -> None: if self.linter.is_message_enabled("use-implicit-booleaness-not-comparison"): self._check_use_implicit_booleaness_not_comparison(node) if self.linter.is_message_enabled( "use-implicit-booleaness-not-comparison-to-zero" ) or self.linter.is_message_enabled( "use-implicit-booleaness-not-comparison-to-str" ): self._check_compare_to_str_or_zero(node) def _check_compare_to_str_or_zero(self, node: nodes.Compare) -> None: # Skip check for chained comparisons if len(node.ops) != 1: return negation_redundant_ops = {"!=", "is not"} # note: nodes.Compare has the left most operand in node.left # while the rest are a list of tuples in node.ops # the format of the tuple is ('compare operator sign', node) # here we squash everything into `ops` to make it easier for processing later ops: list[tuple[str, nodes.NodeNG]] = [("", node.left), *node.ops] iter_ops = iter(ops) all_ops = list(itertools.chain(*iter_ops)) _, left_operand, operator, right_operand = all_ops if operator not in self._operators: return if self.linter.is_message_enabled( "use-implicit-booleaness-not-comparison-to-zero" ): operand = None # 0 ?? X if _is_constant_zero(left_operand): operand = right_operand # X ?? 0 elif _is_constant_zero(right_operand): operand = left_operand if operand is not None: original = ( f"{left_operand.as_string()} {operator} {right_operand.as_string()}" ) suggestion = self._get_suggestion( node, operand.as_string(), operator, negation_redundant_ops ) self.add_message( "use-implicit-booleaness-not-comparison-to-zero", args=(original, suggestion), node=node, confidence=HIGH, ) if self.linter.is_message_enabled( "use-implicit-booleaness-not-comparison-to-str" ): node_name = None # x ?? "" if utils.is_empty_str_literal(left_operand): node_name = right_operand.as_string() # '' ?? X elif utils.is_empty_str_literal(right_operand): node_name = left_operand.as_string() if node_name is not None: suggestion = self._get_suggestion( node, node_name, operator, negation_redundant_ops ) self.add_message( "use-implicit-booleaness-not-comparison-to-string", args=(node.as_string(), suggestion), node=node, confidence=HIGH, ) def _check_use_implicit_booleaness_not_comparison( self, node: nodes.Compare ) -> None: """Check for left side and right side of the node for empty literals.""" # Skip check for chained comparisons if len(node.ops) != 1: return # Check both left-hand side and right-hand side for literals operator, comparator = node.ops[0] is_left_empty_literal = utils.is_base_container( node.left ) or utils.is_empty_dict_literal(node.left) is_right_empty_literal = utils.is_base_container( comparator ) or utils.is_empty_dict_literal(comparator) # If both sides are literals/non-literals, it should be different error. if not (is_left_empty_literal ^ is_right_empty_literal): return # Set target_node to opposite side of literal target_node = node.left if is_right_empty_literal else comparator literal_node = comparator if is_right_empty_literal else node.left # Infer node to check target_instance = utils.safe_infer(target_node) if target_instance is None: return mother_classes = self.base_names_of_instance(target_instance) is_base_comprehension_type = any( t in mother_classes for t in ("tuple", "list", "dict", "set") ) # Only time we bypass check is when target_node is not inherited by # collection literals and have its own __bool__ implementation. if not is_base_comprehension_type and self.instance_has_bool(target_instance): return # No need to check for operator when visiting compare node if operator in {"==", "!=", ">=", ">", "<=", "<"}: self.add_message( "use-implicit-booleaness-not-comparison", args=self._implicit_booleaness_message_args( node, literal_node, operator, target_node ), node=node, confidence=HIGH, ) def _get_node_description(self, node: nodes.NodeNG) -> str: return { nodes.List: "list", nodes.Tuple: "tuple", nodes.Dict: "dict", nodes.Const: "str", }.get(type(node), "iterable") def _implicit_booleaness_message_args( self, node: nodes.Compare, literal_node: nodes.NodeNG, operator: str, target_node: nodes.NodeNG, ) -> tuple[str, str, str]: """Helper to get the right message for "use-implicit-booleaness-not-comparison".""" description = self._get_node_description(literal_node) collection_literal = { "list": "[]", "tuple": "()", "dict": "{}", }.get(description, "iterable") instance_name = "x" match target_node: case nodes.Call(): instance_name = f"{target_node.func.as_string()}(...)" case nodes.Attribute() | nodes.Name(): instance_name = target_node.as_string() original_comparison = f"{instance_name} {operator} {collection_literal}" suggestion = self._get_suggestion(node, instance_name, operator, {"!="}) return original_comparison, suggestion, description def _get_suggestion( self, node: nodes.Compare, name: str, operator: str, negation_redundant_ops: set[str], ) -> str: if operator in negation_redundant_ops: return f"{name}" if self._in_boolean_context(node) else f"bool({name})" return f"not {name}" def _in_boolean_context(self, node: nodes.Compare) -> bool: """Returns True if the comparison is used in a boolean context; False otherwise. A comparison is considered to be in a boolean context when it appears in constructs that evaluate its truthiness directly, such as: - control flow statements (`if`, `while`, `assert`) - ternary expressions (`x if condition else y`) - logical negation (`not`) - comprehension filters (e.g. `[x for x in items if cond]`) - generator expressions passed to `all()` or `any()` - lambdas expressions passed to `filter()` - `bool()` cast - boolean operations `and`, `or` nested within any of the above In contrast, a comparison is not in a boolean context when its result is used as a value, such as when it is assigned to a variable, returned from a function, passed as an argument, or used in an expression that does not depend on its truthiness. """ current, parent = node, node.parent while parent: match parent: case nodes.If() | nodes.While() | nodes.Assert() if ( current is parent.test ): return True case nodes.IfExp() if current is parent.test: return True case nodes.UnaryOp(op="not") if current is parent.operand: return True case nodes.Comprehension() if current in parent.ifs: return True case nodes.GeneratorExp() if ( current is parent.elt and ( utils.is_call_of_name(parent.parent, "all") or utils.is_call_of_name(parent.parent, "any") ) and parent in parent.parent.args ): return True case nodes.Lambda() if ( current is parent.body and utils.is_call_of_name(parent.parent, "filter") and parent in parent.parent.args ): return True case _ if ( utils.is_call_of_name(parent, "bool") and current in parent.args ): return True case nodes.BoolOp() if current in parent.values: current = parent parent = current.parent continue case _: break return False @staticmethod def base_names_of_instance( node: util.UninferableBase | bases.Instance, ) -> list[str]: """Return all names inherited by a class instance or those returned by a function. The inherited names include 'object'. """ if isinstance(node, bases.Instance): return [node.name] + [x.name for x in node.ancestors()] return []
ImplicitBooleanessChecker
python
pytorch__pytorch
tools/gdb/pytorch-gdb.py
{ "start": 643, "end": 1866 }
class ____(gdb.Command): # type: ignore[misc, no-any-unimported] """ Print a human readable representation of the given at::Tensor. Usage: torch-tensor-repr EXP at::Tensor instances do not have a C++ implementation of a repr method: in pytorch, this is done by pure-Python code. As such, torch-tensor-repr internally creates a Python wrapper for the given tensor and call repr() on it. """ # pyrefly: ignore [bad-argument-type] __doc__ = textwrap.dedent(__doc__).strip() def __init__(self) -> None: gdb.Command.__init__( self, "torch-tensor-repr", gdb.COMMAND_USER, gdb.COMPLETE_EXPRESSION ) def invoke(self, args: str, from_tty: bool) -> None: args = gdb.string_to_argv(args) if len(args) != 1: print("Usage: torch-tensor-repr EXP") return name = args[0] with DisableBreakpoints(): res = gdb.parse_and_eval(f"torch::gdb::tensor_repr({name})") print(f"Python-level repr of {name}:") print(res.string()) # torch::gdb::tensor_repr returns a malloc()ed buffer, let's free it gdb.parse_and_eval(f"(void)free({int(res)})")
TensorRepr
python
django-import-export__django-import-export
import_export/results.py
{ "start": 339, "end": 1186 }
class ____: """ Base class representing an Error arising from error during data import. """ def __init__(self, error, row=None, number=None): """ :param error: Instance of an Exception class. :param row: The row as a dict of fields and values (optional). :param number: The row number (optional). """ self.error = error self.row = row self.number = number def __repr__(self): result = f"<Error: {self.error!r}" if self.row is not None: result += f" at row {self.row}" if self.number is not None: result += f" at number {self.number}" result += ">" return result @cached_property def traceback(self): lines = traceback.format_exception(self.error) return "".join(lines)
Error
python
kamyu104__LeetCode-Solutions
Python/find-subarray-with-bitwise-or-closest-to-k.py
{ "start": 102, "end": 853 }
class ____(object): def __init__(self, n): self.__l = 0 self.__n = n self.__count = [0]*n def __iadd__(self, num): self.__l += 1 base = 1 for i in xrange(self.__n): if num&base: self.__count[i] += 1 base <<= 1 return self def __isub__(self, num): self.__l -= 1 base = 1 for i in xrange(self.__n): if num&base: self.__count[i] -= 1 base <<= 1 return self def bit_or(self): num, base = 0, 1 for i in xrange(self.__n): if self.__count[i]: num |= base base <<= 1 return num
BitCount
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 120411, "end": 120597 }
class ____(Numeric[_N]): """The SQL DECIMAL type. .. seealso:: :class:`_types.Numeric` - documentation for the base type. """ __visit_name__ = "DECIMAL"
DECIMAL
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/dynamic.py
{ "start": 3528, "end": 9285 }
class ____(_AbstractCollectionWriter[_T]): """A mixin that expects to be mixing in a Query class with AbstractAppender. """ query_class: Optional[Type[Query[_T]]] = None _order_by_clauses: Tuple[ColumnElement[Any], ...] def __init__( self, attr: _DynamicAttributeImpl, state: InstanceState[_T] ) -> None: Query.__init__( self, # type: ignore[arg-type] attr.target_mapper, None, ) super().__init__(attr, state) @property def session(self) -> Optional[Session]: sess = object_session(self.instance) if sess is not None and sess.autoflush and self.instance in sess: sess.flush() if not orm_util.has_identity(self.instance): return None else: return sess @session.setter def session(self, session: Session) -> None: self.sess = session def _iter(self) -> Union[result.ScalarResult[_T], result.Result[_T]]: sess = self.session if sess is None: state = attributes.instance_state(self.instance) if state.detached: util.warn( "Instance %s is detached, dynamic relationship cannot " "return a correct result. This warning will become " "a DetachedInstanceError in a future release." % (orm_util.state_str(state)) ) return result.IteratorResult( result.SimpleResultMetaData([self.attr.class_.__name__]), iter( self.attr._get_collection_history( attributes.instance_state(self.instance), PassiveFlag.PASSIVE_NO_INITIALIZE, ).added_items ), _source_supports_scalars=True, ).scalars() else: return self._generate(sess)._iter() if TYPE_CHECKING: def __iter__(self) -> Iterator[_T]: ... def __getitem__(self, index: Any) -> Union[_T, List[_T]]: sess = self.session if sess is None: return self.attr._get_collection_history( attributes.instance_state(self.instance), PassiveFlag.PASSIVE_NO_INITIALIZE, ).indexed(index) else: return self._generate(sess).__getitem__(index) # type: ignore[no-any-return] # noqa: E501 def count(self) -> int: sess = self.session if sess is None: return len( self.attr._get_collection_history( attributes.instance_state(self.instance), PassiveFlag.PASSIVE_NO_INITIALIZE, ).added_items ) else: return self._generate(sess).count() def _generate( self, sess: Optional[Session] = None, ) -> Query[_T]: # note we're returning an entirely new Query class instance # here without any assignment capabilities; the class of this # query is determined by the session. instance = self.instance if sess is None: sess = object_session(instance) if sess is None: raise orm_exc.DetachedInstanceError( "Parent instance %s is not bound to a Session, and no " "contextual session is established; lazy load operation " "of attribute '%s' cannot proceed" % (orm_util.instance_str(instance), self.attr.key) ) if self.query_class: query = self.query_class(self.attr.target_mapper, session=sess) else: query = sess.query(self.attr.target_mapper) query._where_criteria = self._where_criteria query._from_obj = self._from_obj query._order_by_clauses = self._order_by_clauses return query def add_all(self, iterator: Iterable[_T]) -> None: """Add an iterable of items to this :class:`_orm.AppenderQuery`. The given items will be persisted to the database in terms of the parent instance's collection on the next flush. This method is provided to assist in delivering forwards-compatibility with the :class:`_orm.WriteOnlyCollection` collection class. .. versionadded:: 2.0 """ self._add_all_impl(iterator) def add(self, item: _T) -> None: """Add an item to this :class:`_orm.AppenderQuery`. The given item will be persisted to the database in terms of the parent instance's collection on the next flush. This method is provided to assist in delivering forwards-compatibility with the :class:`_orm.WriteOnlyCollection` collection class. .. versionadded:: 2.0 """ self._add_all_impl([item]) def extend(self, iterator: Iterable[_T]) -> None: """Add an iterable of items to this :class:`_orm.AppenderQuery`. The given items will be persisted to the database in terms of the parent instance's collection on the next flush. """ self._add_all_impl(iterator) def append(self, item: _T) -> None: """Append an item to this :class:`_orm.AppenderQuery`. The given item will be persisted to the database in terms of the parent instance's collection on the next flush. """ self._add_all_impl([item]) def remove(self, item: _T) -> None: """Remove an item from this :class:`_orm.AppenderQuery`. The given item will be removed from the parent instance's collection on the next flush. """ self._remove_impl(item)
_AppenderMixin
python
rq__rq
rq/registry.py
{ "start": 778, "end": 9055 }
class ____: """ Base implementation of a job registry, implemented in Redis sorted set. Each job is stored as a key in the registry, scored by expiration time (unix timestamp). """ job_class = Job death_penalty_class = UnixSignalDeathPenalty key_template = 'rq:registry:{0}' def __init__( self, name: str = 'default', connection: Optional['Redis'] = None, job_class: Optional[type['Job']] = None, queue: Optional['Queue'] = None, serializer: Optional[Union['Serializer', str]] = None, death_penalty_class: Optional[type[BaseDeathPenalty]] = None, ): if queue: self.name = queue.name self.connection = queue.connection self.serializer = queue.serializer else: self.name = name self.connection = connection # type: ignore[assignment] self.serializer = resolve_serializer(serializer) self.key = self.key_template.format(self.name) self.job_class = job_class if job_class else Job self.death_penalty_class = backend_class(self, 'death_penalty_class', override=death_penalty_class) # type: ignore[assignment] def __len__(self): """Returns the number of jobs in this registry""" return self.count def __eq__(self, other): return ( self.name == other.name and self.connection.connection_pool.connection_kwargs == other.connection.connection_pool.connection_kwargs ) def __contains__(self, item: Any) -> bool: """ Returns a boolean indicating registry contains the given job instance or job id. Args: item (Union[str, Job]): A Job ID or a Job. """ job_id = item if isinstance(item, self.job_class): job_id = item.id return self.connection.zscore(self.key, cast(str, job_id)) is not None @property def count(self) -> int: """Returns the number of jobs in this registry after running cleanup Returns: int: _description_ """ return self.get_job_count(cleanup=True) def get_job_count(self, cleanup=True) -> int: """Returns the number of jobs in this registry after optional cleanup. Args: cleanup (bool, optional): _description_. Defaults to True. Returns: int: _description_ """ if cleanup: self.cleanup() return self.connection.zcard(self.key) def add(self, job: Job, ttl: int = 0, pipeline: Optional['Pipeline'] = None, xx: bool = False) -> int: """Adds a job to a registry with expiry time of now + ttl, unless it's -1 which is set to +inf Args: job (Job): The Job to add, or job_id. ttl (int, optional): The time to live. Defaults to 0. pipeline (Optional['Pipeline'], optional): The Redis Pipeline. Defaults to None. xx (bool, optional): .... Defaults to False. Returns: result (int): The ZADD command result """ score: Union[int, str] = ttl if ttl < 0 else current_timestamp() + ttl if score == -1: score = '+inf' if pipeline is not None: return cast(int, pipeline.zadd(self.key, {job.id: score}, xx=xx)) return self.connection.zadd(self.key, {job.id: score}, xx=xx) def remove(self, job: Union[Job, str], pipeline: Optional['Pipeline'] = None, delete_job: bool = False): """Removes job from registry and deletes it if `delete_job == True` Args: job (Job|str): The Job to remove from the registry, or job_id pipeline (Pipeline|None): The Redis Pipeline. Defaults to None. delete_job (bool, optional): If should delete the job.. Defaults to False. """ connection = pipeline if pipeline is not None else self.connection job_id = job.id if isinstance(job, self.job_class) else job result = connection.zrem(self.key, job_id) if delete_job: if isinstance(job, self.job_class): job_instance = job else: job_instance = Job.fetch(job_id, connection=connection, serializer=self.serializer) job_instance.delete() return result def get_expired_job_ids(self, timestamp: Optional[float] = None): """Returns job ids whose score are less than current timestamp. Returns ids for jobs with an expiry time earlier than timestamp, specified as seconds since the Unix epoch. timestamp defaults to call time if unspecified. """ score = timestamp if timestamp is not None else current_timestamp() expired_jobs = self.connection.zrangebyscore(self.key, 0, score) return [self.parse_job_id(job_id) for job_id in expired_jobs] def get_job_ids(self, start: int = 0, end: int = -1, desc: bool = False, cleanup: bool = True) -> list[str]: """Returns list of all job ids. Args: start (int, optional): start rank. Defaults to 0. end (int, optional): end rank. Defaults to -1. desc (bool, optional): sort in reversed order. Defaults to False. cleanup (bool, optional): whether to perform the cleanup. Defaults to True. Returns: List[str]: list of the job ids in the registry """ if cleanup: self.cleanup() return [self.parse_job_id(job_id) for job_id in self.connection.zrange(self.key, start, end, desc=desc)] def get_queue(self): """Returns Queue object associated with this registry.""" return Queue(self.name, connection=self.connection, serializer=self.serializer) def get_expiration_time(self, job: 'Job') -> datetime: """Returns job's expiration time. Args: job (Job): The Job to get the expiration """ score = self.connection.zscore(self.key, job.id) return datetime.fromtimestamp(score, timezone.utc) # type: ignore[arg-type] def requeue(self, job_or_id: Union['Job', str], at_front: bool = False) -> 'Job': """Requeues the job with the given job ID. Args: job_or_id (Union[&#39;Job&#39;, str]): The Job or the Job ID at_front (bool, optional): If the Job should be put at the front of the queue. Defaults to False. Raises: InvalidJobOperation: If nothing is returned from the `ZREM` operation. Returns: Job: The Requeued Job. """ if isinstance(job_or_id, self.job_class): job = job_or_id serializer = job.serializer else: serializer = self.serializer job = self.job_class.fetch(job_or_id, connection=self.connection, serializer=serializer) result = self.connection.zrem(self.key, job.id) if not result: raise InvalidJobOperation with self.connection.pipeline() as pipeline: queue = Queue(job.origin, connection=self.connection, job_class=self.job_class, serializer=serializer) job.started_at = None job.ended_at = None job._exc_info = '' # TODO: this should be removed job.save() job = queue._enqueue_job(job, pipeline=pipeline, at_front=at_front) pipeline.execute() return job @staticmethod def parse_job_id(entry: str) -> str: """Generic function to retrieve the job id from the stored entry. Some Registries might have a different entry format. Args: entry (str): the entry from the registry Returns: str: the job_id parsed from the registry. """ # base registry only stores job_ids as is. if not isinstance(entry, str): entry = as_text(entry) # type: ignore return entry def cleanup(self, timestamp: Optional[float] = None, exception_handlers: Optional[list] = None): """This method is automatically called by `count()` and `get_job_ids()` methods implemented in BaseRegistry. Base registry doesn't have any special cleanup instructions"""
BaseRegistry
python
plotly__plotly.py
plotly/graph_objs/funnelarea/_stream.py
{ "start": 233, "end": 3526 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "funnelarea" _path_str = "funnelarea.stream" _valid_props = {"maxpoints", "token"} @property def maxpoints(self): """ Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. The 'maxpoints' property is a number and may be specified as: - An int or float in the interval [0, 10000] Returns ------- int|float """ return self["maxpoints"] @maxpoints.setter def maxpoints(self, val): self["maxpoints"] = val @property def token(self): """ The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. The 'token' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["token"] @token.setter def token(self, val): self["token"] = val @property def _prop_descriptions(self): return """\ maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. """ def __init__(self, arg=None, maxpoints=None, token=None, **kwargs): """ Construct a new Stream object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.funnelarea.Stream` maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. Returns ------- Stream """ super().__init__("stream") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.funnelarea.Stream constructor must be a dict or an instance of :class:`plotly.graph_objs.funnelarea.Stream`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("maxpoints", arg, maxpoints) self._set_property("token", arg, token) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Stream
python
kamyu104__LeetCode-Solutions
Python/find-the-maximum-length-of-valid-subsequence-i.py
{ "start": 34, "end": 447 }
class ____(object): def maximumLength(self, nums): """ :type nums: List[int] :type k: int :rtype: int """ k = 2 result = 0 for i in xrange(k): dp = [0]*k for x in nums: dp[x%k] = dp[(i-x)%k]+1 result = max(result, max(dp)) return result # Time: O(n) # Space: O(1) # brute force
Solution
python
viewflow__viewflow
viewflow/workflow/nodes/mixins.py
{ "start": 166, "end": 734 }
class ____(object): """Mixin for an activation of node with NextNodeMixin.""" @Activation.status.transition(source=STATUS.DONE) def create_next(self): if self.flow_task._next: data, seed = {}, None if self.flow_task._task_data: data = self.flow_task._task_data(self) if self.flow_task._task_seed: seed = self.flow_task._task_seed(self) yield self.flow_task._next._create( self, self.task.token, data=data, seed=seed )
NextNodeActivationMixin
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_cond_format21.py
{ "start": 345, "end": 4898 }
class ____(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test writing a worksheet with conditional formatting.""" self.maxDiff = None fh = StringIO() worksheet = Worksheet() worksheet._set_filehandle(fh) worksheet.select() worksheet.write("A1", 1) worksheet.write("A2", 2) worksheet.write("A3", 3) worksheet.write("A4", 4) worksheet.write("A5", 5) worksheet.write("A6", 6) worksheet.write("A7", 7) worksheet.write("A8", 8) worksheet.write("A9", 9) worksheet.write("A10", 10) worksheet.write("A11", 11) worksheet.write("A12", 12) worksheet.conditional_format( "A1:A12", { "type": "data_bar", "min_value": 5, "mid_value": 52, # Should be ignored. "max_value": 90, "min_length": 5, "max_length": 95, "min_type": "num", "mid_type": "percentile", # Should be ignored. "max_type": "percent", "bar_color": "#8DB4E3", }, ) worksheet._assemble_xml_file() exp = _xml_to_list( """ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <dimension ref="A1:A12"/> <sheetViews> <sheetView tabSelected="1" workbookViewId="0"/> </sheetViews> <sheetFormatPr defaultRowHeight="15"/> <sheetData> <row r="1" spans="1:1"> <c r="A1"> <v>1</v> </c> </row> <row r="2" spans="1:1"> <c r="A2"> <v>2</v> </c> </row> <row r="3" spans="1:1"> <c r="A3"> <v>3</v> </c> </row> <row r="4" spans="1:1"> <c r="A4"> <v>4</v> </c> </row> <row r="5" spans="1:1"> <c r="A5"> <v>5</v> </c> </row> <row r="6" spans="1:1"> <c r="A6"> <v>6</v> </c> </row> <row r="7" spans="1:1"> <c r="A7"> <v>7</v> </c> </row> <row r="8" spans="1:1"> <c r="A8"> <v>8</v> </c> </row> <row r="9" spans="1:1"> <c r="A9"> <v>9</v> </c> </row> <row r="10" spans="1:1"> <c r="A10"> <v>10</v> </c> </row> <row r="11" spans="1:1"> <c r="A11"> <v>11</v> </c> </row> <row r="12" spans="1:1"> <c r="A12"> <v>12</v> </c> </row> </sheetData> <conditionalFormatting sqref="A1:A12"> <cfRule type="dataBar" priority="1"> <dataBar minLength="5" maxLength="95"> <cfvo type="num" val="5"/> <cfvo type="percent" val="90"/> <color rgb="FF8DB4E3"/> </dataBar> </cfRule> </conditionalFormatting> <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/> </worksheet> """ ) got = _xml_to_list(fh.getvalue()) self.assertEqual(exp, got)
TestAssembleWorksheet
python
kamyu104__LeetCode-Solutions
Python/count-valid-paths-in-a-tree.py
{ "start": 2188, "end": 3657 }
class ____(object): def countPaths(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n) primes = [] spf = [-1]*(n+1) # the smallest prime factor for i in xrange(2, n+1): if spf[i] == -1: spf[i] = i primes.append(i) for p in primes: if i*p > n or p > spf[i]: break spf[i*p] = p return spf def is_prime(u): return spf[u] == u def dfs(u, p): cnt = [1-is_prime(u+1), is_prime(u+1)] for v in adj[u]: if v == p: continue new_cnt = dfs(v, u) result[0] += cnt[0]*new_cnt[1]+cnt[1]*new_cnt[0] if is_prime(u+1): cnt[1] += new_cnt[0] else: cnt[0] += new_cnt[0] cnt[1] += new_cnt[1] return cnt spf = linear_sieve_of_eratosthenes(n) adj = [[] for _ in xrange(n)] for u, v in edges: u, v = u-1, v-1 adj[u].append(v) adj[v].append(u) result = [0] dfs(0, -1) return result[0] # Time: O(n) # Space: O(n) # number theory, union find
Solution2
python
huggingface__transformers
src/transformers/activations.py
{ "start": 8001, "end": 13245 }
class ____(nn.Module): """ Applies the xIELU activation function introduced in https://arxiv.org/abs/2411.13010 If the user has installed the nickjbrowning/XIELU wheel, we import xIELU CUDA Otherwise, we emit a single warning and use xIELU Python """ def __init__( self, alpha_p_init=0.8, alpha_n_init=0.8, beta=0.5, eps=-1e-6, dtype=torch.bfloat16, with_vector_loads=False, ): super().__init__() self.alpha_p = nn.Parameter(torch.log(torch.expm1(torch.tensor(alpha_p_init, dtype=dtype))).unsqueeze(0)) self.alpha_n = nn.Parameter( torch.log(torch.expm1(torch.tensor(alpha_n_init - beta, dtype=dtype))).unsqueeze(0) ) self.register_buffer("beta", torch.tensor(beta, dtype=dtype)) self.register_buffer("eps", torch.tensor(eps, dtype=dtype)) self.with_vector_loads = with_vector_loads # Temporary until xIELU CUDA fully implemented self._beta_scalar = float(self.beta.detach().cpu().float().item()) self._eps_scalar = float(self.eps.detach().cpu().float().item()) self._xielu_cuda_obj = None try: import xielu.ops # noqa: F401 self._xielu_cuda_obj = torch.classes.xielu.XIELU() msg = "Using experimental xIELU CUDA." try: from torch._dynamo import allow_in_graph self._xielu_cuda_fn = allow_in_graph(self._xielu_cuda) msg += " Enabled torch._dynamo for xIELU CUDA." except Exception as err: msg += f" Could not enable torch._dynamo for xIELU ({err}) - this may result in slower performance." self._xielu_cuda_fn = self._xielu_cuda logger.warning_once(msg) except Exception as err: logger.warning_once( "CUDA-fused xIELU not available (%s) – falling back to a Python version.\n" "For CUDA xIELU (experimental), `pip install git+https://github.com/nickjbrowning/XIELU`", str(err), ) def _xielu_python(self, x: Tensor) -> Tensor: alpha_p = nn.functional.softplus(self.alpha_p) alpha_n = self.beta + nn.functional.softplus(self.alpha_n) return torch.where( x > 0, alpha_p * x * x + self.beta * x, (torch.expm1(torch.min(x, self.eps)) - x) * alpha_n + self.beta * x, ) def _xielu_cuda(self, x: Tensor) -> Tensor: """Firewall function to prevent torch.compile from seeing .item() calls""" original_shape = x.shape # CUDA kernel expects 3D tensors, reshape if needed while x.dim() < 3: x = x.unsqueeze(0) if x.dim() > 3: x = x.view(-1, 1, x.size(-1)) if original_shape != x.shape: logger.warning_once( "Warning: xIELU input tensor expects 3 dimensions but got (shape: %s). Reshaping to (shape: %s).", original_shape, x.shape, ) result = self._xielu_cuda_obj.forward( x, self.alpha_p.to(x.dtype), self.alpha_n.to(x.dtype), # Temporary until xIELU CUDA fully implemented -> self.{beta,eps}.item() self._beta_scalar, self._eps_scalar, self.with_vector_loads, ) return result.view(original_shape) def forward(self, input: Tensor) -> Tensor: if self._xielu_cuda_obj is not None and input.is_cuda: if not is_torchdynamo_compiling(): return self._xielu_cuda_fn(input) else: logger.warning_once("torch._dynamo is compiling, using Python version of xIELU.") return self._xielu_python(input) ACT2CLS = { "gelu": GELUActivation, "gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}), "gelu_fast": FastGELUActivation, "gelu_new": NewGELUActivation, "gelu_python": (GELUActivation, {"use_gelu_python": True}), "gelu_pytorch_tanh": GELUTanh, "gelu_python_tanh": (GELUTanh, {"use_gelu_tanh_python": True}), "gelu_accurate": AccurateGELUActivation, "laplace": LaplaceActivation, "leaky_relu": nn.LeakyReLU, "linear": LinearActivation, "mish": MishActivation, "quick_gelu": QuickGELUActivation, "relu": nn.ReLU, "relu2": ReLUSquaredActivation, "relu6": nn.ReLU6, "sigmoid": nn.Sigmoid, "silu": SiLUActivation, "swish": nn.SiLU, "tanh": nn.Tanh, "prelu": nn.PReLU, "xielu": XIELUActivation, } ACT2FN = ClassInstantier(ACT2CLS) def get_activation(activation_string): if activation_string in ACT2FN: return ACT2FN[activation_string] else: raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}") # For backwards compatibility with: from activations import gelu_python gelu_python = get_activation("gelu_python") gelu_new = get_activation("gelu_new") gelu = get_activation("gelu") gelu_fast = get_activation("gelu_fast") quick_gelu = get_activation("quick_gelu") silu = get_activation("silu") mish = get_activation("mish") linear_act = get_activation("linear")
XIELUActivation
python
chroma-core__chroma
chromadb/api/types.py
{ "start": 57045, "end": 57190 }
class ____(BaseModel): """Configuration for float inverted index.""" model_config = {"extra": "forbid"} pass
FloatInvertedIndexConfig
python
tensorflow__tensorflow
tensorflow/python/ops/tensor_math_operator_overrides_test.py
{ "start": 907, "end": 2080 }
class ____(test.TestCase): def _test_mul_dispatch_factory(self, x, y, expected, name=None): self.assertAllEqual(expected, tmoo._mul_dispatch_factory(x, y, name=name)) def testNonBooleanTensor(self): x = constant_op.constant([1, 2, 3]) y = constant_op.constant([4, 5, 6]) expected = constant_op.constant([4, 10, 18]) self._test_mul_dispatch_factory(x, y, expected) def testBooleanTensor(self): x = constant_op.constant([True, False, True]) y = constant_op.constant([False, True, True]) expected = constant_op.constant([False, False, True]) self._test_mul_dispatch_factory(x, y, expected) def testBooleanMix(self): # Non-boolean tensor is first. x = constant_op.constant([1, 2, 3]) y = constant_op.constant([False, True, True]) expected = constant_op.constant([False, True, True]) self._test_mul_dispatch_factory(x, y, expected) # Boolean tensor is first. x = constant_op.constant([False, True, True]) y = constant_op.constant([1, 2, 3]) expected = constant_op.constant([False, True, True]) self._test_mul_dispatch_factory(x, y, expected) if __name__ == "__main__": test.main()
SortTest
python
joke2k__faker
tests/providers/test_bank.py
{ "start": 13044, "end": 13505 }
class ____: """Test de_CH bank provider""" def test_bban(self, faker, num_samples): for _ in range(num_samples): assert re.fullmatch(r"\d{17}", faker.bban()) def test_iban(self, faker, num_samples): for _ in range(num_samples): iban = faker.iban() assert is_valid_iban(iban) assert iban[:2] == DeChBankProvider.country_code assert re.fullmatch(r"\d{19}", iban[2:])
TestDeCh
python
numba__numba
numba/core/ssa.py
{ "start": 7779, "end": 8714 }
class ____(_BaseHandler): """Find all defs and uses of variable in each block ``states["label"]`` is a int; label of the current block ``states["defs"]`` is a Mapping[str, List[Tuple[ir.Assign, int]]]: - a mapping of the name of the assignee variable to the assignment IR node and the block label. ``states["uses"]`` is a Mapping[Set[int]] """ def on_assign(self, states, assign): # keep track of assignment and the block states["defs"][assign.target.name].append((assign, states["label"])) # keep track of uses for var in assign.list_vars(): k = var.name if k != assign.target.name: states["uses"][k].add(states["label"]) def on_other(self, states, stmt): # keep track of uses for var in stmt.list_vars(): k = var.name states["uses"][k].add(states["label"])
_GatherDefsHandler
python
python-pillow__Pillow
Tests/test_file_libtiff.py
{ "start": 1219, "end": 48065 }
class ____(LibTiffTestCase): def test_version(self) -> None: version = features.version_codec("libtiff") assert version is not None assert re.search(r"\d+\.\d+\.\d+t?$", version) def test_g4_tiff(self, tmp_path: Path) -> None: """Test the ordinary file path load path""" test_file = "Tests/images/hopper_g4_500.tif" with Image.open(test_file) as im: assert im.size == (500, 500) self._assert_noerr(tmp_path, im) def test_g4_large(self, tmp_path: Path) -> None: test_file = "Tests/images/pport_g4.tif" with Image.open(test_file) as im: self._assert_noerr(tmp_path, im) def test_g4_tiff_file(self, tmp_path: Path) -> None: """Testing the string load path""" test_file = "Tests/images/hopper_g4_500.tif" with open(test_file, "rb") as f: with Image.open(f) as im: assert im.size == (500, 500) self._assert_noerr(tmp_path, im) def test_g4_tiff_bytesio(self, tmp_path: Path) -> None: """Testing the stringio loading code path""" test_file = "Tests/images/hopper_g4_500.tif" s = io.BytesIO() with open(test_file, "rb") as f: s.write(f.read()) s.seek(0) with Image.open(s) as im: assert im.size == (500, 500) self._assert_noerr(tmp_path, im) def test_g4_non_disk_file_object(self, tmp_path: Path) -> None: """Testing loading from non-disk non-BytesIO file object""" test_file = "Tests/images/hopper_g4_500.tif" with open(test_file, "rb") as f: data = f.read() class NonBytesIO(io.RawIOBase): def read(self, size: int = -1) -> bytes: nonlocal data if size == -1: size = len(data) result = data[:size] data = data[size:] return result def readable(self) -> bool: return True r = io.BufferedReader(NonBytesIO()) with Image.open(r) as im: assert im.size == (500, 500) self._assert_noerr(tmp_path, im) def test_g4_eq_png(self) -> None: """Checking that we're actually getting the data that we expect""" with Image.open("Tests/images/hopper_bw_500.png") as png: assert_image_equal_tofile(png, "Tests/images/hopper_g4_500.tif") # see https://github.com/python-pillow/Pillow/issues/279 def test_g4_fillorder_eq_png(self) -> None: """Checking that we're actually getting the data that we expect""" with Image.open("Tests/images/g4-fillorder-test.tif") as g4: assert_image_equal_tofile(g4, "Tests/images/g4-fillorder-test.png") def test_g4_write(self, tmp_path: Path) -> None: """Checking to see that the saved image is the same as what we wrote""" test_file = "Tests/images/hopper_g4_500.tif" with Image.open(test_file) as orig: out = tmp_path / "temp.tif" rot = orig.transpose(Image.Transpose.ROTATE_90) assert rot.size == (500, 500) rot.save(out) with Image.open(out) as reread: assert reread.size == (500, 500) self._assert_noerr(tmp_path, reread) assert_image_equal(reread, rot) assert reread.info["compression"] == "group4" assert reread.info["compression"] == orig.info["compression"] assert orig.tobytes() != reread.tobytes() def test_adobe_deflate_tiff(self) -> None: test_file = "Tests/images/tiff_adobe_deflate.tif" with Image.open(test_file) as im: assert im.mode == "RGB" assert im.size == (278, 374) assert im.tile[0][:3] == ("libtiff", (0, 0, 278, 374), 0) im.load() assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png") @pytest.mark.parametrize("legacy_api", (False, True)) def test_write_metadata(self, legacy_api: bool, tmp_path: Path) -> None: """Test metadata writing through libtiff""" f = tmp_path / "temp.tiff" with Image.open("Tests/images/hopper_g4.tif") as img: assert isinstance(img, TiffImagePlugin.TiffImageFile) img.save(f, tiffinfo=img.tag) if legacy_api: original = img.tag.named() else: original = img.tag_v2.named() # PhotometricInterpretation is set from SAVE_INFO, # not the original image. ignored = [ "StripByteCounts", "RowsPerStrip", "PageNumber", "PhotometricInterpretation", ] with Image.open(f) as loaded: assert isinstance(loaded, TiffImagePlugin.TiffImageFile) if legacy_api: reloaded = loaded.tag.named() else: reloaded = loaded.tag_v2.named() for tag, value in itertools.chain(reloaded.items(), original.items()): if tag not in ignored: val = original[tag] if tag.endswith("Resolution"): if legacy_api: assert val[0][0] / val[0][1] == ( 4294967295 / 113653537 ), f"{tag} didn't roundtrip" else: assert val == 37.79000115940079, f"{tag} didn't roundtrip" else: assert val == value, f"{tag} didn't roundtrip" # https://github.com/python-pillow/Pillow/issues/1561 requested_fields = ["StripByteCounts", "RowsPerStrip", "StripOffsets"] for field in requested_fields: assert field in reloaded, f"{field} not in metadata" @pytest.mark.valgrind_known_error(reason="Known invalid metadata") def test_additional_metadata( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: # these should not crash. Seriously dummy data, most of it doesn't make # any sense, so we're running up against limits where we're asking # libtiff to do stupid things. # Get the list of the ones that we should be able to write core_items = { tag: info for tag, info in ((s, TiffTags.lookup(s)) for s in TiffTags.LIBTIFF_CORE) if info.type is not None } # Exclude ones that have special meaning # that we're already testing them with Image.open("Tests/images/hopper_g4.tif") as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) for tag in im.tag_v2: try: del core_items[tag] except KeyError: pass del core_items[320] # colormap is special, tested below # Type codes: # 2: "ascii", # 3: "short", # 4: "long", # 5: "rational", # 12: "double", # Type: dummy value values = { 2: "test", 3: 1, 4: 2**20, 5: TiffImagePlugin.IFDRational(100, 1), 12: 1.05, } new_ifd = TiffImagePlugin.ImageFileDirectory_v2() for tag, info in core_items.items(): assert info.type is not None if info.length == 1: new_ifd[tag] = values[info.type] elif not info.length: new_ifd[tag] = tuple(values[info.type] for _ in range(3)) else: new_ifd[tag] = tuple(values[info.type] for _ in range(info.length)) # Extra samples really doesn't make sense in this application. del new_ifd[338] out = tmp_path / "temp.tif" monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True) im.save(out, tiffinfo=new_ifd) @pytest.mark.parametrize("libtiff", (True, False)) def test_custom_metadata( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, libtiff: bool ) -> None: monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", libtiff) class Tc(NamedTuple): value: Any type: int supported_by_default: bool custom = { 37000 + k: v for k, v in enumerate( [ Tc(4, TiffTags.SHORT, True), Tc(123456789, TiffTags.LONG, True), Tc(-4, TiffTags.SIGNED_BYTE, False), Tc(-4, TiffTags.SIGNED_SHORT, False), Tc(-123456789, TiffTags.SIGNED_LONG, False), Tc(TiffImagePlugin.IFDRational(4, 7), TiffTags.RATIONAL, True), Tc(4.25, TiffTags.FLOAT, True), Tc(4.25, TiffTags.DOUBLE, True), Tc("custom tag value", TiffTags.ASCII, True), Tc(b"custom tag value", TiffTags.BYTE, True), Tc((4, 5, 6), TiffTags.SHORT, True), Tc((123456789, 9, 34, 234, 219387, 92432323), TiffTags.LONG, True), Tc((-4, 9, 10), TiffTags.SIGNED_BYTE, False), Tc((-4, 5, 6), TiffTags.SIGNED_SHORT, False), Tc( (-123456789, 9, 34, 234, 219387, -92432323), TiffTags.SIGNED_LONG, False, ), Tc((4.25, 5.25), TiffTags.FLOAT, True), Tc((4.25, 5.25), TiffTags.DOUBLE, True), # array of TIFF_BYTE requires bytes instead of tuple for backwards # compatibility Tc(bytes([4]), TiffTags.BYTE, True), Tc(bytes((4, 9, 10)), TiffTags.BYTE, True), ] ) } def check_tags( tiffinfo: TiffImagePlugin.ImageFileDirectory_v2 | dict[int, str], ) -> None: im = hopper() out = tmp_path / "temp.tif" im.save(out, tiffinfo=tiffinfo) with Image.open(out) as reloaded: assert isinstance(reloaded, TiffImagePlugin.TiffImageFile) for tag, value in tiffinfo.items(): reloaded_value = reloaded.tag_v2[tag] if ( isinstance(reloaded_value, TiffImagePlugin.IFDRational) and libtiff ): # libtiff does not support real RATIONALS assert round(abs(float(reloaded_value) - float(value)), 7) == 0 continue assert reloaded_value == value # Test with types ifd = TiffImagePlugin.ImageFileDirectory_v2() for tag, tagdata in custom.items(): ifd[tag] = tagdata.value ifd.tagtype[tag] = tagdata.type check_tags(ifd) # Test without types. This only works for some types, int for example are # always encoded as LONG and not SIGNED_LONG. check_tags( { tag: tagdata.value for tag, tagdata in custom.items() if tagdata.supported_by_default } ) def test_osubfiletype(self, tmp_path: Path) -> None: outfile = tmp_path / "temp.tif" with Image.open("Tests/images/g4_orientation_6.tif") as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) im.tag_v2[OSUBFILETYPE] = 1 im.save(outfile) def test_subifd(self, tmp_path: Path) -> None: outfile = tmp_path / "temp.tif" with Image.open("Tests/images/g4_orientation_6.tif") as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) im.tag_v2[SUBIFD] = 10000 # Should not segfault im.save(outfile) def test_whitepoint_tag( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True) out = tmp_path / "temp.tif" hopper().save(out, tiffinfo={318: (0.3127, 0.3289)}) with Image.open(out) as reloaded: assert isinstance(reloaded, TiffImagePlugin.TiffImageFile) assert reloaded.tag_v2[318] == pytest.approx((0.3127, 0.3289)) # Save tag by default out = tmp_path / "temp2.tif" with Image.open("Tests/images/rdf.tif") as im: im.save(out) with Image.open(out) as reloaded: assert isinstance(reloaded, TiffImagePlugin.TiffImageFile) assert reloaded.tag_v2[318] == pytest.approx((0.3127, 0.3289999)) def test_xmlpacket_tag( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True) out = tmp_path / "temp.tif" hopper().save(out, tiffinfo={700: b"xmlpacket tag"}) with Image.open(out) as reloaded: assert isinstance(reloaded, TiffImagePlugin.TiffImageFile) assert reloaded.tag_v2[700] == b"xmlpacket tag" def test_int_dpi(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: # issue #1765 im = hopper("RGB") out = tmp_path / "temp.tif" monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True) im.save(out, dpi=(72, 72)) with Image.open(out) as reloaded: assert reloaded.info["dpi"] == (72.0, 72.0) def test_g3_compression(self, tmp_path: Path) -> None: with Image.open("Tests/images/hopper_g4_500.tif") as i: out = tmp_path / "temp.tif" i.save(out, compression="group3") with Image.open(out) as reread: assert reread.info["compression"] == "group3" assert_image_equal(reread, i) def test_little_endian(self, tmp_path: Path) -> None: with Image.open("Tests/images/16bit.deflate.tif") as im: assert im.getpixel((0, 0)) == 480 assert im.mode == "I;16" b = im.tobytes() # Bytes are in image native order (little endian) assert b[0] == ord(b"\xe0") assert b[1] == ord(b"\x01") out = tmp_path / "temp.tif" # out = "temp.le.tif" im.save(out) with Image.open(out) as reread: assert reread.info["compression"] == im.info["compression"] assert reread.getpixel((0, 0)) == 480 # UNDONE - libtiff defaults to writing in native endian, so # on big endian, we'll get back mode = 'I;16B' here. def test_big_endian(self, tmp_path: Path) -> None: with Image.open("Tests/images/16bit.MM.deflate.tif") as im: assert im.getpixel((0, 0)) == 480 assert im.mode == "I;16B" b = im.tobytes() # Bytes are in image native order (big endian) assert b[0] == ord(b"\x01") assert b[1] == ord(b"\xe0") out = tmp_path / "temp.tif" im.save(out) with Image.open(out) as reread: assert reread.info["compression"] == im.info["compression"] assert reread.getpixel((0, 0)) == 480 def test_g4_string_info(self, tmp_path: Path) -> None: """Tests String data in info directory""" test_file = "Tests/images/hopper_g4_500.tif" with Image.open(test_file) as orig: assert isinstance(orig, TiffImagePlugin.TiffImageFile) out = tmp_path / "temp.tif" orig.tag[269] = "temp.tif" orig.save(out) with Image.open(out) as reread: assert isinstance(reread, TiffImagePlugin.TiffImageFile) assert "temp.tif" == reread.tag_v2[269] assert "temp.tif" == reread.tag[269][0] def test_12bit_rawmode(self, monkeypatch: pytest.MonkeyPatch) -> None: """Are we generating the same interpretation of the image as Imagemagick is?""" monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open("Tests/images/12bit.cropped.tif") as im: im.load() monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", False) # to make the target -- # convert 12bit.cropped.tif -depth 16 tmp.tif # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0, # so we need to unshift so that the integer values are the same. assert_image_equal_tofile(im, "Tests/images/12in16bit.tif") def test_blur(self, tmp_path: Path) -> None: # test case from irc, how to do blur on b/w image # and save to compressed tif. out = tmp_path / "temp.tif" with Image.open("Tests/images/pport_g4.tif") as im: im = im.convert("L") im = im.filter(ImageFilter.GaussianBlur(4)) im.save(out, compression="tiff_adobe_deflate") assert_image_equal_tofile(im, out) def test_compressions(self, tmp_path: Path) -> None: # Test various tiff compressions and assert similar image content but reduced # file sizes. im = hopper("RGB") out = tmp_path / "temp.tif" im.save(out) size_raw = os.path.getsize(out) for compression in ("packbits", "tiff_lzw"): im.save(out, compression=compression) size_compressed = os.path.getsize(out) assert_image_equal_tofile(im, out) im.save(out, compression="jpeg") size_jpeg = os.path.getsize(out) with Image.open(out) as im2: assert_image_similar(im, im2, 30) im.save(out, compression="jpeg", quality=30) size_jpeg_30 = os.path.getsize(out) assert_image_similar_tofile(im2, out, 30) assert size_raw > size_compressed assert size_compressed > size_jpeg assert size_jpeg > size_jpeg_30 def test_tiff_jpeg_compression(self, tmp_path: Path) -> None: im = hopper("RGB") out = tmp_path / "temp.tif" im.save(out, compression="tiff_jpeg") with Image.open(out) as reloaded: assert reloaded.info["compression"] == "jpeg" def test_tiff_deflate_compression(self, tmp_path: Path) -> None: im = hopper("RGB") out = tmp_path / "temp.tif" im.save(out, compression="tiff_deflate") with Image.open(out) as reloaded: assert reloaded.info["compression"] == "tiff_adobe_deflate" def test_quality(self, tmp_path: Path) -> None: im = hopper("RGB") out = tmp_path / "temp.tif" with pytest.raises(ValueError): im.save(out, compression="tiff_lzw", quality=50) with pytest.raises(ValueError): im.save(out, compression="jpeg", quality=-1) with pytest.raises(ValueError): im.save(out, compression="jpeg", quality=101) with pytest.raises(ValueError): im.save(out, compression="jpeg", quality="good") im.save(out, compression="jpeg", quality=0) im.save(out, compression="jpeg", quality=100) def test_cmyk_save(self, tmp_path: Path) -> None: im = hopper("CMYK") out = tmp_path / "temp.tif" im.save(out, compression="tiff_adobe_deflate") assert_image_equal_tofile(im, out) @pytest.mark.parametrize("im", (hopper("P"), Image.new("P", (1, 1), "#000"))) def test_palette_save( self, im: Image.Image, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: out = tmp_path / "temp.tif" monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True) im.save(out) with Image.open(out) as reloaded: # colormap/palette tag assert isinstance(reloaded, TiffImagePlugin.TiffImageFile) assert len(reloaded.tag_v2[320]) == 768 @pytest.mark.parametrize("compression", ("tiff_ccitt", "group3", "group4")) def test_bw_compression_w_rgb(self, compression: str, tmp_path: Path) -> None: im = hopper("RGB") out = tmp_path / "temp.tif" with pytest.raises(OSError): im.save(out, compression=compression) def test_fp_leak(self) -> None: im: Image.Image | None = Image.open("Tests/images/hopper_g4_500.tif") assert im is not None fn = im.fp.fileno() os.fstat(fn) im.load() # this should close it. with pytest.raises(OSError): os.fstat(fn) im = None # this should force even more closed. with pytest.raises(OSError): os.fstat(fn) with pytest.raises(OSError): os.close(fn) def test_multipage(self, monkeypatch: pytest.MonkeyPatch) -> None: # issue #862 monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open("Tests/images/multipage.tiff") as im: # file is a multipage tiff, 10x10 green, 10x10 red, 20x20 blue assert isinstance(im, TiffImagePlugin.TiffImageFile) im.seek(0) assert im.size == (10, 10) assert im.convert("RGB").getpixel((0, 0)) == (0, 128, 0) assert im.tag.next im.seek(1) assert im.size == (10, 10) assert im.convert("RGB").getpixel((0, 0)) == (255, 0, 0) assert im.tag.next im.seek(2) assert not im.tag.next assert im.size == (20, 20) assert im.convert("RGB").getpixel((0, 0)) == (0, 0, 255) def test_multipage_nframes(self, monkeypatch: pytest.MonkeyPatch) -> None: # issue #862 monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open("Tests/images/multipage.tiff") as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) frames = im.n_frames assert frames == 3 for _ in range(frames): im.seek(0) # Should not raise ValueError: I/O operation on closed file im.load() def test_multipage_seek_backwards(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open("Tests/images/multipage.tiff") as im: im.seek(1) im.load() im.seek(0) assert im.convert("RGB").getpixel((0, 0)) == (0, 128, 0) def test__next(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open("Tests/images/hopper.tif") as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) assert not im.tag.next im.load() assert not im.tag.next def test_4bit(self, monkeypatch: pytest.MonkeyPatch) -> None: # Arrange test_file = "Tests/images/hopper_gray_4bpp.tif" original = hopper("L") # Act monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open(test_file) as im: # Assert assert im.size == (128, 128) assert im.mode == "L" assert_image_similar(im, original, 7.3) def test_gray_semibyte_per_pixel(self) -> None: test_files = ( ( 24.8, # epsilon ( # group "Tests/images/tiff_gray_2_4_bpp/hopper2.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2I.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2R.tif", "Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif", ), ), ( 7.3, # epsilon ( # group "Tests/images/tiff_gray_2_4_bpp/hopper4.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4I.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4R.tif", "Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif", ), ), ) original = hopper("L") for epsilon, group in test_files: with Image.open(group[0]) as im: assert im.size == (128, 128) assert im.mode == "L" assert_image_similar(im, original, epsilon) for file in group[1:]: with Image.open(file) as im2: assert im2.size == (128, 128) assert im2.mode == "L" assert_image_equal(im, im2) def test_save_bytesio(self, monkeypatch: pytest.MonkeyPatch) -> None: # PR 1011 # Test TIFF saving to io.BytesIO() object. monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True) monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) # Generate test image pilim = hopper() def save_bytesio(compression: str | None = None) -> None: buffer_io = io.BytesIO() pilim.save(buffer_io, format="tiff", compression=compression) buffer_io.seek(0) with Image.open(buffer_io) as saved_im: assert_image_similar(pilim, saved_im, 0) save_bytesio() save_bytesio("raw") save_bytesio("packbits") save_bytesio("tiff_lzw") def test_save_ycbcr(self, tmp_path: Path) -> None: im = hopper("YCbCr") outfile = tmp_path / "temp.tif" im.save(outfile, compression="jpeg") with Image.open(outfile) as reloaded: assert isinstance(reloaded, TiffImagePlugin.TiffImageFile) assert reloaded.tag_v2[530] == (1, 1) assert reloaded.tag_v2[532] == (0, 255, 128, 255, 128, 255) def test_exif_ifd(self) -> None: out = io.BytesIO() with Image.open("Tests/images/tiff_adobe_deflate.tif") as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) assert im.tag_v2[34665] == 125456 im.save(out, "TIFF") with Image.open(out) as reloaded: assert isinstance(reloaded, TiffImagePlugin.TiffImageFile) assert 34665 not in reloaded.tag_v2 im.save(out, "TIFF", tiffinfo={34665: 125456}) with Image.open(out) as reloaded: assert isinstance(reloaded, TiffImagePlugin.TiffImageFile) assert reloaded.tag_v2[34665] == 125456 def test_crashing_metadata( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: # issue 1597 with Image.open("Tests/images/rdf.tif") as im: out = tmp_path / "temp.tif" monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True) # this shouldn't crash im.save(out, format="TIFF") def test_page_number_x_0(self, tmp_path: Path) -> None: # Issue 973 # Test TIFF with tag 297 (Page Number) having value of 0 0. # The first number is the current page number. # The second is the total number of pages, zero means not available. outfile = tmp_path / "temp.tif" # Created by printing a page in Chrome to PDF, then: # /usr/bin/gs -q -sDEVICE=tiffg3 -sOutputFile=total-pages-zero.tif # -dNOPAUSE /tmp/test.pdf -c quit infile = "Tests/images/total-pages-zero.tif" with Image.open(infile) as im: # Should not divide by zero im.save(outfile) def test_fd_duplication(self, tmp_path: Path) -> None: # https://github.com/python-pillow/Pillow/issues/1651 tmpfile = tmp_path / "temp.tif" with open(tmpfile, "wb") as f: with open("Tests/images/g4-multi.tiff", "rb") as src: f.write(src.read()) im = Image.open(tmpfile) assert isinstance(im, TiffImagePlugin.TiffImageFile) im.n_frames im.close() # Should not raise PermissionError. os.remove(tmpfile) def test_read_icc(self, monkeypatch: pytest.MonkeyPatch) -> None: with Image.open("Tests/images/hopper.iccprofile.tif") as img: icc = img.info.get("icc_profile") assert icc is not None monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open("Tests/images/hopper.iccprofile.tif") as img: icc_libtiff = img.info.get("icc_profile") assert icc_libtiff is not None assert icc == icc_libtiff @pytest.mark.parametrize("libtiff", (True, False)) def test_write_icc( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, libtiff: bool ) -> None: monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", libtiff) with Image.open("Tests/images/hopper.iccprofile.tif") as img: icc_profile = img.info["icc_profile"] out = tmp_path / "temp.tif" img.save(out, icc_profile=icc_profile) with Image.open(out) as reloaded: assert icc_profile == reloaded.info["icc_profile"] def test_multipage_compression(self) -> None: with Image.open("Tests/images/compression.tif") as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) im.seek(0) assert im._compression == "tiff_ccitt" assert im.size == (10, 10) im.seek(1) assert im._compression == "packbits" assert im.size == (10, 10) im.load() im.seek(0) assert im._compression == "tiff_ccitt" assert im.size == (10, 10) im.load() def test_save_tiff_with_jpegtables(self, tmp_path: Path) -> None: # Arrange outfile = tmp_path / "temp.tif" # Created with ImageMagick: convert hopper.jpg hopper_jpg.tif # Contains JPEGTables (347) tag infile = "Tests/images/hopper_jpg.tif" with Image.open(infile) as im: # Act / Assert # Should not raise UnicodeDecodeError or anything else im.save(outfile) def test_16bit_RGB_tiff(self) -> None: with Image.open("Tests/images/tiff_16bit_RGB.tiff") as im: assert im.mode == "RGB" assert im.size == (100, 40) assert im.tile, [ ( "libtiff", (0, 0, 100, 40), 0, ("RGB;16N", "tiff_adobe_deflate", False, 8), ) ] im.load() assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGB_target.png") def test_16bit_RGBa_tiff(self) -> None: with Image.open("Tests/images/tiff_16bit_RGBa.tiff") as im: assert im.mode == "RGBA" assert im.size == (100, 40) assert im.tile, [ ("libtiff", (0, 0, 100, 40), 0, ("RGBa;16N", "tiff_lzw", False, 38236)) ] im.load() assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGBa_target.png") @skip_unless_feature("jpg") def test_gimp_tiff(self) -> None: # Read TIFF JPEG images from GIMP [@PIL168] filename = "Tests/images/pil168.tif" with Image.open(filename) as im: assert im.mode == "RGB" assert im.size == (256, 256) assert im.tile == [ ("libtiff", (0, 0, 256, 256), 0, ("RGB", "jpeg", False, 5122)) ] im.load() assert_image_equal_tofile(im, "Tests/images/pil168.png") def test_sampleformat(self) -> None: # https://github.com/python-pillow/Pillow/issues/1466 with Image.open("Tests/images/copyleft.tiff") as im: assert im.mode == "RGB" assert_image_equal_tofile(im, "Tests/images/copyleft.png", mode="RGB") def test_sampleformat_write( self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: im = Image.new("F", (1, 1)) out = tmp_path / "temp.tif" monkeypatch.setattr(TiffImagePlugin, "WRITE_LIBTIFF", True) im.save(out) with Image.open(out) as reloaded: assert reloaded.mode == "F" assert reloaded.getexif()[SAMPLEFORMAT] == 3 def test_lzma(self, capfd: pytest.CaptureFixture[str]) -> None: try: with Image.open("Tests/images/hopper_lzma.tif") as im: assert im.mode == "RGB" assert im.size == (128, 128) assert im.format == "TIFF" with hopper() as im2: assert_image_similar(im, im2, 5) except OSError: captured = capfd.readouterr() if "LZMA compression support is not configured" in captured.err: pytest.skip("LZMA compression support is not configured") sys.stdout.write(captured.out) sys.stderr.write(captured.err) raise def test_webp(self, capfd: pytest.CaptureFixture[str]) -> None: try: with Image.open("Tests/images/hopper_webp.tif") as im: assert im.mode == "RGB" assert im.size == (128, 128) assert im.format == "TIFF" assert_image_similar_tofile(im, "Tests/images/hopper_webp.png", 1) except OSError: captured = capfd.readouterr() if "WEBP compression support is not configured" in captured.err: pytest.skip("WEBP compression support is not configured") if ( "Compression scheme 50001 strip decoding is not implemented" in captured.err ): pytest.skip( "Compression scheme 50001 strip decoding is not implemented" ) sys.stdout.write(captured.out) sys.stderr.write(captured.err) raise def test_lzw(self) -> None: with Image.open("Tests/images/hopper_lzw.tif") as im: assert im.mode == "RGB" assert im.size == (128, 128) assert im.format == "TIFF" im2 = hopper() assert_image_similar(im, im2, 5) def test_strip_cmyk_jpeg(self) -> None: infile = "Tests/images/tiff_strip_cmyk_jpeg.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/pil_sample_cmyk.jpg", 0.5) def test_strip_cmyk_16l_jpeg(self) -> None: infile = "Tests/images/tiff_strip_cmyk_16l_jpeg.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/pil_sample_cmyk.jpg", 0.5) @mark_if_feature_version( pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing" ) def test_strip_ycbcr_jpeg_2x2_sampling(self) -> None: infile = "Tests/images/tiff_strip_ycbcr_jpeg_2x2_sampling.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/flower.jpg", 1.2) @mark_if_feature_version( pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing" ) def test_strip_ycbcr_jpeg_1x1_sampling(self) -> None: infile = "Tests/images/tiff_strip_ycbcr_jpeg_1x1_sampling.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/flower2.jpg", 0.01) def test_tiled_cmyk_jpeg(self) -> None: infile = "Tests/images/tiff_tiled_cmyk_jpeg.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/pil_sample_cmyk.jpg", 0.5) @mark_if_feature_version( pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing" ) def test_tiled_ycbcr_jpeg_1x1_sampling(self) -> None: infile = "Tests/images/tiff_tiled_ycbcr_jpeg_1x1_sampling.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/flower2.jpg", 0.01) @mark_if_feature_version( pytest.mark.valgrind_known_error, "libjpeg_turbo", "2.0", reason="Known Failing" ) def test_tiled_ycbcr_jpeg_2x2_sampling(self) -> None: infile = "Tests/images/tiff_tiled_ycbcr_jpeg_2x2_sampling.tif" with Image.open(infile) as im: assert_image_similar_tofile(im, "Tests/images/flower.jpg", 1.5) def test_strip_planar_rgb(self) -> None: # gdal_translate -co TILED=no -co INTERLEAVE=BAND -co COMPRESS=LZW \ # tiff_strip_raw.tif tiff_strip_planar_lzw.tiff infile = "Tests/images/tiff_strip_planar_lzw.tiff" with Image.open(infile) as im: assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png") def test_tiled_planar_rgb(self) -> None: # gdal_translate -co TILED=yes -co INTERLEAVE=BAND -co COMPRESS=LZW \ # tiff_tiled_raw.tif tiff_tiled_planar_lzw.tiff infile = "Tests/images/tiff_tiled_planar_lzw.tiff" with Image.open(infile) as im: assert_image_equal_tofile(im, "Tests/images/tiff_adobe_deflate.png") def test_tiled_planar_16bit_RGB(self) -> None: # gdal_translate -co TILED=yes -co INTERLEAVE=BAND -co COMPRESS=LZW \ # tiff_16bit_RGB.tiff tiff_tiled_planar_16bit_RGB.tiff with Image.open("Tests/images/tiff_tiled_planar_16bit_RGB.tiff") as im: assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGB_target.png") def test_strip_planar_16bit_RGB(self) -> None: # gdal_translate -co TILED=no -co INTERLEAVE=BAND -co COMPRESS=LZW \ # tiff_16bit_RGB.tiff tiff_strip_planar_16bit_RGB.tiff with Image.open("Tests/images/tiff_strip_planar_16bit_RGB.tiff") as im: assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGB_target.png") def test_tiled_planar_16bit_RGBa(self) -> None: # gdal_translate -co TILED=yes \ # -co INTERLEAVE=BAND -co COMPRESS=LZW -co ALPHA=PREMULTIPLIED \ # tiff_16bit_RGBa.tiff tiff_tiled_planar_16bit_RGBa.tiff with Image.open("Tests/images/tiff_tiled_planar_16bit_RGBa.tiff") as im: assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGBa_target.png") def test_strip_planar_16bit_RGBa(self) -> None: # gdal_translate -co TILED=no \ # -co INTERLEAVE=BAND -co COMPRESS=LZW -co ALPHA=PREMULTIPLIED \ # tiff_16bit_RGBa.tiff tiff_strip_planar_16bit_RGBa.tiff with Image.open("Tests/images/tiff_strip_planar_16bit_RGBa.tiff") as im: assert_image_equal_tofile(im, "Tests/images/tiff_16bit_RGBa_target.png") @pytest.mark.parametrize("compression", (None, "jpeg")) def test_block_tile_tags(self, compression: str | None, tmp_path: Path) -> None: im = hopper() out = tmp_path / "temp.tif" tags = { TiffImagePlugin.TILEWIDTH: 256, TiffImagePlugin.TILELENGTH: 256, TiffImagePlugin.TILEOFFSETS: 256, TiffImagePlugin.TILEBYTECOUNTS: 256, } im.save(out, exif=tags, compression=compression) with Image.open(out) as reloaded: for tag in tags: assert tag not in reloaded.getexif() def test_old_style_jpeg(self) -> None: with Image.open("Tests/images/old-style-jpeg-compression.tif") as im: assert_image_equal_tofile(im, "Tests/images/old-style-jpeg-compression.png") def test_old_style_jpeg_orientation(self) -> None: with open("Tests/images/old-style-jpeg-compression.tif", "rb") as fp: data = fp.read() # Set EXIF Orientation to 2 data = data[:102] + b"\x02" + data[103:] with Image.open(io.BytesIO(data)) as im: im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT) assert_image_equal_tofile(im, "Tests/images/old-style-jpeg-compression.png") def test_open_missing_samplesperpixel(self) -> None: with Image.open( "Tests/images/old-style-jpeg-compression-no-samplesperpixel.tif" ) as im: assert_image_equal_tofile(im, "Tests/images/old-style-jpeg-compression.png") @pytest.mark.parametrize( "file_name, mode, size, tile", [ ( "tiff_wrong_bits_per_sample.tiff", "RGBA", (52, 53), [("raw", (0, 0, 52, 53), 160, ("RGBA", 0, 1))], ), ( "tiff_wrong_bits_per_sample_2.tiff", "RGB", (16, 16), [("raw", (0, 0, 16, 16), 8, ("RGB", 0, 1))], ), ( "tiff_wrong_bits_per_sample_3.tiff", "RGBA", (512, 256), [("libtiff", (0, 0, 512, 256), 0, ("RGBA", "tiff_lzw", False, 48782))], ), ], ) def test_wrong_bits_per_sample( self, file_name: str, mode: str, size: tuple[int, int], tile: list[tuple[str, tuple[int, int, int, int], int, tuple[Any, ...]]], ) -> None: with Image.open("Tests/images/" + file_name) as im: assert im.mode == mode assert im.size == size assert im.tile == tile im.load() def test_no_rows_per_strip(self) -> None: # This image does not have a RowsPerStrip TIFF tag infile = "Tests/images/no_rows_per_strip.tif" with Image.open(infile) as im: im.load() assert im.size == (950, 975) def test_orientation(self) -> None: with Image.open("Tests/images/g4_orientation_1.tif") as base_im: for i in range(2, 9): with Image.open("Tests/images/g4_orientation_" + str(i) + ".tif") as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) assert 274 in im.tag_v2 im.load() assert 274 not in im.tag_v2 assert_image_similar(base_im, im, 0.7) def test_exif_transpose(self) -> None: with Image.open("Tests/images/g4_orientation_1.tif") as base_im: for i in range(2, 9): with Image.open("Tests/images/g4_orientation_" + str(i) + ".tif") as im: im = ImageOps.exif_transpose(im) assert_image_similar(base_im, im, 0.7) @pytest.mark.parametrize( "test_file", [ "Tests/images/old-style-jpeg-compression-no-samplesperpixel.tif", "Tests/images/old-style-jpeg-compression.tif", ], ) def test_buffering(self, test_file: str) -> None: # load exif first with open(test_file, "rb", buffering=1048576) as f: with Image.open(f) as im: exif = dict(im.getexif()) # load image before exif with open(test_file, "rb", buffering=1048576) as f: with Image.open(f) as im2: im2.load() exif_after_load = dict(im2.getexif()) assert exif == exif_after_load @pytest.mark.valgrind_known_error(reason="Backtrace in Python Core") def test_sampleformat_not_corrupted(self) -> None: # Assert that a TIFF image with SampleFormat=UINT tag is not corrupted # when saving to a new file. # Pillow 6.0 fails with "OSError: cannot identify image file". tiff = io.BytesIO( base64.b64decode( b"SUkqAAgAAAAPAP4ABAABAAAAAAAAAAABBAABAAAAAQAAAAEBBAABAAAAAQAA" b"AAIBAwADAAAAwgAAAAMBAwABAAAACAAAAAYBAwABAAAAAgAAABEBBAABAAAA" b"4AAAABUBAwABAAAAAwAAABYBBAABAAAAAQAAABcBBAABAAAACwAAABoBBQAB" b"AAAAyAAAABsBBQABAAAA0AAAABwBAwABAAAAAQAAACgBAwABAAAAAQAAAFMB" b"AwADAAAA2AAAAAAAAAAIAAgACAABAAAAAQAAAAEAAAABAAAAAQABAAEAAAB4" b"nGNgYAAAAAMAAQ==" ) ) out = io.BytesIO() with Image.open(tiff) as im: im.save(out, format="tiff") out.seek(0) with Image.open(out) as im: im.load() def test_realloc_overflow(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open("Tests/images/tiff_overflow_rows_per_strip.tif") as im: # Assert that the error code is IMAGING_CODEC_MEMORY with pytest.raises(OSError, match="decoder error -9"): im.load() @pytest.mark.parametrize("compression", ("tiff_adobe_deflate", "jpeg")) def test_save_multistrip(self, compression: str, tmp_path: Path) -> None: im = hopper("RGB").resize((256, 256)) out = tmp_path / "temp.tif" im.save(out, compression=compression) with Image.open(out) as im: # Assert that there are multiple strips assert isinstance(im, TiffImagePlugin.TiffImageFile) assert len(im.tag_v2[STRIPOFFSETS]) > 1 @pytest.mark.parametrize("argument", (True, False)) def test_save_single_strip( self, argument: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: im = hopper("RGB").resize((256, 256)) out = tmp_path / "temp.tif" if not argument: monkeypatch.setattr(TiffImagePlugin, "STRIP_SIZE", 2**18) arguments: dict[str, str | int] = {"compression": "tiff_adobe_deflate"} if argument: arguments["strip_size"] = 2**18 im.save(out, "TIFF", **arguments) with Image.open(out) as im: assert isinstance(im, TiffImagePlugin.TiffImageFile) assert len(im.tag_v2[STRIPOFFSETS]) == 1 @pytest.mark.parametrize("compression", ("tiff_adobe_deflate", None)) def test_save_zero(self, compression: str | None, tmp_path: Path) -> None: im = Image.new("RGB", (0, 0)) out = tmp_path / "temp.tif" with pytest.raises(SystemError): im.save(out, compression=compression) def test_save_many_compressed(self, tmp_path: Path) -> None: im = hopper() out = tmp_path / "temp.tif" for _ in range(10000): im.save(out, compression="jpeg") @pytest.mark.parametrize( "path, sizes", ( ("Tests/images/hopper.tif", ()), ("Tests/images/child_ifd.tiff", (16, 8)), ("Tests/images/child_ifd_jpeg.tiff", (20,)), ), ) def test_get_child_images(self, path: str, sizes: tuple[int, ...]) -> None: with Image.open(path) as im: ims = im.get_child_images() assert len(ims) == len(sizes) for i, im in enumerate(ims): w = sizes[i] expected = Image.new("RGB", (w, w), "#f00") assert_image_similar(im, expected, 1)
TestFileLibTiff
python
django__django
tests/admin_views/admin.py
{ "start": 9827, "end": 11255 }
class ____(admin.ModelAdmin): actions = ["mail_admin"] action_form = MediaActionForm def delete_queryset(self, request, queryset): SubscriberAdmin.overridden = True super().delete_queryset(request, queryset) @admin.action def mail_admin(self, request, selected): EmailMessage( "Greetings from a ModelAdmin action", "This is the test email from an admin action", "from@example.com", ["to@example.com"], ).send() @admin.action(description="External mail (Another awesome action)") def external_mail(modeladmin, request, selected): EmailMessage( "Greetings from a function action", "This is the test email from a function action", "from@example.com", ["to@example.com"], ).send() @admin.action(description="Redirect to (Awesome action)") def redirect_to(modeladmin, request, selected): from django.http import HttpResponseRedirect return HttpResponseRedirect("/some-where-else/") @admin.action(description="Download subscription") def download(modeladmin, request, selected): buf = StringIO("This is the content of the file") return StreamingHttpResponse(FileWrapper(buf)) @admin.action(description="No permission to run") def no_perm(modeladmin, request, selected): return HttpResponse(content="No permission to perform this action", status=403)
SubscriberAdmin
python
django__django
django/forms/fields.py
{ "start": 12682, "end": 13959 }
class ____(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def to_python(self, value): """ Validate that float() can be called on the input. Return the result of float() or None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = float(value) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not math.isfinite(value): raise ValidationError(self.error_messages["invalid"], code="invalid") def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.step_size is not None: step = str(self.step_size) else: step = "any" attrs.setdefault("step", step) return attrs
FloatField
python
PrefectHQ__prefect
src/prefect/exceptions.py
{ "start": 10715, "end": 10843 }
class ____(PrefectException): """ A base class for exceptions related to infrastructure blocks """
InfrastructureError
python
huggingface__transformers
src/transformers/models/git/configuration_git.py
{ "start": 4368, "end": 9656 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`GitModel`]. It is used to instantiate a GIT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the GIT [microsoft/git-base](https://huggingface.co/microsoft/git-base) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vision_config (`dict`, *optional*): Dictionary of configuration options used to initialize [`GitVisionConfig`]. vocab_size (`int`, *optional*, defaults to 30522): Vocabulary size of the GIT model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`GitModel`]. hidden_size (`int`, *optional*, defaults to 768): Dimensionality of the encoder layers and the pooler layer. num_hidden_layers (`int`, *optional*, defaults to 6): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. intermediate_size (`int`, *optional*, defaults to 3072): Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. hidden_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities. max_position_embeddings (`int`, *optional*, defaults to 1024): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the layer normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). num_image_with_embedding (`int`, *optional*): The number of temporal embeddings to add, in case the model is used for video captioning/VQA. Examples: ```python >>> from transformers import GitConfig, GitModel >>> # Initializing a GIT microsoft/git-base style configuration >>> configuration = GitConfig() >>> # Initializing a model (with random weights) from the microsoft/git-base style configuration >>> model = GitModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "git" sub_configs = {"vision_config": GitVisionConfig} def __init__( self, vision_config=None, vocab_size=30522, hidden_size=768, num_hidden_layers=6, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=1024, initializer_range=0.02, layer_norm_eps=1e-12, pad_token_id=0, use_cache=True, tie_word_embeddings=False, bos_token_id=101, eos_token_id=102, num_image_with_embedding=None, **kwargs, ): if vision_config is None: vision_config = {} logger.info("vision_config is None. initializing the GitVisionConfig with default values.") self.vision_config = GitVisionConfig(**vision_config) self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps self.use_cache = use_cache self.num_image_with_embedding = num_image_with_embedding super().__init__( bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) __all__ = ["GitConfig", "GitVisionConfig"]
GitConfig
python
Lightning-AI__lightning
tests/tests_fabric/utilities/test_data.py
{ "start": 2915, "end": 2962 }
class ____(DataLoader): pass
MyBaseDataLoader
python
django__django
django/contrib/postgres/forms/hstore.py
{ "start": 173, "end": 1787 }
class ____(forms.CharField): """ A field for HStore data which accepts dictionary JSON input. """ widget = forms.Textarea default_error_messages = { "invalid_json": _("Could not load JSON data."), "invalid_format": _("Input must be a JSON dictionary."), } def prepare_value(self, value): if isinstance(value, dict): return json.dumps(value, ensure_ascii=False) return value def to_python(self, value): if not value: return {} if not isinstance(value, dict): try: value = json.loads(value) except json.JSONDecodeError: raise ValidationError( self.error_messages["invalid_json"], code="invalid_json", ) if not isinstance(value, dict): raise ValidationError( self.error_messages["invalid_format"], code="invalid_format", ) # Cast everything to strings for ease. for key, val in value.items(): if val is not None: val = str(val) value[key] = val return value def has_changed(self, initial, data): """ Return True if data differs from initial. """ # For purposes of seeing whether something has changed, None is # the same as an empty dict, if the data or initial value we get # is None, replace it w/ {}. initial_value = self.to_python(initial) return super().has_changed(initial_value, data)
HStoreField