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 | huggingface__transformers | src/transformers/models/diffllama/configuration_diffllama.py | {
"start": 935,
"end": 7931
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DiffLlamaModel`]. It is used to instantiate an DiffLlama
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults
will yield a similar ... | DiffLlamaConfig |
python | pytorch__pytorch | test/inductor/test_compiled_autograd.py | {
"start": 204027,
"end": 206513
} | class ____(TestCase):
def setUp(self) -> None:
super(TestCase, self).setUp()
reset()
def tearDown(self) -> None:
super(TestCase, self).tearDown()
reset()
@skipIfXpu(msg="NotImplementedError: The operator 'testlib::mutating_custom_op'")
@ops(
list(filter(lambda o... | TestCompiledAutogradOpInfo |
python | RaRe-Technologies__gensim | gensim/test/test_utils.py | {
"start": 8493,
"end": 9680
} | class ____(unittest.TestCase):
def test_save_as_line_sentence_en(self):
corpus_file = get_tmpfile('gensim_utils.tst')
ref_sentences = [
line.split()
for line in utils.any2unicode('hello world\nhow are you').split('\n')
]
utils.save_as_line_sentence(ref_senten... | TestSaveAsLineSentence |
python | ipython__ipython | IPython/core/completer.py | {
"start": 63607,
"end": 136627
} | class ____(Completer):
"""Extension of the completer class with IPython-specific features"""
@observe('greedy')
def _greedy_changed(self, change):
"""update the splitter and readline delims when greedy is changed"""
if change["new"]:
self.evaluation = "unsafe"
self.a... | IPCompleter |
python | getsentry__sentry | src/sentry/relay/config/metric_extraction.py | {
"start": 34652,
"end": 35554
} | class ____(TypedDict):
condition: RuleCondition
targetMetrics: Sequence[str]
targetTag: str
tagValue: str
_TRANSACTION_METRICS_TO_RULE_FIELD = {
TransactionMetric.LCP.value: "event.measurements.lcp.value",
TransactionMetric.DURATION.value: "event.duration",
}
_SATISFACTION_TARGET_METRICS = (
... | MetricConditionalTaggingRule |
python | walkccc__LeetCode | solutions/106. Construct Binary Tree from Inorder and Postorder Traversal/106.py | {
"start": 0,
"end": 805
} | class ____:
def buildTree(
self,
inorder: list[int],
postorder: list[int],
) -> TreeNode | None:
inToIndex = {num: i for i, num in enumerate(inorder)}
def build(
inStart: int,
inEnd: int,
postStart: int,
postEnd: int,
) -> TreeNode | None:
if inSt... | Solution |
python | huggingface__transformers | templates/adding_a_new_example_script/{{cookiecutter.directory_name}}/run_{{cookiecutter.example_shortcut}}.py | {
"start": 3077,
"end": 4965
} | class ____:
"""
Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
"""
model_name_or_path: str = field(
metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
)
config_name: Optional[str] = field(
default=No... | ModelArguments |
python | networkx__networkx | networkx/algorithms/community/tests/test_kclique.py | {
"start": 786,
"end": 2413
} | class ____:
def setup_method(self):
self.G = nx.karate_club_graph()
def _check_communities(self, k, expected):
communities = set(nx.community.k_clique_communities(self.G, k))
assert communities == expected
def test_k2(self):
# clique percolation with k=2 is just connected c... | TestZacharyKarateClub |
python | sympy__sympy | sympy/codegen/cfunctions.py | {
"start": 11874,
"end": 12102
} | class ____(BooleanFunction):
nargs = 1
@classmethod
def eval(cls, arg):
if arg is S.NaN:
return true
elif arg.is_number:
return false
else:
return None
| isnan |
python | getsentry__sentry | src/sentry/analytics/events/sentry_app_installed.py | {
"start": 77,
"end": 233
} | class ____(analytics.Event):
user_id: int
organization_id: int
sentry_app: str
analytics.register(SentryAppInstalledEvent)
| SentryAppInstalledEvent |
python | weaviate__weaviate-python-client | weaviate/collections/classes/tenants.py | {
"start": 3691,
"end": 3906
} | class ____(Tenant): # noqa: D101
"""Wrapper around Tenant for output purposes."""
def model_post_init(self, __context: Any) -> None: # noqa: D102
self._model_post_init(user_input=False)
| TenantOutput |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 15391,
"end": 20154
} | class ____(TruetypeFonts):
"""
Use the Bakoma TrueType fonts for rendering.
Symbols are strewn about a number of font files, each of which has
its own proprietary 8-bit encoding.
"""
_fontmap = {
'cal': 'cmsy10',
'rm': 'cmr10',
'tt': 'cmtt10',
'it': 'cmmi10',
... | BakomaFonts |
python | tensorflow__tensorflow | tensorflow/compiler/tests/image_ops_test.py | {
"start": 39121,
"end": 48981
} | class ____(xla_test.XLATestCase):
def testNMSV3(self):
boxes_data = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9],
[0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]]
boxes_np = np.array(boxes_data, dtype=np.float32)
scores_data = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]
scores_np =... | NonMaxSuppressionTest |
python | huggingface__transformers | src/transformers/models/visual_bert/modeling_visual_bert.py | {
"start": 13262,
"end": 14524
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = VisualBertAttention(config)
self.intermediate = VisualBertIntermediate(config)
se... | VisualBertLayer |
python | walkccc__LeetCode | solutions/718. Maximum Length of Repeated Subarray/718.py | {
"start": 0,
"end": 481
} | class ____:
def findLength(self, nums1: list[int], nums2: list[int]) -> int:
m = len(nums1)
n = len(nums2)
ans = 0
# dp[i][j] := the maximum length of a subarray that appears in both
# nums1[i..m) and nums2[j..n)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in reversed(range(m)):
... | Solution |
python | docker__docker-py | tests/unit/api_volume_test.py | {
"start": 139,
"end": 3886
} | class ____(BaseAPIClientTest):
def test_list_volumes(self):
volumes = self.client.volumes()
assert 'Volumes' in volumes
assert len(volumes['Volumes']) == 2
args = fake_request.call_args
assert args[0][0] == 'GET'
assert args[0][1] == f"{url_prefix}volumes"
def t... | VolumeTest |
python | django__django | tests/admin_inlines/models.py | {
"start": 2468,
"end": 2616
} | class ____(models.Model):
dummy = models.IntegerField()
holder = models.ForeignKey(Holder3, models.CASCADE)
# Models for ticket #8190
| Inner3 |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/numerics_test.py | {
"start": 1255,
"end": 2535
} | class ____(test.TestCase):
def testVerifyTensorAllFiniteSucceeds(self):
x_shape = [5, 4]
x = np.random.random_sample(x_shape).astype(np.float32)
with test_util.use_gpu():
t = constant_op.constant(x, shape=x_shape, dtype=dtypes.float32)
t_verified = numerics.verify_tensor_all_finite(t,
... | VerifyTensorAllFiniteTest |
python | pytest-dev__pytest | testing/test_monkeypatch.py | {
"start": 6017,
"end": 9660
} | class ____:
"""
os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably
subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing
and raises an error.
"""
VAR_NAME = "PYTEST_INTERNAL_MY... | TestEnvironWarnings |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 51237,
"end": 53024
} | class ____(Request):
"""
Gets queue information
:param queue: Queue ID
:type queue: str
:param max_task_entries: Max number of queue task entries to return
:type max_task_entries: int
"""
_service = "queues"
_action = "get_by_id"
_version = "2.23"
_schema = {
"defin... | GetByIdRequest |
python | keras-team__keras | keras/src/losses/losses_test.py | {
"start": 30955,
"end": 34032
} | class ____(testing.TestCase):
def setup(self):
self.y_pred = np.asarray(
[0.4, 0.9, 0.12, 0.36, 0.3, 0.4], dtype=np.float32
).reshape((2, 3))
self.y_true = np.asarray(
[0.5, 0.8, 0.12, 0.7, 0.43, 0.8], dtype=np.float32
).reshape((2, 3))
self.batch_siz... | KLDivergenceTest |
python | viewflow__viewflow | viewflow/templatetags/viewflow.py | {
"start": 3445,
"end": 3855
} | class ____(BaseViewsetURLNode):
"""
Reverse a url to a view within viewset
Example::
{% reverse viewset viewname args kwargs %}
"""
def _reverse_url(self, viewset, view_name, args, kwargs, current_app, context):
return viewset.reverse(
view_name, args=args, kwargs=kwarg... | ViewsetURLNode |
python | walkccc__LeetCode | solutions/421. Maximum XOR of Two Numbers in an Array/421-2.py | {
"start": 854,
"end": 1167
} | class ____:
def findMaximumXOR(self, nums: list[int]) -> int:
maxNum = max(nums)
if maxNum == 0:
return 0
maxBit = int(math.log2(maxNum))
ans = 0
bitTrie = BitTrie(maxBit)
for num in nums:
ans = max(ans, bitTrie.getMaxXor(num))
bitTrie.insert(num)
return ans
| Solution |
python | kubernetes-client__python | kubernetes/base/leaderelection/resourcelock/configmaplock.py | {
"start": 850,
"end": 5857
} | class ____:
def __init__(self, name, namespace, identity):
"""
:param name: name of the lock
:param namespace: namespace
:param identity: A unique identifier that the candidate is using
"""
self.api_instance = client.CoreV1Api()
self.leader_electionrecord_anno... | ConfigMapLock |
python | mlflow__mlflow | dev/clint/tests/rules/test_mlflow_class_name.py | {
"start": 377,
"end": 450
} | class ____:
pass
# Bad - nested occurrence of MLFlow
| CustomMLflowHandler |
python | doocs__leetcode | solution/1100-1199/1180.Count Substrings with Only One Distinct Letter/Solution2.py | {
"start": 0,
"end": 313
} | class ____:
def countLetters(self, s: str) -> int:
ans = 0
i, n = 0, len(s)
while i < n:
j = i
cnt = 0
while j < n and s[j] == s[i]:
j += 1
cnt += 1
ans += cnt
i = j
return ans
| Solution |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 3732,
"end": 6317
} | class ____(rv_continuous):
r"""Kolmogorov-Smirnov one-sided test statistic distribution.
This is the distribution of the one-sided Kolmogorov-Smirnov (KS)
statistics :math:`D_n^+` and :math:`D_n^-`
for a finite sample size ``n >= 1`` (the shape parameter).
%(before_notes)s
See Also
------... | ksone_gen |
python | plotly__plotly.py | tests/test_optional/test_tools/test_figure_factory.py | {
"start": 4118,
"end": 29438
} | class ____(TestCaseNoTemplate, NumpyTestUtilsMixin):
def test_unequal_ohlc_length(self):
# check: PlotlyError if open, high, low, close are not the same length
# for TraceFactory.create_ohlc and TraceFactory.create_candlestick
kwargs = {
"open": [1],
"high": [1, 3],
... | TestFinanceCharts |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_points02.py | {
"start": 315,
"end": 1299
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_points02.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with point formatting."""
workbook = ... | TestCompareXLSXFiles |
python | neetcode-gh__leetcode | python/1514-path-with-maximum-probability.py | {
"start": 0,
"end": 699
} | class ____:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
adj = collections.defaultdict(list)
for i in range(len(edges)):
src, dst = edges[i]
adj[src].append([dst, succProb[i]])
adj[dst].append([src... | Solution |
python | python__mypy | mypy/test/teststubgen.py | {
"start": 4483,
"end": 5119
} | class ____(unittest.TestCase):
def test_walk_packages(self) -> None:
with ModuleInspect() as m:
assert_equal(set(walk_packages(m, ["mypy.errors"])), {"mypy.errors"})
assert_equal(
set(walk_packages(m, ["mypy.errors", "mypy.stubgen"])),
{"mypy.errors",... | StubgenCliParseSuite |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0087_relink_crons_to_compatible_issue_workflows.py | {
"start": 1338,
"end": 1616
} | class ____:
"""Represents an action with its type and config."""
type: str
config: dict[str, Any]
def to_dict(self) -> dict[str, Any]:
return {
"type": self.type,
"config": self.config,
}
@dataclass(frozen=True)
| ActionData |
python | sphinx-doc__sphinx | sphinx/builders/latex/util.py | {
"start": 117,
"end": 1703
} | class ____(Babel):
cyrillic_languages = ('bulgarian', 'kazakh', 'mongolian', 'russian', 'ukrainian')
def __init__(self, language_code: str, use_polyglossia: bool = False) -> None:
self.language_code = language_code
self.use_polyglossia = use_polyglossia
self.supported = True
sup... | ExtBabel |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 94037,
"end": 96057
} | class ____:
def test_format_timeframe(self):
# Now
assert self.locale._format_timeframe("now", 0) == "sada"
# Second(s)
assert self.locale._format_timeframe("second", 1) == "sekundu"
assert self.locale._format_timeframe("seconds", 3) == "3 sekunde"
assert self.locale... | TestSerbianLocale |
python | nedbat__coveragepy | tests/plugin1.py | {
"start": 1578,
"end": 1932
} | class ____(FileReporter):
"""Dead-simple FileReporter."""
def lines(self) -> set[TLineNo]:
return {105, 106, 107, 205, 206, 207}
def coverage_init(
reg: Plugins,
options: Any, # pylint: disable=unused-argument
) -> None:
"""Called by coverage to initialize the plugins here."""
reg.ad... | MyFileReporter |
python | scipy__scipy | benchmarks/benchmarks/spatial.py | {
"start": 17945,
"end": 18568
} | class ____(Benchmark):
params = [10, 1000, 10000]
param_names = ['num_points']
def setup(self, num_points):
points = generate_spherical_points(50)
# any two points from the random spherical points
# will suffice for the interpolation bounds:
self.start = points[0]
se... | GeometricSlerpBench |
python | ray-project__ray | python/ray/serve/_private/router.py | {
"start": 20846,
"end": 39735
} | class ____:
def __init__(
self,
controller_handle: ActorHandle,
deployment_id: DeploymentID,
handle_id: str,
self_actor_id: str,
handle_source: DeploymentHandleSource,
event_loop: asyncio.BaseEventLoop,
enable_strict_max_ongoing_requests: bool,
... | AsyncioRouter |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 783,
"end": 860
} | class ____(TypedDict):
userId: str
userType: str
| WeaviateUserAssignment |
python | getsentry__sentry | src/sentry/plugins/base/v1.py | {
"start": 691,
"end": 1248
} | class ____(type):
def __new__(cls, name, bases, attrs):
new_cls: type[IPlugin] = type.__new__(cls, name, bases, attrs) # type: ignore[assignment]
if IPlugin in bases:
return new_cls
if not hasattr(new_cls, "title"):
new_cls.title = new_cls.__name__
if not has... | PluginMount |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 114527,
"end": 117301
} | class ____(fixtures.TestBase):
__backend__ = True
__only_on__ = "postgresql"
__unsupported_on__ = ("postgresql+pg8000",)
@testing.combinations(
sqltypes.ARRAY, postgresql.ARRAY, argnames="array_cls"
)
@testing.combinations(
sqltypes.JSON, postgresql.JSON, postgresql.JSONB, argna... | ArrayJSON |
python | nryoung__algorithms | tests/test_sorting.py | {
"start": 3673,
"end": 3932
} | class ____(SortingAlgorithmTestCase):
"""
Test Selection sort on a small range from 0-9
"""
def test_selectionsort(self):
self.output = selection_sort.sort(self.input)
self.assertEqual(self.correct, self.output)
| TestSelectionort |
python | viewflow__viewflow | viewflow/jsonstore.py | {
"start": 7065,
"end": 7127
} | class ____(JSONFieldMixin, fields.TextField):
pass
| TextField |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 31146,
"end": 37100
} | class ____(multi_rv_frozen):
__class_getitem__ = None
def __init__(self, mean=None, cov=1, allow_singular=False, seed=None,
maxpts=None, abseps=1e-5, releps=1e-5):
"""Create a frozen multivariate normal distribution.
Parameters
----------
mean : array_like, def... | multivariate_normal_frozen |
python | pypa__hatch | tests/backend/builders/test_config.py | {
"start": 73583,
"end": 83663
} | class ____:
@pytest.mark.parametrize("separator", ["/", "\\"])
def test_default(self, isolation, separator, platform):
if separator == "\\" and not platform.windows:
pytest.skip("Not running on Windows")
builder = MockBuilder(str(isolation))
assert isinstance(builder.config... | TestPatternExclude |
python | eventlet__eventlet | eventlet/backdoor.py | {
"start": 891,
"end": 4043
} | class ____(greenlets.greenlet):
def __init__(self, desc, hostport, locals):
self.hostport = hostport
self.locals = locals
# mangle the socket
self.desc = FileProxy(desc)
greenlets.greenlet.__init__(self)
def run(self):
try:
console = InteractiveConsol... | SocketConsole |
python | jmcnamara__XlsxWriter | xlsxwriter/test/workbook/test_write_defined_names.py | {
"start": 299,
"end": 2618
} | class ____(unittest.TestCase):
"""
Test the Workbook _write_defined_names() method.
"""
def setUp(self):
self.fh = StringIO()
self.workbook = Workbook()
self.workbook._set_filehandle(self.fh)
def test_write_defined_names_1(self):
"""Test the _write_defined_names() ... | TestWriteDefinedNames |
python | openai__openai-python | src/openai/types/beta/realtime/realtime_server_event.py | {
"start": 3688,
"end": 5408
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
response_id: str
"""The unique ID of the response that produced the audio."""
type: Literal["output_audio_buffer.cleared"]
"""The event type, must be `output_audio_buffer.cleared`."""
RealtimeServerEvent: TypeAlias... | OutputAudioBufferCleared |
python | bokeh__bokeh | src/bokeh/core/property/data_frame.py | {
"start": 2851,
"end": 3539
} | class ____(Property["DataFrame"]):
""" Accept Pandas DataFrame values.
This class is pandas-specific - are more generic one is
``EagerDataFrame()``.
This property only exists to support type validation, e.g. for "accepts"
clauses. It is not serializable itself, and is not useful to add to
Boke... | PandasDataFrame |
python | ray-project__ray | python/ray/tune/utils/file_transfer.py | {
"start": 10935,
"end": 17431
} | class ____:
"""Actor wrapping around a packing job.
This actor is used for chunking the packed data into smaller chunks that
can be transferred via the object store more efficiently.
The actor will start packing the directory when initialized, and separate
chunks can be received by calling the rem... | _PackActor |
python | kamyu104__LeetCode-Solutions | Python/balance-a-binary-search-tree.py | {
"start": 66,
"end": 217
} | class ____(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# dfs solution with stack
| TreeNode |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/react/types.py | {
"start": 148,
"end": 410
} | class ____(BaseModel):
"""Reasoning step."""
@abstractmethod
def get_content(self) -> str:
"""Get content."""
@property
@abstractmethod
def is_done(self) -> bool:
"""Is the reasoning step the last one."""
| BaseReasoningStep |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 33717,
"end": 34101
} | class ____(IncrementalMixin, GithubStream):
"""
API docs: https://docs.github.com/en/rest/pulls/comments?apiVersion=2022-11-28#list-review-comments-in-a-repository
"""
use_cache = True
large_stream = True
def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:
return f... | ReviewComments |
python | realpython__materials | python-isinstance/balls.py | {
"start": 0,
"end": 106
} | class ____:
def __init__(self, color, shape):
self.color = color
self.shape = shape
| Ball |
python | kamyu104__LeetCode-Solutions | Python/cat-and-mouse.py | {
"start": 1767,
"end": 3945
} | class ____(object):
def catMouseGame(self, graph):
"""
:type graph: List[List[int]]
:rtype: int
"""
HOLE, MOUSE_START, CAT_START = range(3)
DRAW, MOUSE, CAT = range(3)
def parents(m, c, t):
if t == CAT:
for nm in graph[m]:
... | Solution2 |
python | walkccc__LeetCode | solutions/1558. Minimum Numbers of Function Calls to Make Target Array/1558.py | {
"start": 0,
"end": 190
} | class ____:
def minOperations(self, nums: list[int]) -> int:
mx = max(nums)
return (sum(num.bit_count() for num in nums) +
(0 if mx == 0 else mx.bit_length() - 1))
| Solution |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 3092,
"end": 3325
} | class ____:
def m3(self):
return _test_source() # Interval: (-∞,+∞) /\ [9,10] = [9,10]
def propagate_source_empty(c: C6):
return _test_sink(c.m1()) # Interval: [6,7] /\ [2,5] = Empty
"""
A7: [1,2]
B7: [3,4]
"""
| E6 |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_tags.py | {
"start": 456,
"end": 524
} | class ____(TransformerMixin, BaseEstimator):
pass
| EmptyTransformer |
python | pytorch__pytorch | test/distributed/tensor/test_common_rules.py | {
"start": 556,
"end": 16758
} | class ____(DTensorContinuousTestBase):
# hard code world size to 4 as we need to test
# at least with 2d mesh
world_size = 4
def _gen_tensor_meta(self, shape):
empty_tensor = torch.empty(shape)
return TensorMeta(
empty_tensor.shape,
empty_tensor.stride(),
... | CommonRulesTest |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_bash_code_execution_tool_result_error_param.py | {
"start": 241,
"end": 564
} | class ____(TypedDict, total=False):
error_code: Required[
Literal[
"invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded", "output_file_too_large"
]
]
type: Required[Literal["bash_code_execution_tool_result_error"]]
| BetaBashCodeExecutionToolResultErrorParam |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/reconstruct.py | {
"start": 5802,
"end": 6918
} | class ____(NamedTupleSerializer):
def before_unpack(self, _, unpacked_dict: dict[str, Any]) -> dict[str, Any]: # pyright: ignore[reportIncompatibleMethodOverride]
solid_selection_str = unpacked_dict.get("solid_selection_str")
solids_to_execute = unpacked_dict.get("solids_to_execute")
if sol... | ReconstructableJobSerializer |
python | joke2k__faker | faker/providers/person/ga_IE/__init__.py | {
"start": 265,
"end": 70554
} | class ____(PersonProvider):
formats = (
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}",
"{{first_name_male}} {{last_name}}-{{last_name}}",
"{{first_name_female}} {{last... | Provider |
python | getsentry__sentry | tests/sentry/api/endpoints/test_auth_login.py | {
"start": 197,
"end": 1753
} | class ____(APITestCase):
endpoint = "sentry-api-0-auth-login"
method = "post"
def setUp(self) -> None:
# Requests to set the test cookie
self.client.get(reverse("sentry-api-0-auth-config"))
def test_login_invalid_password(self) -> None:
response = self.get_error_response(
... | AuthLoginEndpointTest |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 149403,
"end": 150469
} | class ____(nn.Module):
def __init__(self, dim: int):
super().__init__()
self.dwconv = Qwen3OmniMoeCausalConvNet(
dim,
dim,
kernel_size=7,
groups=dim,
dilation=1,
)
self.norm = nn.LayerNorm(dim, eps=1e-6)
self.pwconv1... | Qwen3OmniMoeConvNeXtBlock |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 18552,
"end": 19062
} | class ____(GroupType):
type_id = 1021
slug = "query_injection_vulnerability"
description = "Potential Query Injection Vulnerability"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.DB_QUERY.value
enable_auto_resolve = False
enable_escalation_detection = False
noise... | QueryInjectionVulnerabilityGroupType |
python | huggingface__transformers | src/transformers/models/csm/modeling_csm.py | {
"start": 2425,
"end": 5633
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the lan... | CsmOutputWithPast |
python | falconry__falcon | tests/test_utils.py | {
"start": 25689,
"end": 46436
} | class ____:
"""Verify some branches not covered elsewhere."""
def test_path_escape_chars_in_create_environ(self):
env = testing.create_environ('/hello%20world%21')
assert env['PATH_INFO'] == '/hello world!'
def test_no_prefix_allowed_for_query_strings_in_create_environ(self):
with ... | TestFalconTestingUtils |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 146963,
"end": 147824
} | class ____(BaseModel):
index_name: Optional[str] = Field(default=None, description="")
unfiltered_plain: "OperationDurationStatistics" = Field(..., description="")
unfiltered_hnsw: "OperationDurationStatistics" = Field(..., description="")
unfiltered_sparse: "OperationDurationStatistics" = Field(..., de... | VectorIndexSearchesTelemetry |
python | run-llama__llama_index | llama-index-integrations/evaluation/llama-index-evaluation-tonic-validate/llama_index/evaluation/tonic_validate/augmentation_accuracy.py | {
"start": 364,
"end": 2000
} | class ____(BaseEvaluator):
"""
Tonic Validate's augmentation accuracy metric.
The output score is a float between 0.0 and 1.0.
See https://docs.tonic.ai/validate/ for more details.
Args:
openai_service(OpenAIService): The OpenAI service to use. Specifies the chat
completion mo... | AugmentationAccuracyEvaluator |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax_error.py | {
"start": 2811,
"end": 2929
} | class ____:
my_var: int | str # [unsupported-binary-operation]
@my_decorator
@dataclasses.dataclass
| CustomDataClass3 |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_dms.py | {
"start": 19081,
"end": 21304
} | class ____:
filter = [{"Name": "replication-type", "Values": ["cdc"]}]
def test_init(self):
op = DmsDescribeReplicationConfigsOperator(task_id="test_task")
assert op.filter is None
@pytest.mark.db_test
@mock.patch.object(DmsHook, "conn")
def test_template_fields_native(
sel... | TestDmsDescribeReplicationConfigsOperator |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/live.py | {
"start": 1044,
"end": 14270
} | class ____(JupyterMixin, RenderHook):
"""Renders an auto-updating live display of any given renderable.
Args:
renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.
console (Console, optional): Optional Console instance. Defaults to an internal Co... | Live |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 23762,
"end": 25644
} | class ____(SemiIncrementalMixin, GithubStream):
"""
API docs: https://docs.github.com/en/rest/pulls/pulls?apiVersion=2022-11-28#list-pull-requests
"""
use_cache = True
large_stream = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._first_read = True
def ... | PullRequests |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/control_flow/cond_v2_test.py | {
"start": 2438,
"end": 48258
} | class ____(test.TestCase):
def _testCond(self, true_fn, false_fn, train_vals, feed_dict=None):
if not feed_dict:
feed_dict = {}
with self.session(graph=ops.get_default_graph()) as sess:
pred = array_ops.placeholder(dtypes.bool, name="pred")
expected = tf_cond.cond(
array_ops.sque... | CondV2Test |
python | ray-project__ray | java/test/src/main/resources/test_cross_language_invocation.py | {
"start": 3329,
"end": 3541
} | class ____(object):
def __init__(self, value):
self.value = int(value)
def increase(self, delta):
self.value += int(delta)
return str(self.value).encode("utf-8")
@ray.remote
| Counter |
python | apache__airflow | airflow-core/tests/unit/utils/test_process_utils.py | {
"start": 5013,
"end": 6484
} | class ____:
def test_should_kill_process(self):
before_num_process = subprocess.check_output(["ps", "-ax", "-o", "pid="]).decode().count("\n")
process = multiprocessing.Process(target=my_sleep_subprocess, args=())
process.start()
sleep(0)
num_process = subprocess.check_outp... | TestKillChildProcessesByPids |
python | getsentry__sentry | src/sentry/api/invite_helper.py | {
"start": 1821,
"end": 9715
} | class ____:
@classmethod
def from_session_or_email(
cls,
request: HttpRequest,
organization_id: int,
email: str,
logger: Logger | None = None,
) -> ApiInviteHelper | None:
"""
Initializes the ApiInviteHelper by locating the pending organization
... | ApiInviteHelper |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/input_util_test.py | {
"start": 1894,
"end": 19286
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
self._num_devices = MESH_SIZE_BATCH * MESH_SIZE_HEIGHT * MESH_SIZE_WIDTH
self.mesh = mesh_util.create_mesh(
devices=['CPU:%d' % i for i in range(self._num_devices)],
mesh_dims=[(MESH_DIM_BATCH, MESH_SIZE_BATCH),
... | DTensorDatasetTest |
python | pytorch__pytorch | torch/distributions/normal.py | {
"start": 352,
"end": 3990
} | class ____(ExponentialFamily):
r"""
Creates a normal (also called Gaussian) distribution parameterized by
:attr:`loc` and :attr:`scale`.
Example::
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> m = Normal(torch.tensor([0.0]), torch.tensor([1.0]))
>>> m.sample() # normal... | Normal |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_auth_index.py | {
"start": 2143,
"end": 2874
} | class ____(APITestCase):
path = "/api/0/auth/"
def test_valid_password(self) -> None:
user = self.create_user("foo@example.com")
response = self.client.post(
self.path,
HTTP_AUTHORIZATION=self.create_basic_auth_header(user.username, "admin"),
)
assert res... | AuthLoginEndpointTest |
python | huggingface__transformers | src/transformers/models/flaubert/modeling_flaubert.py | {
"start": 43602,
"end": 48908
} | class ____(FlaubertPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"pred_layer.proj.weight": "transformer.embeddings.weight"}
def __init__(self, config):
super().__init__(config)
self.transformer = FlaubertModel(config)
self.pred_layer = FlaubertPredLayer(config)
# Ini... | FlaubertWithLMHeadModel |
python | google__jax | jax/_src/pallas/mosaic_gpu/primitives.py | {
"start": 81137,
"end": 114881
} | class ____:
transforms: tuple[gpu_core.MemoryRefTransform, ...] = ()
def _undo_transforms(
raw_ref: state.AbstractRef,
memory_transforms: Sequence[gpu_core.MemoryRefTransform],
):
"""Extract the `Transform`s that reverse the `MemoryRefTransform`s"""
tmp_ref = state_types.TransformedRef(raw_ref, transfor... | RefType |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 23917,
"end": 24577
} | class ____(_DMLReturningColFilter):
"""an adapter used for the DML RETURNING case specifically
for ORM bulk insert (or any hypothetical DML that is splitting out a class
hierarchy among multiple DML statements....ORM bulk insert is the only
example right now)
its main job is to limit the columns in... | _DMLBulkInsertReturningColFilter |
python | django__django | tests/delete/models.py | {
"start": 5697,
"end": 5729
} | class ____(Parent):
pass
| Child |
python | tornadoweb__tornado | tornado/locks.py | {
"start": 14127,
"end": 14840
} | class ____(Semaphore):
"""A semaphore that prevents release() being called too many times.
If `.release` would increment the semaphore's value past the initial
value, it raises `ValueError`. Semaphores are mostly used to guard
resources with limited capacity, so a semaphore released too many times
... | BoundedSemaphore |
python | fsspec__filesystem_spec | fsspec/implementations/http.py | {
"start": 844,
"end": 19177
} | class ____(AsyncFileSystem):
"""
Simple File-System for fetching data via HTTP(S)
``ls()`` is implemented by loading the parent page and doing a regex
match on the result. If simple_link=True, anything of the form
"http(s)://server.com/stuff?thing=other"; otherwise only links within
HTML href t... | HTTPFileSystem |
python | apache__airflow | shared/secrets_masker/tests/secrets_masker/test_secrets_masker.py | {
"start": 23589,
"end": 26118
} | class ____:
def test_kubernetes_env_var_redaction(self):
class MockV1EnvVar:
def __init__(self, name, value):
self.name = name
self.value = value
def to_dict(self):
return {"name": self.name, "value": self.value}
secret_env_va... | TestContainerTypesRedaction |
python | kamyu104__LeetCode-Solutions | Python/generate-parentheses.py | {
"start": 1049,
"end": 1738
} | class ____(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def generateParenthesisRecu(left, right, curr, result):
if left == 0 and right == 0:
result.append("".join(curr))
if left > 0:
... | Solution2 |
python | keon__algorithms | tests/test_dp.py | {
"start": 1444,
"end": 1718
} | class ____(unittest.TestCase):
def test_combination_sum_topdown(self):
self.assertEqual(combination_sum_topdown([1, 2, 3], 4), 7)
def test_combination_sum_bottom_up(self):
self.assertEqual(combination_sum_bottom_up([1, 2, 3], 4), 7)
| TestCombinationSum |
python | nedbat__coveragepy | tests/test_context.py | {
"start": 613,
"end": 5092
} | class ____(CoverageTest):
"""Tests of the static context."""
def test_no_context(self) -> None:
self.make_file("main.py", "a = 1")
cov = coverage.Coverage()
self.start_import_stop(cov, "main")
data = cov.get_data()
assert_count_equal(data.measured_contexts(), [""])
... | StaticContextTest |
python | rapidsai__cudf | python/cudf/cudf/core/series.py | {
"start": 123173,
"end": 123587
} | class ____:
"""
Base accessor class for Series values.
"""
def __init__(self, series: Series):
self.series = series
def _return_result_like_self(self, column: ColumnBase) -> Series:
"""Return the method result like self.series"""
data = ColumnAccessor({self.series.name: col... | BaseDatelikeProperties |
python | jazzband__django-model-utils | tests/test_managers/test_inheritance_manager.py | {
"start": 646,
"end": 8431
} | class ____(TestCase):
def setUp(self) -> None:
self.child1 = InheritanceManagerTestChild1.objects.create()
self.child2 = InheritanceManagerTestChild2.objects.create()
self.grandchild1 = InheritanceManagerTestGrandChild1.objects.create()
self.grandchild1_2 = \
InheritanceM... | InheritanceManagerTests |
python | has2k1__plotnine | plotnine/positions/position_stack.py | {
"start": 213,
"end": 4027
} | class ____(position):
"""
Stack plotted objects on top of each other
The objects to stack are those that have
an overlapping x range.
Parameters
----------
vjust :
By what fraction to avoid overlapping the lower object,
where `0` gives a complete overlap and `1` gives no ov... | position_stack |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_cloud_build.py | {
"start": 2378,
"end": 12832
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_no_default_project_id,
):
self.hook = CloudBuildHook(gcp_conn_id="test")
@mock.patch("airflow.providers.go... | TestCloudBuildHook |
python | doocs__leetcode | solution/1400-1499/1492.The kth Factor of n/Solution.py | {
"start": 0,
"end": 222
} | class ____:
def kthFactor(self, n: int, k: int) -> int:
for i in range(1, n + 1):
if n % i == 0:
k -= 1
if k == 0:
return i
return -1
| Solution |
python | allegroai__clearml | clearml/automation/hpbandster/bandster.py | {
"start": 955,
"end": 4638
} | class ____(Worker):
def __init__(
self,
*args: Any,
optimizer: "OptimizerBOHB",
base_task_id: str,
queue_name: str,
objective: Objective,
sleep_interval: float = 0,
budget_iteration_scale: float = 1.0,
**kwargs: Any,
) -> "_TrainsBandsterWo... | _TrainsBandsterWorker |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 3495,
"end": 3736
} | class ____:
@classmethod
def _type_fixture(cls):
return MutableDict
def teardown_test(self):
# clear out mapper events
Mapper.dispatch._clear()
ClassManager.dispatch._clear()
| _MutableDictTestFixture |
python | apache__airflow | airflow-core/src/airflow/timetables/base.py | {
"start": 2306,
"end": 2711
} | class ____(NamedTuple):
"""
A data interval for a DagRun to operate over.
Both ``start`` and ``end`` **MUST** be "aware", i.e. contain timezone
information.
"""
start: DateTime
end: DateTime
@classmethod
def exact(cls, at: DateTime) -> DataInterval:
"""Represent an "interv... | DataInterval |
python | pytorch__pytorch | torch/jit/_script.py | {
"start": 11664,
"end": 11794
} | class ____:
def __get__(self, obj, cls):
return self.__getattr__("forward") # type: ignore[attr-defined]
| _CachedForward |
python | getsentry__sentry | src/sentry/integrations/slack/requests/event.py | {
"start": 608,
"end": 2916
} | class ____(SlackDMRequest):
"""
An Event request sent from Slack.
These requests require the same Data and Token validation as all other
requests from Slack, but also event data validation.
Challenge Requests
------------------
Slack Event requests first start with a "challenge request". T... | SlackEventRequest |
python | pandas-dev__pandas | pandas/core/arrays/datetimelike.py | {
"start": 62232,
"end": 69947
} | class ____(DatetimeLikeArrayMixin):
"""
Common ops for DatetimeIndex/PeriodIndex, but not TimedeltaIndex.
"""
@Substitution(
URL="https://docs.python.org/3/library/datetime.html"
"#strftime-and-strptime-behavior"
)
def strftime(self, date_format: str) -> npt.NDArray[np.object_]:... | DatelikeOps |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.