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
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 31208, "end": 31964 }
class ____(TestCase): def test_basic(self): for coefficients, x, expected in [ ([1, -4, -17, 60], 2, 18), ([1, -4, -17, 60], 2.5, 8.125), ([1, -4, -17, 60], Fraction(2, 3), Fraction(1274, 27)), ([1, -4, -17, 60], Decimal('1.75'), Decimal('23.359375')), ...
PolynomialEvalTests
python
pypa__pip
tests/unit/test_configuration.py
{ "start": 7240, "end": 10245 }
class ____(ConfigurationMixin): # Tests for methods to that modify the state of a Configuration def test_no_specific_given_modification(self) -> None: self.configuration.load() with pytest.raises(ConfigurationError): self.configuration.set_value("test.hello", "10") def test_si...
TestConfigurationModification
python
getsentry__sentry
src/sentry/grouping/fingerprinting/utils.py
{ "start": 637, "end": 715 }
class ____(TypedDict): type: str | None value: str | None
_ExceptionInfo
python
walkccc__LeetCode
solutions/3190. Find Minimum Operations to Make All Elements Divisible by Three/3190.py
{ "start": 0, "end": 116 }
class ____: def minimumOperations(self, nums: list[int]) -> int: return sum(num % 3 != 0 for num in nums)
Solution
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 60234, "end": 60393 }
class ____(AnsiFunction[datetime.datetime]): """The localtimestamp() SQL function.""" type = sqltypes.DateTime() inherit_cache = True
localtimestamp
python
pytorch__pytorch
torch/optim/_adafactor.py
{ "start": 383, "end": 28633 }
class ____(Optimizer): def __init__( self, params: ParamsT, lr: Union[float, Tensor] = 1e-2, beta2_decay: float = -0.8, eps: tuple[Optional[float], float] = (None, 1e-3), d: float = 1.0, weight_decay: float = 0.0, *, foreach: Optional[bool] = N...
Adafactor
python
marshmallow-code__marshmallow
examples/inflection_example.py
{ "start": 242, "end": 610 }
class ____(Schema): """Schema that uses camel-case for its external representation and snake-case for its internal representation. """ def on_bind_field(self, field_name, field_obj): field_obj.data_key = camelcase(field_obj.data_key or field_name) # -------------------------------------------...
CamelCaseSchema
python
RaRe-Technologies__gensim
gensim/test/test_fasttext.py
{ "start": 52000, "end": 54376 }
class ____(unittest.TestCase): """Loosely based on the test described here: https://github.com/RaRe-Technologies/gensim/issues/2059#issuecomment-432300777 With a broken hash, vectors for non-ASCII keywords don't match when loaded from a native model. """ def setUp(self): # # ./...
FTHashResultsTest
python
numpy__numpy
numpy/_core/tests/test_cpu_features.py
{ "start": 13782, "end": 15128 }
class ____(AbstractTest): features = [ "SVE", "NEON", "ASIMD", "FPHP", "ASIMDHP", "ASIMDDP", "ASIMDFHM" ] features_groups = { "NEON_FP16": ["NEON", "HALF"], "NEON_VFPV4": ["NEON", "VFPV4"], } def load_flags(self): self.load_flags_cpuinfo("Features") arch = s...
Test_ARM_Features
python
getsentry__sentry
src/sentry/utils/retries.py
{ "start": 274, "end": 743 }
class ____(Exception): def __init__(self, message, exception): super().__init__(message) self.message = message self.exception = exception def __reduce__(self): return RetryException, (self.message, self.exception) def __str__(self) -> str: return force_bytes(self.m...
RetryException
python
pypa__hatch
src/hatch/utils/shells.py
{ "start": 583, "end": 5243 }
class ____: def __init__(self, environment: EnvironmentInterface) -> None: self.environment = environment def enter_cmd(self, path: str, args: Iterable[str], exe_dir: Path) -> None: # noqa: ARG002 self.environment.platform.exit_with_command([path or "cmd", "/k", str(exe_dir / "activate.bat")])...
ShellManager
python
django__django
tests/cache/tests.py
{ "start": 52904, "end": 57334 }
class ____(BaseCacheTests, TestCase): def setUp(self): super().setUp() # LocMem requires a hack to make the other caches # share a data store with the 'normal' cache. caches["prefix"]._cache = cache._cache caches["prefix"]._expire_info = cache._expire_info caches["v...
LocMemCacheTests
python
ray-project__ray
python/ray/tune/tests/test_tune_restore.py
{ "start": 17033, "end": 17334 }
class ____(unittest.TestCase): def testTuneRestore(self): self.assertFalse(ray.is_initialized()) tune.run(MyTrainableClass, name="TestAutoInit", stop={"training_iteration": 1}) self.assertTrue(ray.is_initialized()) def tearDown(self): ray.shutdown()
AutoInitTest
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 32033, "end": 32209 }
class ____(Structure): _fields_ = (("name", lc_str), ("header_addr", p_uint32)) def describe(self): return {"header_addr": int(self.header_addr)}
fvmfile_command
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_exec_order.py
{ "start": 964, "end": 3275 }
class ____(torch.nn.Module): """ Model that supports two computation paths: `layer0` -> `layer1` and `layer0` -> `layer2`. Notably, both `layer1` and `layer2` have 36 elements when flattened, which means that their corresponding all-gathers and reduce-scatters may be silently matched if we do not pe...
Model
python
huggingface__transformers
src/transformers/models/olmo2/modular_olmo2.py
{ "start": 14609, "end": 14764 }
class ____(OlmoForCausalLM): pass __all__ = [ "Olmo2Config", "Olmo2ForCausalLM", "Olmo2Model", "Olmo2PreTrainedModel", ]
Olmo2ForCausalLM
python
PyCQA__pylint
tests/functional/r/regression_02/regression_5408.py
{ "start": 360, "end": 642 }
class ____: sub_class = MySubClass() def get_unpatched_class(cls): return cls def get_unpatched(item): lookup = get_unpatched_class if isinstance(item, type) else lambda item: None return lookup(item) _Child = get_unpatched(MyClass.sub_class.inner_class)
MyClass
python
mitmproxy__pdoc
test/testdata/demo_long.py
{ "start": 5759, "end": 6398 }
class ____: """ This is an example for a dataclass. As usual, you can link to individual properties: `DataDemo.a`. """ a: int """Again, we can document individual properties with docstrings.""" a2: Sequence[str] # This property has a type annotation but is not documented. a3 = "a3"...
DataDemo
python
getsentry__sentry
src/sentry/search/eap/types.py
{ "start": 516, "end": 680 }
class ____: functions: set[str] = field(default_factory=set) attributes: set[str] = field(default_factory=set) @dataclass(frozen=True, kw_only=True)
FieldsACL
python
walkccc__LeetCode
solutions/909. Snakes and Ladders/909.py
{ "start": 0, "end": 699 }
class ____: def snakesAndLadders(self, board: list[list[int]]) -> int: n = len(board) q = collections.deque([1]) seen = set() arr = [0] * (1 + n * n) # 2D -> 1D for i in range(n): for j in range(n): arr[(n - 1 - i) * n + (n - j if (n - i) % 2 == 0 else j + 1)] = board[i][j] st...
Solution
python
jina-ai__jina
tests/unit/orchestrate/deployments/test_deployments.py
{ "start": 8644, "end": 12492 }
class ____(Executor): def __init__(self, runtime_args, *args, **kwargs): super().__init__(*args, **kwargs) self.shard_id = runtime_args['shard_id'] @requests def foo(self, docs: DocumentArray, **kwargs): docs.append(Document(text=str(self.shard_id))) return docs def test_p...
AppendShardExecutor
python
ray-project__ray
python/ray/data/_internal/execution/operators/map_transformer.py
{ "start": 10582, "end": 12349 }
class ____(MapTransformFn): """A batch-to-batch MapTransformFn.""" def __init__( self, batch_fn: MapTransformCallable[DataBatch, DataBatch], *, is_udf: bool = False, batch_size: Optional[int] = None, batch_format: Optional[BatchFormat] = None, zero_copy_b...
BatchMapTransformFn
python
doocs__leetcode
solution/3000-3099/3070.Count Submatrices with Top-Left Element and Sum Less Than k/Solution.py
{ "start": 0, "end": 385 }
class ____: def countSubmatrices(self, grid: List[List[int]], k: int) -> int: s = [[0] * (len(grid[0]) + 1) for _ in range(len(grid) + 1)] ans = 0 for i, row in enumerate(grid, 1): for j, x in enumerate(row, 1): s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1...
Solution
python
redis__redis-py
redis/commands/search/field.py
{ "start": 55, "end": 2123 }
class ____: """ A class representing a field in a document. """ NUMERIC = "NUMERIC" TEXT = "TEXT" WEIGHT = "WEIGHT" GEO = "GEO" TAG = "TAG" VECTOR = "VECTOR" SORTABLE = "SORTABLE" NOINDEX = "NOINDEX" AS = "AS" GEOSHAPE = "GEOSHAPE" INDEX_MISSING = "INDEXMISSING" ...
Field
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/return_in_init.py
{ "start": 99, "end": 187 }
class ____: def __init__(self): return 3 def gen(self): return 5
B
python
pytorch__pytorch
test/inductor/test_cutedsl_template.py
{ "start": 1911, "end": 16383 }
class ____(TestCase): """Test cases for CuteDSL template functionality.""" def test_gen_imports(self): kernel = CuteDSLTemplateKernel( kernel_name="test_kernel", input_nodes=[], output_node=None, ) imports = kernel.gen_imports() self.assertI...
TestCuteDSLTemplate
python
ansible__ansible
lib/ansible/module_utils/facts/system/loadavg.py
{ "start": 256, "end": 740 }
class ____(BaseFactCollector): name = 'loadavg' _fact_ids = set() # type: t.Set[str] def collect(self, module=None, collected_facts=None): facts = {} try: # (0.58, 0.82, 0.98) loadavg = os.getloadavg() facts['loadavg'] = { '1m': loadavg[0...
LoadAvgFactCollector
python
apache__airflow
airflow-e2e-tests/tests/airflow_e2e_tests/basic_tests/test_basic_dag_operations.py
{ "start": 946, "end": 1833 }
class ____: """Test basic DAG functionality using the Airflow REST API.""" airflow_client = AirflowClient() def test_dag_unpause(self): self.airflow_client.un_pause_dag( "example_xcom_test", ) def test_xcom_value(self): resp = self.airflow_client.trigger_dag( ...
TestBasicDagFunctionality
python
django__django
tests/apps/tests.py
{ "start": 1210, "end": 15460 }
class ____(SimpleTestCase): def test_singleton_main(self): """ Only one main registry can exist. """ with self.assertRaises(RuntimeError): Apps(installed_apps=None) def test_ready(self): """ Tests the ready property of the main registry. """ ...
AppsTests
python
streamlit__streamlit
lib/streamlit/components/lib/local_component_registry.py
{ "start": 1069, "end": 3016 }
class ____(BaseComponentRegistry): def __init__(self) -> None: self._components: dict[str, BaseCustomComponent] = {} self._lock = threading.Lock() def __repr__(self) -> str: return util.repr_(self) def register_component(self, component: BaseCustomComponent) -> None: """Reg...
LocalComponentRegistry
python
ipython__ipython
IPython/core/splitinput.py
{ "start": 2822, "end": 5006 }
class ____: """A single line of input and associated info. Includes the following as properties: line The original, raw line continue_prompt Is this line a continuation in a sequence of multiline input? pre Any leading whitespace. esc The escape character(s) in pre o...
LineInfo
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIn1.py
{ "start": 3287, "end": 3322 }
class ____(TypedDict): x: str
TD1
python
getsentry__sentry
tests/sentry/models/test_apitoken.py
{ "start": 791, "end": 7449 }
class ____(TestCase): def test_is_expired(self) -> None: token = ApiToken(expires_at=None) assert not token.is_expired() token = ApiToken(expires_at=timezone.now() + timedelta(days=1)) assert not token.is_expired() token = ApiToken(expires_at=timezone.now() - timedelta(days...
ApiTokenTest
python
sympy__sympy
sympy/printing/tests/test_pycode.py
{ "start": 11335, "end": 19525 }
class ____(Expr): def _numpycode(self, printer): return 'numpy' def _mpmathcode(self, printer): return 'mpmath' def test_printmethod(): obj = CustomPrintedObject() assert NumPyPrinter().doprint(obj) == 'numpy' assert MpmathPrinter().doprint(obj) == 'mpmath' def test_codegen_ast_...
CustomPrintedObject
python
scrapy__scrapy
tests/test_spidermiddleware.py
{ "start": 11338, "end": 11458 }
class ____: def process_spider_output(self, response, result): return
ProcessSpiderOutputNonIterableMiddleware
python
allegroai__clearml
clearml/backend_api/services/v2_9/workers.py
{ "start": 58040, "end": 60187 }
class ____(Response): """ Response of workers.get_metric_keys endpoint. :param categories: List of unique metric categories found in the statistics of the requested workers. :type categories: Sequence[MetricsCategory] """ _service = "workers" _action = "get_metric_keys" _versio...
GetMetricKeysResponse
python
aio-libs__aiohttp
aiohttp/connector.py
{ "start": 60107, "end": 62645 }
class ____(BaseConnector): """Named pipe connector. Only supported by the proactor event loop. See also: https://docs.python.org/3/library/asyncio-eventloop.html path - Windows named pipe path. keepalive_timeout - (optional) Keep-alive timeout. force_close - Set to True to force close and do r...
NamedPipeConnector
python
networkx__networkx
networkx/algorithms/tests/test_reciprocity.py
{ "start": 39, "end": 1296 }
class ____: # test overall reciprocity by passing whole graph def test_reciprocity_digraph(self): DG = nx.DiGraph([(1, 2), (2, 1)]) reciprocity = nx.reciprocity(DG) assert reciprocity == 1.0 # test empty graph's overall reciprocity which will throw an error def test_overall_reci...
TestReciprocity
python
openai__openai-python
src/openai/resources/completions.py
{ "start": 29536, "end": 58207 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCompletionsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://ww...
AsyncCompletions
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 36732, "end": 38987 }
class ____(TypedDict, total=False): type: Required[Literal['time']] strict: bool le: time ge: time lt: time gt: time tz_constraint: Union[Literal['aware', 'naive'], int] microseconds_precision: Literal['truncate', 'error'] ref: str metadata: dict[str, Any] serialization: SerS...
TimeSchema
python
spack__spack
lib/spack/spack/compilers/adaptor.py
{ "start": 6583, "end": 7150 }
class ____(lang.DeprecatedProperty): def __init__(self) -> None: super().__init__(name="compiler") def factory(self, instance, owner) -> CompilerAdaptor: spec = instance.spec if not spec.concrete: raise ValueError("Can only get a compiler for a concrete package.") c...
DeprecatedCompiler
python
doocs__leetcode
solution/2500-2599/2536.Increment Submatrices by One/Solution.py
{ "start": 0, "end": 716 }
class ____: def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]: mat = [[0] * n for _ in range(n)] for x1, y1, x2, y2 in queries: mat[x1][y1] += 1 if x2 + 1 < n: mat[x2 + 1][y1] -= 1 if y2 + 1 < n: mat[x1]...
Solution
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/skill_create_params.py
{ "start": 381, "end": 978 }
class ____(TypedDict, total=False): display_title: Optional[str] """Display title for the skill. This is a human-readable label that is not included in the prompt sent to the model. """ files: Optional[SequenceNotStr[FileTypes]] """Files to upload for the skill. All files must be in t...
SkillCreateParams
python
openai__gym
gym/vector/utils/misc.py
{ "start": 117, "end": 1587 }
class ____: """Wrapper that uses cloudpickle to pickle and unpickle the result.""" def __init__(self, fn: callable): """Cloudpickle wrapper for a function.""" self.fn = fn def __getstate__(self): """Get the state using `cloudpickle.dumps(self.fn)`.""" import cloudpickle ...
CloudpickleWrapper
python
PrefectHQ__prefect
tests/cli/test_typer_utils.py
{ "start": 129, "end": 2194 }
class ____: singular_subcommand = PrefectTyper(name="singular-subcommand") pluralized_subcommand = PrefectTyper(name="pluralized-subcommand") app.add_typer(singular_subcommand) app.add_typer(pluralized_subcommand, aliases=["pluralized-subcommands"]) def test_pluralized_subcommands_have_multiple_val...
TestPrefectTyper
python
pandas-dev__pandas
pandas/tests/indexes/period/methods/test_factorize.py
{ "start": 82, "end": 1425 }
class ____: def test_factorize_period(self): idx1 = PeriodIndex( ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"], freq="M", ) exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp) exp_idx = PeriodIndex(["2014-01", "2014-02", "2014-03"], fre...
TestFactorize
python
catalyst-team__catalyst
catalyst/contrib/datasets/cifar.py
{ "start": 366, "end": 1565 }
class ____(object): def __init__( self, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None, ) -> None: self.transform = transform self.target_transform = target_transform def __call__(self, input: Any, target: Any) -> Tuple[Any, Any]: ...
StandardTransform
python
psf__requests
tests/test_requests.py
{ "start": 1886, "end": 81009 }
class ____: digest_auth_algo = ("MD5", "SHA-256", "SHA-512") def test_entry_points(self): requests.session requests.session().get requests.session().head requests.get requests.head requests.put requests.patch requests.post # Not really an ...
TestRequests
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py
{ "start": 42549, "end": 46467 }
class ____(GoogleCloudBaseOperator): """ Export Redis instance data into a Redis RDB format file in Cloud Storage. In next step, deletes this instance. Redis will continue serving during this operation. .. seealso:: For more information on how to use this operator, take a look at the guid...
CloudMemorystoreExportAndDeleteInstanceOperator
python
huggingface__transformers
examples/modular-transformers/modeling_test_detr.py
{ "start": 21800, "end": 27371 }
class ____(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Here, we add position embeddings to the queries and keys (as explained in the Deformable DETR paper). """ def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0...
TestDetrMultiheadAttention
python
pytransitions__transitions
transitions/extensions/asyncio.py
{ "start": 3942, "end": 6718 }
class ____(Transition): """Representation of an asynchronous transition managed by a ``AsyncMachine`` instance.""" condition_cls = AsyncCondition async def _eval_conditions(self, event_data): res = await event_data.machine.await_all([partial(cond.check, event_data) for cond in self.conditions]) ...
AsyncTransition
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 3898, "end": 18489 }
class ____(NonStrictDataModel): """ :param id: Model id :type id: str :param name: Model name :type name: str :param user: Associated user id :type user: str :param company: Company id :type company: str :param created: Model creation time :type created: datetime.datetime ...
Model
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 11896, "end": 12757 }
class ____(TestOutEdgeDataView): @classmethod def setup_class(cls): cls.G = nx.path_graph(9, create_using=nx.DiGraph()) cls.eview = nx.reportviews.InEdgeView def test_repr(self): ev = self.eview(self.G)(data=True) rep = ( "InEdgeDataView([(0, 1, {}), (1, 2, {}), ...
TestInEdgeDataView
python
pytorch__pytorch
torch/_inductor/autotune_process.py
{ "start": 1466, "end": 7024 }
class ____: """ Class to launch and interact with a benchmarking subprocess. """ @staticmethod def process_main(read_pipe: IO[bytes], write_pipe: IO[bytes]) -> None: """ Entry point for the child process. """ autotuning_log.debug( "Started autotune subpro...
TuningProcess
python
fluentpython__example-code
attic/objects/cards_format.py
{ "start": 1262, "end": 2081 }
class ____(Enum): spades = '\u2660' # U+2660 ♠ BLACK SPADE SUIT diamonds = '\u2662' # U+2662 ♢ WHITE DIAMOND SUIT clubs = '\u2663' # U+2663 ♣ BLACK CLUB SUIT hearts = '\u2661' # U+2661 ♡ WHITE HEART SUIT def format_p(self): return chr(0x2660 + self.value) def format_s(self):...
Suite
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/test_groups.py
{ "start": 587, "end": 2692 }
class ____(TestCase): @property def _config(self): return ( ConfigBuilder() .with_basic_auth_credentials("user@example.com", "password") .with_subdomain("d3v-airbyte") .with_start_date(ab_datetime_now().subtract(timedelta(weeks=104))) .build() ...
TestGroupsStreamFullRefresh
python
giampaolo__psutil
tests/test_memleaks.py
{ "start": 10610, "end": 11052 }
class ____(MemoryLeakTestCase): def test_cmdline_peb_true(self): self.execute(lambda: cext.proc_cmdline(os.getpid(), use_peb=True)) def test_cmdline_peb_false(self): self.execute(lambda: cext.proc_cmdline(os.getpid(), use_peb=False)) # =========================================================...
TestProcessDualImplementation
python
huggingface__transformers
tests/models/phi3/test_modeling_phi3.py
{ "start": 3114, "end": 25419 }
class ____(unittest.TestCase): def test_model_phi3_mini_4k_instruct_logits(self): input_ids = { "input_ids": torch.tensor( [[1212, 318, 281, 1672, 2643, 290, 428, 318, 257, 1332]], dtype=torch.long, device=torch_device ) } model = Phi3ForCausalLM.from...
Phi3IntegrationTest
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 520905, "end": 522638 }
class ____(Response): """ Response of tasks.stopped endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict """ _service = "tasks" _action = "stopped" _version = "2.23" _schema = { ...
StoppedResponse
python
pypa__pip
src/pip/_vendor/pkg_resources/__init__.py
{ "start": 64048, "end": 64940 }
class ____(EggProvider): """Provides access to package resources in the filesystem""" def _has(self, path) -> bool: return os.path.exists(path) def _isdir(self, path) -> bool: return os.path.isdir(path) def _listdir(self, path): return os.listdir(path) def get_resource_st...
DefaultProvider
python
PrefectHQ__prefect
src/prefect/server/orchestration/core_policy.py
{ "start": 51747, "end": 54385 }
class ____(TaskRunOrchestrationRule): """ We do not allow tasks to leave terminal states if: - The task is completed and has a persisted result - The task is going to CANCELLING / PAUSED / CRASHED We reset the run count when a task leaves a terminal state for a non-terminal state which resets t...
HandleTaskTerminalStateTransitions
python
getsentry__sentry
src/sentry/logging/handlers.py
{ "start": 4344, "end": 5048 }
class ____(logging.Filter): """ A logging filter that allows log records where the message contains given substring(s). contains -- a string or list of strings to match """ def __init__(self, contains): if not isinstance(contains, list): contains = [contains] if not...
MessageContainsFilter
python
langchain-ai__langchain
libs/partners/prompty/tests/unit_tests/fake_callback_handler.py
{ "start": 2956, "end": 6171 }
class ____(BaseCallbackHandler, BaseFakeCallbackHandlerMixin): """Fake callback handler for testing.""" def __init__(self) -> None: super().__init__() self.input_prompts = [] @property def ignore_llm(self) -> bool: """Whether to ignore LLM callbacks.""" return self.igno...
FakeCallbackHandler
python
doocs__leetcode
lcp/LCP 51. 烹饪料理/Solution.py
{ "start": 0, "end": 696 }
class ____: def perfectMenu( self, materials: List[int], cookbooks: List[List[int]], attribute: List[List[int]], limit: int, ) -> int: n = len(cookbooks) ans = -1 for mask in range(1 << n): a = b = 0 cnt = [0] * 5 ...
Solution
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/validators/actions/test_webhook.py
{ "start": 386, "end": 3499 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.webhooks_plugin = plugins.get(WebHooksPlugin.slug) self.webhooks_plugin.enable(self.project) # non notification plugin self.trello_plugin = plugins.get(TrelloPlugin.slug) self.trello_plugin.enable(se...
TestWebhookActionValidator
python
jazzband__django-oauth-toolkit
oauth2_provider/migrations/0007_application_post_logout_redirect_uris.py
{ "start": 92, "end": 498 }
class ____(migrations.Migration): dependencies = [ ("oauth2_provider", "0006_alter_application_client_secret"), ] operations = [ migrations.AddField( model_name="application", name="post_logout_redirect_uris", field=models.TextField(blank=True, help_text...
Migration
python
bokeh__bokeh
src/bokeh/core/property/any.py
{ "start": 2347, "end": 3001 }
class ____(Any): """ Accept all values and force reference discovery. """ @property def has_ref(self) -> bool: return True #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #-----...
AnyRef
python
mlflow__mlflow
tests/pyfunc/test_pyfunc_model_with_type_hints.py
{ "start": 9417, "end": 16973 }
class ____(pydantic.BaseModel): custom_field: dict[str, list[str]] messages: list[Message] optional_int: Optional[int] = None # noqa: UP045 int_or_none: int | None = None @pytest.mark.parametrize( ("type_hint", "result_type", "input_example"), [ # scalars # bytes and datetime ...
CustomExample3
python
spack__spack
lib/spack/spack/util/gcs.py
{ "start": 5053, "end": 7464 }
class ____: """GCS Blob object Wraps some blob methods for spack functionality """ def __init__(self, url, client=None): self.url = url if url.scheme != "gs": raise ValueError( "Can not create GCS blob connection with scheme: {SCHEME}".format( ...
GCSBlob
python
astropy__astropy
astropy/extern/ply/lex.py
{ "start": 3883, "end": 22447 }
class ____: def __init__(self): self.lexre = None # Master regular expression. This is a list of # tuples (re, findex) where re is a compiled # regular expression and findex is a list ...
Lexer
python
tensorflow__tensorflow
tensorflow/python/training/momentum_test.py
{ "start": 1373, "end": 27888 }
class ____(test.TestCase): def _update_nesterov_momentum_numpy(self, var, accum, g, lr, momentum): var = var + accum * lr * momentum accum = accum * momentum + g var = var - lr * accum var = var - accum * lr * momentum return var, accum def doTestBasic(self, use_resource=False, use_callable_pa...
MomentumOptimizerTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI045.py
{ "start": 86, "end": 140 }
class ____: def __iter__(self): ...
NoReturn
python
pytorch__pytorch
test/inductor/test_snode_runtime.py
{ "start": 1450, "end": 2480 }
class ____(InductorTestCase): device = DEVICE """ Helper methods to compare runtime estimate against 0. Since this estimate is hardware dependent, stronger comparisons may fail depending on the host's specs. atol/rtol must be provided explicitly with each call, since precision/rel_tol overrides ar...
TestCase
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/psycopg.py
{ "start": 23948, "end": 25030 }
class ____(PGDialect_psycopg): is_async = True supports_statement_cache = True @classmethod def import_dbapi(cls): import psycopg from psycopg.pq import ExecStatus return PsycopgAdaptDBAPI(psycopg, ExecStatus) def _type_info_fetch(self, connection, name): from psyc...
PGDialectAsync_psycopg
python
google__jax
jax/_src/prng.py
{ "start": 4949, "end": 12675 }
class ____(Array): """An array of PRNG keys backed by an RNG implementation. This class lifts the definition of a PRNG, provided in the form of a ``PRNGImpl``, into an array-like pytree class. Instances of this class behave like an array whose base elements are keys, hiding the fact that keys are typically a...
PRNGKeyArray
python
pytorch__pytorch
torch/testing/_internal/distributed/distributed_test.py
{ "start": 10104, "end": 10732 }
class ____(nn.Module): """ A module containing an embedding with different dimension or different # of parameters depending on the rank. """ def __init__(self, rank, diff_num_params=False): super().__init__() embedding_dim = 500 if diff_num_params or rank == 0 else 50 self.e...
EmbeddingNetDifferentParams
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/relativity/relativity.py
{ "start": 25007, "end": 28029 }
class ____(pg.ItemGroup): def __init__(self, clock): pg.ItemGroup.__init__(self) self.size = clock.size self.item = QtWidgets.QGraphicsEllipseItem(QtCore.QRectF(0, 0, self.size, self.size)) tr = QtGui.QTransform.fromTranslate(-self.size*0.5, -self.size*0.5) self.item.setTrans...
ClockItem
python
jmcnamara__XlsxWriter
xlsxwriter/test/table/test_table04.py
{ "start": 481, "end": 1956 }
class ____(unittest.TestCase): """ Test assembling a complete Table file. """ def test_assemble_xml_file(self): """Test writing a table""" self.maxDiff = None worksheet = Worksheet() worksheet.worksheet_meta = WorksheetMeta() worksheet.str_table = SharedStringT...
TestAssembleTable
python
huggingface__transformers
src/transformers/models/longcat_flash/modeling_longcat_flash.py
{ "start": 24013, "end": 25118 }
class ____(PreTrainedModel): config: LongcatFlashConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["LongcatFlashDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_a...
LongcatFlashPreTrainedModel
python
kamyu104__LeetCode-Solutions
Python/booking-concert-tickets-in-groups.py
{ "start": 1508, "end": 2949 }
class ____(object): def __init__(self, n, m): """ :type n: int :type m: int """ self.__st = SegmentTree(n, build_fn=lambda _: [m]*2, query_fn=lambda x, y: y if x is None else x if y is None else [max(x[0], y[0])...
BookMyShow
python
huggingface__transformers
src/transformers/models/sew_d/modeling_sew_d.py
{ "start": 62835, "end": 67790 }
class ____(SEWDPreTrainedModel): def __init__(self, config): super().__init__(config) if hasattr(config, "add_adapter") and config.add_adapter: raise ValueError( "Sequence classification does not support the use of SEWD adapters (config.add_adapter=True)" ) ...
SEWDForSequenceClassification
python
coleifer__peewee
tests/sql.py
{ "start": 82935, "end": 83384 }
class ____(BaseTestCase): def test_parentheses_functions(self): expr = (User.c.income + 100) expr2 = expr * expr query = User.select(fn.sum(expr), fn.avg(expr2)) self.assertSQL(query, ( 'SELECT sum("t1"."income" + ?), ' 'avg(("t1"."income" + ?) * ("t1"."income...
TestExpressionSQL
python
google__jax
tests/array_api_test.py
{ "start": 3581, "end": 4187 }
class ____(absltest.TestCase): """Smoke test for the array API.""" def test_main_namespace(self): self.assertContainsSubset(MAIN_NAMESPACE, names(ARRAY_API_NAMESPACE)) def test_linalg_namespace(self): self.assertContainsSubset(LINALG_NAMESPACE, names(ARRAY_API_NAMESPACE.linalg)) def test_fft_namespac...
ArrayAPISmokeTest
python
django__django
tests/backends/base/test_base.py
{ "start": 6200, "end": 10775 }
class ____(TestCase): @staticmethod def call_execute(connection, params=None): ret_val = "1" if params is None else "%s" sql = "SELECT " + ret_val + connection.features.bare_select_suffix with connection.cursor() as cursor: cursor.execute(sql, params) def call_executeman...
ExecuteWrapperTests
python
protocolbuffers__protobuf
python/google/protobuf/internal/containers.py
{ "start": 19978, "end": 20667 }
class ____: """A parsed unknown field.""" # Disallows assignment to other attributes. __slots__ = ['_field_number', '_wire_type', '_data'] def __init__(self, field_number, wire_type, data): self._field_number = field_number self._wire_type = wire_type self._data = data return def __lt__(sel...
_UnknownField
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 6244, "end": 7124 }
class ____(ModelOutput): r""" embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when model is initialized with `with_projection=True`): The embeddings obtained by applying the projection layer to the pooler_output. last_hidden_state (`torch.FloatTensor` of shape `...
ClvpEncoderOutput
python
huggingface__transformers
src/transformers/models/bitnet/modular_bitnet.py
{ "start": 4054, "end": 5781 }
class ____(LlamaForCausalLM): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = None _pp_plan = None def forward( self, **super_kwargs, ) -> CausalLMOutputWithPast: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`...
BitNetForCausalLM
python
huggingface__transformers
tests/models/dinat/test_modeling_dinat.py
{ "start": 7092, "end": 11955 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( DinatModel, DinatForImageClassification, DinatBackbone, ) if is_torch_available() else () ) pipeline_model_mapping = ( {"image-feature-ext...
DinatModelTest
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_dataflow.py
{ "start": 65548, "end": 69595 }
class ____: @pytest.mark.parametrize( "log", [ pytest.param(APACHE_BEAM_V_2_14_0_JAVA_SDK_LOG, id="apache-beam-2.14.0-JDK"), pytest.param(APACHE_BEAM_V_2_22_0_JAVA_SDK_LOG, id="apache-beam-2.22.0-JDK"), pytest.param(APACHE_BEAM_V_2_58_1_JAVA_SDK_LOG, id="apache-be...
TestDataflow
python
Netflix__metaflow
metaflow/exception.py
{ "start": 249, "end": 1275 }
class ____(Exception): def __init__(self, exc=None): if exc is not None: self.exception = str(exc) self.type = "%s.%s" % (exc.__class__.__module__, exc.__class__.__name__) if sys.exc_info()[0] is None: self.stacktrace = None else: ...
MetaflowExceptionWrapper
python
getsentry__sentry
tests/sentry/rules/processing/test_delayed_processing.py
{ "start": 21393, "end": 25499 }
class ____(TestCase): def setUp(self) -> None: self.organization = self.create_organization() self.project = self.create_project() self.environment = self.create_environment() self.rule1: Rule = self.create_project_rule( project=self.project, condition_data=[...
GetRulesToFireTest
python
pytorch__pytorch
test/quantization/core/test_quantized_module.py
{ "start": 79703, "end": 89331 }
class ____(QuantizationTestCase): def _quant_dequant_weight(self, weight, weight_qparams): qscheme = weight_qparams["qscheme"] scale = weight_qparams["scale"] zero_point = weight_qparams["zero_point"] dtype = weight_qparams["dtype"] if qscheme == torch.per_tensor_affine: ...
TestReferenceQuantizedModule
python
doocs__leetcode
solution/3200-3299/3242.Design Neighbor Sum Service/Solution.py
{ "start": 0, "end": 897 }
class ____: def __init__(self, grid: List[List[int]]): self.grid = grid self.d = {} self.dirs = ((-1, 0, 1, 0, -1), (-1, 1, 1, -1, -1)) for i, row in enumerate(grid): for j, x in enumerate(row): self.d[x] = (i, j) def adjacentSum(self, value: int) ->...
NeighborSum
python
pytorch__pytorch
test/dynamo/test_exceptions.py
{ "start": 574, "end": 671 }
class ____(type): def __instancecheck__(cls, instance): return True
CustomExceptionMeta
python
langchain-ai__langchain
libs/partners/openai/langchain_openai/llms/base.py
{ "start": 26799, "end": 30726 }
class ____(BaseOpenAI): """OpenAI completion model integration. Setup: Install `langchain-openai` and set environment variable `OPENAI_API_KEY`. ```bash pip install -U langchain-openai export OPENAI_API_KEY="your-api-key" ``` Key init args — completion params: ...
OpenAI
python
huggingface__transformers
tests/models/dit/test_modeling_dit.py
{ "start": 992, "end": 2038 }
class ____(unittest.TestCase): @slow def test_for_image_classification(self): image_processor = AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip") model = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip") model.to(torch_device...
DiTIntegrationTest
python
agronholm__apscheduler
src/apscheduler/serializers/pickle.py
{ "start": 208, "end": 1119 }
class ____(Serializer): """ Uses the :mod:`pickle` module to (de)serialize objects. As this serialization method is native to Python, it is able to serialize a wide range of types, at the expense of being insecure. Do **not** use this serializer unless you can fully trust the entire system to not h...
PickleSerializer
python
ansible__ansible
test/lib/ansible_test/_internal/host_profiles.py
{ "start": 3837, "end": 5379 }
class ____: """Simple representation of an Ansible inventory.""" host_groups: dict[str, dict[str, dict[str, t.Union[str, int]]]] extra_groups: t.Optional[dict[str, list[str]]] = None @staticmethod def create_single_host(name: str, variables: dict[str, t.Union[str, int]]) -> Inventory: """R...
Inventory
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/unit_tests/test_limit_reducing_error_handler.py
{ "start": 928, "end": 3868 }
class ____: def test_orders_stream_500_error_handling(self, requests_mock): # Mock the events endpoint to prevent NoMockAddress error requests_mock.get( "https://test-shop.myshopify.com/admin/api/2025-01/events.json?filter=Order&verb=destroy", [{"status_code": 200, "json": {"...
TestOrdersLimitReducingErrorHandler
python
ray-project__ray
python/ray/serve/_private/proxy_request_response.py
{ "start": 497, "end": 1126 }
class ____(ABC): """Base ProxyRequest class to use in the common interface among proxies""" @property @abstractmethod def request_type(self) -> str: raise NotImplementedError @property @abstractmethod def method(self) -> str: raise NotImplementedError @property @ab...
ProxyRequest