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 | openai__openai-python | src/openai/types/beta/threads/runs/run_step_delta_message_delta.py | {
"start": 250,
"end": 390
} | class ____(BaseModel):
message_id: Optional[str] = None
"""The ID of the message that was created by this run step."""
| MessageCreation |
python | django__django | django/core/paginator.py | {
"start": 463,
"end": 511
} | class ____(InvalidPage):
pass
| PageNotAnInteger |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/api/run.py | {
"start": 356,
"end": 591
} | class ____:
"""API for run metadata operations."""
client: IGraphQLClient
def get_run(self, run_id: str) -> "DgApiRun":
"""Get run metadata by ID."""
return get_run_via_graphql(self.client, run_id)
| DgApiRunApi |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple13.py | {
"start": 343,
"end": 560
} | class ____(Protocol[Unpack[Ts]]):
def __call__(self, *args: *Ts) -> tuple[Unpack[Ts]]: ...
def invoke_posonly(fn: CallbackPosOnly[Unpack[Ts]], *args: *Ts) -> tuple[Unpack[Ts]]:
return fn(*args)
| CallbackPosOnly |
python | kamyu104__LeetCode-Solutions | Python/generate-binary-strings-without-adjacent-zeros.py | {
"start": 641,
"end": 1043
} | class ____(object):
def validStrings(self, n):
"""
:type n: int
:rtype: List[str]
"""
q = [[]]
for _ in xrange(n):
new_q = []
for x in q:
if not x or x[-1] == '1':
new_q.append(x+['0'])
new_q.... | Solution2 |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 91919,
"end": 95479
} | class ____(nn.Module):
def __init__(self, config: DFineConfig):
super().__init__()
self.normalize_before = config.normalize_before
# self-attention
self.self_attn = DFineMultiheadAttention(
embed_dim=config.encoder_hidden_dim,
num_heads=config.num_attention_h... | DFineEncoderLayer |
python | django__django | django/contrib/sites/migrations/0001_initial.py | {
"start": 148,
"end": 1361
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="Site",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
... | Migration |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/descriptor1.py | {
"start": 1281,
"end": 1437
} | class ____:
def __get__(self, instance: Any, owner: Any) -> int | None: ...
def __set__(self, owner: Any, value: int | None) -> None: ...
| Descriptor1 |
python | plotly__plotly.py | plotly/graph_objs/_deprecations.py | {
"start": 11937,
"end": 12836
} | class ____(dict):
"""
plotly.graph_objs.Marker is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.scatter.Marker
- plotly.graph_objs.histogram.selected.Marker
- etc.
"""
def __init__(self, *args, **kwargs):
"""
... | Marker |
python | celery__celery | t/unit/contrib/test_migrate.py | {
"start": 1241,
"end": 1524
} | class ____:
def test_strtotal(self):
x = State()
assert x.strtotal == '?'
x.total_apx = 100
assert x.strtotal == '100'
def test_repr(self):
x = State()
assert repr(x)
x.filtered = 'foo'
assert repr(x)
| test_State |
python | pytorch__pytorch | torch/distributed/flight_recorder/components/types.py | {
"start": 5310,
"end": 12011
} | class ____:
"""
Util class to keep track of the state of an entry and standardize the way we
log the error info during analysis.
"""
def __init__(self, entry: dict[str, Any], expected_ranks: set[int]) -> None:
self.pg_name = entry["process_group"][0]
self.desc = entry["process_group... | EntryState |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 853616,
"end": 854047
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "created_at", "issue")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_na... | PinnedEvent |
python | doocs__leetcode | solution/0600-0699/0641.Design Circular Deque/Solution.py | {
"start": 0,
"end": 2578
} | class ____:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the deque to be k.
"""
self.q = [0] * k
self.front = 0
self.size = 0
self.capacity = k
def insertFront(self, value: int) -> bool:
"""
Adds an ... | MyCircularDeque |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/benchmarks/pdsh.py | {
"start": 31158,
"end": 56209
} | class ____:
"""PDS-H DuckDB query definitions."""
name: str = "pdsh"
@staticmethod
def q1(run_config: RunConfig) -> str:
"""Query 1."""
return """
select
l_returnflag,
l_linestatus,
sum(l_quantity) as sum_qty,
sum(l_extendedprice)... | PDSHDuckDBQueries |
python | pytorch__pytorch | torch/_inductor/runtime/caching/context.py | {
"start": 7156,
"end": 7335
} | class ____(TypedDict):
torch_version_hash: bool
triton_version_hash: bool
runtime: bool
runtime_version: bool
accelerator_properties: bool
| SelectedCompileContext |
python | ipython__ipython | IPython/terminal/prompts.py | {
"start": 320,
"end": 2889
} | class ____:
def __init__(self, shell):
self.shell = shell
def vi_mode(self):
if (getattr(self.shell.pt_app, 'editing_mode', None) == EditingMode.VI
and self.shell.prompt_includes_vi_mode):
mode = str(self.shell.pt_app.app.vi_state.input_mode)
if mode.star... | Prompts |
python | apache__airflow | providers/google/tests/unit/google/marketing_platform/hooks/test_search_ads.py | {
"start": 6964,
"end": 7805
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.marketing_platform.hooks.search_ads.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.hook = GoogleSearchAdsHook(gcp_conn_id=GCP_CONN_ID)
@mock.patch("ai... | TestSearchAdsHook |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 179587,
"end": 182014
} | class ____(Request):
"""
Get unique source ids from the given dataset version
:param version: Dataset version ID. If not provided, returns sources used by
all versions.
:type version: str
:param dataset: Dataset ID
:type dataset: str
:param max_count: Number of sources to return. de... | GetSourceIdsRequest |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/shard_test.py | {
"start": 1333,
"end": 4534
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
def testSimpleCase(self):
dataset = dataset_ops.Dataset.range(10).shard(5, 2)
self.assertDatasetProduces(dataset, expected_output=[2, 7])
@combinations.generate(test_base.default_... | ShardTest |
python | bokeh__bokeh | tests/unit/bokeh/test_settings.py | {
"start": 11350,
"end": 14167
} | class ____:
def test_allowed_ws_origin(self):
assert bs.settings.allowed_ws_origin.default == []
def test_auth_module(self):
assert bs.settings.auth_module.default is None
def test_browser(self):
assert bs.settings.browser.default is None
def test_cdn_version(self):
a... | TestDefaults |
python | kamyu104__LeetCode-Solutions | Python/3sum-closest.py | {
"start": 31,
"end": 859
} | class ____(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
result, min_diff = 0, float("inf")
nums.sort()
for i in reversed(xrange(2, len(nums))):
if i+1 < len(nums) and nums[i] ... | Solution |
python | tensorflow__tensorflow | tensorflow/python/distribute/packed_distributed_variable.py | {
"start": 9542,
"end": 14024
} | class ____(object):
"""Holds a packed distributed variable and a device."""
def __init__(self, var, device):
self._var = var
self._device = device
def __getattr__(self, name):
# Exceptions raised inside the contextmanager can cause a reference
# cycle.[1] The cycle involves the current frame, wh... | PackedVarAndDevice |
python | fluentpython__example-code | 14-it-generator/sentence_genexp.py | {
"start": 148,
"end": 989
} | class ____:
def __init__(self, text):
self.text = text
def __repr__(self):
return 'Sentence(%s)' % reprlib.repr(self.text)
def __iter__(self):
return (match.group() for match in RE_WORD.finditer(self.text))
# END SENTENCE_GENEXP
def main():
import sys
import warnings
... | Sentence |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_bincount_ops_test.py | {
"start": 1725,
"end": 11831
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
@parameterized.parameters([{
"dtype": np.int32,
}, {
"dtype": np.int64,
}])
def test_ragged_input_count(self, dtype):
x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]],
dtyp... | TestDenseBincount |
python | tensorflow__tensorflow | tensorflow/python/framework/immutable_dict_test.py | {
"start": 932,
"end": 3483
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
def testGetItem(self):
d = immutable_dict.ImmutableDict({'x': 1, 'y': 2})
self.assertEqual(d['x'], 1)
self.assertEqual(d['y'], 2)
with self.assertRaises(KeyError):
d['z'] # pylint: disable=pointless-statement
def testIter(sel... | ImmutableDictTest |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 12787,
"end": 14207
} | class ____(StepBase):
def who(self):
self.cmd = 'SR AAAA-CORRECT NAME IS {last_name} {first_name}{middle_name} {title}/P{passenger_association}'.format(
last_name=last_name,
first_name=first_name,
middle_name=middle_name,
title=title,
passenger_ass... | Step |
python | ijl__orjson | test/test_dataclass.py | {
"start": 1389,
"end": 1521
} | class ____(abc.ABC):
@abc.abstractmethod
def key(self):
raise NotImplementedError
@dataclass(frozen=True)
| AbstractBase |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 64471,
"end": 66274
} | class ____:
# For these, making behaviour work means deviating only slightly from
# the docstring, and by default they fail miserably. So, might as well.
def setup_method(self):
self.q = np.arange(3.0) * u.Jy
def test_array2string(self):
# The default formatters cannot handle units, so... | TestStringFunctions |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 312147,
"end": 314794
} | class ____(Response):
"""
Response of tasks.get_configurations endpoint.
:param configurations: Configurations (keyed by task ID)
:type configurations: Sequence[dict]
"""
_service = "tasks"
_action = "get_configurations"
_version = "2.13"
_schema = {
"definitions": {
... | GetConfigurationsResponse |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-snowflake-query-engine/llama_index/packs/snowflake_query_engine/base.py | {
"start": 303,
"end": 2634
} | class ____(BaseLlamaPack):
"""
Snowflake query engine pack.
It uses snowflake-sqlalchemy to connect to Snowflake, then calls
NLSQLTableQueryEngine to query data.
"""
def __init__(
self,
user: str,
password: str,
account: str,
database: str,
schema... | SnowflakeQueryEnginePack |
python | kamyu104__LeetCode-Solutions | Python/construct-binary-tree-from-preorder-and-inorder-traversal.py | {
"start": 982,
"end": 1666
} | class ____(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
preorder_iterator = iter(preorder)
inorder_lookup = {n: i for i, n in enumerate(inorder)}
def helper(start,... | Solution2 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol48.py | {
"start": 281,
"end": 548
} | class ____:
def method1(self) -> tuple[Self, Self]: ...
def method2(self):
x = apply_method1(self)
reveal_type(x, expected_text="tuple[Self@A, Self@A]")
def func1(a: A):
x = apply_method1(a)
reveal_type(x, expected_text="tuple[A, A]")
| A |
python | PrefectHQ__prefect | src/prefect/server/schemas/statuses.py | {
"start": 677,
"end": 935
} | class ____(AutoEnum):
"""Enumeration of work queue statuses."""
READY = AutoEnum.auto()
NOT_READY = AutoEnum.auto()
PAUSED = AutoEnum.auto()
def in_kebab_case(self) -> str:
return self.value.lower().replace("_", "-")
| WorkQueueStatus |
python | gevent__gevent | src/greentest/3.9/test_socket.py | {
"start": 112695,
"end": 118639
} | class ____(SendrecvmsgBase):
# Tests for recvmsg() which can also be emulated using
# recvmsg_into(), and can use any socket type.
def testRecvmsg(self):
# Receive a simple message with recvmsg[_into]().
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
self.asser... | RecvmsgGenericTests |
python | skorch-dev__skorch | skorch/exceptions.py | {
"start": 639,
"end": 741
} | class ____(SkorchException):
"""The net cannot be used for training"""
| SkorchTrainingImpossibleError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1124004,
"end": 1124855
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'demilestoned' event on a given issue or pull
request.
"""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "milestone_title", "subject")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor wh... | DemilestonedEvent |
python | huggingface__transformers | src/transformers/models/sam_hq/modeling_sam_hq.py | {
"start": 46276,
"end": 46919
} | class ____(SamHQPreTrainedModel):
config: SamHQVisionConfig
main_input_name = "pixel_values"
def __init__(self, config: SamHQVisionConfig):
super().__init__(config)
self.vision_encoder = SamHQVisionEncoder(config)
self.post_init()
def get_input_embeddings(self) -> nn.Module:
... | SamHQVisionModel |
python | Textualize__textual | src/textual/drivers/win32.py | {
"start": 1679,
"end": 2015
} | class ____(Structure):
"""https://docs.microsoft.com/en-us/windows/console/key-event-record-str"""
_fields_ = [
("bKeyDown", BOOL),
("wRepeatCount", WORD),
("wVirtualKeyCode", WORD),
("wVirtualScanCode", WORD),
("uChar", uChar),
("dwControlKeyState", DWORD),
... | KEY_EVENT_RECORD |
python | django__django | tests/from_db_value/models.py | {
"start": 47,
"end": 99
} | class ____(decimal.Decimal):
currency = "USD"
| Cash |
python | bokeh__bokeh | src/bokeh/plotting/contour.py | {
"start": 2168,
"end": 2378
} | class ____:
''' Coordinates for all filled polygons over a whole sequence of contour levels.
'''
xs: list[list[list[np.ndarray]]]
ys: list[list[list[np.ndarray]]]
@dataclass(frozen=True)
| FillCoords |
python | pytransitions__transitions | transitions/extensions/asyncio.py | {
"start": 12606,
"end": 25847
} | class ____(Machine):
"""Machine manages states, transitions and models. In case it is initialized without a specific model
(or specifically no model), it will also act as a model itself. Machine takes also care of decorating
models with conveniences functions related to added transitions and states during r... | AsyncMachine |
python | django-import-export__django-import-export | tests/core/admin.py | {
"start": 2317,
"end": 2401
} | class ____(ExportActionModelAdmin):
pass
@admin.register(Author)
| UUIDCategoryAdmin |
python | altair-viz__altair | altair/utils/server.py | {
"start": 572,
"end": 709
} | class ____:
def makefile(self, *args, **kwargs):
return IO(b"GET /")
def sendall(self, response):
pass
| MockRequest |
python | kamyu104__LeetCode-Solutions | Python/two-sum-ii-input-array-is-sorted.py | {
"start": 29,
"end": 373
} | class ____(object):
def twoSum(self, nums, target):
start, end = 0, len(nums) - 1
while start != end:
sum = nums[start] + nums[end]
if sum > target:
end -= 1
elif sum < target:
start += 1
else:
return [s... | Solution |
python | walkccc__LeetCode | solutions/3458. Select K Disjoint Special Substrings/3458.py | {
"start": 0,
"end": 870
} | class ____:
def maxSubstringLength(self, s: str, k: int) -> bool:
n = len(s)
first = [n] * 26
last = [-1] * 26
# dp[i] := the maximum disjoint special substrings for the first i letters
dp = [0] * (n + 1)
seenOrder = []
for i, c in enumerate(s):
a = ord(c) - ord('a')
if first[... | Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 120231,
"end": 124516
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("pipeline_job.PipelineJobHook"))
@mock.patch("google.cloud.aiplatform_v1.types.PipelineJob.to_dict")
def test_execute(self, to_dict_mock, mock_hook):
op = RunPipelineJobOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
... | TestVertexAIRunPipelineJobOperator |
python | pydantic__pydantic | tests/test_forward_ref.py | {
"start": 16411,
"end": 17036
} | class ____(BaseModel):
foo_user: FooUser
user: User
@field_serializer('user')
def serialize_user(self, v):
return f'User({v.y})'
"""
)
m = module.Model(foo_user={'x': 'user1'}, user={'y': 'user2'})
# TODO: How can we replicate this custom-encoder functionality without affecting th... | Model |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 997211,
"end": 997987
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for TeamDiscussionComment."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("TeamDiscussionCommentEdge"), graphql_name="edges")
"""A list of e... | TeamDiscussionCommentConnection |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-nvidia-triton/llama_index/llms/nvidia_triton/utils.py | {
"start": 1877,
"end": 3076
} | class ____(Queue):
"""A Generator that provides the inference results from an LLM."""
def __init__(
self,
client: "GrpcTritonClient",
request_id: str,
force_batch: bool,
model_name: str,
max_tokens: int,
) -> None:
"""Instantiate the generator class."... | StreamingResponseGenerator |
python | django__django | tests/modeladmin/models.py | {
"start": 548,
"end": 983
} | class ____(models.Model):
main_band = models.ForeignKey(Band, models.CASCADE, related_name="main_concerts")
opening_band = models.ForeignKey(
Band, models.CASCADE, related_name="opening_concerts", blank=True
)
day = models.CharField(max_length=3, choices=((1, "Fri"), (2, "Sat")))
transport =... | Concert |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-non-overlapping-substrings.py | {
"start": 1207,
"end": 2446
} | class ____(object):
def maxNumOfSubstrings(self, s):
"""
:type s: str
:rtype: List[str]
"""
def find_right_from_left(s, first, last, left):
right, i = last[ord(s[left])-ord('a')], left
while i <= right:
if first[ord(s[i])-ord('a')] < le... | Solution2 |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 8941,
"end": 9545
} | class ____(SpanToken):
"""
Span-level HTML token.
This is an inline token without children.
Attributes:
content (str): the raw HTML content.
"""
pattern = re.compile('|'.join([_open_tag, _closing_tag, _comment,
_instruction, _declaration, _cdata]),
... | HtmlSpan |
python | getsentry__sentry | src/sentry/auth/providers/saml2/activedirectory/provider.py | {
"start": 80,
"end": 197
} | class ____(GenericSAML2Provider):
name = "Active Directory"
key = "active-directory"
| ActiveDirectorySAML2Provider |
python | xlwings__xlwings | xlwings/_xlwindows.py | {
"start": 22427,
"end": 24202
} | class ____(base_classes.Books):
def __init__(self, xl, app):
self.xl = xl
self.app = app
@property
def api(self):
return self.xl
@property
def active(self):
return Book(self.xl.Application.ActiveWorkbook)
def __call__(self, name_or_index):
try:
... | Books |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-sheets/unit_tests/integration/conftest/request_builder.py | {
"start": 304,
"end": 1636
} | class ____:
@classmethod
def get_account_endpoint(cls) -> RequestBuilder:
return cls(resource="values:batchGet")
def __init__(self, resource: str = None) -> None:
self._spreadsheet_id = None
self._query_params = {}
self._body = None
self.resource = resource
def ... | RequestBuilder |
python | dateutil__dateutil | src/dateutil/tz/tz.py | {
"start": 5055,
"end": 8940
} | class ____(_tzinfo):
"""
A :class:`tzinfo` subclass built around the ``time`` timezone functions.
"""
def __init__(self):
super(tzlocal, self).__init__()
self._std_offset = datetime.timedelta(seconds=-time.timezone)
if time.daylight:
self._dst_offset = datetime.timed... | tzlocal |
python | pytest-dev__pytest | src/_pytest/config/__init__.py | {
"start": 3298,
"end": 7103
} | class ____(Exception):
def __init__(
self,
path: pathlib.Path,
*,
cause: Exception,
) -> None:
self.path = path
self.cause = cause
def __str__(self) -> str:
return f"{type(self.cause).__name__}: {self.cause} (from {self.path})"
def filter_traceback_... | ConftestImportFailure |
python | davidhalter__jedi | jedi/inference/value/instance.py | {
"start": 18087,
"end": 19062
} | class ____(TreeNameDefinition):
"""
This name calculates the parent_context lazily.
"""
def __init__(self, instance, class_context, tree_name):
self._instance = instance
self.class_context = class_context
self.tree_name = tree_name
@property
def parent_context(self):
... | SelfName |
python | dask__dask | dask/dataframe/dask_expr/_merge.py | {
"start": 28397,
"end": 28618
} | class ____(Merge):
def _lower(self):
# This is cheap and avoids shuffling unnecessary data
right = DropDuplicatesBlockwise(self.right)
return Merge(self.left, right, *self.operands[2:])
| SemiMerge |
python | pypa__pip | src/pip/_internal/utils/temp_dir.py | {
"start": 6597,
"end": 9307
} | class ____(TempDirectory):
"""Helper class that creates a temporary directory adjacent to a real one.
Attributes:
original
The original directory to create a temp directory for.
path
After calling create() or entering, contains the full
path to the temporary ... | AdjacentTempDirectory |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 23845,
"end": 26540
} | class ____(Request):
"""
Create a new queue
:param name: Queue name Unique within the company.
:type name: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for system use,
please don't use it.
:type sy... | CreateRequest |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/utils/config.py | {
"start": 32964,
"end": 33434
} | class ____:
"""
Configuration for the CUDA stream pool.
Parameters
----------
pool_size
The size of the CUDA stream pool.
flags
The flags to use for the CUDA stream pool.
"""
pool_size: int = 16
flags: CudaStreamFlags = CudaStreamFlags.NON_BLOCKING
def build(se... | CUDAStreamPoolConfig |
python | RaRe-Technologies__gensim | gensim/models/ldaseqmodel.py | {
"start": 28864,
"end": 48810
} | class ____(utils.SaveLoad):
"""Encapsulate the inner State Space Language Model for DTM.
Some important attributes of this class:
* `obs` is a matrix containing the document to topic ratios.
* `e_log_prob` is a matrix containing the topic to word ratios.
* `mean` contains the mean valu... | sslm |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 245862,
"end": 248174
} | class ____(GeneratedAirbyteSource):
class AuthenticateViaHarvestOAuth:
@public
def __init__(
self,
client_id: str,
client_secret: str,
refresh_token: str,
auth_type: Optional[str] = None,
):
self.auth_type = check.opt_st... | HarvestSource |
python | scikit-image__scikit-image | src/skimage/_shared/utils.py | {
"start": 16210,
"end": 18239
} | class ____:
"""Class to indicate a failed transform estimation.
The ``from_estimate`` class method of each transform type may return an
instance of this class to indicate some failure in the estimation process.
Parameters
----------
message : str
Message indicating reason for failed es... | FailedEstimation |
python | tensorflow__tensorflow | tensorflow/python/training/monitored_session.py | {
"start": 38115,
"end": 41522
} | class ____(_MonitoredSession):
"""Session-like object that handles initialization, recovery and hooks.
Example usage:
```python
saver_hook = CheckpointSaverHook(...)
summary_hook = SummarySaverHook(...)
with MonitoredSession(session_creator=ChiefSessionCreator(...),
hooks=[saver_ho... | MonitoredSession |
python | getsentry__sentry | src/sentry/apidocs/parameters.py | {
"start": 30193,
"end": 30431
} | class ____:
DASHBOARD_ID = OpenApiParameter(
name="dashboard_id",
location="path",
required=True,
type=int,
description="""The ID of the dashboard you'd like to retrieve.""",
)
| DashboardParams |
python | pypa__pipenv | pipenv/patched/pip/_internal/commands/show.py | {
"start": 918,
"end": 1920
} | class ____(Command):
"""
Show information about one or more installed packages.
The output is in RFC-compliant mail header format.
"""
usage = """
%prog [options] <package> ..."""
ignore_require_venv = True
def add_options(self) -> None:
self.cmd_opts.add_option(
... | ShowCommand |
python | catalyst-team__catalyst | catalyst/engines/torch.py | {
"start": 1234,
"end": 5867
} | class ____(Engine):
"""Distributed multi-GPU-based engine.
Args:
*args: args for Accelerator.__init__
address: master node (rank 0)'s address,
should be either the IP address or the hostname
of node 0, for single node multi-proc training, can simply be 127.0.0.1
... | DistributedDataParallelEngine |
python | Lightning-AI__lightning | tests/tests_fabric/utilities/test_registry.py | {
"start": 238,
"end": 2105
} | class ____:
"""A callback in another library that gets registered through entry points."""
pass
def test_load_external_callbacks():
"""Test that the connector collects Callback instances from factories registered through entry points."""
def factory_no_callback():
return []
def factory_... | ExternalCallback |
python | joke2k__faker | tests/providers/test_phone_number.py | {
"start": 5859,
"end": 6660
} | class ____:
"""Test de_CH phone number provider methods"""
pattern: Pattern = re.compile(r"(\+41|0) ?(?P<dialing_code>\d{2}) \d{3} \d{2} \d{2}")
def test_phone_number(self, faker, num_samples):
for _ in range(num_samples):
phone_number = faker.phone_number()
assert self.pat... | TestDeCh |
python | PyCQA__pycodestyle | pycodestyle.py | {
"start": 67932,
"end": 80804
} | class ____:
"""Load a Python source file, tokenize it, check coding style."""
def __init__(self, filename=None, lines=None,
options=None, report=None, **kwargs):
if options is None:
options = StyleGuide(kwargs).options
else:
assert not kwargs
sel... | Checker |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 85492,
"end": 86021
} | class ____(WebTestCase):
def get_handlers(self):
return [("/foo", RequestHandler)]
def get_app_kwargs(self):
class Custom404Handler(RequestHandler):
def get(self):
self.set_status(404)
self.write("custom 404 response")
return dict(default_han... | Custom404Test |
python | pytorch__pytorch | benchmarks/tensorexpr/reduction.py | {
"start": 7666,
"end": 8286
} | class ____(DynamicReduce2DBench):
def __init__(self, mode, device, dtype, dim0, dim1):
super().__init__(mode, device, dtype, 0, dim0, dim1)
@staticmethod
def default_configs():
parent_config = DynamicReduce2DBench.default_configs()[0]
return [parent_config[1:]]
def config(self)... | DynamicReduce2DOuterBench |
python | readthedocs__readthedocs.org | readthedocs/projects/models.py | {
"start": 3635,
"end": 5104
} | class ____(models.Model):
"""
Project to project relationship.
This is used for subprojects.
Terminology: We should say main project and subproject.
Saying "child" and "parent" only has internal, technical value.
"""
parent = models.ForeignKey(
"projects.Project",
verbose_... | ProjectRelationship |
python | PrefectHQ__prefect | tests/test_serializers.py | {
"start": 5716,
"end": 13171
} | class ____:
@pytest.mark.parametrize("data", SERIALIZER_TEST_CASES)
def test_simple_roundtrip(self, data: Any):
serializer = JSONSerializer()
serialized = serializer.dumps(data)
assert serializer.loads(serialized) == data
@pytest.mark.parametrize("data", EXCEPTION_TEST_CASES)
de... | TestJSONSerializer |
python | pytorch__pytorch | torch/distributed/_tools/ilp_utils.py | {
"start": 594,
"end": 2080
} | class ____(TypedDict):
fqn: str
# per-module params
param_per_module: int
# per-module grads
grad_per_module: int
# total accumulated gradients up to and including this module
grad_total: int
# per module fw activation size (excluding input and output)
act_fw_per_module: int
# pe... | ModStats |
python | huggingface__transformers | src/transformers/models/llama/tokenization_llama.py | {
"start": 1661,
"end": 7565
} | class ____(TokenizersBackend):
"""
Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.
This uses notably ByteFallback and no normalization.
```python
>>> from transformers import LlamaTokenizer
>>> tokenizer = LlamaTokenizer.from_pretrained("hf-internal-testing/llama-tokenize... | LlamaTokenizer |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/data_utils.py | {
"start": 12884,
"end": 16922
} | class ____(object):
"""Base object for fitting to a sequence of data, such as a dataset.
Every `Sequence` must implement the `__getitem__` and the `__len__` methods.
If you want to modify your dataset between epochs you may implement
`on_epoch_end`.
The method `__getitem__` should return a complete batch.
... | Sequence |
python | kamyu104__LeetCode-Solutions | Python/number-of-changing-keys.py | {
"start": 38,
"end": 238
} | class ____(object):
def countKeyChanges(self, s):
"""
:type s: str
:rtype: int
"""
return sum(s[i].lower() != s[i+1].lower() for i in xrange(len(s)-1))
| Solution |
python | eventlet__eventlet | eventlet/green/http/client.py | {
"start": 57274,
"end": 57442
} | class ____(Exception):
# Subclasses that define an __init__ must call Exception.__init__
# or define self.args. Otherwise, str() will fail.
pass
| HTTPException |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_table03.py | {
"start": 315,
"end": 1708
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_table03.xlsx")
self.ignore_elements = {"xl/charts/chart1.xml": ["<a:pPr"]}
def test_create_file(self):
"""Test XlsxWriter ch... | TestCompareXLSXFiles |
python | django__django | tests/db_functions/text/test_reverse.py | {
"start": 250,
"end": 2367
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.john = Author.objects.create(name="John Smith", alias="smithj")
cls.elena = Author.objects.create(name="Élena Jordan", alias="elena")
cls.python = Author.objects.create(name="パイソン")
def test_null(self):
author = ... | ReverseTests |
python | kubernetes-client__python | kubernetes/client/models/v1_rbd_volume_source.py | {
"start": 383,
"end": 10731
} | 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... | V1RBDVolumeSource |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 51085,
"end": 54095
} | class ____:
def setup_method(self):
self.rng = np.random.default_rng(7672986002)
def test_rvs(self):
vals = stats.geom.rvs(0.75, size=(2, 50), random_state=self.rng)
assert_(np.all(vals >= 0))
assert_(np.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes['AllIn... | TestGeom |
python | ray-project__ray | python/ray/autoscaler/local/coordinator_server.py | {
"start": 2545,
"end": 4471
} | class ____(threading.Thread):
"""Initializes HTTPServer and serves CoordinatorSenderNodeProvider forever.
It handles requests from the remote CoordinatorSenderNodeProvider. The
requests are forwarded to LocalNodeProvider function calls.
"""
def __init__(self, list_of_node_ips, host, port):
... | OnPremCoordinatorServer |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/error_utils.py | {
"start": 4376,
"end": 4663
} | class ____(KeyError):
def __init__(self, message, original_key):
super(MultilineMessageKeyError, self).__init__(original_key)
self.__message = message
def __str__(self):
return self.__message
MultilineMessageKeyError.__name__ = KeyError.__name__
| MultilineMessageKeyError |
python | sqlalchemy__sqlalchemy | test/base/test_except.py | {
"start": 13768,
"end": 17300
} | class ____(Exception):
def __init__(self, msg):
self.msg = msg
def __eq__(self, other):
return isinstance(other, EqException) and other.msg == self.msg
ALL_EXC = [
(
[sa_exceptions.SQLAlchemyError],
[lambda cls: cls(1, 2, code="42")],
),
([sa_exceptions.ObjectNotEx... | EqException |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip_text.py | {
"start": 15072,
"end": 18745
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([BlipTextLayer(config, i) for i in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
hidden_states: torch.... | BlipTextEncoder |
python | django__django | tests/model_fields/tests.py | {
"start": 15957,
"end": 17187
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.foo1 = Foo.objects.create(a="a", d="12.34")
cls.foo2 = Foo.objects.create(a="b", d="12.34")
cls.bar1 = Bar.objects.create(a=cls.foo1, b="b")
cls.bar2 = Bar.objects.create(a=cls.foo2, b="a")
cls.field = Bar._me... | GetChoicesLimitChoicesToTests |
python | pola-rs__polars | py-polars/src/polars/io/iceberg/dataset.py | {
"start": 18005,
"end": 19553
} | class ____(_ResolvedScanDataBase):
"""Resolved parameters for a native Iceberg scan."""
sources: list[str]
projected_iceberg_schema: pyiceberg.schema.Schema
column_mapping: pa.Schema
default_values: dict[int, pl.Series | str]
deletion_files: dict[int, list[str]]
min_max_statistics: pl.DataF... | _NativeIcebergScanData |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess18.py | {
"start": 319,
"end": 663
} | class ____(Generic[_T]):
thing: _T
def __getitem__(self, key: str) -> _T:
return self.thing
def __getattr__(self, key: str) -> _T:
return self.thing
c1: CollectionThing[Descriptor] = CollectionThing()
reveal_type(c1["key"], expected_text="Descriptor")
reveal_type(c1.key, expected_text="... | CollectionThing |
python | tensorflow__tensorflow | tensorflow/lite/python/lite.py | {
"start": 70729,
"end": 76773
} | class ____(TFLiteConverterBaseV2):
"""Converts the given frozen graph into TensorFlow Lite model."""
def __init__(self, funcs, trackable_obj=None):
"""Constructor for TFLiteConverter.
Args:
funcs: List of TensorFlow ConcreteFunctions. The list should not contain
duplicate elements.
tra... | TFLiteFrozenGraphConverterV2 |
python | scikit-learn__scikit-learn | sklearn/_loss/link.py | {
"start": 5197,
"end": 5593
} | class ____(BaseLink):
"""Half the logit link function g(x)=1/2 * logit(x).
Used for the exponential loss.
"""
interval_y_pred = Interval(0, 1, False, False)
def link(self, y_pred, out=None):
out = logit(y_pred, out=out)
out *= 0.5
return out
def inverse(self, raw_pred... | HalfLogitLink |
python | pypa__setuptools | setuptools/_vendor/typeguard/_memo.py | {
"start": 130,
"end": 1303
} | class ____:
"""
Contains information necessary for type checkers to do their work.
.. attribute:: globals
:type: dict[str, Any]
Dictionary of global variables to use for resolving forward references.
.. attribute:: locals
:type: dict[str, Any]
Dictionary of local variab... | TypeCheckMemo |
python | walkccc__LeetCode | solutions/1408. String Matching in an Array/1408-2.py | {
"start": 0,
"end": 84
} | class ____:
def __init__(self):
self.children: dict[str, TrieNode] = {}
| TrieNode |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_sequence.py | {
"start": 6040,
"end": 9704
} | class ____(fixtures.TablesTest):
run_deletes = None
__requires__ = ("sequences",)
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
normalize_sequence(config, Sequence("user_id_seq", metadata=metadata))
normalize_sequence(
config,
... | HasSequenceTest |
python | numpy__numpy | numpy/matrixlib/tests/test_defmatrix.py | {
"start": 6906,
"end": 8601
} | class ____:
def test_basic(self):
import numpy.linalg as linalg
A = np.array([[1., 2.], [3., 4.]])
mA = matrix(A)
B = np.identity(2)
for i in range(6):
assert_(np.allclose((mA ** i).A, B))
B = np.dot(B, A)
Ainv = linalg.inv(A)
B = np... | TestAlgebra |
python | pandas-dev__pandas | asv_bench/benchmarks/io/json.py | {
"start": 2811,
"end": 5168
} | class ____(BaseIO):
fname = "__test__.json"
params = [
["split", "columns", "index", "values", "records"],
["df", "df_date_idx", "df_td_int_ts", "df_int_floats", "df_int_float_str"],
]
param_names = ["orient", "frame"]
def setup(self, orient, frame):
N = 10**5
ncols ... | ToJSON |
python | PyCQA__pylint | tests/utils/unittest_ast_walker.py | {
"start": 478,
"end": 2877
} | class ____:
class MockLinter:
def __init__(self, msgs: dict[str, bool]) -> None:
self._msgs = msgs
def is_message_enabled(self, msgid: str) -> bool:
return self._msgs.get(msgid, True)
class Checker(BaseChecker):
# pylint: disable-next=super-init-not-called
... | TestASTWalker |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.