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
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_step_function.py
{ "start": 1345, "end": 3801 }
class ____: def test_init(self): sensor = StepFunctionExecutionSensor( task_id=TASK_ID, execution_arn=EXECUTION_ARN, aws_conn_id=AWS_CONN_ID, region_name=REGION_NAME, verify=True, botocore_config={"read_timeout": 42}, ) ...
TestStepFunctionExecutionSensor
python
encode__django-rest-framework
tests/schemas/test_openapi.py
{ "start": 39907, "end": 47853 }
class ____(TestCase): def test_override_settings(self): assert isinstance(views.ExampleListView.schema, AutoSchema) def test_paths_construction(self): """Construction of the `paths` key.""" patterns = [ path('example/', views.ExampleListView.as_view()), ] ge...
TestGenerator
python
ray-project__ray
release/ray_release/exception.py
{ "start": 2800, "end": 2900 }
class ____(EnvironmentSetupError): exit_code = ExitCode.REMOTE_ENV_SETUP_ERROR
RemoteEnvSetupError
python
pytorch__pytorch
test/jit/test_list_dict.py
{ "start": 73253, "end": 80819 }
class ____(JitTestCase): """ This class contains a suite of tests for torch.jit.script, a function that returns a dictionary-like object that has reference semantics across the Python/TorchScript boundary. That is, it can be passed to a TorchScript function that mutates it and those modification...
TestScriptDict
python
wandb__wandb
wandb/apis/importers/internals/internal.py
{ "start": 1981, "end": 12887 }
class ____: run: ImporterRun interface: InterfaceQueue = InterfaceQueue() @property def run_dir(self) -> str: p = Path(f"{ROOT_DIR}/{self.run.run_id()}/wandb") p.mkdir(parents=True, exist_ok=True) return f"{ROOT_DIR}/{self.run.run_id()}" def make_artifacts_only_records( ...
RecordMaker
python
automl__auto-sklearn
autosklearn/pipeline/components/regression/decision_tree.py
{ "start": 566, "end": 4904 }
class ____(AutoSklearnRegressionAlgorithm): def __init__( self, criterion, max_features, max_depth_factor, min_samples_split, min_samples_leaf, min_weight_fraction_leaf, max_leaf_nodes, min_impurity_decrease, random_state=None, ): ...
DecisionTree
python
qdrant__qdrant-client
qdrant_client/local/sparse_distances.py
{ "start": 1549, "end": 1864 }
class ____: def __init__(self, positive: SparseVector, negative: SparseVector): validate_sparse_vector(positive) validate_sparse_vector(negative) self.positive: SparseVector = sort_sparse_vector(positive) self.negative: SparseVector = sort_sparse_vector(negative)
SparseContextPair
python
modin-project__modin
asv_bench/benchmarks/benchmarks.py
{ "start": 20381, "end": 22288 }
class ____: param_names = ["shape", "indexer_type"] params = [ get_benchmark_shapes("TimeIndexing"), [ "bool_array", "bool_series", "scalar", "slice", "continuous_slice", "numpy_array_take_all_values", "python_li...
TimeIndexing
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/json.py
{ "start": 4182, "end": 4431 }
class ____(_FormatTypeMixin, sqltypes.JSON.JSONIndexType): def _format_value(self, value): if isinstance(value, int): value = "$[%s]" % value else: value = '$."%s"' % value return value
JSONIndexType
python
getsentry__sentry
src/sentry/features/base.py
{ "start": 1224, "end": 1482 }
class ____(Feature): def __init__(self, name: str, organization: Organization) -> None: super().__init__(name) self.organization = organization def get_subject(self) -> Organization: return self.organization
OrganizationFeature
python
kubernetes-client__python
kubernetes/client/models/v1_replication_controller_list.py
{ "start": 383, "end": 7334 }
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...
V1ReplicationControllerList
python
PyCQA__pylint
tests/functional/r/regression_02/regression_5244.py
{ "start": 205, "end": 332 }
class ____: def some_func(self): return lambda: 42 def __len__(self): return len(self.some_func())
MyClass
python
run-llama__llama_index
llama-index-core/llama_index/core/memory/types.py
{ "start": 442, "end": 2412 }
class ____(BaseComponent): """Base class for all memory types.""" @classmethod def class_name(cls) -> str: """Get class name.""" return "BaseMemory" @classmethod @abstractmethod def from_defaults( cls, **kwargs: Any, ) -> "BaseMemory": """Create a ch...
BaseMemory
python
Netflix__metaflow
metaflow/plugins/argo/argo_workflows.py
{ "start": 215846, "end": 216776 }
class ____(object): # https://github.com/argoproj/argo-events/blob/master/api/sensor.md#argoproj.io/v1alpha1.ArgoWorkflowTrigger def __init__(self): tree = lambda: defaultdict(tree) self.payload = tree() self.payload["operation"] = "submit" self.payload["group"] = "argoproj.io" ...
ArgoWorkflowTrigger
python
allegroai__clearml
examples/frameworks/pytorch/pytorch_tensorboard.py
{ "start": 409, "end": 6227 }
class ____(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 10) def forw...
Net
python
django__django
tests/bash_completion/management/commands/test_command.py
{ "start": 54, "end": 258 }
class ____(BaseCommand): def add_arguments(self, parser): parser.add_argument("--list", action="store_true", help="Print all options") def handle(self, *args, **options): pass
Command
python
sympy__sympy
sympy/stats/rv.py
{ "start": 6285, "end": 8632 }
class ____(Expr): """ Random Symbols represent ProbabilitySpaces in SymPy Expressions. In principle they can take on any value that their symbol can take on within the associated PSpace with probability determined by the PSpace Density. Explanation =========== Random Symbols contain ps...
RandomSymbol
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/service/cross_trainer_cache_test.py
{ "start": 1237, "end": 19200 }
class ____(data_service_test_base.TestBase, parameterized.TestCase): """Tests for sharing datasets across jobs using a cross-trainer cache.""" @combinations.generate(test_base.default_test_combinations()) def testEnableCrossTrainerCache(self): """Tests cross-trainer cache with `di...
CrossTrainerCacheTest
python
mlflow__mlflow
mlflow/utils/autologging_utils/logging_and_warnings.py
{ "start": 237, "end": 8120 }
class ____: """ Provides threadsafe utilities to modify warning behavior for MLflow autologging, including: - Global disablement of MLflow warnings across all threads - Global rerouting of MLflow warnings to an MLflow event logger (i.e. `logger.warning()`) across all threads - Disablement of ...
_WarningsController
python
huggingface__transformers
src/transformers/models/nllb_moe/modeling_nllb_moe.py
{ "start": 33148, "end": 38252 }
class ____(NllbMoePreTrainedModel): """ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`NllbMoeDecoderLayer`] Args: config: NllbMoeConfig embed_tokens (nn.Embedding): output embedding """ _can_record_outputs = { "h...
NllbMoeDecoder
python
huggingface__transformers
src/transformers/models/funnel/modeling_funnel.py
{ "start": 22520, "end": 23318 }
class ____(nn.Module): def __init__(self, config: FunnelConfig) -> None: super().__init__() self.linear_1 = nn.Linear(config.d_model, config.d_inner) self.activation_function = ACT2FN[config.hidden_act] self.activation_dropout = nn.Dropout(config.activation_dropout) self.line...
FunnelPositionwiseFFN
python
pydata__xarray
xarray/tests/arrays.py
{ "start": 373, "end": 901 }
class ____(utils.NDArrayMixin, ExplicitlyIndexed): """Disallows any loading.""" def __init__(self, array): self.array = array def get_duck_array(self): raise UnexpectedDataAccess("Tried accessing data") def __array__( self, dtype: np.typing.DTypeLike | None = None, /, *, copy:...
InaccessibleArray
python
ansible__ansible
lib/ansible/config/manager.py
{ "start": 11980, "end": 32459 }
class ____: DEPRECATED = [] # type: list[tuple[str, dict[str, str]]] WARNINGS = set() # type: set[str] _errors: list[tuple[str, Exception]] def __init__(self, conf_file=None, defs_file=None): self._get_ini_config_value = functools.cache(self._get_ini_config_value) self._base_defs =...
ConfigManager
python
langchain-ai__langchain
libs/core/langchain_core/language_models/base.py
{ "start": 1117, "end": 3072 }
class ____(TypedDict, total=False): """LangSmith parameters for tracing.""" ls_provider: str """Provider of the model.""" ls_model_name: str """Name of the model.""" ls_model_type: Literal["chat", "llm"] """Type of the model. Should be 'chat' or 'llm'.""" ls_temperature: float | None ...
LangSmithParams
python
pytorch__pytorch
test/distributed/_shard/sharding_spec/test_sharding_spec.py
{ "start": 1251, "end": 19870 }
class ____(TestCase): @skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "2 CUDA GPUs are needed") def test_device_placement(self): # valid devices DevicePlacementSpec("cuda:0") DevicePlacementSpec(torch.device(0)) DevicePlacementSpec(torch.device("cuda:0")) DevicePlaceme...
TestShardingSpec
python
pytorch__pytorch
test/distributed/_shard/sharded_tensor/test_sharded_tensor.py
{ "start": 85361, "end": 120165 }
class ____(ShardedTensorTestBase): @with_comms(init_rpc=False) @skip_if_lt_x_gpu(4) @requires_nccl() def test_local_shards(self): shard_offsets = [(self.rank // 2) * 5, (self.rank % 2) * 5] local_shard_metadata = ShardMetadata( shard_offsets=shard_offsets, shard_s...
TestShardedTensorFromLocalShards
python
pytorch__pytorch
test/test_nestedtensor.py
{ "start": 154252, "end": 345832 }
class ____(NestedTensorTestCase): # TODO: consolidate with the below def _get_list_for_jagged_tensor(self, nested_size, device, requires_grad=True): Ds = nested_size[1:] out = [] for s in nested_size[0]: out.append( torch.randn( s, ...
TestNestedTensorSubclass
python
pypa__hatch
src/hatch/config/model.py
{ "start": 13575, "end": 14338 }
class ____(LazilyParsedConfig): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._field_location = FIELD_TO_PARSE @property def location(self): if self._field_location is FIELD_TO_PARSE: if "location" in self.raw_data: location...
ProjectConfig
python
numba__numba
numba/core/withcontexts.py
{ "start": 3980, "end": 16343 }
class ____(WithContext): """Creates a contextmanager to be used inside jitted functions to enter *object-mode* for using interpreter features. The body of the with-context is lifted into a function that is compiled in *object-mode*. This transformation process is limited and cannot process all possibl...
_ObjModeContextType
python
tornadoweb__tornado
tornado/test/httpserver_test.py
{ "start": 44597, "end": 45625 }
class ____(AsyncHTTPTestCase): def get_app(self): return Application([("/", HelloWorldRequestHandler)]) def get_httpserver_options(self): return dict(max_header_size=1024) def test_small_headers(self): response = self.fetch("/", headers={"X-Filler": "a" * 100}) response.ret...
MaxHeaderSizeTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/fixtures/mypy.py
{ "start": 710, "end": 8786 }
class ____(TestBase): __requires__ = ("no_sqlalchemy2_stubs",) @config.fixture(scope="function") def per_func_cachedir(self): yield from self._cachedir() @config.fixture(scope="class") def cachedir(self): yield from self._cachedir() def _cachedir(self): # as of mypy 0....
MypyTest
python
tqdm__tqdm
tqdm/contrib/telegram.py
{ "start": 2815, "end": 5008 }
class ____(tqdm_auto): """ Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot. May take a few seconds to create (`__init__`). - create a bot <https://core.telegram.org/bots#6-botfather> - copy its `{token}` - add the bot to a chat and send it a message such as `/start` - go ...
tqdm_telegram
python
scrapy__scrapy
scrapy/utils/request.py
{ "start": 3595, "end": 3701 }
class ____(Protocol): def fingerprint(self, request: Request) -> bytes: ...
RequestFingerprinterProtocol
python
lazyprogrammer__machine_learning_examples
unsupervised_class3/autoencoder_theano.py
{ "start": 427, "end": 2942 }
class ____: def __init__(self, D, M): # represents a batch of training data self.X = T.matrix('X') # input -> hidden self.W = theano.shared(np.random.randn(D, M) * np.sqrt(2.0 / M)) self.b = theano.shared(np.zeros(M)) # hidden -> output self.V = theano.shared(np.random.randn(M, D) * np.s...
Autoencoder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py
{ "start": 11306, "end": 11636 }
class ____(RawDataMixin, IncrementalAppsflyerStream): cursor_field = "install_time" def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: return f"raw-data/export/app/{self.app_id}/installs_report/...
Installs
python
PrefectHQ__prefect
src/prefect/logging/highlighters.py
{ "start": 86, "end": 413 }
class ____(RegexHighlighter): """Apply style to log levels.""" base_style = "level." highlights: list[str] = [ r"(?P<debug_level>DEBUG)", r"(?P<info_level>INFO)", r"(?P<warning_level>WARNING)", r"(?P<error_level>ERROR)", r"(?P<critical_level>CRITICAL)", ]
LevelHighlighter
python
google__jax
tests/source_mapper_test.py
{ "start": 4508, "end": 5335 }
class ____(jtu.JaxTestCase): def test_hlo_parser(self): source_map = hlo._parse_hlo_new_format(HLO_EXAMPLE.split("\n")) print(source_map) self.assertLen(source_map.sources, 1) self.assertEqual(source_map.sources[0], "<embedded module>") mappings = source_map.mappings constant_line_idx = -1 ...
HLOParserTest
python
ray-project__ray
python/ray/tests/accelerators/mock_dpctl_2.py
{ "start": 124, "end": 271 }
class ____: def __init__(self, info): pass @property def name(self): return "Intel(R) Data Center GPU Max 1100"
SyclDevice
python
paramiko__paramiko
tests/test_transport.py
{ "start": 38416, "end": 38834 }
class ____(TransportTest): _auth_handler_class = AuthOnlyHandler def setUp(self): # Copypasta (Transport init is load-bearing) self.socks = LoopSocket() self.sockc = LoopSocket() self.sockc.link(self.socks) # New class who dis self.tc = ServiceRequestingTransport...
ServiceRequestingTransportTest
python
PyCQA__pylint
tests/functional/r/regression_02/regression_5408.py
{ "start": 309, "end": 360 }
class ____: inner_class = MyInnerClass
MySubClass
python
pypa__pip
src/pip/_internal/distributions/base.py
{ "start": 274, "end": 1830 }
class ____(metaclass=abc.ABCMeta): """A base class for handling installable artifacts. The requirements for anything installable are as follows: - we must be able to determine the requirement name (or we can't correctly handle the non-upgrade case). - for packages with setup requirements, we...
AbstractDistribution
python
dask__dask
dask/_task_spec.py
{ "start": 10780, "end": 15069 }
class ____: key: KeyType _dependencies: frozenset __slots__ = tuple(__annotations__) def ref(self): return Alias(self.key) def copy(self): raise NotImplementedError @property def data_producer(self) -> bool: return False @property def dependencies(self) -...
GraphNode
python
allegroai__clearml
clearml/backend_api/services/v2_23/workers.py
{ "start": 26542, "end": 29519 }
class ____(NonStrictDataModel): """ :param id: Worker ID :type id: str :param name: Worker name :type name: str :param running_time: Task running time :type running_time: int :param last_iteration: Last task iteration :type last_iteration: int """ _schema = { "proper...
CurrentTaskEntry
python
marshmallow-code__marshmallow
tests/test_decorators.py
{ "start": 3917, "end": 7876 }
class ____: def test_pass_original_single(self): class MySchema(Schema): foo = fields.Raw() @post_load(pass_original=True) def post_load(self, data, original_data, **kwargs): ret = data.copy() ret["_post_load"] = original_data["sentinel"] ...
TestPassOriginal
python
spack__spack
lib/spack/spack/vendor/jinja2/nodes.py
{ "start": 25066, "end": 25654 }
class ____(Expr): """Get an attribute or item from an expression and prefer the item.""" fields = ("node", "arg", "ctx") node: Expr arg: Expr ctx: str def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any: if self.ctx != "load": raise Impossible() e...
Getitem
python
bokeh__bokeh
src/bokeh/models/glyph.py
{ "start": 3013, "end": 3317 }
class ____(XYGlyph): ''' Base class of glyphs with `x` and `y` coordinate attributes and a connected topology. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @abstract
ConnectedXYGlyph
python
astropy__astropy
astropy/coordinates/tests/test_representation_methods.py
{ "start": 12187, "end": 16795 }
class ____(ShapeSetup): def test_broadcast_to(self): s0_broadcast = np.broadcast_to(self.s0, (3, 6, 7)) s0_diff = s0_broadcast.differentials["s"] assert type(s0_broadcast) is type(self.s0) assert s0_broadcast.shape == (3, 6, 7) assert s0_diff.shape == s0_broadcast.shape ...
TestShapeFunctions
python
Netflix__metaflow
metaflow/plugins/pypi/pip.py
{ "start": 709, "end": 1538 }
class ____(Exception): "Wrapper for pip package resolve errors." def __init__(self, error): self.error = error try: # Parse the package spec from error message: # ERROR: ERROR: Could not find a version that satisfies the requirement pkg==0.0.1 (from versions: none) ...
PipPackageNotFound
python
neetcode-gh__leetcode
python/0707-design-linked-list.py
{ "start": 119, "end": 1863 }
class ____: def __init__(self): self.left = ListNode(0) self.right = ListNode(0) self.left.next = self.right self.right.prev = self.left def get(self, index: int) -> int: cur = self.left.next while cur and index > 0: cur = cur.next index ...
MyLinkedList
python
MTrajK__coding-problems
Other/running_median.py
{ "start": 573, "end": 2859 }
class ____: def __init__(self, is_min=True): self.data = [] self.is_min = is_min def push(self, el): if not self.is_min: el = -el heapq.heappush(self.data, el) def pop(self): el = heapq.heappop(self.data) if not self.is_min: el = -el ...
PriorityQueue
python
eth-brownie__brownie
brownie/_gui/console.py
{ "start": 107, "end": 420 }
class ____(ToggleButton): def __init__(self, parent): super().__init__(parent, "Console", "c") self.console = self.root.main.console def toggle_on(self): self.console.config(height=3) return True def toggle_off(self): self.console.config(height=1)
ConsoleButton
python
pytorch__pytorch
torchgen/api/types/types.py
{ "start": 4746, "end": 5082 }
class ____(CType): elem: CType def cpp_type(self, *, strip_ref: bool = False) -> str: # Do not pass `strip_ref` recursively. return f"::std::optional<{self.elem.cpp_type()}>" def remove_const_ref(self) -> CType: return OptionalCType(self.elem.remove_const_ref()) @dataclass(frozen...
OptionalCType
python
ray-project__ray
python/ray/train/examples/pytorch/torch_data_prefetch_benchmark/auto_pipeline_for_host_to_device_data_transfer.py
{ "start": 239, "end": 621 }
class ____(nn.Module): def __init__(self, in_d, hidden): # output dim = 1 super(Net, self).__init__() dims = [in_d] + hidden + [1] self.layers = nn.ModuleList( [nn.Linear(dims[i - 1], dims[i]) for i in range(len(dims))] ) def forward(self, x): for lay...
Net
python
openai__openai-python
src/openai/types/audio/transcription.py
{ "start": 872, "end": 1373 }
class ____(BaseModel): input_tokens: int """Number of input tokens billed for this request.""" output_tokens: int """Number of output tokens generated.""" total_tokens: int """Total number of tokens used (input + output).""" type: Literal["tokens"] """The type of the usage object. Alw...
UsageTokens
python
tensorflow__tensorflow
third_party/xla/xla/backends/cpu/testlib/elemental_kernel_emitter_test.py
{ "start": 6971, "end": 8863 }
class ____(parameterized.TestCase): def test_elemental_comparision_kernel_emitter(self, op_def, shape, dtype): [direction, np_op] = op_def is_unsigned = np.issubdtype(dtype, np.unsignedinteger) value_range = (0.0, 20.0) if is_unsigned else (-10.0, 10.0) lhs_np = create_input(value_range, shape, dtyp...
ElementalComparisonKernelRunnerTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py
{ "start": 1432, "end": 1481 }
class ____[T1 = str, T4 = dict[T1, T2]]: ...
ClassJ
python
pytorch__pytorch
torch/ao/nn/quantized/modules/conv.py
{ "start": 16624, "end": 21181 }
class ____(_ConvNd): r"""Applies a 2D convolution over a quantized input signal composed of several quantized input planes. For details on input arguments, parameters, and implementation see :class:`~torch.nn.Conv2d`. .. note:: Only `zeros` is supported for the :attr:`padding_mode` argumen...
Conv2d
python
html5lib__html5lib-python
html5lib/html5parser.py
{ "start": 2188, "end": 14726 }
class ____(object): """HTML parser Generates a tree structure from a stream of (possibly malformed) HTML. """ def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False): """ :arg tree: a treebuilder class controlling the type of tree that will be ...
HTMLParser
python
django__django
tests/admin_views/test_autocomplete_view.py
{ "start": 2061, "end": 14744 }
class ____(AdminViewBasicTestCase): as_view_args = {"admin_site": site} opts = { "app_label": Answer._meta.app_label, "model_name": Answer._meta.model_name, "field_name": "question", } factory = RequestFactory() url = reverse_lazy("autocomplete_admin:autocomplete") @clas...
AutocompleteJsonViewTests
python
getsentry__sentry
src/flagpole/__init__.py
{ "start": 1999, "end": 2334 }
class ____(Exception): pass @functools.cache def load_json_schema() -> dict[str, Any]: path = os.path.join(os.path.dirname(__file__), "flagpole-schema.json") with open(path, "rb") as json_file: data = orjson.loads(json_file.read()) return data @dataclasses.dataclass(frozen=True)
InvalidFeatureFlagConfiguration
python
langchain-ai__langchain
libs/core/langchain_core/prompts/structured.py
{ "start": 715, "end": 6005 }
class ____(ChatPromptTemplate): """Structured prompt template for a language model.""" schema_: dict | type """Schema for the structured prompt.""" structured_output_kwargs: dict[str, Any] = Field(default_factory=dict) def __init__( self, messages: Sequence[MessageLikeRepresentatio...
StructuredPrompt
python
getsentry__sentry
src/sentry/api/bases/organization.py
{ "start": 7098, "end": 7311 }
class ____(OrganizationPermission): scope_map = { "GET": ["event:read", "event:write", "event:admin"], "POST": ["event:read", "event:write", "event:admin"], }
OrganizationDataExportPermission
python
dagster-io__dagster
examples/docs_projects/project_ml/src/project_ml/defs/types.py
{ "start": 395, "end": 577 }
class ____(TypedDict): test_accuracy: float predictions: list[int] labels: list[int] classification_report: dict[str, Any] model_info: dict[str, str]
EvaluationResult
python
getsentry__sentry
tests/sentry/integrations/github_enterprise/test_webhooks.py
{ "start": 697, "end": 11263 }
class ____(APITestCase): def setUp(self) -> None: self.url = "/extensions/github-enterprise/webhook/" self.metadata = { "url": "35.232.149.196", "id": "2", "name": "test-app", "webhook_secret": "b3002c3e321d4b7880360d397db2ccfd", "private_k...
WebhookTest
python
pytorch__pytorch
torch/_inductor/fx_passes/overlap_scheduling.py
{ "start": 6035, "end": 6456 }
class ____: """Track info about a collective operation""" start_node: fx.Node wait_node: fx.Node size_bytes: int estimated_time_ms: float exposed_time_ms: float # How much of this collective is still exposed hiding_nodes: OrderedSet[fx.Node] = field(default_factory=OrderedSet) @proper...
CollectiveInfo
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 12001, "end": 14051 }
class ____(nn.Module): """ A class to patchify the time series sequence into different patches Returns: `torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)` """ def __init__(self, config: PatchTSTConfig): super().__init__() self.sequence_length =...
PatchTSTPatchify
python
Textualize__textual
docs/examples/guide/css/nesting02.py
{ "start": 122, "end": 479 }
class ____(App): """App with nested CSS.""" CSS_PATH = "nesting02.tcss" def compose(self) -> ComposeResult: with Horizontal(id="questions"): yield Static("Yes", classes="button affirmative") yield Static("No", classes="button negative") if __name__ == "__main__": app ...
NestingDemo
python
PyCQA__pylint
tests/functional/u/unpacking/unpacking_non_sequence_py37.py
{ "start": 373, "end": 486 }
class ____: function: Callable[..., tuple[int, int]] def update(self): _, _ = self.function()
Metric
python
realpython__materials
thread-safety-locks/bank_deadlock.py
{ "start": 81, "end": 1213 }
class ____: def __init__(self): self.balance = 0 self.lock = threading.Lock() def deposit(self, amount): print( f"Thread {threading.current_thread().name} waiting " "to acquire lock for deposit()" ) with self.lock: print( ...
BankAccount
python
pytorch__pytorch
torch/distributed/algorithms/ddp_comm_hooks/mixed_precision_hooks.py
{ "start": 218, "end": 3254 }
class ____: """ State to manage DDP mixed precision in backward / gradient communication. This contains a weakref to the DDP module for access to reducer and process group, and a stream to run parameter and gradient upcasts. """ ddp_weakref: Any upcast_stream: torch.Stream wait_for_str...
_AllreduceUpcastHookState
python
getsentry__sentry
src/sentry/models/groupreaction.py
{ "start": 522, "end": 3205 }
class ____(DefaultFieldsModel): """ This model has no affiliation with PullRequestComment.reactions. This model represents feedback/evaluations related to a Group or an entity associated with a Group. This model supports multiple patterns based on NULL combinations: Suspect Commit Reactions: - ...
GroupReaction
python
sympy__sympy
sympy/plotting/pygletplot/plot.py
{ "start": 891, "end": 11354 }
class ____: """ Plot Examples ============= See examples/advanced/pyglet_plotting.py for many more examples. >>> from sympy.plotting.pygletplot import PygletPlot as Plot >>> from sympy.abc import x, y, z >>> Plot(x*y**3-y*x**3) [0]: -x**3*y + x*y**3, 'mode=cartesian' >>> p = Plot...
PygletPlot
python
mlflow__mlflow
mlflow/webhooks/types.py
{ "start": 9245, "end": 9922 }
class ____(TypedDict): """Payload sent when an alias is created for a prompt version. Example payload: .. code-block:: python { "name": "example_prompt", "alias": "example_alias", "version": "1", } """ name: str """The name of the prompt."...
PromptAliasCreatedPayload
python
nryoung__algorithms
algorithms/data_structures/queue.py
{ "start": 672, "end": 1445 }
class ____: def __init__(self): self._queue = deque([]) def add(self, value): """ Add element as the last item in the Queue. Worst Case Complexity: O(1) """ self._queue.append(value) def remove(self): """ Remove element from the front of t...
Queue
python
kamyu104__LeetCode-Solutions
Python/longest-fibonacci-subarray.py
{ "start": 37, "end": 413 }
class ____(object): def longestSubarray(self, nums): """ :type nums: List[int] :rtype: int """ result = cnt = 2 for i in xrange(2, len(nums)): if nums[i] != nums[i-1]+nums[i-2]: cnt = 2 continue cnt += 1 ...
Solution
python
pytorch__pytorch
test/distributed/_composable/test_replicate_with_compiler.py
{ "start": 13679, "end": 16131 }
class ____(InductorTestCase): def setUp(self): # Hmm, why a specific set_device call for rank 0? self.rank = 0 self.world_size = 4 torch.get_device_module(device_type).set_device(device_type) store = FakeStore() dist.init_process_group( backend="fake", ...
DDP_TP_Test
python
huggingface__transformers
src/transformers/models/timm_wrapper/modeling_timm_wrapper.py
{ "start": 5645, "end": 10641 }
class ____(TimmWrapperPreTrainedModel): """ Wrapper class for timm models to be used in transformers. """ def __init__(self, config: TimmWrapperConfig): super().__init__(config) # using num_classes=0 to avoid creating classification head extra_init_kwargs = config.model_args or ...
TimmWrapperModel
python
google__pytype
pytype/pytd/pytd.py
{ "start": 15072, "end": 15193 }
class ____(Type): """A type we know nothing about yet (? in pytd).""" def __bool__(self): return True
AnythingType
python
openai__openai-python
src/openai/types/evals/create_eval_completions_run_data_source.py
{ "start": 1913, "end": 3015 }
class ____(BaseModel): type: Literal["stored_completions"] """The type of source. Always `stored_completions`.""" created_after: Optional[int] = None """An optional Unix timestamp to filter items created after this time.""" created_before: Optional[int] = None """An optional Unix timestamp to ...
SourceStoredCompletions
python
pytorch__pytorch
torch/_inductor/codegen/cpp_gemm_template.py
{ "start": 25570, "end": 73855 }
class ____(CppTemplate): """ GEMM Template for Inductor CPP Backend. """ def __init__( self, input_nodes, layout: ir.Layout, num_threads: int, register_blocking: GemmBlocking, beta=1, alpha=1, has_bias=False, epilogue_creator: Opti...
CppGemmTemplate
python
getsentry__sentry
src/sentry/conduit/auth.py
{ "start": 194, "end": 2436 }
class ____(NamedTuple): token: str channel_id: str url: str def generate_channel_id() -> str: """Generate a unique channel ID for a Conduit stream.""" return str(uuid.uuid4()) def generate_conduit_token( org_id: int, channel_id: str, issuer: str | None = None, audience: str | Non...
ConduitCredentials
python
walkccc__LeetCode
solutions/3393. Count Paths With the Given XOR Value/3393.py
{ "start": 0, "end": 613 }
class ____: def countPathsWithXorValue(self, grid: list[list[int]], k: int) -> int: MOD = 1_000_000_007 m = len(grid) n = len(grid[0]) @functools.lru_cache(None) def count(i: int, j: int, xors: int) -> int: """ Return the number of paths from (i, j) to (m - 1, n - 1) with XOR value ...
Solution
python
getsentry__sentry
tests/sentry/monitors/endpoints/test_organization_monitor_details.py
{ "start": 301, "end": 430 }
class ____(BaseUpdateMonitorTest): endpoint = "sentry-api-0-organization-monitor-details" __test__ = True
UpdateMonitorTest
python
mozilla__bleach
bleach/_vendor/html5lib/serializer.py
{ "start": 15682, "end": 15759 }
class ____(Exception): """Error in serialized tree""" pass
SerializeError
python
django-extensions__django-extensions
tests/test_autoslug_fields.py
{ "start": 740, "end": 8185 }
class ____(TestCase): def tearDown(self): super().tearDown() SluggedTestModel.objects.all().delete() CustomFuncSluggedTestModel.objects.all().delete() CustomFuncPrecedenceSluggedTestModel.objects.all().delete() def test_auto_create_slug(self): m = SluggedTestModel(title...
AutoSlugFieldTest
python
pennersr__django-allauth
allauth/socialaccount/providers/openid/migrations/0001_initial.py
{ "start": 43, "end": 1643 }
class ____(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name="OpenIDNonce", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=...
Migration
python
scipy__scipy
scipy/sparse/linalg/_eigen/arpack/arpack.py
{ "start": 12741, "end": 13029 }
class ____(RuntimeError): """ ARPACK error """ def __init__(self, info, infodict=None): if infodict is None: infodict = _NAUPD_ERRORS msg = infodict.get(info, "Unknown error") super().__init__(f"ARPACK error {info}: {msg}")
ArpackError
python
getsentry__sentry
src/sentry/notifications/notifications/organization_request/invite_request.py
{ "start": 373, "end": 1447 }
class ____(AbstractInviteRequestNotification): metrics_key = "invite_request" template_path = "sentry/emails/organization-invite-request" def get_specific_analytics_event(self, provider: ExternalProviders) -> analytics.Event | None: """ Returns the specific analytics event for the provider....
InviteRequestNotification
python
cherrypy__cherrypy
cherrypy/lib/sessions.py
{ "start": 16221, "end": 22261 }
class ____(Session): """Implementation of the file backend for sessions. storage_path The folder where session data will be saved. Each session will be saved as pickle.dump(data, expiration_time) in its own file; the filename will be self.SESSION_PREFIX + self.id. lock_timeout ...
FileSession
python
wandb__wandb
tests/unit_tests/test_step_prepare.py
{ "start": 7170, "end": 10537 }
class ____: @staticmethod def _bg_prepare( step_prepare: StepPrepare, *args, **kwargs ) -> "concurrent.futures.Future[ResponsePrepare]": """Starts prepare running in the background.""" enqueued = threading.Event() future = concurrent.futures.Future() def prepare_and_...
TestStepPrepare
python
huggingface__transformers
src/transformers/models/x_clip/modeling_x_clip.py
{ "start": 2100, "end": 4250 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`): Contrastive loss for video-text similarity. logits_per_video (`torch.FloatTensor` of shape `(video_batch_size, text_batch_size)`): The scaled dot product scores betwee...
XCLIPOutput
python
astropy__astropy
astropy/nddata/__init__.py
{ "start": 838, "end": 1551 }
class ____(_config.ConfigNamespace): """ Configuration parameters for `astropy.nddata`. """ warn_unsupported_correlated = _config.ConfigItem( True, "Whether to issue a warning if `~astropy.nddata.NDData` arithmetic " "is performed with uncertainties and the uncertainties do not ...
Conf
python
sanic-org__sanic
sanic/http/tls/creators.py
{ "start": 7907, "end": 9542 }
class ____(CertCreator): def check_supported(self) -> None: if not TRUSTME_INSTALLED: raise SanicException( "Sanic is attempting to use trustme to generate local TLS " "certificates since you did not supply a certificate, but " "one is required. Sa...
TrustmeCreator
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/auto_ml.py
{ "start": 26661, "end": 28896 }
class ____(GoogleCloudBaseOperator): """ List an AutoML training job. Can be used with AutoMLForecastingTrainingJob, AutoMLImageTrainingJob, AutoMLTabularTrainingJob, AutoMLTextTrainingJob, or AutoMLVideoTrainingJob in a Location. """ template_fields = ( "region", "project_id",...
ListAutoMLTrainingJobOperator
python
doocs__leetcode
solution/0000-0099/0078.Subsets/Solution.py
{ "start": 0, "end": 350 }
class ____: def subsets(self, nums: List[int]) -> List[List[int]]: def dfs(i: int): if i == len(nums): ans.append(t[:]) return dfs(i + 1) t.append(nums[i]) dfs(i + 1) t.pop() ans = [] t = [] ...
Solution
python
getsentry__sentry
src/sentry/plugins/bases/issue2.py
{ "start": 3030, "end": 17351 }
class ____(Plugin): auth_provider: str | None = None allowed_actions = ("create", "link", "unlink") # we default this to None to support legacy integrations, but newer style # should explicitly call out what is stored issue_fields: frozenset[str] | None = None # issue_fields = frozenset(['id',...
IssueTrackingPlugin2
python
jazzband__pip-tools
piptools/resolver.py
{ "start": 19485, "end": 32056 }
class ____(BaseResolver): """A wrapper for the backtracking (or 2020) resolver.""" def __init__( self, constraints: Iterable[InstallRequirement], existing_constraints: dict[str, InstallRequirement], repository: BaseRepository, allow_unsafe: bool = False, unsafe_p...
BacktrackingResolver
python
urllib3__urllib3
src/urllib3/contrib/emscripten/response.py
{ "start": 694, "end": 9507 }
class ____(BaseHTTPResponse): def __init__( self, internal_response: EmscriptenResponse, url: str | None = None, connection: BaseHTTPConnection | BaseHTTPSConnection | None = None, ): self._pool = None # set by pool class self._body = None self._response ...
EmscriptenHttpResponseWrapper
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 245009, "end": 247841 }
class ____: def _create_arrays(self): a = np.arange(20.0).reshape(4, 5) a.flags.writeable = False b = a[::2, ::2] return a, b def test_contiguous(self): testpassed = False a, _ = self._create_arrays() try: a.flat[12] = 100.0 except Val...
TestFlat
python
kamyu104__LeetCode-Solutions
Python/maximum-and-sum-of-array.py
{ "start": 72, "end": 2199 }
class ____(object): def maximumANDSum(self, nums, numSlots): """ :type nums: List[int] :type numSlots: int :rtype: int """ # Template translated from: # https://github.com/kth-competitive-programming/kactl/blob/main/content/graph/WeightedMatching.h def...
Solution