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
keras-team__keras
keras/src/ops/numpy.py
{ "start": 194033, "end": 195505 }
class ____(Operation): def __init__(self, axis=None, *, name=None): super().__init__(name=name) self.axis = axis def call(self, x, indices): return backend.numpy.take(x, indices, axis=self.axis) def compute_output_spec(self, x, indices): x_shape = list(x.shape) if i...
Take
python
PyCQA__pylint
tests/functional/u/unused/unused_private_member.py
{ "start": 6865, "end": 7484 }
class ____: __instance = None @classmethod # Use class method here def instance(cls): if cls.__instance is None: cls() return cls.__instance def __init__(self): try: FalsePositive4681b.__instance = 42 # This should be fine except Exception: # ...
FalsePositive4681b
python
encode__django-rest-framework
tests/test_renderers.py
{ "start": 21344, "end": 22771 }
class ____(TestCase): """ Test rendering ChoiceField with HTMLFormRenderer. """ def setUp(self): choices = ((1, 'Option1'), (2, 'Option2'), (12, 'Option12')) class TestSerializer(serializers.Serializer): test_field = serializers.ChoiceField(choices=choices, ...
TestChoiceFieldHTMLFormRenderer
python
numpy__numpy
numpy/_core/tests/test_shape_base.py
{ "start": 1813, "end": 3034 }
class ____: def test_0D_array(self): a = array(1) b = array(2) res = [atleast_2d(a), atleast_2d(b)] desired = [array([[1]]), array([[2]])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast...
TestAtleast2d
python
kamyu104__LeetCode-Solutions
Python/cutting-ribbons.py
{ "start": 54, "end": 571 }
class ____(object): def maxLength(self, ribbons, k): """ :type ribbons: List[int] :type k: int :rtype: int """ def check(ribbons, k, s): return reduce(lambda total,x: total+x//s, ribbons, 0) >= k left, right = 1, sum(ribbons)//k while left...
Solution
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 31731, "end": 31938 }
class ____(Structure): _fields_ = (("offset", p_uint32), ("size", p_uint32)) def describe(self): s = {} s["offset"] = int(self.offset) s["size"] = int(self.size)
symseg_command
python
PyCQA__pylint
tests/functional/c/ctor_arguments.py
{ "start": 503, "end": 544 }
class ____(Class1Arg): pass
Subclass1Arg
python
kamyu104__LeetCode-Solutions
Python/leftmost-column-with-at-least-a-one.py
{ "start": 145, "end": 554 }
class ____(object): def leftMostColumnWithOne(self, binaryMatrix): """ :type binaryMatrix: BinaryMatrix :rtype: int """ m, n = binaryMatrix.dimensions() r, c = 0, n-1 while r < m and c >= 0: if not binaryMatrix.get(r, c): r += 1 ...
Solution
python
huggingface__transformers
src/transformers/models/modernbert/modeling_modernbert.py
{ "start": 8143, "end": 9098 }
class ____(nn.Module): """Applies the GLU at the end of each ModernBERT layer. Compared to the default BERT architecture, this block replaces :class:`~transformers.model.bert.modeling_bert.BertIntermediate` and :class:`~transformers.model.bert.modeling_bert.SelfOutput` with a single module that has similar...
ModernBertMLP
python
scrapy__scrapy
scrapy/core/downloader/handlers/http11.py
{ "start": 9752, "end": 11837 }
class ____(Agent): """An agent that uses a L{TunnelingTCP4ClientEndpoint} to make HTTPS downloads. It may look strange that we have chosen to subclass Agent and not ProxyAgent but consider that after the tunnel is opened the proxy is transparent to the client; thus the agent should behave like there is ...
TunnelingAgent
python
encode__httpx
httpx/_transports/default.py
{ "start": 8667, "end": 9161 }
class ____(AsyncByteStream): def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None: self._httpcore_stream = httpcore_stream async def __aiter__(self) -> typing.AsyncIterator[bytes]: with map_httpcore_exceptions(): async for part in self._httpcore_stream: ...
AsyncResponseStream
python
jazzband__django-formtools
formtools/wizard/views.py
{ "start": 23404, "end": 23589 }
class ____(WizardView): """ A WizardView with pre-configured SessionStorage backend. """ storage_name = 'formtools.wizard.storage.session.SessionStorage'
SessionWizardView
python
scrapy__scrapy
tests/test_settings/__init__.py
{ "start": 15605, "end": 21777 }
class ____: def setup_method(self): self.settings = Settings() @mock.patch.dict("scrapy.settings.SETTINGS_PRIORITIES", {"default": 10}) @mock.patch("scrapy.settings.default_settings", default_settings) def test_initial_defaults(self): settings = Settings() assert len(settings.at...
TestSettings
python
miyuchina__mistletoe
mistletoe/span_token.py
{ "start": 2819, "end": 3068 }
class ____(SpanToken): """ Emphasis token. ("*some text*") This is an inline token. Its children are inline (span) tokens. One of the core tokens. """ def __init__(self, match): self.delimiter = match.delimiter
Emphasis
python
run-llama__llama_index
llama-index-core/llama_index/core/instrumentation/events/llm.py
{ "start": 777, "end": 1069 }
class ____(BaseEvent): """ LLMPredictEndEvent. The result of an llm.predict() call. Args: output (str): Output. """ output: str @classmethod def class_name(cls) -> str: """Class name.""" return "LLMPredictEndEvent"
LLMPredictEndEvent
python
getsentry__sentry
src/sentry/preprod/api/models/size_analysis/project_preprod_size_analysis_compare_models.py
{ "start": 261, "end": 688 }
class ____(BaseModel): head_size_metric_id: int base_size_metric_id: int | None metrics_artifact_type: PreprodArtifactSizeMetrics.MetricsArtifactType identifier: str | None state: PreprodArtifactSizeComparison.State # Only present when state is SUCCESS comparison_id: int | None # Only...
SizeAnalysisComparison
python
langchain-ai__langchain
libs/partners/anthropic/langchain_anthropic/middleware/prompt_caching.py
{ "start": 783, "end": 5075 }
class ____(AgentMiddleware): """Prompt Caching Middleware. Optimizes API usage by caching conversation prefixes for Anthropic models. Requires both `langchain` and `langchain-anthropic` packages to be installed. Learn more about Anthropic prompt caching [here](https://platform.claude.com/docs/en/...
AnthropicPromptCachingMiddleware
python
django__django
tests/cache/tests.py
{ "start": 72620, "end": 72897 }
class ____(FileBasedCacheTests): def mkdtemp(self): tmp_dir = super().mkdtemp() return Path(tmp_dir) @override_settings( CACHES={ "default": { "BACKEND": "cache.liberal_backend.CacheClass", }, } )
FileBasedCachePathLibTests
python
pytorch__pytorch
torch/export/unflatten.py
{ "start": 58135, "end": 59848 }
class ____: parent_fqn: str parent_module: torch.nn.Module parent_call_module: torch.fx.Node fqn: str call_idx: int module: torch.nn.Module def _outline_submodules(orig_graph: torch.fx.Graph, root_module: UnflattenedModule): seen_nodes: dict[str, torch.fx.Node] = {} seen_modules: dict[...
_SubmoduleEntry
python
airbytehq__airbyte
airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_authorizations.py
{ "start": 3583, "end": 9495 }
class ____(TestCase): @HttpMocker() def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None: http_mocker.get( _authorizations_request().with_created_gte(_A_START_DATE).with_created_lte(_NOW).with_limit(100).build(), _authorizations_response()....
FullRefreshTest
python
apache__airflow
dev/breeze/src/airflow_breeze/prepare_providers/provider_documentation.py
{ "start": 5399, "end": 5502 }
class ____(Exception): """Raised when package has no changes."""
PrepareReleaseDocsNoChangesException
python
pdm-project__pdm
src/pdm/cli/commands/init.py
{ "start": 696, "end": 12518 }
class ____(BaseCommand): """Initialize a pyproject.toml for PDM. Built-in templates: - default: `pdm init`, A simple template with a basic structure. - minimal: `pdm init minimal`, A minimal template with only `pyproject.toml`. """ supports_other_generator = True def __init__(self) -> Non...
Command
python
pandas-dev__pandas
pandas/core/internals/managers.py
{ "start": 33247, "end": 66776 }
class ____(libinternals.BlockManager, BaseBlockManager): """ BaseBlockManager that holds 2D blocks. """ ndim = 2 # ---------------------------------------------------------------- # Constructors def __init__( self, blocks: Sequence[Block], axes: Sequence[Index], ...
BlockManager
python
kamyu104__LeetCode-Solutions
Python/find-most-frequent-vowel-and-consonant.py
{ "start": 48, "end": 446 }
class ____(object): def maxFreqSum(self, s): """ :type s: str :rtype: int """ VOWELS = {'a', 'e', 'i', 'o', 'u'} cnt = [0]*26 for x in s: cnt[ord(x)-ord('a')] += 1 return max(cnt[i] for i in xrange(26) if chr(i+ord('a')) in VOWELS)+\ ...
Solution
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/security.py
{ "start": 7291, "end": 7529 }
class ____(PermittedDagFilter): """A parameter that filters the permitted task instances for the user.""" def to_orm(self, select: Select) -> Select: return select.where(TI.dag_id.in_(self.value or set()))
PermittedTIFilter
python
keon__algorithms
algorithms/graph/check_digraph_strongly_connected.py
{ "start": 291, "end": 2079 }
class ____: """ A directed graph where edges are one-way (a two-way edge can be represented by using two edges). """ def __init__(self,vertex_count): """ Create a new graph with vertex_count vertices. """ self.vertex_count = vertex_count self.graph = defaultdict...
Graph
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 118685, "end": 119193 }
class ____(_PrintableStructure): _fields_ = [ ('version', c_uint), ('str', c_char * NVML_PERF_MODES_BUFFER_SIZE), ] nvmlDevicePerfModes_v1 = 0x1000804 @convertStrBytes def nvmlDeviceGetPerformanceModes(handle): perfModes = c_nvmlDevicePerfModes_v1_t() perfModes.version = nvmlDevicePerf...
c_nvmlDevicePerfModes_v1_t
python
tensorflow__tensorflow
tensorflow/tools/proto_splitter/split.py
{ "start": 1934, "end": 9915 }
class ____(Splitter): """A Splitter that can be composed with other splitters. This Splitter writes to the riegeli file format. See README for details. """ def __init__( self, proto, *, proto_as_initial_chunk: bool = True, parent_splitter: Optional["ComposableSplitter"] = None...
ComposableSplitter
python
doocs__leetcode
solution/0300-0399/0307.Range Sum Query - Mutable/Solution2.py
{ "start": 108, "end": 1353 }
class ____: __slots__ = ["nums", "tr"] def __init__(self, nums): self.nums = nums n = len(nums) self.tr = [Node() for _ in range(n << 2)] self.build(1, 1, n) def build(self, u, l, r): self.tr[u].l, self.tr[u].r = l, r if l == r: self.tr[u].v = se...
SegmentTree
python
matplotlib__matplotlib
lib/matplotlib/backend_tools.py
{ "start": 9661, "end": 10603 }
class ____(ToolBase): """ Send message with the current pointer position. This tool runs in the background reporting the position of the cursor. """ def __init__(self, *args, **kwargs): self._id_drag = None super().__init__(*args, **kwargs) def set_figure(self, figure): ...
ToolCursorPosition
python
Netflix__metaflow
test/unit/spin/flows/hello_spin_flow.py
{ "start": 52, "end": 569 }
class ____(FlowSpec): @step def start(self): chunk_size = 1024 * 1024 # 1 MB total_size = 1024 * 1024 * 1000 # 1000 MB data = bytearray() for _ in range(total_size // chunk_size): data.extend(random.randbytes(chunk_size)) self.a = data self.next(s...
HelloSpinFlow
python
dask__dask
dask/dataframe/dask_expr/_groupby.py
{ "start": 31038, "end": 31140 }
class ____(GroupByBFill): func = staticmethod(functools.partial(_fillna, what="ffill"))
GroupByFFill
python
pytorch__pytorch
test/higher_order_ops/test_invoke_subgraph.py
{ "start": 96968, "end": 99235 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[8, 8]", L_y_: "f32[8, 8]"): l_x_ = L_x_ l_y_ = L_y_ subgraph_0 = self.subgraph_0 invoke_subgraph = torch.ops.higher_order.invoke_subgraph(subgraph_0, 'subgraph_0', l_x_, l_y_); subgraph_0 = l_x_ = None getitem: "f32[...
GraphModule
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 9951, "end": 10311 }
class ____: def setup(self): data = np.random.randn(1000, 500) df = DataFrame(data) df = df.where(df > 0) self.bools = df > 0 self.mask = isnull(df) def time_frame_mask_bools(self): self.bools.mask(self.mask) def time_frame_mask_floats(self): self.bo...
MaskBool
python
tensorflow__tensorflow
tensorflow/python/keras/saving/saved_model/layer_serialization.py
{ "start": 1257, "end": 5221 }
class ____(base_serialization.SavedModelSaver): """Implements Layer SavedModel serialization.""" @property def object_identifier(self): return constants.LAYER_IDENTIFIER @property def python_properties(self): # TODO(kathywu): Add python property validator return self._python_properties_internal(...
LayerSavedModelSaver
python
allegroai__clearml
clearml/automation/trigger.py
{ "start": 7916, "end": 37332 }
class ____(BaseScheduler): """ Trigger Task execution if an event happens in the system. Examples: - New model is published/tagged, - New Dataset is created, - General Task failed, - Task metric below/above threshold, alert every X minutes """ _datasets_section = "datasets" _m...
TriggerScheduler
python
getsentry__sentry
tests/sentry_plugins/trello/test_plugin.py
{ "start": 363, "end": 498 }
class ____(PluginTestCase): @cached_property def plugin(self) -> TrelloPlugin: return TrelloPlugin()
TrelloPluginTestBase
python
pandas-dev__pandas
pandas/io/html.py
{ "start": 16986, "end": 20467 }
class ____(_HtmlFrameParser): """ HTML to DataFrame parser that uses BeautifulSoup under the hood. See Also -------- pandas.io.html._HtmlFrameParser pandas.io.html._LxmlFrameParser Notes ----- Documentation strings for this class are in the base class :class:`pandas.io.html._Ht...
_BeautifulSoupHtml5LibFrameParser
python
astropy__astropy
astropy/time/formats.py
{ "start": 66180, "end": 67831 }
class ____(TimeISO): """ Year, day-of-year and time as "YYYY:DOY:HH:MM:SS.sss...". The day-of-year (DOY) goes from 001 to 365 (366 in leap years). For example, 2000:001:00:00:00.000 is midnight on January 1, 2000. The allowed subformats are: - 'date_hms': date + hours, mins, secs (and optional...
TimeYearDayTime
python
facebook__pyre-check
tools/incremental_test/environment.py
{ "start": 1590, "end": 2271 }
class ____(Environment): def run( self, working_directory: Path, command: str, stdin: Optional[str] ) -> CommandOutput: LOG.debug( f"Invoking subprocess `{command}` at `{working_directory}`" f"{' with stdin' if stdin is not None else ''}" ) result = subpro...
SubprocessEnvironment
python
tensorflow__tensorflow
tensorflow/python/training/supervisor.py
{ "start": 39343, "end": 40120 }
class ____(coordinator.LooperThread): """A thread to save summaries on a timer.""" def __init__(self, sv, sess): """Create a SVSummaryThread. Args: sv: A `Supervisor`. sess: A `Session`. """ super(SVSummaryThread, self).__init__(sv.coord, sv.save_summaries_secs) self._sv = sv s...
SVSummaryThread
python
numba__numba
numba/tests/gdb/test_pretty_print.py
{ "start": 350, "end": 2416 }
class ____(TestCase): def test(self): rdt_a = np.dtype([("x", np.int16), ("y", np.float64)], align=True) @njit(debug=True) def foo(): a = 1.234 b = (1, 2, 3) c = ('a', b, 4) d = np.arange(5.) e = np.array([[1, 3j], [2, 4j]]) ...
Test
python
tornadoweb__tornado
tornado/web.py
{ "start": 100501, "end": 100933 }
class ____(HTTPError): """Exception raised by `RequestHandler.get_argument`. This is a subclass of `HTTPError`, so if it is uncaught a 400 response code will be used instead of 500 (and a stack trace will not be logged). .. versionadded:: 3.1 """ def __init__(self, arg_name: str) -> None: ...
MissingArgumentError
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-fish-in-a-grid.py
{ "start": 43, "end": 1146 }
class ____(object): def findMaxFish(self, grid): """ :type grid: List[List[int]] :rtype: int """ DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1)) def bfs(i, j): result = grid[i][j] grid[i][j] = 0 q = [(i, j)] while q: ...
Solution
python
python__mypy
mypy/nodes.py
{ "start": 19041, "end": 25034 }
class ____(FuncBase, SymbolNode, Statement): """A logical node representing all the variants of a multi-declaration function. A multi-declaration function is often an @overload, but can also be a @property with a setter and a/or a deleter. This node has no explicit representation in the source program...
OverloadedFuncDef
python
huggingface__transformers
src/transformers/models/sam/modeling_sam.py
{ "start": 43554, "end": 44261 }
class ____(PreTrainedModel): config: SamConfig base_model_prefix = "sam" main_input_name = "pixel_values" input_modalities = ("image",) _no_split_modules = ["SamVisionAttention"] supports_gradient_checkpointing = True _supports_sdpa = True @torch.no_grad() def _init_weights(self, mo...
SamPreTrainedModel
python
django__django
django/templatetags/i18n.py
{ "start": 659, "end": 983 }
class ____(Node): def __init__(self, lang_code, variable): self.lang_code = lang_code self.variable = variable def render(self, context): lang_code = self.lang_code.resolve(context) context[self.variable] = translation.get_language_info(lang_code) return ""
GetLanguageInfoNode
python
django__django
tests/migrations/test_migrations_squashed_double/0002_auto.py
{ "start": 43, "end": 306 }
class ____(migrations.Migration): dependencies = [("migrations", "0001_initial")] operations = [ migrations.AlterField( model_name="a", name="foo", field=models.BooleanField(default=True), ), ]
Migration
python
walkccc__LeetCode
solutions/1732. Find the Highest Altitude/1732.py
{ "start": 0, "end": 195 }
class ____: def largestAltitude(self, gain: list[int]) -> int: ans = 0 currAltitude = 0 for g in gain: currAltitude += g ans = max(ans, currAltitude) return ans
Solution
python
Netflix__metaflow
metaflow/plugins/metadata_providers/local.py
{ "start": 486, "end": 23938 }
class ____(MetadataProvider): TYPE = "local" DATASTORE_DIR = DATASTORE_LOCAL_DIR # ".metaflow" @classmethod def _get_storage_class(cls): # This method is meant to be overridden from metaflow.plugins.datastores.local_storage import LocalStorage return LocalStorage def __in...
LocalMetadataProvider
python
django__django
tests/db_functions/json/test_json_object.py
{ "start": 362, "end": 3371 }
class ____(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(name="Ivan Ivanov", alias="iivanov"), Author(name="Bertha Berthy", alias="bberthy"), ] ) def test_empty(self): obj = Author.objects...
JSONObjectTests
python
pytorch__pytorch
test/inductor/test_perf.py
{ "start": 18252, "end": 20828 }
class ____(TestCase): """ Testing the fusion group creation heuristic (i.e. cases where we can't fuse everything into a single kernel) Disables inductor rematerialization for easier reasoning of tests. """ @classmethod def setUpClass(cls): super().setUpClass() cls._stack = c...
SchedulerFusionTests
python
great-expectations__great_expectations
tests/integration/test_utils/data_source_config/postgres.py
{ "start": 1367, "end": 2030 }
class ____(SQLBatchTestSetup[PostgreSQLDatasourceTestConfig]): @property @override def connection_string(self) -> str: return "postgresql+psycopg2://postgres@localhost:5432/test_ci" @property @override def use_schema(self) -> bool: return False @override def make_asset(...
PostgresBatchTestSetup
python
PrefectHQ__prefect
tests/test_logging.py
{ "start": 55992, "end": 69420 }
class ____: def test_filters_current_api_key(self): test_api_key = "hi-hello-im-an-api-key" with temporary_settings({PREFECT_API_KEY: test_api_key}): filter = ObfuscateApiKeyFilter() record = logging.LogRecord( name="Test Log", level=1, ...
TestObfuscateApiKeyFilter
python
python__mypy
mypyc/test/test_lowering.py
{ "start": 888, "end": 2433 }
class ____(MypycDataSuite): files = ["lowering-int.test", "lowering-list.test"] base_path = test_temp_dir def run_case(self, testcase: DataDrivenTestCase) -> None: options = infer_ir_build_options_from_test_name(testcase.name) if options is None: # Skipped test case ...
TestLowering
python
huggingface__transformers
src/transformers/models/electra/modeling_electra.py
{ "start": 44573, "end": 46824 }
class ____(ElectraPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.electra = ElectraModel(config) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_d...
ElectraForTokenClassification
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 66606, "end": 67533 }
class ____(Request): """ get task scalar metrics and variants :param task: task ID :type task: str """ _service = "events" _action = "get_scalar_metrics_and_variants" _version = "2.13" _schema = { "definitions": {}, "properties": {"task": {"description": "task ID", ...
GetScalarMetricsAndVariantsRequest
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 237437, "end": 241021 }
class ____(TokenConverter): """Converter to return a repetitive expression as a list, but also as a dictionary. Each element can also be referenced using the first token in the expression as its key. Useful for tabular report scraping when the first column can be used as a item key. The optional ``...
Dict
python
kamyu104__LeetCode-Solutions
Python/maximum-binary-tree-ii.py
{ "start": 191, "end": 736 }
class ____(object): def insertIntoMaxTree(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ if not root: return TreeNode(val) if val > root.val: node = TreeNode(val) node.left = root ...
Solution
python
huggingface__transformers
tests/models/aya_vision/test_modeling_aya_vision.py
{ "start": 5197, "end": 7104 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( AyaVisionModel, AyaVisionForConditionalGeneration, ) if is_torch_available() else () ) all_generative_model_classes = (AyaVisionForCond...
AyaVisionModelTest
python
django__django
django/utils/functional.py
{ "start": 1799, "end": 7671 }
class ____: """ Base class for the proxy class created in the closure of the lazy function. It's used to recognize promises in code. """ pass def lazy(func, *resultclasses): """ Turn any callable into a lazy evaluated callable. result classes or types is required -- at least one is ne...
Promise
python
openai__openai-python
src/openai/resources/completions.py
{ "start": 58940, "end": 59189 }
class ____: def __init__(self, completions: AsyncCompletions) -> None: self._completions = completions self.create = async_to_streamed_response_wrapper( completions.create, )
AsyncCompletionsWithStreamingResponse
python
numba__numba
numba/tests/test_array_methods.py
{ "start": 7024, "end": 68040 }
class ____(MemoryLeakMixin, TestCase): """ Test various array methods and array-related functions. """ def setUp(self): super(TestArrayMethods, self).setUp() def check_round_scalar(self, unary_pyfunc, binary_pyfunc): base_values = [-3.0, -2.5, -2.25, -1.5, 1.5, 2.25, 2.5, 2.75] ...
TestArrayMethods
python
getsentry__sentry
tests/sentry/issues/test_ingest.py
{ "start": 36904, "end": 40512 }
class ____(OccurrenceTestMixin, TestCase): def test_simple(self) -> None: occurrence = self.build_occurrence() event = self.store_event(data={}, project_id=self.project.id) assert materialize_metadata(occurrence, event) == { "type": "default", "culprit": occurrence.cu...
MaterializeMetadataTest
python
huggingface__transformers
src/transformers/models/esm/modeling_esmfold.py
{ "start": 49168, "end": 49700 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.linear_1 = EsmFoldLinear(config.resnet_dim, config.resnet_dim, init="relu") self.linear_2 = EsmFoldLinear(config.resnet_dim, config.resnet_dim, init="final") self.relu = nn.ReLU() def forward(self, a: t...
EsmFoldAngleResnetBlock
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 96887, "end": 97401 }
class ____(Expr): _parameters = ["obj"] def __str__(self): return f"{type(self).__name__}({self.obj})" @property def _name(self): return self.obj.key def _layer(self) -> dict: dc = self.obj.__dask_optimize__(self.obj.dask, self.obj.key).to_dict().copy() dc[(self.ob...
_DelayedExpr
python
scipy__scipy
scipy/signal/tests/test_spectral.py
{ "start": 36628, "end": 58365 }
class ____: def test_frequency(self): """Test if frequency location of peak corresponds to frequency of generated input signal. """ # Input parameters ampl = 2. w = 1. phi = 0.5 * np.pi nin = 100 nout = 1000 p = 0.7 # Fraction of poin...
TestLombscargle
python
getsentry__sentry
tests/sentry/feedback/endpoints/test_organization_feedback_categories.py
{ "start": 545, "end": 12219 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-user-feedback-categories" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.org = self.organization self.project1 = self.project self.project2 = self.create_project(teams=[self.team]...
OrganizationFeedbackCategoriesTest
python
doocs__leetcode
solution/0400-0499/0409.Longest Palindrome/Solution2.py
{ "start": 0, "end": 245 }
class ____: def longestPalindrome(self, s: str) -> int: odd = defaultdict(int) cnt = 0 for c in s: odd[c] ^= 1 cnt += 1 if odd[c] else -1 return len(s) - cnt + 1 if cnt else len(s)
Solution
python
cherrypy__cherrypy
cherrypy/tutorial/tut04_complex_site.py
{ "start": 620, "end": 954 }
class ____: """Joke app.""" @cherrypy.expose def index(self): """Produce HTTP response body of joke page app index URI.""" return """ <p>"In Python, how do you create a string of random characters?" -- "Read a Perl file!"</p> <p>[<a href="../">Return</a>]...
JokePage
python
pdm-project__pdm
src/pdm/cli/commands/lock.py
{ "start": 585, "end": 4867 }
class ____(BaseCommand): """Resolve and lock dependencies""" arguments = ( *BaseCommand.arguments, lockfile_option, no_isolation_option, config_setting_option, override_option, skip_option, groups_group, lock_strategy_group, ) def add_arg...
Command
python
python-poetry__poetry
src/poetry/console/command_loader.py
{ "start": 292, "end": 615 }
class ____(FactoryCommandLoader): def register_factory( self, command_name: str, factory: Callable[[], Command] ) -> None: if command_name in self._factories: raise CleoLogicError(f'The command "{command_name}" already exists.') self._factories[command_name] = factory
CommandLoader
python
tensorflow__tensorflow
tensorflow/python/ops/control_flow_ops_test.py
{ "start": 24100, "end": 39288 }
class ____(test_util.TensorFlowTestCase): def assertAllEqualNested(self, a, b): if isinstance(a, (list, tuple)): for entry_a, entry_b in zip(a, b): self.assertAllEqualNested(entry_a, entry_b) else: self.assertAllEqual(a, b) def _testShape(self, fn_true, fn_false, expected_shape, strict...
DataTypesTest
python
getsentry__sentry
src/sentry/integrations/messaging/metrics.py
{ "start": 3327, "end": 3477 }
class ____(StrEnum): """Common reasons why a messaging interaction may fail.""" MISSING_ACTION = "missing_action"
MessageInteractionFailureReason
python
spack__spack
lib/spack/spack/test/llnl/util/lock.py
{ "start": 20302, "end": 26203 }
class ____: def __init__(self, lock_path): self.lock_path = lock_path def p1(self, barrier): lock = lk.Lock(self.lock_path) lock.acquire_write() barrier.wait() # ---------------------------------------- 1 # others test timeout barrier.wait() # ----------------...
ComplexAcquireAndRelease
python
apache__airflow
providers/openai/src/airflow/providers/openai/operators/openai.py
{ "start": 1343, "end": 3468 }
class ____(BaseOperator): """ Operator that accepts input text to generate OpenAI embeddings using the specified model. :param conn_id: The OpenAI connection ID to use. :param input_text: The text to generate OpenAI embeddings for. This can be a string, a list of strings, a list of ...
OpenAIEmbeddingOperator
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 54787, "end": 54952 }
class ____(_PrintableStructure): _fields_ = [ ('fans', c_nvmlUnitFanInfo_t * 24), ('count', c_uint) ] ## Device structures
c_nvmlUnitFanSpeeds_t
python
pytorch__pytorch
test/inductor/test_group_batch_fusion.py
{ "start": 3695, "end": 5243 }
class ____(torch.nn.Module): def __init__(self, device, has_weight=True, has_bias=True): super().__init__() self.device = device self.scale0 = torch.nn.ParameterList( [torch.nn.Parameter(torch.randn(10)) for _ in range(5)] ).to(self.device) self.bias0 = torch.nn.P...
MyModule3
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 87644, "end": 91639 }
class ____: @pytest.mark.parametrize('use_list', (False, True)) def test_validationerror_code_with_msg(self, use_list): class ExampleSerializer(serializers.Serializer): password = serializers.CharField() def validate_password(self, obj): err = DjangoValidationEr...
TestValidationErrorCode
python
ray-project__ray
python/ray/autoscaler/_private/aws/cloudwatch/cloudwatch_helper.py
{ "start": 779, "end": 32701 }
class ____: def __init__( self, provider_config: Dict[str, Any], node_id: str, cluster_name: str ) -> None: self.node_id = node_id self.cluster_name = cluster_name self.provider_config = provider_config region = provider_config["region"] self.ec2_resource = resour...
CloudwatchHelper
python
doocs__leetcode
lcci/16.14.Best Line/Solution.py
{ "start": 0, "end": 591 }
class ____: def bestLine(self, points: List[List[int]]) -> List[int]: n = len(points) mx = 0 for i in range(n): x1, y1 = points[i] for j in range(i + 1, n): x2, y2 = points[j] cnt = 2 for k in range(j + 1, n): ...
Solution
python
py-pdf__pypdf
pypdf/constants.py
{ "start": 10577, "end": 10779 }
class ____: Fields = "/Fields" NeedAppearances = "/NeedAppearances" SigFlags = "/SigFlags" CO = "/CO" DR = "/DR" DA = "/DA" Q = "/Q" XFA = "/XFA"
InteractiveFormDictEntries
python
dagster-io__dagster
python_modules/dagster/dagster/_utils/concurrency.py
{ "start": 1778, "end": 1845 }
class ____: run_id: str step_key: str @record
ClaimedSlotInfo
python
PyCQA__pylint
tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_returned.py
{ "start": 1308, "end": 1447 }
class ____: """Potential uninferable return value""" def __getnewargs__(self): return tuple(Missing)
AnotherAmbiguousGetNewArgs
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
{ "start": 8940, "end": 9334 }
class ____(StrictBaseModel): """Schema for AssetEvent model used in DagRun.""" asset: AssetReferenceAssetEventDagRun extra: dict[str, JsonValue] source_task_id: str | None source_dag_id: str | None source_run_id: str | None source_map_index: int | None source_aliases: list[AssetAliasRef...
AssetEventDagRunReference
python
dagster-io__dagster
python_modules/dagster/dagster/_config/pythonic_config/resource.py
{ "start": 5912, "end": 24202 }
class ____( Config, TypecheckAllowPartialResourceInitParams, Generic[TResValue], ABC, metaclass=BaseResourceMeta, ): """Base class for creating and managing the lifecycle of Dagster resources that utilize structured config. Users should directly inherit from this class when they want the ob...
ConfigurableResourceFactory
python
huggingface__transformers
src/transformers/models/omdet_turbo/modeling_omdet_turbo.py
{ "start": 2292, "end": 4045 }
class ____(ModelOutput): r""" last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the decoder. decoder_coords (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`): The predicted c...
OmDetTurboDecoderOutput
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/map_and_batch_test.py
{ "start": 17134, "end": 20581 }
class ____(checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine( dro...
MapAndBatchCheckpointTest
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/grid.py
{ "start": 1226, "end": 1389 }
class ____(BaseModel): """DAG Run model for the Grid UI.""" run_id: str dag_id: str task_instances: list[LightGridTaskInstanceSummary]
GridTISummaries
python
python-openxml__python-docx
tests/parts/test_settings.py
{ "start": 420, "end": 2540 }
class ____: def it_is_used_by_loader_to_construct_settings_part(self, load_, package_, settings_part_): partname, blob = "partname", "blob" content_type = CT.WML_SETTINGS load_.return_value = settings_part_ part = PartFactory(partname, content_type, None, blob, package_) lo...
DescribeSettingsPart
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1002292, "end": 1002847 }
class ____(sgqlc.types.Type): """Represents a team repository.""" __schema__ = github_schema __field_names__ = ("cursor", "node", "permission") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field(sgqlc.t...
TeamRepositoryEdge
python
sympy__sympy
sympy/assumptions/predicates/order.py
{ "start": 6646, "end": 7211 }
class ____(Predicate): r""" Positive extended real number predicate. Explanation =========== ``Q.extended_positive(x)`` is true iff ``x`` is extended real and `x > 0`, that is if ``x`` is in the interval `(0, \infty]`. Examples ======== >>> from sympy import ask, I, oo, Q >>>...
ExtendedPositivePredicate
python
airbytehq__airbyte
airbyte-integrations/connectors/source-genesys/source_genesys/source.py
{ "start": 2659, "end": 2878 }
class ____(GenesysStream): """ API Docs: https://developer.genesys.cloud/telephony/locations-apis """ primary_key = "id" def path(self, **kwargs) -> str: return "locations"
TelephonyLocations
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 205222, "end": 208413 }
class ____(test_util.TensorFlowTestCase): # NOTE(b/142795960): parameterized tests do not work well with tf.tensor # inputs. Due to failures, creating another test `testInvalidTensorInput` # which is identical to this one except that the input here is a scalar as # opposed to a tensor. def testInvalidPyInput...
CombinedNonMaxSuppressionTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF031.py
{ "start": 756, "end": 908 }
class ____(dict[str, int]): pass # Skip tuples of length one that are single-starred expressions # https://github.com/astral-sh/ruff/issues/16077 d[*x]
Foo
python
getsentry__sentry
src/sentry/hybridcloud/rpc/pagination.py
{ "start": 2428, "end": 3154 }
class ____(RpcModel): ids: list[int] = Field(default_factory=list) hits: int | None = None max_hits: int | None = None next: RpcCursorState = Field(default_factory=lambda: RpcCursorState()) prev: RpcCursorState = Field(default_factory=lambda: RpcCursorState()) @classmethod def from_cursor_r...
RpcPaginationResult
python
run-llama__llama_index
llama-index-core/llama_index/core/ingestion/pipeline.py
{ "start": 6013, "end": 30444 }
class ____(BaseModel): """ An ingestion pipeline that can be applied to data. Args: name (str, optional): Unique name of the ingestion pipeline. Defaults to DEFAULT_PIPELINE_NAME. project_name (str, optional): Unique name of the project. Defaults to DEFAULT_PROJECT_N...
IngestionPipeline
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 43795, "end": 45593 }
class ____(ASTExpression): def __init__(self, exprs: list[ASTExpression], ops: list[str]) -> None: assert len(exprs) > 0 assert len(exprs) == len(ops) + 1 self.exprs = exprs self.ops = ops def __eq__(self, other: object) -> bool: if not isinstance(other, ASTBinOpExpr): ...
ASTBinOpExpr
python
huggingface__transformers
tests/models/musicgen/test_modeling_musicgen.py
{ "start": 52162, "end": 55393 }
class ____(unittest.TestCase): @cached_property def model(self): return MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-stereo-small").to(torch_device) @cached_property def processor(self): return MusicgenProcessor.from_pretrained("facebook/musicgen-stereo-small") ...
MusicgenStereoIntegrationTests
python
pytest-dev__pytest
testing/test_doctest.py
{ "start": 48698, "end": 50931 }
class ____: def __getattr__(self, _): raise KeyError("This should be an AttributeError") @pytest.mark.parametrize( # pragma: no branch (lambdas are not called) "stop", [ None, pytest.param(_is_mocked, id="is_mocked"), pytest.param(lambda f: None, id="lambda_none"), ...
Broken