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 | pennersr__django-allauth | tests/mocking.py | {
"start": 89,
"end": 739
} | class ____:
def __init__(self, status_code, content, headers=None):
if headers is None:
headers = {}
self.status_code = status_code
if isinstance(content, dict):
content = json.dumps(content)
headers["content-type"] = "application/json"
self.conte... | MockedResponse |
python | pennersr__django-allauth | allauth/socialaccount/providers/bitly/provider.py | {
"start": 436,
"end": 809
} | class ____(OAuth2Provider):
id = "bitly"
name = "Bitly"
account_class = BitlyAccount
oauth2_adapter_class = BitlyOAuth2Adapter
def extract_uid(self, data):
return str(data["login"])
def extract_common_fields(self, data):
return dict(username=data["login"], name=data.get("full_n... | BitlyProvider |
python | spack__spack | lib/spack/spack/builder.py | {
"start": 19430,
"end": 24096
} | class ____(BaseBuilder, collections.abc.Sequence):
"""A builder is a class that, given a package object (i.e. associated with concrete spec),
knows how to install it.
The builder behaves like a sequence, and when iterated over return the ``phases`` of the
installation in the correct order.
"""
... | Builder |
python | huggingface__transformers | src/transformers/models/mistral3/modular_mistral3.py | {
"start": 4215,
"end": 4279
} | class ____(LlavaPreTrainedModel):
pass
| Mistral3PreTrainedModel |
python | getsentry__sentry | src/sentry/testutils/helpers/apigateway.py | {
"start": 1009,
"end": 1334
} | class ____(OrganizationEndpoint):
permission_classes: tuple[type[BasePermission], ...] = (AllowAny,)
def get(self, request, organization):
return Response({"proxy": False})
def post(self, request, organization):
return HttpResponseRedirect("https://zombo.com")
@region_silo_endpoint
| RegionEndpoint |
python | kamyu104__LeetCode-Solutions | Python/taking-maximum-energy-from-the-mystic-dungeon.py | {
"start": 37,
"end": 492
} | class ____(object):
def maximumEnergy(self, energy, k):
"""
:type energy: List[int]
:type k: int
:rtype: int
"""
result = float("-inf")
for i in xrange(k):
curr = 0
for j in reversed(xrange(((len(energy)-i)-1)%k, len(energy)-i, k)): # ... | Solution |
python | getsentry__sentry | src/sentry/codecov/endpoints/repositories/serializers.py | {
"start": 505,
"end": 2421
} | class ____(serializers.Serializer):
"""
Serializer for repositories response
"""
results = RepositoryNodeSerializer(many=True)
pageInfo = PageInfoSerializer()
totalCount = serializers.IntegerField()
def to_representation(self, graphql_response):
"""
Transform the GraphQL re... | RepositoriesSerializer |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 834098,
"end": 834593
} | class ____(mupdf.PdfFilterOptions2):
def __init__(self):
super().__init__()
self.use_virtual_image_filter()
def image_filter( self, ctx, ctm, name, image):
assert isinstance(ctm, mupdf.fz_matrix)
JM_image_filter(self, mupdf.FzMatrix(ctm), name, image)
if mupdf_cppyy:
... | JM_image_reporter_Filter |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 11170,
"end": 11237
} | class ____(HTTPServerError):
status_code = 501
| HTTPNotImplemented |
python | spyder-ide__spyder | spyder/plugins/editor/extensions/docstring.py | {
"start": 29586,
"end": 38117
} | class ____(object):
"""Parse function definition text."""
def __init__(self):
"""."""
self.has_info = False
self.func_text = ''
self.args_text = ''
self.func_indent = ''
self.arg_name_list = []
self.arg_type_list = []
self.arg_value_list = []
... | FunctionInfo |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 45626,
"end": 45926
} | class ____(TestErrorInApplication):
def application(self, env, start_response):
self.error = greentest.ExpectedException('TestError_after_start_response.application')
start_response('200 OK', [('Content-Type', 'text/plain')])
raise self.error
| TestError_after_start_response |
python | pydata__xarray | xarray/core/dtypes.py | {
"start": 379,
"end": 556
} | class ____:
def __gt__(self, other):
return True
def __eq__(self, other):
return isinstance(other, type(self))
@functools.total_ordering
| AlwaysGreaterThan |
python | sphinx-doc__sphinx | sphinx/ext/autodoc/_dynamic/_preserve_defaults.py | {
"start": 505,
"end": 5458
} | class ____:
def __init__(self, name: str) -> None:
self.name = name
def __repr__(self) -> str:
return self.name
def _get_arguments(obj: Any, /) -> ast.arguments | None:
"""Parse 'ast.arguments' from an object.
This tries to parse the original code for an object and returns
an 'as... | DefaultValue |
python | ray-project__ray | rllib/connectors/env_to_module/prev_actions_prev_rewards.py | {
"start": 513,
"end": 6813
} | class ____(ConnectorV2):
"""A connector piece that adds previous rewards and actions to the input obs.
- Requires Columns.OBS to be already a part of the batch.
- This connector makes the assumption that under the Columns.OBS key in batch,
there is either a list of individual env observations to be fla... | PrevActionsPrevRewards |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 5102,
"end": 5218
} | class ____(models.Model):
articles = models.ManyToManyField(ModelArticle, related_name="orderline")
| ModelOrderLine |
python | pypa__pip | src/pip/_vendor/rich/errors.py | {
"start": 271,
"end": 344
} | class ____(ConsoleError):
"""Style stack is invalid."""
| StyleStackError |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 41259,
"end": 41991
} | class ____:
"""Test fi_FI address provider methods"""
def test_city(self, faker, num_samples):
for _ in range(num_samples):
city = faker.city()
assert isinstance(city, str)
assert city in FiFiAddressProvider.cities
def test_street_suffix(self, faker, num_samples... | TestFiFi |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 17911,
"end": 17960
} | class ____(RootModel[Any]):
root: Any
| JsonValue |
python | docker__docker-py | tests/integration/api_client_test.py | {
"start": 478,
"end": 912
} | class ____(unittest.TestCase):
def test_client_init(self):
client = docker.APIClient(version='auto', **kwargs_from_env())
client_version = client._version
api_version = client.version(api_version=False)['ApiVersion']
assert client_version == api_version
api_version_2 = client... | AutoDetectVersionTest |
python | django__django | tests/test_client_regress/models.py | {
"start": 104,
"end": 357
} | class ____(AbstractBaseUser):
email = models.EmailField(verbose_name="email address", max_length=255, unique=True)
custom_objects = BaseUserManager()
USERNAME_FIELD = "email"
class Meta:
app_label = "test_client_regress"
| CustomUser |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/legacy/legacy_context.py | {
"start": 2033,
"end": 18188
} | class ____:
"""Context object containing methods and properties used for evaluating the entire state of an
asset's automation rules.
"""
asset_key: AssetKey
condition: "AutomationCondition"
cursor: Optional[AutomationConditionCursor]
node_cursor: Optional[AutomationConditionNodeCursor]
... | LegacyRuleEvaluationContext |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 64395,
"end": 64774
} | class ____:
def test_basic(self, xp):
b = xp.asarray([1])
a = xp.asarray([1, 1])
b_bs, a_bs = lp2bs(b, a, 0.41722257286366754, 0.18460575326152251)
assert_array_almost_equal(b_bs, xp.asarray([1, 0, 0.17407]), decimal=5)
assert_array_almost_equal(a_bs, xp.asarray([1, 0.18461,... | TestLp2bs |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 9738,
"end": 10364
} | class ____(nn.Module):
def __init__(self, config: MobileViTConfig, hidden_size: int, intermediate_size: int) -> None:
super().__init__()
self.dense = nn.Linear(hidden_size, intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_a... | MobileViTIntermediate |
python | modin-project__modin | modin/core/storage_formats/pandas/parsers.py | {
"start": 14808,
"end": 22672
} | class ____(PandasParser):
@classmethod
def get_sheet_data(cls, sheet, convert_float):
"""
Get raw data from the excel sheet.
Parameters
----------
sheet : openpyxl.worksheet.worksheet.Worksheet
Sheet to get data from.
convert_float : bool
... | PandasExcelParser |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 25865,
"end": 26082
} | class ____(torch.utils.data.Dataset):
def __init__(self, len):
self.len = len
def __len__(self):
return self.len
def __getitem__(self, any):
return torch.empty(0)
| EmptyTensorDataset |
python | kamyu104__LeetCode-Solutions | Python/minimum-moves-to-capture-the-queen.py | {
"start": 36,
"end": 630
} | class ____(object):
def minMovesToCaptureTheQueen(self, a, b, c, d, e, f):
"""
:type a: int
:type b: int
:type c: int
:type d: int
:type e: int
:type f: int
:rtype: int
"""
if a == e and not (a == c and (b-d)*(f-d) < 0):
ret... | Solution |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_process.py | {
"start": 105022,
"end": 105899
} | class ____(RelocationTaskTestCase):
def setUp(self) -> None:
RelocationTaskTestCase.setUp(self)
TransactionTestCase.setUp(self)
self.relocation.step = Relocation.Step.NOTIFYING.value
self.relocation.latest_task = OrderedTask.NOTIFYING_OWNER.name
self.relocation.save()
de... | CompletedTest |
python | doocs__leetcode | solution/3100-3199/3112.Minimum Time to Visit Disappearing Nodes/Solution.py | {
"start": 0,
"end": 680
} | class ____:
def minimumTime(
self, n: int, edges: List[List[int]], disappear: List[int]
) -> List[int]:
g = defaultdict(list)
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
dist = [inf] * n
dist[0] = 0
pq = [(0, 0)]
w... | Solution |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 6894,
"end": 7240
} | class ____(ConcreteTemplate):
cases = [signature(types.float64, op1, op2)
for op1, op2 in itertools.product(machine_ints, machine_ints)]
cases += [signature(op, op, op) for op in sorted(types.real_domain)]
cases += [signature(op, op, op) for op in sorted(types.complex_domain)]
@infer_global(o... | BinOpTrueDiv |
python | PyCQA__pylint | tests/functional/s/singledispatch/singledispatchmethod_function.py | {
"start": 721,
"end": 1113
} | class ____:
@singledispatchmethod
def convert_position(self, position):
pass
@convert_position.register
def _(self, position: str) -> tuple:
position_a, position_b = position.split(",")
return (int(position_a), int(position_b))
@convert_position.register
def _(self, pos... | Board1 |
python | numpy__numpy | benchmarks/benchmarks/bench_shape_base.py | {
"start": 1938,
"end": 2536
} | class ____(Benchmark):
params = [[(16, 16), (64, 64), (256, 256), (1024, 1024)],
['uint8', 'uint16', 'uint32', 'uint64'],
[(2, 2), (4, 4)]]
param_names = ['shape', 'dtype', 'n_chunks']
def setup(self, shape, dtype, n_chunks):
self.block_list = [
[np.full(sh... | Block2D |
python | kamyu104__LeetCode-Solutions | Python/number-of-pairs-of-interchangeable-rectangles.py | {
"start": 67,
"end": 464
} | class ____(object):
def interchangeableRectangles(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: int
"""
count = collections.defaultdict(int)
for w, h in rectangles:
g = fractions.gcd(w, h) # Time: O(logx) ~= O(1)
count[(w//g... | Solution |
python | PyCQA__pylint | doc/data/messages/c/catching-non-exception/good.py | {
"start": 0,
"end": 79
} | class ____(Exception):
pass
try:
1 / 0
except FooError:
pass
| FooError |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/choice.py | {
"start": 1921,
"end": 2141
} | class ____:
type: Literal["simplest"]
count: int | None
def __post_init__(self) -> None:
if self.count is not None:
assert self.count > 0
@dataclass(slots=True, frozen=False)
| ChoiceTemplate |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 15318,
"end": 17037
} | class ____(DistanceResultMixin, OracleToleranceMixin, GeoFunc):
def __init__(self, expr1, spheroid=True, **extra):
self.spheroid = spheroid
super().__init__(expr1, **extra)
def as_sql(self, compiler, connection, **extra_context):
if (
self.geo_field.geodetic(connection)
... | Length |
python | google__pytype | pytype/attribute_test.py | {
"start": 4925,
"end": 8028
} | class ____(test_base.UnitTest):
def setUp(self):
super().setUp()
options = config.Options.create(python_version=self.python_version)
self._ctx = test_utils.make_context(options)
def test_type_parameter_instance(self):
t = abstract.TypeParameter(abstract_utils.T, self._ctx)
t_instance = abstrac... | AttributeTest |
python | huggingface__transformers | src/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py | {
"start": 777,
"end": 6375
} | class ____(PreTrainedConfig):
"""
This is the configuration class to store the configuration of a [`GPTBigCodeModel`]. It is used to instantiate a
GPTBigCode model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar ... | GPTBigCodeConfig |
python | ray-project__ray | doc/source/serve/doc_code/whisper_example.py | {
"start": 1239,
"end": 2736
} | class ____:
def __init__(self, model_size="large-v2"):
# Load model
from faster_whisper import WhisperModel
# Run on GPU with FP16
self.model = WhisperModel(model_size, device="cuda", compute_type="float16")
async def transcribe(self, file_path: str):
subprocess.check_c... | WhisperModel |
python | networkx__networkx | networkx/algorithms/tests/test_regular.py | {
"start": 115,
"end": 1624
} | class ____:
@pytest.mark.parametrize("n", [3, 4, 5])
def test_k_factor_cycle(self, n):
g = nx.cycle_graph(n)
kf = nx.k_factor(g, 2)
assert g.edges == kf.edges
assert g.nodes == kf.nodes
@pytest.mark.parametrize("k", range(3))
def test_k_factor_grid(self, k):
g = ... | TestKFactor |
python | tensorflow__tensorflow | tensorflow/python/distribute/multi_worker_util_test.py | {
"start": 5183,
"end": 6888
} | class ____(test.TestCase):
def testChiefId(self):
cluster_spec = {
"chief": ["127.0.0.1:1234"],
"worker": ["127.0.0.1:8964", "127.0.0.1:2333"],
"ps": ["127.0.0.1:1926", "127.0.0.1:3141"]
}
self.assertEqual(
multi_worker_util.id_in_cluster(cluster_spec, "chief", 0), 0)
d... | IdInClusterTest |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 31113,
"end": 31938
} | class ____(_MutableListTestBase, fixtures.MappedTest):
__requires__ = ("array_type",)
@classmethod
def define_tables(cls, metadata):
from sqlalchemy.sql.sqltypes import ARRAY
MutableList = cls._type_fixture()
Base = declarative_base(metadata=metadata)
class Mixin:
... | MutableColumnCopyArrayTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-qdrant/destination_qdrant/indexer.py | {
"start": 937,
"end": 5921
} | class ____(Indexer):
config: QdrantIndexingConfigModel
def __init__(self, config: QdrantIndexingConfigModel, embedding_dimensions: int):
super().__init__(config)
self.embedding_dimensions = embedding_dimensions
def check(self) -> Optional[str]:
auth_method_mode = self.config.auth_m... | QdrantIndexer |
python | pypa__hatch | src/hatch/project/config.py | {
"start": 515,
"end": 22113
} | class ____:
def __init__(self, root, config, plugin_manager=None):
self.root = root
self.config = config
self.plugin_manager = plugin_manager
self._matrices = None
self._env = None
self._env_requires_complex = None
self._env_requires = None
self._env_... | ProjectConfig |
python | numpy__numpy | numpy/lib/_index_tricks_impl.py | {
"start": 10299,
"end": 14875
} | class ____:
"""
Translates slice objects to concatenation along an axis.
For detailed documentation on usage, see `r_`.
"""
__slots__ = ('axis', 'matrix', 'ndmin', 'trans1d')
# allow ma.mr_ to override this
concatenate = staticmethod(_nx.concatenate)
makemat = staticmethod(matrixlib.ma... | AxisConcatenator |
python | optuna__optuna | optuna/visualization/_optimization_history.py | {
"start": 787,
"end": 923
} | class ____(NamedTuple):
values: list[float]
stds: list[float] | None
label_name: str
states: list[_ValueState]
| _ValuesInfo |
python | huggingface__transformers | src/transformers/models/ovis2/processing_ovis2.py | {
"start": 966,
"end": 1145
} | class ____(ProcessingKwargs, total=False):
_defaults = {
"text_kwargs": {
"padding": False,
},
"image_kwargs": {},
}
| Ovis2ProcessorKwargs |
python | apache__airflow | devel-common/src/tests_common/test_utils/timetables.py | {
"start": 1235,
"end": 2107
} | class ____(Timetable):
"""Custom timetable for testing serialization."""
def __init__(self, value: str):
self.value = value
@classmethod
def deserialize(cls, data):
return cls(data["value"])
def __eq__(self, other) -> bool:
"""Only for testing purposes."""
if not i... | CustomSerializationTimetable |
python | ray-project__ray | rllib/algorithms/bc/torch/default_bc_torch_rl_module.py | {
"start": 432,
"end": 1712
} | class ____(TorchRLModule, abc.ABC):
"""The default TorchRLModule used, if no custom RLModule is provided.
Builds an encoder net based on the observation space.
Builds a pi head based on the action space.
Passes observations from the input batch through the encoder, then the pi head to
compute acti... | DefaultBCTorchRLModule |
python | Netflix__metaflow | metaflow/metadata_provider/metadata.py | {
"start": 1448,
"end": 2170
} | class ____:
# Consider this list a constant that should never change.
# Lots of code depend on the membership of this list as
# well as exact ordering
_order_as_list = [
"root",
"flow",
"run",
"step",
"task",
"artifact",
"metadata",
"self",... | ObjectOrder |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 102134,
"end": 105880
} | class ____(Request):
"""
Get a list of distinct values for the chosen model metadata key
:param projects: Project IDs
:type projects: Sequence[str]
:param key: Metadata key
:type key: str
:param allow_public: If set to 'true' then collect values from both company and
public models o... | GetModelMetadataValuesRequest |
python | django__django | tests/composite_pk/test_delete.py | {
"start": 78,
"end": 3235
} | class ____(TestCase):
maxDiff = None
@classmethod
def setUpTestData(cls):
cls.tenant_1 = Tenant.objects.create()
cls.tenant_2 = Tenant.objects.create()
cls.user_1 = User.objects.create(
tenant=cls.tenant_1,
id=1,
email="user0001@example.com",
... | CompositePKDeleteTests |
python | huggingface__transformers | tests/models/gemma3/test_modeling_gemma3.py | {
"start": 2180,
"end": 11747
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = Gemma3TextModelTester
_is_stateful = True
model_split_percents = [0.5, 0.6]
@unittest.skip("Gemma3 applies key/query norm which doesn't work with packing")
def test_flash_attention_2_padding_matches_padding_free_with_position_id... | Gemma3TextModelTest |
python | apache__airflow | providers/databricks/tests/unit/databricks/utils/test_mixins.py | {
"start": 1008,
"end": 2184
} | class ____(DatabricksSQLStatementsMixin):
def __init__(self):
self.databricks_conn_id = "databricks_conn_id"
self.databricks_retry_limit = 3
self.databricks_retry_delay = 60
self.databricks_retry_args = None
self.polling_period_seconds = 10
self.statement_id = "statem... | DatabricksSQLStatements |
python | kubernetes-client__python | kubernetes/client/api/resource_v1_api.py | {
"start": 543,
"end": 450263
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | ResourceV1Api |
python | tiangolo__fastapi | docs_src/sql_databases/tutorial002.py | {
"start": 406,
"end": 448
} | class ____(HeroBase):
id: int
| HeroPublic |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 223216,
"end": 226498
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3]", L_v_: "f32[3, 3]"):
l_x_ = L_x_
l_v_ = L_v_
_set_fwd_grad_enabled = torch._C._set_fwd_grad_enabled(False); _set_fwd_grad_enabled = None
_set_fwd_grad_enabled_1 = torch._C._set_fwd_grad_enabled(True); _set_fwd_grad_e... | GraphModule |
python | pennersr__django-allauth | allauth/socialaccount/providers/spotify/provider.py | {
"start": 581,
"end": 1129
} | class ____(OAuth2Provider):
id = "spotify"
name = "Spotify"
account_class = SpotifyAccount
oauth2_adapter_class = SpotifyOAuth2Adapter
def extract_uid(self, data):
return data["id"]
def extract_common_fields(self, data):
return dict(name=data.get("display_name"), email=data.get... | SpotifyOAuth2Provider |
python | mlflow__mlflow | mlflow/store/model_registry/dbmodels/models.py | {
"start": 926,
"end": 2364
} | class ____(Base):
__tablename__ = "registered_models"
name = Column(String(256), unique=True, nullable=False)
creation_time = Column(BigInteger, default=get_current_time_millis)
last_updated_time = Column(BigInteger, nullable=True, default=None)
description = Column(String(5000), nullable=True)
... | SqlRegisteredModel |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 1130,
"end": 1286
} | class ____(ApeException, IndexError):
"""
An exception that is also an IndexError.
Useful for nicely displaying IndexErrors.
"""
| ApeIndexError |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image28.py | {
"start": 315,
"end": 900
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image28.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | getsentry__sentry | tests/sentry/tasks/test_clear_expired_rulesnoozes.py | {
"start": 262,
"end": 3213
} | class ____(APITestCase):
def setUp(self) -> None:
self.issue_alert_rule = Rule.objects.create(
label="test rule", project=self.project, owner_team=self.team
)
self.metric_alert_rule = self.create_alert_rule(
organization=self.project.organization, projects=[self.proje... | ClearExpiredRuleSnoozesTest |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 51732,
"end": 51963
} | class ____(Text):
""" Base class for math text glyphs.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| MathTextGlyph |
python | django__django | tests/fixtures_regress/models.py | {
"start": 7460,
"end": 7609
} | class ____(BaseNKModel):
c_set = models.ManyToManyField(
"M2MComplexCircular1C", through="M2MCircular1ThroughBC"
)
| M2MComplexCircular1B |
python | Netflix__metaflow | metaflow/plugins/gcp/gs_storage_client_factory.py | {
"start": 540,
"end": 2110
} | class ____(object):
name = "gcp-default"
@staticmethod
def get_gs_storage_client(*args, **kwargs):
return _get_gs_storage_client_default()
@staticmethod
def get_credentials(scopes, *args, **kwargs):
import google.auth
return google.auth.default(scopes=scopes)
cached_prov... | GcpDefaultClientProvider |
python | spulec__freezegun | freezegun/api.py | {
"start": 19178,
"end": 40478
} | class ____:
"""
A class to freeze time for testing purposes.
This class can be used as a context manager or a decorator to freeze time
during the execution of a block of code or a function. It provides various
options to customize the behavior of the frozen time.
Attributes:
time_to_fr... | _freeze_time |
python | crytic__slither | slither/detectors/naming_convention/naming_convention.py | {
"start": 278,
"end": 8860
} | class ____(AbstractDetector):
"""
Check if naming conventions are followed
https://solidity.readthedocs.io/en/v0.4.25/style-guide.html?highlight=naming_convention%20convention#naming_convention-conventions
Exceptions:
- Allow constant variables name/symbol/decimals to be lowercase (ERC20)
- All... | NamingConvention |
python | getsentry__sentry | src/sentry/sentry_apps/services/app/model.py | {
"start": 2346,
"end": 3875
} | class ____(RpcModel):
id: int = -1
scope_list: list[str] = Field(default_factory=list)
application_id: int = -1
application: RpcApiApplication | None = None
proxy_user_id: int | None = None # can be null on deletion.
owner_id: int = -1 # relation to an organization
name: str = ""
slug:... | RpcSentryApp |
python | kamyu104__LeetCode-Solutions | Python/longest-happy-string.py | {
"start": 1144,
"end": 1731
} | class ____(object):
def longestDiverseString(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: str
"""
choices = [[a, 'a'], [b, 'b'], [c, 'c']]
result = []
for _ in xrange(a+b+c):
choices.sort(reverse=True)
... | Solution2 |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/fault_tolerance_test_base.py | {
"start": 2182,
"end": 4634
} | class ____(object):
def __init__(self, coordinator):
self.cluster_coord = coordinator
self.strategy = self.cluster_coord.strategy
with self.cluster_coord.strategy.scope():
self.build()
def build(self):
self.w = variables.Variable(
initial_value=random_ops.random_uniform((10, 10)), dt... | Model |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_base.py | {
"start": 1082,
"end": 6084
} | class ____(autotrackable.AutoTrackable):
"""The TPUEmbedding Base class.
This class only contains the basic logic to check the feature config and table
config for the tpu embedding mid level APIs.
"""
def __init__(
self,
feature_config: Union[tpu_embedding_v2_utils.FeatureConfig, Iterable], # p... | TPUEmbeddingBase |
python | nedbat__coveragepy | tests/test_process.py | {
"start": 40303,
"end": 43243
} | class ____(CoverageTest):
"""Tests of sys.excepthook support."""
# TODO: do we need these as process tests if we have test_execfile.py:RunFileTest?
def test_excepthook(self) -> None:
self.make_file(
"excepthook.py",
"""\
import sys
def excepthook(*a... | ExcepthookTest |
python | scipy__scipy | benchmarks/benchmarks/stats.py | {
"start": 22639,
"end": 22961
} | class ____(Benchmark):
params = [
[1, 2, 3, 8],
[100, 1000, 10000],
]
param_names = ["order", "size"]
def setup(self, order, size):
np.random.random(1234)
self.x = np.random.random(size)
def time_moment(self, order, size):
stats.moment(self.x, order)
| BenchMoment |
python | google__pytype | pytype/vm.py | {
"start": 2096,
"end": 151676
} | class ____:
"""A bytecode VM that generates a cfg as it executes."""
# This class is defined inside VirtualMachine so abstract.py can use it.
class VirtualMachineRecursionError(Exception):
pass
def __init__(self, ctx):
"""Construct a TypegraphVirtualMachine."""
self.ctx = ctx # context.Context
... | VirtualMachine |
python | PrefectHQ__prefect | src/integrations/prefect-kubernetes/prefect_kubernetes/worker.py | {
"start": 22974,
"end": 25526
} | class ____(BaseVariables):
"""
Default variables for the Kubernetes worker.
The schema for this class is used to populate the `variables` section of the default
base job template.
"""
namespace: str = Field(
default="default", description="The Kubernetes namespace to create jobs within... | KubernetesWorkerVariables |
python | spack__spack | lib/spack/spack/compilers/adaptor.py | {
"start": 264,
"end": 346
} | class ____(enum.Enum):
C = "c"
CXX = "cxx"
FORTRAN = "fortran"
| Languages |
python | sqlalchemy__sqlalchemy | test/orm/test_dynamic.py | {
"start": 4851,
"end": 4919
} | class ____(_DynamicFixture):
lazy = "write_only"
| _WriteOnlyFixture |
python | google__jax | jax/experimental/mosaic/gpu/layout_inference.py | {
"start": 2615,
"end": 2833
} | class ____(enum.Enum):
"""The memory space of a variable."""
REG = enum.auto()
SMEM = enum.auto()
TMEM = enum.auto()
_op_name_regex = re.compile(r"^(%\d+ = )?\S+")
@dataclasses.dataclass(frozen=True)
| MemorySpace |
python | walkccc__LeetCode | solutions/2266. Count Number of Texts/2266.py | {
"start": 0,
"end": 821
} | class ____:
def countTexts(self, pressedKeys: str) -> int:
MOD = 1_000_000_007
n = len(pressedKeys)
# dp[i] := the number of possible text messages of pressedKeys[i..n)
dp = [0] * n + [1]
def isSame(s: str, i: int, k: int) -> bool:
"""Returns True if s[i..i + k) are the same digits."""
... | Solution |
python | scipy__scipy | scipy/io/matlab/_mio5_params.py | {
"start": 7781,
"end": 8201
} | class ____(np.ndarray):
"""Subclass for a MATLAB opaque matrix.
This is a simple subclass of :class:`numpy.ndarray` meant to be used
by :func:`scipy.io.loadmat` and should not be directly instantiated.
"""
def __new__(cls, input_array):
obj = np.asarray(input_array).view(cls)
retur... | MatlabOpaque |
python | apache__airflow | providers/yandex/src/airflow/providers/yandex/operators/dataproc.py | {
"start": 1434,
"end": 14001
} | class ____(BaseOperator):
"""
Creates Yandex.Cloud Data Proc cluster.
:param folder_id: ID of the folder in which cluster should be created.
:param cluster_name: Cluster name. Must be unique inside the folder.
:param cluster_description: Cluster description.
:param cluster_image_version: Cluste... | DataprocCreateClusterOperator |
python | pandas-dev__pandas | pandas/tests/series/methods/test_cov_corr.py | {
"start": 1589,
"end": 5770
} | class ____:
def test_corr(self, datetime_series, any_float_dtype):
stats = pytest.importorskip("scipy.stats")
datetime_series = datetime_series.astype(any_float_dtype)
# full overlap
tm.assert_almost_equal(datetime_series.corr(datetime_series), 1)
# partial overlap
... | TestSeriesCorr |
python | Netflix__metaflow | metaflow/_vendor/click/_winconsole.py | {
"start": 5226,
"end": 6041
} | class ____(object):
def __init__(self, text_stream, byte_stream):
self._text_stream = text_stream
self.buffer = byte_stream
@property
def name(self):
return self.buffer.name
def write(self, x):
if isinstance(x, text_type):
return self._text_stream.write(x)
... | ConsoleStream |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 103822,
"end": 106554
} | class ____(fixtures.MappedTest):
"""'viewonly' mappings with unique PK column names."""
@classmethod
def define_tables(cls, metadata):
Table(
"t1",
metadata,
Column(
"t1id",
Integer,
primary_key=True,
... | ViewOnlyUniqueNames |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 11915,
"end": 12225
} | class ____(_GenerativeProvider):
generative: Union[GenerativeSearches, _EnumLikeStr] = Field(
default=GenerativeSearches.FRIENDLIAI, frozen=True, exclude=True
)
temperature: Optional[float]
model: Optional[str]
maxTokens: Optional[int]
baseURL: Optional[str]
| _GenerativeFriendliai |
python | doocs__leetcode | solution/0200-0299/0239.Sliding Window Maximum/Solution.py | {
"start": 0,
"end": 377
} | class ____:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = [(-v, i) for i, v in enumerate(nums[: k - 1])]
heapify(q)
ans = []
for i in range(k - 1, len(nums)):
heappush(q, (-nums[i], i))
while q[0][1] <= i - k:
heappop(q)... | Solution |
python | nedbat__coveragepy | coverage/exceptions.py | {
"start": 993,
"end": 1092
} | class ____(CoverageException):
"""We couldn't find the source for a module."""
pass
| NoSource |
python | aio-libs__aiohttp | aiohttp/_websocket/models.py | {
"start": 2899,
"end": 3170
} | class ____(Exception):
"""WebSocket protocol parser error."""
def __init__(self, code: int, message: str) -> None:
self.code = code
super().__init__(code, message)
def __str__(self) -> str:
return cast(str, self.args[1])
| WebSocketError |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py | {
"start": 2289,
"end": 2419
} | class ____[Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, *Bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, **Cccccccccccccccccccccc]:
pass
| TestTypeParams |
python | faif__python-patterns | patterns/structural/bridge.py | {
"start": 386,
"end": 552
} | class ____:
def draw_circle(self, x: int, y: int, radius: float) -> None:
print(f"API2.circle at {x}:{y} radius {radius}")
# Refined Abstraction
| DrawingAPI2 |
python | kamyu104__LeetCode-Solutions | Python/minimum-time-to-collect-all-apples-in-a-tree.py | {
"start": 50,
"end": 1101
} | class ____(object):
def minTime(self, n, edges, hasApple):
"""
:type n: int
:type edges: List[List[int]]
:type hasApple: List[bool]
:rtype: int
"""
graph = collections.defaultdict(list)
for u, v in edges:
graph[u].append(v)
grap... | Solution |
python | ipython__ipython | IPython/core/magic_arguments.py | {
"start": 9104,
"end": 9459
} | class ____(ArgMethodWrapper):
""" Store arguments and keywords to pass to add_argument_group().
Instances also serve to decorate command methods.
"""
def add_to_parser(self, parser, group):
""" Add this object's information to the parser.
"""
return parser.add_argument_group(*s... | argument_group |
python | Pylons__pyramid | tests/test_request.py | {
"start": 24448,
"end": 24646
} | class ____:
def __init__(self, result):
self.result = result
def generate(self, path, request, **kw):
self.args = path, request, kw
return self.result
| DummyStaticURLInfo |
python | dagster-io__dagster | python_modules/libraries/dagster-k8s/dagster_k8s/client.py | {
"start": 1086,
"end": 1876
} | class ____(Exception):
def __init__(self, *args, **kwargs):
k8s_api_exception = check.inst_param(
kwargs.pop("k8s_api_exception"), "k8s_api_exception", Exception
)
original_exc_info = check.tuple_param(kwargs.pop("original_exc_info"), "original_exc_info")
max_retries = ch... | DagsterK8sAPIRetryLimitExceeded |
python | dask__distributed | distributed/diagnostics/progressbar.py | {
"start": 9973,
"end": 15837
} | class ____(MultiProgressBar):
"""Multiple progress bar Widget suitable for the notebook
Displays multiple progress bars for a computation, split on computation
type.
See Also
--------
progress: User-level function <--- use this
MultiProgress: Non-visualization component that contains most ... | MultiProgressWidget |
python | scipy__scipy | scipy/spatial/tests/test_hausdorff.py | {
"start": 304,
"end": 8217
} | class ____:
# Test various properties of the directed Hausdorff code.
def setup_method(self):
np.random.seed(1234)
random_angles = np.random.random(100) * np.pi * 2
random_columns = np.column_stack(
(random_angles, random_angles, np.zeros(100)))
random_columns[..., 0... | TestHausdorff |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance4.py | {
"start": 539,
"end": 589
} | class ____(Generic[T_co]):
pass
| Parent_Covariant |
python | spack__spack | lib/spack/spack/fetch_strategy.py | {
"start": 64822,
"end": 65651
} | class ____:
def __init__(self, root):
self.root = os.path.abspath(root)
def store(self, fetcher, relative_dest):
# skip fetchers that aren't cachable
if not fetcher.cachable:
return
# Don't store things that are already cached.
if isinstance(fetcher, CacheUR... | FsCache |
python | ApeWorX__ape | src/ape/pytest/fixtures.py | {
"start": 17301,
"end": 17898
} | class ____:
"""
All the data necessary for accurately supporting isolation.
"""
scope: Scope
"""Corresponds to fixture scope."""
identifier: Optional["SnapshotID"] = None
"""Snapshot ID taken before the peer-fixtures in the same scope."""
fixtures: list = field(default_factory=list)
... | Snapshot |
python | huggingface__transformers | src/transformers/models/helium/modular_helium.py | {
"start": 5177,
"end": 5415
} | class ____(GemmaForTokenClassification):
pass
__all__ = [
"HeliumPreTrainedModel",
"HeliumModel",
"HeliumForCausalLM",
"HeliumForSequenceClassification",
"HeliumForTokenClassification",
]
| HeliumForTokenClassification |
python | facelessuser__pymdown-extensions | pymdownx/blocks/tab.py | {
"start": 3815,
"end": 8923
} | class ____(Block):
"""
Tabbed container.
Arguments (1 required):
- A tab title.
Options:
- `new` (boolean): since consecutive tabs are automatically grouped, `new` can force a tab
to start a new tab container.
Content:
Detail body.
"""
NAME = 'tab'
ARGUMENT = True
... | Tab |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.