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
doocs__leetcode
solution/0800-0899/0835.Image Overlap/Solution.py
{ "start": 0, "end": 463 }
class ____: def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: n = len(img1) cnt = Counter() for i in range(n): for j in range(n): if img1[i][j]: for h in range(n): for k in range(n): ...
Solution
python
jazzband__django-oauth-toolkit
oauth2_provider/views/device.py
{ "start": 3191, "end": 4703 }
class ____(LoginRequiredMixin, FormView): """ The view where the user is instructed (by the device) to come to in order to enter the user code. More details in this section of the RFC: https://datatracker.ietf.org/doc/html/rfc8628#section-3.3 Note: it's common to see in other implementations of thi...
DeviceUserCodeView
python
kamyu104__LeetCode-Solutions
Python/count-the-digits-that-divide-a-number.py
{ "start": 39, "end": 312 }
class ____(object): def countDigits(self, num): """ :type num: int :rtype: int """ result = 0 curr = num while curr: result += int(num%(curr%10) == 0) curr //= 10 return result
Solution
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataplex.py
{ "start": 13442, "end": 14420 }
class ____: @mock.patch(HOOK_STR) @mock.patch(DATASCANJOB_STR) def test_execute(self, mock_data_scan_job, hook_mock): op = DataplexRunDataProfileScanOperator( task_id="execute_data_scan", project_id=PROJECT_ID, region=REGION, data_scan_id=DATA_SCAN_ID,...
TestDataplexRunDataProfileScanOperator
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-uniprot/llama_index/readers/uniprot/base.py
{ "start": 871, "end": 15279 }
class ____(BaseReader): """ UniProt reader for LlamaIndex. Reads UniProt Swiss-Prot format files and converts them into LlamaIndex Documents. Each record is converted into a document with structured text and metadata. Args: include_fields (Optional[Set[str]]): Set of fields to include in t...
UniProtReader
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/resource_requirement.py
{ "start": 7267, "end": 10062 }
class ____(ResourceKeyRequirement): key: str # pyright: ignore[reportIncompatibleMethodOverride] source_key: Optional[str] def describe_requirement(self) -> str: source_descriptor = f" by resource with key '{self.source_key}'" if self.source_key else "" return f"resource with key '{self.ke...
ResourceDependencyRequirement
python
getsentry__sentry
tests/sentry/features/test_flagpole_context.py
{ "start": 5956, "end": 8651 }
class ____(TestCase): def test_without_user_passed(self) -> None: context_data = project_context_transformer(SentryContextData()) assert context_data == {} def test_with_invalid_user_passed(self) -> None: with pytest.raises(InvalidContextDataException): user_context_transfor...
TestUserContextTransformer
python
huggingface__transformers
src/transformers/models/phi3/modular_phi3.py
{ "start": 9111, "end": 9187 }
class ____(MistralPreTrainedModel): _version = "0.0.5"
Phi3PreTrainedModel
python
django-guardian__django-guardian
example_project_custom_group/core/migrations/0001_initial.py
{ "start": 251, "end": 4901 }
class ____(migrations.Migration): initial = True dependencies = [ ("auth", "0012_alter_user_first_name_max_length"), ] operations = [ migrations.CreateModel( name="CustomGroup", fields=[ ( "group_ptr", mode...
Migration
python
neetcode-gh__leetcode
python/2616-minimize-the-maximum-difference-of-pairs.py
{ "start": 0, "end": 619 }
class ____: def minimizeMax(self, nums: List[int], p: int) -> int: nums.sort() def checkPair(mid): count, i = 0, 0 while i < len(nums) - 1: if nums[i + 1] - nums[i] <= mid: count += 1 i += 2 else: ...
Solution
python
google__jax
docs/autodidax.py
{ "start": 73326, "end": 73369 }
class ____(NamedTuple): val: Any
ConstRecipe
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/components/using-template-variables/component.py
{ "start": 61, "end": 349 }
class ____(dg.Component): @staticmethod @dg.template_var def database_url() -> str: return "postgresql://localhost:5432/mydb" @staticmethod @dg.template_var def get_table_name() -> Callable: return lambda prefix: f"{prefix}_processed_data"
MyComponent
python
huggingface__transformers
tests/models/prophetnet/test_modeling_prophetnet.py
{ "start": 30424, "end": 40770 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (ProphetNetModel, ProphetNetForConditionalGeneration) if is_torch_available() else () pipeline_model_mapping = ( { "feature-extraction": ProphetNetModel, "summarizatio...
ProphetNetModelTest
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-glassflow/destination_glassflow/destination.py
{ "start": 979, "end": 4836 }
class ____(Destination): def write( self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage] ) -> Iterable[AirbyteMessage]: """ Reads the input stream of messages, config, and catalog to write data to the destination. ...
DestinationGlassflow
python
aio-libs__aiohttp
aiohttp/client.py
{ "start": 3825, "end": 4755 }
class ____(TypedDict, total=False): params: Query data: Any json: Any cookies: LooseCookies | None headers: LooseHeaders | None skip_auto_headers: Iterable[str] | None auth: BasicAuth | None allow_redirects: bool max_redirects: int compress: str | bool chunked: bool | None ...
_RequestOptions
python
pytorch__pytorch
test/distributed/pipelining/model_registry.py
{ "start": 2031, "end": 3798 }
class ____(torch.nn.Module): DEFAULT_DHID = 512 DEFAULT_BATCH_SIZE = 256 def __init__(self, d_hid: int = DEFAULT_DHID, splits=2): assert splits <= 8 super().__init__() self.splits = splits self.mm_param0 = torch.nn.Parameter(torch.randn(d_hid, d_hid)) self.mm_param1 ...
ModelWithKwargs
python
explosion__spaCy
spacy/lang/fi/__init__.py
{ "start": 282, "end": 536 }
class ____(BaseDefaults): infixes = TOKENIZER_INFIXES suffixes = TOKENIZER_SUFFIXES tokenizer_exceptions = TOKENIZER_EXCEPTIONS lex_attr_getters = LEX_ATTRS stop_words = STOP_WORDS syntax_iterators = SYNTAX_ITERATORS
FinnishDefaults
python
getsentry__sentry
src/sentry/api/endpoints/prompts_activity.py
{ "start": 1336, "end": 5125 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.UNKNOWN, "PUT": ApiPublishStatus.UNKNOWN, } def get(self, request: Request, **kwargs) -> Response: """Return feature prompt status if dismissed or in snoozed period""" if not request.user.is_authen...
PromptsActivityEndpoint
python
zostera__django-bootstrap4
tests/forms.py
{ "start": 399, "end": 556 }
class ____(forms.Form): subject = forms.CharField( max_length=100, help_text="my_help_text", required=True, )
CharFieldTestForm
python
kubernetes-client__python
kubernetes/client/models/v1_persistent_volume_spec.py
{ "start": 383, "end": 31908 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1PersistentVolumeSpec
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 2552, "end": 2741 }
class ____(Point): @classmethod def coerce(cls, key, value): if isinstance(value, tuple): value = Point(*value) return value @dataclasses.dataclass
MyPoint
python
huggingface__transformers
src/transformers/models/gemma3/modeling_gemma3.py
{ "start": 45886, "end": 55030 }
class ____(Gemma3PreTrainedModel, GenerationMixin): _checkpoint_conversion_mapping = { "^language_model.model": "model.language_model", "^vision_tower": "model.vision_tower", "^multi_modal_projector": "model.multi_modal_projector", "^language_model.lm_head": "lm_head", } _tie...
Gemma3ForConditionalGeneration
python
cherrypy__cherrypy
cherrypy/_cpconfig.py
{ "start": 4982, "end": 5931 }
class ____(reprconf.Config): """The 'global' configuration data for the entire CherryPy process.""" def update(self, config): """Update self from a dict, file or filename.""" _if_filename_register_autoreload(config) super(Config, self).update(config) def _apply(self, config): ...
Config
python
walkccc__LeetCode
solutions/1713. Minimum Operations to Make a Subsequence/1713.py
{ "start": 0, "end": 678 }
class ____: def minOperations(self, target: list[int], arr: list[int]) -> int: indices = [] numToIndex = {num: i for i, num in enumerate(target)} for a in arr: if a in numToIndex: indices.append(numToIndex[a]) return len(target) - self._lengthOfLIS(indices) # Same as 300. Longest In...
Solution
python
mlflow__mlflow
mlflow/models/rag_signatures.py
{ "start": 1028, "end": 1383 }
class ____: index: int = 0 message: Message = field( default_factory=lambda: Message( role="assistant", content="MLflow is an open source platform for the machine learning lifecycle.", ) ) finish_reason: str = "stop" @deprecated("mlflow.types.llm.ChatCompletionC...
ChainCompletionChoice
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_slots/SLOT002.py
{ "start": 634, "end": 712 }
class ____(namedtuple("foo", ["str", "int"]), object): pass
UnusualButStillBad
python
numba__numba
numba/core/typing/builtins.py
{ "start": 9046, "end": 9981 }
class ____(ConcreteTemplate): # For bitshifts, only the first operand's signedness matters # to choose the operation's signedness (the second operand # should always be positive but will generally be considered # signed anyway, since it's often a constant integer). # (also, see issue #1995 for right...
BitwiseShiftOperation
python
sphinx-doc__sphinx
sphinx/util/logging.py
{ "start": 2465, "end": 2912 }
class ____(logging.LogRecord): """Log record class supporting location""" prefix = '' location: Any = None def getMessage(self) -> str: message = super().getMessage() location = getattr(self, 'location', None) if location: message = f'{location}: {self.prefix}{messa...
SphinxLogRecord
python
getsentry__sentry
src/sentry/identity/services/identity/impl.py
{ "start": 656, "end": 4780 }
class ____(IdentityService): def get_provider( self, *, provider_id: int | None = None, provider_type: str | None = None, provider_ext_id: str | None = None, ) -> RpcIdentityProvider | None: from sentry.users.models.identity import IdentityProvider # If a...
DatabaseBackedIdentityService
python
google__jax
jax/_src/interpreters/batching.py
{ "start": 17517, "end": 18737 }
class ____: name : Any size : Any # Only one of spmd_axis_name and explicit_mesh_axis is set. spmd_name : Any # short for private `_explicit_mesh_axis`. The public property is called # `.explicit_mesh_axis` _ema: tuple[Any, ...] | None @property def explicit_mesh_axis(self): assert self._ema is N...
AxisData
python
walkccc__LeetCode
solutions/1429. First Unique Number/1429.py
{ "start": 0, "end": 532 }
class ____: def __init__(self, nums: list[int]): self.seen = set() self.unique = {} for num in nums: self.add(num) def showFirstUnique(self) -> int: return next(iter(self.unique), -1) def add(self, value: int) -> None: if value not in self.seen: self.seen.add(value) self.un...
FirstUnique
python
walkccc__LeetCode
solutions/2531. Make Number of Distinct Characters Equal/2531.py
{ "start": 0, "end": 854 }
class ____: def isItPossible(self, word1: str, word2: str) -> bool: count1 = collections.Counter(word1) count2 = collections.Counter(word2) distinct1 = len(count1) distinct2 = len(count2) for a in count1: for b in count2: if a == b: # Swapping the same letters won't change...
Solution
python
numba__llvmlite
llvmlite/tests/test_binding.py
{ "start": 36194, "end": 41831 }
class ____(object): """ Mixin for ExecutionEngine tests. """ def get_sum(self, ee, func_name="sum"): ee.finalize_object() cfptr = ee.get_function_address(func_name) self.assertTrue(cfptr) return CFUNCTYPE(c_int, c_int, c_int)(cfptr) def test_run_code(self): ...
JITTestMixin
python
google__pytype
pytype/matcher.py
{ "start": 2057, "end": 2312 }
class ____: """A correct type/actual value match.""" view: _ViewType subst: _SubstType @classmethod def default(cls): return cls(datatypes.AccessTrackingDict(), datatypes.HashableDict()) @dataclasses.dataclass(eq=True, frozen=True)
GoodMatch
python
pypa__setuptools
setuptools/_distutils/command/install_egg_info.py
{ "start": 279, "end": 2868 }
class ____(Command): """Install an .egg-info file for the package""" description = "Install package's PKG-INFO metadata as an .egg-info file" user_options: ClassVar[list[tuple[str, str, str]]] = [ ('install-dir=', 'd', "directory to install to"), ] def initialize_options(self): sel...
install_egg_info
python
Netflix__metaflow
metaflow/_vendor/importlib_metadata/__init__.py
{ "start": 1257, "end": 2827 }
class ____: """ A simple entry point config parser for performance >>> for item in Sectioned.read(Sectioned._sample): ... print(item) Pair(name='sec1', value='# comments ignored') Pair(name='sec1', value='a = 1') Pair(name='sec1', value='b = 2') Pair(name='sec2', value='a = 2') ...
Sectioned
python
arrow-py__arrow
arrow/locales.py
{ "start": 47504, "end": 47573 }
class ____(GermanBaseLocale, Locale): names = ["de-ch"]
SwissLocale
python
pypa__pipenv
pipenv/patched/pip/_internal/exceptions.py
{ "start": 11363, "end": 12644 }
class ____(DiagnosticPipError, InstallationError): """A subprocess call failed.""" reference = "subprocess-exited-with-error" def __init__( self, *, command_description: str, exit_code: int, output_lines: Optional[List[str]], ) -> None: if output_lines i...
InstallationSubprocessError
python
bokeh__bokeh
src/bokeh/models/annotations/legends.py
{ "start": 3337, "end": 7776 }
class ____(Annotation): ''' Abstract base class for color bars. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) location = Either(Enum(HVAlign), Tuple(Float, Float), default="top_right", help=""" ...
BaseColorBar
python
django__django
tests/migrations/test_migrations_clashing_prefix/a.py
{ "start": 35, "end": 83 }
class ____(migrations.Migration): pass
Migration
python
GoogleCloudPlatform__python-docs-samples
kubernetes_engine/django_tutorial/polls/migrations/0001_initial.py
{ "start": 763, "end": 1940 }
class ____(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Choice', fields=[ ('id', models.AutoField( auto_created=True, primary_key=True, serialize=False, ver...
Migration
python
streamlit__streamlit
lib/tests/streamlit/data_test_cases.py
{ "start": 2380, "end": 3231 }
class ____(NamedTuple): # The expected number of rows expected_rows: int # The expected number of columns (doesn't include index columns) expected_cols: int # The expected data format expected_data_format: DataFormat # The expected sequence when the data is converted to a sequence # If N...
CaseMetadata
python
conda__conda
conda/exceptions.py
{ "start": 8626, "end": 9488 }
class ____(ClobberError): def __init__( self, target_path: PathType, incompatible_package_dists: Iterable[PackageRecord | str], context: Context, ): message = dals( """ This transaction has incompatible packages due to a shared path. packages...
SharedLinkPathClobberError
python
openai__openai-python
src/openai/types/chat/chat_completion_deleted.py
{ "start": 198, "end": 470 }
class ____(BaseModel): id: str """The ID of the chat completion that was deleted.""" deleted: bool """Whether the chat completion was deleted.""" object: Literal["chat.completion.deleted"] """The type of object being deleted."""
ChatCompletionDeleted
python
hynek__structlog
src/structlog/stdlib.py
{ "start": 3141, "end": 4389 }
class ____(logging.Logger): """ Change the behavior of `logging.Logger.findCaller` to cope with *structlog*'s extra frames. """ def findCaller( self, stack_info: bool = False, stacklevel: int = 1 ) -> tuple[str, int, str, str | None]: """ Finds the first caller frame out...
_FixedFindCallerLogger
python
PrefectHQ__prefect
src/prefect/server/utilities/database.py
{ "start": 5417, "end": 6658 }
class ____(TypeDecorator[uuid.UUID]): """ Platform-independent UUID type. Uses PostgreSQL's UUID type, otherwise uses CHAR(36), storing as stringified hex values with hyphens. """ impl: type[TypeEngine[Any]] | TypeEngine[Any] = TypeEngine cache_ok: bool | None = True def load_dial...
UUID
python
pypa__pip
src/pip/_vendor/requests/models.py
{ "start": 9506, "end": 21015 }
class ____(RequestEncodingMixin, RequestHooksMixin): """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Instances are generated from a :class:`Request <Request>` object, and should not be instantiated manually; doing so ma...
PreparedRequest
python
pytorch__pytorch
torch/_functorch/_aot_autograd/runtime_wrappers.py
{ "start": 81326, "end": 82201 }
class ____: """ Represents a result of AOTDispatch after calling the inner compiler that can be serialized """ compiled_fn: Callable serialize_fn: Callable def __init__(self, compiled_fn: Callable, serialize_fn: Callable): self.compiled_fn = compiled_fn self.serialize_fn = ...
SerializableCompiledFunction
python
getsentry__sentry
src/sentry/search/events/fields.py
{ "start": 44152, "end": 44940 }
class ____(ColumnArg): # XXX(ahmed): hack to get this to work with crash rate alerts over the sessions dataset until # we deprecate the logic that is tightly coupled with the events dataset. At which point, # we will just rely on dataset specific logic and refactor this class out def normalize(self, val...
SessionColumnArg
python
gevent__gevent
src/gevent/tests/test__socket.py
{ "start": 985, "end": 1364 }
class ____(object): terminal_exc = None def __init__(self, target): @wraps(target) def errors_are_fatal(*args, **kwargs): try: return target(*args, **kwargs) except: # pylint:disable=bare-except self.terminal_exc = sys.exc_info() ...
BaseThread
python
tensorflow__tensorflow
tensorflow/tools/common/public_api_test.py
{ "start": 841, "end": 2526 }
class ____(googletest.TestCase): class TestVisitor(object): def __init__(self): self.symbols = set() self.last_parent = None self.last_children = None def __call__(self, path, parent, children): self.symbols.add(path) self.last_parent = parent self.last_children = list(c...
PublicApiTest
python
pytorch__pytorch
benchmarks/functional_autograd_benchmark/torchvision_models.py
{ "start": 2170, "end": 3983 }
class ____(nn.Module): # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) # while original implementation places the stride at the first 1x1 convolution(self.conv1) # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385. #...
Bottleneck
python
Lightning-AI__lightning
src/lightning/pytorch/cli.py
{ "start": 9393, "end": 13848 }
class ____(Callback): """Saves a LightningCLI config to the log_dir when training starts. Args: parser: The parser object used to parse the configuration. config: The parsed configuration that will be saved. config_filename: Filename for the config file. overwrite: Whether to ov...
SaveConfigCallback
python
apache__airflow
task-sdk/src/airflow/sdk/api/client.py
{ "start": 35881, "end": 37483 }
class ____(httpx.HTTPStatusError): def __init__(self, message: str, *, request: httpx.Request, response: httpx.Response): super().__init__(message, request=request, response=response) detail: list[RemoteValidationError] | str | dict[str, Any] | None def __reduce__(self) -> tuple[Any, ...]: ...
ServerResponseError
python
realpython__materials
python-enum/http_methods.py
{ "start": 113, "end": 204 }
class ____(Enum): GET = 1 POST = 2 PUSH = 3 PATCH = 4 DELETE = 5
HTTPMethod
python
PyCQA__pylint
tests/test_check_parallel.py
{ "start": 4673, "end": 4889 }
class ____(SequentialTestChecker): """A checker that does not need to consolidate data across run invocations.""" name = "extra-sequential-checker" test_data = "extra-sequential"
ExtraSequentialTestChecker
python
pytorch__pytorch
test/quantization/fx/test_subgraph_rewriter.py
{ "start": 708, "end": 15936 }
class ____(JitTestCase): def test_subgraph_rewriter_preserves_logic(self): class M(torch.nn.Module): def forward(self, x): val = torch.neg(x) + torch.relu(x) return torch.add(val, val) def pattern(x): return torch.neg(x) + torch.relu(x) ...
TestSubgraphRewriter
python
sympy__sympy
sympy/functions/elementary/exponential.py
{ "start": 19814, "end": 36790 }
class ____(DefinedFunction): r""" The natural logarithm function `\ln(x)` or `\log(x)`. Explanation =========== Logarithms are taken with the natural base, `e`. To get a logarithm of a different base ``b``, use ``log(x, b)``, which is essentially short-hand for ``log(x)/log(b)``. ``lo...
log
python
mitsuhiko__rye
rye-devtools/src/rye_devtools/find_downloads.py
{ "start": 606, "end": 780 }
class ____: version: Version triple: PlatformTriple implementation: PythonImplementation filename: str url: str sha256: str | None = None
PythonDownload
python
getsentry__sentry
src/sentry/explore/endpoints/explore_saved_query_starred_order.py
{ "start": 744, "end": 1158 }
class ____(serializers.Serializer): query_ids = serializers.ListField(child=serializers.IntegerField(), required=True, min_length=0) def validate_query_ids(self, query_ids): if len(query_ids) != len(set(query_ids)): raise serializers.ValidationError("Single query cannot take up multiple pos...
ExploreSavedQueryStarredOrderSerializer
python
dask__dask
dask/layers.py
{ "start": 10690, "end": 14789 }
class ____(Blockwise): """DataFrame-based Blockwise Layer with IO Parameters ---------- name : str Name to use for the constructed layer. columns : str, list or None Field name(s) to read in as columns in the output. inputs : list or BlockwiseDep List of arguments to be ...
DataFrameIOLayer
python
PyCQA__pylint
tests/data/suppliermodule_test.py
{ "start": 60, "end": 204 }
class ____: def get_value(self): raise NotImplementedError def set_value(self, value): raise NotImplementedError
Interface
python
google__jax
jax/experimental/pallas/ops/tpu/splash_attention/splash_attention_mask.py
{ "start": 785, "end": 4086 }
class ____: """A base class for splash attention masks.""" @property def shape(self) -> tuple[int, ...]: raise NotImplementedError def __getitem__(self, idx) -> np.ndarray: raise NotImplementedError def __bool__(self) -> bool: raise NotImplementedError( 'Conversion to bool is unsupporte...
Mask
python
numba__numba
numba/tests/test_typeguard.py
{ "start": 329, "end": 1153 }
class ____(TestCase): def setUp(self): super().setUp() import typeguard # This is a test class invariant but the Numba multiprocesses test # runner doesn't respect `setUpClass` so just use `setUp`. # typeguard 3+ uses typeguard.TypeCheckError, 2.x uses TypeError self...
TestTypeGuard
python
eventlet__eventlet
eventlet/green/http/cookiejar.py
{ "start": 69155, "end": 73886 }
class ____(FileCookieJar): """ The LWPCookieJar saves a sequence of "Set-Cookie3" lines. "Set-Cookie3" is the format used by the libwww-perl library, not known to be compatible with any browser, but which is easy to read and doesn't lose information about RFC 2965 cookies. Additional methods ...
LWPCookieJar
python
pypa__setuptools
setuptools/_distutils/command/bdist_dumb.py
{ "start": 461, "end": 4631 }
class ____(Command): description = "create a \"dumb\" built distribution" user_options = [ ('bdist-dir=', 'd', "temporary directory for creating the distribution"), ( 'plat-name=', 'p', "platform name to embed in generated filenames " f"[default: ...
bdist_dumb
python
scipy__scipy
scipy/io/matlab/_mio4.py
{ "start": 15037, "end": 19563 }
class ____: def __init__(self, file_writer): self.file_stream = file_writer.file_stream self.oned_as = file_writer.oned_as def write_bytes(self, arr): self.file_stream.write(arr.tobytes(order='F')) def write_string(self, s): self.file_stream.write(s) def write_header(s...
VarWriter4
python
huggingface__transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
{ "start": 50936, "end": 51889 }
class ____(nn.Module): def __init__(self, config: SeamlessM4TConfig, ffn_dim: int): super().__init__() self.fc1 = nn.Linear(config.hidden_size, ffn_dim) self.fc2 = nn.Linear(ffn_dim, config.hidden_size) self.dropout = nn.Dropout(config.activation_dropout) self.act = ACT2FN[co...
SeamlessM4TFeedForwardNetwork
python
sympy__sympy
sympy/plotting/series.py
{ "start": 61824, "end": 67507 }
class ____(ParametricLineBaseSeries): """Representation for a line consisting of two parametric SymPy expressions over a range.""" is_2Dline = True def __init__(self, expr_x, expr_y, var_start_end, label="", **kwargs): super().__init__(**kwargs) self.expr_x = expr_x if callable(expr_x)...
Parametric2DLineSeries
python
pyca__cryptography
src/cryptography/x509/general_name.py
{ "start": 5623, "end": 6901 }
class ____(GeneralName): def __init__(self, value: _IPAddressTypes) -> None: if not isinstance( value, ( ipaddress.IPv4Address, ipaddress.IPv6Address, ipaddress.IPv4Network, ipaddress.IPv6Network, ), ...
IPAddress
python
getsentry__sentry
tests/sentry/middleware/test_access_log_middleware.py
{ "start": 13173, "end": 13917 }
class ____(LogCaptureAPITestCase): endpoint = "sentry-api-0-organization-members" def setUp(self) -> None: self.login_as(user=self.user) def test_org_id_populated(self) -> None: self._caplog.set_level(logging.INFO, logger="sentry") self.get_success_response( self.organi...
TestOrganizationIdPresentForControl
python
getsentry__sentry
tests/snuba/api/endpoints/test_discover_saved_query_detail.py
{ "start": 21871, "end": 23779 }
class ____(APITestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.org = self.create_organization(owner=self.user) self.org_without_access = self.create_organization() self.project_ids = [ self.create_project(organi...
OrganizationDiscoverQueryVisitTest
python
spyder-ide__spyder
spyder/plugins/pythonpath/widgets/pathmanager.py
{ "start": 1325, "end": 1620 }
class ____: MoveTop = 'move_top' MoveUp = 'move_up' MoveDown = 'move_down' MoveToBottom = 'move_to_bottom' AddPath = 'add_path' RemovePath = 'remove_path' ImportPaths = 'import_paths' ExportPaths = 'export_paths' Prioritize = 'prioritize'
PathManagerToolbuttons
python
numpy__numpy
numpy/_core/tests/test_numeric.py
{ "start": 140305, "end": 142747 }
class ____: def test_roll1d(self): x = np.arange(10) xr = np.roll(x, 2) assert_equal(xr, np.array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])) def test_roll2d(self): x2 = np.reshape(np.arange(10), (2, 5)) x2r = np.roll(x2, 1) assert_equal(x2r, np.array([[9, 0, 1, 2, 3], [4, ...
TestRoll
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline_run_stats.py
{ "start": 2058, "end": 2234 }
class ____(graphene.Union): class Meta: types = (GrapheneRunStatsSnapshot, GraphenePythonError) name = "RunStatsSnapshotOrError"
GrapheneRunStatsSnapshotOrError
python
walkccc__LeetCode
solutions/2908. Minimum Sum of Mountain Triplets I/2908.py
{ "start": 0, "end": 449 }
class ____: # Same as 2908. Minimum Sum of Mountain Triplets I def minimumSum(self, nums: list[int]) -> int: ans = math.inf minPrefix = list(itertools.accumulate(nums, min)) minSuffix = list(itertools.accumulate(reversed(nums), min))[::-1] for i, num in enumerate(nums): if num > minPrefix[i] ...
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/noop_compute_log_manager.py
{ "start": 497, "end": 2325 }
class ____(ComputeLogManager, ConfigurableClass): """When enabled for a Dagster instance, stdout and stderr will not be available for any step.""" def __init__(self, inst_data: Optional[ConfigurableClassData] = None): self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData)...
NoOpComputeLogManager
python
numpy__numpy
tools/swig/test/testFortran.py
{ "start": 303, "end": 1407 }
class ____(unittest.TestCase): def __init__(self, methodName="runTests"): unittest.TestCase.__init__(self, methodName) self.typeStr = "double" self.typeCode = "d" # Test (type* IN_FARRAY2, int DIM1, int DIM2) typemap def testSecondElementFortran(self): "Test Fortran matrix ...
FortranTestCase
python
doocs__leetcode
solution/1300-1399/1320.Minimum Distance to Type a Word Using Two Fingers/Solution.py
{ "start": 0, "end": 1133 }
class ____: def minimumDistance(self, word: str) -> int: def dist(a: int, b: int) -> int: x1, y1 = divmod(a, 6) x2, y2 = divmod(b, 6) return abs(x1 - x2) + abs(y1 - y2) n = len(word) f = [[[inf] * 26 for _ in range(26)] for _ in range(n)] for j in...
Solution
python
pypa__installer
tests/test_utils.py
{ "start": 6110, "end": 7693 }
class ____: @pytest.mark.parametrize( ("script", "expected"), [ pytest.param("", [], id="empty"), pytest.param( """ [foo] foo = foo.bar """, [], id="unrelated", ...
TestParseEntryPoints
python
cython__cython
docs/examples/userguide/extension_types/extendable_animal.py
{ "start": 162, "end": 293 }
class ____(Animal): # Note that we use class, not cdef class pass dog = ExtendableAnimal(4) dog.has_tail = True
ExtendableAnimal
python
getsentry__sentry
src/sentry/notifications/notification_action/action_validation.py
{ "start": 5012, "end": 5184 }
class ____(TicketingActionValidatorHandler): provider = Action.Type.GITHUB @action_validator_registry.register(Action.Type.GITHUB_ENTERPRISE)
GithubActionValidatorHandler
python
allegroai__clearml
clearml/backend_api/services/v2_23/models.py
{ "start": 108675, "end": 109814 }
class ____(Response): """ Response of models.make_private endpoint. :param updated: Number of models updated :type updated: int """ _service = "models" _action = "make_private" _version = "2.23" _schema = { "definitions": {}, "properties": { "updated": {...
MakePrivateResponse
python
plotly__plotly.py
_plotly_utils/basevalidators.py
{ "start": 8169, "end": 12303 }
class ____(object): """ Base class for all validator classes """ def __init__(self, plotly_name, parent_name, role=None, **_): """ Construct a validator instance Parameters ---------- plotly_name : str Name of the property being validated par...
BaseValidator
python
django__django
tests/auth_tests/test_hashers.py
{ "start": 1047, "end": 23838 }
class ____(SimpleTestCase): def test_simple(self): encoded = make_password("lètmein") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmei...
TestUtilsHashPass
python
explosion__spaCy
spacy/lang/nb/__init__.py
{ "start": 629, "end": 1274 }
class ____(Language): lang = "nb" Defaults = NorwegianDefaults @Norwegian.factory( "lemmatizer", assigns=["token.lemma"], default_config={ "model": None, "mode": "rule", "overwrite": False, "scorer": {"@scorers": "spacy.lemmatizer_scorer.v1"}, }, default_sco...
Norwegian
python
fastapi__sqlmodel
docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py
{ "start": 279, "end": 4488 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) team_id: int | None = Field(default=None, foreign_key="team.id") team: Team | None = Relationship() sqlite_...
Hero
python
getsentry__sentry
src/sentry/users/api/endpoints/user_identity_config.py
{ "start": 3786, "end": 5806 }
class ____(UserEndpoint): publish_status = { "DELETE": ApiPublishStatus.PRIVATE, "GET": ApiPublishStatus.PRIVATE, } permission_classes = (UserAndStaffPermission,) @staticmethod def _get_identity(user: User, category: str, identity_id: str) -> UserIdentityConfig | None: iden...
UserIdentityConfigDetailsEndpoint
python
gevent__gevent
src/gevent/tests/test__socket_dns.py
{ "start": 20294, "end": 21787 }
class ____(TestCase): # certain tests in test_patched_socket.py only work if getaddrinfo('localhost') does not switch # (e.g. NetworkConnectionAttributesTest.testSourceAddress) #switch_expected = False # XXX: The above has been commented out for some time. Apparently this isn't the case # anymore. ...
TestLocalhost
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_kubernetes_engine.py
{ "start": 5117, "end": 7255 }
class ____: def setup_method(self): with mock.patch( BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id ): self.gke_hook = GKEHook(gcp_conn_id="test", location=GKE_ZONE) self.gke_hook._client = mock.Mock() @mock.patch(GKE_STR...
TestGKEHookDelete
python
tensorflow__tensorflow
tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/partially_shaped_variables.py
{ "start": 905, "end": 1573 }
class ____(tf.Module): def __init__(self): super(TestModule, self).__init__() # CHECK: "tf_saved_model.global_tensor"() <{is_mutable, {{.*}} type = tensor<*xf32>, value = dense<0.000000e+00> : tensor<1xf32>}> {tf_saved_model.exported_names = ["v0"]} : () -> () # CHECK: "tf_saved_model.global_tensor"() <{...
TestModule
python
great-expectations__great_expectations
tests/datasource/fluent/test_batch.py
{ "start": 6389, "end": 10617 }
class ____: @pytest.fixture def suite(self) -> ExpectationSuite: return gx.ExpectationSuite( name="my-suite", expectations=[gxe.ExpectColumnValuesToNotBeNull(column="vendor_id", mostly=0.95)], ) @pytest.mark.filesystem def test_boolean_validation_result( ...
TestBatchValidateExpectationSuite
python
gevent__gevent
src/gevent/tests/test__threading_2.py
{ "start": 2889, "end": 16510 }
class ____(unittest.TestCase): maxDiff = None # Create a bunch of threads, let each do some work, wait until all are # done. def test_various_ops(self): # This takes about n/3 seconds to run (about n/3 clumps of tasks, # times about 1 second per clump). NUMTASKS = 10 # ...
ThreadTests
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py
{ "start": 2419, "end": 2586 }
class ____[Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]: pass
TestTypeParams
python
xlwings__xlwings
xlwings/constants.py
{ "start": 63230, "end": 63353 }
class ____: xlTypePDF = 0 # from enum XlFixedFormatType xlTypeXPS = 1 # from enum XlFixedFormatType
FixedFormatType
python
huggingface__transformers
src/transformers/models/ernie/modeling_ernie.py
{ "start": 31905, "end": 32585 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.predictions = ErnieLMPredictionHead(config) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output, pooled_output): prediction_scores = self.predictions(sequence_output...
ErniePreTrainingHeads
python
python__mypy
test-data/unit/plugins/union_method.py
{ "start": 224, "end": 1857 }
class ____(Plugin): def get_method_signature_hook( self, fullname: str ) -> Callable[[MethodSigContext], CallableType] | None: if fullname.startswith("__main__.Foo."): return my_meth_sig_hook return None def get_method_hook(self, fullname: str) -> Callable[[MethodContext...
MethodPlugin
python
apache__airflow
helm-tests/tests/helm_tests/airflow_core/test_pdb_scheduler.py
{ "start": 900, "end": 2705 }
class ____: """Tests Scheduler PDB.""" def test_should_pass_validation_with_just_pdb_enabled_v1(self): render_chart( values={"scheduler": {"podDisruptionBudget": {"enabled": True}}}, show_only=["templates/scheduler/scheduler-poddisruptionbudget.yaml"], ) # checks that n...
TestSchedulerPdb
python
kamyu104__LeetCode-Solutions
Python/select-cells-in-grid-with-maximum-score.py
{ "start": 147, "end": 2294 }
class ____(object): def maxScore(self, grid): """ :type grid: List[List[int]] :rtype: int """ # Template translated from: # https://github.com/kth-competitive-programming/kactl/blob/main/content/graph/WeightedMatching.h def hungarian(a): # Time: O(n^2 * m), S...
Solution
python
pallets__click
src/click/types.py
{ "start": 641, "end": 5592 }
class ____: """Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of the ty...
ParamType