language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
getsentry__sentry
tests/sentry/snuba/test_discover_query.py
{ "start": 992, "end": 116651 }
class ____(SnubaTestCase, TestCase): def setUp(self) -> None: super().setUp() self.environment = self.create_environment(self.project, name="prod") self.release = self.create_release(self.project, version="first-release") self.now = before_now() self.one_min_ago = before_now(...
DiscoverQueryIntegrationTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructorCallable2.py
{ "start": 355, "end": 551 }
class ____: def __init__(self, x: int) -> None: pass r1 = accepts_callable(Class1) reveal_type(r1, expected_text="(x: int) -> Class1") reveal_type(r1(1), expected_text="Class1")
Class1
python
ray-project__ray
python/ray/data/tests/test_consumption.py
{ "start": 24361, "end": 24845 }
class ____(CSVDatasource): def __init__(self, paths, **csv_datasource_kwargs): super().__init__(paths, **csv_datasource_kwargs) self.counter = Counter.remote() def _read_stream(self, f: "pa.NativeFile", path: str): count = self.counter.increment.remote() if ray.get(count) == 1:...
FlakyCSVDatasource
python
langchain-ai__langchain
libs/text-splitters/tests/unit_tests/test_text_splitters.py
{ "start": 1102, "end": 23196 }
class ____: def bar(): def foo(): def testing_func(): def bar(): """ def test_character_text_splitter() -> None: """Test splitting by character count.""" text = "foo bar baz 123" splitter = CharacterTextSplitter(separator=" ", chunk_size=7, chunk_overlap=3) output = splitter.split_text(text) ...
Foo
python
PrefectHQ__prefect
src/integrations/prefect-docker/prefect_docker/host.py
{ "start": 643, "end": 3854 }
class ____(Block): """ Block used to manage settings for interacting with a Docker host. Attributes: base_url: URL to the Docker server, e.g. `unix:///var/run/docker.sock` or `tcp://127.0.0.1:1234`. If this is not set, the client will be configured from environment variables...
DockerHost
python
doocs__leetcode
solution/0600-0699/0647.Palindromic Substrings/Solution.py
{ "start": 0, "end": 293 }
class ____: def countSubstrings(self, s: str) -> int: ans, n = 0, len(s) for k in range(n * 2 - 1): i, j = k // 2, (k + 1) // 2 while ~i and j < n and s[i] == s[j]: ans += 1 i, j = i - 1, j + 1 return ans
Solution
python
ApeWorX__ape
src/ape/types/private_mempool.py
{ "start": 2816, "end": 3170 }
class ____(BaseModel): """ A new signed transaction. """ model_config = ConfigDict(populate_by_name=True) tx: HexBytes """ Bytes of the signed transaction. """ can_revert: bool = Field(alias="canRevert") """ If true, the transaction can revert without the bundle being cons...
BundleTxItem
python
google__pytype
pytype/pytd/printer.py
{ "start": 1339, "end": 4001 }
class ____: """Imports tracker.""" def __init__(self): self.track_imports = True self._typing = _TypingImports() self._direct_imports: dict[_AliasType, _NameType] = {} self._from_imports: dict[_NameType, dict[_AliasType, _NameType]] = {} # Map from fully qualified import name to alias self....
_Imports
python
getsentry__sentry
tests/sentry/middleware/test_ratelimit_middleware.py
{ "start": 10603, "end": 12809 }
class ____(TestCase): def test_default_rate_limit_values(self) -> None: """Ensure that the default rate limits are called for endpoints without overrides""" class TestEndpoint(Endpoint): pass view = TestEndpoint.as_view() rate_limit_config = get_rate_limit_config(view.v...
TestGetRateLimitValue
python
mwaskom__seaborn
tests/test_regression.py
{ "start": 15807, "end": 23576 }
class ____: rs = np.random.RandomState(56) df = pd.DataFrame(dict(x=rs.randn(90), y=rs.randn(90) + 5, z=rs.randint(0, 1, 90), g=np.repeat(list("abc"), 30), h=np.tile(list("xy"), 45), ...
TestRegressionPlots
python
allegroai__clearml
clearml/backend_api/services/v2_23/projects.py
{ "start": 133990, "end": 136561 }
class ____(Response): """ Response of projects.get_unique_metric_variants endpoint. :param metrics: A list of metric variants reported for tasks in this project :type metrics: Sequence[MetricVariantResult] """ _service = "projects" _action = "get_unique_metric_variants" _version = "2.2...
GetUniqueMetricVariantsResponse
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 86804, "end": 87060 }
class ____(BlockwiseTail): def _task(self, name: Key, index: int) -> Task: return Task( name, operator.getitem, TaskRef((self.frame._name, index)), slice(-self.n, None), )
BlockwiseTailIndex
python
ray-project__ray
python/ray/tests/test_output.py
{ "start": 1545, "end": 4989 }
class ____: def __init__(self): time.sleep(1) # NOTE: We should save actor, otherwise it will be out of scope. actors = [Foo.remote() for _ in range(30)] for actor in actors: try: ray.get(actor.__ray_ready__.remote()) except ray.exceptions.OutOfMemoryError: # When running the test o...
Foo
python
pypa__pip
tests/unit/test_options.py
{ "start": 1148, "end": 7213 }
class ____(AddFakeCommandMixin): """ Tests for confirming our option precedence: cli -> environment -> subcommand config -> global config -> option defaults """ def get_config_section(self, section: str) -> list[tuple[str, str]]: config = { "global": [("timeout", "-3...
TestOptionPrecedence
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/links/emr.py
{ "start": 1524, "end": 4385 }
class ____(BaseAwsLink): """Helper class for constructing Amazon EMR Logs Link.""" name = "EMR Cluster Logs" key = "emr_logs" format_str = BASE_AWS_CONSOLE_LINK + "/s3/buckets/{log_uri}?region={region_name}&prefix={job_flow_id}/" def format_link(self, **kwargs) -> str: if not kwargs.get("l...
EmrLogsLink
python
kamyu104__LeetCode-Solutions
Python/the-most-similar-path-in-a-graph.py
{ "start": 70, "end": 987 }
class ____(object): def mostSimilar(self, n, roads, names, targetPath): """ :type n: int :type roads: List[List[int]] :type names: List[str] :type targetPath: List[str] :rtype: List[int] """ adj = [[] for _ in xrange(n)] for u, v in roads: ...
Solution
python
tensorflow__tensorflow
tensorflow/python/profiler/pprof_profiler.py
{ "start": 4676, "end": 6639 }
class ____(object): """Keeps track of `Location` protos for pprof profile. `Locations` store information about function call locations. """ def __init__(self, functions): """Constructor. Args: functions: A `Functions` object. """ self._functions = functions # Maps tuples in the form...
Locations
python
readthedocs__readthedocs.org
readthedocs/sso/migrations/0003_allow_saml_with_old_dashboard.py
{ "start": 150, "end": 712 }
class ____(migrations.Migration): safe = Safe.before_deploy() dependencies = [ ("sso", "0002_add_saml_app"), ] operations = [ migrations.AddField( model_name="ssointegration", name="using_old_dashboard", field=models.BooleanField( defa...
Migration
python
scikit-learn__scikit-learn
sklearn/model_selection/_search.py
{ "start": 7557, "end": 16353 }
class ____: """Generator on parameters sampled from given distributions. Non-deterministic iterable over random candidate combinations for hyper- parameter search. If all parameters are presented as a list, sampling without replacement is performed. If at least one parameter is given as a distribut...
ParameterSampler
python
kamyu104__LeetCode-Solutions
Python/count-pairs-that-form-a-complete-day-i.py
{ "start": 383, "end": 638 }
class ____(object): def countCompleteDayPairs(self, hours): """ :type hours: List[int] :rtype: int """ return sum((hours[i]+hours[j])%24 == 0 for i in xrange(len(hours)-1) for j in xrange(i+1, len(hours)))
Solution2
python
readthedocs__readthedocs.org
readthedocs/organizations/views/base.py
{ "start": 1353, "end": 3048 }
class ____(SuccessMessageMixin, CheckOrganizationsEnabled): """ Mixin class that provides organization sublevel objects. This mixin uses several class level variables org_url_field The URL kwarg name for the organization slug admin_only Boolean the dictacts access for organization...
OrganizationMixin
python
huggingface__transformers
src/transformers/models/owlvit/image_processing_owlvit_fast.py
{ "start": 1195, "end": 8219 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BICUBIC image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD size = {"height": 768, "width": 768} default_to_square = True crop_size = {"height": 768, "width": 768} do_resize = True do_center_crop = False do_resca...
OwlViTImageProcessorFast
python
huggingface__transformers
src/transformers/models/dinov2_with_registers/configuration_dinov2_with_registers.py
{ "start": 1371, "end": 8345 }
class ____(BackboneConfigMixin, PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Dinov2WithRegistersModel`]. It is used to instantiate an Dinov2WithRegisters model according to the specified arguments, defining the model architecture. Instantiating a configuration ...
Dinov2WithRegistersConfig
python
ray-project__ray
python/ray/dashboard/modules/aggregator/tests/test_ray_event_publisher.py
{ "start": 579, "end": 1484 }
class ____(PublisherClientInterface): """Test implementation of PublisherClientInterface.""" def __init__( self, batch_size: int = 1, side_effect=lambda batch: PublishStats(True, 1, 0), ): self.batch_size = batch_size self.publish_calls = [] self._side_effect...
MockPublisherClient
python
nedbat__coveragepy
tests/test_python.py
{ "start": 487, "end": 2174 }
class ____(CoverageTest): """Tests of `get_zip_bytes`.""" run_in_temp_dir = False @pytest.mark.parametrize( "encoding", ["utf-8", "gb2312", "hebrew", "shift_jis", "cp1252"], ) def test_get_encoded_zip_files(self, encoding: str) -> None: # See igor.py, do_zipmods, for the te...
GetZipBytesTest
python
walkccc__LeetCode
solutions/3531. Count Covered Buildings/3531.py
{ "start": 0, "end": 601 }
class ____: def countCoveredBuildings(self, n: int, buildings: list[list[int]]) -> int: northernmost = [math.inf] * (n + 1) southernmost = [0] * (n + 1) westernmost = [math.inf] * (n + 1) easternmost = [0] * (n + 1) for x, y in buildings: northernmost[x] = min(northernmost[x], y) sout...
Solution
python
google__jax
jax/_src/core.py
{ "start": 96591, "end": 98962 }
class ____(effects.Effect): pass array_ref_effect = internal_mutable_array_effect = InternalMutableArrayEffect() effects.control_flow_allowed_effects.add_type(InternalMutableArrayEffect) effects.remat_allowed_effects.add_type(InternalMutableArrayEffect) @ref_p.def_effectful_abstract_eval def _ref_abstract_eval(init_...
InternalMutableArrayEffect
python
django__django
tests/admin_views/tests.py
{ "start": 235199, "end": 238385 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) cls.s1 = Section.objects.create(name="Test section") def setUp(self): self.client.force_logi...
NeverCacheTests
python
tensorflow__tensorflow
tensorflow/python/ops/nn_test.py
{ "start": 7196, "end": 8665 }
class ____(test_lib.TestCase, parameterized.TestCase): def _log_softmax(self, x): assert len(x.shape) == 2 m = x.max(1)[:, np.newaxis] u = x - m return u - np.log(np.sum(np.exp(u), 1, keepdims=True)) def testLogSoftmax(self): x_shape = [5, 10] x_np = np.random.randn(*x_shape).astype(np.flo...
LogSoftmaxTest
python
huggingface__transformers
src/transformers/models/camembert/modeling_camembert.py
{ "start": 16715, "end": 17399 }
class ____(PreTrainedModel): config_class = CamembertConfig base_model_prefix = "roberta" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _supports_attention_backend = True _can_record_outputs = { "hidden_states"...
CamembertPreTrainedModel
python
spack__spack
lib/spack/spack/util/executable.py
{ "start": 16870, "end": 16984 }
class ____(spack.error.SpackError): """Raised when :class:`Executable` exits with an error code."""
ProcessError
python
etianen__django-reversion
tests/test_app/migrations/0001_initial.py
{ "start": 123, "end": 5523 }
class ____(migrations.Migration): initial = True dependencies = [ ('reversion', '0001_squashed_0004_auto_20160611_1202'), ('contenttypes', '0002_remove_content_type_name'), ] operations = [ migrations.CreateModel( name='TestModel', fields=[ ...
Migration
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/assertions.py
{ "start": 25734, "end": 30654 }
class ____: def assert_result(self, result, class_, *objects): result = list(result) print(repr(result)) self.assert_list(result, class_, objects) def assert_list(self, result, class_, list_): self.assert_( len(result) == len(list_), "result list is not t...
AssertsExecutionResults
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/cache_key.py
{ "start": 2190, "end": 14637 }
class ____: """Mixin for objects which can produce a cache key. This class is usually in a hierarchy that starts with the :class:`.HasTraverseInternals` base, but this is optional. Currently, the class should be able to work on its own without including :class:`.HasTraverseInternals`. .. seea...
HasCacheKey
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_base_classes_1.py
{ "start": 265, "end": 321 }
class ____(pydantic.BaseModel): x: datetime.datetime
A
python
pytorch__pytorch
test/dynamo/test_aot_compile.py
{ "start": 2677, "end": 2882 }
class ____(torch.nn.Module): def forward(self, x): chunk = x.chunk(2, dim=-1) y = chunk[0] y_repeat = y.repeat_interleave(2, dim=-1) return y_repeat
RepeatInterleaveModule
python
facebookresearch__faiss
demos/offline_ivf/dataset.py
{ "start": 2071, "end": 5743 }
class ____: def __init__( self, root: str, file_descriptors: List[FileDescriptor], d: int, normalize: bool, size: int, ): assert os.path.exists(root) self.root = root self.file_descriptors = file_descriptors self.d = d self....
MultiFileVectorDataset
python
huggingface__transformers
src/transformers/models/sam2/modeling_sam2.py
{ "start": 44208, "end": 54306 }
class ____(nn.Module): def __init__(self, config: Sam2MaskDecoderConfig): super().__init__() self.config = config self.hidden_size = config.hidden_size self.num_multimask_outputs = config.num_multimask_outputs self.num_mask_tokens = config.num_multimask_outputs + 1 ...
Sam2MaskDecoder
python
scipy__scipy
scipy/ndimage/tests/test_measurements.py
{ "start": 16033, "end": 51403 }
class ____: def test_label_default_dtype(self, xp): test_array = np.random.rand(10, 10) test_array = xp.asarray(test_array) label, no_features = ndimage.label(test_array > 0.5) assert label.dtype in (xp.int32, xp.int64) # Shouldn't raise an exception ndimage.find_obje...
TestFindObjects
python
jina-ai__jina
jina/enums.py
{ "start": 6868, "end": 7286 }
class ____(BetterEnum): """Data input type in the request generator.""" AUTO = 0 # auto inference the input type from data (!WARN: could be slow as it relies on try-execept) DOCUMENT = 1 # the input is a full document CONTENT = 2 # the input is just the content of the document DICT = 3 # the in...
DataInputType
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/enumerate_test.py
{ "start": 1267, "end": 2118 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testEnumerate(self): components = (["a", "b"], [1, 2], [37.0, 38]) start = constant_op.constant(20, dtype=dtypes.int64) dataset = dataset_ops.Dataset.from_tensor_slices(comp...
EnumerateTest
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 14509, "end": 14885 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.fc1 = torch.nn.LazyLinear(10) self.relu1 = torch.nn.ReLU() self.fc2 = torch.nn.LazyLinear(1) self.relu2 = torch.nn.ReLU() def forward(self, input): x = self.relu1(self.fc1(input)) ...
LazyMLP
python
PyCQA__pylint
tests/functional/u/unnecessary/unnecessary_dunder_call.py
{ "start": 1864, "end": 2027 }
class ____: def __init__(self, state): self._state = state def __eq__(self, other: Any) -> bool: return self._state.__eq__(other)
CustomState
python
google__jax
tests/dtypes_test.py
{ "start": 33276, "end": 34786 }
class ____(jtu.JaxTestCase): @parameterized.parameters([True, False]) def test_extended_dtypes_at_rest(self, jit): # Test a trivial isomorphic-to-float32 extended dtype working with EArray from jax._src import core from jax._src.interpreters import pxla class foo(dtypes.extended): pass class ...
EArrayTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_str.py
{ "start": 98, "end": 151 }
class ____: def __str__(self): return 1
Int
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_sys.py
{ "start": 6866, "end": 53183 }
class ____(__TestCase): def tearDown(self): test.support.reap_children() def test_exit(self): # call with two arguments self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument with self.assertRaises(SystemExit) as cm: sys.exit() self....
SysModuleTest
python
walkccc__LeetCode
solutions/2349. Design a Number Container System/2349.py
{ "start": 41, "end": 699 }
class ____: def __init__(self): self.numberToIndices = collections.defaultdict(SortedSet) self.indexToNumber = {} def change(self, index: int, number: int) -> None: if index in self.indexToNumber: originalNumber = self.indexToNumber[index] self.numberToIndices[originalNumber].remove(index) ...
NumberContainers
python
numba__numba
numba/core/datamodel/models.py
{ "start": 33315, "end": 33869 }
class ____(StructModel): def __init__(self, dmm, fe_type): array_type = fe_type.array_type dtype = array_type.dtype ndim = array_type.ndim members = [('array', array_type), ('pointers', types.EphemeralArray(types.CPointer(dtype), ndim)), ('indice...
FlatIter
python
lazyprogrammer__machine_learning_examples
rl3/a2c/atari_wrappers.py
{ "start": 1222, "end": 1868 }
class ____(gym.Wrapper): def __init__(self, env): """Take action on reset for environments that are fixed until firing.""" gym.Wrapper.__init__(self, env) assert env.unwrapped.get_action_meanings()[1] == 'FIRE' assert len(env.unwrapped.get_action_meanings()) >= 3 def reset(self,...
FireResetEnv
python
spack__spack
lib/spack/spack/test/concretization/core.py
{ "start": 126524, "end": 186501 }
class ____: """Collects tests on edge properties""" @pytest.mark.parametrize( "spec_str,expected_satisfies,expected_not_satisfies", [ ("conditional-edge", ["^zlib@2.0"], ["^zlib-api"]), ("conditional-edge~foo", ["^zlib@2.0"], ["^zlib-api"]), ( ...
TestConcretizeEdges
python
tensorflow__tensorflow
tensorflow/python/debug/cli/analyzer_cli_test.py
{ "start": 64874, "end": 78874 }
class ____(test_util.TensorFlowTestCase): @classmethod def setUpClass(cls): cls._dump_root = tempfile.mkdtemp() cls._is_gpu_available = test.is_gpu_available() if cls._is_gpu_available: gpu_name = test_util.gpu_device_name() cls._main_device = "/job:localhost/replica:0/task:0" + gpu_name ...
AnalyzerCLIControlDepTest
python
getsentry__sentry
src/sentry/issues/endpoints/organization_eventid.py
{ "start": 1126, "end": 1345 }
class ____(TypedDict): organizationSlug: str projectSlug: str groupId: str eventId: str event: EventSerializerResponse @region_silo_endpoint @extend_schema(tags=["Organizations"])
EventIdLookupResponse
python
kamyu104__LeetCode-Solutions
Python/cut-off-trees-for-golf-event.py
{ "start": 1984, "end": 3320 }
class ____(object): def cutOffTree(self, forest): """ :type forest: List[List[int]] :rtype: int """ def minStep(p1, p2): min_steps = 0 lookup = {p1} q = collections.deque([p1]) while q: size = len(q) ...
Solution_TLE
python
nedbat__coveragepy
tests/plugin2.py
{ "start": 770, "end": 1105 }
class ____(CoveragePlugin): """A file tracer plugin for testing.""" def file_tracer(self, filename: str) -> FileTracer | None: if "render.py" in filename: return RenderFileTracer() return None def file_reporter(self, filename: str) -> FileReporter: return MyFileReporter...
Plugin
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 191124, "end": 192281 }
class ____(Binding): """ BindCheckbox schema wrapper. Parameters ---------- input : Literal['checkbox'] debounce : float If defined, delays event handling until the specified milliseconds have elapsed since the last event was fired. element : str, :class:`Element` A...
BindCheckbox
python
tensorflow__tensorflow
tensorflow/python/ops/numpy_ops/np_random_test.py
{ "start": 2337, "end": 2759 }
class ____(RandomTestBase): def setUp(self): self.np_func = np_random.randn self.onp_func = onp.random.randn super(RandNTest, self).setUp() @parameterized.parameters((), (2), (2, 3)) def test_float64(self, *dims): self._test(*dims) @parameterized.parameters((), (2), ((2,)), (2, 3)) def test...
RandNTest
python
pytorch__pytorch
torch/testing/_internal/distributed/_shard/test_common.py
{ "start": 131, "end": 1219 }
class ____(nn.Module): def __init__(self, linear_size, rank=None, dtype=torch.float32): super().__init__() self.fc1 = nn.Linear(*linear_size[0], dtype=dtype) self.gelu = nn.GELU() self.fc2 = nn.Linear(*linear_size[1], dtype=dtype) if rank is not None: self.fc1.cud...
SimpleMegatronLM
python
ray-project__ray
python/ray/air/tests/mocked_wandb_integration.py
{ "start": 637, "end": 746 }
class ____: args: list kwargs: dict exclude: list logs: list config: dict
LoggingActorState
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 28636, "end": 30917 }
class ____(GeneratedAirbyteDestination): class None_: @public def __init__( self, ): self.method = "none" class ApiKeySecret: @public def __init__(self, apiKeyId: str, apiKeySecret: str): self.method = "secret" self.apiKeyI...
ElasticsearchDestination
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol15.py
{ "start": 307, "end": 474 }
class ____: @property def f(self: T) -> T: return self def m(self, item: T, callback: Callable[[T], str]) -> str: ... x: Proto = Concrete()
Concrete
python
gevent__gevent
src/greentest/3.9/test_asyncore.py
{ "start": 10999, "end": 13189 }
class ____(unittest.TestCase): def setUp(self): self.d = b"It's not dead, it's sleeping!" with open(support.TESTFN, 'wb') as file: file.write(self.d) def tearDown(self): support.unlink(support.TESTFN) def test_recv(self): fd = os.open(support.TESTFN, os.O_RDONLY...
FileWrapperTest
python
run-llama__llama_index
llama-index-core/llama_index/core/data_structs/data_structs.py
{ "start": 8210, "end": 8391 }
class ____(IndexStruct): """Empty index.""" @classmethod def get_type(cls) -> IndexStructType: """Get type.""" return IndexStructType.EMPTY
EmptyIndexStruct
python
pytorch__pytorch
torch/_inductor/codegen/cpp.py
{ "start": 221606, "end": 224527 }
class ____: def __init__(self): super().__init__() self.args = KernelArgs() self.loops_code = BracesBuffer() self.ws = WorkSharing(self.loops_code) self.stack = contextlib.ExitStack() self.stack.enter_context(self.ws) self.scheduled_nodes = [] def new_ker...
KernelGroup
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 34840, "end": 35163 }
class ____(Base): name: Mapped[str] parent_block_schema_id: Mapped[uuid.UUID] = mapped_column( sa.ForeignKey("block_schema.id", ondelete="cascade") ) reference_block_schema_id: Mapped[uuid.UUID] = mapped_column( sa.ForeignKey("block_schema.id", ondelete="cascade") )
BlockSchemaReference
python
getsentry__sentry
src/sentry/api/endpoints/project_profiling_profile.py
{ "start": 2993, "end": 3598 }
class ____(ProjectProfilingBaseEndpoint): def get( self, request: Request, project: Project, profiler_id: str, chunk_id: str ) -> HttpResponse: if not features.has( "organizations:continuous-profiling", project.organization, actor=request.user ): return Response(s...
ProjectProfilingRawChunkEndpoint
python
tensorflow__tensorflow
tensorflow/python/util/type_annotations_test.py
{ "start": 958, "end": 2799 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters([ (typing.Union[int, float], 'Union'), (typing.Tuple[int, ...], 'Tuple'), (typing.Tuple[int, float, float], 'Tuple'), (typing.Mapping[int, float], 'Mapping'), (typing.Union[typing.Tuple[int], typ...
TypeAnnotationsTest
python
astropy__astropy
astropy/logger.py
{ "start": 4377, "end": 17990 }
class ____(Logger): """ This class is used to set up the Astropy logging. The main functionality added by this class over the built-in logging.Logger class is the ability to keep track of the origin of the messages, the ability to enable logging of warnings.warn calls and exceptions, and the ad...
AstropyLogger
python
django__django
django/db/migrations/serializer.py
{ "start": 8888, "end": 9245 }
class ____(BaseSerializer): def serialize(self): from django.db.migrations.writer import OperationWriter string, imports = OperationWriter(self.value, indentation=0).serialize() # Nested operation, trailing comma is handled in upper # OperationWriter._write() return string.r...
OperationSerializer
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-box/llama_index/readers/box/BoxReaderAIPrompt/base.py
{ "start": 495, "end": 4671 }
class ____(BoxReaderBase): """ A reader class for loading data from Box files using a custom AI prompt. This class inherits from the `BaseReader` class and allows specifying a custom AI prompt for data extraction. It utilizes the provided BoxClient object to interact with the Box API and extracts d...
BoxReaderAIPrompt
python
pytorch__pytorch
torch/utils/data/sampler.py
{ "start": 6869, "end": 7519 }
class ____(Sampler[int]): r"""Samples elements randomly from a given list of indices, without replacement. Args: indices (sequence): a sequence of indices generator (Generator): Generator used in sampling. """ indices: Sequence[int] def __init__(self, indices: Sequence[int], gener...
SubsetRandomSampler
python
pallets__jinja
tests/test_bytecode_cache.py
{ "start": 644, "end": 1068 }
class ____: class Error(Exception): pass key = None value = None timeout = None def get(self, key): return self.value def set(self, key, value, timeout=None): self.key = key self.value = value self.timeout = timeout def get_side_effect(self, key): ...
MockMemcached
python
python-excel__xlwt
xlwt/antlr.py
{ "start": 27836, "end": 28190 }
class ____(object): def nextToken(self): pass def __iter__(self): return TokenStreamIterator(self) ###xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx### ### TokenStreamIterator ### ###xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
TokenStream
python
cython__cython
pyximport/pyximport.py
{ "start": 13606, "end": 18510 }
class ____(object): build_dir=True build_in_temp=True setup_args={} #None def _have_importers(): has_py_importer = False has_pyx_importer = False for importer in sys.meta_path: if isinstance(importer, PyxImportMetaFinder): if isinstance(importer, PyImportMetaFinder): ...
PyxArgs
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 15962, "end": 17248 }
class ____(TestCase): @classmethod def setUpTestData(cls): b1 = Blog.objects.create(name='Blog 1') b2 = Blog.objects.create(name='Blog 2') # Multiple entries on Lennon published in 1979 - distinct should deduplicate Entry.objects.create(blog=b1, headline='Something about Lennon...
SearchFilterToManyTests
python
viewflow__viewflow
tests/json/test_json__boolean.py
{ "start": 233, "end": 753 }
class ____(TestCase): def test_crud(self): model = BooleanFieldModel(boolean_field=False) self.assertIsInstance( model._meta.get_field('boolean_field'), models.BooleanField ) self.assertEqual(model.data, { 'boolean_field': False }) ...
Test
python
automl__auto-sklearn
test/test_pipeline/components/data_preprocessing/test_numerical_imputation.py
{ "start": 247, "end": 1401 }
class ____(PreprocessingTestCase): def test_default_configuration(self): transformations = [] for i in range(2): transformation, original = _test_preprocessing(NumericalImputation) self.assertEqual(transformation.shape, original.shape) self.assertTrue((transformat...
NumericalImputationTest
python
networkx__networkx
networkx/algorithms/flow/tests/test_maxflow.py
{ "start": 12741, "end": 17526 }
class ____: def setup_method(self): G = nx.DiGraph() G.add_edge("x", "a", capacity=3.0) G.add_edge("x", "b", capacity=1.0) G.add_edge("a", "c", capacity=3.0) G.add_edge("b", "c", capacity=5.0) G.add_edge("b", "d", capacity=4.0) G.add_edge("d", "e", capacity=2....
TestMaxFlowMinCutInterface
python
django-extensions__django-extensions
tests/management/commands/test_reset_db.py
{ "start": 3200, "end": 6180 }
class ____(TestCase): """Tests for reset_db command and mysql engine.""" @mock.patch("sys.stdout", new_callable=StringIO) @mock.patch("django_extensions.management.commands.reset_db.input") def test_should_cancel_reset_db_if_input_is_different_than_yes( self, m_input, m_stdout ): m_...
ResetDbMysqlTests
python
django__django
tests/one_to_one/models.py
{ "start": 2328, "end": 2508 }
class ____(models.Model): target = models.OneToOneField( Target, models.CASCADE, to_field="name", primary_key=True ) # Test related objects visibility.
ToFieldPointer
python
run-llama__llama_index
llama-index-integrations/postprocessor/llama-index-postprocessor-rankgpt-rerank/llama_index/postprocessor/rankgpt_rerank/base.py
{ "start": 846, "end": 7070 }
class ____(BaseNodePostprocessor): """RankGPT-based reranker.""" top_n: int = Field(default=5, description="Top N nodes to return from reranking.") llm: Optional[LLM] = None verbose: bool = Field( default=False, description="Whether to print intermediate steps." ) rankgpt_rerank_prompt:...
RankGPTRerank
python
huggingface__transformers
src/transformers/models/bart/modeling_bart.py
{ "start": 3491, "end": 5018 }
class ____(nn.Embedding): """ This module overrides nn.Embeddings' forward by multiplying with embeddings scale. """ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0): super().__init__(num_embeddings, embedding_dim, padding_idx) ...
BartScaledWordEmbedding
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_int.py
{ "start": 35024, "end": 39077 }
class ____(__TestCase): # Tests of the functions in _pylong.py. Those get used when the # number of digits in the input values are large enough. def setUp(self): super().setUp() self._previous_limit = sys.get_int_max_str_digits() sys.set_int_max_str_digits(0) def tearDown(self...
PyLongModuleTests
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 15805, "end": 16441 }
class ____(TestCase): """Tests for ``first_true()``""" def test_something_true(self): """Test with no keywords""" self.assertEqual(mi.first_true(range(10)), 1) def test_nothing_true(self): """Test default return value.""" self.assertIsNone(mi.first_true([0, 0, 0])) def...
FirstTrueTests
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 215459, "end": 215760 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("CWE", graphql_name="node")
CWEEdge
python
getsentry__sentry
src/sentry/integrations/discord/message_builder/issues.py
{ "start": 1609, "end": 6887 }
class ____(DiscordMessageBuilder): def __init__( self, group: Group, event: GroupEvent | None = None, tags: set[str] | None = None, rules: list[Rule] | None = None, link_to_event: bool = False, issue_details: bool = False, notification: ProjectNotifica...
DiscordIssuesMessageBuilder
python
pydantic__pydantic
tests/benchmarks/test_discriminated_unions.py
{ "start": 150, "end": 239 }
class ____(BaseModel): state_type: Literal['nested'] substate: AnyState
NestedState
python
redis__redis-py
redis/commands/search/query.py
{ "start": 109, "end": 11316 }
class ____: """ Query is used to build complex queries that have more parameters than just the query string. The query string is set in the constructor, and other options have setter functions. The setter functions return the query object so they can be chained. i.e. `Query("foo").verbatim().fi...
Query
python
dagster-io__dagster
docs/sphinx/_ext/sphinx-mdx-builder/sphinxcontrib/mdxbuilder/writers/mdx.py
{ "start": 706, "end": 3889 }
class ____(textwrap.TextWrapper): """Custom subclass that uses a different word separator regex.""" wordsep_re = re.compile( r"(\s+|" # any whitespace r"(?<=\s)(?::[a-z-]+:)?`\S+|" # interpreted text start r"[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|" # hyphenated words r"(?<=[\w\!...
TextWrapper
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 14668, "end": 14952 }
class ____(TestCase): """Tests for ``consumer()``""" def test_consumer(self): @mi.consumer def eater(): while True: x = yield # noqa e = eater() e.send('hi') # without @consumer, would raise TypeError
ConsumerTests
python
google__jax
tests/jaxpr_effects_test.py
{ "start": 20793, "end": 22607 }
class ____(jtu.JaxTestCase): def test_cannot_pmap_unlowerable_effect(self): def f(x): # abc is not lowerable effect_p.bind(effect='abc') return x with self.assertRaisesRegex( ValueError, "Cannot lower jaxpr with effects: {'abc'}"): jax.pmap(f)(jnp.arange(jax.local_device_coun...
ParallelEffectsTest
python
huggingface__transformers
tests/trainer/test_trainer_distributed_worker_seed.py
{ "start": 738, "end": 1046 }
class ____(Dataset): def __init__(self): self.length = 64 def __len__(self): return self.length def __getitem__(self, i) -> int: x = random.random() y = np.random.random() z = torch.rand([]).item() return {"x": torch.tensor([x, y, z])}
DummyDataset
python
walkccc__LeetCode
solutions/296. Best Meeting Point/296.py
{ "start": 0, "end": 616 }
class ____: def minTotalDistance(self, grid: list[list[int]]) -> int: m = len(grid) n = len(grid[0]) # i indices s.t. grid[i][j] == 1 I = [i for i in range(m) for j in range(n) if grid[i][j]] # j indices s.t. grid[i][j] == 1 J = [j for j in range(n) for i in range(m) if grid[i][j]] def mi...
Solution
python
doocs__leetcode
solution/2800-2899/2865.Beautiful Towers I/Solution.py
{ "start": 0, "end": 460 }
class ____: def maximumSumOfHeights(self, maxHeights: List[int]) -> int: ans, n = 0, len(maxHeights) for i, x in enumerate(maxHeights): y = t = x for j in range(i - 1, -1, -1): y = min(y, maxHeights[j]) t += y y = x for ...
Solution
python
ansible__ansible
lib/ansible/utils/display.py
{ "start": 5643, "end": 11978 }
class ____(logging.Filter): """ This is a filter which injects the current user as the 'user' attribute on each record. We need to add this filter to all logger handlers so that 3rd party libraries won't print an exception due to user not being defined. """ try: username = getpass.getuser()...
FilterUserInjector
python
google__jax
tests/pallas/mosaic_gpu_test.py
{ "start": 213559, "end": 215019 }
class ____(PallasSm90ATest): # WGMMA def test_stage6(self): self.skip_if_wg_semantics() # `fa.optimization_barrier` does not support f16 arrays. m_block = n_block = 64 k_block = 32 x = jnp.arange(128 * 128, dtype=jnp.float16).reshape(128, 128) @functools.partial( self.kernel, out_sha...
ExamplesSm90ATest
python
joke2k__faker
faker/providers/date_time/th_TH/__init__.py
{ "start": 9706, "end": 11663 }
class ____(DateParseTypeProvider): def date( self, pattern: str = "%-d %b %Y", end_datetime: Optional[DateParseType] = None, thai_digit: bool = False, buddhist_era: bool = True, ) -> str: """ Get a date string between January 1, 1970 and now :param...
Provider
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/async/guestbook.py
{ "start": 977, "end": 1153 }
class ____(ndb.Model): text = ndb.StringProperty() when = ndb.DateTimeProperty(auto_now_add=True) author = ndb.KeyProperty(kind=Account) # references Account
Message
python
kamyu104__LeetCode-Solutions
Python/mark-elements-on-array-by-performing-queries.py
{ "start": 56, "end": 930 }
class ____(object): def unmarkedSumArray(self, nums, queries): """ :type nums: List[int] :type queries: List[List[int]] :rtype: List[int] """ total = sum(nums) lookup = [False]*len(nums) min_heap = [(x, i) for i, x in enumerate(nums)] heapq.hea...
Solution
python
django__django
tests/user_commands/management/commands/hal.py
{ "start": 68, "end": 1062 }
class ____(BaseCommand): help = "Useless command." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="*", help="Specify the app label(s) to works on.", ) parser.add_argument("--empty", action="store_t...
Command
python
allegroai__clearml
clearml/backend_api/services/v2_23/dataviews.py
{ "start": 74883, "end": 76400 }
class ____(Request): """ Delete a dataview :param dataview: Datatview ID :type dataview: str :param force: Allow deletion of the published dataview :type force: bool """ _service = "dataviews" _action = "delete" _version = "2.23" _schema = { "definitions": {}, ...
DeleteRequest