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
great-expectations__great_expectations
great_expectations/core/expectation_diagnostics/supporting_types.py
{ "start": 645, "end": 2441 }
class ____(SerializableDictDot): """An augmented version of the Expectation.library_metadata object, used within ExpectationDiagnostics""" # noqa: E501 # FIXME CoP maturity: Maturity tags: List[str] contributors: List[str] requirements: List[str] library_metadata_passed_checks: bool has_fu...
AugmentedLibraryMetadata
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/tests/test_gradle.py
{ "start": 306, "end": 1239 }
class ____: class DummyStep(gradle.GradleTask): gradle_task_name = "dummyTask" title = "Dummy Step" async def _run(self) -> steps.StepResult: return steps.StepResult(step=self, status=steps.StepStatus.SUCCESS) @pytest.fixture def test_context(self, mocker, dagger_client...
TestGradleTask
python
doocs__leetcode
solution/2300-2399/2303.Calculate Amount Paid in Taxes/Solution.py
{ "start": 0, "end": 269 }
class ____: def calculateTax(self, brackets: List[List[int]], income: int) -> float: ans = prev = 0 for upper, percent in brackets: ans += max(0, min(income, upper) - prev) * percent prev = upper return ans / 100
Solution
python
rapidsai__cudf
python/cudf/cudf/core/groupby/groupby.py
{ "start": 11028, "end": 101846 }
class ____(Serializable, Reducible, Scannable): obj: Series | DataFrame _VALID_REDUCTIONS = { "sum", "prod", "idxmin", "idxmax", "min", "max", "mean", "median", "nunique", "first", "last", "var", "std", ...
GroupBy
python
matplotlib__matplotlib
lib/matplotlib/category.py
{ "start": 5128, "end": 7377 }
class ____: def __init__(self, data=None): """ Create mapping between unique categorical values and integer ids. Parameters ---------- data : iterable sequence of string values """ self._mapping = OrderedDict() self._counter = itertools.co...
UnitData
python
tensorflow__tensorflow
tensorflow/python/framework/extension_type.py
{ "start": 23520, "end": 29674 }
class ____(type_spec.TypeSpecBatchEncoder): """Class used to encode and decode extension type values for batching. In order to be batched and unbatched by APIs such as `tf.data.Dataset`, `tf.keras`, and `tf.map_fn`, extension type values must be encoded as a list of `tf.Tensor`s, where stacking, unstacking, or...
ExtensionTypeBatchEncoder
python
getsentry__sentry
src/sentry/api/serializers/models/artifactbundle.py
{ "start": 2084, "end": 3800 }
class ____(Serializer): def __init__(self, archive, *args, **kwargs): Serializer.__init__(self, *args, **kwargs) self.archive = archive def get_attrs(self, item_list, user, **kwargs): return {item: self._compute_attrs(item) for item in item_list} def _compute_attrs(self, item): ...
ArtifactBundleFilesSerializer
python
keras-team__keras
keras/src/trainers/trainer_test.py
{ "start": 9478, "end": 10094 }
class ____(Callback): def __init__(self): super().__init__() self.begin_count = 0 self.end_count = 0 self.epoch_begin_count = 0 self.epoch_end_count = 0 self.batch_loss_history = [] def on_epoch_begin(self, epoch, logs=None): self.epoch_begin_count += 1 ...
StepObserver
python
getsentry__sentry
tests/sentry/api/serializers/test_project.py
{ "start": 37509, "end": 39319 }
class ____(TestCase): @cached_property def project(self): return self.create_project(teams=[self.team], organization=self.organization) @cached_property def other_project(self): return self.create_project(teams=[self.team], organization=self.organization) def test_single_no_release...
BulkFetchProjectLatestReleases
python
great-expectations__great_expectations
great_expectations/data_context/data_context/serializable_data_context.py
{ "start": 1068, "end": 18183 }
class ____(AbstractDataContext): UNCOMMITTED_DIRECTORIES: ClassVar[list[str]] = ["data_docs", "validations"] GX_UNCOMMITTED_DIR: ClassVar[str] = "uncommitted" GITIGNORE: ClassVar[str] = ".gitignore" GX_CONFIG_VARIABLES: ClassVar[str] = "config_variables.yml" BASE_DIRECTORIES: ClassVar[list[str]] = [...
SerializableDataContext
python
ray-project__ray
python/ray/llm/_internal/serve/engines/vllm/kv_transfer/lmcache.py
{ "start": 425, "end": 2020 }
class ____(BaseConnectorBackend): KV_CONNECTOR_EXTRA_CONFIG_FIELD_NAME = "kv_connector_extra_config" LMCACHE_RPC_PORT_FIELD_NAME = "lmcache_rpc_port" DEFAULT_LMCACHE_RPC_PORT_NAME = "lmcache_rpc_port" def setup(self) -> None: """Initialize the LMCache connector backend. Creates a uniq...
LMCacheConnectorV1Backend
python
ansible__ansible
lib/ansible/galaxy/dependency_resolution/resolvers.py
{ "start": 364, "end": 623 }
class ____(Resolver): """A dependency resolver for Ansible Collections. This is a proxy class allowing us to abstract away importing resolvelib outside of the `ansible.galaxy.dependency_resolution` Python package. """
CollectionDependencyResolver
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py
{ "start": 82987, "end": 95458 }
class ____(test.TestCase): def setUp(self): self._seed = 23489 np.random.seed(self._seed) @test_util.run_v1_only("b/124229375") def _testRawRNN(self, max_time): with self.session(graph=ops.Graph()) as sess: batch_size = 16 input_depth = 4 num_units = 3 inputs = array_ops.pla...
RawRNNTest
python
walkccc__LeetCode
solutions/1617. Count Subtrees With Max Distance Between Cities/1617.py
{ "start": 0, "end": 1340 }
class ____: def countSubgraphsForEachDiameter( self, n: int, edges: list[list[int]], ) -> list[int]: maxMask = 1 << n dist = self._floydWarshall(n, edges) ans = [0] * (n - 1) # mask := the subset of the cities for mask in range(maxMask): maxDist = self._getMaxDist(mask, ...
Solution
python
huggingface__transformers
src/transformers/models/sam2/modular_sam2.py
{ "start": 39868, "end": 48949 }
class ____(SamMaskDecoder): def __init__(self, config: Sam2MaskDecoderConfig): super().__init__(config) del self.iou_prediction_head self.iou_prediction_head = Sam2FeedForward( self.hidden_size, config.iou_head_hidden_dim, self.num_mask_tokens, ...
Sam2MaskDecoder
python
python-poetry__poetry
src/poetry/plugins/plugin.py
{ "start": 241, "end": 452 }
class ____(BasePlugin): """ Generic plugin not related to the console application. """ group = "poetry.plugin" @abstractmethod def activate(self, poetry: Poetry, io: IO) -> None: ...
Plugin
python
ray-project__ray
python/ray/llm/tests/common/cloud/test_utils.py
{ "start": 5059, "end": 9477 }
class ____: """Tests for the remote_object_cache decorator.""" @pytest.mark.asyncio async def test_basic_functionality(self): """Test basic remote_object_cache decorator functionality.""" call_count = 0 MISSING = object() @remote_object_cache( max_size=2, ...
TestRemoteObjectCacheDecorator
python
django__django
django/core/validators.py
{ "start": 13959, "end": 14174 }
class ____(BaseValidator): message = _("Ensure this value is greater than or equal to %(limit_value)s.") code = "min_value" def compare(self, a, b): return a < b @deconstructible
MinValueValidator
python
pytorch__pytorch
torch/_inductor/codegen/cuda/cutlass_utils.py
{ "start": 7214, "end": 15415 }
class ____: """ CUTLASS args used to initialize a CUTLASS Manifest. """ architectures: Optional[str] = None cuda_version: Optional[str] = None instantiation_level: Optional[str] = None operations: Optional[str] = None build_dir = "" curr_build_dir = "" generator_target = "" ...
CUTLASSArgs
python
huggingface__transformers
src/transformers/models/git/modeling_git.py
{ "start": 25291, "end": 27386 }
class ____(GradientCheckpointingLayer): def __init__(self, config: GitVisionConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = GitVisionAttention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.mlp = GitVis...
GitVisionEncoderLayer
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI052.py
{ "start": 3791, "end": 3814 }
class ____: WIZ = 4
Bop
python
google__pytype
pytype/constant_folding.py
{ "start": 3837, "end": 4495 }
class ____: """Build up a map of constants.""" def __init__(self): self.key_types = set() self.value_types = set() self.keys = [] self.values = [] self.elements = {} def add(self, key, value): self.key_types.add(key.typ) self.value_types.add(value.typ) self.keys.append(key.value)...
_MapBuilder
python
pytorch__pytorch
tools/gen_vulkan_spv.py
{ "start": 7244, "end": 15794 }
class ____: def __init__( self, src_dir_paths: str | list[str], env: dict[Any, Any], glslc_path: str | None, ) -> None: if isinstance(src_dir_paths, str): self.src_dir_paths = [src_dir_paths] else: self.src_dir_paths = src_dir_paths ...
SPVGenerator
python
tensorflow__tensorflow
tensorflow/python/profiler/pprof_profiler.py
{ "start": 3117, "end": 4676 }
class ____(object): """Keeps track of `Function` protos for pprof profile.""" def __init__(self, string_table): """Constructor. Args: string_table: A `StringTable` object. """ self._string_table = string_table # Maps tuples in the form (file_path, function_name, start_line_number) # ...
Functions
python
davidhalter__jedi
jedi/inference/signature.py
{ "start": 1947, "end": 3960 }
class ____(AbstractSignature): def __init__(self, value, function_value=None, is_bound=False): super().__init__(value, is_bound) self._function_value = function_value or value def bind(self, value): return TreeSignature(value, self._function_value, is_bound=True) @property def ...
TreeSignature
python
allegroai__clearml
clearml/backend_interface/metrics/events.py
{ "start": 587, "end": 5236 }
class ____(object): """ Adapter providing all the base attributes required by a metrics event and defining an interface used by the metrics manager when batching and writing events. """ default_nan_value = 0.0 default_inf_value = 0.0 """ Default value used when a np.nan or np.inf value is e...
MetricsEventAdapter
python
getsentry__sentry
src/sentry/api/serializers/models/project.py
{ "start": 22875, "end": 23534 }
class ____(ProjectSerializer): def get_attrs( self, item_list: Sequence[Project], user: User | RpcUser | AnonymousUser, **kwargs: Any ) -> dict[Project, dict[str, Any]]: attrs = super().get_attrs(item_list, user) orgs = {d["id"]: d for d in serialize(list({i.organization for i in item_l...
ProjectWithOrganizationSerializer
python
scipy__scipy
scipy/linalg/tests/test_lapack.py
{ "start": 17813, "end": 18976 }
class ____: def test_sing_val_update(self): sigmas = np.array([4., 3., 2., 0]) m_vec = np.array([3.12, 5.7, -4.8, -2.2]) M = np.hstack((np.vstack((np.diag(sigmas[0:-1]), np.zeros((1, len(m_vec) - 1)))), m_vec[:, np.newaxis])) ...
TestDlasd4
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1407162, "end": 1407457 }
class ____( sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, RepositoryAuditEntryData ): """Audit log entry for a repo.config.enable_anonymous_git_access event. """ __schema__ = github_schema __field_names__ = ()
RepoConfigEnableAnonymousGitAccessAuditEntry
python
django__django
tests/admin_scripts/tests.py
{ "start": 93335, "end": 95909 }
class ____(AdminScriptTestCase): """Tests for 2-stage argument parsing scheme. django-admin command arguments are parsed in 2 parts; the core arguments (--settings, --traceback and --pythonpath) are parsed using a basic parser, ignoring any unknown options. Then the full settings are passed to the ...
ArgumentOrder
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_dlpack.py
{ "start": 733, "end": 3989 }
class ____(TestCase): @xpassIfTorchDynamo_np # (reason="pytorch seems to handle refcounts differently") @skipif(IS_PYPY, reason="PyPy can't get refcounts.") def test_dunder_dlpack_refcount(self): x = np.arange(5) y = x.__dlpack__() assert sys.getrefcount(x) == 3 del y ...
TestDLPack
python
numba__numba
numba/cuda/cudadrv/devicearray.py
{ "start": 24888, "end": 26415 }
class ____(object): """ An IPC array handle that can be serialized and transfer to another process in the same machine for share a GPU allocation. On the destination process, use the *.open()* method to creates a new *DeviceNDArray* object that shares the allocation from the original process. T...
IpcArrayHandle
python
streamlit__streamlit
lib/streamlit/runtime/caching/storage/cache_storage_protocol.py
{ "start": 4220, "end": 5695 }
class ____(Protocol): """Cache storage protocol, that should be implemented by the concrete cache storages. Used to store cached values for a single `@st.cache_data` decorated function serialized as bytes. CacheStorage instances should be created by `CacheStorageManager.create()` method. Notes ...
CacheStorage
python
google__jax
jax/_src/interpreters/partial_eval.py
{ "start": 86118, "end": 110455 }
class ____(core.Trace): __slots__ = ("frame", "tag", "parent_trace") def __init__(self, debug_info: core.DebugInfo, parent_trace=None, lower=False, auto_dce=False): super().__init__() self.requires_low = lower self.frame = JaxprStackFrame(debug_info, auto_dce) self.parent_trace = par...
DynamicJaxprTrace
python
geekcomputers__Python
venv/Lib/site-packages/pip/_internal/req/req_file.py
{ "start": 2195, "end": 2688 }
class ____: def __init__( self, requirement: str, is_editable: bool, comes_from: str, constraint: bool, options: Optional[Dict[str, Any]] = None, line_source: Optional[str] = None, ) -> None: self.requirement = requirement self.is_editable ...
ParsedRequirement
python
pandas-dev__pandas
asv_bench/benchmarks/series_methods.py
{ "start": 4859, "end": 5168 }
class ____: params = [[10**3, 10**4, 10**5], ["int", "uint", "float", "object"]] param_names = ["N", "dtype"] def setup(self, N, dtype): self.s = Series(np.random.randint(0, N, size=10 * N)).astype(dtype) def time_value_counts(self, N, dtype): self.s.value_counts()
ValueCounts
python
sqlalchemy__sqlalchemy
examples/dogpile_caching/caching_query.py
{ "start": 851, "end": 3243 }
class ____: """An add-on for an ORM :class:`.Session` optionally loads full results from a dogpile cache region. """ def __init__(self, regions): self.cache_regions = regions self._statement_cache = {} def listen_on_session(self, session_factory): event.listen(session_fac...
ORMCache
python
openai__gym
gym/envs/mujoco/mujoco_env.py
{ "start": 9587, "end": 14450 }
class ____(BaseMujocoEnv): """Superclass for MuJoCo environments.""" def __init__( self, model_path, frame_skip, observation_space: Space, render_mode: Optional[str] = None, width: int = DEFAULT_SIZE, height: int = DEFAULT_SIZE, camera_id: Optiona...
MujocoEnv
python
getsentry__sentry
tests/sentry/issues/endpoints/test_group_tagkey_values.py
{ "start": 502, "end": 10828 }
class ____(APITestCase, SnubaTestCase, PerformanceIssueTestCase): @mock.patch("sentry.analytics.record") def test_simple(self, mock_record: mock.MagicMock) -> None: key, value = "foo", "bar" project = self.create_project() event = self.store_event( data={"tags": {key: value...
GroupTagKeyValuesTest
python
anthropics__anthropic-sdk-python
src/anthropic/types/text_block.py
{ "start": 259, "end": 662 }
class ____(BaseModel): citations: Optional[List[TextCitation]] = None """Citations supporting the text block. The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results i...
TextBlock
python
pypa__pip
src/pip/_internal/cli/spinners.py
{ "start": 2650, "end": 3487 }
class ____(SpinnerInterface): def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None: self._message = message self._finished = False self._rate_limiter = RateLimiter(min_update_interval_seconds) self._update("started") def _update(self, status: str) ...
NonInteractiveSpinner
python
huggingface__transformers
src/transformers/models/m2m_100/modeling_m2m_100.py
{ "start": 8710, "end": 14415 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
M2M100Attention
python
run-llama__llama_index
llama-index-core/llama_index/core/callbacks/schema.py
{ "start": 2923, "end": 3351 }
class ____: """Generic class to store event information.""" event_type: CBEventType payload: Optional[Dict[str, Any]] = None time: str = "" id_: str = "" def __post_init__(self) -> None: """Init time and id if needed.""" if not self.time: self.time = datetime.now()....
CBEvent
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/_internal/expandinput.py
{ "start": 3877, "end": 8799 }
class ____(ResolveMixin): """ Storage type of a mapped operator's mapped kwargs. This is created from ``expand(**kwargs)``. """ value: dict[str, OperatorExpandArgument] EXPAND_INPUT_TYPE: ClassVar[str] = "dict-of-lists" def _iter_parse_time_resolved_kwargs(self) -> Iterable[tuple[str, Si...
DictOfListsExpandInput
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_audio.py
{ "start": 46949, "end": 47809 }
class ____(nn.Module): def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4): super().__init__() self.scale = scale self.margin = margin self.num_labels = num_labels self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True) self.lo...
AMSoftmaxLoss
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 497530, "end": 498009 }
class ____(sgqlc.types.Type): """Autogenerated return type of ClosePullRequest""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "pull_request") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the ...
ClosePullRequestPayload
python
walkccc__LeetCode
solutions/403. Frog Jump/403.py
{ "start": 0, "end": 463 }
class ____: def canCross(self, stones: list[int]) -> bool: n = len(stones) # dp[i][j] := True if a frog can make a size j jump to stones[i] dp = [[False] * (n + 1) for _ in range(n)] dp[0][0] = True for i in range(1, n): for j in range(i): k = stones[i] - stones[j] if k > n:...
Solution
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 6964, "end": 6998 }
class ____(BlogBase): pass
BlogB
python
scipy__scipy
scipy/stats/tests/test_qmc.py
{ "start": 33904, "end": 37802 }
class ____(QMCEngineTests): qmce = qmc.PoissonDisk can_scramble = False def test_bounds(self, *args): pytest.skip("Too costly in memory.") def test_fast_forward(self, *args): pytest.skip("Not applicable: recursive process.") def test_sample(self, *args): pytest.skip("Not a...
TestPoisson
python
pennersr__django-allauth
allauth/headless/app_settings.py
{ "start": 37, "end": 2110 }
class ____: def __init__(self, prefix): self.prefix = prefix def _setting(self, name, dflt): from allauth.utils import get_setting return get_setting(self.prefix + name, dflt) @property def ADAPTER(self): return self._setting( "ADAPTER", "allauth.headless.a...
AppSettings
python
python__mypy
mypyc/irbuild/for_helpers.py
{ "start": 40286, "end": 42567 }
class ____(ForGenerator): """Generate optimized IR for a for loop over an integer range.""" def init(self, start_reg: Value, end_reg: Value, step: int) -> None: builder = self.builder self.start_reg = start_reg self.end_reg = end_reg self.step = step self.end_target = bu...
ForRange
python
kamyu104__LeetCode-Solutions
Python/sum-of-good-subsequences.py
{ "start": 67, "end": 538 }
class ____(object): def sumOfGoodSubsequences(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9+7 dp = collections.defaultdict(int) cnt = collections.defaultdict(int) for x in nums: c = cnt[x-1]+cnt[x+1]+1 cnt[x...
Solution
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/integrations/dlt/dlt_dagster_translator.py
{ "start": 316, "end": 1145 }
class ____(DagsterDltTranslator): def get_asset_spec(self, data: DltResourceTranslatorData) -> AssetSpec: """Overrides asset spec to override asset key to be the dlt resource name.""" default_spec = super().get_asset_spec(data) return default_spec.replace_attributes( key=AssetKey...
CustomDagsterDltTranslator
python
spyder-ide__spyder
spyder/plugins/layout/container.py
{ "start": 1996, "end": 2089 }
class ____: PluginsMenu = "plugins_menu" LayoutsMenu = 'layouts_menu'
LayoutPluginMenus
python
pytorch__pytorch
torch/distributed/fsdp/_flat_param.py
{ "start": 6926, "end": 7312 }
class ____(_ParameterMeta): # Make `isinstance(t, FlatParameter)` return True for custom tensor # instances that have the _is_flat_param flag for BC def __instancecheck__(self, instance): # NB: do NOT test the super implementation return isinstance(instance, torch.Tensor) and getattr( ...
_FlatParameterMeta
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 692739, "end": 693429 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "created_at", "new_base", "old_base", "pull_request") actor = sgqlc.types.Field(Actor, graphql_name="actor") created_at = sgqlc.types.Field( sgqlc.types...
AutomaticBaseChangeFailedEvent
python
spyder-ide__spyder
spyder/plugins/run/plugin.py
{ "start": 1424, "end": 32683 }
class ____(SpyderPluginV2): """ Run Plugin. """ NAME = "run" REQUIRES = [Plugins.Preferences, Plugins.WorkingDirectory] OPTIONAL = [Plugins.MainMenu, Plugins.Toolbar, Plugins.Shortcuts] CONTAINER_CLASS = RunContainer CONF_SECTION = NAME CONF_WIDGET_CLASS = RunConfigPage CONF_FIL...
Run
python
django__django
tests/auth_tests/models/with_custom_email_field.py
{ "start": 423, "end": 772 }
class ____(AbstractBaseUser): username = models.CharField(max_length=255) password = models.CharField(max_length=255) email_address = models.EmailField(null=True) is_active = models.BooleanField(default=True) EMAIL_FIELD = "email_address" USERNAME_FIELD = "username" objects = CustomEmailFi...
CustomEmailField
python
numba__numba
numba/core/types/functions.py
{ "start": 20053, "end": 22054 }
class ____(WeakType, Callable, Dummy): """ Type class for @jit-compiled functions. """ def __init__(self, dispatcher): self._store_object(dispatcher) super(Dispatcher, self).__init__("type(%s)" % dispatcher) def dump(self, tab=''): print((f'{tab}DUMP {type(self).__name__}[c...
Dispatcher
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/base.py
{ "start": 6028, "end": 7015 }
class ____(Enum): """enumeration which indicates the 'direction' of a :class:`_orm.RelationshipProperty`. :class:`.RelationshipDirection` is accessible from the :attr:`_orm.Relationship.direction` attribute of :class:`_orm.RelationshipProperty`. """ ONETOMANY = 1 """Indicates the one-...
RelationshipDirection
python
ansible__ansible
lib/ansible/utils/context_objects.py
{ "start": 2794, "end": 3130 }
class ____(CLIArgs, metaclass=_ABCSingleton): """ Globally hold a parsed copy of cli arguments. Only one of these exist per program as it is for global context """ pass def __getattr__(importable_name): return _no_six.deprecate(importable_name, __name__, "binary_type", "text_type", "add_metac...
GlobalCLIArgs
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/inputs.py
{ "start": 20708, "end": 22534 }
class ____(MultiStepInputSource, IHaveNew): """This step input fans-in multiple sources in to a single input. The input will receive just the value from loading source_to_load_from. """ sources: Sequence[StepInputSource] source_to_load_from: StepInputSource def __new__(cls, sources: Sequence[S...
FromMultipleSourcesLoadSingleSource
python
getsentry__sentry
tests/sentry/api/bases/test_team.py
{ "start": 8303, "end": 15960 }
class ____(TeamPermissionBase): def setUp(self) -> None: super().setUp() self.org = self.create_organization() self.org.flags.allow_joinleave = False self.org.save() self.team = self.create_team(organization=self.org) self.project = self.create_project(organization=se...
TeamPermissionNoJoinLeaveTest
python
apache__airflow
providers/standard/src/airflow/providers/standard/sensors/external_task.py
{ "start": 28140, "end": 30837 }
class ____(EmptyOperator): """ Use this operator to indicate that a task on a different DAG depends on this task. When this task is cleared with "Recursive" selected, Airflow will clear the task on the other DAG and its downstream tasks recursively. Transitive dependencies are followed until the re...
ExternalTaskMarker
python
tensorflow__tensorflow
tensorflow/python/ops/distributions/distribution.py
{ "start": 4194, "end": 7343 }
class ____(abc.ABCMeta): def __new__(mcs, classname, baseclasses, attrs): """Control the creation of subclasses of the Distribution class. The main purpose of this method is to properly propagate docstrings from private Distribution methods, like `_log_prob`, into their public wrappers as inherited ...
_DistributionMeta
python
h5py__h5py
h5py/_hl/filters.py
{ "start": 4900, "end": 14604 }
class ____(FilterRefBase): filter_id = h5z.FILTER_DEFLATE def __init__(self, level=DEFAULT_GZIP): self.filter_options = (level,) def fill_dcpl(plist, shape, dtype, chunks, compression, compression_opts, shuffle, fletcher32, maxshape, scaleoffset, external, allow_unknown_fil...
Gzip
python
OmkarPathak__pygorithm
pygorithm/data_structures/queue.py
{ "start": 1673, "end": 3160 }
class ____(object): """Deque Deque implementation """ def __init__(self, limit=10): self.queue = [] self.limit = limit def __str__(self): return ' '.join([str(i) for i in self.queue]) def is_empty(self): """ checks whether the deque is empty """ ...
Deque
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 173323, "end": 175720 }
class ____(OperationBuffer): """ Represents a Triton (in the future other type) of template operator that we can fuse an epilogue onto. """ def __init__( self, layout: OutputSpec, inputs: Sequence[IRNode], make_kernel_render: Optional[Callable[..., Any]], ) -> No...
TemplateBuffer
python
langchain-ai__langchain
libs/partners/mistralai/langchain_mistralai/embeddings.py
{ "start": 1095, "end": 10203 }
class ____(BaseModel, Embeddings): """MistralAI embedding model integration. Setup: Install `langchain_mistralai` and set environment variable `MISTRAL_API_KEY`. ```bash pip install -U langchain_mistralai export MISTRAL_API_KEY="your-api-key" ``` Key init a...
MistralAIEmbeddings
python
doocs__leetcode
solution/2000-2099/2024.Maximize the Confusion of an Exam/Solution.py
{ "start": 0, "end": 376 }
class ____: def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int: def f(c: str) -> int: cnt = l = 0 for ch in answerKey: cnt += ch == c if cnt > k: cnt -= answerKey[l] == c l += 1 return len...
Solution
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_multicolumn_values_to_be_unique.py
{ "start": 1038, "end": 7687 }
class ____(ColumnMapExpectation): """Expect that the columns are unique together (e.g. a multi-column primary key) Note that all instances of any duplicates are considered failed ExpectMulticolumnvaluesToBeUnique is a \ Column Map Expectation. For example: :: A B C 1 1...
ExpectMulticolumnValuesToBeUnique
python
ipython__ipython
IPython/core/prefilter.py
{ "start": 14842, "end": 15221 }
class ____(PrefilterChecker): priority = Integer(100).tag(config=True) enabled = Bool(False).tag(config=True) def check(self, line_info): "Emacs ipython-mode tags certain input lines." if line_info.line.endswith('# PYTHON-MODE'): return self.prefilter_manager.get_handler_by_nam...
EmacsChecker
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/sqlite/dml.py
{ "start": 8237, "end": 9859 }
class ____(OnConflictClause): __visit_name__ = "on_conflict_do_update" update_values_to_set: Dict[_DMLColumnElement, ColumnElement[Any]] update_whereclause: Optional[ColumnElement[Any]] _traverse_internals = OnConflictClause._traverse_internals + [ ("update_values_to_set", InternalTraversal.dp...
OnConflictDoUpdate
python
huggingface__transformers
src/transformers/models/blip_2/modeling_blip_2.py
{ "start": 6211, "end": 6848 }
class ____(ModelOutput): r""" image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`): The image embeddings obtained by applying the projection layer to the pooler_output. """ image_embeds: Optional[torch.F...
Blip2VisionModelOutput
python
walkccc__LeetCode
solutions/458. Poor Pigs/458.py
{ "start": 0, "end": 234 }
class ____: def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int: base = minutesToTest // minutesToDie + 1 ans = 0 x = 1 while x < buckets: ans += 1 x *= base return ans
Solution
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-non-overlapping-palindrome-substrings.py
{ "start": 56, "end": 588 }
class ____(object): def maxPalindromes(self, s, k): """ :type s: str :type k: int :rtype: int """ result = prev = 0 for mid in xrange(2*len(s)-1): left, right = mid//2, mid//2+mid%2 while left >= prev and right < len(s) and s[left] == s...
Solution
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_namers.py
{ "start": 1619, "end": 2049 }
class ____(TestCase): def test_basic(self): filename = namers.alias( thumbnailer=FakeThumbnailer(), prepared_options=['100x100', 'q80', 'crop', 'upscale'], thumbnail_options={'size': (100, 100), 'ALIAS': 'medium_large'}, source_filename='source.jpg', ...
Alias
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 3425, "end": 3513 }
class ____(Variadic_TA[T_co]): ... # This should generate an error.
VariadicChildCo_WithTA
python
mlflow__mlflow
tests/store/tracking/test_rest_store.py
{ "start": 3131, "end": 107108 }
class ____(RestStore): def _call_endpoint(self, api, json_body): raise MyCoolException("cool") def mock_http_request(): return mock.patch( "mlflow.utils.rest_utils.http_request", return_value=mock.MagicMock(status_code=200, text="{}"), ) def test_successful_http_request(): de...
CustomErrorHandlingRestStore
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_health.py
{ "start": 1067, "end": 1356 }
class ____(graphene.ObjectType): numFailedChecks = graphene.NonNull(graphene.Int) numWarningChecks = graphene.NonNull(graphene.Int) totalNumChecks = graphene.NonNull(graphene.Int) class Meta: name = "AssetHealthCheckDegradedMeta"
GrapheneAssetHealthCheckDegradedMeta
python
spyder-ide__spyder
spyder/plugins/remoteclient/api/modules/file_services.py
{ "start": 1611, "end": 10228 }
class ____(SpyderBaseJupyterAPI, RawIOBase): """ API for remote file I/O. This API is a RawIOBase subclass that allows reading and writing files on a remote server. The file is open upon the websocket connection and closed when the connection is closed. If lock is True, the file will be l...
SpyderRemoteFileIOAPI
python
numba__numba
numba/core/types/abstract.py
{ "start": 7873, "end": 7948 }
class ____(Type): """ Base class for hashable types. """
Hashable
python
pennersr__django-allauth
tests/apps/socialaccount/providers/strava/tests.py
{ "start": 339, "end": 3551 }
class ____(OAuth2TestsMixin, TestCase): provider_id = StravaProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """{ "id": 32641234, "username": null, "resource_state": 2, "firstname": "...
StravaTests
python
kamyu104__LeetCode-Solutions
Python/number-of-matching-subsequences.py
{ "start": 124, "end": 585 }
class ____(object): def numMatchingSubseq(self, S, words): """ :type S: str :type words: List[str] :rtype: int """ waiting = collections.defaultdict(list) for word in words: it = iter(word) waiting[next(it, None)].append(it) for...
Solution
python
jina-ai__jina
tests/k8s/test-executor/debug_executor.py
{ "start": 78, "end": 3142 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) from jina.logging.logger import JinaLogger self.logger = JinaLogger(self.__class__.__name__) self._name = self.runtime_args.name @requests(on='/debug') def debug(self, docs: Documen...
TestExecutor
python
pytorch__pytorch
test/test_cpp_extensions_jit.py
{ "start": 1148, "end": 50091 }
class ____(common.TestCase): """Tests just-in-time cpp extensions. Don't confuse this with the PyTorch JIT (aka TorchScript). """ def setUp(self): super().setUp() # cpp extensions use relative paths. Those paths are relative to # this file, so we'll change the working directory ...
TestCppExtensionJIT
python
huggingface__transformers
tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py
{ "start": 5202, "end": 22110 }
class ____: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: str | None = field( default=None,...
ModelArguments
python
django__django
tests/managers_regress/models.py
{ "start": 2697, "end": 3127 }
class ____(models.Model): fk = models.ForeignKey(RelatedModel, models.CASCADE, related_name="test_fk") m2m = models.ManyToManyField(RelatedModel, related_name="test_m2m") gfk_ctype = models.ForeignKey(ContentType, models.SET_NULL, null=True) gfk_id = models.IntegerField(null=True) gfk = GenericFor...
RelationModel
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 13289, "end": 17056 }
class ____(BaseField): """Disclaimer: This field is kept for historical reason but since it converts the values to float, it is not suitable for true decimal storage. Consider using :class:`~mongoengine.fields.Decimal128Field`. Fixed-point decimal number field. Stores the value as a float by default unless...
DecimalField
python
django__django
tests/view_tests/tests/test_csrf.py
{ "start": 328, "end": 5706 }
class ____(SimpleTestCase): def setUp(self): super().setUp() self.client = Client(enforce_csrf_checks=True) @override_settings( USE_I18N=True, MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ...
CsrfViewTests
python
jina-ai__jina
tests/unit/serve/runtimes/worker/test_worker_runtime.py
{ "start": 2246, "end": 2652 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._count = 0 @requests async def foo(self, docs, **kwargs): self._count += 1 current_count = self._count if current_count % 2 == 0: await asyncio.sleep(0.1) ...
AsyncSlowNewDocsExecutor
python
tensorflow__tensorflow
tensorflow/tools/compatibility/ast_edits.py
{ "start": 28047, "end": 28390 }
class ____: """This class represents an analysis result and how it should be logged. This class must provide the following fields: * `log_level`: The log level to which this detection should be logged * `log_message`: The message that should be logged for this detection For an example, see `VersionedTFImpo...
AnalysisResult
python
ray-project__ray
python/ray/exceptions.py
{ "start": 30649, "end": 32655 }
class ____(RayError): """Raised when there is an error deserializing a serialized exception. This occurs when deserializing (unpickling) a previously serialized exception fails. In this case, we fall back to raising the string representation of the original exception along with its stack trace that was...
UnserializableException
python
pytorch__pytorch
torch/cuda/__init__.py
{ "start": 54609, "end": 55162 }
class ____: is_cuda = True is_sparse = False def type(self, *args, **kwargs): # We could use a Protocol here to tell mypy that self has `get_device` method # but it is only available in the typing module on Python >= 3.8 # or on typing_extensions module on Python >= 3.6 with...
_CudaBase
python
walkccc__LeetCode
solutions/2973. Find Number of Coins to Place in Tree Nodes/2973.py
{ "start": 917, "end": 1384 }
class ____: def placedCoins(self, edges: list[list[int]], cost: list[int]) -> list[int]: n = len(cost) ans = [0] * n tree = [[] for _ in range(n)] for u, v in edges: tree[u].append(v) tree[v].append(u) def dfs(u: int, prev: int) -> None: res = ChildCost(cost[u]) for v in ...
Solution
python
kamyu104__LeetCode-Solutions
Python/minimum-total-space-wasted-with-k-resizing-operations.py
{ "start": 39, "end": 730 }
class ____(object): def minSpaceWastedKResizing(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ INF = float("inf") k += 1 dp = [[INF]*(k+1) for _ in xrange(len(nums)+1)] dp[0][0] = 0 for i in xrange(1, len(nums)+1...
Solution
python
django-haystack__django-haystack
test_haystack/solr_tests/test_inputs.py
{ "start": 77, "end": 3738 }
class ____(TestCase): def setUp(self): super().setUp() self.query_obj = connections["solr"].get_query() def test_raw_init(self): raw = inputs.Raw("hello OR there, :you") self.assertEqual(raw.query_string, "hello OR there, :you") self.assertEqual(raw.kwargs, {}) s...
SolrInputTestCase
python
astropy__astropy
astropy/time/tests/test_methods.py
{ "start": 22035, "end": 33464 }
class ____: """Arithmetic on Time objects, using both doubles.""" kwargs = ({}, {"axis": None}, {"axis": 0}, {"axis": 1}, {"axis": 2}) functions = ("min", "max", "sort") def setup_class(cls): mjd = np.arange(50000, 50100, 10).reshape(2, 5, 1) frac = np.array([0.1, 0.1 + 1.0e-15, 0.1 - ...
TestArithmetic
python
scipy__scipy
scipy/stats/tests/test_mstats_basic.py
{ "start": 52491, "end": 55310 }
class ____: # data from gh-1428 x = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., ...
TestMannwhitneyu
python
python-attrs__attrs
typing-examples/mypy.py
{ "start": 5637, "end": 5916 }
class ____: num: int = attr.field(validator=attr.validators.ge(0)) with attr.validators.disabled(): Validated2(num=-1) try: attr.validators.set_disabled(True) Validated2(num=-1) finally: attr.validators.set_disabled(False) # Custom repr() @attr.s
Validated2