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 | ethereum__web3.py | web3/_utils/filters.py | {
"start": 6033,
"end": 6081
} | class ____(AsyncFilter):
pass
| AsyncBlockFilter |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 161421,
"end": 165142
} | class ____(Response):
"""
Response of events.scalar_metrics_iter_raw endpoint.
:param variants: Raw data points for each variant
:type variants: dict
:param total: Total data points count. If count_total is false, null is
returned
:type total: int
:param returned: Number of data poi... | ScalarMetricsIterRawResponse |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py | {
"start": 1139,
"end": 1473
} | class ____:
def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, weird_extra_arg: int = ..., *args: int, **kwargs: str) -> None: ...
async def __aexit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> Awaitable[No... | GoodFive |
python | astropy__astropy | astropy/io/votable/converters.py | {
"start": 29658,
"end": 30857
} | class ____(NumericArray):
"""
Handles a fixed-size array of complex numbers.
"""
vararray_type = ComplexArrayVarArray
def __init__(self, field, base, arraysize, config=None, pos=None):
NumericArray.__init__(self, field, base, arraysize, config, pos)
self._items *= 2
def parse(... | ComplexArray |
python | getsentry__sentry | tests/sentry/seer/fetch_issues/test_by_text_query.py | {
"start": 1998,
"end": 9459
} | class ____(IntegrationTestCase, CreateEventTestCase):
provider = GitHubIntegrationProvider
def setUp(self):
super().setUp()
self.gh_repo: Repository = self.create_repo(
name="getsentry/sentry",
provider="integrations:github",
integration_id=self.integration.i... | TestFetchIssuesByTextQuery |
python | pytorch__pytorch | torch/testing/_internal/common_subclass.py | {
"start": 2230,
"end": 3161
} | class ____(WrapperTensor):
@classmethod
def get_wrapper_properties(cls, t, requires_grad=False):
return t, {"requires_grad": requires_grad, "dispatch_sizes_strides_policy": "sizes"}
def __init__(self, t, requires_grad=False):
self.t = t
@classmethod
def __torch_dispatch__(cls, func... | WrapperTensorWithCustomSizes |
python | tornadoweb__tornado | demos/facebook/facebook.py | {
"start": 3426,
"end": 3613
} | class ____(BaseHandler, tornado.auth.FacebookGraphMixin):
def get(self):
self.clear_cookie("fbdemo_user")
self.redirect(self.get_argument("next", "/"))
| AuthLogoutHandler |
python | boto__boto3 | tests/unit/dynamodb/test_transform.py | {
"start": 15331,
"end": 18368
} | class ____(BaseTransformationTest):
def setUp(self):
super().setUp()
self.add_shape({'ConditionExpression': {'type': 'string'}})
self.add_shape({'KeyExpression': {'type': 'string'}})
shapes = self.json_model['shapes']
input_members = shapes['SampleOperationInputOutput']['mem... | TestTransformConditionExpression |
python | django__django | tests/staticfiles_tests/test_storage.py | {
"start": 36663,
"end": 38949
} | class ____(CollectionTestCase):
"""
Files referenced from CSS use the correct final hashed name regardless of
the order in which the files are post-processed.
"""
hashed_file_path = hashed_file_path
def setUp(self):
super().setUp()
self._temp_dir = temp_dir = tempfile.mkdtemp()... | TestCollectionHashedFilesCache |
python | pydantic__pydantic | pydantic/deprecated/config.py | {
"start": 475,
"end": 958
} | class ____(type):
def __getattr__(self, item: str) -> Any:
try:
obj = _config.config_defaults[item]
warnings.warn(_config.DEPRECATION_MESSAGE, DeprecationWarning)
return obj
except KeyError as exc:
raise AttributeError(f"type object '{self.__name__}' h... | _ConfigMetaclass |
python | wandb__wandb | wandb/sdk/internal/file_stream.py | {
"start": 10455,
"end": 25640
} | class ____:
"""Pushes chunks of files to our streaming endpoint.
This class is used as a singleton. It has a thread that serializes access to
the streaming endpoint and performs rate-limiting and batching.
TODO: Differentiate between binary/text encoding.
"""
class Finish(NamedTuple):
... | FileStreamApi |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_gtk3.py | {
"start": 22384,
"end": 22540
} | class ____(_FigureManagerGTK):
_toolbar2_class = NavigationToolbar2GTK3
_toolmanager_toolbar_class = ToolbarGTK3
@_BackendGTK.export
| FigureManagerGTK3 |
python | pypa__setuptools | setuptools/_distutils/tests/test_install_headers.py | {
"start": 214,
"end": 936
} | class ____(
support.TempdirManager,
):
def test_simple_run(self):
# we have two headers
header_list = self.mkdtemp()
header1 = os.path.join(header_list, 'header1')
header2 = os.path.join(header_list, 'header2')
self.write_file(header1)
self.write_file(header2)
... | TestInstallHeaders |
python | numba__numba | numba/core/types/abstract.py | {
"start": 9724,
"end": 9863
} | class ____(Sized):
"""
For types that have a constant size
"""
@abstractmethod
def __len__(self):
pass
| ConstSized |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 14716,
"end": 15244
} | class ____(BiffRecord):
"""
This record specifies if the formulas in the workbook can use natural
language formulas. This type of formula can refer to cells by its
content or the content of the column or row header cell.
Record USESELFS, BIFF8:
Offset Size Contents
0 2 ... | UseSelfsRecord |
python | davidhalter__parso | parso/normalizer.py | {
"start": 297,
"end": 3132
} | class ____(metaclass=_NormalizerMeta):
_rule_type_instances: Dict[str, List[type]] = {}
_rule_value_instances: Dict[str, List[type]] = {}
def __init__(self, grammar, config):
self.grammar = grammar
self._config = config
self.issues = []
self._rule_type_instances = self._ins... | Normalizer |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 56690,
"end": 57205
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("sv_SE")
Faker.seed(0)
def test_gender_first_names(self):
"""simple test to verify that we are pulling gender specific names"""
name = self.fake.first_name_female()
assert name in SvSEProvider.first_names_... | TestSvSE |
python | joke2k__faker | faker/providers/company/zh_CN/__init__.py | {
"start": 45,
"end": 1602
} | class ____(CompanyProvider):
formats = ["{{company_prefix}}{{company_suffix}}"]
company_prefixes = [
"超艺",
"和泰",
"九方",
"鑫博腾飞",
"戴硕电子",
"济南亿次元",
"海创",
"创联世纪",
"凌云",
"泰麒麟",
"彩虹",
"兰金电子",
"晖来计算机",
"天益",... | Provider |
python | django__django | tests/forms_tests/widget_tests/test_textarea.py | {
"start": 129,
"end": 2205
} | class ____(WidgetTest):
widget = Textarea()
def test_render(self):
self.check_html(
self.widget,
"msg",
"value",
html=('<textarea rows="10" cols="40" name="msg">value</textarea>'),
)
def test_render_required(self):
widget = Textarea()... | TextareaTest |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 16816,
"end": 17850
} | class ____:
param_names = ["value_type", "shape", "limit"]
params = [
["scalar", "dict", "Series"],
get_benchmark_shapes("TimeFillnaSeries"),
[None, 0.8],
]
def setup(self, value_type, shape, limit):
self.series = gen_nan_data(*shape)
if value_type == "scalar":
... | TimeFillnaSeries |
python | pypa__warehouse | tests/unit/admin/views/test_users.py | {
"start": 59686,
"end": 60631
} | class ____:
def test_user_email_domain_check(self, db_request):
user = UserFactory.create(with_verified_primary_email=True)
db_request.POST["email_address"] = user.primary_email.email
db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/foobar")
db_request.session = prete... | TestUserEmailDomainCheck |
python | ray-project__ray | python/ray/data/_internal/execution/interfaces/task_context.py | {
"start": 323,
"end": 2782
} | class ____:
"""This describes the information of a task running block transform."""
# The index of task. Each task has a unique task index within the same
# operator.
task_idx: int
# Name of the operator that this task belongs to.
op_name: str
# The dictionary of sub progress bar to updat... | TaskContext |
python | openai__gym | tests/wrappers/test_filter_observation.py | {
"start": 168,
"end": 1533
} | class ____(gym.Env):
def __init__(
self, render_mode=None, observation_keys: Tuple[str, ...] = ("state",)
):
self.observation_space = spaces.Dict(
{
name: spaces.Box(shape=(2,), low=-1, high=1, dtype=np.float32)
for name in observation_keys
... | FakeEnvironment |
python | google__jax | jax/_src/test_util.py | {
"start": 20620,
"end": 25417
} | class ____:
"""A mixin with methods allowing to skip arch specific tests."""
def skip_unless_sm90a(self):
if not is_cuda_compute_capability_equal("9.0"):
self.skipTest("Only works on GPU with capability sm90a") # pytype: disable=attribute-error
def skip_unless_sm100a(self):
if not is_cuda_compute... | CudaArchSpecificTest |
python | mwaskom__seaborn | seaborn/_marks/area.py | {
"start": 356,
"end": 2527
} | class ____:
def _plot(self, split_gen, scales, orient):
patches = defaultdict(list)
for keys, data, ax in split_gen():
kws = {}
data = self._standardize_coordinate_parameters(data, orient)
resolved = resolve_properties(self, keys, scales)
verts = s... | AreaBase |
python | pytorch__pytorch | test/distributed/checkpoint/test_planner.py | {
"start": 2890,
"end": 20617
} | class ____(TestCase):
@with_fake_comms(rank=1, world_size=4)
def test_local_plan(self):
tensor = torch.rand(10)
val = [1, 2, 3]
st = create_sharded_tensor(rank=1, world_size=4, shards_per_rank=1)
state_dict = {"tensor": tensor, "value": val, "st": st}
plan = create_defaul... | TestSavePlan |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context_creation_job.py | {
"start": 3508,
"end": 5727
} | class ____(NamedTuple):
job: IJob
resolved_run_config: ResolvedRunConfig
dagster_run: DagsterRun
executor_def: ExecutorDefinition
instance: DagsterInstance
resource_keys_to_init: AbstractSet[str]
execution_plan: ExecutionPlan
@property
def job_def(self) -> JobDefinition:
ret... | ContextCreationData |
python | plotly__plotly.py | plotly/graph_objs/scatterpolar/marker/_gradient.py | {
"start": 233,
"end": 4917
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolar.marker"
_path_str = "scatterpolar.marker.gradient"
_valid_props = {"color", "colorsrc", "type", "typesrc"}
@property
def color(self):
"""
Sets the final color of the gradient fill: the center color for
rad... | Gradient |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_connections.py | {
"start": 33957,
"end": 36589
} | class ____(TestConnectionEndpoint):
def setup_method(self):
try:
metadata("apache-airflow-providers-sqlite")
except PackageNotFoundError:
pytest.skip("The SQlite distribution package is not installed.")
@mock.patch.dict(os.environ, {"AIRFLOW__CORE__TEST_CONNECTION": "Ena... | TestConnection |
python | ray-project__ray | python/ray/serve/_private/router.py | {
"start": 20301,
"end": 20846
} | class ____(ABC):
@abstractmethod
def running_replicas_populated(self) -> bool:
pass
@abstractmethod
def assign_request(
self,
request_meta: RequestMetadata,
*request_args,
**request_kwargs,
) -> concurrent.futures.Future[ReplicaResult]:
pass
@abs... | Router |
python | langchain-ai__langchain | libs/core/langchain_core/_api/deprecation.py | {
"start": 711,
"end": 840
} | class ____(DeprecationWarning):
"""A class for issuing deprecation warnings for LangChain users."""
| LangChainDeprecationWarning |
python | getsentry__sentry | src/sentry/web/forms/fields.py | {
"start": 1825,
"end": 2128
} | class ____(Widget):
def render(self, name, value, attrs=None, renderer=None):
final_attrs = self.build_attrs(attrs)
if not value:
value = mark_safe("<em>%s</em>" % _("Not set"))
return format_html("<div{0}>{1}</div>", flatatt(final_attrs), value)
| ReadOnlyTextWidget |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/interfaces.py | {
"start": 13333,
"end": 14881
} | class ____(_DCAttributeOptions):
__slots__ = ()
_default_scalar_value: Any
_disable_dataclass_default_factory: bool = False
def _get_dataclass_setup_options(
self,
decl_scan: _ClassScanAbstractConfig,
key: str,
dataclass_setup_arguments: _DataclassArguments,
en... | _DataclassDefaultsDontSet |
python | automl__auto-sklearn | autosklearn/ensemble_building/builder.py | {
"start": 1144,
"end": 41032
} | class ____:
"""Builds ensembles out of runs that exist in the Backend
This is used by EnsembleBuilderManager and created in a dask-client
every time a run finishes and there is currently no EnsembleBuilder active.
"""
def __init__(
self,
backend: Backend,
dataset_name: str,... | EnsembleBuilder |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 65848,
"end": 66098
} | class ____(BaseModel):
"""
Asset event collection response.
"""
asset_events: Annotated[list[AssetEventResponse], Field(title="Asset Events")]
total_entries: Annotated[int, Field(title="Total Entries")]
| AssetEventCollectionResponse |
python | celery__celery | examples/stamping/visitors.py | {
"start": 160,
"end": 385
} | class ____(StampingVisitor):
def on_signature(self, sig: Signature, **headers) -> dict:
logger.critical(f"Visitor: Sig '{sig}' is stamped with: mystamp")
return {"mystamp": "I am a stamp!"}
| MyStampingVisitor |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/base_env.py | {
"start": 6235,
"end": 6944
} | class ____(NamedTuple):
"""
Contains the data a single Agent collected when its episode ended.
- obs is a list of numpy arrays observations collected by the agent.
- reward is a float. Corresponds to the rewards collected by the agent
since the last simulation step.
- interrupted is a bool. ... | TerminalStep |
python | mahmoud__boltons | boltons/fileutils.py | {
"start": 22396,
"end": 25486
} | class ____:
# TODO: raise ValueErrors on closed for all methods?
# TODO: enforce read/write
def __init__(self, path, mode='r', buffering=None):
self.name = path
self.mode = mode
self.closed = False
self.errors = None
self.isatty = False
self.encoding = None
... | DummyFile |
python | dagster-io__dagster | python_modules/dagster/dagster/components/lib/shim_components/asset_check.py | {
"start": 342,
"end": 458
} | class ____(BaseModel):
"""Parameters for the AssetCheckScaffolder."""
asset_key: str
| AssetCheckScaffoldParams |
python | EpistasisLab__tpot | tpot/builtin_modules/arithmetictransformer.py | {
"start": 1726,
"end": 5415
} | class ____(TransformerMixin, BaseEstimator):
#functions = ["add", "mul_neg_1", "mul", "safe_reciprocal", "eq","ne","ge","gt","le","lt", "min","max","0","1"]
def __init__(self, function,):
"""
A transformer that applies a function to the input array along axis 1.
Parameters
-----... | ArithmeticTransformer |
python | django__django | django/contrib/gis/gdal/datasource.py | {
"start": 1639,
"end": 4603
} | class ____(GDALBase):
"Wraps an OGR Data Source object."
destructor = capi.destroy_ds
def __init__(self, ds_input, ds_driver=False, write=False, encoding="utf-8"):
# The write flag.
self._write = capi.GDAL_OF_UPDATE if write else capi.GDAL_OF_READONLY
# See also https://gdal.org/de... | DataSource |
python | huggingface__transformers | src/transformers/models/instructblipvideo/modular_instructblipvideo.py | {
"start": 6543,
"end": 6655
} | class ____(InstructBlipPreTrainedModel):
input_modalities = ("video", "text")
| InstructBlipVideoPreTrainedModel |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/structure.py | {
"start": 1542,
"end": 1669
} | class ____(BaseGraphResponse[EdgeResponse, NodeResponse]):
"""Structure Data serializer for responses."""
| StructureDataResponse |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 21807,
"end": 22176
} | class ____:
def setup(self):
self.df = DataFrame(np.random.randn(100000, 2), columns=list("AB"))
self.df2 = self.df.copy()
self.df2["A"] = self.df2["A"].astype("object")
def time_memory_usage(self):
self.df.memory_usage(deep=True)
def time_memory_usage_object_dtype(self):
... | MemoryUsage |
python | PyCQA__pylint | tests/functional/n/no/no_member_assign_same_line.py | {
"start": 280,
"end": 463
} | class ____:
"""This class attempts to assign and access a member in the same line."""
def __init__(self):
self.member = self.member # [no-member]
| AssignMemberInSameLine |
python | wandb__wandb | wandb/apis/public/reports.py | {
"start": 413,
"end": 4302
} | class ____(SizedPaginator["BetaReport"]):
"""Reports is a lazy iterator of `BetaReport` objects.
Args:
client (`wandb.apis.internal.Api`): The API client instance to use.
project (`wandb.sdk.internal.Project`): The project to fetch reports from.
name (str, optional): The name of the rep... | Reports |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 30286,
"end": 31008
} | class ____(themeable):
"""
x-axis line
Parameters
----------
theme_element : element_line
"""
position = "bottom"
_omit = ["solid_capstyle"]
def apply_ax(self, ax: Axes):
super().apply_ax(ax)
properties = self.properties
# MPL has a default zorder of 2.5 fo... | axis_line_x |
python | pypa__warehouse | warehouse/packaging/services.py | {
"start": 5864,
"end": 7211
} | class ____(GenericBlobStorage):
def get(self, path: str):
path = self._get_path(path)
try:
file_obj = io.BytesIO()
downloaded_file = self.bucket.download_file_by_name(path)
downloaded_file.save(file_obj)
file_obj.seek(0)
return file_obj
... | GenericB2BlobStorage |
python | networkx__networkx | networkx/algorithms/tests/test_distance_measures.py | {
"start": 417,
"end": 6154
} | class ____:
def setup_method(self):
self.G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
@pytest.mark.parametrize("seed", list(range(10)))
@pytest.mark.parametrize("n", list(range(10, 20)))
@pytest.mark.parametrize("prob", [x / 10 for x in range(0, 10, 2)])
def test_use_... | TestDistance |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_data_forwarding.py | {
"start": 283,
"end": 889
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-forwarding"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def get_response(self, *args, **kwargs):
"""
Override get_response to always add the required feature flag.
"""
... | DataForwardingIndexEndpointTest |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_eth_address_positive_balance.py | {
"start": 1061,
"end": 2097
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_eth_address_positive_balance"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngin... | ColumnValuesEthAddressPositiveBalance |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 57005,
"end": 57091
} | class ____(_TestNormBase, TestCase):
dt = np.double
dec = 12
| _TestNormDoubleBase |
python | ethereum__web3.py | web3/providers/persistent/request_processor.py | {
"start": 1081,
"end": 13647
} | class ____:
_subscription_queue_synced_with_ws_stream: bool = False
# set by the subscription manager when it is initialized
_subscription_container: SubscriptionContainer | None = None
def __init__(
self,
provider: "PersistentConnectionProvider",
subscription_response_queue_si... | RequestProcessor |
python | boto__boto3 | boto3/dynamodb/conditions.py | {
"start": 5067,
"end": 5138
} | class ____(ComparisonCondition):
expression_operator = '<>'
| NotEquals |
python | spyder-ide__spyder | spyder/plugins/editor/api/run.py | {
"start": 364,
"end": 792
} | class ____(TypedDict):
"""Editor supported run configuration schema."""
# Name of the plugin that is extending the editor supported run
# configurations
origin: str
# Filename extension for which the editor should be able to provide
# run configurations.
extension: str
# List of conte... | EditorRunConfiguration |
python | keras-team__keras | keras/src/ops/linalg.py | {
"start": 299,
"end": 1524
} | class ____(Operation):
def __init__(self, upper=False, *, name=None):
super().__init__(name=name)
self.upper = upper
def call(self, x):
return _cholesky(x, self.upper)
def compute_output_spec(self, x):
_assert_2d(x)
_assert_square(x)
return KerasTensor(x.sha... | Cholesky |
python | getsentry__sentry | tests/sentry/manager/test_team_manager.py | {
"start": 142,
"end": 2085
} | class ____(TestCase):
def test_simple(self) -> None:
user = self.create_user()
org = self.create_organization()
team = self.create_team(organization=org, name="Test")
self.create_member(organization=org, user=user, teams=[team])
result = Team.objects.get_for_user(organizatio... | TeamManagerTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/bulk_persistence.py | {
"start": 12855,
"end": 21890
} | class ____(_AbstractORMCompileState):
is_dml_returning = True
from_statement_ctx: Optional[_ORMFromStatementCompileState] = None
@classmethod
def _get_orm_crud_kv_pairs(
cls, mapper, statement, kv_iterator, needs_to_be_cacheable
):
core_get_crud_kv_pairs = UpdateDMLState._get_crud_k... | _ORMDMLState |
python | getsentry__sentry | src/sentry/utils/rust.py | {
"start": 6244,
"end": 6596
} | class ____(Integration):
identifier = "rust_info"
@staticmethod
def setup_once():
@add_global_event_processor
def processor(event, hint):
if sentry_sdk.get_client().get_integration(RustInfoIntegration) is None:
return event
return merge_rust_info_fra... | RustInfoIntegration |
python | pytorch__pytorch | torch/distributed/elastic/utils/data/elastic_distributed_sampler.py | {
"start": 493,
"end": 3056
} | class ____(DistributedSampler[T]):
"""
Sampler that restricts data loading to a subset of
the dataset for elastic training.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
process can pass a DistributedSampler instance as a Data... | ElasticDistributedSampler |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 27156,
"end": 28870
} | class ____(BinaryExpression[Any]):
_traverse_internals = [
("sql_function", InternalTraversal.dp_clauseelement),
("left_index", InternalTraversal.dp_plain_obj),
("right_index", InternalTraversal.dp_plain_obj),
("modifiers", InternalTraversal.dp_plain_dict),
]
sql_function: F... | FunctionAsBinary |
python | celery__celery | t/unit/events/test_state.py | {
"start": 7911,
"end": 10427
} | class ____:
def test_equality(self):
assert Task(uuid='foo').uuid == 'foo'
assert Task(uuid='foo') == Task(uuid='foo')
assert Task(uuid='foo') != Task(uuid='bar')
assert hash(Task(uuid='foo')) == hash(Task(uuid='foo'))
assert hash(Task(uuid='foo')) != hash(Task(uuid='bar'))
... | test_Task |
python | tornadoweb__tornado | tornado/test/auth_test.py | {
"start": 787,
"end": 1385
} | class ____(RequestHandler, OpenIdMixin):
def initialize(self, test):
self._OPENID_ENDPOINT = test.get_url("/openid/server/authenticate")
@gen.coroutine
def get(self):
if self.get_argument("openid.mode", None):
user = yield self.get_authenticated_user(
http_client... | OpenIdClientLoginHandler |
python | scipy__scipy | scipy/interpolate/tests/test_bsplines.py | {
"start": 27311,
"end": 36347
} | class ____:
@pytest.mark.parametrize('xval', [0.0, 1.0, 2.5, 4, 6.5, 7.0])
def test_insert(self, xval, xp):
# insert a knot, incl edges (0.0, 7.0) and exactly at an existing knot (4.0)
x = xp.arange(8, dtype=xp.float64)
y = xp.sin(x)**3
spl = make_interp_spline(x, y, k=3)
... | TestInsert |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/check_ops_test.py | {
"start": 76542,
"end": 84666
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_assert_shapes_sparse_tensor_scalar_target_success(self):
sparse_float = sparse_tensor.SparseTensor(
constant_op.constant([[]], dtypes.int64),
constant_op.constant([42], dtypes.float32),
constant_op.constant([], ... | AssertShapesSparseTensorTest |
python | kamyu104__LeetCode-Solutions | Python/repeated-substring-pattern.py | {
"start": 29,
"end": 898
} | class ____(object):
def repeatedSubstringPattern(self, str):
"""
:type str: str
:rtype: bool
"""
def getPrefix(pattern):
prefix = [-1] * len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j > -1 and pattern[j + 1] !... | Solution |
python | Netflix__metaflow | test/core/tests/resume_succeeded_step.py | {
"start": 67,
"end": 1646
} | class ____(MetaflowTest):
"""
Resuming from the succeeded end step should work
"""
RESUME = True
# resuming on a successful step.
RESUME_STEP = "a"
PRIORITY = 3
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
... | ResumeSucceededStepTest |
python | wandb__wandb | wandb/sdk/lib/redirect.py | {
"start": 2314,
"end": 3846
} | class ____:
"""Class encapsulating a single character, its foreground, background and style attributes."""
__slots__ = (
"data",
"fg",
"bg",
"bold",
"italics",
"underscore",
"blink",
"strikethrough",
"reverse",
)
def __init__(
... | Char |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_exceptions.py | {
"start": 2673,
"end": 68408
} | class ____(__TestCase):
def raise_catch(self, exc, excname):
with self.subTest(exc=exc, excname=excname):
try:
raise exc("spam")
except exc as err:
buf1 = str(err)
try:
raise exc("spam")
except exc as err:
... | ExceptionTests |
python | pytorch__pytorch | test/distributed/test_c10d_gloo.py | {
"start": 102129,
"end": 103090
} | class ____(test_c10d_common.AbstractLargeCommTest, MultiProcessTestCase):
def setUp(self):
super().setUp()
self._spawn_processes()
def tearDown(self):
super().tearDown()
try:
os.remove(self.file_name)
except OSError:
pass
@property
def de... | LargeCommTest |
python | huggingface__transformers | examples/pytorch/image-classification/run_image_classification.py | {
"start": 2258,
"end": 4497
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify
them on the command line.
"""
dataset_name: Optional[str] = field(
default=None,
... | DataTrainingArguments |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 2363,
"end": 3166
} | class ____(_WeaviateInput):
"""Define which metadata should be returned in the query's results."""
creation_time: bool = Field(default=False)
last_update_time: bool = Field(default=False)
distance: bool = Field(default=False)
certainty: bool = Field(default=False)
score: bool = Field(default=Fa... | MetadataQuery |
python | mitmproxy__pdoc | test/testdata/flavors_google.py | {
"start": 12587,
"end": 14188
} | class ____:
"""Summary of class here.
Longer class information....
Longer class information....
Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam=False):
"""Inits Samp... | SampleClass |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 81102,
"end": 95780
} | class ____(TestCase):
def setUp(self):
self.model = PollWithManyToMany
self.history_model = self.model.history.model
self.place = Place.objects.create(name="Home")
self.poll = PollWithManyToMany.objects.create(
question="what's up?", pub_date=today
)
def asse... | ManyToManyTest |
python | kamyu104__LeetCode-Solutions | Python/number-of-possible-sets-of-closing-branches.py | {
"start": 1408,
"end": 2675
} | class ____(object):
def numberOfSets(self, n, maxDistance, roads):
"""
:type n: int
:type maxDistance: int
:type roads: List[List[int]]
:rtype: int
"""
def check(mask, dist):
return all(dist[i][j] <= maxDistance for i in xrange(n) if mask&(1<<i) fo... | Solution2 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 570492,
"end": 572365
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"content",
"created_at",
"reactors",
"subject",
"users",
"viewer_has_reacted",
)
content = sgqlc.types.Field(
sgqlc.ty... | ReactionGroup |
python | numpy__numpy | numpy/typing/tests/data/pass/shape.py | {
"start": 86,
"end": 439
} | class ____(NamedTuple):
x_axis: int
y_axis: int
# Test variance of _ShapeT_co
def accepts_2d(a: np.ndarray[tuple[int, int], Any]) -> None:
return None
accepts_2d(np.empty(XYGrid(2, 2)))
accepts_2d(np.zeros(XYGrid(2, 2), dtype=int))
accepts_2d(np.ones(XYGrid(2, 2), dtype=int))
accepts_2d(np.full(XYGrid(2,... | XYGrid |
python | tensorflow__tensorflow | tensorflow/python/tpu/client/client.py | {
"start": 3555,
"end": 14785
} | class ____:
"""Client for working with the Cloud TPU API.
This client is intended to be used for resolving tpu name to ip addresses.
It's recommended to use this library as a contextlib to utilize all
functionality.
"""
def __init__(self,
tpu=None,
zone=None,
... | Client |
python | spack__spack | lib/spack/spack/vendor/attr/_make.py | {
"start": 88356,
"end": 91629
} | class ____:
"""
Intermediate representation of attributes that uses a counter to preserve
the order in which the attributes have been defined.
*Internal* data structure of the attrs library. Running into is most
likely the result of a bug like a forgotten `@attr.s` decorator.
"""
__slots_... | _CountingAttr |
python | getsentry__sentry | src/sentry/interfaces/geo.py | {
"start": 67,
"end": 555
} | class ____(Interface):
"""
The (approximate) geographical location of the end user.
>>> {
>>> 'country_code': 'US',
>>> 'city': 'San Francisco',
>>> 'region': 'CA',
>>> }
"""
@classmethod
def to_python(cls, data, **kwargs):
data = {
"country_code... | Geo |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/source.py | {
"start": 1859,
"end": 2078
} | class ____(TokenAuthenticator):
def __init__(self, token: str):
token = base64.b64encode(token.encode("utf8")).decode("utf8")
super().__init__(token=token, auth_method="Basic")
| TokenAuthenticatorBase64 |
python | kamyu104__LeetCode-Solutions | Python/compute-decimal-representation.py | {
"start": 39,
"end": 387
} | class ____(object):
def decimalRepresentation(self, n):
"""
:type n: int
:rtype: List[int]
"""
result = []
base = 1
while n:
n, r = divmod(n, 10)
if r:
result.append(r*base)
base *= 10
result.reverse(... | Solution |
python | GoogleCloudPlatform__python-docs-samples | compute/client_library/snippets/instances/custom_machine_types/helper_class.py | {
"start": 989,
"end": 8320
} | class ____:
"""
Allows to create custom machine types to be used with the VM instances.
"""
@unique
class CPUSeries(Enum):
N1 = "custom"
N2 = "n2-custom"
N2D = "n2d-custom"
E2 = "e2-custom"
E2_MICRO = "e2-custom-micro"
E2_SMALL = "e2-custom-small"
... | CustomMachineType |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 4836,
"end": 5008
} | class ____(ValueError):
"""Raised when a webhook signature is invalid, meaning the computed signature does not match the expected signature."""
| InvalidWebhookSignatureError |
python | scrapy__scrapy | tests/test_squeues.py | {
"start": 3770,
"end": 3856
} | class ____(PickleFifoDiskQueueTest):
chunksize = 1
| ChunkSize1PickleFifoDiskQueueTest |
python | patrick-kidger__equinox | equinox/_module/_module.py | {
"start": 1357,
"end": 1721
} | class ____(eqx.Module):
foo: Callable
def __init__(self):
self.foo = self.bar
def bar(self):
...
```
this is because Equinox modules are PyTrees -- but the above does not have a tree
structure! `self.foo.__self__` is a cycle that brings us back to `self`.
In the above example, you probabl... | MyModule |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py | {
"start": 24885,
"end": 27286
} | class ____(GradientCheckpointingLayer):
"""Conformer block based on https://huggingface.co/papers/2005.08100."""
def __init__(self, config):
super().__init__()
embed_dim = config.hidden_size
dropout = config.attention_dropout
# Feed-forward 1
self.ffn1_layer_norm = nn.L... | Wav2Vec2ConformerEncoderLayer |
python | MongoEngine__mongoengine | mongoengine/base/datastructures.py | {
"start": 12347,
"end": 14563
} | class ____:
__slots__ = ()
_special_fields = {"get", "pop", "iteritems", "items", "keys", "create"}
_classes = {}
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
def __getitem__(self, key):
key = "_reserved_" + key if key in self._special_f... | StrictDict |
python | pennersr__django-allauth | allauth/idp/oidc/models.py | {
"start": 6185,
"end": 6572
} | class ____(models.query.QuerySet):
def valid(self):
return self.filter(
Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now())
)
def by_value(self, value: str):
return self.filter(hash=get_adapter().hash_token(value))
def lookup(self, type, value):
return... | TokenQuerySet |
python | getsentry__sentry | tests/sentry/codecov/endpoints/test_repositories.py | {
"start": 1654,
"end": 7526
} | class ____(APITestCase):
endpoint_name = "sentry-api-0-repositories"
def setUp(self) -> None:
super().setUp()
self.organization = self.create_organization(owner=self.user)
self.integration = self.create_integration(
organization=self.organization,
external_id="12... | RepositoriesEndpointTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_selection01.py | {
"start": 315,
"end": 807
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("selection01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py30.py | {
"start": 1898,
"end": 1988
} | class ____(metaclass=int):
""" int is not a proper metaclass, but it is defined. """
| Good |
python | kamyu104__LeetCode-Solutions | Python/minimum-rounds-to-complete-all-tasks.py | {
"start": 69,
"end": 337
} | class ____(object):
def minimumRounds(self, tasks):
"""
:type tasks: List[int]
:rtype: int
"""
cnt = collections.Counter(tasks)
return sum((x+2)//3 for x in cnt.itervalues()) if 1 not in cnt.itervalues() else -1
| Solution |
python | pytest-dev__pytest | testing/test_pastebin.py | {
"start": 2702,
"end": 6547
} | class ____:
@pytest.fixture
def pastebin(self, request):
return request.config.pluginmanager.getplugin("pastebin")
@pytest.fixture
def mocked_urlopen_invalid(self, monkeypatch: MonkeyPatch):
"""Monkeypatch the actual urlopen calls done by the internal plugin
function that connec... | TestPaste |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py | {
"start": 9034,
"end": 10927
} | class ____(Exception):
"""For internal use when backend raises UnsupportedOperation"""
def __init__(self, traceback):
self.traceback = traceback
def build_sdist(sdist_directory, config_settings):
"""Invoke the mandatory build_sdist hook."""
backend = _build_backend()
try:
return ba... | GotUnsupportedOperation |
python | celery__celery | t/unit/app/test_utils.py | {
"start": 1574,
"end": 1790
} | class ____:
def test_no_conn_driver_info(self):
self.app.connection = Mock()
conn = self.app.connection.return_value = Mock()
conn.transport = None
bugreport(self.app)
| test_bugreport |
python | falconry__falcon | tests/test_headers.py | {
"start": 5447,
"end": 6239
} | class ____:
def on_get(self, req, resp):
resp.append_header('X-Things', 'thing-1')
resp.append_header('X-THINGS', 'thing-2')
resp.append_header('x-thiNgs', 'thing-3')
def on_head(self, req, resp):
resp.set_header('X-things', 'thing-1')
resp.append_header('X-THINGS', 'thi... | AppendHeaderResource |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 182825,
"end": 183727
} | class ____:
"""Used to help Cython interpret indexed types from the typing module (or similar)
"""
modifier_name = None
contains_none = False
def allows_none(self):
return (
self.modifier_name == 'typing.Optional' or
self.modifier_name == 'typing.Union' and self.cont... | PythonTypeConstructorMixin |
python | openai__openai-python | src/openai/_types.py | {
"start": 5931,
"end": 6190
} | class ____(Protocol):
"""Represents a type that has inherited from `Generic`
The `__orig_bases__` property can be used to determine the resolved
type variable for a given base class.
"""
__orig_bases__: tuple[_GenericAlias]
| InheritsGeneric |
python | getsentry__sentry | src/sentry/relocation/utils.py | {
"start": 9347,
"end": 12092
} | class ____(ExportCheckpointer):
"""
An export checkpointer that uses GCP cloud storage to store encrypted checkpoints for every
model we export for a SAAS_TO_SAAS relocation.
"""
def __init__(
self,
*,
crypto: EncryptorDecryptorPair,
uuid: UUID,
storage: Stor... | StorageBackedCheckpointExporter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.