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
catalyst-team__catalyst
catalyst/contrib/layers/pooling.py
{ "start": 1776, "end": 2512 }
class ____(nn.Module): """@TODO: Docs (add `Example`). Contribution is welcome.""" def __init__(self): """Constructor method for the ``GlobalConcatPool2d`` class.""" super().__init__() self.avg = GlobalAvgPool2d() self.max = GlobalMaxPool2d() def forward(self, x: torch.Tens...
GlobalConcatPool2d
python
fastai__fastai
fastai/text/models/awdlstm.py
{ "start": 976, "end": 1339 }
class ____(Module): "Dropout with probability `p` that is consistent on the seq_len dimension." def __init__(self, p:float=0.5): self.p=p def forward(self, x): if not self.training or self.p == 0.: return x return x * dropout_mask(x.data, (x.size(0), 1, *x.shape[2:]), self.p) # %% ../../.....
RNNDropout
python
langchain-ai__langchain
libs/text-splitters/langchain_text_splitters/html.py
{ "start": 1562, "end": 11753 }
class ____: """Split HTML content into structured Documents based on specified headers. Splits HTML content by detecting specified header tags and creating hierarchical `Document` objects that reflect the semantic structure of the original content. For each identified section, the splitter associates t...
HTMLHeaderTextSplitter
python
google__pytype
pytype/pytd/serialize_ast.py
{ "start": 414, "end": 526 }
class ____(Exception): """If a dependency can't be restored in the current state."""
UnrestorableDependencyError
python
pyca__cryptography
src/cryptography/x509/general_name.py
{ "start": 2125, "end": 3223 }
class ____(GeneralName): def __init__(self, value: str) -> None: if isinstance(value, str): try: value.encode("ascii") except UnicodeEncodeError: raise ValueError( "DNSName values should be passed as an A-label string. " ...
DNSName
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 6752, "end": 6974 }
class ____(BaseModel, extra="forbid"): type: "BoolIndexType" = Field(..., description="") on_disk: Optional[bool] = Field(default=None, description="If true, store the index on disk. Default: false.")
BoolIndexParams
python
pytorch__pytorch
test/test_utils.py
{ "start": 23278, "end": 25969 }
class ____(TestCase): def setUp(self): super().setUp() from torch.utils.hipify import hipify_python self.trie = hipify_python.Trie() def test_add_and_search_trie(self): self.trie.add("banana") self.assertTrue(self.trie.search("banana")) self.assertFalse(self.tri...
TestHipifyTrie
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/executors/ecs/test_boto_schema.py
{ "start": 1123, "end": 9610 }
class ____: def test_boto_container_schema_load(self): schema = BotoContainerSchema() data = { "exitCode": 0, "lastStatus": "STOPPED", "name": "test_container", "reason": "Essential container in task exited", "containerArn": "arn:aws:ecs:us...
TestBotoSchema
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py
{ "start": 11926, "end": 11996 }
class ____(AdsInsights): breakdowns = ["country"]
AdsInsightsCountry
python
django-compressor__django-compressor
compressor/exceptions.py
{ "start": 812, "end": 950 }
class ____(Exception): """ This exception is raised when a template syntax error is encountered. """ pass
TemplateSyntaxError
python
plotly__plotly.py
plotly/graph_objs/layout/shape/label/_font.py
{ "start": 235, "end": 9894 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.shape.label" _path_str = "layout.shape.label.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } ...
Font
python
google__jax
tests/deprecation_test.py
{ "start": 811, "end": 2886 }
class ____(absltest.TestCase): @contextlib.contextmanager def deprecation_context(self, deprecation_id): deprecations.register(deprecation_id) try: yield finally: deprecations.unregister(deprecation_id) def testModuleDeprecation(self): with test_warning_util.raise_on_warnings(): ...
DeprecationTest
python
PrefectHQ__prefect
tests/test_settings.py
{ "start": 103340, "end": 109918 }
class ____: """Test the PREFECT_CLIENT_CUSTOM_HEADERS setting.""" def test_default_empty_dict(self): """Test that custom headers default to empty dict.""" from prefect.settings import get_current_settings settings = get_current_settings() assert settings.client.custom_headers =...
TestClientCustomHeadersSetting
python
streamlit__streamlit
lib/tests/streamlit/file_uploader_utils_test.py
{ "start": 1918, "end": 3923 }
class ____(unittest.TestCase): @parameterized.expand( [ # Valid cases ("valid_single_extension_pdf", "document.pdf", [".pdf", ".png"], True), ("valid_single_extension_png", "image.png", [".pdf", ".png"], True), ("case_insensitive", "image.png", [".PDF", ".PNG"...
EnforceFilenameRestrictionTest
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/views/test_roles_list.py
{ "start": 2265, "end": 2527 }
class ____: def test_role_model_view(self, client_roles_reader, recwarn): resp = client_roles_reader.get("/roles/list/", follow_redirects=True) _assert_dataset_deprecation_warning(recwarn) assert resp.status_code == 200
TestRolesListView
python
bokeh__bokeh
src/bokeh/protocol/messages/server_info_reply.py
{ "start": 1547, "end": 1609 }
class ____(TypedDict): bokeh: str server: str
VersionInfo
python
getsentry__sentry
src/sentry/seer/similarity/types.py
{ "start": 1202, "end": 1400 }
class ____(TypedDict): responses: list[RawSeerSimilarIssueData] # Like the data that comes back from seer, but guaranteed to have an existing parent hash @dataclass
SimilarIssuesEmbeddingsResponse
python
apache__airflow
providers/slack/src/airflow/providers/slack/operators/slack_webhook.py
{ "start": 1198, "end": 5074 }
class ____(BaseOperator): """ This operator allows you to post messages to Slack using Incoming Webhooks. .. note:: You cannot override the default channel (chosen by the user who installed your app), username, or icon when you're using Incoming Webhooks to post messages. Instead, t...
SlackWebhookOperator
python
weaviate__weaviate-python-client
weaviate/collections/classes/internal.py
{ "start": 3950, "end": 4192 }
class ____: """The generative data returned relevant to a single prompt generative query.""" debug: Optional[generative_pb2.GenerativeDebug] metadata: Optional[GenerativeMetadata] text: Optional[str] @dataclass
GenerativeSingle
python
pytorch__pytorch
test/inductor/test_fp8.py
{ "start": 15632, "end": 54737 }
class ____(TestCase): @unittest.skipIf(not PLATFORM_SUPPORTS_FP8, f8_msg) @parametrize("dtype", (torch.bfloat16, torch.float32)) @parametrize("shape", ("16,16,32", "16,32,32", "1024,1024,512")) @parametrize("has_bias", (False, True)) @parametrize("use_fast_accum", (False, True)) @parametrize( ...
TestFP8Lowering
python
tensorflow__tensorflow
tensorflow/python/module/module_test.py
{ "start": 13161, "end": 13296 }
class ____(AbstractModule): @module.Module.with_name_scope def __call__(self, x): return x ** 2, get_name_scope()
ConcreteModule
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/build_systems/bundle.py
{ "start": 215, "end": 466 }
class ____(PackageBase): """General purpose bundle, or no-code, package class.""" build_system_class = "BundlePackage" default_buildsystem = "bundle" has_code = False build_system("bundle") @register_builder("bundle")
BundlePackage
python
catalyst-team__catalyst
catalyst/contrib/data/reader.py
{ "start": 3088, "end": 4442 }
class ____(IReader): """ Reader abstraction with an lambda encoders. Can read an elem from dataset and apply `encode_fn` function to it. """ def __init__( self, input_key: str, output_key: Optional[str] = None, lambda_fn: Optional[Callable] = None, **kwargs, ...
LambdaReader
python
dagster-io__dagster
python_modules/dagster/dagster/_core/snap/node.py
{ "start": 3309, "end": 4565 }
class ____: mapped_node_name: str mapped_input_name: str external_input_name: str def build_input_mapping_snap(input_mapping: InputMapping) -> InputMappingSnap: return InputMappingSnap( mapped_node_name=input_mapping.maps_to.node_name, mapped_input_name=input_mapping.maps_to.input_name...
InputMappingSnap
python
donnemartin__interactive-coding-challenges
graphs_trees/graph/graph.py
{ "start": 1148, "end": 2079 }
class ____: def __init__(self): self.nodes = {} # Key = key, val = Node def add_node(self, key): if key is None: raise TypeError('key cannot be None') if key not in self.nodes: self.nodes[key] = Node(key) return self.nodes[key] def add_edge(self, s...
Graph
python
numba__numba
numba/cuda/types.py
{ "start": 31, "end": 207 }
class ____(types.Type): """ A 3-tuple (x, y, z) representing the position of a block or thread. """ def __init__(self): super().__init__(name='Dim3')
Dim3
python
pytorch__pytorch
torch/_tensor.py
{ "start": 3333, "end": 76306 }
class ____(torch._C.TensorBase): _is_param: bool def _clear_non_serializable_cached_data(self): r"""Clears any data cached in the tensor's ``__dict__`` that would prevent the tensor from being serialized. For example, subclasses with custom dispatched sizes / strides cache this info in...
Tensor
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 191974, "end": 194504 }
class ____: def test_pmf(self): # comparison to R k = np.arange(-10, 15) mu1, mu2 = 10, 5 skpmfR = np.array( [4.2254582961926893e-005, 1.1404838449648488e-004, 2.8979625801752660e-004, 6.9177078182101231e-004, 1.5480716105844...
TestSkellam
python
ray-project__ray
python/ray/serve/tests/test_task_processor.py
{ "start": 484, "end": 4958 }
class ____: def __init__(self): self.processed_tasks = set() def add_task(self, task_data): self.processed_tasks.add(task_data) def get_processed_tasks(self): return self.processed_tasks def get_count(self): return len(self.processed_tasks) @ray.remote def send_reque...
ProcessedTasksTracker
python
euske__pdfminer
pdfminer/image.py
{ "start": 1729, "end": 4086 }
class ____: def __init__(self, outdir): self.outdir = outdir if not os.path.exists(self.outdir): os.makedirs(self.outdir) return def export_image(self, image): stream = image.stream filters = stream.get_filters() (width, height) = image.srcsize ...
ImageWriter
python
pytorch__pytorch
test/torch_np/test_reductions.py
{ "start": 2364, "end": 5237 }
class ____(TestCase): def test_mean(self): A = [[1, 2, 3], [4, 5, 6]] assert np.mean(A) == 3.5 assert np.all(np.mean(A, 0) == np.array([2.5, 3.5, 4.5])) assert np.all(np.mean(A, 1) == np.array([2.0, 5.0])) # XXX: numpy emits a warning on empty slice assert np.isnan(n...
TestMean
python
jmcnamara__XlsxWriter
xlsxwriter/test/utility/test_xl_rowcol_to_cell.py
{ "start": 323, "end": 2684 }
class ____(unittest.TestCase): """ Test xl_rowcol_to_cell() utility function. """ def test_xl_rowcol_to_cell(self): """Test xl_rowcol_to_cell()""" tests = [ # row, col, A1 string (0, 0, "A1"), (0, 1, "B1"), (0, 2, "C1"), (0, ...
TestUtility
python
django__django
tests/auth_tests/test_forms.py
{ "start": 15502, "end": 17318 }
class ____(BaseUserCreationFormTest): form_class = UserCreationForm def test_case_insensitive_username(self): data = { "username": "TeStClIeNt", "password1": "test123", "password2": "test123", } form = UserCreationForm(data) self.assertFalse(...
UserCreationFormTest
python
numba__numba
numba/tests/test_npdatetime.py
{ "start": 33079, "end": 33178 }
class ____(TestDatetimeArithmetic): jitargs = dict(nopython=True)
TestDatetimeArithmeticNoPython
python
django__django
tests/test_runner/models.py
{ "start": 649, "end": 733 }
class ____(models.Model): people = models.ManyToManyField(Person, through=Through)
B
python
huggingface__transformers
tests/trainer/test_trainer.py
{ "start": 26861, "end": 55832 }
class ____(TestCasePlus, TrainerIntegrationCommon): """ Only tests that want to tap into the auto-pre-run 2 trainings: - self.default_trained_model - self.alternate_trained_model directly, or via check_trained_model """ def setUp(self): super().setUp() args = TrainingArgumen...
TrainerIntegrationPrerunTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1506811, "end": 1507441 }
class ____(sgqlc.types.Type, Node): """Represents a 'subscribed' event on a given `Subscribable`.""" __schema__ = github_schema __field_names__ = ("actor", "created_at", "subscribable") actor = sgqlc.types.Field(Actor, graphql_name="actor") """Identifies the actor who performed the event.""" c...
SubscribedEvent
python
pytorch__pytorch
torch/utils/data/datapipes/utils/decoder.py
{ "start": 9047, "end": 10100 }
class ____: def __init__(self, **loadmat_kwargs) -> None: try: import scipy.io as sio except ImportError as e: raise ModuleNotFoundError( "Package `scipy` is required to be installed for mat file." "Please use `pip install scipy`" ...
MatHandler
python
huggingface__transformers
src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
{ "start": 35884, "end": 38948 }
class ____(XLMRobertaXLPreTrainedModel): _tied_weights_keys = { "lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight", "lm_head.decoder.bias": "lm_head.bias", } def __init__(self, config): super().__init__(config) if config.is_decoder: logger.war...
XLMRobertaXLForMaskedLM
python
kamyu104__LeetCode-Solutions
Python/longest-absolute-file-path.py
{ "start": 62, "end": 797 }
class ____(object): def lengthLongestPath(self, input): """ :type input: str :rtype: int """ def split_iter(s, tok): start = 0 for i in xrange(len(s)): if s[i] == tok: yield s[start:i] start = i +...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-microsoft-lists/integration_tests/fast/test_airbyte_standards.py
{ "start": 384, "end": 734 }
class ____(standard_tests.DeclarativeSourceTestSuite): """Test suite for the Airbyte standard tests. This class inherits from SourceTestSuiteBase and implements all of the tests in the suite. As long as the class name starts with "Test", pytest will automatically discover and run the tests in this class...
TestAirbyteStandardTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_product_dimension_performance_report.py
{ "start": 220, "end": 1859 }
class ____(TestSuiteReportStream): state_file_after_migration = "non_hourly_reports_state_after_migration" state_file_after_migration_with_cursor_further_config_start_date = ( "non_hourly_reports_state_after_migration_with_cursor_further_config_start_date" ) first_read_state = get_state_after_mi...
TestBaseProductDimensionPerformanceReport
python
getsentry__sentry-python
sentry_sdk/integrations/django/transactions.py
{ "start": 1045, "end": 4951 }
class ____: _new_style_group_matcher = re.compile( r"<(?:([^>:]+):)?([^>]+)>" ) # https://github.com/django/django/blob/21382e2743d06efbf5623e7c9b6dccf2a325669b/django/urls/resolvers.py#L245-L247 _optional_group_matcher = re.compile(r"\(\?\:([^\)]+)\)") _named_group_matcher = re.compile(r"\(\?P...
RavenResolver
python
plotly__plotly.py
plotly/graph_objs/layout/_font.py
{ "start": 235, "end": 9909 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout" _path_str = "layout.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @property def col...
Font
python
huggingface__transformers
tests/pipelines/test_pipelines_image_classification.py
{ "start": 1388, "end": 10995 }
class ____(unittest.TestCase): model_mapping = MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _dataset = None @classmethod def _load_dataset(cls): # Lazy loading of the dataset. Because it is a class method, it will only be loaded once per pytest process. if cls._dataset is None: # ...
ImageClassificationPipelineTests
python
pennersr__django-allauth
allauth/socialaccount/providers/openid/admin.py
{ "start": 134, "end": 289 }
class ____(admin.ModelAdmin): pass admin.site.register(OpenIDStore, OpenIDStoreAdmin) admin.site.register(OpenIDNonce, OpenIDNonceAdmin)
OpenIDNonceAdmin
python
realpython__materials
python-del-statement/factorial.py
{ "start": 0, "end": 774 }
class ____: def __init__(self, number): self._number = number self._cache = {0: 1, 1: 1} self._factorial = self._calculate_factorial(number) del self._cache def _calculate_factorial(self, number): if number in self._cache: return self._cache[number] c...
Factorial
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 21644, "end": 21916 }
class ____(BaseModel): """ Scheduler info serializer for responses. """ status: Annotated[str | None, Field(title="Status")] = None latest_scheduler_heartbeat: Annotated[str | None, Field(title="Latest Scheduler Heartbeat")] = None
SchedulerInfoResponse
python
sqlalchemy__sqlalchemy
test/orm/dml/test_orm_upd_del_assorted.py
{ "start": 13023, "end": 14090 }
class ____(fixtures.DeclarativeMappedTest): __sparse_driver_backend__ = True __only_on__ = ("postgresql",) @classmethod def setup_classes(cls): from sqlalchemy.dialects.postgresql import JSONB Base = cls.DeclarativeBasic class TestTbl(Base): __tablename__ = "testt...
PGIssue11849Test
python
pikepdf__pikepdf
tests/test_parsers.py
{ "start": 9541, "end": 10720 }
class ____: def test_indirect_object(self): p = pikepdf.new() arr = p.make_indirect(Array([42])) d = p.make_indirect(Dictionary(Foo=Name.Bar)) stream = p.make_stream(b'test stream') with pytest.raises(TypeError): ContentStreamInstruction([arr], Operator('Do')) ...
TestBadSingleInstructions
python
PrefectHQ__prefect
src/integrations/prefect-aws/prefect_aws/workers/ecs_worker.py
{ "start": 7971, "end": 8146 }
class ____(BaseModel): """ The capacity provider strategy to use when running the task. """ capacityProvider: str weight: int base: int
CapacityProvider
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 14504, "end": 14850 }
class ____(RoleImpl): __slots__ = () def _implicit_coercions(self, element, resolved, argname=None, **kw): if isinstance(element, str): return element else: self._raise_for_expected(element, argname, resolved) def _literal_coercion(self, element, **kw): retu...
_ReturnsStringKey
python
paramiko__paramiko
paramiko/ssh_exception.py
{ "start": 974, "end": 1252 }
class ____(SSHException): """ Exception raised when authentication failed for some reason. It may be possible to retry with different credentials. (Other classes specify more specific reasons.) .. versionadded:: 1.6 """ pass
AuthenticationException
python
matplotlib__matplotlib
lib/matplotlib/backends/backend_gtk3.py
{ "start": 22540, "end": 22647 }
class ____(_BackendGTK): FigureCanvas = FigureCanvasGTK3 FigureManager = FigureManagerGTK3
_BackendGTK3
python
spack__spack
lib/spack/spack/stage.py
{ "start": 48433, "end": 48513 }
class ____(StageError): """Error encountered during restaging."""
RestageError
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 78178, "end": 78369 }
class ____(BiffRecord): """ Semantic is equal to HEADER record """ _REC_ID = 0x0015 def __init__(self, footer_str): self._rec_data = upack2(footer_str)
FooterRecord
python
getsentry__sentry
src/sentry/sentry_metrics/querying/visitors/query_condition.py
{ "start": 3230, "end": 3902 }
class ____(QueryConditionVisitor[QueryCondition]): """ Visitor that recursively transforms all conditions whose `key` matches one of the supplied mappings. If found, replaces it with the mapped value. """ def __init__(self, mappings: Mapping[str, str]): self._mappings = mappings def _v...
MappingTransformationVisitor
python
pytorch__pytorch
torch/_dynamo/variables/user_defined.py
{ "start": 80306, "end": 80628 }
class ____(UserDefinedObjectVariable): # Dummy class to check if the object is an IntWrapper, and turn it into a # symint @staticmethod def is_matching_object(obj): mod = sys.modules.get("torch.export.dynamic_shapes") return mod is not None and type(obj) is mod._IntWrapper
IntWrapperVariable
python
getsentry__sentry
src/sentry/utils/types.py
{ "start": 2537, "end": 2855 }
class ____(Type[float]): """Coerce a float from a string or integer""" name = "float" default = 0.0 expected_types = (float,) compatible_types = (str, int, float) def convert(self, value): try: return float(value) except ValueError: return None
FloatType
python
apache__airflow
providers/apache/beam/tests/unit/apache/beam/hooks/test_beam.py
{ "start": 2977, "end": 14553 }
class ____: @mock.patch(BEAM_STRING.format("run_beam_command")) @mock.patch("airflow.providers.apache.beam.hooks.beam.subprocess.check_output", return_value=b"2.39.0") def test_start_python_pipeline(self, mock_check_output, mock_runner): hook = BeamHook(runner=DEFAULT_RUNNER) process_line_ca...
TestBeamHook
python
doocs__leetcode
solution/0700-0799/0700.Search in a Binary Search Tree/Solution.py
{ "start": 192, "end": 508 }
class ____: def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None or root.val == val: return root return ( self.searchBST(root.left, val) if root.val > val else self.searchBST(root.right, val) )
Solution
python
openai__openai-python
src/openai/types/responses/response_output_text_param.py
{ "start": 833, "end": 1344 }
class ____(TypedDict, total=False): end_index: Required[int] """The index of the last character of the URL citation in the message.""" start_index: Required[int] """The index of the first character of the URL citation in the message.""" title: Required[str] """The title of the web resource."""...
AnnotationURLCitation
python
gevent__gevent
src/gevent/events.py
{ "start": 6901, "end": 7234 }
class ____(object): """ The event emitted when the event loop is blocked. Implements `IEventLoopBlocked`. """ def __init__(self, greenlet, blocking_time, info, *, hub=None): self.greenlet = greenlet self.blocking_time = blocking_time self.info = info self.hub = hub ...
EventLoopBlocked
python
great-expectations__great_expectations
great_expectations/datasource/fluent/sources.py
{ "start": 1844, "end": 2139 }
class ____(str, Enum): ADD = "ADD" DELETE = "DELETE" # Deprecated as we don't care about backend-specific deletion UPDATE = "UPDATE" ADD_OR_UPDATE = "ADD_OR_UPDATE" CrudMethodInfoFn: TypeAlias = Callable[..., Tuple[CrudMethodType, Type["Datasource"]]] @public_api
CrudMethodType
python
aio-libs__aiohttp
aiohttp/abc.py
{ "start": 3972, "end": 5084 }
class ____(Sized, Iterable[Morsel[str]]): """Abstract Cookie Jar.""" @property @abstractmethod def quote_cookie(self) -> bool: """Return True if cookies should be quoted.""" @abstractmethod def clear(self, predicate: ClearCookiePredicate | None = None) -> None: """Clear all coo...
AbstractCookieJar
python
xlwings__xlwings
xlwings/constants.py
{ "start": 58109, "end": 58395 }
class ____: xlErrorBarIncludeBoth = 1 # from enum XlErrorBarInclude xlErrorBarIncludeMinusValues = 3 # from enum XlErrorBarInclude xlErrorBarIncludeNone = -4142 # from enum XlErrorBarInclude xlErrorBarIncludePlusValues = 2 # from enum XlErrorBarInclude
ErrorBarInclude
python
davidhalter__jedi
jedi/file_io.py
{ "start": 1779, "end": 2195 }
class ____(file_io.KnownContentFileIO, FileIOFolderMixin): """For .zip and .egg archives""" def __init__(self, path, code, zip_path): super().__init__(path, code) self._zip_path = zip_path def get_last_modified(self): try: return os.path.getmtime(self._zip_path) ...
ZipFileIO
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/errors.py
{ "start": 9656, "end": 9872 }
class ____(Exception): """Signal that the type inference should be rewound due to recursive types. Internal use only.""" def __init__(self, target: object) -> None: self.target = target
RewindRecursive
python
ray-project__ray
rllib/examples/rl_modules/classes/vpg_using_shared_encoder_rlm.py
{ "start": 457, "end": 1618 }
class ____(TorchRLModule): """A VPG (vanilla pol. gradient)-style RLModule using a shared encoder. # __sphinx_doc_policy_end__ The shared encoder RLModule must be held by the same MultiRLModule, under which this RLModule resides. The shared encoder's forward is called before this RLModu...
VPGPolicyAfterSharedEncoder
python
pytorch__pytorch
torch/_dynamo/variables/distributed.py
{ "start": 15006, "end": 18780 }
class ____(VariableTracker): """ Handles torch.utils.hooks.BackwardHook for module-level backward hooks. """ @staticmethod def create( tx: "InstructionTranslator", module: VariableTracker, user_hooks: VariableTracker, user_pre_hooks: VariableTracker, ) -> "Ba...
BackwardHookVariable
python
Netflix__metaflow
test/core/tests/card_refresh_test.py
{ "start": 72, "end": 7599 }
class ____(MetaflowTest): """ This test Does few checks that the core user interfaces are working : 1. It validates we can call `current.card.refresh` without any errors. 2. It validates if the data updates that are getting shipped are correct. How will it do it : 1. In step code: 1. W...
CardWithRefreshTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 22800, "end": 23285 }
class ____(graphene.Interface): runId = graphene.NonNull(graphene.String) stepKey = graphene.NonNull(graphene.String) status = graphene.Field(GrapheneStepEventStatus) startTime = graphene.Field(graphene.Float) endTime = graphene.Field(graphene.Float) materializations = non_null_list(GrapheneMate...
GraphenePipelineRunStepStats
python
gevent__gevent
src/greentest/3.14/test_httpservers.py
{ "start": 15093, "end": 16228 }
class ____(BaseTestCase): class request_handler(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' default_request_version = 'HTTP/1.1' def do_GET(self): self.send_response(HTTPStatus.OK) self.end_headers() def do_ERROR(self): self.send_error...
RequestHandlerLoggingTestCase
python
run-llama__llama_index
llama-index-integrations/program/llama-index-program-evaporate/llama_index/program/evaporate/df.py
{ "start": 4755, "end": 7670 }
class ____(BasePydanticProgram[DataFrameRowsOnly]): """ DF Rows output parser. Given DF schema, extract text into a set of rows. """ def __init__( self, pydantic_program_cls: Type[BaseLLMFunctionProgram], df_parser_template_str: str = DEFAULT_ROWS_DF_PARSER_TMPL, c...
DFRowsProgram
python
sympy__sympy
doc/ext/docscrape.py
{ "start": 161, "end": 1986 }
class ____: """ A line-based string reader. """ def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\n'. """ if isinstance(data, list): self._str = data else: self._str ...
Reader
python
kamyu104__LeetCode-Solutions
Python/sequentially-ordinal-rank-tracker.py
{ "start": 101, "end": 505 }
class ____(object): def __init__(self): self.__sl = SortedList() self.__i = 0 def add(self, name, score): """ :type name: str :type score: int :rtype: None """ self.__sl.add((-score, name)) def get(self): """ :rtype: ...
SORTracker
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 22978, "end": 26089 }
class ____(BaseModel): type: Literal["MinMaxDatetime"] datetime: str = Field( ..., description="Datetime value.", examples=["2021-01-01", "2021-01-01T00:00:00Z", "{{ config['start_time'] }}"], title="Datetime", ) datetime_format: Optional[str] = Field( "", ...
MinMaxDatetime
python
getsentry__sentry
src/sentry/models/apigrant.py
{ "start": 925, "end": 3820 }
class ____(Model): """ A grant represents a token with a short lifetime that can be swapped for an access token, as described in :rfc:`4.1.2` of the OAuth 2 spec. """ __relocation_scope__ = RelocationScope.Global user = FlexibleForeignKey("sentry.User") application = FlexibleForeignKey...
ApiGrant
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-milvus/destination_milvus/indexer.py
{ "start": 749, "end": 6674 }
class ____(Indexer): config: MilvusIndexingConfigModel def __init__(self, config: MilvusIndexingConfigModel, embedder_dimensions: int): super().__init__(config) self.embedder_dimensions = embedder_dimensions def _connect(self): connections.connect( uri=self.config.host,...
MilvusIndexer
python
tensorflow__tensorflow
tensorflow/python/data/experimental/ops/data_service_ops.py
{ "start": 2147, "end": 5347 }
class ____(enum.IntEnum): """Specifies how to shard data among tf.data service workers. OFF: No sharding will be performed. Each worker produces the entire dataset without any sharding. With this mode, the best practice is to shuffle the dataset nondeterministically so that workers process the dataset in diffe...
ShardingPolicy
python
readthedocs__readthedocs.org
readthedocs/api/v2/views/model_views.py
{ "start": 9242, "end": 15878 }
class ____(DisableListEndpoint, UpdateModelMixin, UserSelectViewSet): permission_classes = [HasBuildAPIKey | ReadOnlyPermission] renderer_classes = (JSONRenderer, PlainTextBuildRenderer) model = Build filterset_fields = ("project__slug", "commit") def get_serializer_class(self): """ ...
BuildViewSet
python
walkccc__LeetCode
solutions/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031.py
{ "start": 0, "end": 795 }
class ____: def maxSumTwoNoOverlap( self, nums: list[int], firstLen: int, secondLen: int, ) -> int: def helper(l: int, r: int) -> int: n = len(nums) left = [0] * n summ = 0 for i in range(n): summ += nums[i] if i >= l: summ -= nums[i - l...
Solution
python
walkccc__LeetCode
solutions/3027. Find the Number of Ways to Place People II/3027.py
{ "start": 0, "end": 639 }
class ____: # Same as 3025. Find the Number of Ways to Place People I def numberOfPairs(self, points: list[list[int]]) -> int: ans = 0 points.sort(key=lambda x: (x[0], -x[1])) for i, (_, yi) in enumerate(points): maxY = -math.inf for j in range(i + 1, len(points)): _, yj = points[j...
Solution
python
apache__airflow
task-sdk/src/airflow/sdk/types.py
{ "start": 2099, "end": 4183 }
class ____(Protocol): """Minimal interface for a task instance available during the execution.""" id: uuid.UUID dag_version_id: uuid.UUID task: BaseOperator task_id: str dag_id: str run_id: str try_number: int map_index: int | None max_tries: int hostname: str | None = None ...
RuntimeTaskInstanceProtocol
python
django__django
django/db/models/functions/math.py
{ "start": 5951, "end": 6048 }
class ____(NumericOutputFieldMixin, Transform): function = "SQRT" lookup_name = "sqrt"
Sqrt
python
tensorflow__tensorflow
tensorflow/python/checkpoint/async_checkpoint_helper.py
{ "start": 5834, "end": 26199 }
class ____: """Helper class for async checkpoint.""" def __init__(self, checkpointer_impl, root=None, **kwargs): """Initialize AsyncCheckpoint. Args: checkpointer_impl: The Checkpoint class to power the AsyncCheckpoint. root: The root object to checkpoint. `root` may be a trackable object or ...
AsyncCheckpointHelper
python
tensorflow__tensorflow
tensorflow/python/util/protobuf/compare_test.py
{ "start": 1145, "end": 10162 }
class ____(googletest.TestCase): def assertNotEquals(self, a, b): """Asserts that ProtoEq says a != b.""" a, b = LargePbs(a, b) googletest.TestCase.assertEqual(self, compare.ProtoEq(a, b), False) def assertEqual(self, a, b): """Asserts that ProtoEq says a == b.""" a, b = LargePbs(a, b) goo...
ProtoEqTest
python
protocolbuffers__protobuf
python/google/protobuf/internal/descriptor_pool_test.py
{ "start": 44510, "end": 45559 }
class ____(object): def __init__(self, number, type_name): self.number = number self.type_name = type_name def CheckField(self, test, msg_desc, name, index, file_desc): field_desc = msg_desc.fields_by_name[name] field_type_desc = msg_desc.nested_types_by_name[self.type_name] test.assertEqual(n...
MessageField
python
kamyu104__LeetCode-Solutions
Python/where-will-the-ball-fall.py
{ "start": 33, "end": 512 }
class ____(object): def findBall(self, grid): """ :type grid: List[List[int]] :rtype: List[int] """ result = [] for c in xrange(len(grid[0])): for r in xrange(len(grid)): nc = c+grid[r][c] if not (0 <= nc < len(grid[0]) and ...
Solution
python
huggingface__transformers
tests/models/maskformer/test_modeling_maskformer_swin.py
{ "start": 1332, "end": 6129 }
class ____: def __init__( self, parent, batch_size=13, image_size=32, patch_size=2, num_channels=3, embed_dim=16, depths=[1, 2, 1], num_heads=[2, 2, 4], window_size=2, mlp_ratio=2.0, qkv_bias=True, hidden_dropout...
MaskFormerSwinModelTester
python
run-llama__llama_index
llama-index-core/llama_index/core/chat_ui/models/artifact.py
{ "start": 106, "end": 183 }
class ____(str, Enum): CODE = "code" DOCUMENT = "document"
ArtifactType
python
getsentry__sentry
src/sentry/taskworker/app.py
{ "start": 315, "end": 2764 }
class ____: """ Container for an application's task setup and configuration. """ def __init__(self, taskregistry: TaskRegistry | None = None) -> None: self._config = { "rpc_secret": None, "at_most_once_timeout": None, } self._modules: Iterable[str] = [] ...
TaskworkerApp
python
ray-project__ray
python/ray/serve/tests/unit/test_application_state.py
{ "start": 1874, "end": 9106 }
class ____: def __init__(self, kv_store): self.kv_store = kv_store self.deployment_infos: Dict[DeploymentID, DeploymentInfo] = dict() self.deployment_statuses: Dict[DeploymentID, DeploymentStatusInfo] = dict() self.deleting: Dict[DeploymentID, bool] = dict() # Recover ...
MockDeploymentStateManager
python
PrefectHQ__prefect
tests/test_task_engine.py
{ "start": 63173, "end": 70073 }
class ____: async def test_result_stored_with_storage_key_if_no_policy_set( self, prefect_client ): # avoid conflicts key = f"foo-bar-{random.randint(0, 10000)}" @task(persist_result=True, result_storage_key=key) async def async_task(): return 1800 s...
TestCachePolicy
python
aio-libs__aiohttp
aiohttp/http_exceptions.py
{ "start": 1366, "end": 1452 }
class ____(BadHttpMessage): """Base class for payload errors"""
PayloadEncodingError
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_lib.py
{ "start": 167631, "end": 168008 }
class ____(ReplicaContextBase): __doc__ = ReplicaContextBase.__doc__ def _batch_reduce_destination(x): """Returns the destinations for batch all-reduce.""" if isinstance(x, tensor_lib.Tensor): # If this is a one device strategy. return x.device else: return x # ------------------------------------...
ReplicaContextV1
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 14519, "end": 14825 }
class ____(_VectorizerConfigCreate): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.TEXT2VEC_WEAVIATE, frozen=True, exclude=True ) model: Optional[str] baseURL: Optional[str] vectorizeClassName: bool dimensions: Optional[int]
_Text2VecWeaviateConfig
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/executors/batch/utils.py
{ "start": 4785, "end": 5145 }
class ____(BatchSubmitJobKwargsConfigKeys): """All keys loaded into the config which are related to the Batch Executor.""" MAX_SUBMIT_JOB_ATTEMPTS = "max_submit_job_attempts" AWS_CONN_ID = "conn_id" SUBMIT_JOB_KWARGS = "submit_job_kwargs" REGION_NAME = "region_name" CHECK_HEALTH_ON_STARTUP = "c...
AllBatchConfigKeys
python
cherrypy__cherrypy
cherrypy/test/test_wsgi_vhost.py
{ "start": 51, "end": 1061 }
class ____(helper.CPWebCase): @staticmethod def setup_server(): class ClassOfRoot(object): def __init__(self, name): self.name = name @cherrypy.expose def index(self): return 'Welcome to the %s website!' % self.name default = ...
WSGI_VirtualHost_Test
python
PrefectHQ__prefect
src/prefect/utilities/visualization.py
{ "start": 2907, "end": 7421 }
class ____: def __init__(self): self.tasks: list[VizTask] = [] self.dynamic_task_counter: dict[str, int] = {} self.object_id_to_task: dict[int, VizTask] = {} def add_task(self, task: VizTask) -> None: if task.name not in self.dynamic_task_counter: self.dynamic_task_c...
TaskVizTracker