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 | faif__python-patterns | tests/test_hsm.py | {
"start": 1475,
"end": 3850
} | class ____(unittest.TestCase):
"""Exemplary 2nd level state test class (here: Standby state). Add missing
state test classes..."""
@classmethod
def setUpClass(cls):
cls.hsm = HierachicalStateMachine()
def setUp(cls):
cls.hsm._current_state = Standby(cls.hsm)
def test_given_sta... | StandbyStateTest |
python | getsentry__sentry-python | sentry_sdk/sessions.py | {
"start": 4465,
"end": 9172
} | class ____:
def __init__(
self,
capture_func, # type: Callable[[Envelope], None]
flush_interval=60, # type: int
):
# type: (...) -> None
self.capture_func = capture_func
self.flush_interval = flush_interval
self.pending_sessions = [] # type: List[Any]
... | SessionFlusher |
python | mlflow__mlflow | .claude/hooks/lint.py | {
"start": 560,
"end": 1767
} | class ____:
start: int
end: int
def overlaps(self, start: int, end: int) -> bool:
return start <= self.end and self.start <= end
def parse_diff_ranges(diff_output: str) -> list[DiffRange]:
"""Parse unified diff output and extract added line ranges."""
ranges: list[DiffRange] = []
for ... | DiffRange |
python | aio-libs__aiohttp | aiohttp/web_routedef.py | {
"start": 976,
"end": 1853
} | class ____(AbstractRouteDef):
method: str
path: str
handler: _HandlerType
kwargs: dict[str, Any]
def __repr__(self) -> str:
info = []
for name, value in sorted(self.kwargs.items()):
info.append(f", {name}={value!r}")
return "<RouteDef {method} {path} -> {handler.... | RouteDef |
python | celery__celery | celery/events/state.py | {
"start": 2446,
"end": 4524
} | class ____(defaultdict):
""":class:`~collections.defaultdict` with configurable __call__.
We use this for backwards compatibility in State.tasks_by_type
etc, which used to be a method but is now an index instead.
So you can do::
>>> add_tasks = state.tasks_by_type['proj.tasks.add']
while... | CallableDefaultdict |
python | getsentry__sentry | src/sentry/notifications/types.py | {
"start": 265,
"end": 1477
} | class ____(ValueEqualityEnum):
DEPLOY = "deploy"
ISSUE_ALERTS = "alerts"
WORKFLOW = "workflow"
APPROVAL = "approval"
# Notifications for when 100% reserved quota is reached
QUOTA = "quota"
# Notifications for when 80% reserved quota is reached
QUOTA_WARNINGS = "quotaWarnings"
# Notif... | NotificationSettingEnum |
python | getsentry__sentry | tests/sentry/data_export/test_tasks.py | {
"start": 28178,
"end": 47420
} | class ____(TestCase, SnubaTestCase, SpanTestCase, OurLogTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user()
self.org = self.create_organization()
self.project = self.create_project(organization=self.org)
@patch("sentry.data_export.models.ExportedDa... | AssembleDownloadExploreTest |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 13204,
"end": 15650
} | class ____(NonStrictDataModel):
"""
:param preview: Description or textual data
:type preview: str
:param content_type: System defined raw data content type
:type content_type: str
:param data_hash: Hash of raw data, without any headers or descriptive parts
:type data_hash: str
"""
... | ArtifactTypeData |
python | ansible__ansible | test/units/parsing/vault/test_vault.py | {
"start": 13883,
"end": 15135
} | class ____(unittest.TestCase):
def test_randomname(self):
filename = 'randomname'
res = vault.script_is_client(filename)
self.assertFalse(res)
def test_something_dash_client(self):
filename = 'something-client'
res = vault.script_is_client(filename)
self.assertTr... | TestScriptIsClient |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mixpanel/source_mixpanel/components.py | {
"start": 3022,
"end": 3350
} | class ____(MixpanelHttpRequester):
def get_request_params(
self,
*,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
next_page_token: Optional[Mapping[str, Any]] = None,
) -> MutableMapping[str, Any]:
return {}
| AnnotationsHttpRequester |
python | TheAlgorithms__Python | data_structures/hashing/double_hash.py | {
"start": 774,
"end": 2736
} | class ____(HashTable):
"""
Hash Table example with open addressing and Double Hash
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __hash_function_2(self, value, data):
next_prime_gt = (
next_prime(value % self.size_table)
if n... | DoubleHash |
python | pytorch__pytorch | test/test_determination.py | {
"start": 127,
"end": 169
} | class ____:
verbose = False
| DummyOptions |
python | google__pytype | pytype/metrics_test.py | {
"start": 3934,
"end": 4976
} | class ____(unittest.TestCase):
"""Tests for MapCounter."""
def setUp(self):
super().setUp()
metrics._prepare_for_test()
def test_enabled(self):
c = metrics.MapCounter("foo")
# Check contents of an empty map.
self.assertEqual(0, c._total)
# Increment a few values and check again.
c.in... | MapCounterTest |
python | lazyprogrammer__machine_learning_examples | rl2/mountaincar/pg_theano_random.py | {
"start": 716,
"end": 1266
} | class ____:
def __init__(self, M1, M2, f=T.nnet.relu, use_bias=True, zeros=False):
if zeros:
W = np.zeros((M1, M2))
else:
W = np.random.randn(M1, M2) * np.sqrt(2 / M1)
self.W = theano.shared(W)
self.params = [self.W]
self.use_bias = use_bias
if use_bias:
self.b = theano.share... | HiddenLayer |
python | wandb__wandb | wandb/automations/events.py | {
"start": 13579,
"end": 14068
} | class ____:
alias = FilterableField()
MetricThresholdFilter.model_rebuild()
RunMetricFilter.model_rebuild()
_WrappedSavedEventFilter.model_rebuild()
OnLinkArtifact.model_rebuild()
OnAddArtifactAlias.model_rebuild()
OnCreateArtifact.model_rebuild()
OnRunMetric.model_rebuild()
__all__ = [
"EventType",
*(n... | ArtifactEvent |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/api_endpoints/test_user_endpoint.py | {
"start": 8669,
"end": 9417
} | class ____(TestUserEndpoint):
def test_should_response_200(self):
response = self.client.get("/fab/v1/users", environ_overrides={"REMOTE_USER": "test"})
assert response.status_code == 200
assert response.json["total_entries"] == 2
usernames = [user["username"] for user in response.js... | TestGetUsers |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py | {
"start": 29683,
"end": 32649
} | class ____(OutbrainAmplifyStream, HttpSubStream):
primary_key = None
def __init__(self, authenticator, config, parent: Marketers, **kwargs):
super().__init__(parent=parent, **kwargs)
self.config = config
self._authenticator = authenticator
self._session = requests.sessions.Sessi... | PerformanceReportPublishersByCampaigns |
python | tiangolo__fastapi | docs_src/body_multiple_params/tutorial004_py310.py | {
"start": 204,
"end": 603
} | class ____(BaseModel):
username: str
full_name: str | None = None
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int,
item: Item,
user: User,
importance: int = Body(gt=0),
q: str | None = None,
):
results = {"item_id": item_id, "item": item, "user": user, "importan... | User |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/llm.py | {
"start": 1069,
"end": 1586
} | class ____(BaseEvent):
"""
LLMStructuredPredictStartEvent.
Args:
output_cls (Any): Output class to predict.
template (BasePromptTemplate): Prompt template.
template_args (Optional[dict]): Prompt template arguments.
"""
output_cls: Any
template: SerializeAsAny[BasePromp... | LLMStructuredPredictStartEvent |
python | spack__spack | lib/spack/spack/environment/list.py | {
"start": 10391,
"end": 10492
} | class ____(SpackError):
"""Error class for all errors related to SpecList objects."""
| SpecListError |
python | dateutil__dateutil | src/dateutil/tz/win.py | {
"start": 6640,
"end": 8730
} | class ____(tzwinbase):
"""
Time zone object created from the zone info in the Windows registry
These are similar to :py:class:`dateutil.tz.tzrange` objects in that
the time zone data is provided in the format of a single offset rule
for either 0 or 2 time zone transitions per year.
:param: nam... | tzwin |
python | dask__distributed | distributed/utils_test.py | {
"start": 66813,
"end": 67520
} | class ____(Worker):
"""A Worker that sets event `in_get_data` the first time it enters the get_data
method and then does not answer the comms, thus leaving the task(s) in flight
indefinitely, until the test sets `block_get_data`
See also
--------
BarrierGetData
BlockedGatherDep
BlockedE... | BlockedGetData |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/trace_type_test.py | {
"start": 15940,
"end": 16784
} | class ____(test.TestCase):
@test_util.assert_no_new_pyobjects_executing_eagerly()
def testGeneric(self):
trace_type.from_value(1)
trace_type.from_value(DummyGenericClass())
@test_util.assert_no_new_pyobjects_executing_eagerly()
def testTensor(self):
tensor = array_ops.zeros([10])
trace_type.fr... | TraceTypeMemoryTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 101728,
"end": 104482
} | class ____(OperatorExpression[_T]):
"""Describe a list of clauses, separated by an operator,
in a column expression context.
:class:`.ExpressionClauseList` differs from :class:`.ClauseList` in that
it represents a column-oriented DQL expression only, not an open ended
list of anything comma separat... | ExpressionClauseList |
python | pytorch__pytorch | test/distributed/test_dynamo_distributed.py | {
"start": 55176,
"end": 85702
} | class ____(DynamoDistributedSingleProcTestCase):
"""
Test harness initializes dist process group.
Test simple things here since they are simpler to debug.
Use TestMultiProc for things that really need to run on multiple nodes
"""
device_type = (
acc.type if (acc := torch.accelerator.cu... | TestSingleProc |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/tests/test_new_features.py | {
"start": 11981,
"end": 12898
} | class ____:
"""Test logging functionality."""
def test_custom_logger(self):
"""Test that custom logger is properly stored."""
import logging
custom_logger = logging.getLogger("test_confluence_logger")
reader = ConfluenceReader(
base_url="https://example.atlassian.n... | TestLogging |
python | django__django | tests/admin_custom_urls/tests.py | {
"start": 392,
"end": 5801
} | class ____(TestCase):
"""
Remember that:
* The Action model has a CharField PK.
* The ModelAdmin for Action customizes the add_view URL, it's
'<app name>/<model name>/!add/'
"""
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
use... | AdminCustomUrlsTest |
python | Textualize__textual | src/textual/messages.py | {
"start": 379,
"end": 498
} | class ____(Message, verbose=True, bubble=False):
"""Ask the node to prune (remove from DOM)."""
@rich.repr.auto
| Prune |
python | gevent__gevent | src/greentest/3.14/test_timeout.py | {
"start": 4637,
"end": 10283
} | class ____(TimeoutTestCase):
"""TCP test case for socket.socket() timeout functions"""
def setUp(self):
self.sock = self.enterContext(
socket.socket(socket.AF_INET, socket.SOCK_STREAM))
self.addr_remote = resolve_address('www.python.org.', 80)
def testConnectTimeout(self):
... | TCPTimeoutTestCase |
python | django__django | tests/model_forms/tests.py | {
"start": 48536,
"end": 74729
} | class ____(TestCase):
def create_basic_data(self):
self.c1 = Category.objects.create(
name="Entertainment", slug="entertainment", url="entertainment"
)
self.c2 = Category.objects.create(
name="It's a test", slug="its-test", url="test"
)
self.c3 = Categ... | ModelFormBasicTests |
python | pydata__xarray | xarray/ufuncs.py | {
"start": 2244,
"end": 8877
} | class ____(_ufunc_wrapper):
"""Wrapper for dispatching binary ufuncs."""
def __call__(self, x, y, /, **kwargs):
xp = get_array_namespace(x, y)
func = getattr(xp, self.__name__)
return xr.apply_ufunc(func, x, y, dask="allowed", **kwargs)
def _skip_signature(doc, name):
if not isins... | _binary_ufunc |
python | django__django | tests/many_to_one/models.py | {
"start": 2459,
"end": 2665
} | class ____(models.Model):
parent = models.ForeignKey(
Parent, models.CASCADE, to_field="name", related_name="to_field_children"
)
# Multiple paths to the same model (#7110, #7125)
| ToFieldChild |
python | tensorflow__tensorflow | tensorflow/python/distribute/cluster_resolver/kubernetes_cluster_resolver_test.py | {
"start": 1780,
"end": 7602
} | class ____(test.TestCase):
def _verifyClusterSpecEquality(self, cluster_spec, expected_proto):
"""Verifies that the ClusterSpec generates the correct proto.
We are testing this four different ways to ensure that the ClusterSpec
returned by the TPUClusterResolver behaves identically to a normal
Clust... | KubernetesClusterResolverTest |
python | scikit-learn__scikit-learn | sklearn/linear_model/_ridge.py | {
"start": 42354,
"end": 46378
} | class ____(LinearClassifierMixin):
def _prepare_data(self, X, y, sample_weight, solver):
"""Validate `X` and `y` and binarize `y`.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
Training data.
y : ndarray of shape (n_samples,... | _RidgeClassifierMixin |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 64410,
"end": 64764
} | class ____:
@classmethod
def create(cls, **kwargs):
instance = cls(**kwargs)
instance.id = 1
return instance
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
self.id = None
@unittest.skipIf(SKIP_DJANGO, "dj... | BetterFakeModel |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/sdk_crash_detection_config.py | {
"start": 3206,
"end": 24460
} | class ____(TypedDict):
project_id: int
sample_rate: float
organization_allowlist: list[int]
def build_sdk_crash_detection_configs() -> Sequence[SDKCrashDetectionConfig]:
configs: list[SDKCrashDetectionConfig] = []
cocoa_options = _get_options(sdk_name=SdkName.Cocoa, has_organization_allowlist=Fal... | SDKCrashDetectionOptions |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/__init__.py | {
"start": 9448,
"end": 9969
} | class ____(WindowsTargetParser):
"""Composite argument parser for a Windows SSH target."""
@property
def option_name(self) -> str:
"""The option name used for this parser."""
return '--target-windows'
@property
def allow_inventory(self) -> bool:
"""True if inventory is allo... | WindowsSshTargetParser |
python | jmcnamara__XlsxWriter | xlsxwriter/test/styles/test_write_border.py | {
"start": 332,
"end": 903
} | class ____(unittest.TestCase):
"""
Test the Styles _write_border() method.
"""
def setUp(self):
self.fh = StringIO()
self.styles = Styles()
self.styles._set_filehandle(self.fh)
def test_write_border(self):
"""Test the _write_border() method"""
xf_format = ... | TestWriteBorder |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 11668,
"end": 12211
} | class ____(HelperFunction):
def _calculate(self, X, y, logger, feat_type):
if len(y.shape) == 2:
occurences = []
for i in range(y.shape[1]):
occurences.append(self._calculate(X, y[:, i], logger, feat_type))
return occurences
else:
occur... | ClassOccurences |
python | pytorch__pytorch | test/test_mps.py | {
"start": 381950,
"end": 396062
} | class ____(NNTestCase):
def _create_basic_net(self):
class Layer(nn.Module):
def __init__(self) -> None:
super().__init__()
self.layer_dummy_param = Parameter(torch.empty(3, 5))
self.layer_dummy_buf = Buffer(torch.zeros(1, 3, 3, 7))
class... | TestNNMPS |
python | modin-project__modin | modin/config/envvars.py | {
"start": 38742,
"end": 38962
} | class ____(EnvironmentVariable, type=str):
"""Set to AWS_SECRET_ACCESS_KEY when running mock S3 tests for Modin in GitHub CI."""
varname = "AWS_SECRET_ACCESS_KEY"
default = "foobar_secret"
| CIAWSSecretAccessKey |
python | huggingface__transformers | src/transformers/models/smolvlm/modular_smolvlm.py | {
"start": 4627,
"end": 4697
} | class ____(Idefics3VisionTransformer):
pass
| SmolVLMVisionTransformer |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/qtenum.py | {
"start": 90,
"end": 2622
} | class ____(ListParameter):
def __init__(self, enum, searchObj=QtCore.Qt, **opts):
"""
Constructs a list of allowed enum values from the enum class provided
`searchObj` is only needed for PyQt5 compatibility, where it must be the module holding the enum.
For instance, if making a QtEn... | QtEnumParameter |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 64407,
"end": 64710
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("app_id", "check_name")
app_id = sgqlc.types.Field(Int, graphql_name="appId")
check_name = sgqlc.types.Field(String, graphql_name="checkName")
| CheckSuiteFilter |
python | Netflix__metaflow | metaflow/plugins/azure/azure_secret_manager_secrets_provider.py | {
"start": 895,
"end": 1034
} | class ____(MetaflowException):
"""Raised when the secret version does not match expected pattern"""
| MetaflowAzureKeyVaultBadSecretVersion |
python | huggingface__transformers | src/transformers/models/esm/modeling_esmfold.py | {
"start": 41239,
"end": 46324
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
sequence_state_dim = config.sequence_state_dim
pairwise_state_dim = config.pairwise_state_dim
sequence_num_heads = sequence_state_dim // config.sequence_head_width
pairwise_num... | EsmFoldTriangularSelfAttentionBlock |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 56377,
"end": 57288
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
key: Optional[str] = Field(
None,
description=(
"[Databricks Runtime"
" version](https://docs.databricks.com/dev-tools/api/lates... | SparkVersion |
python | ApeWorX__ape | src/ape_pm/dependency.py | {
"start": 1195,
"end": 3026
} | class ____(DependencyAPI):
"""
A dependency located on the local machine.
"""
local: Path
"""
The root path (and API defining key) to the dependency files.
"""
version: Optional[str] = None
"""
Specified version.
"""
@model_validator(mode="before")
@classmethod
... | LocalDependency |
python | django__django | tests/mail/custombackend.py | {
"start": 99,
"end": 448
} | class ____(BaseEmailBackend):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.test_outbox = []
def send_messages(self, email_messages):
# Messages are stored in an instance variable for testing.
self.test_outbox.extend(email_messages)
return l... | EmailBackend |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py | {
"start": 43150,
"end": 44062
} | class ____(Stream):
state_converter = IsoMillisConcurrentStreamStateConverter(is_sequential_state=False)
"""
Stream of sObjects' (Salesforce Objects) describe:
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_describe.htm
"""
name = "Describe"
prima... | Describe |
python | scrapy__scrapy | scrapy/core/downloader/handlers/ftp.py | {
"start": 2201,
"end": 2847
} | class ____(Protocol):
def __init__(self, filename: bytes | None = None):
self.__filename: bytes | None = filename
self.body: BinaryIO = (
Path(filename.decode()).open("wb") if filename else BytesIO()
)
self.size: int = 0
def dataReceived(self, data: bytes) -> None:
... | ReceivedDataProtocol |
python | pyinstaller__pyinstaller | tests/functional/modules/pyi_import_pyqt_uic_port/PyQt5/QtCore.py | {
"start": 135,
"end": 371
} | class ____:
def __init__(*args, **kw):
pass
PrefixPath = 1
BinariesPath = 2
@classmethod
def location(cls, val):
return "."
@classmethod
def isDebugBuild(cls):
return False
| QLibraryInfo |
python | walkccc__LeetCode | solutions/2357. Make Array Zero by Subtracting Equal Amounts/2357.py | {
"start": 0,
"end": 103
} | class ____:
def minimumOperations(self, nums: list[int]) -> int:
return len(set(nums) - {0})
| Solution |
python | facebook__pyre-check | client/language_server/features.py | {
"start": 973,
"end": 1409
} | class ____(enum.Enum):
DISABLED = "disabled"
FUNCTION_LEVEL = "function_level"
EXPRESSION_LEVEL = "expression_level"
# User-facing features
StatusUpdatesAvailability = _Availability
TypeErrorsAvailability = _Availability
UnsavedChangesAvailability = _Availability
# Telemetry: is the editor able to forwar... | TypeCoverageAvailability |
python | django-extensions__django-extensions | tests/management/commands/test_describe_form.py | {
"start": 151,
"end": 502
} | class ____(TestCase):
"""Tests for describe_form command exceptions."""
def test_should_raise_CommandError_if_invalid_arg(self):
with self.assertRaisesRegex(
CommandError, "Need application and model name in the form: appname.model"
):
call_command("describe_form", "test... | DescribeFormExceptionsTests |
python | getsentry__sentry | src/sentry/grouping/grouptype.py | {
"start": 573,
"end": 831
} | class ____(DetectorHandler):
def evaluate_impl(self, data_packet: DataPacket[T]) -> GroupedDetectorEvaluationResult:
# placeholder
return GroupedDetectorEvaluationResult(result={}, tainted=False)
@dataclass(frozen=True)
| ErrorDetectorHandler |
python | xlwings__xlwings | xlwings/_xlmac.py | {
"start": 13440,
"end": 18158
} | class ____(base_classes.Book):
def __init__(self, app, name_or_index):
self._app = app
self.xl = app.xl.workbooks[name_or_index]
@property
def app(self):
return self._app
@property
def api(self):
return self.xl
def json(self):
raise NotImplementedError(... | Book |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 11837,
"end": 12214
} | class ____(LTTextGroup):
def analyze(self, laparams):
LTTextGroup.analyze(self, laparams)
# reorder the objects from top-left to bottom-right.
self._objs = csort(self._objs, key=lambda obj:
(1-laparams.boxes_flow)*(obj.x0) -
(1+laparams.... | LTTextGroupLRTB |
python | jazzband__django-model-utils | model_utils/tracker.py | {
"start": 769,
"end": 872
} | class ____(Descriptor[T]):
def __delete__(self, instance: object) -> None:
...
| FullDescriptor |
python | getsentry__sentry | tests/sentry/integrations/jira/test_sentry_installation.py | {
"start": 556,
"end": 931
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.path = absolute_uri("extensions/jira/ui-hook/") + "?xdm_e=base_url"
self.user.name = "Sentry Admin"
self.user.save()
self.integration = self.create_provider_integration(provider="jira", name="Example Jir... | JiraSentryInstallationViewTestCase |
python | jina-ai__jina | jina/jaml/helper.py | {
"start": 532,
"end": 2576
} | class ____(FullConstructor):
"""Convert List into tuple when doing hashing."""
def get_hashable_key(self, key):
"""
Get the hash value of key.
:param key: key value to be hashed.
:return: Hash value of key.
"""
try:
hash(key)
except:
... | JinaConstructor |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_india_zip.py | {
"start": 1724,
"end": 5176
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid India zipcodes.
See https://pypi.org/project/indiapins/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidIndiaZip |
python | getsentry__sentry | tests/sentry/integrations/repository/metric_alert/test_new_metric_alert_notification_message.py | {
"start": 251,
"end": 2826
} | class ____:
@classmethod
def _raises_error_for_obj(
cls, obj: NewMetricAlertNotificationMessage, expected_error: type[Exception]
) -> None:
error = obj.get_validation_error()
assert error is not None
with pytest.raises(expected_error):
raise error
def test_re... | TestGetValidationError |
python | huggingface__transformers | src/transformers/models/lfm2_vl/image_processing_lfm2_vl_fast.py | {
"start": 6578,
"end": 21143
} | class ____(BaseImageProcessorFast):
downsample_factor = 2
do_image_splitting = True
min_tiles = 2
max_tiles = 10
use_thumbnail = True
min_image_tokens = 64
max_image_tokens = 256
encoder_patch_size = 16
tile_size = 512
max_pixels_tolerance = 2.0
do_resize = True
size = {"... | Lfm2VlImageProcessorFast |
python | celery__celery | examples/django/demoapp/migrations/0001_initial.py | {
"start": 92,
"end": 486
} | class ____(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Widget',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name'... | Migration |
python | ipython__ipython | IPython/core/completer.py | {
"start": 14676,
"end": 17104
} | class ____:
"""
Completion object used and returned by IPython completers.
.. warning::
Unstable
This function is unstable, API may change without warning.
It will also raise unless use in proper context manager.
This act as a middle ground :any:`Completion` object between th... | Completion |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 13911,
"end": 14006
} | class ____(Egg):
def __init__(self, thing: int) -> None:
super().__init__(thing)
| Spam |
python | joke2k__faker | faker/providers/job/ja_JP/__init__.py | {
"start": 42,
"end": 1125
} | class ____(BaseProvider):
"""
source: https://ja.wikipedia.org/wiki/%E8%81%B7%E6%A5%AD%E4%B8%80%E8%A6%A7
"""
jobs = [
"アイドル",
"アーティスト",
"アートディレクター",
"アナウンサー",
"アニメーター",
"医師",
"イラストレーター",
"医療事務員",
"ウェディングプランナー",
"ウェブデザイナー",
... | Provider |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-jira/integration_tests/fixtures/data_generator/streams.py | {
"start": 2223,
"end": 2947
} | class ____(FilterSharing, GeneratorMixin):
"""
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-filter-sharing/#api-rest-api-3-filter-id-permission-post
"""
def generate(self):
filters_stream = Filters(authenticator=self._session.auth, domain=self._domain)
for filte... | FilterSharingGenerator |
python | getsentry__sentry | src/social_auth/backends/asana.py | {
"start": 425,
"end": 950
} | class ____(OAuthBackend):
"""Asana OAuth authentication backend"""
name = "asana"
EXTRA_DATA = [
("email", "email"),
("name", "full_name"),
("gid", "id"),
("refresh_token", "refresh_token"),
]
ID_KEY = "gid"
def get_user_details(self, response):
"""Retur... | AsanaBackend |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-wordlift/llama_index/readers/wordlift/base.py | {
"start": 819,
"end": 10555
} | class ____(BaseReader):
"""
A reader class for fetching and transforming data from WordLift GraphQL API.
Args:
endpoint (str): The API endpoint URL.
headers (dict): The request headers.
query (str): The GraphQL query.
fields (str): The fields to extract from the API response... | WordLiftLoader |
python | fluentpython__example-code-2e | 10-dp-1class-func/untyped/strategy.py | {
"start": 1302,
"end": 2600
} | class ____: # the Context
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = list(cart)
self.promotion = promotion
def total(self):
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
... | Order |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 13444,
"end": 17242
} | class ____(Metric):
"""Encapsulates metrics that perform a reduce operation on the values.
Args:
reduction: a `tf.keras.metrics.Reduction` enum value.
name: string name of the metric instance.
dtype: (Optional) data type of the metric result.
"""
def __init__(self, reduction, name, dtype=None):
... | Reduce |
python | openai__openai-python | src/openai/types/completion_create_params.py | {
"start": 7023,
"end": 7650
} | class ____(CompletionCreateParamsBase):
stream: Required[Literal[True]]
"""Whether to stream back partial progress.
If set, tokens will be sent as data-only
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)
as they... | CompletionCreateParamsStreaming |
python | kubernetes-client__python | kubernetes/client/models/v1_device_selector.py | {
"start": 383,
"end": 3328
} | 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... | V1DeviceSelector |
python | doocs__leetcode | solution/3100-3199/3184.Count Pairs That Form a Complete Day I/Solution.py | {
"start": 0,
"end": 235
} | class ____:
def countCompleteDayPairs(self, hours: List[int]) -> int:
cnt = Counter()
ans = 0
for x in hours:
ans += cnt[(24 - (x % 24)) % 24]
cnt[x % 24] += 1
return ans
| Solution |
python | bokeh__bokeh | src/bokeh/core/property/either.py | {
"start": 1567,
"end": 4190
} | class ____(ParameterizedProperty[Any]):
""" Accept values according to a sequence of other property types.
Example:
.. code-block:: python
>>> class EitherModel(HasProps):
... prop = Either(Bool, Int, Auto)
...
>>> m = EitherModel()
>>... | Either |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 78731,
"end": 79001
} | class ____(AddPrefixSeries):
_parameters = ["frame", "suffix"]
operation = M.add_suffix
_preserves_partitioning_information = True
def _divisions(self):
return tuple(str(division) + self.suffix for division in self.frame.divisions)
| AddSuffixSeries |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/gather_nd_op_test.py | {
"start": 18043,
"end": 18817
} | class ____(test.Benchmark):
def benchmark_gather_nd_op(self):
shape = (100, 47, 18, 170, 13)
np.random.seed(127)
params = np.random.rand(*shape)
indices = np.vstack([np.random.randint(0, s, size=10000) for s in shape]).T
with session.Session():
t_params = variables.Variable(params)
t... | GatherNdOpBenchmark |
python | jina-ai__jina | tests/integration/v2_api/test_docs_matrix_tail_pea.py | {
"start": 1173,
"end": 3120
} | class ____(Executor):
@requests
def merge(self, docs_matrix, **kwargs):
results = OrderedDict()
for docs in docs_matrix:
for doc in docs:
if doc.id in results:
results[doc.id].chunks.extend(doc.chunks)
else:
resu... | ChunkMerger |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc.py | {
"start": 43732,
"end": 49679
} | class ____(GoogleCloudBaseOperator):
"""
Delete a cluster in a project.
:param region: Required. The Cloud Dataproc region in which to handle the request (templated).
:param cluster_name: Required. The cluster name (templated).
:param project_id: Optional. The ID of the Google Cloud project that th... | DataprocDeleteClusterOperator |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/tokens.py | {
"start": 8168,
"end": 8453
} | class ____(Token):
__slots__ = ('encoding',)
id = '<stream start>'
def __init__(self, start_mark=None, end_mark=None, encoding=None):
# type: (Any, Any, Any) -> None
Token.__init__(self, start_mark, end_mark)
self.encoding = encoding
| StreamStartToken |
python | explosion__spaCy | spacy/tokens/underscore.py | {
"start": 234,
"end": 5590
} | class ____:
mutable_types = (dict, list, set)
doc_extensions: Dict[Any, Any] = {}
span_extensions: Dict[Any, Any] = {}
token_extensions: Dict[Any, Any] = {}
_extensions: Dict[str, Any]
_obj: Union["Doc", "Span", "Token"]
_start: Optional[int]
_end: Optional[int]
def __init__(
... | Underscore |
python | Lightning-AI__lightning | tests/tests_pytorch/accelerators/test_xla.py | {
"start": 7817,
"end": 11987
} | class ____(BoringModel):
def __init__(self):
super(BoringModel, self).__init__()
self.layer = nn.Linear(32, 10, bias=False)
self.net_a = SubModule(self.layer)
self.layer_2 = nn.Linear(10, 32, bias=False)
self.net_b = SubModule(self.layer)
def forward(self, x):
x ... | NestedModule |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 6167,
"end": 6290
} | class ____(ParentI):
def f(self):
__class__: "Any"
super
builtins.super(ChildI8, self).f()
| ChildI8 |
python | matplotlib__matplotlib | lib/matplotlib/patches.py | {
"start": 142593,
"end": 156093
} | class ____(Patch):
"""
A fancy arrow patch.
It draws an arrow using the `ArrowStyle`. It is primarily used by the
`~.axes.Axes.annotate` method. For most purposes, use the annotate method for
drawing arrows.
The head and tail positions are fixed at the specified start and end points
of th... | FancyArrowPatch |
python | walkccc__LeetCode | solutions/1467. Probability of a Two Boxes Having The Same Number of Distinct Balls/1467.py | {
"start": 91,
"end": 1266
} | class ____:
def getProbability(self, balls: list[int]) -> float:
n = sum(balls) // 2
fact = [1, 1, 2, 6, 24, 120, 720]
def cases(
i: int,
ballsCountA: int,
ballsCountB: int,
colorsCountA: int,
colorsCountB,
boxCase: BoxCase) -> float... | Solution |
python | huggingface__transformers | src/transformers/models/bamba/modeling_bamba.py | {
"start": 46141,
"end": 46882
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
... | BambaMLP |
python | pypa__hatch | backend/src/hatchling/version/source/code.py | {
"start": 126,
"end": 2348
} | class ____(VersionSourceInterface):
PLUGIN_NAME = "code"
def get_version_data(self) -> dict:
import sys
from importlib.util import module_from_spec, spec_from_file_location
relative_path = self.config.get("path")
if not relative_path:
message = "option `path` must b... | CodeSource |
python | sqlalchemy__sqlalchemy | test/orm/test_lazy_relations.py | {
"start": 37576,
"end": 40149
} | class ____(_fixtures.FixtureTest):
run_inserts = "once"
run_deletes = None
def test_m2o_noload(self):
"""test that a NULL foreign key doesn't trigger a lazy load"""
users, Address, addresses, User = (
self.tables.users,
self.classes.Address,
self.tables.... | M2OGetTest |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 70396,
"end": 71349
} | class ____:
@xfail_xp_backends(
'dask.array', reason='https://github.com/dask/dask/issues/11883'
)
def test_basic(self, xp):
z = xp.asarray([])
p = xp.asarray([(-1+1j) / math.sqrt(2), (-1-1j) / math.sqrt(2)])
k = 1
z_hp, p_hp, k_hp = lp2hp_zpk(z, p, k, 5)
xp... | TestLp2hp_zpk |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_responses.py | {
"start": 372,
"end": 491
} | class ____(BaseModel):
"""Custom model with a custom docstring."""
value: float
description: str
| CustomModel |
python | celery__celery | t/integration/test_backend.py | {
"start": 280,
"end": 1120
} | class ____:
def test_crud(self, manager):
backend = AzureBlockBlobBackend(
app=manager.app,
url=os.environ["AZUREBLOCKBLOB_URL"])
key_values = {("akey%d" % i).encode(): "avalue%d" % i
for i in range(5)}
for key, value in key_values.items():
... | test_AzureBlockBlobBackend |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/functional_saver_test.py | {
"start": 1712,
"end": 10996
} | class ____(test.TestCase):
def setUp(self):
super(SaverTest, self).setUp()
cpus = config.list_physical_devices("CPU")
# Set 3 virtual CPUs
config.set_logical_device_configuration(cpus[0], [
context.LogicalDeviceConfiguration(),
context.LogicalDeviceConfiguration(),
context.Log... | SaverTest |
python | davidhalter__parso | parso/python/tokenize.py | {
"start": 8651,
"end": 8830
} | class ____(Token):
def __repr__(self):
return ('TokenInfo(type=%s, string=%r, start_pos=%r, prefix=%r)' %
self._replace(type=self.type.name))
| PythonToken |
python | sphinx-doc__sphinx | sphinx/util/cfamily.py | {
"start": 7296,
"end": 8401
} | class ____(ASTBaseBase):
def __init__(self, attrs: list[ASTAttribute]) -> None:
self.attrs = attrs
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTAttributeList):
return NotImplemented
return self.attrs == other.attrs
def __hash__(self) -> int:
... | ASTAttributeList |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/aggregate.py | {
"start": 7255,
"end": 7927
} | class ____(GenericBase):
@staticmethod
def visit_eq(expression: Expression, value: UUID) -> Condition:
return contains(UUIDScalar.visit_eq(expression, value))
@staticmethod
def visit_neq(expression: Expression, value: UUID) -> Condition:
return does_not_contain(UUIDScalar.visit_eq(expre... | SumOfUUIDScalar |
python | davidhalter__jedi | test/completion/arrays.py | {
"start": 4476,
"end": 5620
} | class ____(list):
def __getitem__(self, index):
return super()[index]
#?
SuperYeah([1])[0]
#?
SuperYeah()[0]
# -----------------
# conversions
# -----------------
a = [1, ""]
#? int() str()
list(a)[1]
#? int() str()
list(a)[0]
#?
set(a)[0]
#? int() str()
list(set(a))[1]
#? int() str()
next(iter(set(a))... | SuperYeah |
python | redis__redis-py | tests/test_asyncio/test_cluster.py | {
"start": 98176,
"end": 111034
} | class ____:
"""
Tests for the NodesManager class
"""
async def test_load_balancer(self, r: RedisCluster) -> None:
n_manager = r.nodes_manager
lb = n_manager.read_load_balancer
slot_1 = 1257
slot_2 = 8975
node_1 = ClusterNode(default_host, 6379, PRIMARY)
n... | TestNodesManager |
python | getsentry__sentry | tests/apidocs/endpoints/releases/test_organization_releases.py | {
"start": 269,
"end": 2069
} | class ____(APIDocsTestCase):
def setUp(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.create_organization(owner=user, name="blah")
org2 = self.create_organization(owner=user, name="bloop")
team1 = self.create_team(organization=org)
team... | OrganizationReleasesDocsTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.