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 | spyder-ide__spyder | spyder/plugins/run/models.py | {
"start": 9965,
"end": 13150
} | class ____(QAbstractListModel):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.executor_conf_params: Dict[
str, ExtendedRunExecutionParameters] = {}
self.params_index: Dict[int, str] = {}
self.inverse_index: Dict[str, int] = {}
def data(self, index: QModelIndex, role: int = Qt.DisplayRole):
pos = index.row()
pos = 0 if pos == -1 else pos
params_id = self.params_index[pos]
params = self.executor_conf_params[params_id]
params_name = params['name']
if role == Qt.DisplayRole or role == Qt.EditRole:
return params_name
def rowCount(self, parent: QModelIndex = ...) -> int:
return len(self.executor_conf_params)
def get_parameters(self, index: int) -> ExtendedRunExecutionParameters:
params_id = self.params_index[index]
return self.executor_conf_params[params_id]
def get_parameters_uuid_name(
self, index: int
) -> Tuple[Optional[str], Optional[str]]:
params_id = self.params_index[index]
params = self.executor_conf_params[params_id]
return params['uuid'], params['name']
def set_parameters(
self,
parameters: Dict[str, ExtendedRunExecutionParameters]
):
self.beginResetModel()
self.executor_conf_params = parameters
self.params_index = dict(enumerate(self.executor_conf_params))
self.inverse_index = {
self.params_index[k]: k for k in self.params_index
}
self.endResetModel()
def get_parameters_index_by_uuid(
self, parameters_uuid: Optional[str]
) -> int:
return self.inverse_index.get(parameters_uuid, 0)
def get_parameters_index_by_name(self, parameters_name: str) -> int:
index = -1
for id_, idx in self.inverse_index.items():
if self.executor_conf_params[id_]['name'] == parameters_name:
index = idx
break
return index
def get_parameter_names(self, filter_global: bool = False) -> List[str]:
"""
Get all parameter names for this executor.
Parameters
----------
filter_global: bool, optional
Whether to filter global parameters from the results.
"""
names = []
for params in self.executor_conf_params.values():
if filter_global:
if params["file_uuid"] is not None:
names.append(params["name"])
else:
names.append(params["name"])
return names
def get_number_of_custom_params(self, global_params_name: str) -> int:
"""
Get the number of custom parameters derived from a set of global ones.
Parameters
----------
global_params_name: str
Name of the global parameters.
"""
names = self.get_parameter_names(filter_global=True)
return len(
[name for name in names if name.startswith(global_params_name)]
)
def __len__(self) -> int:
return len(self.executor_conf_params)
| RunExecutorParameters |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 14455,
"end": 14842
} | class ____(_GenerativeProvider):
generative: Union[GenerativeSearches, _EnumLikeStr] = Field(
default=GenerativeSearches.PALM, frozen=True, exclude=True
)
apiEndpoint: Optional[str]
maxOutputTokens: Optional[int]
modelId: Optional[str]
projectId: str
temperature: Optional[float]
topK: Optional[int]
topP: Optional[float]
| _GenerativeGoogleConfig |
python | prabhupant__python-ds | data_structures/bst/check_bt_is_subtree_of_another_bt.py | {
"start": 0,
"end": 632
} | class ____():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def check(root1, root2):
if root1 == None:
return True
if root2 == None:
return False
if are_identical(root1, root2):
return True
return (check(root1.left, root2) or check(root1.right, root2))
def are_identical(root1, root2):
if root1 == None and root2 == None:
return True
if root1 == None or root2 == None:
return False
return (root1.val == root2.val and are_identical(root1.left, root2.left) and are_identical(root1.right, root2.right))
| Node |
python | spack__spack | lib/spack/spack/vendor/markupsafe/__init__.py | {
"start": 728,
"end": 6415
} | class ____(str):
"""A string that is ready to be safely inserted into an HTML or XML
document, either because it was escaped or because it was marked
safe.
Passing an object to the constructor converts it to text and wraps
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
>>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
>>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello <em>World</em>!')
This implements the ``__html__()`` interface that some frameworks
use. Passing an object that implements ``__html__()`` will wrap the
output of that method, marking it safe.
>>> class Foo:
... def __html__(self):
... return '<a href="/foo">foo</a>'
...
>>> Markup(Foo())
Markup('<a href="/foo">foo</a>')
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
>>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo & bar</em>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(
cls, base: t.Any = "", encoding: t.Optional[str] = None, errors: str = "strict"
) -> "Markup":
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
return super().__new__(cls, base)
return super().__new__(cls, base, encoding, errors)
def __html__(self) -> "Markup":
return self
def __add__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.__class__(super().__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other: t.Union[str, "HasHTML"]) -> "Markup":
if isinstance(other, str) or hasattr(other, "__html__"):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num: int) -> "Markup":
if isinstance(num, int):
return self.__class__(super().__mul__(num))
return NotImplemented # type: ignore
__rmul__ = __mul__
def __mod__(self, arg: t.Any) -> "Markup":
if isinstance(arg, tuple):
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
else:
arg = _MarkupEscapeHelper(arg, self.escape)
return self.__class__(super().__mod__(arg))
def __repr__(self) -> str:
return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq: t.Iterable[t.Union[str, "HasHTML"]]) -> "Markup":
return self.__class__(super().join(map(self.escape, seq)))
join.__doc__ = str.join.__doc__
def split( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().split(sep, maxsplit)]
split.__doc__ = str.split.__doc__
def rsplit( # type: ignore
self, sep: t.Optional[str] = None, maxsplit: int = -1
) -> t.List["Markup"]:
return [self.__class__(v) for v in super().rsplit(sep, maxsplit)]
rsplit.__doc__ = str.rsplit.__doc__
def splitlines(self, keepends: bool = False) -> t.List["Markup"]: # type: ignore
return [self.__class__(v) for v in super().splitlines(keepends)]
splitlines.__doc__ = str.splitlines.__doc__
def unescape(self) -> str:
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup("Main » <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from html import unescape
return unescape(str(self))
def striptags(self) -> str:
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
>>> Markup("Main »\t<em>About</em>").striptags()
'Main » About'
"""
stripped = " ".join(_striptags_re.sub("", self).split())
return Markup(stripped).unescape()
@classmethod
def escape(cls, s: t.Any) -> "Markup":
"""Escape a string. Calls :func:`escape` and ensures that for
subclasses the correct type is returned.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
for method in (
"__getitem__",
"capitalize",
"title",
"lower",
"upper",
"replace",
"ljust",
"rjust",
"lstrip",
"rstrip",
"center",
"strip",
"translate",
"expandtabs",
"swapcase",
"zfill",
):
locals()[method] = _simple_escaping_wrapper(method)
del method
def partition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().partition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def rpartition(self, sep: str) -> t.Tuple["Markup", "Markup", "Markup"]:
l, s, r = super().rpartition(self.escape(sep))
cls = self.__class__
return cls(l), cls(s), cls(r)
def format(self, *args: t.Any, **kwargs: t.Any) -> "Markup":
formatter = EscapeFormatter(self.escape)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec: str) -> "Markup":
if format_spec:
raise ValueError("Unsupported format specification for Markup.")
return self
| Markup |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-operations-to-reinitialize-a-permutation.py | {
"start": 1178,
"end": 1491
} | class ____(object):
def reinitializePermutation(self, n):
"""
:type n: int
:rtype: int
"""
result, i = 0, 1
while not result or i != 1: # find cycle length
i = (i//2 if not i%2 else n//2+(i-1)//2)
result += 1
return result
| Solution3 |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 2907,
"end": 3174
} | class ____(models.Model):
content_type = models.ForeignKey(
ContentType, models.CASCADE, related_name="g_r_r_tags"
)
object_id = models.CharField(max_length=15)
content_object = GenericForeignKey()
label = models.CharField(max_length=15)
| Tag |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 8894,
"end": 9138
} | class ____(models.Model):
related_field = models.ForeignKey(SluggedTestModel, on_delete=models.CASCADE)
slug = AutoSlugField(populate_from="related_field__title")
class Meta:
app_label = "django_extensions"
| FKSluggedTestModel |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0003_add-cold-storage.py | {
"start": 149,
"end": 600
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0002_build_command_initial"),
]
operations = [
migrations.AddField(
model_name="build",
name="cold_storage",
field=models.NullBooleanField(
help_text="Build steps stored outside the database.",
verbose_name="Cold Storage",
),
),
]
| Migration |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/rds.py | {
"start": 3575,
"end": 5672
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger to wait asynchronously for a DB instance or cluster to be deleted.
:param db_identifier: The DB identifier for the DB instance or cluster to be polled.
:param waiter_delay: The amount of time in seconds to wait between attempts.
:param waiter_max_attempts: The maximum number of attempts to be made.
:param aws_conn_id: The Airflow connection used for AWS credentials.
:param region_name: AWS region where the DB is located, if different from the default one.
:param response: The response from the RdsHook, to be passed back to the operator.
:param db_type: The type of DB: instance or cluster.
"""
def __init__(
self,
db_identifier: str,
waiter_delay: int,
waiter_max_attempts: int,
aws_conn_id: str | None,
response: dict[str, Any],
db_type: RdsDbType | str,
region_name: str | None = None,
) -> None:
# allow passing enums for users,
# but we can only rely on strings because (de-)serialization doesn't support enums
if isinstance(db_type, RdsDbType):
db_type_str = db_type.value
else:
db_type_str = db_type
super().__init__(
serialized_fields={
"db_identifier": db_identifier,
"response": response,
"db_type": db_type_str,
},
waiter_name=f"db_{db_type_str}_deleted",
waiter_args={_waiter_arg[db_type_str]: db_identifier},
failure_message="Error while deleting DB",
status_message="DB deletion in progress",
status_queries=_status_paths[db_type_str],
return_key="response",
return_value=response,
waiter_delay=waiter_delay,
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
region_name=region_name,
)
def hook(self) -> AwsGenericHook:
return RdsHook(aws_conn_id=self.aws_conn_id, region_name=self.region_name)
| RdsDbDeletedTrigger |
python | doocs__leetcode | solution/0500-0599/0504.Base 7/Solution.py | {
"start": 0,
"end": 307
} | class ____:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
if num < 0:
return '-' + self.convertToBase7(-num)
ans = []
while num:
ans.append(str(num % 7))
num //= 7
return ''.join(ans[::-1])
| Solution |
python | walkccc__LeetCode | solutions/3101. Count Alternating Subarrays/3101.py | {
"start": 0,
"end": 288
} | class ____:
def countAlternatingSubarrays(self, nums: list[int]) -> int:
# dp[i] := the number of alternating subarrays ending in index i
dp = [1] * len(nums)
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
dp[i] += dp[i - 1]
return sum(dp)
| Solution |
python | pytorch__pytorch | torch/distributed/_tools/sac_estimator.py | {
"start": 4799,
"end": 5879
} | class ____:
"""
Stores statistics for activation-checkpointing trade-off.
Attributes:
n_segments (int): Number of piecewise linear segments fitted to the trade-off curve.
slopes (List[float]): Slopes of the pieces of linear segments fitted to the trade-off curve.
intercepts (List[float]): Intercepts of the of the pieces of linear segments fitted to the trade-off curve.
fit_breaks (List[float]): Breakpoints of the of the pieces of linear segments fitted to the trade-off curve.
tradeoff_curve (OrderedDict[float, float]): Trade-off curve data of memory discarded vs recomputation time.
sac_memory (int): Total memory of operations available for activation checkpointing in bytes.
sac_runtime (float): Total runtime of operations available for activation checkpointing in milliseconds.
"""
n_segments: int
slopes: list[float]
intercepts: list[float]
fit_breaks: list[float]
tradeoff_curve: OrderedDict[float, float]
sac_memory: int
sac_runtime: float
@dataclass
| SACTradeOffStats |
python | pypa__virtualenv | src/virtualenv/activation/batch/__init__.py | {
"start": 117,
"end": 756
} | class ____(ViaTemplateActivator):
@classmethod
def supports(cls, interpreter):
return interpreter.os == "nt"
def templates(self):
yield "activate.bat"
yield "deactivate.bat"
yield "pydoc.bat"
@staticmethod
def quote(string):
return string
def instantiate_template(self, replacements, template, creator):
# ensure the text has all newlines as \r\n - required by batch
base = super().instantiate_template(replacements, template, creator)
return base.replace(os.linesep, "\n").replace("\n", os.linesep)
__all__ = [
"BatchActivator",
]
| BatchActivator |
python | pandas-dev__pandas | asv_bench/benchmarks/series_methods.py | {
"start": 8165,
"end": 8434
} | class ____:
param_names = ["dtype"]
params = [
["int", "uint", "float", "object"],
]
def setup(self, dtype):
self.s = Series(np.random.randint(0, 1000, size=100000), dtype=dtype)
def time_rank(self, dtype):
self.s.rank()
| Rank |
python | facebook__pyre-check | tools/generate_taint_models/tests/function_tainter_test.py | {
"start": 1657,
"end": 8437
} | class ____(unittest.TestCase):
def test_taint_callable_with_dataclass(self) -> None:
test_dataclass_parameter_models = taint_callable_dataclass_fields_parameters(
test_dataclass_parameter,
"TaintSource",
"UserControlled",
"TaintSink[ReturnedToUser]",
)
self.assertEqual(
str(list(test_dataclass_parameter_models)[0]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_dataclass_parameter(data: TaintSource[UserControlled, ParameterPath[_.x1]]) -> TaintSink[ReturnedToUser]: ...",
)
self.assertEqual(
str(list(test_dataclass_parameter_models)[1]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_dataclass_parameter(data: TaintSource[UserControlled, ParameterPath[_.y]]) -> TaintSink[ReturnedToUser]: ...",
)
def test_taint_callable_with_dataclass_and_simple_parameters(self) -> None:
test_dataclass_parameter_models = taint_callable_dataclass_fields_parameters(
test_simple_and_dataclass_parameters,
"TaintSource",
"UserControlled",
"TaintSink[ReturnedToUser]",
)
self.assertEqual(
str(list(test_dataclass_parameter_models)[0]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_simple_and_dataclass_parameters(data: TaintSource[UserControlled, ParameterPath[_.x1]], x) -> TaintSink[ReturnedToUser]: ...",
)
self.assertEqual(
str(list(test_dataclass_parameter_models)[1]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_simple_and_dataclass_parameters(data: TaintSource[UserControlled, ParameterPath[_.y]], x) -> TaintSink[ReturnedToUser]: ...",
)
def test_taint_callable_with_dataclass_and_simple_parameters_args_kwargs_without_annotation(
self,
) -> None:
test_dataclass_parameter_models = taint_callable_dataclass_fields_parameters(
test_args_kwargs_without_annotation,
"TaintSource",
"UserControlled",
"TaintSink[ReturnedToUser]",
)
print(str(list(test_dataclass_parameter_models)[0]))
self.assertEqual(
str(list(test_dataclass_parameter_models)[0]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_args_kwargs_without_annotation(*args: TaintSource[UserControlled], **kwargs: TaintSource[UserControlled]) -> TaintSink[ReturnedToUser]: ...",
)
def test_taint_callable_with_dataclass_and_simple_parameters_args_kwargs_any_annotation(
self,
) -> None:
test_dataclass_parameter_models = taint_callable_dataclass_fields_parameters(
test_args_kwargs_with_any_annotation,
"TaintSource",
"UserControlled",
"TaintSink[ReturnedToUser]",
)
print(str(list(test_dataclass_parameter_models)[0]))
self.assertEqual(
str(list(test_dataclass_parameter_models)[0]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_args_kwargs_with_any_annotation(*args: TaintSource[UserControlled], **kwargs: TaintSource[UserControlled]) -> TaintSink[ReturnedToUser]: ...",
)
def test_taint_callable_with_dataclass_with_optional_annotation(self) -> None:
test_dataclass_parameter_models = taint_callable_dataclass_fields_parameters(
test_optional_annotation,
"TaintSource",
"UserControlled",
"TaintSink[ReturnedToUser]",
)
self.assertEqual(
str(list(test_dataclass_parameter_models)[0]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_optional_annotation(data: TaintSource[UserControlled, ParameterPath[_.x1]]) -> TaintSink[ReturnedToUser]: ...",
)
self.assertEqual(
str(list(test_dataclass_parameter_models)[1]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_optional_annotation(data: TaintSource[UserControlled, ParameterPath[_.y]]) -> TaintSink[ReturnedToUser]: ...",
)
def test_taint_callable_with_dataclass_with_annotated_annotation(self) -> None:
test_dataclass_parameter_models = taint_callable_dataclass_fields_parameters(
test_annotated_annotation,
"TaintSource",
"UserControlled",
"TaintSink[ReturnedToUser]",
)
self.assertEqual(
str(list(test_dataclass_parameter_models)[0]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_annotated_annotation(data: TaintSource[UserControlled, ParameterPath[_.x1]]) -> TaintSink[ReturnedToUser]: ...",
)
self.assertEqual(
str(list(test_dataclass_parameter_models)[1]),
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_annotated_annotation(data: TaintSource[UserControlled, ParameterPath[_.y]]) -> TaintSink[ReturnedToUser]: ...",
)
def test_taint_callable_with_mixed_args(self) -> None:
test_mixed_args_parameter_models = taint_callable_dataclass_fields_parameters(
test_mixed_args,
"TaintSource",
"UserControlled",
"TaintSink[ReturnedToUser]",
)
self.assertEqual(
{str(model) for model in test_mixed_args_parameter_models},
{
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_mixed_args(data1: TaintSource[UserControlled, ParameterPath[_.x1]], data2, x, *args, **kwargs) -> TaintSink[ReturnedToUser]: ...",
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_mixed_args(data1: TaintSource[UserControlled, ParameterPath[_.y]], data2, x, *args, **kwargs) -> TaintSink[ReturnedToUser]: ...",
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_mixed_args(data1, data2: TaintSource[UserControlled, ParameterPath[_.x1]], x, *args, **kwargs) -> TaintSink[ReturnedToUser]: ...",
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_mixed_args(data1, data2: TaintSource[UserControlled, ParameterPath[_.y]], x, *args, **kwargs) -> TaintSink[ReturnedToUser]: ...",
"def tools.pyre.tools.generate_taint_models.tests.function_tainter_test.test_mixed_args(data1, data2, x: TaintSource[UserControlled], *args: TaintSource[UserControlled], **kwargs: TaintSource[UserControlled]) -> TaintSink[ReturnedToUser]: ...",
},
)
| FunctionTainterTest |
python | PyCQA__bandit | tests/functional/test_functional.py | {
"start": 376,
"end": 36318
} | class ____(testtools.TestCase):
"""Functional tests for bandit test plugins.
This set of tests runs bandit against each example file in turn
and records the score returned. This is compared to a known good value.
When new tests are added to an example the expected result should be
adjusted to match.
"""
def setUp(self):
super().setUp()
# NOTE(tkelsey): bandit is very sensitive to paths, so stitch
# them up here for the testing environment.
#
path = os.path.join(os.getcwd(), "bandit", "plugins")
b_conf = b_config.BanditConfig()
self.b_mgr = b_manager.BanditManager(b_conf, "file")
self.b_mgr.b_conf._settings["plugins_dir"] = path
self.b_mgr.b_ts = b_test_set.BanditTestSet(config=b_conf)
@contextmanager
def with_test_set(self, ts):
"""A helper context manager to change the test set without
side-effects for any follow-up tests.
"""
orig_ts = self.b_mgr.b_ts
self.b_mgr.b_ts = ts
try:
yield
finally:
self.b_mgr.b_ts = orig_ts
def run_example(self, example_script, ignore_nosec=False):
"""A helper method to run the specified test
This method runs the test, which populates the self.b_mgr.scores
value. Call this directly if you need to run a test, but do not
need to test the resulting scores against specified values.
:param example_script: Filename of an example script to test
"""
path = os.path.join(os.getcwd(), "examples", example_script)
self.b_mgr.ignore_nosec = ignore_nosec
self.b_mgr.discover_files([path], True)
self.b_mgr.run_tests()
def check_example(self, example_script, expect, ignore_nosec=False):
"""A helper method to test the scores for example scripts.
:param example_script: Filename of an example script to test
:param expect: dict with expected counts of issue types
"""
# reset scores for subsequent calls to check_example
self.b_mgr.scores = []
self.run_example(example_script, ignore_nosec=ignore_nosec)
result = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
}
for test_scores in self.b_mgr.scores:
for score_type in test_scores:
self.assertIn(score_type, expect)
for idx, rank in enumerate(C.RANKING):
result[score_type][rank] = (
test_scores[score_type][idx] // C.RANKING_VALUES[rank]
)
self.assertDictEqual(expect, result)
def check_metrics(self, example_script, expect):
"""A helper method to test the metrics being returned.
:param example_script: Filename of an example script to test
:param expect: dict with expected values of metrics
"""
self.b_mgr.metrics = metrics.Metrics()
self.b_mgr.scores = []
self.run_example(example_script)
# test general metrics (excludes issue counts)
m = self.b_mgr.metrics.data
for k in expect:
if k != "issues":
self.assertEqual(expect[k], m["_totals"][k])
# test issue counts
if "issues" in expect:
for criteria, default in C.CRITERIA:
for rank in C.RANKING:
label = f"{criteria}.{rank}"
expected = 0
if expect["issues"].get(criteria).get(rank):
expected = expect["issues"][criteria][rank]
self.assertEqual(expected, m["_totals"][label])
def test_binding(self):
"""Test the bind-to-0.0.0.0 example."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
}
self.check_example("binding.py", expect)
def test_crypto_md5(self):
"""Test the `hashlib.md5` example."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 16, "HIGH": 9},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 25},
}
self.check_example("crypto-md5.py", expect)
def test_ciphers(self):
"""Test the `Crypto.Cipher` example."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 24},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 25},
}
self.check_example("ciphers.py", expect)
def test_cipher_modes(self):
"""Test for insecure cipher modes."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("cipher-modes.py", expect)
def test_eval(self):
"""Test the `eval` example."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 3, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("eval.py", expect)
def test_mark_safe(self):
"""Test the `mark_safe` example."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("mark_safe.py", expect)
def test_exec(self):
"""Test the `exec` example."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("exec.py", expect)
def test_hardcoded_passwords(self):
"""Test for hard-coded passwords."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 14, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 14, "HIGH": 0},
}
self.check_example("hardcoded-passwords.py", expect)
def test_hardcoded_tmp(self):
"""Test for hard-coded /tmp, /var/tmp, /dev/shm."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 3, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 3, "HIGH": 0},
}
self.check_example("hardcoded-tmp.py", expect)
def test_imports_aliases(self):
"""Test the `import X as Y` syntax."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 4, "MEDIUM": 1, "HIGH": 4},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 9},
}
self.check_example("imports-aliases.py", expect)
def test_imports_from(self):
"""Test the `from X import Y` syntax."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 3, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("imports-from.py", expect)
def test_imports_function(self):
"""Test the `__import__` function."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 2, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("imports-function.py", expect)
def test_telnet_usage(self):
"""Test for `import telnetlib` and Telnet.* calls."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("telnetlib.py", expect)
def test_ftp_usage(self):
"""Test for `import ftplib` and FTP.* calls."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("ftplib.py", expect)
def test_imports(self):
"""Test for dangerous imports."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 2, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("imports.py", expect)
def test_imports_using_importlib(self):
"""Test for dangerous imports using importlib."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 4, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 4},
}
self.check_example("imports-with-importlib.py", expect)
def test_mktemp(self):
"""Test for `tempfile.mktemp`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 4, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 4},
}
self.check_example("mktemp.py", expect)
def test_nonsense(self):
"""Test that a syntactically invalid module is skipped."""
self.run_example("nonsense.py")
self.assertEqual(1, len(self.b_mgr.skipped))
def test_okay(self):
"""Test a vulnerability-free file."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
}
self.check_example("okay.py", expect)
def test_subdirectory_okay(self):
"""Test a vulnerability-free file under a subdirectory."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
}
self.check_example("init-py-test/subdirectory-okay.py", expect)
def test_os_chmod(self):
"""Test setting file permissions."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 4, "HIGH": 8},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 11},
}
self.check_example("os-chmod.py", expect)
def test_os_exec(self):
"""Test for `os.exec*`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 8, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 8, "HIGH": 0},
}
self.check_example("os-exec.py", expect)
def test_os_popen(self):
"""Test for `os.popen`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 8, "MEDIUM": 0, "HIGH": 1},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 9},
}
self.check_example("os-popen.py", expect)
def test_os_spawn(self):
"""Test for `os.spawn*`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 8, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 8, "HIGH": 0},
}
self.check_example("os-spawn.py", expect)
def test_os_startfile(self):
"""Test for `os.startfile`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 3, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 3, "HIGH": 0},
}
self.check_example("os-startfile.py", expect)
def test_os_system(self):
"""Test for `os.system`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("os_system.py", expect)
def test_pickle(self):
"""Test for the `pickle` module."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 3, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 4},
}
self.check_example("pickle_deserialize.py", expect)
def test_dill(self):
"""Test for the `dill` module."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 3, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 4},
}
self.check_example("dill.py", expect)
def test_shelve(self):
"""Test for the `shelve` module."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 2, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("shelve_open.py", expect)
def test_jsonpickle(self):
"""Test for the `jsonpickle` module."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 3, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("jsonpickle.py", expect)
def test_pandas_read_pickle(self):
"""Test for the `pandas.read_pickle` module."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("pandas_read_pickle.py", expect)
def test_popen_wrappers(self):
"""Test the `popen2` and `commands` modules."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 7, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 7},
}
self.check_example("popen_wrappers.py", expect)
def test_random_module(self):
"""Test for the `random` module."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 12, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 12},
}
self.check_example("random_module.py", expect)
def test_requests_ssl_verify_disabled(self):
"""Test for the `requests` library skipping verification."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 18},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 18},
}
self.check_example("requests-ssl-verify-disabled.py", expect)
def test_requests_without_timeout(self):
"""Test for the `requests` library missing timeouts."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 25, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 25, "MEDIUM": 0, "HIGH": 0},
}
self.check_example("requests-missing-timeout.py", expect)
def test_skip(self):
"""Test `#nosec` and `#noqa` comments."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 5, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 5},
}
self.check_example("skip.py", expect)
def test_ignore_skip(self):
"""Test --ignore-nosec flag."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 7, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 7},
}
self.check_example("skip.py", expect, ignore_nosec=True)
def test_sql_statements(self):
"""Test for SQL injection through string building."""
expect = {
"SEVERITY": {
"UNDEFINED": 0,
"LOW": 0,
"MEDIUM": 20,
"HIGH": 0,
},
"CONFIDENCE": {
"UNDEFINED": 0,
"LOW": 10,
"MEDIUM": 10,
"HIGH": 0,
},
}
self.check_example("sql_statements.py", expect)
def test_multiline_sql_statements(self):
"""
Test for SQL injection through string building using
multi-line strings.
"""
example_file = "sql_multiline_statements.py"
confidence_low_tests = 13
severity_medium_tests = 26
nosec_tests = 7
skipped_tests = 8
expect = {
"SEVERITY": {
"UNDEFINED": 0,
"LOW": 0,
"MEDIUM": severity_medium_tests,
"HIGH": 0,
},
"CONFIDENCE": {
"UNDEFINED": 0,
"LOW": confidence_low_tests,
"MEDIUM": 13,
"HIGH": 0,
},
}
expect_stats = {
"nosec": nosec_tests,
"skipped_tests": skipped_tests,
}
self.check_example(example_file, expect)
self.check_metrics(example_file, expect_stats)
def test_ssl_insecure_version(self):
"""Test for insecure SSL protocol versions."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 13, "HIGH": 9},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 14, "HIGH": 9},
}
self.check_example("ssl-insecure-version.py", expect)
def test_subprocess_shell(self):
"""Test for `subprocess.Popen` with `shell=True`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 24, "MEDIUM": 1, "HIGH": 11},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 0, "HIGH": 35},
}
self.check_example("subprocess_shell.py", expect)
def test_urlopen(self):
"""Test for dangerous URL opening."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 8, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 8},
}
self.check_example("urlopen.py", expect)
def test_wildcard_injection(self):
"""Test for wildcard injection in shell commands."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 10, "MEDIUM": 0, "HIGH": 4},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 5, "HIGH": 9},
}
self.check_example("wildcard-injection.py", expect)
def test_django_sql_injection(self):
"""Test insecure extra functions on Django."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 11, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 11, "HIGH": 0},
}
self.check_example("django_sql_injection_extra.py", expect)
def test_django_sql_injection_raw(self):
"""Test insecure raw functions on Django."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 6, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 6, "HIGH": 0},
}
self.check_example("django_sql_injection_raw.py", expect)
def test_yaml(self):
"""Test for `yaml.load`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 2, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("yaml_load.py", expect)
def test_host_key_verification(self):
"""Test for ignoring host key verification."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 8},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 8, "HIGH": 0},
}
self.check_example("no_host_key_verification.py", expect)
def test_jinja2_templating(self):
"""Test jinja templating for potential XSS bugs."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 5},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 2, "HIGH": 3},
}
self.check_example("jinja2_templating.py", expect)
def test_mako_templating(self):
"""Test Mako templates for XSS."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 3, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("mako_templating.py", expect)
def test_django_xss_secure(self):
"""Test false positives for Django XSS"""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
}
with self.with_test_set(
b_test_set.BanditTestSet(
config=self.b_mgr.b_conf, profile={"exclude": ["B308"]}
)
):
self.check_example("mark_safe_secure.py", expect)
def test_django_xss_insecure(self):
"""Test for Django XSS via django.utils.safestring"""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 29, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 29},
}
with self.with_test_set(
b_test_set.BanditTestSet(
config=self.b_mgr.b_conf, profile={"exclude": ["B308"]}
)
):
self.check_example("mark_safe_insecure.py", expect)
def test_xml(self):
"""Test xml vulnerabilities."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 4, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 5},
}
self.check_example("xml_etree_celementtree.py", expect)
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 2, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("xml_expatbuilder.py", expect)
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 2, "MEDIUM": 2, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 4},
}
self.check_example("xml_pulldom.py", expect)
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("xml_xmlrpc.py", expect)
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 4, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 5},
}
self.check_example("xml_etree_elementtree.py", expect)
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("xml_expatreader.py", expect)
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 2, "MEDIUM": 2, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 4},
}
self.check_example("xml_minidom.py", expect)
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 2, "MEDIUM": 6, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 8},
}
self.check_example("xml_sax.py", expect)
def test_httpoxy(self):
"""Test httpoxy vulnerability."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("httpoxy_cgihandler.py", expect)
self.check_example("httpoxy_twisted_script.py", expect)
self.check_example("httpoxy_twisted_directory.py", expect)
def test_asserts(self):
"""Test catching the use of assert."""
test = next(
x
for x in self.b_mgr.b_ts.tests["Assert"]
if x.__name__ == "assert_used"
)
test._config = {"skips": []}
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("assert.py", expect)
test._config = {"skips": ["*assert.py"]}
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
}
self.check_example("assert.py", expect)
test._config = {}
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("assert.py", expect)
def test_paramiko_injection(self):
"""Test paramiko command execution."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
}
self.check_example("paramiko_injection.py", expect)
def test_partial_path(self):
"""Test process spawning with partial file paths."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 11, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 11},
}
self.check_example("partial_path_process.py", expect)
def test_try_except_continue(self):
"""Test try, except, continue detection."""
test = next(
x
for x in self.b_mgr.b_ts.tests["ExceptHandler"]
if x.__name__ == "try_except_continue"
)
test._config = {"check_typed_exception": True}
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 3, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("try_except_continue.py", expect)
test._config = {"check_typed_exception": False}
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 2, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("try_except_continue.py", expect)
def test_try_except_pass(self):
"""Test try, except pass detection."""
test = next(
x
for x in self.b_mgr.b_ts.tests["ExceptHandler"]
if x.__name__ == "try_except_pass"
)
test._config = {"check_typed_exception": True}
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 3, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("try_except_pass.py", expect)
test._config = {"check_typed_exception": False}
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 2, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("try_except_pass.py", expect)
def test_metric_gathering(self):
expect = {
"nosec": 2,
"loc": 7,
"issues": {"CONFIDENCE": {"HIGH": 5}, "SEVERITY": {"LOW": 5}},
}
self.check_metrics("skip.py", expect)
expect = {
"nosec": 0,
"loc": 4,
"issues": {"CONFIDENCE": {"HIGH": 2}, "SEVERITY": {"LOW": 2}},
}
self.check_metrics("imports.py", expect)
def test_weak_cryptographic_key(self):
"""Test for weak key sizes."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 8, "HIGH": 8},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 16},
}
self.check_example("weak_cryptographic_key_sizes.py", expect)
def test_multiline_code(self):
"""Test issues in multiline statements return code as expected."""
self.run_example("multiline_statement.py")
self.assertEqual(0, len(self.b_mgr.skipped))
self.assertEqual(1, len(self.b_mgr.files_list))
self.assertTrue(
self.b_mgr.files_list[0].endswith("multiline_statement.py")
)
issues = self.b_mgr.get_issue_list()
self.assertEqual(3, len(issues))
self.assertTrue(
issues[0].fname.endswith("examples/multiline_statement.py")
)
self.assertEqual(1, issues[0].lineno)
self.assertEqual(list(range(1, 2)), issues[0].linerange)
self.assertIn("subprocess", issues[0].get_code())
self.assertEqual(5, issues[1].lineno)
self.assertEqual(list(range(3, 6 + 1)), issues[1].linerange)
self.assertIn("shell=True", issues[1].get_code())
self.assertEqual(11, issues[2].lineno)
self.assertEqual(list(range(8, 13 + 1)), issues[2].linerange)
self.assertIn("shell=True", issues[2].get_code())
def test_code_line_numbers(self):
self.run_example("binding.py")
issues = self.b_mgr.get_issue_list()
code_lines = issues[0].get_code().splitlines()
lineno = issues[0].lineno
self.assertEqual("%i " % (lineno - 1), code_lines[0][:2])
self.assertEqual("%i " % (lineno), code_lines[1][:2])
self.assertEqual("%i " % (lineno + 1), code_lines[2][:2])
def test_flask_debug_true(self):
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
}
self.check_example("flask_debug.py", expect)
def test_nosec(self):
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 5, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 5},
}
self.check_example("nosec.py", expect)
def test_baseline_filter(self):
issue_text = (
"A Flask app appears to be run with debug=True, which "
"exposes the Werkzeug debugger and allows the execution "
"of arbitrary code."
)
json = f"""{{
"results": [
{{
"code": "...",
"filename": "{os.getcwd()}/examples/flask_debug.py",
"issue_confidence": "MEDIUM",
"issue_severity": "HIGH",
"issue_cwe": {{
"id": 94,
"link": "https://cwe.mitre.org/data/definitions/94.html"
}},
"issue_text": "{issue_text}",
"line_number": 10,
"col_offset": 0,
"line_range": [
10
],
"test_name": "flask_debug_true",
"test_id": "B201"
}}
]
}}
"""
self.b_mgr.populate_baseline(json)
self.run_example("flask_debug.py")
self.assertEqual(1, len(self.b_mgr.baseline))
self.assertEqual({}, self.b_mgr.get_issue_list())
def test_unverified_context(self):
"""Test for `ssl._create_unverified_context`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
self.check_example("unverified_context.py", expect)
def test_hashlib_new_insecure_functions(self):
"""Test insecure hash functions created by `hashlib.new`."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 9},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 9},
}
self.check_example("hashlib_new_insecure_functions.py", expect)
def test_blacklist_pycrypto(self):
"""Test importing pycrypto module"""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
self.check_example("pycrypto.py", expect)
def test_no_blacklist_pycryptodome(self):
"""Test importing pycryptodome module
make sure it's no longer blacklisted
"""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
}
self.check_example("pycryptodome.py", expect)
def test_blacklist_pyghmi(self):
"""Test calling pyghmi methods"""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 0, "HIGH": 1},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 1},
}
self.check_example("pyghmi.py", expect)
def test_snmp_security_check(self):
"""Test insecure and weak crypto usage of SNMP."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 3, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("snmp.py", expect)
def test_tarfile_unsafe_members(self):
"""Test insecure usage of tarfile."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 2, "HIGH": 2},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 1, "MEDIUM": 2, "HIGH": 2},
}
self.check_example("tarfile_extractall.py", expect)
def test_pytorch_load(self):
"""Test insecure usage of torch.load."""
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 3, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 3},
}
self.check_example("pytorch_load.py", expect)
def test_trojansource(self):
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
}
self.check_example("trojansource.py", expect)
def test_trojansource_latin1(self):
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 0},
}
self.check_example("trojansource_latin1.py", expect)
def test_markupsafe_markup_xss(self):
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 4, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 4},
}
self.check_example("markupsafe_markup_xss.py", expect)
def test_markupsafe_markup_xss_extend_markup_names(self):
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 2, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 2},
}
b_conf = b_config.BanditConfig()
b_conf.config["markupsafe_xss"] = {
"extend_markup_names": ["webhelpers.html.literal"]
}
with self.with_test_set(b_test_set.BanditTestSet(config=b_conf)):
self.check_example(
"markupsafe_markup_xss_extend_markup_names.py", expect
)
def test_markupsafe_markup_xss_allowed_calls(self):
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 1, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 1},
}
b_conf = b_config.BanditConfig()
b_conf.config["markupsafe_xss"] = {"allowed_calls": ["bleach.clean"]}
with self.with_test_set(b_test_set.BanditTestSet(config=b_conf)):
self.check_example(
"markupsafe_markup_xss_allowed_calls.py", expect
)
def test_huggingface_unsafe_download(self):
expect = {
"SEVERITY": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 15, "HIGH": 0},
"CONFIDENCE": {"UNDEFINED": 0, "LOW": 0, "MEDIUM": 0, "HIGH": 15},
}
self.check_example("huggingface_unsafe_download.py", expect)
| FunctionalTests |
python | getsentry__sentry | src/sentry/db/models/base.py | {
"start": 13767,
"end": 17047
} | class ____(Model):
"""
A base model that adds default date fields to existing models.
"""
date_updated = models.DateTimeField(auto_now=True)
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
def __model_pre_save(instance: models.Model, **kwargs: Any) -> None:
if not isinstance(instance, DefaultFieldsModelExisting):
return
# Only update this field when we're updating the row, not on create.
if instance.pk is not None:
instance.date_updated = timezone.now()
def __model_post_save(instance: models.Model, **kwargs: Any) -> None:
if not isinstance(instance, BaseModel):
return
def __model_class_prepared(sender: Any, **kwargs: Any) -> None:
if not issubclass(sender, BaseModel):
return
if not hasattr(sender, "__relocation_scope__"):
raise ValueError(
f"{sender!r} model has not defined __relocation_scope__. This is used to determine "
f"which models we export from sentry as part of our migration workflow: \n"
f"https://docs.sentry.io/product/sentry-basics/migration/#3-export-your-data.\n"
f"This should be True for core, low volume models used to configure Sentry. Things like "
f"Organization, Project and related settings. It should be False for high volume models "
f"like Group."
)
if (
isinstance(getattr(sender, "__relocation_scope__"), set)
and RelocationScope.Excluded in sender.get_possible_relocation_scopes()
):
raise ValueError(
f"{sender!r} model uses a set of __relocation_scope__ values, one of which is "
f"`Excluded`, which does not make sense. `Excluded` must always be a standalone value."
)
if (
getattr(sender._meta, "app_label", None) == "getsentry"
and sender.__relocation_scope__ != RelocationScope.Excluded
):
raise ValueError(
f"{sender!r} model is in the `getsentry` app, and therefore cannot be exported. "
f"Please set `__relocation_scope__ = RelocationScope.Excluded` on the model definition."
)
from sentry.hybridcloud.outbox.base import ReplicatedControlModel, ReplicatedRegionModel
if issubclass(sender, ReplicatedControlModel):
sender.category.connect_control_model_updates(sender)
elif issubclass(sender, ReplicatedRegionModel):
sender.category.connect_region_model_updates(sender)
signals.pre_save.connect(__model_pre_save)
signals.post_save.connect(__model_post_save)
signals.class_prepared.connect(__model_class_prepared)
def get_model_if_available(app_config: AppConfig, model_name: str) -> type[models.Model] | None:
"""Get a named model class if it exists and is available in this silo mode."""
try:
model = app_config.get_model(model_name)
except LookupError:
return None
assert isinstance(model, type) and issubclass(model, models.Model)
silo_limit = getattr(model._meta, "silo_limit", None)
if silo_limit is not None:
assert isinstance(silo_limit, ModelSiloLimit)
if not silo_limit.is_available():
return None
return model
ModelClass = TypeVar("ModelClass")
| DefaultFieldsModel |
python | tornadoweb__tornado | tornado/test/auth_test.py | {
"start": 3972,
"end": 4111
} | class ____(RequestHandler):
def get(self):
self.write("oauth_token=zxcv&oauth_token_secret=1234")
| OAuth1ServerRequestTokenHandler |
python | openai__openai-python | src/openai/types/beta/realtime/response_cancel_event.py | {
"start": 225,
"end": 637
} | class ____(BaseModel):
type: Literal["response.cancel"]
"""The event type, must be `response.cancel`."""
event_id: Optional[str] = None
"""Optional client-generated ID used to identify this event."""
response_id: Optional[str] = None
"""
A specific response ID to cancel - if not provided, will cancel an in-progress
response in the default conversation.
"""
| ResponseCancelEvent |
python | sqlalchemy__sqlalchemy | test/orm/test_naturalpks.py | {
"start": 32963,
"end": 41986
} | class ____(fixtures.MappedTest, testing.AssertsCompiledSQL):
"""A primary key mutation cascades onto a foreign key that is itself a
primary key."""
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
fk_args = _backend_specific_fk_args()
Table(
"users",
metadata,
Column("username", String(50), primary_key=True),
test_needs_fk=True,
)
Table(
"addresses",
metadata,
Column(
"username",
String(50),
ForeignKey("users.username", **fk_args),
primary_key=True,
),
Column("email", String(50), primary_key=True),
Column("etc", String(50)),
test_needs_fk=True,
)
@classmethod
def setup_classes(cls):
class User(cls.Comparable):
pass
class Address(cls.Comparable):
pass
@testing.requires.on_update_cascade
def test_onetomany_passive(self):
self._test_onetomany(True)
@testing.requires.non_updating_cascade
def test_onetomany_nonpassive(self):
self._test_onetomany(False)
def test_o2m_change_passive(self):
self._test_o2m_change(True)
def test_o2m_change_nonpassive(self):
self._test_o2m_change(False)
def _test_o2m_change(self, passive_updates):
"""Change the PK of a related entity to another.
"on update cascade" is not involved here, so the mapper has
to do the UPDATE itself.
"""
User, Address, users, addresses = (
self.classes.User,
self.classes.Address,
self.tables.users,
self.tables.addresses,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(
Address, passive_updates=passive_updates
)
},
)
self.mapper_registry.map_imperatively(Address, addresses)
sess = fixture_session()
a1 = Address(username="ed", email="ed@host1")
u1 = User(username="ed", addresses=[a1])
u2 = User(username="jack")
sess.add_all([a1, u1, u2])
sess.flush()
a1.username = "jack"
sess.flush()
def test_o2m_move_passive(self):
self._test_o2m_move(True)
def test_o2m_move_nonpassive(self):
self._test_o2m_move(False)
def _test_o2m_move(self, passive_updates):
"""Move the related entity to a different collection,
changing its PK.
"""
User, Address, users, addresses = (
self.classes.User,
self.classes.Address,
self.tables.users,
self.tables.addresses,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(
Address, passive_updates=passive_updates
)
},
)
self.mapper_registry.map_imperatively(Address, addresses)
sess = fixture_session(autoflush=False)
a1 = Address(username="ed", email="ed@host1")
u1 = User(username="ed", addresses=[a1])
u2 = User(username="jack")
sess.add_all([a1, u1, u2])
sess.flush()
u1.addresses.remove(a1)
u2.addresses.append(a1)
sess.flush()
@testing.requires.on_update_cascade
def test_change_m2o_passive(self):
self._test_change_m2o(True)
@testing.requires.non_updating_cascade
def test_change_m2o_nonpassive(self):
self._test_change_m2o(False)
@testing.requires.on_update_cascade
def test_change_m2o_passive_uselist(self):
self._test_change_m2o(True, True)
@testing.requires.non_updating_cascade
def test_change_m2o_nonpassive_uselist(self):
self._test_change_m2o(False, True)
def _test_change_m2o(self, passive_updates, uselist=False):
User, Address, users, addresses = (
self.classes.User,
self.classes.Address,
self.tables.users,
self.tables.addresses,
)
self.mapper_registry.map_imperatively(User, users)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={
"user": relationship(
User, uselist=uselist, passive_updates=passive_updates
)
},
)
sess = fixture_session()
u1 = User(username="jack")
if uselist:
a1 = Address(user=[u1], email="foo@bar")
else:
a1 = Address(user=u1, email="foo@bar")
sess.add_all([u1, a1])
sess.flush()
u1.username = "edmodified"
sess.flush()
eq_(a1.username, "edmodified")
sess.expire_all()
eq_(a1.username, "edmodified")
def test_move_m2o_passive(self):
self._test_move_m2o(True)
def test_move_m2o_nonpassive(self):
self._test_move_m2o(False)
def _test_move_m2o(self, passive_updates):
User, Address, users, addresses = (
self.classes.User,
self.classes.Address,
self.tables.users,
self.tables.addresses,
)
# tests [ticket:1856]
self.mapper_registry.map_imperatively(User, users)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={
"user": relationship(User, passive_updates=passive_updates)
},
)
sess = fixture_session()
u1 = User(username="jack")
u2 = User(username="ed")
a1 = Address(user=u1, email="foo@bar")
sess.add_all([u1, u2, a1])
sess.flush()
a1.user = u2
sess.flush()
def test_rowswitch_doesntfire(self):
User, Address, users, addresses = (
self.classes.User,
self.classes.Address,
self.tables.users,
self.tables.addresses,
)
self.mapper_registry.map_imperatively(User, users)
self.mapper_registry.map_imperatively(
Address,
addresses,
properties={"user": relationship(User, passive_updates=True)},
)
sess = fixture_session()
u1 = User(username="ed")
a1 = Address(user=u1, email="ed@host1")
sess.add(u1)
sess.add(a1)
sess.flush()
sess.delete(u1)
sess.delete(a1)
u2 = User(username="ed")
a2 = Address(user=u2, email="ed@host1", etc="foo")
sess.add(u2)
sess.add(a2)
from sqlalchemy.testing.assertsql import CompiledSQL
# test that the primary key columns of addresses are not
# being updated as well, since this is a row switch.
self.assert_sql_execution(
testing.db,
sess.flush,
CompiledSQL(
"UPDATE addresses SET etc=:etc WHERE "
"addresses.username = :addresses_username AND"
" addresses.email = :addresses_email",
{
"etc": "foo",
"addresses_username": "ed",
"addresses_email": "ed@host1",
},
),
)
def _test_onetomany(self, passive_updates):
"""Change the PK of a related entity via foreign key cascade.
For databases that require "on update cascade", the mapper
has to identify the row by the new value, not the old, when
it does the update.
"""
User, Address, users, addresses = (
self.classes.User,
self.classes.Address,
self.tables.users,
self.tables.addresses,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(
Address, passive_updates=passive_updates
)
},
)
self.mapper_registry.map_imperatively(Address, addresses)
sess = fixture_session()
a1, a2 = (
Address(username="ed", email="ed@host1"),
Address(username="ed", email="ed@host2"),
)
u1 = User(username="ed", addresses=[a1, a2])
sess.add(u1)
sess.flush()
eq_(a1.username, "ed")
eq_(a2.username, "ed")
eq_(
sess.execute(sa.select(addresses.c.username)).fetchall(),
[("ed",), ("ed",)],
)
u1.username = "jack"
a2.email = "ed@host3"
sess.flush()
eq_(a1.username, "jack")
eq_(a2.username, "jack")
eq_(
sess.execute(sa.select(addresses.c.username)).fetchall(),
[("jack",), ("jack",)],
)
| CascadeToFKPKTest |
python | getsentry__sentry | tests/sentry/plugins/bases/test_issue2.py | {
"start": 1513,
"end": 2473
} | class ____(TestCase):
def _get_mock_user(self):
user = mock.Mock(spec=User(id=1))
user.is_authenticated = False
return user
def test_requires_auth_provider(self) -> None:
user = self._get_mock_user()
p = IssueTrackingPlugin2()
pytest.raises(AssertionError, p.get_auth_for_user, user)
def test_returns_none_on_missing_identity(self) -> None:
user = self._get_mock_user()
p = IssueTrackingPlugin2()
p.auth_provider = "test"
self.assertEqual(p.get_auth_for_user(user), None)
def test_returns_identity(self) -> None:
user = self.create_user(username="test", email="test@example.com")
auth = self.create_usersocialauth(user=user, provider="test")
p = IssueTrackingPlugin2()
p.auth_provider = "test"
got_auth = p.get_auth_for_user(user)
assert got_auth is not None
assert got_auth.id == auth.id
| GetAuthForUserTest |
python | ray-project__ray | python/ray/serve/_private/logging_utils.py | {
"start": 7641,
"end": 18350
} | class ____(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
This comes from https://stackoverflow.com/a/36296215 directly.
"""
def __init__(self, logger: logging.Logger, log_level: int, original_object: Any):
self._logger = logger
self._log_level = log_level
self._original_object = original_object
self._linebuf = ""
def __getattr__(self, attr: str) -> Any:
# getting attributes from the original object
return getattr(self._original_object, attr)
@staticmethod
def get_stacklevel() -> int:
"""Rewind stack to get the stacklevel for the user code.
Going from the back of the traceback and traverse until it's no longer in
logging_utils.py or site-packages.
"""
reverse_traces = traceback.extract_stack()[::-1]
for index, trace in enumerate(reverse_traces):
if (
"logging_utils.py" not in trace.filename
and "site-packages" not in trace.filename
):
return index
return 1
def write(self, buf: str):
temp_linebuf = self._linebuf + buf
self._linebuf = ""
for line in temp_linebuf.splitlines(True):
# From the io.TextIOWrapper docs:
# On output, if newline is None, any '\n' characters written
# are translated to the system default line separator.
# By default sys.stdout.write() expects '\n' newlines and then
# translates them so this is still cross-platform.
if line[-1] == "\n":
self._logger.log(
self._log_level,
line.rstrip(),
stacklevel=self.get_stacklevel(),
)
else:
self._linebuf += line
def flush(self):
if self._linebuf != "":
self._logger.log(
self._log_level,
self._linebuf.rstrip(),
stacklevel=self.get_stacklevel(),
)
self._linebuf = ""
def isatty(self) -> bool:
return True
def redirected_print(*objects, sep=" ", end="\n", file=None, flush=False):
"""Implement python's print function to redirect logs to Serve's logger.
If the file is set to anything other than stdout, stderr, or None, call the
builtin print. Else, construct the message and redirect to Serve's logger.
See https://docs.python.org/3/library/functions.html#print
"""
if file not in [sys.stdout, sys.stderr, None]:
return buildin_print(objects, sep=sep, end=end, file=file, flush=flush)
serve_logger = logging.getLogger(SERVE_LOGGER_NAME)
message = sep.join(map(str, objects)) + end
# We monkey patched print function, so this is always at stack level 2.
serve_logger.log(logging.INFO, message, stacklevel=2)
def configure_component_logger(
*,
component_name: str,
component_id: str,
logging_config: LoggingConfig,
component_type: Optional[ServeComponentType] = None,
max_bytes: Optional[int] = None,
backup_count: Optional[int] = None,
stream_handler_only: bool = False,
buffer_size: int = 1,
):
"""Configure a logger to be used by a Serve component.
The logger will log using a standard format to make components identifiable
using the provided name and unique ID for this instance (e.g., replica ID).
This logger will *not* propagate its log messages to the parent logger(s).
"""
logger = logging.getLogger(SERVE_LOGGER_NAME)
logger.propagate = False
logger.setLevel(logging_config.log_level)
logger.handlers.clear()
serve_formatter = ServeFormatter(component_name, component_id)
json_formatter = JSONFormatter()
if logging_config.additional_log_standard_attrs:
json_formatter.set_additional_log_standard_attrs(
logging_config.additional_log_standard_attrs
)
serve_formatter.set_additional_log_standard_attrs(
logging_config.additional_log_standard_attrs
)
# Only add stream handler if RAY_SERVE_LOG_TO_STDERR is True or if
# `stream_handler_only` is set to True.
if RAY_SERVE_LOG_TO_STDERR or stream_handler_only:
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(serve_formatter)
stream_handler.addFilter(log_to_stderr_filter)
stream_handler.addFilter(ServeContextFilter())
logger.addHandler(stream_handler)
# Skip setting up file handler and stdout/stderr redirect if `stream_handler_only`
# is set to True. Logger such as default serve logger can be configured outside the
# context of a Serve component, we don't want those logs to redirect into serve's
# logger and log files.
if stream_handler_only:
return
if logging_config.logs_dir:
logs_dir = logging_config.logs_dir
else:
logs_dir = get_serve_logs_dir()
os.makedirs(logs_dir, exist_ok=True)
if max_bytes is None:
max_bytes = ray._private.worker._global_node.max_bytes
if backup_count is None:
backup_count = ray._private.worker._global_node.backup_count
log_file_name = get_component_file_name(
component_name=component_name,
component_id=component_id,
component_type=component_type,
suffix=".log",
)
file_handler = logging.handlers.RotatingFileHandler(
os.path.join(logs_dir, log_file_name),
maxBytes=max_bytes,
backupCount=backup_count,
)
# Create a memory handler that buffers log records and flushes to file handler
# Buffer capacity: buffer_size records
# Flush triggers: buffer full, ERROR messages, or explicit flush
memory_handler = logging.handlers.MemoryHandler(
capacity=buffer_size,
target=file_handler,
flushLevel=logging.ERROR, # Auto-flush on ERROR/CRITICAL
)
if RAY_SERVE_ENABLE_JSON_LOGGING:
logger.warning(
"'RAY_SERVE_ENABLE_JSON_LOGGING' is deprecated, please use "
"'LoggingConfig' to enable json format."
)
# Add filters directly to the memory handler effective for both buffered and non buffered cases
if RAY_SERVE_ENABLE_JSON_LOGGING or logging_config.encoding == EncodingType.JSON:
memory_handler.addFilter(ServeCoreContextFilter())
memory_handler.addFilter(ServeContextFilter())
memory_handler.addFilter(
ServeComponentFilter(component_name, component_id, component_type)
)
file_handler.setFormatter(json_formatter)
else:
file_handler.setFormatter(serve_formatter)
if logging_config.enable_access_log is False:
memory_handler.addFilter(log_access_log_filter)
else:
memory_handler.addFilter(ServeContextFilter())
# Remove unwanted attributes from the log record.
memory_handler.addFilter(ServeLogAttributeRemovalFilter())
# Redirect print, stdout, and stderr to Serve logger, only when it's on the replica.
if not RAY_SERVE_LOG_TO_STDERR and component_type == ServeComponentType.REPLICA:
builtins.print = redirected_print
sys.stdout = StreamToLogger(logger, logging.INFO, sys.stdout)
sys.stderr = StreamToLogger(logger, logging.INFO, sys.stderr)
# Add the memory handler instead of the file handler directly
logger.addHandler(memory_handler)
def configure_default_serve_logger():
"""Helper function to configure the default Serve logger that's used outside of
individual Serve components."""
configure_component_logger(
component_name="serve",
component_id=str(os.getpid()),
logging_config=LoggingConfig(),
max_bytes=LOGGING_ROTATE_BYTES,
backup_count=LOGGING_ROTATE_BACKUP_COUNT,
stream_handler_only=True,
)
def configure_component_memory_profiler(
component_name: str,
component_id: str,
component_type: Optional[ServeComponentType] = None,
):
"""Configures the memory logger for this component.
Does nothing if RAY_SERVE_ENABLE_MEMORY_PROFILING is disabled.
"""
if RAY_SERVE_ENABLE_MEMORY_PROFILING:
logger = logging.getLogger(SERVE_LOGGER_NAME)
try:
import memray
logs_dir = get_serve_logs_dir()
memray_file_name = get_component_file_name(
component_name=component_name,
component_id=component_id,
component_type=component_type,
suffix="_memray_0.bin",
)
memray_file_path = os.path.join(logs_dir, memray_file_name)
# If the actor restarted, memray requires a new file to start
# tracking memory.
restart_counter = 1
while os.path.exists(memray_file_path):
memray_file_name = get_component_file_name(
component_name=component_name,
component_id=component_id,
component_type=component_type,
suffix=f"_memray_{restart_counter}.bin",
)
memray_file_path = os.path.join(logs_dir, memray_file_name)
restart_counter += 1
# Memray usually tracks the memory usage of only a block of code
# within a context manager. We explicitly call __enter__ here
# instead of using a context manager to track memory usage across
# all of the caller's code instead.
memray.Tracker(memray_file_path, native_traces=True).__enter__()
logger.info(
"RAY_SERVE_ENABLE_MEMORY_PROFILING is enabled. Started a "
"memray tracker on this actor. Tracker file located at "
f'"{memray_file_path}"'
)
except ImportError:
logger.warning(
"RAY_SERVE_ENABLE_MEMORY_PROFILING is enabled, but memray "
"is not installed. No memory profiling is happening. "
"`pip install memray` to enable memory profiling."
)
def get_serve_logs_dir() -> str:
"""Get the directory that stores Serve log files.
If `ray._private.worker._global_node` is None (running outside the context of Ray),
then the current working directory with subdirectory of serve is used as the logs
directory. Otherwise, the logs directory is determined by the global node's logs
directory path.
"""
if ray._private.worker._global_node is None:
return os.path.join(os.getcwd(), "serve")
return os.path.join(ray._private.worker._global_node.get_logs_dir_path(), "serve")
| StreamToLogger |
python | getsentry__sentry | tests/sentry/grouping/test_hashing.py | {
"start": 928,
"end": 2517
} | class ____(TestCase):
@override_options({"store.background-grouping-config-id": NO_MSG_PARAM_CONFIG})
@patch("sentry.grouping.ingest.hashing._calculate_background_grouping")
def test_background_grouping_sample_rate(
self, mock_calc_background_grouping: MagicMock
) -> None:
with override_options({"store.background-grouping-sample-rate": 0.0}):
save_new_event({"message": "Dogs are great! 1231"}, self.project)
assert mock_calc_background_grouping.call_count == 0
with override_options({"store.background-grouping-sample-rate": 1.0}):
save_new_event({"message": "Dogs are great! 1121"}, self.project)
assert mock_calc_background_grouping.call_count == 1
@override_options({"store.background-grouping-config-id": NO_MSG_PARAM_CONFIG})
@override_options({"store.background-grouping-sample-rate": 1.0})
@patch("sentry_sdk.capture_exception")
def test_handles_errors_with_background_grouping(
self, mock_capture_exception: MagicMock
) -> None:
background_grouping_error = Exception("nope")
with patch(
"sentry.grouping.ingest.hashing._calculate_background_grouping",
side_effect=background_grouping_error,
):
event = save_new_event({"message": "Dogs are great! 1231"}, self.project)
mock_capture_exception.assert_called_with(background_grouping_error)
# This proves the background grouping crash didn't crash the overall grouping process
assert event.group
| BackgroundGroupingTest |
python | openai__gym | gym/wrappers/frame_stack.py | {
"start": 2946,
"end": 6322
} | class ____(gym.ObservationWrapper):
"""Observation wrapper that stacks the observations in a rolling manner.
For example, if the number of stacks is 4, then the returned observation contains
the most recent 4 observations. For environment 'Pendulum-v1', the original observation
is an array with shape [3], so if we stack 4 observations, the processed observation
has shape [4, 3].
Note:
- To be memory efficient, the stacked observations are wrapped by :class:`LazyFrame`.
- The observation space must be :class:`Box` type. If one uses :class:`Dict`
as observation space, it should apply :class:`FlattenObservation` wrapper first.
- After :meth:`reset` is called, the frame buffer will be filled with the initial observation. I.e. the observation returned by :meth:`reset` will consist of ``num_stack`-many identical frames,
Example:
>>> import gym
>>> env = gym.make('CarRacing-v1')
>>> env = FrameStack(env, 4)
>>> env.observation_space
Box(4, 96, 96, 3)
>>> obs = env.reset()
>>> obs.shape
(4, 96, 96, 3)
"""
def __init__(
self,
env: gym.Env,
num_stack: int,
lz4_compress: bool = False,
):
"""Observation wrapper that stacks the observations in a rolling manner.
Args:
env (Env): The environment to apply the wrapper
num_stack (int): The number of frames to stack
lz4_compress (bool): Use lz4 to compress the frames internally
"""
super().__init__(env)
self.num_stack = num_stack
self.lz4_compress = lz4_compress
self.frames = deque(maxlen=num_stack)
low = np.repeat(self.observation_space.low[np.newaxis, ...], num_stack, axis=0)
high = np.repeat(
self.observation_space.high[np.newaxis, ...], num_stack, axis=0
)
self.observation_space = Box(
low=low, high=high, dtype=self.observation_space.dtype
)
def observation(self, observation):
"""Converts the wrappers current frames to lazy frames.
Args:
observation: Ignored
Returns:
:class:`LazyFrames` object for the wrapper's frame buffer, :attr:`self.frames`
"""
assert len(self.frames) == self.num_stack, (len(self.frames), self.num_stack)
return LazyFrames(list(self.frames), self.lz4_compress)
def step(self, action):
"""Steps through the environment, appending the observation to the frame buffer.
Args:
action: The action to step through the environment with
Returns:
Stacked observations, reward, terminated, truncated, and information from the environment
"""
observation, reward, terminated, truncated, info = self.env.step(action)
self.frames.append(observation)
return self.observation(None), reward, terminated, truncated, info
def reset(self, **kwargs):
"""Reset the environment with kwargs.
Args:
**kwargs: The kwargs for the environment reset
Returns:
The stacked observations
"""
obs, info = self.env.reset(**kwargs)
[self.frames.append(obs) for _ in range(self.num_stack)]
return self.observation(None), info
| FrameStack |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/common/struct_store/base.py | {
"start": 1154,
"end": 5441
} | class ____:
"""
Builder that builds context for a given set of SQL tables.
Args:
sql_database (Optional[SQLDatabase]): SQL database to use,
text_splitter (Optional[TextSplitter]): Text Splitter to use.
table_context_prompt (Optional[BasePromptTemplate]): A
Table Context Prompt (see :ref:`Prompt-Templates`).
refine_table_context_prompt (Optional[BasePromptTemplate]):
A Refine Table Context Prompt (see :ref:`Prompt-Templates`).
table_context_task (Optional[str]): The query to perform
on the table context. A default query string is used
if none is provided by the user.
"""
def __init__(
self,
sql_database: SQLDatabase,
llm: Optional[LLM] = None,
text_splitter: Optional[TextSplitter] = None,
table_context_prompt: Optional[BasePromptTemplate] = None,
refine_table_context_prompt: Optional[BasePromptTemplate] = None,
table_context_task: Optional[str] = None,
) -> None:
"""Initialize params."""
# TODO: take in an entire index instead of forming a response builder
if sql_database is None:
raise ValueError("sql_database must be provided.")
self._sql_database = sql_database
self._text_splitter = text_splitter
self._llm = llm or Settings.llm
self._prompt_helper = Settings._prompt_helper or PromptHelper.from_llm_metadata(
self._llm.metadata,
)
self._callback_manager = Settings.callback_manager
self._table_context_prompt = (
table_context_prompt or DEFAULT_TABLE_CONTEXT_PROMPT
)
self._refine_table_context_prompt = (
refine_table_context_prompt or DEFAULT_REFINE_TABLE_CONTEXT_PROMPT_SEL
)
self._table_context_task = table_context_task or DEFAULT_TABLE_CONTEXT_QUERY
def build_all_context_from_documents(
self,
documents_dict: Dict[str, List[BaseNode]],
) -> Dict[str, str]:
"""Build context for all tables in the database."""
context_dict = {}
for table_name in self._sql_database.get_usable_table_names():
context_dict[table_name] = self.build_table_context_from_documents(
documents_dict[table_name], table_name
)
return context_dict
def build_table_context_from_documents(
self,
documents: Sequence[BaseNode],
table_name: str,
) -> str:
"""Build context from documents for a single table."""
schema = self._sql_database.get_single_table_info(table_name)
prompt_with_schema = self._table_context_prompt.partial_format(schema=schema)
prompt_with_schema.metadata["prompt_type"] = PromptType.QUESTION_ANSWER
refine_prompt_with_schema = self._refine_table_context_prompt.partial_format(
schema=schema
)
refine_prompt_with_schema.metadata["prompt_type"] = PromptType.REFINE
text_splitter = (
self._text_splitter
or self._prompt_helper.get_text_splitter_given_prompt(
prompt_with_schema, llm=self._llm
)
)
# we use the ResponseBuilder to iteratively go through all texts
response_builder = get_response_synthesizer(
llm=self._llm,
text_qa_template=prompt_with_schema,
refine_template=refine_prompt_with_schema,
)
with self._callback_manager.event(
CBEventType.CHUNKING,
payload={EventPayload.DOCUMENTS: documents},
) as event:
text_chunks = []
for doc in documents:
chunks = text_splitter.split_text(
doc.get_content(metadata_mode=MetadataMode.LLM)
)
text_chunks.extend(chunks)
event.on_end(
payload={EventPayload.CHUNKS: text_chunks},
)
# feed in the "query_str" or the task
table_context = response_builder.get_response(
text_chunks=text_chunks, query_str=self._table_context_task
)
return cast(str, table_context)
OUTPUT_PARSER_TYPE = Callable[[str], Optional[Dict[str, Any]]]
| SQLDocumentContextBuilder |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py | {
"start": 10118,
"end": 12442
} | class ____:
@pytest.mark.parametrize(
("dag_id", "run_id", "state", "run_type", "triggered_by", "dag_run_note"),
[
(
DAG1_ID,
DAG1_RUN1_ID,
DAG1_RUN1_STATE,
DAG1_RUN1_RUN_TYPE,
DAG1_RUN1_TRIGGERED_BY,
DAG1_RUN1_NOTE,
),
(
DAG1_ID,
DAG1_RUN2_ID,
DAG1_RUN2_STATE,
DAG1_RUN2_RUN_TYPE,
DAG1_RUN2_TRIGGERED_BY,
None,
),
(
DAG2_ID,
DAG2_RUN1_ID,
DAG2_RUN1_STATE,
DAG2_RUN1_RUN_TYPE,
DAG2_RUN1_TRIGGERED_BY,
None,
),
(
DAG2_ID,
DAG2_RUN2_ID,
DAG2_RUN2_STATE,
DAG2_RUN2_RUN_TYPE,
DAG2_RUN2_TRIGGERED_BY,
None,
),
],
)
@pytest.mark.usefixtures("configure_git_connection_for_dag_bundle")
def test_get_dag_run(self, test_client, dag_id, run_id, state, run_type, triggered_by, dag_run_note):
response = test_client.get(f"/dags/{dag_id}/dagRuns/{run_id}")
assert response.status_code == 200
body = response.json()
assert body["dag_id"] == dag_id
assert body["dag_run_id"] == run_id
assert body["state"] == state
assert body["run_type"] == run_type
assert body["triggered_by"] == triggered_by.value
assert body["note"] == dag_run_note
def test_get_dag_run_not_found(self, test_client):
response = test_client.get(f"/dags/{DAG1_ID}/dagRuns/invalid")
assert response.status_code == 404
body = response.json()
assert body["detail"] == "The DagRun with dag_id: `test_dag1` and run_id: `invalid` was not found"
def test_should_respond_401(self, unauthenticated_test_client):
response = unauthenticated_test_client.get(f"/dags/{DAG1_ID}/dagRuns/invalid")
assert response.status_code == 401
def test_should_respond_403(self, unauthorized_test_client):
response = unauthorized_test_client.get(f"/dags/{DAG1_ID}/dagRuns/invalid")
assert response.status_code == 403
| TestGetDagRun |
python | pennersr__django-allauth | allauth/account/forms.py | {
"start": 29783,
"end": 30299
} | class ____(BaseConfirmCodeForm):
def __init__(self, *args, **kwargs) -> None:
self.user = kwargs.pop("user", None)
self.email = kwargs.pop("email", None)
super().__init__(*args, **kwargs)
def clean_code(self) -> str:
code = super().clean_code()
if code:
# We have a valid code. But, can we actually perform the change?
email_already_exists(user=self.user, email=self.email, always_raise=True)
return code
| ConfirmEmailVerificationCodeForm |
python | ray-project__ray | python/ray/serve/tests/test_config_files/grpc_deployment.py | {
"start": 2901,
"end": 3107
} | class ____:
def __init__(self):
self.price = 2.0
def __call__(self, num_oranges: int):
return num_oranges * self.price
@serve.deployment(ray_actor_options={"num_cpus": 0})
| OrangeStand |
python | xlwings__xlwings | xlwings/pro/_xlremote.py | {
"start": 32456,
"end": 34547
} | class ____(base_classes.Names):
def __init__(self, parent, api):
self.parent = parent
self.api = api
def add(self, name, refers_to):
# TODO: raise backend error in case of duplicates
if isinstance(self.parent, Book):
is_parent_book = True
else:
is_parent_book = False
self.parent.append_json_action(func="namesAdd", args=[name, refers_to])
def _get_sheet_index(parent):
if is_parent_book:
sheets = parent.sheets
else:
sheets = parent.book.sheets
for sheet in sheets:
if sheet.name == refers_to.split("!")[0].replace("=", "").replace(
"'", ""
):
return sheet.index - 1
return Name(
self.parent,
{
"name": name,
"sheet_index": _get_sheet_index(self.parent),
"address": refers_to.split("!")[1].replace("$", ""),
"book_scope": True if is_parent_book else False,
},
)
def __call__(self, name_or_index):
if isinstance(name_or_index, numbers.Number):
name_or_index -= 1
if name_or_index > len(self):
raise KeyError(name_or_index)
else:
return Name(self.parent, api=self.api[name_or_index])
else:
for ix, i in enumerate(self.api):
name = Name(self.parent, api=self.api[ix])
if name.name == name_or_index:
# Sheet scope names have the sheet name prepended
return name
raise KeyError(name_or_index)
def contains(self, name_or_index):
if isinstance(name_or_index, numbers.Number):
return 1 <= name_or_index <= len(self)
else:
for i in self.api:
if i["name"] == name_or_index:
return True
return False
def __len__(self):
return len(self.api)
engine = Engine()
| Names |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 17869,
"end": 17932
} | class ____(TrackedConcreteBase):
pass
| TrackedWithConcreteBase |
python | openai__openai-python | tests/api_resources/test_realtime.py | {
"start": 223,
"end": 352
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
| TestRealtime |
python | spack__spack | lib/spack/spack/ci/common.py | {
"start": 4909,
"end": 10081
} | class ____:
"""
Class for managing CDash data and processing.
"""
def __init__(self, ci_cdash):
# start with the gitlab ci configuration
self.url = ci_cdash.get("url")
self.build_group = ci_cdash.get("build-group")
self.project = ci_cdash.get("project")
self.site = ci_cdash.get("site")
# grab the authorization token when available
self.auth_token = os.environ.get("SPACK_CDASH_AUTH_TOKEN")
if self.auth_token:
tty.verbose("Using CDash auth token from environment")
# append runner description to the site if available
runner = os.environ.get("CI_RUNNER_DESCRIPTION")
if runner:
self.site += f" ({runner})"
def args(self):
return [
"--cdash-upload-url",
win_quote(self.upload_url),
"--cdash-build",
win_quote(self.build_name()),
"--cdash-site",
win_quote(self.site),
"--cdash-buildstamp",
win_quote(self.build_stamp),
]
def build_name(self, spec: Optional[spack.spec.Spec] = None) -> Optional[str]:
"""Returns the CDash build name.
A name will be generated if the ``spec`` is provided,
otherwise, the value will be retrieved from the environment
through the ``SPACK_CDASH_BUILD_NAME`` variable.
Returns: (str) given spec's CDash build name."""
if spec:
spec_str = spec.format("{name}{@version}{%compiler} hash={hash} arch={architecture}")
build_name = f"{spec_str} ({self.build_group})"
tty.debug(f"Generated CDash build name ({build_name}) from the {spec.name}")
return build_name
env_build_name = os.environ.get("SPACK_CDASH_BUILD_NAME")
tty.debug(f"Using CDash build name ({env_build_name}) from the environment")
return env_build_name
@property # type: ignore
def build_stamp(self):
"""Returns the CDash build stamp.
The one defined by SPACK_CDASH_BUILD_STAMP environment variable
is preferred due to the representation of timestamps; otherwise,
one will be built.
Returns: (str) current CDash build stamp"""
build_stamp = os.environ.get("SPACK_CDASH_BUILD_STAMP")
if build_stamp:
tty.debug(f"Using build stamp ({build_stamp}) from the environment")
return build_stamp
build_stamp = cdash_build_stamp(self.build_group, time.time())
tty.debug(f"Generated new build stamp ({build_stamp})")
return build_stamp
@property # type: ignore
@memoized
def project_enc(self):
tty.debug(f"Encoding project ({type(self.project)}): {self.project})")
encode = urlencode({"project": self.project})
index = encode.find("=") + 1
return encode[index:]
@property
def upload_url(self):
url_format = f"{self.url}/submit.php?project={self.project_enc}"
return url_format
def copy_test_results(self, source, dest):
"""Copy test results to artifacts directory."""
reports = fs.join_path(source, "*_Test*.xml")
copy_files_to_artifacts(reports, dest)
def create_buildgroup(self):
"""Create the CDash buildgroup if it does not already exist."""
headers = {
"Authorization": f"Bearer {self.auth_token}",
"Content-Type": "application/json",
}
data = {"newbuildgroup": self.build_group, "project": self.project, "type": "Daily"}
enc_data = json.dumps(data).encode("utf-8")
request = Request(f"{self.url}/api/v1/buildgroup.php", data=enc_data, headers=headers)
response_text = None
group_id = None
try:
response_text = _urlopen(request, timeout=SPACK_CDASH_TIMEOUT).read()
except OSError as e:
tty.warn(f"Failed to create CDash buildgroup: {e}")
if response_text:
try:
response_json = json.loads(response_text)
group_id = response_json["id"]
except (json.JSONDecodeError, KeyError) as e:
tty.warn(f"Failed to parse CDash response: {e}")
if not group_id:
tty.warn(f"Failed to create or retrieve buildgroup for {self.build_group}")
def report_skipped(self, spec: spack.spec.Spec, report_dir: str, reason: Optional[str]):
"""Explicitly report skipping testing of a spec (e.g., it's CI
configuration identifies it as known to have broken tests or
the CI installation failed).
Args:
spec: spec being tested
report_dir: directory where the report will be written
reason: reason the test is being skipped
"""
configuration = CDashConfiguration(
upload_url=self.upload_url,
packages=[spec.name],
build=self.build_name(),
site=self.site,
buildstamp=self.build_stamp,
track=None,
)
reporter = CDash(configuration=configuration)
reporter.test_skipped_report(report_dir, spec, reason)
| CDashHandler |
python | django-haystack__django-haystack | haystack/utils/highlighting.py | {
"start": 43,
"end": 5645
} | class ____:
css_class = "highlighted"
html_tag = "span"
max_length = 200
text_block = ""
def __init__(self, query, **kwargs):
self.query = query
if "max_length" in kwargs:
self.max_length = int(kwargs["max_length"])
if "html_tag" in kwargs:
self.html_tag = kwargs["html_tag"]
if "css_class" in kwargs:
self.css_class = kwargs["css_class"]
self.query_words = {
word.lower() for word in self.query.split() if not word.startswith("-")
}
def highlight(self, text_block):
self.text_block = strip_tags(text_block)
highlight_locations = self.find_highlightable_words()
start_offset, end_offset = self.find_window(highlight_locations)
return self.render_html(highlight_locations, start_offset, end_offset)
def find_highlightable_words(self):
# Use a set so we only do this once per unique word.
word_positions = {}
# Pre-compute the length.
end_offset = len(self.text_block)
lower_text_block = self.text_block.lower()
for word in self.query_words:
if word not in word_positions:
word_positions[word] = []
start_offset = 0
while start_offset < end_offset:
next_offset = lower_text_block.find(word, start_offset, end_offset)
# If we get a -1 out of find, it wasn't found. Bomb out and
# start the next word.
if next_offset == -1:
break
word_positions[word].append(next_offset)
start_offset = next_offset + len(word)
return word_positions
def find_window(self, highlight_locations):
best_start = 0
best_end = self.max_length
# First, make sure we have words.
if not len(highlight_locations):
return (best_start, best_end)
words_found = []
# Next, make sure we found any words at all.
for _, offset_list in highlight_locations.items():
if len(offset_list):
# Add all of the locations to the list.
words_found.extend(offset_list)
if not len(words_found):
return (best_start, best_end)
if len(words_found) == 1:
return (words_found[0], words_found[0] + self.max_length)
# Sort the list so it's in ascending order.
words_found = sorted(words_found)
# We now have a denormalized list of all positions were a word was
# found. We'll iterate through and find the densest window we can by
# counting the number of found offsets (-1 to fit in the window).
highest_density = 0
if words_found[:-1][0] > self.max_length:
best_start = words_found[:-1][0]
best_end = best_start + self.max_length
for count, start in enumerate(words_found[:-1]):
current_density = 1
for end in words_found[count + 1 :]:
if end - start < self.max_length:
current_density += 1
else:
current_density = 0
# Only replace if we have a bigger (not equal density) so we
# give deference to windows earlier in the document.
if current_density > highest_density:
best_start = start
best_end = start + self.max_length
highest_density = current_density
return (best_start, best_end)
def render_html(self, highlight_locations=None, start_offset=None, end_offset=None):
# Start by chopping the block down to the proper window.
text = self.text_block[start_offset:end_offset]
# Invert highlight_locations to a location -> term list
term_list = []
for term, locations in highlight_locations.items():
term_list += [(loc - start_offset, term) for loc in locations]
loc_to_term = sorted(term_list)
# Prepare the highlight template
if self.css_class:
hl_start = '<%s class="%s">' % (self.html_tag, self.css_class)
else:
hl_start = "<%s>" % (self.html_tag)
hl_end = "</%s>" % self.html_tag
# Copy the part from the start of the string to the first match,
# and there replace the match with a highlighted version.
highlighted_chunk = ""
matched_so_far = 0
prev = 0
prev_str = ""
for cur, cur_str in loc_to_term:
# This can be in a different case than cur_str
actual_term = text[cur : cur + len(cur_str)]
# Handle incorrect highlight_locations by first checking for the term
if actual_term.lower() == cur_str:
if cur < prev + len(prev_str):
continue
highlighted_chunk += (
text[prev + len(prev_str) : cur] + hl_start + actual_term + hl_end
)
prev = cur
prev_str = cur_str
# Keep track of how far we've copied so far, for the last step
matched_so_far = cur + len(actual_term)
# Don't forget the chunk after the last term
highlighted_chunk += text[matched_so_far:]
if start_offset > 0:
highlighted_chunk = "...%s" % highlighted_chunk
if end_offset < len(self.text_block):
highlighted_chunk = "%s..." % highlighted_chunk
return highlighted_chunk
| Highlighter |
python | pallets__jinja | tests/test_utils.py | {
"start": 3820,
"end": 4447
} | class ____:
def test_escape_urlize_target(self):
url = "http://example.org"
target = "<script>"
assert urlize(url, target=target) == (
'<a href="http://example.org"'
' target="<script>">'
"http://example.org</a>"
)
def test_urlize_mail_mastodon(self):
fr = "nabijaczleweli@nabijaczleweli.xyz\n@eater@cijber.social\n"
to = (
'<a href="mailto:nabijaczleweli@nabijaczleweli.xyz">'
"nabijaczleweli@nabijaczleweli.xyz</a>\n@eater@cijber.social\n"
)
assert urlize(fr) == to
| TestEscapeUrlizeTarget |
python | dagster-io__dagster | python_modules/libraries/dagster-postgres/dagster_postgres/event_log/event_log.py | {
"start": 1674,
"end": 16145
} | class ____(SqlEventLogStorage, ConfigurableClass):
"""Postgres-backed event log storage.
Users should not directly instantiate this class; it is instantiated by internal machinery when
``dagster-webserver`` and ``dagster-graphql`` load, based on the values in the ``dagster.yaml`` file in
``$DAGSTER_HOME``. Configuration of this class should be done by setting values in that file.
To use Postgres for all of the components of your instance storage, you can add the following
block to your ``dagster.yaml``:
.. literalinclude:: ../../../../../../examples/docs_snippets/docs_snippets/deploying/dagster-pg.yaml
:caption: dagster.yaml
:lines: 1-8
:language: YAML
If you are configuring the different storage components separately and are specifically
configuring your event log storage to use Postgres, you can add a block such as the following
to your ``dagster.yaml``:
.. literalinclude:: ../../../../../../examples/docs_snippets/docs_snippets/deploying/dagster-pg-legacy.yaml
:caption: dagster.yaml
:lines: 12-21
:language: YAML
Note that the fields in this config are :py:class:`~dagster.StringSource` and
:py:class:`~dagster.IntSource` and can be configured from environment variables.
"""
def __init__(
self,
postgres_url: str,
should_autocreate_tables: bool = True,
inst_data: Optional[ConfigurableClassData] = None,
):
self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData)
self.postgres_url = check.str_param(postgres_url, "postgres_url")
self.should_autocreate_tables = check.bool_param(
should_autocreate_tables, "should_autocreate_tables"
)
# Default to not holding any connections open to prevent accumulating connections per DagsterInstance
self._engine = create_engine(
self.postgres_url, isolation_level="AUTOCOMMIT", poolclass=db_pool.NullPool
)
self._event_watcher: Optional[SqlPollingEventWatcher] = None
self._secondary_index_cache = {}
# Stamp and create tables if the main table does not exist (we can't check alembic
# revision because alembic config may be shared with other storage classes)
if self.should_autocreate_tables:
table_names = retry_pg_connection_fn(lambda: db.inspect(self._engine).get_table_names())
if "event_logs" not in table_names:
retry_pg_creation_fn(self._init_db)
self.reindex_events()
self.reindex_assets()
super().__init__()
def _init_db(self) -> None:
with self._connect() as conn:
with conn.begin():
SqlEventLogStorageMetadata.create_all(conn)
stamp_alembic_rev(pg_alembic_config(__file__), conn)
def optimize_for_webserver(
self, statement_timeout: int, pool_recycle: int, max_overflow: int
) -> None:
# When running in dagster-webserver, hold an open connection and set statement_timeout
kwargs = {
"isolation_level": "AUTOCOMMIT",
"pool_size": 1,
"pool_recycle": pool_recycle,
"max_overflow": max_overflow,
}
existing_options = self._engine.url.query.get("options")
if existing_options:
kwargs["connect_args"] = {"options": existing_options}
self._engine = create_engine(self.postgres_url, **kwargs)
event.listen(
self._engine,
"connect",
lambda connection, _: set_pg_statement_timeout(connection, statement_timeout),
)
def upgrade(self) -> None:
alembic_config = pg_alembic_config(__file__)
with self._connect() as conn:
run_alembic_upgrade(alembic_config, conn)
@property
def inst_data(self) -> Optional[ConfigurableClassData]:
return self._inst_data
@classmethod
def config_type(cls) -> UserConfigSchema:
return pg_config()
@classmethod
def from_config_value(
cls, inst_data: Optional[ConfigurableClassData], config_value: Mapping[str, Any]
) -> "PostgresEventLogStorage":
return PostgresEventLogStorage(
inst_data=inst_data,
postgres_url=pg_url_from_config(config_value),
should_autocreate_tables=config_value.get("should_autocreate_tables", True),
)
@staticmethod
def create_clean_storage(
conn_string: str, should_autocreate_tables: bool = True
) -> "PostgresEventLogStorage":
engine = create_engine(
conn_string, isolation_level="AUTOCOMMIT", poolclass=db_pool.NullPool
)
try:
SqlEventLogStorageMetadata.drop_all(engine)
finally:
engine.dispose()
return PostgresEventLogStorage(conn_string, should_autocreate_tables)
def store_event(self, event: EventLogEntry) -> None:
"""Store an event corresponding to a run.
Args:
event (EventLogEntry): The event to store.
"""
check.inst_param(event, "event", EventLogEntry)
insert_event_statement = self.prepare_insert_event(event) # from SqlEventLogStorage.py
with self._connect() as conn:
result = conn.execute(
insert_event_statement.returning(
SqlEventLogStorageTable.c.run_id, SqlEventLogStorageTable.c.id
)
)
res = result.fetchone()
result.close()
# LISTEN/NOTIFY no longer used for pg event watch - preserved here to support version skew
conn.execute(
db.text(f"""NOTIFY {CHANNEL_NAME}, :notify_id; """),
{"notify_id": res[0] + "_" + str(res[1])}, # type: ignore
)
event_id = int(res[1]) # type: ignore
if (
event.is_dagster_event
and event.dagster_event_type in ASSET_EVENTS
and event.dagster_event.asset_key # type: ignore
):
self.store_asset_event(event, event_id)
if event_id is None:
raise DagsterInvariantViolationError(
"Cannot store asset event tags for null event id."
)
self.store_asset_event_tags([event], [event_id])
if event.is_dagster_event and event.dagster_event_type in ASSET_CHECK_EVENTS:
self.store_asset_check_event(event, event_id)
def store_event_batch(self, events: Sequence[EventLogEntry]) -> None:
from dagster import DagsterEventType
check.sequence_param(events, "event", of_type=EventLogEntry)
event_types = {event.get_dagster_event().event_type for event in events}
check.invariant(
all(event_type in BATCH_WRITABLE_EVENTS for event_type in event_types),
f"{BATCH_WRITABLE_EVENTS} are the only currently supported events for batch writes.",
)
events = [
event
for event in events
if not event.get_dagster_event().is_asset_failed_to_materialize
]
if len(events) == 0:
return
if event_types == {DagsterEventType.ASSET_MATERIALIZATION} or event_types == {
DagsterEventType.ASSET_OBSERVATION
}:
insert_event_statement = self.prepare_insert_event_batch(events)
with self._connect() as conn:
result = conn.execute(
insert_event_statement.returning(SqlEventLogStorageTable.c.id)
)
event_ids = [cast("int", row[0]) for row in result.fetchall()]
# We only update the asset table with the last event
self.store_asset_event(events[-1], event_ids[-1])
if any(event_id is None for event_id in event_ids):
raise DagsterInvariantViolationError(
"Cannot store asset event tags for null event id."
)
self.store_asset_event_tags(events, event_ids)
else:
return super().store_event_batch(events)
def store_asset_event(self, event: EventLogEntry, event_id: int) -> None:
check.inst_param(event, "event", EventLogEntry)
if not (event.dagster_event and event.dagster_event.asset_key):
return
# We switched to storing the entire event record of the last materialization instead of just
# the AssetMaterialization object, so that we have access to metadata like timestamp,
# job, run_id, etc.
#
# This should make certain asset queries way more performant, without having to do extra
# queries against the event log.
#
# This should be accompanied by a schema change in 0.12.0, renaming `last_materialization`
# to `last_materialization_event`, for clarity. For now, we should do some back-compat.
#
# https://github.com/dagster-io/dagster/issues/3945
# The AssetKeyTable contains a `last_materialization_timestamp` column that is exclusively
# used to determine if an asset exists (last materialization timestamp > wipe timestamp).
# This column is used nowhere else, and as of AssetObservation/AssetMaterializationPlanned
# event creation, we want to extend this functionality to ensure that assets with any event
# (observation, materialization, or materialization planned) yielded with timestamp
# > wipe timestamp display in the Dagster UI.
# As of the following PRs, we update last_materialization_timestamp to store the timestamp
# of the latest asset observation, materialization, or materialization_planned that has occurred.
# https://github.com/dagster-io/dagster/pull/6885
# https://github.com/dagster-io/dagster/pull/7319
# The AssetKeyTable also contains a `last_run_id` column that is updated upon asset
# materialization. This column was not being used until the below PR. This new change
# writes to the column upon `ASSET_MATERIALIZATION_PLANNED` events to fetch the last
# run id for a set of assets in one roundtrip call to event log storage.
# https://github.com/dagster-io/dagster/pull/7319
values = self._get_asset_entry_values(
event, event_id, self.has_secondary_index(ASSET_KEY_INDEX_COLS)
)
with self.index_connection() as conn:
query = db_dialects.postgresql.insert(AssetKeyTable).values(
asset_key=event.dagster_event.asset_key.to_string(),
**values,
)
if values:
query = query.on_conflict_do_update(
index_elements=[AssetKeyTable.c.asset_key],
set_=dict(**values),
)
else:
query = query.on_conflict_do_nothing()
conn.execute(query)
def add_dynamic_partitions(
self, partitions_def_name: str, partition_keys: Sequence[str]
) -> None:
if not partition_keys:
return
# Overload base implementation to push upsert logic down into the db layer
self._check_partitions_table()
with self.index_connection() as conn:
conn.execute(
db_dialects.postgresql.insert(DynamicPartitionsTable)
.values(
[
dict(partitions_def_name=partitions_def_name, partition=partition_key)
for partition_key in partition_keys
]
)
.on_conflict_do_nothing(),
)
def _connect(self) -> ContextManager[Connection]:
return create_pg_connection(self._engine)
def run_connection(self, run_id: Optional[str] = None) -> ContextManager[Connection]:
return self._connect()
def index_connection(self) -> ContextManager[Connection]:
return self._connect()
@contextmanager
def index_transaction(self) -> Iterator[Connection]:
"""Context manager yielding a connection to the index shard that has begun a transaction."""
with self.index_connection() as conn:
if conn.in_transaction():
yield conn
else:
conn = conn.execution_options(isolation_level="READ COMMITTED") # noqa: PLW2901
with conn.begin():
yield conn
def has_table(self, table_name: str) -> bool:
return bool(self._engine.dialect.has_table(self._engine.connect(), table_name))
def has_secondary_index(self, name: str) -> bool:
if name not in self._secondary_index_cache:
self._secondary_index_cache[name] = super().has_secondary_index(name)
return self._secondary_index_cache[name]
def enable_secondary_index(self, name: str) -> None:
super().enable_secondary_index(name)
if name in self._secondary_index_cache:
del self._secondary_index_cache[name]
def watch(
self,
run_id: str,
cursor: Optional[str],
callback: EventHandlerFn,
) -> None:
if cursor and EventLogCursor.parse(cursor).is_offset_cursor():
check.failed("Cannot call `watch` with an offset cursor")
if self._event_watcher is None:
self._event_watcher = SqlPollingEventWatcher(self)
self._event_watcher.watch_run(run_id, cursor, callback)
def _gen_event_log_entry_from_cursor(self, cursor) -> EventLogEntry:
with self._engine.connect() as conn:
cursor_res = conn.execute(
db_select([SqlEventLogStorageTable.c.event]).where(
SqlEventLogStorageTable.c.id == cursor
),
)
return deserialize_value(cursor_res.scalar(), EventLogEntry) # type: ignore
def end_watch(self, run_id: str, handler: EventHandlerFn) -> None:
if self._event_watcher:
self._event_watcher.unwatch_run(run_id, handler)
def dispose(self) -> None:
if self._event_watcher:
self._event_watcher.close()
self._event_watcher = None
def alembic_version(self) -> AlembicVersion:
alembic_config = pg_alembic_config(__file__)
with self._connect() as conn:
return check_alembic_revision(alembic_config, conn)
| PostgresEventLogStorage |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/auto_suggest.py | {
"start": 3508,
"end": 3746
} | class ____(AutoSuggest):
"""
AutoSuggest class that doesn't return any suggestion.
"""
def get_suggestion(self, buffer: Buffer, document: Document) -> Suggestion | None:
return None # No suggestion
| DummyAutoSuggest |
python | getsentry__sentry | src/sentry/notifications/platform/types.py | {
"start": 5795,
"end": 6242
} | class ____(Protocol):
"""
A block that applies formatting such as a newline and encapsulates other text.
"""
type: NotificationBodyFormattingBlockType
"""
The type of the block, such as ParagraphBlock, BoldTextBlock, etc.
"""
blocks: list[NotificationBodyTextBlock]
"""
Some blocks may want to contain other blocks, such as a ParagraphBlock containing a BoldTextBlock.
"""
| NotificationBodyFormattingBlock |
python | oauthlib__oauthlib | examples/skeleton_oauth2_web_application_server.py | {
"start": 360,
"end": 4594
} | class ____(RequestValidator):
# Ordered roughly in order of appearance in the authorization grant flow
# Pre- and post-authorization.
def validate_client_id(self, client_id, request, *args, **kwargs):
# Simple validity check, does client exist? Not banned?
pass
def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs):
# Is the client allowed to use the supplied redirect_uri? i.e. has
# the client previously registered this EXACT redirect uri.
pass
def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
# The redirect used if none has been supplied.
# Prefer your clients to pre register a redirect uri rather than
# supplying one on each authorization request.
pass
def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs):
# Is the client allowed to access the requested scopes?
pass
def get_default_scopes(self, client_id, request, *args, **kwargs):
# Scopes a client will authorize for if none are supplied in the
# authorization request.
pass
def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs):
# Clients should only be allowed to use one type of response type, the
# one associated with their one allowed grant type.
# In this case it must be "code".
pass
# Post-authorization
def save_authorization_code(self, client_id, code, request, *args, **kwargs):
# Remember to associate it with request.scopes, request.redirect_uri
# request.client and request.user (the last is passed in
# post_authorization credentials, i.e. { 'user': request.user}.
pass
# Token request
def client_authentication_required(self, request, *args, **kwargs):
# Check if the client provided authentication information that needs to
# be validated, e.g. HTTP Basic auth
pass
def authenticate_client(self, request, *args, **kwargs):
# Whichever authentication method suits you, HTTP Basic might work
pass
def authenticate_client_id(self, client_id, request, *args, **kwargs):
# The client_id must match an existing public (non-confidential) client
pass
def validate_code(self, client_id, code, client, request, *args, **kwargs):
# Validate the code belongs to the client. Add associated scopes
# and user to request.scopes and request.user.
pass
def confirm_redirect_uri(self, client_id, code, redirect_uri, client, request, *args, **kwargs):
# You did save the redirect uri with the authorization code right?
pass
def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs):
# Clients should only be allowed to use one type of grant.
# In this case, it must be "authorization_code" or "refresh_token"
pass
def save_bearer_token(self, token, request, *args, **kwargs):
# Remember to associate it with request.scopes, request.user and
# request.client. The two former will be set when you validate
# the authorization code. Don't forget to save both the
# access_token and the refresh_token and set expiration for the
# access_token to now + expires_in seconds.
pass
def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs):
# Authorization codes are use once, invalidate it when a Bearer token
# has been acquired.
pass
# Protected resource request
def validate_bearer_token(self, token, scopes, request):
# Remember to check expiration and scope membership
pass
# Token refresh request
def get_original_scopes(self, refresh_token, request, *args, **kwargs):
# Obtain the token associated with the given refresh_token and
# return its scopes, these will be passed on to the refreshed
# access token if the client did not specify a scope during the
# request.
pass
validator = SkeletonValidator()
server = WebApplicationServer(validator)
| SkeletonValidator |
python | mlflow__mlflow | tests/pyfunc/test_pyfunc_input_converter.py | {
"start": 1638,
"end": 2529
} | class ____(ChatCompletionRequest):
custom_input: Optional[CustomInput] = None # noqa: UP045
another_custom_input: CustomInput | None = None
def test_hydrate_child_dataclass():
result = _hydrate_dataclass(
FlexibleChatCompletionRequest,
asdict(
FlexibleChatCompletionRequest(
custom_input=CustomInput(), another_custom_input=CustomInput()
)
),
)
assert result == FlexibleChatCompletionRequest(
custom_input=CustomInput(), another_custom_input=CustomInput()
)
def test_hydrate_optional_dataclass():
result = _hydrate_dataclass(
FlexibleChatCompletionRequest,
asdict(FlexibleChatCompletionRequest(custom_input=None, another_custom_input=None)),
)
assert result == FlexibleChatCompletionRequest(custom_input=None, another_custom_input=None)
| FlexibleChatCompletionRequest |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 19077,
"end": 28636
} | class ____(GeneratedAirbyteDestination):
class PLAINTEXT:
@public
def __init__(self, security_protocol: str):
self.security_protocol = check.str_param(security_protocol, "security_protocol")
class SASLPLAINTEXT:
@public
def __init__(self, security_protocol: str, sasl_mechanism: str, sasl_jaas_config: str):
self.security_protocol = check.str_param(security_protocol, "security_protocol")
self.sasl_mechanism = check.str_param(sasl_mechanism, "sasl_mechanism")
self.sasl_jaas_config = check.str_param(sasl_jaas_config, "sasl_jaas_config")
class SASLSSL:
@public
def __init__(self, security_protocol: str, sasl_mechanism: str, sasl_jaas_config: str):
self.security_protocol = check.str_param(security_protocol, "security_protocol")
self.sasl_mechanism = check.str_param(sasl_mechanism, "sasl_mechanism")
self.sasl_jaas_config = check.str_param(sasl_jaas_config, "sasl_jaas_config")
@public
def __init__(
self,
name: str,
bootstrap_servers: str,
topic_pattern: str,
protocol: Union[
"KafkaDestination.PLAINTEXT",
"KafkaDestination.SASLPLAINTEXT",
"KafkaDestination.SASLSSL",
],
acks: str,
enable_idempotence: bool,
compression_type: str,
batch_size: int,
linger_ms: str,
max_in_flight_requests_per_connection: int,
client_dns_lookup: str,
buffer_memory: str,
max_request_size: int,
retries: int,
socket_connection_setup_timeout_ms: str,
socket_connection_setup_timeout_max_ms: str,
max_block_ms: str,
request_timeout_ms: int,
delivery_timeout_ms: int,
send_buffer_bytes: int,
receive_buffer_bytes: int,
test_topic: Optional[str] = None,
sync_producer: Optional[bool] = None,
client_id: Optional[str] = None,
):
"""Airbyte Destination for Kafka.
Documentation can be found at https://docs.airbyte.com/integrations/destinations/kafka
Args:
name (str): The name of the destination.
bootstrap_servers (str): A list of host/port pairs to use for establishing the initial connection to the Kafka cluster. The client will make use of all servers irrespective of which servers are specified here for bootstrapping—this list only impacts the initial hosts used to discover the full set of servers. This list should be in the form host1:port1,host2:port2,.... Since these servers are just used for the initial connection to discover the full cluster membership (which may change dynamically), this list need not contain the full set of servers (you may want more than one, though, in case a server is down).
topic_pattern (str): Topic pattern in which the records will be sent. You can use patterns like '{namespace}' and/or '{stream}' to send the message to a specific topic based on these values. Notice that the topic name will be transformed to a standard naming convention.
test_topic (Optional[str]): Topic to test if Airbyte can produce messages.
sync_producer (Optional[bool]): Wait synchronously until the record has been sent to Kafka.
protocol (Union[KafkaDestination.PLAINTEXT, KafkaDestination.SASLPLAINTEXT, KafkaDestination.SASLSSL]): Protocol used to communicate with brokers.
client_id (Optional[str]): An ID string to pass to the server when making requests. The purpose of this is to be able to track the source of requests beyond just ip/port by allowing a logical application name to be included in server-side request logging.
acks (str): The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent.
enable_idempotence (bool): When set to 'true', the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries due to broker failures, etc., may write duplicates of the retried message in the stream.
compression_type (str): The compression type for all data generated by the producer.
batch_size (int): The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition.
linger_ms (str): The producer groups together any records that arrive in between request transmissions into a single batched request.
max_in_flight_requests_per_connection (int): The maximum number of unacknowledged requests the client will send on a single connection before blocking. Can be greater than 1, and the maximum value supported with idempotency is 5.
client_dns_lookup (str): Controls how the client uses DNS lookups. If set to use_all_dns_ips, connect to each returned IP address in sequence until a successful connection is established. After a disconnection, the next IP is used. Once all IPs have been used once, the client resolves the IP(s) from the hostname again. If set to resolve_canonical_bootstrap_servers_only, resolve each bootstrap address into a list of canonical names. After the bootstrap phase, this behaves the same as use_all_dns_ips. If set to default (deprecated), attempt to connect to the first IP address returned by the lookup, even if the lookup returns multiple IP addresses.
buffer_memory (str): The total bytes of memory the producer can use to buffer records waiting to be sent to the server.
max_request_size (int): The maximum size of a request in bytes.
retries (int): Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error.
socket_connection_setup_timeout_ms (str): The amount of time the client will wait for the socket connection to be established.
socket_connection_setup_timeout_max_ms (str): The maximum amount of time the client will wait for the socket connection to be established. The connection setup timeout will increase exponentially for each consecutive connection failure up to this maximum.
max_block_ms (str): The configuration controls how long the KafkaProducer's send(), partitionsFor(), initTransactions(), sendOffsetsToTransaction(), commitTransaction() and abortTransaction() methods will block.
request_timeout_ms (int): The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted.
delivery_timeout_ms (int): An upper bound on the time to report success or failure after a call to 'send()' returns.
send_buffer_bytes (int): The size of the TCP send buffer (SO_SNDBUF) to use when sending data. If the value is -1, the OS default will be used.
receive_buffer_bytes (int): The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. If the value is -1, the OS default will be used.
"""
self.bootstrap_servers = check.str_param(bootstrap_servers, "bootstrap_servers")
self.topic_pattern = check.str_param(topic_pattern, "topic_pattern")
self.test_topic = check.opt_str_param(test_topic, "test_topic")
self.sync_producer = check.opt_bool_param(sync_producer, "sync_producer")
self.protocol = check.inst_param(
protocol,
"protocol",
(KafkaDestination.PLAINTEXT, KafkaDestination.SASLPLAINTEXT, KafkaDestination.SASLSSL),
)
self.client_id = check.opt_str_param(client_id, "client_id")
self.acks = check.str_param(acks, "acks")
self.enable_idempotence = check.bool_param(enable_idempotence, "enable_idempotence")
self.compression_type = check.str_param(compression_type, "compression_type")
self.batch_size = check.int_param(batch_size, "batch_size")
self.linger_ms = check.str_param(linger_ms, "linger_ms")
self.max_in_flight_requests_per_connection = check.int_param(
max_in_flight_requests_per_connection, "max_in_flight_requests_per_connection"
)
self.client_dns_lookup = check.str_param(client_dns_lookup, "client_dns_lookup")
self.buffer_memory = check.str_param(buffer_memory, "buffer_memory")
self.max_request_size = check.int_param(max_request_size, "max_request_size")
self.retries = check.int_param(retries, "retries")
self.socket_connection_setup_timeout_ms = check.str_param(
socket_connection_setup_timeout_ms, "socket_connection_setup_timeout_ms"
)
self.socket_connection_setup_timeout_max_ms = check.str_param(
socket_connection_setup_timeout_max_ms, "socket_connection_setup_timeout_max_ms"
)
self.max_block_ms = check.str_param(max_block_ms, "max_block_ms")
self.request_timeout_ms = check.int_param(request_timeout_ms, "request_timeout_ms")
self.delivery_timeout_ms = check.int_param(delivery_timeout_ms, "delivery_timeout_ms")
self.send_buffer_bytes = check.int_param(send_buffer_bytes, "send_buffer_bytes")
self.receive_buffer_bytes = check.int_param(receive_buffer_bytes, "receive_buffer_bytes")
super().__init__("Kafka", name)
| KafkaDestination |
python | python-poetry__poetry | src/poetry/utils/password_manager.py | {
"start": 588,
"end": 6597
} | class ____:
# some private sources expect tokens to be provided as passwords with empty userames
# we use a fixed literal to ensure that this can be stored in keyring (jaraco/keyring#687)
#
# Note: If this is changed, users with passwords stored with empty usernames will have to
# re-add the config.
_EMPTY_USERNAME_KEY = "__poetry_source_empty_username__"
def __init__(self, namespace: str) -> None:
self._namespace = namespace
@staticmethod
def preflight_check(io: IO | None = None, config: Config | None = None) -> None:
"""
Performs a preflight check to determine the availability of the keyring service
and logs the status if verbosity is enabled. This method is used to validate
the configuration setup related to the keyring functionality.
:param io: An optional input/output handler used to log messages during the
preflight check. If not provided, logging will be skipped.
:param config: An optional configuration object. If not provided, a new
configuration instance will be created using the default factory method.
:return: None
"""
config = config or Config.create()
if config.get("keyring.enabled"):
if io and io.is_verbose():
io.write("Checking keyring availability: ")
message = "<fg=yellow;options=bold>Unavailable</>"
with suppress(RuntimeError, ValueError):
if PoetryKeyring.is_available():
message = "<fg=green;options=bold>Available</>"
if io and io.is_verbose():
io.write(message)
io.write_line("")
def get_credential(
self, *names: str, username: str | None = None
) -> HTTPAuthCredential:
import keyring
from keyring.errors import KeyringError
from keyring.errors import KeyringLocked
for name in names:
credential = None
try:
# we do default to empty username string here since credentials support empty usernames
credential = keyring.get_credential(name, username)
except KeyringLocked:
logger.debug("Keyring %s is locked", name)
except (KeyringError, RuntimeError):
logger.debug("Accessing keyring %s failed", name, exc_info=True)
if credential:
return HTTPAuthCredential(
username=credential.username, password=credential.password
)
return HTTPAuthCredential(username=username, password=None)
def get_password(self, name: str, username: str) -> str | None:
import keyring
import keyring.errors
name = self.get_entry_name(name)
try:
return keyring.get_password(name, username or self._EMPTY_USERNAME_KEY)
except (RuntimeError, keyring.errors.KeyringError) as e:
raise PoetryKeyringError(
f"Unable to retrieve the password for {name} from the key ring {e}"
)
def set_password(self, name: str, username: str, password: str) -> None:
import keyring
import keyring.errors
name = self.get_entry_name(name)
try:
keyring.set_password(name, username or self._EMPTY_USERNAME_KEY, password)
except (RuntimeError, keyring.errors.KeyringError) as e:
raise PoetryKeyringError(
f"Unable to store the password for {name} in the key ring: {e}"
)
def delete_password(self, name: str, username: str) -> None:
import keyring.errors
name = self.get_entry_name(name)
try:
keyring.delete_password(name, username or self._EMPTY_USERNAME_KEY)
except (RuntimeError, keyring.errors.KeyringError):
raise PoetryKeyringError(
f"Unable to delete the password for {name} from the key ring"
)
def get_entry_name(self, name: str) -> str:
return f"{self._namespace}-{name}"
@classmethod
@functools.cache
def is_available(cls) -> bool:
logger.debug("Checking if keyring is available")
try:
import keyring
import keyring.backend
import keyring.errors
except ImportError as e:
logger.debug("An error occurred while importing keyring: %s", e)
return False
def backend_name(backend: keyring.backend.KeyringBackend) -> str:
name: str = backend.name
return name.split(" ")[0]
def backend_is_valid(backend: keyring.backend.KeyringBackend) -> bool:
name = backend_name(backend)
if name in ("chainer", "fail", "null"):
logger.debug(f"Backend {backend.name!r} is not suitable")
return False
elif "plaintext" in backend.name.lower():
logger.debug(f"Not using plaintext keyring backend {backend.name!r}")
return False
return True
backend = keyring.get_keyring()
if backend_name(backend) == "chainer":
backends = keyring.backend.get_all_keyring()
valid_backend = next((b for b in backends if backend_is_valid(b)), None)
else:
valid_backend = backend if backend_is_valid(backend) else None
if valid_backend is None:
logger.debug("No valid keyring backend was found")
return False
logger.debug(f"Using keyring backend {backend.name!r}")
try:
# unfortunately there is no clean way of checking if keyring is unlocked
keyring.get_password("python-poetry-check", "python-poetry")
except (RuntimeError, keyring.errors.KeyringError):
logger.debug(
"Accessing keyring failed during availability check", exc_info=True
)
return False
return True
| PoetryKeyring |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 45337,
"end": 45870
} | class ____(SuccessMessageMixin, PrivateViewMixin, UpdateView):
model = Project
form_class = ProjectPullRequestForm
success_message = _("Pull request settings have been updated")
template_name = "projects/pull_requests_form.html"
lookup_url_kwarg = "project_slug"
lookup_field = "slug"
def get_queryset(self):
return self.model.objects.for_admin_user(self.request.user)
def get_success_url(self):
return reverse("projects_pull_requests", args=[self.object.slug])
| ProjectPullRequestsUpdate |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_argument_names.py | {
"start": 787,
"end": 2484
} | class ____(ValidationRule):
def enter_Argument(self, node, key, parent, path, ancestors):
argument_of = ancestors[-1]
if isinstance(argument_of, ast.Field):
field_def = self.context.get_field_def()
if not field_def:
return
field_arg_def = field_def.args.get(node.name.value)
if not field_arg_def:
parent_type = self.context.get_parent_type()
assert parent_type
self.context.report_error(GraphQLError(
_unknown_arg_message(
node.name.value,
argument_of.name.value,
parent_type.name,
suggestion_list(
node.name.value,
(arg_name for arg_name in field_def.args.keys())
)
),
[node]
))
elif isinstance(argument_of, ast.Directive):
directive = self.context.get_directive()
if not directive:
return
directive_arg_def = directive.args.get(node.name.value)
if not directive_arg_def:
self.context.report_error(GraphQLError(
_unknown_directive_arg_message(
node.name.value,
directive.name,
suggestion_list(
node.name.value,
(arg_name for arg_name in directive.args.keys())
)
),
[node]
))
| KnownArgumentNames |
python | getsentry__sentry | src/sentry/users/api/serializers/user_identity_config.py | {
"start": 2049,
"end": 4137
} | class ____:
category: str
id: int
provider: UserIdentityProvider
name: str
status: Status
is_login: bool
organization_id: int | None = None
date_added: datetime | None = None
date_verified: datetime | None = None
date_synced: datetime | None = None
@classmethod
def wrap(cls, identity: IdentityType, status: Status) -> UserIdentityConfig:
def base(**kwargs: Any) -> UserIdentityConfig:
return cls(
category=_IDENTITY_CATEGORY_KEYS[type(identity)],
id=identity.id,
status=status,
**kwargs,
)
if isinstance(identity, UserSocialAuth):
return base(
provider=UserIdentityProvider(identity.provider, get_provider_label(identity)),
name=identity.uid,
is_login=False,
)
elif isinstance(identity, Identity):
provider: PipelineProvider[Any]
try:
provider = identity.get_provider()
except NotRegistered:
provider = integrations.get(identity.idp.type)
return base(
provider=UserIdentityProvider.adapt(provider),
name=identity.external_id,
is_login=supports_login(identity),
date_added=identity.date_added,
date_verified=identity.date_verified,
)
elif isinstance(identity, AuthIdentity):
return base(
provider=UserIdentityProvider.adapt(identity.auth_provider.get_provider()),
name=identity.ident,
is_login=True,
organization_id=identity.auth_provider.organization_id,
date_added=identity.date_added,
date_verified=identity.last_verified,
date_synced=identity.last_synced,
)
else:
raise TypeError
def get_model_type_for_category(self) -> type[Model]:
return _IDENTITY_CATEGORIES_BY_KEY[self.category]
| UserIdentityConfig |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 82798,
"end": 84068
} | class ____(Response):
"""
Response of events.get_debug_image_sample endpoint.
"""
_service = "events"
_action = "get_debug_image_sample"
_version = "2.23"
_schema = {
"$ref": "#/definitions/debug_image_sample_response",
"definitions": {
"debug_image_sample_response": {
"properties": {
"event": {
"description": "Debug image event",
"type": ["object", "null"],
},
"max_iteration": {
"description": "maximal valid iteration for the variant",
"type": ["integer", "null"],
},
"min_iteration": {
"description": "minimal valid iteration for the variant",
"type": ["integer", "null"],
},
"scroll_id": {
"description": "Scroll ID to pass to the next calls to get_debug_image_sample or next_debug_image_sample",
"type": ["string", "null"],
},
},
"type": "object",
}
},
}
| GetDebugImageSampleResponse |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/sglang_engine_stage.py | {
"start": 12030,
"end": 13870
} | class ____(StatefulStage):
"""
A stage that runs SGLang engine.
"""
fn: Type[StatefulStageUDF] = SGLangEngineStageUDF
@root_validator(pre=True)
def post_init(cls, values):
"""Post-initialize the stage. Specifically,
this function determines the num_gpus and Ray remote args
for the .map_batches() call in this stage.
Args:
values: The raw stage values.
Returns:
The updated values.
"""
map_batches_kwargs = values["map_batches_kwargs"]
accelerator_type = map_batches_kwargs.get("accelerator_type", "")
fn_constructor_kwargs = values["fn_constructor_kwargs"]
engine_kwargs = fn_constructor_kwargs.get("engine_kwargs", {})
ray_remote_args = {}
if accelerator_type:
ray_remote_args["accelerator_type"] = accelerator_type
# Set up num_gpus required
tp_size = engine_kwargs.get("tp_size", 1)
dp_size = engine_kwargs.get("dp_size", 1)
num_gpus = tp_size * dp_size
ray_remote_args["num_gpus"] = num_gpus
map_batches_kwargs.update(ray_remote_args)
return values
def get_required_input_keys(self) -> Dict[str, str]:
"""The required input keys of the stage and their descriptions."""
ret = {"prompt": "The text prompt (str)."}
task_type = self.fn_constructor_kwargs.get("task_type", SGLangTaskType.GENERATE)
if task_type == SGLangTaskType.GENERATE:
ret[
"sampling_params"
] = "The sampling parameters. See https://docs.sglang.ai/backend/sampling_params.html for details."
return ret
def get_optional_input_keys(self) -> Dict[str, str]:
"""The optional input keys of the stage and their descriptions."""
return {}
| SGLangEngineStage |
python | getsentry__sentry | tests/sentry/services/eventstore/snuba/test_backend.py | {
"start": 606,
"end": 26736
} | class ____(TestCase, SnubaTestCase, PerformanceIssueTestCase):
def setUp(self) -> None:
super().setUp()
self.min_ago = before_now(minutes=1)
self.two_min_ago = before_now(minutes=2)
self.project1 = self.create_project()
self.project2 = self.create_project()
self.event1 = self.store_event(
data={
"event_id": "a" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group1"],
"timestamp": self.two_min_ago.isoformat(),
"tags": {"foo": "1"},
},
project_id=self.project1.id,
)
self.event2 = self.store_event(
data={
"event_id": "b" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group1"],
"timestamp": self.min_ago.isoformat(),
"tags": {"foo": "1"},
},
project_id=self.project2.id,
)
self.event3 = self.store_event(
data={
"event_id": "c" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group2"],
"timestamp": self.min_ago.isoformat(),
"tags": {"foo": "1"},
},
project_id=self.project2.id,
)
event_data = load_data("transaction")
event_data["timestamp"] = before_now(minutes=1).isoformat()
event_data["start_timestamp"] = before_now(minutes=1, seconds=1).isoformat()
event_data["event_id"] = "d" * 32
self.transaction_event = self.store_event(data=event_data, project_id=self.project1.id)
event_data_2 = load_data(
platform="transaction-n-plus-one",
fingerprint=[f"{PerformanceNPlusOneGroupType.type_id}-group3"],
)
event_data_2["timestamp"] = before_now(seconds=30).isoformat()
event_data_2["start_timestamp"] = before_now(seconds=31).isoformat()
event_data_2["event_id"] = "e" * 32
self.transaction_event_2 = self.create_performance_issue(
event_data=event_data_2, project_id=self.project2.id
)
event_data_3 = load_data(
"transaction-n-plus-one", fingerprint=[f"{PerformanceNPlusOneGroupType.type_id}-group3"]
)
event_data_3["timestamp"] = before_now(seconds=30).isoformat()
event_data_3["start_timestamp"] = before_now(seconds=31).isoformat()
event_data_3["event_id"] = "f" * 32
self.transaction_event_3 = self.create_performance_issue(
event_data=event_data_3, project_id=self.project2.id
)
self.eventstore = SnubaEventStorage()
def test_get_events(self) -> None:
events = self.eventstore.get_events(
filter=Filter(
project_ids=[self.project1.id, self.project2.id],
conditions=[
["type", "!=", "transaction"]
], # TODO: Remove once errors storage rolled out
),
tenant_ids={"organization_id": 123, "referrer": "r"},
)
assert len(events) == 3
# Default sort is timestamp desc, event_id desc
assert events[0].event_id == "c" * 32
assert events[1].event_id == "b" * 32
assert events[2].event_id == "a" * 32
# No events found
project = self.create_project()
events = self.eventstore.get_events(
filter=Filter(project_ids=[project.id]),
tenant_ids={"organization_id": 123, "referrer": "r"},
)
assert events == []
# Test with a list of event IDs and project ID filters
events = self.eventstore.get_events(
filter=Filter(
project_ids=[self.project1.id, self.project2.id],
event_ids=["a" * 32, "b" * 32, "c" * 32, "x" * 32, "y" * 32, "z" * 32],
),
tenant_ids={"organization_id": 123, "referrer": "r"},
)
assert len(events) == 3
assert events[0].event_id == "c" * 32
assert events[1].event_id == "b" * 32
assert events[2].event_id == "a" * 32
@mock.patch("sentry.services.nodestore.get_multi")
def test_get_unfetched_events(self, get_multi: MagicMock) -> None:
events = self.eventstore.get_unfetched_events(
filter=Filter(project_ids=[self.project1.id]),
tenant_ids={"organization_id": 123, "referrer": "r"},
)
assert len(events) == 1
assert get_multi.call_count == 0
@mock.patch("sentry.services.nodestore.get_multi")
def test_get_unfetched_transactions(self, get_multi: MagicMock) -> None:
transactions_proj1 = self.eventstore.get_unfetched_transactions(
filter=Filter(project_ids=[self.project1.id]),
tenant_ids={"organization_id": self.project1.organization_id},
)
assert len(transactions_proj1) == 1
assert get_multi.call_count == 0
transactions_proj2 = self.eventstore.get_unfetched_transactions(
filter=Filter(project_ids=[self.project2.id]),
tenant_ids={"organization_id": self.project1.organization_id},
)
assert len(transactions_proj2) == 2
assert get_multi.call_count == 0
def test_get_event_by_id(self) -> None:
# Get valid event
event = self.eventstore.get_event_by_id(self.project1.id, "a" * 32)
assert event is not None
assert event.group is not None
assert event.event_id == "a" * 32
assert event.project_id == self.project1.id
assert event.group_id == event.group.id
# Get non existent event
event = self.eventstore.get_event_by_id(self.project2.id, "z" * 32)
assert event is None
# Get transaction
event = self.eventstore.get_event_by_id(self.project2.id, self.transaction_event_2.event_id)
assert event is not None
assert event.event_id == "e" * 32
assert event.get_event_type() == "transaction"
assert event.project_id == self.project2.id
def test_get_event_by_id_cached(self) -> None:
# Simulate getting an event that exists in eventstore but has not yet been written to snuba.
with mock.patch("sentry.services.eventstore.snuba.backend.Event") as mock_event:
dummy_event = Event(
project_id=self.project2.id,
event_id="1" * 32,
data={"something": "hi", "timestamp": self.min_ago.isoformat(), "type": "error"},
)
mock_event.return_value = dummy_event
event = self.eventstore.get_event_by_id(self.project2.id, "1" * 32)
# Result of query should be None
assert event is None
# Now we store the event properly, so it will exist in Snuba.
self.store_event(
data={"event_id": "1" * 32, "timestamp": self.min_ago.isoformat(), "type": "error"},
project_id=self.project2.id,
)
# Make sure that the negative cache isn't causing the event to not show up
event = self.eventstore.get_event_by_id(self.project2.id, "1" * 32)
assert event is not None
assert event.group is not None
assert event.event_id == "1" * 32
assert event.project_id == self.project2.id
assert event.group_id == event.group.id
def test_get_events_snql_with_inner_limit(self) -> None:
project = self.create_project()
ts_old = before_now(minutes=6).isoformat()
ts_mid = before_now(minutes=5).isoformat()
ts_new = before_now(minutes=4).isoformat()
event_oldest = self.store_event(
data={
"event_id": "1" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["inner-limit-group"],
"timestamp": ts_old,
},
project_id=project.id,
)
event_middle = self.store_event(
data={
"event_id": "2" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["inner-limit-group"],
"timestamp": ts_mid,
},
project_id=project.id,
)
event_newest = self.store_event(
data={
"event_id": "3" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["inner-limit-group"],
"timestamp": ts_new,
},
project_id=project.id,
)
group_id = event_oldest.group_id
assert group_id is not None
eventstore = SnubaEventStorage()
# Ascending order should return oldest first when no inner limit is used
no_inner = eventstore.get_events_snql(
organization_id=project.organization.id,
group_id=group_id,
start=before_now(minutes=10),
end=before_now(minutes=0),
conditions=[
Condition(Column("project_id"), Op.IN, [project.id]),
Condition(Column("group_id"), Op.IN, [group_id]),
],
orderby=["timestamp", "event_id"],
dataset=Dataset.Events,
tenant_ids={"organization_id": project.organization.id},
limit=2,
)
assert [e.event_id for e in no_inner] == [event_oldest.event_id, event_middle.event_id]
# With inner_limit=2 we first query for the two most recent events, THEN apply sorting
# The result of which should be [event_middle, event_newest]
with_inner = eventstore.get_events_snql(
organization_id=project.organization.id,
group_id=group_id,
start=before_now(minutes=10),
end=before_now(minutes=0),
conditions=[
Condition(Column("project_id"), Op.IN, [project.id]),
Condition(Column("group_id"), Op.IN, [group_id]),
],
orderby=["timestamp", "event_id"],
dataset=Dataset.Events,
tenant_ids={"organization_id": project.organization.id},
limit=2,
inner_limit=2,
)
assert [e.event_id for e in with_inner] == [event_middle.event_id, event_newest.event_id]
def test_get_event_beyond_retention(self) -> None:
event = self.store_event(
data={
"event_id": "d" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group2"],
"timestamp": before_now(days=14).isoformat(),
"tags": {"foo": "1"},
},
project_id=self.project2.id,
)
with mock.patch("sentry.quotas.backend.get_event_retention", return_value=7):
event = self.eventstore.get_event_by_id(self.project2.id, "d" * 32)
assert event is None
def test_get_adjacent_event_ids(self) -> None:
event = self.eventstore.get_event_by_id(self.project2.id, "b" * 32)
assert event is not None
filter = Filter(project_ids=[self.project1.id, self.project2.id])
prev_event, next_event = self.eventstore.get_adjacent_event_ids(event, filter=filter)
assert prev_event == (str(self.project1.id), "a" * 32)
# Events with the same timestamp are sorted by event_id
assert next_event == (str(self.project2.id), "c" * 32)
# Returns None if the prev event is outside the start window
period_filter = Filter(
project_ids=[self.project1.id, self.project2.id],
start=self.min_ago,
)
prev_event, next_event = self.eventstore.get_adjacent_event_ids(event, filter=period_filter)
assert prev_event is None
assert next_event == (str(self.project2.id), "c" * 32)
# Returns None if the next event is outside the end window
period_filter = Filter(
project_ids=[self.project1.id, self.project2.id],
end=self.min_ago,
)
prev_event, next_event = self.eventstore.get_adjacent_event_ids(event, filter=period_filter)
assert prev_event == (str(self.project1.id), "a" * 32)
assert next_event is None
# Returns None if no event
prev_event, next_event = self.eventstore.get_adjacent_event_ids(None, filter=filter)
assert prev_event is None
assert next_event is None
# Returns None if the query fails for a known reason
with mock.patch(
"sentry.utils.snuba.bulk_raw_query", side_effect=snuba.QueryOutsideRetentionError()
):
prev_event, next_event = self.eventstore.get_adjacent_event_ids(event, filter=filter)
assert prev_event is None
assert next_event is None
def test_adjacent_event_ids_same_timestamp(self) -> None:
project = self.create_project()
event1 = self.store_event(
data={
"event_id": "a" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.min_ago.isoformat(),
},
project_id=project.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.min_ago.isoformat(),
},
project_id=project.id,
)
# the 2 events should be in the same group
assert event1.group_id == event2.group_id
# the 2 events should have the same timestamp
assert event1.datetime == event2.datetime
_filter = Filter(
project_ids=[project.id],
conditions=[["event.type", "!=", "transaction"]],
group_ids=[event1.group_id],
)
event = self.eventstore.get_event_by_id(project.id, "a" * 32)
prev_event, next_event = self.eventstore.get_adjacent_event_ids(event, filter=_filter)
assert prev_event is None
assert next_event == (str(project.id), "b" * 32)
event = self.eventstore.get_event_by_id(project.id, "b" * 32)
prev_event, next_event = self.eventstore.get_adjacent_event_ids(event, filter=_filter)
assert prev_event == (str(project.id), "a" * 32)
assert next_event is None
def test_transaction_get_next_prev_event_id(self) -> None:
group = self.transaction_event_2.group
assert group is not None
_filter = Filter(
project_ids=[self.project2.id],
group_ids=[group.id],
)
event = self.eventstore.get_event_by_id(
self.project2.id, self.transaction_event_3.event_id, group_id=group.id
)
prev_event, next_event = self.eventstore.get_adjacent_event_ids(event, filter=_filter)
assert prev_event == (str(self.project2.id), self.transaction_event_2.event_id)
assert next_event is None
event = self.eventstore.get_event_by_id(
self.project2.id, self.transaction_event_2.event_id, group_id=group.id
)
prev_event, next_event = self.eventstore.get_adjacent_event_ids(event, filter=_filter)
assert prev_event is None
assert next_event == (str(self.project2.id), self.transaction_event_3.event_id)
def test_get_adjacent_event_ids_snql(self) -> None:
project = self.create_project()
data = {
"type": "default",
"platform": "python",
"fingerprint": ["group"],
}
self.store_event(
data={**data, "event_id": "a" * 32, "timestamp": before_now(minutes=10).isoformat()},
project_id=project.id,
)
event1 = self.store_event(
data={**data, "event_id": "b" * 32, "timestamp": before_now(minutes=4).isoformat()},
project_id=project.id,
)
event2 = self.store_event(
data={**data, "event_id": "c" * 32, "timestamp": before_now(minutes=3).isoformat()},
project_id=project.id,
)
event3 = self.store_event(
data={**data, "event_id": "d" * 32, "timestamp": before_now(minutes=2).isoformat()},
project_id=project.id,
)
self.store_event(
data={**data, "event_id": "e" * 32, "timestamp": before_now(minutes=0).isoformat()},
project_id=project.id,
)
# Finds next and previous IDs
prev_ids, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event2.organization.id,
project_id=event2.project_id,
group_id=event2.group_id,
environments=[],
event=event2,
)
assert prev_ids == (str(event1.project_id), event1.event_id)
assert next_ids == (str(event3.project_id), event3.event_id)
# Filter previous events that are outside of the start window
prev_ids, _ = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event1.organization.id,
project_id=event1.project_id,
group_id=event1.group_id,
environments=[],
event=event1,
start=before_now(minutes=5),
)
assert prev_ids is None
# Filter next events that are outside of the end window
_, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event3.organization.id,
project_id=event3.project_id,
group_id=event3.group_id,
environments=[],
event=event3,
end=before_now(minutes=1),
)
assert next_ids is None
def test_get_adjacent_event_ids_snql_order_of_event_ids(self) -> None:
project = self.create_project()
event1 = self.store_event(
data={
"event_id": "c" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.two_min_ago.isoformat(),
},
project_id=project.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.min_ago.isoformat(),
},
project_id=project.id,
)
event3 = self.store_event(
data={
"event_id": "a" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": before_now(minutes=0).isoformat(),
},
project_id=project.id,
)
prev_ids, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event2.organization.id,
project_id=event2.project_id,
group_id=event2.group_id,
environments=[],
event=event2,
)
assert prev_ids == (str(event1.project_id), event1.event_id)
assert next_ids == (str(event3.project_id), event3.event_id)
def test_adjacent_event_ids_same_timestamp_snql(self) -> None:
project = self.create_project()
event1 = self.store_event(
data={
"event_id": "a" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.min_ago.isoformat(),
},
project_id=project.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.min_ago.isoformat(),
},
project_id=project.id,
)
# the 2 events should be in the same group
assert event1.group_id == event2.group_id
# the 2 events should have the same timestamp
assert event1.datetime == event2.datetime
prev_ids, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event1.organization.id,
project_id=event1.project_id,
group_id=event1.group_id,
environments=[],
event=event1,
)
assert prev_ids is None
assert next_ids == (str(project.id), event2.event_id)
prev_ids, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event2.organization.id,
project_id=event2.project_id,
group_id=event2.group_id,
environments=[],
event=event2,
)
assert prev_ids == (str(project.id), event1.event_id)
assert next_ids is None
def test_adjacent_event_ids_with_query_conditions(self) -> None:
project = self.create_project()
event_a = self.store_event(
data={
"event_id": "a" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.min_ago.isoformat(),
"tags": {"organization.slug": "sentry"},
},
project_id=project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.min_ago.isoformat(),
},
project_id=project.id,
)
event_c = self.store_event(
data={
"event_id": "c" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": self.min_ago.isoformat(),
"tags": {"organization.slug": "sentry"},
},
project_id=project.id,
)
query_conditions = [Condition(Column("tags[organization.slug]"), Op.EQ, "sentry")]
prev_ids, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event_a.organization.id,
project_id=event_a.project_id,
group_id=event_a.group_id,
environments=[],
event=event_a,
conditions=query_conditions,
)
assert prev_ids is None
assert next_ids == (str(event_c.project_id), event_c.event_id)
prev_ids, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event_c.organization.id,
project_id=event_c.project_id,
group_id=event_c.group_id,
environments=[],
event=event_c,
conditions=query_conditions,
)
assert prev_ids == (str(event_a.project_id), event_a.event_id)
assert next_ids is None
def test_adjacent_event_ids_with_date_range_conditions(self) -> None:
project = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": before_now(hours=1).isoformat(),
},
project_id=project.id,
)
event_b = self.store_event(
data={
"event_id": "b" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": before_now(hours=2).isoformat(),
},
project_id=project.id,
)
event_c = self.store_event(
data={
"event_id": "c" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": before_now(hours=3).isoformat(),
},
project_id=project.id,
)
event_d = self.store_event(
data={
"event_id": "d" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": before_now(hours=4).isoformat(),
},
project_id=project.id,
)
self.store_event(
data={
"event_id": "e" * 32,
"type": "default",
"platform": "python",
"fingerprint": ["group"],
"timestamp": before_now(hours=5).isoformat(),
},
project_id=project.id,
)
# -> E (5h ago), D (4h ago), C (3h ago), B (2h ago), A (1h ago), now
date_range_conditions = [
Condition(Column("timestamp"), Op.LT, before_now(hours=1.5)),
Condition(Column("timestamp"), Op.GT, before_now(hours=4.5)),
]
prev_ids, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event_b.organization.id,
project_id=event_b.project_id,
group_id=event_b.group_id,
environments=[],
event=event_b,
conditions=date_range_conditions,
)
assert prev_ids == (str(event_c.project_id), event_c.event_id)
assert next_ids is None
prev_ids, next_ids = self.eventstore.get_adjacent_event_ids_snql(
organization_id=event_d.organization.id,
project_id=event_d.project_id,
group_id=event_d.group_id,
environments=[],
event=event_d,
conditions=date_range_conditions,
)
assert prev_ids is None
assert next_ids == (str(event_c.project_id), event_c.event_id)
| SnubaEventStorageTest |
python | pytorch__pytorch | torch/distributed/checkpoint/filesystem.py | {
"start": 27516,
"end": 28435
} | class ____:
"""
This is experimental, and will likely move elsewhere in the
future. It lives here to minimize changes while we are still
learning and gathering feedback.
"""
def __init__(self, extension_registry: Optional[ExtensionRegistry] = None) -> None:
self.extension_registry = (
ExtensionRegistry() if extension_registry is None else extension_registry
)
def transform_load_stream(
self,
read_item: ReadItem,
transform_descriptors: Sequence[str],
raw_stream: IO[bytes],
) -> IO[bytes]:
extensions = self.extension_registry.from_descriptor_list(transform_descriptors)
transform_from = raw_stream
for ex in extensions:
if isinstance(ex, StreamTransformExtension):
transform_from = ex.transform_from(transform_from)
return transform_from
| _StorageReaderTransforms |
python | getsentry__sentry | src/sentry/api/serializers/models/role.py | {
"start": 1471,
"end": 2251
} | class ____(Serializer):
def __init__(self, **kwargs):
"""
Remove this when deleting "organizations:team-roles" flag
"""
self.organization = kwargs["organization"]
def serialize(
self,
obj: OrganizationRole,
attrs: Mapping[str, Any],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> OrganizationRoleSerializerResponse:
base = _serialize_base_role(
obj, self.organization, allowed_roles=kwargs.get("allowed_roles", ())
)
return {
**base,
"is_global": obj.is_global, # backward compatibility
"isGlobal": obj.is_global,
"minimumTeamRole": obj.get_minimum_team_role().id,
}
| OrganizationRoleSerializer |
python | pyparsing__pyparsing | pyparsing/util.py | {
"start": 3214,
"end": 3908
} | class ____:
def __init__(self, size):
cache = {}
self.size = size
self.not_in_cache = not_in_cache = object()
cache_get = cache.get
cache_pop = cache.pop
def get(_, key):
return cache_get(key, not_in_cache)
def set_(_, key, value):
cache[key] = value
while len(cache) > size:
# pop oldest element in cache by getting the first key
cache_pop(next(iter(cache)))
def clear(_):
cache.clear()
self.get = types.MethodType(get, self)
self.set = types.MethodType(set_, self)
self.clear = types.MethodType(clear, self)
| _FifoCache |
python | getsentry__sentry | src/sentry/monitors/models.py | {
"start": 4268,
"end": 6155
} | class ____:
UNKNOWN = 0
"""
Checkin may have lost data and we cannot know the resulting status of the
check-in. This can happen when an incident is detected using clock-tick
volume anomoly detection.
"""
OK = 1
"""Checkin had no issues during execution"""
ERROR = 2
"""Checkin failed or otherwise had some issues"""
IN_PROGRESS = 3
"""Checkin is expected to complete"""
MISSED = 4
"""Monitor did not check in on time"""
TIMEOUT = 5
"""Checkin was left in-progress past max_runtime"""
USER_TERMINAL_VALUES = (OK, ERROR)
"""
Values indicating the monitor is in a terminal status where the terminal
status was reported by the monitor itself (was not synthetic)
"""
SYNTHETIC_TERMINAL_VALUES = (MISSED, TIMEOUT, UNKNOWN)
"""
Values indicating the montior is in a terminal "synthetic" status. These
status are not sent by the monitor themselve but are a side effect result.
For some values such as UNKNOWN it is possible for it to transition to a
USER_TERMINAL_VALUES.
"""
FINISHED_VALUES = (OK, ERROR, MISSED, TIMEOUT)
"""
All terminal values indicating the monitor has reached it's final status
"""
@classmethod
def as_choices(cls):
return (
(cls.UNKNOWN, "unknown"),
(cls.OK, "ok"),
(cls.ERROR, "error"),
(cls.IN_PROGRESS, "in_progress"),
(cls.MISSED, "missed"),
(cls.TIMEOUT, "timeout"),
)
DEFAULT_STATUS_ORDER = [
MonitorStatus.ERROR,
MonitorStatus.OK,
MonitorStatus.ACTIVE,
MonitorStatus.DISABLED,
]
MONITOR_ENVIRONMENT_ORDERING = Case(
When(is_muted=True, then=Value(len(DEFAULT_STATUS_ORDER) + 1)),
*[When(status=s, then=Value(i)) for i, s in enumerate(DEFAULT_STATUS_ORDER)],
output_field=IntegerField(),
)
| CheckInStatus |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_feature_store.py | {
"start": 15312,
"end": 16834
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("feature_store.FeatureStoreHook"))
def test_execute(self, mock_hook_class):
# Create the mock hook and set up its return value
mock_hook = mock.MagicMock()
mock_hook_class.return_value = mock_hook
sample_operation = mock.MagicMock()
mock_hook.delete_feature_view.return_value = sample_operation
mock_hook.return_value.wait_for_operation_result.side_effect = lambda operation: operation.result()
common_kwargs = {
"project_id": GCP_PROJECT,
"location": GCP_LOCATION,
"feature_online_store_id": FEATURE_ONLINE_STORE_ID,
"feature_view_id": FEATURE_VIEW_ID,
"metadata": (),
"timeout": 100,
"retry": None,
}
op = DeleteFeatureViewOperator(
task_id=TASK_ID,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
**common_kwargs,
)
response = op.execute(context={"ti": mock.MagicMock()})
# Verify hook initialization
mock_hook_class.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
# Verify hook method call
mock_hook.delete_feature_view.assert_called_once_with(**common_kwargs)
# Verify response matches expected value
assert response == {"result": f"The {FEATURE_VIEW_ID} has been deleted."}
| TestDeleteFeatureViewOperator |
python | coleifer__peewee | playhouse/sqlite_ext.py | {
"start": 1703,
"end": 1798
} | class ____(DecimalField):
field_type = 'TEXT'
def get_modifiers(self): pass
| TDecimalField |
python | huggingface__transformers | src/transformers/models/edgetam_video/modular_edgetam_video.py | {
"start": 46358,
"end": 46446
} | class ____(Sam2VideoImageSegmentationOutput):
pass
| EdgeTamVideoImageSegmentationOutput |
python | tensorflow__tensorflow | third_party/xla/xla/hlo/tools/generate_hlo_test_checks.py | {
"start": 12221,
"end": 14533
} | class ____:
"""Splits out CHECK/RUN directives into separate streams.
Strips away CHECK/RUN directives, optionally splitting them into their own
streams if indicated by the `record_directives` constructor argument.
"""
def __init__(self,
input_stream: Iterator[str],
record_directives: Optional[set[DirectiveComment]] = None):
if record_directives is None:
record_directives = set()
self._non_directive_lines: collections.deque[str] = collections.deque()
self._directive_histories: dict[
DirectiveComment, collections.deque[str]
] = {directive: collections.deque() for directive in record_directives}
self._splitter: IterateByCategory[str] = IterateByCategory(
input_stream,
self._select_buffer,
)
def non_directive_lines(self) -> Iterator[str]:
return self._splitter.iterate_over_buffer(self._non_directive_lines)
def directive_history(self, directive: DirectiveComment) -> Iterator[str]:
try:
directive_history_lines = self._directive_histories[directive]
except KeyError as e:
raise KeyError(
f"This `HloStreamSplitter` was not configured to keep a record of "
f'stripped "{directive}:" directives.'
) from e
return self._splitter.iterate_over_buffer(directive_history_lines)
def _select_buffer(
self, line: str
) -> Union[collections.deque[str], tuple[collections.deque[str], ...], None]:
directive = DirectiveComment.extract_from_line(line)
if directive is None:
# Strip the top-of-file comment if present so as to avoid duplicating it.
return None if line == _BANNER_COMMENT_LINE else self._non_directive_lines
return self._directive_histories.get(directive, None)
def _fix_whitespace(input_stream: Iterator[str]) -> Iterator[str]:
"""Fixes indentation; trims redundant empty lines."""
before_first_section: bool = True
at_section_boundary: bool = True
for line in input_stream:
if not line.strip():
at_section_boundary = True
continue
if at_section_boundary:
if before_first_section:
before_first_section = False
else:
yield "\n"
at_section_boundary = False
yield f" {line.lstrip()}" if line.startswith(" ") else line
| HloStreamSplitter |
python | realpython__materials | dwitter-part-1/source_code_step_01/dwitter/admin.py | {
"start": 86,
"end": 300
} | class ____(admin.ModelAdmin):
model = User
# Only display the "username" field
fields = ["username"]
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin.site.unregister(Group)
| UserAdmin |
python | PyCQA__pylint | pylint/lint/run.py | {
"start": 4447,
"end": 9617
} | class ____:
"""Helper class to use as main for pylint with 'run(*sys.argv[1:])'."""
LinterClass = PyLinter
option_groups = (
(
"Commands",
"Options which are actually commands. Options in this \
group are mutually exclusive.",
),
)
_is_pylint_config: ClassVar[bool] = False
"""Boolean whether or not this is a 'pylint-config' run.
Used by _PylintConfigRun to make the 'pylint-config' command work.
"""
# pylint: disable = too-many-statements, too-many-branches
def __init__(
self,
args: Sequence[str],
reporter: BaseReporter | None = None,
exit: bool = True, # pylint: disable=redefined-builtin
) -> None:
# Immediately exit if user asks for version
if "--version" in args:
print(full_version)
sys.exit(0)
self._rcfile: str | None = None
self._output: str | None = None
self._plugins: list[str] = []
self.verbose: bool = False
# Pre-process certain options and remove them from args list
try:
args = _preprocess_options(self, args)
except ArgumentPreprocessingError as ex:
print(ex, file=sys.stderr)
sys.exit(32)
# Determine configuration file
if self._rcfile is None:
default_file = next(config.find_default_config_files(), None)
if default_file:
self._rcfile = str(default_file)
self.linter = linter = self.LinterClass(
_make_run_options(self),
option_groups=self.option_groups,
)
# register standard checkers
linter.load_default_plugins()
# load command line plugins
linter.load_plugin_modules(self._plugins)
# Register the options needed for 'pylint-config'
# By not registering them by default they don't show up in the normal usage message
if self._is_pylint_config:
_register_generate_config_options(linter._arg_parser)
args = _config_initialization(
linter, args, reporter, config_file=self._rcfile, verbose_mode=self.verbose
)
# Handle the 'pylint-config' command
if self._is_pylint_config:
warnings.warn(
"NOTE: The 'pylint-config' command is experimental and usage can change",
UserWarning,
stacklevel=2,
)
code = _handle_pylint_config_commands(linter)
if exit:
sys.exit(code)
return
# Display help if there are no files to lint or only internal checks enabled (`--disable=all`)
disable_all_msg_set = set(
msg.symbol for msg in linter.msgs_store.messages
) - set(msg[1] for msg in linter.default_enabled_messages.values())
if not args or (
len(linter.config.enable) == 0
and set(linter.config.disable) == disable_all_msg_set
):
print("No files to lint: exiting.")
sys.exit(32)
if linter.config.jobs < 0:
print(
f"Jobs number ({linter.config.jobs}) should be greater than or equal to 0",
file=sys.stderr,
)
sys.exit(32)
if linter.config.jobs > 1 or linter.config.jobs == 0:
if ProcessPoolExecutor is None:
print(
"concurrent.futures module is missing, fallback to single process",
file=sys.stderr,
)
linter.set_option("jobs", 1)
elif linter.config.jobs == 0:
linter.config.jobs = _cpu_count()
if self._output:
try:
with open(self._output, "w", encoding="utf-8") as output:
linter.reporter.out = output
linter.check(args)
score_value = linter.generate_reports(verbose=self.verbose)
except OSError as ex:
print(ex, file=sys.stderr)
sys.exit(32)
else:
linter.check(args)
score_value = linter.generate_reports(verbose=self.verbose)
if linter.config.clear_cache_post_run:
clear_lru_caches()
MANAGER.clear_cache()
if exit:
if linter.config.exit_zero:
sys.exit(0)
elif linter.any_fail_on_issues():
# We need to make sure we return a failing exit code in this case.
# So we use self.linter.msg_status if that is non-zero, otherwise we just return 1.
sys.exit(self.linter.msg_status or 1)
elif score_value is not None:
if score_value >= linter.config.fail_under:
sys.exit(0)
else:
# We need to make sure we return a failing exit code in this case.
# So we use self.linter.msg_status if that is non-zero, otherwise we just return 1.
sys.exit(self.linter.msg_status or 1)
else:
sys.exit(self.linter.msg_status)
| Run |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/llm/test_llm_engine.py | {
"start": 609,
"end": 5073
} | class ____:
@pytest.mark.parametrize("api_type", ["chat", "completion"])
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("max_tokens", [5])
@pytest.mark.asyncio
async def test_unified_llm_engine(
self,
mock_llm_config,
mock_chat_request,
mock_completion_request,
api_type: str,
stream: bool,
max_tokens: int,
):
"""Unified test for both chat and completion APIs, streaming and non-streaming."""
# Create and start the engine
engine = MockVLLMEngine(mock_llm_config)
await engine.start()
# Create request based on API type
if api_type == "chat":
request = mock_chat_request
response_generator = engine.chat(request)
elif api_type == "completion":
request = mock_completion_request
response_generator = engine.completions(request)
print(
f"\n\n_____ {api_type.upper()} ({'STREAMING' if stream else 'NON-STREAMING'}) max_tokens={max_tokens} _____\n\n"
)
if stream:
# Collect streaming chunks
chunks = []
async for chunk in response_generator:
assert isinstance(chunk, str)
chunks.append(chunk)
# Validate streaming response
LLMResponseValidator.validate_streaming_chunks(chunks, api_type, max_tokens)
else:
# Validate non-streaming response
async for response in response_generator:
LLMResponseValidator.validate_non_streaming_response(
response, api_type, max_tokens
)
@pytest.mark.parametrize("dimensions", [None, 512])
@pytest.mark.asyncio
async def test_embedding_mock_engine(
self, mock_llm_config, mock_embedding_request, dimensions: Optional[int]
):
"""Test embedding API with different dimensions."""
# Create and start the engine
engine = MockVLLMEngine(mock_llm_config)
await engine.start()
# Create embedding request
request = mock_embedding_request
print(f"\n\n_____ EMBEDDING dimensions={dimensions} _____\n\n")
async for response in engine.embeddings(request):
LLMResponseValidator.validate_embedding_response(response, dimensions)
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("temperature", [0.0])
@pytest.mark.parametrize("language", ["en", "hi"])
@pytest.mark.asyncio
async def test_transcription_mock_engine(
self,
mock_llm_config,
mock_transcription_request,
stream: bool,
temperature: float,
language: Optional[str],
):
"""Test transcription API with different language and temperature, streaming and non-streaming."""
engine = MockVLLMEngine(mock_llm_config)
await engine.start()
request = mock_transcription_request
response_generator = engine.transcriptions(request)
print(
f"\n\n_____ TRANSCRIPTION ({'STREAMING' if stream else 'NON-STREAMING'}) language={language} temperature={temperature} _____\n\n"
)
if stream:
# Collect streaming chunks
chunks = []
async for chunk in response_generator:
assert isinstance(chunk, str)
chunks.append(chunk)
# Validate streaming response
LLMResponseValidator.validate_transcription_response(
chunks, temperature, language
)
else:
# Validate non-streaming response
async for response in response_generator:
LLMResponseValidator.validate_transcription_response(
response, temperature, language
)
@pytest.mark.asyncio
async def test_score_mock_engine(self, mock_llm_config, mock_score_request):
"""Test score API for text similarity."""
# Create and start the engine
engine = MockVLLMEngine(mock_llm_config)
await engine.start()
# Create score request
request = mock_score_request
print("\n\n_____ SCORE _____\n\n")
async for response in engine.score(request):
LLMResponseValidator.validate_score_response(response)
if __name__ == "__main__":
sys.exit(pytest.main(["-v", __file__]))
| TestMockLLMEngine |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 14416,
"end": 15221
} | class ____(ExtensionType):
oid = ExtensionOID.DELTA_CRL_INDICATOR
def __init__(self, crl_number: int) -> None:
if not isinstance(crl_number, int):
raise TypeError("crl_number must be an integer")
self._crl_number = crl_number
@property
def crl_number(self) -> int:
return self._crl_number
def __eq__(self, other: object) -> bool:
if not isinstance(other, DeltaCRLIndicator):
return NotImplemented
return self.crl_number == other.crl_number
def __hash__(self) -> int:
return hash(self.crl_number)
def __repr__(self) -> str:
return f"<DeltaCRLIndicator(crl_number={self.crl_number})>"
def public_bytes(self) -> bytes:
return rust_x509.encode_extension_value(self)
| DeltaCRLIndicator |
python | walkccc__LeetCode | solutions/3506. Find Time Required to Eliminate Bacterial Strains/3506.py | {
"start": 0,
"end": 335
} | class ____:
def minEliminationTime(self, timeReq: list[int], splitTime: int) -> int:
minHeap = timeReq.copy()
heapq.heapify(minHeap)
heapq.heappop(minHeap)
while True:
bacterial = splitTime + heapq.heappop(minHeap)
if not minHeap:
return bacterial
heapq.heappushpop(minHeap, bacterial)
| Solution |
python | walkccc__LeetCode | solutions/1628. Design an Expression Tree With Evaluate Function/1628.py | {
"start": 963,
"end": 1315
} | class ____(object):
def buildTree(self, postfix: list[str]) -> 'Node':
stack: list[ExpNode | None] = []
for val in postfix:
if val in '+-*/':
right = stack.pop()
left = stack.pop()
stack.append(ExpNode(val, left, right))
else:
stack.append(ExpNode(val, None, None))
return stack.pop()
| TreeBuilder |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_constraints.py | {
"start": 1326,
"end": 1612
} | class ____(HasProps, Local):
p0 = Either(Instance(Child0), Instance(Child2))
p1 = Either(Int, String)
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
| Parent |
python | pytorch__pytorch | torch/fx/graph.py | {
"start": 7970,
"end": 8257
} | class ____:
def __init__(self, graph, new_insert):
self.graph = graph
self.orig_insert, graph._insert = graph._insert, new_insert
def __enter__(self):
pass
def __exit__(self, type, value, tb):
self.graph._insert = self.orig_insert
| _InsertPoint |
python | plotly__plotly.py | plotly/matplotlylib/mplexporter/renderers/vega_renderer.py | {
"start": 103,
"end": 3513
} | class ____(Renderer):
def open_figure(self, fig, props):
self.props = props
self.figwidth = int(props["figwidth"] * props["dpi"])
self.figheight = int(props["figheight"] * props["dpi"])
self.data = []
self.scales = []
self.axes = []
self.marks = []
def open_axes(self, ax, props):
if len(self.axes) > 0:
warnings.warn("multiple axes not yet supported")
self.axes = [
dict(type="x", scale="x", ticks=10),
dict(type="y", scale="y", ticks=10),
]
self.scales = [
dict(
name="x",
domain=props["xlim"],
type="linear",
range="width",
),
dict(
name="y",
domain=props["ylim"],
type="linear",
range="height",
),
]
def draw_line(self, data, coordinates, style, label, mplobj=None):
if coordinates != "data":
warnings.warn("Only data coordinates supported. Skipping this")
dataname = "table{0:03d}".format(len(self.data) + 1)
# TODO: respect the other style settings
self.data.append(
{"name": dataname, "values": [dict(x=d[0], y=d[1]) for d in data]}
)
self.marks.append(
{
"type": "line",
"from": {"data": dataname},
"properties": {
"enter": {
"interpolate": {"value": "monotone"},
"x": {"scale": "x", "field": "data.x"},
"y": {"scale": "y", "field": "data.y"},
"stroke": {"value": style["color"]},
"strokeOpacity": {"value": style["alpha"]},
"strokeWidth": {"value": style["linewidth"]},
}
},
}
)
def draw_markers(self, data, coordinates, style, label, mplobj=None):
if coordinates != "data":
warnings.warn("Only data coordinates supported. Skipping this")
dataname = "table{0:03d}".format(len(self.data) + 1)
# TODO: respect the other style settings
self.data.append(
{"name": dataname, "values": [dict(x=d[0], y=d[1]) for d in data]}
)
self.marks.append(
{
"type": "symbol",
"from": {"data": dataname},
"properties": {
"enter": {
"interpolate": {"value": "monotone"},
"x": {"scale": "x", "field": "data.x"},
"y": {"scale": "y", "field": "data.y"},
"fill": {"value": style["facecolor"]},
"fillOpacity": {"value": style["alpha"]},
"stroke": {"value": style["edgecolor"]},
"strokeOpacity": {"value": style["alpha"]},
"strokeWidth": {"value": style["edgewidth"]},
}
},
}
)
def draw_text(
self, text, position, coordinates, style, text_type=None, mplobj=None
):
if text_type == "xlabel":
self.axes[0]["title"] = text
elif text_type == "ylabel":
self.axes[1]["title"] = text
| VegaRenderer |
python | PrefectHQ__prefect | src/prefect/server/api/concurrency_limits.py | {
"start": 15862,
"end": 24503
} | class ____(Exception):
def __init__(self, delay_seconds: float, reason: str):
self.delay_seconds = delay_seconds
self.reason = reason
@router.post("/increment")
async def increment_concurrency_limits_v1(
names: List[str] = Body(..., description="The tags to acquire a slot for"),
task_run_id: UUID = Body(
..., description="The ID of the task run acquiring the slot"
),
db: PrefectDBInterface = Depends(provide_database_interface),
) -> List[MinimalConcurrencyLimitResponse]:
"""
Increment concurrency limits for the given tags.
During migration, this handles both V1 and V2 limits to support mixed states.
Post-migration, it only uses V2 with lease-based concurrency.
"""
results = []
v2_names = [f"tag:{tag}" for tag in names]
async with db.session_context(begin_transaction=True) as session:
# Get V2 limits
v2_limits = await cl_v2_models.bulk_read_concurrency_limits(
session=session, names=v2_names
)
v2_by_name = {limit.name: limit for limit in v2_limits}
# Get V1 limits (for pre-migration compatibility)
v1_limits = (
await concurrency_limits.filter_concurrency_limits_for_orchestration(
session, tags=names
)
)
v1_by_tag = {limit.tag: limit for limit in v1_limits}
# Check all zero limits upfront before acquiring any
for tag in names:
v2_limit = v2_by_name.get(f"tag:{tag}")
v1_limit = v1_by_tag.get(tag)
if v2_limit and v2_limit.limit == 0:
raise HTTPException(
status_code=status.HTTP_423_LOCKED,
detail=f'The concurrency limit on tag "{tag}" is 0 and will deadlock if the task tries to run again.',
)
elif v1_limit and v1_limit.concurrency_limit == 0:
raise HTTPException(
status_code=status.HTTP_423_LOCKED,
detail=f'The concurrency limit on tag "{tag}" is 0 and will deadlock if the task tries to run again.',
)
# Collect V2 limits to acquire in bulk
v2_to_acquire = []
v2_tags_map = {} # Map limit IDs to tags for results
# Check V1 limits availability upfront
v1_to_acquire = []
for tag in names:
v2_limit = v2_by_name.get(f"tag:{tag}")
v1_limit = v1_by_tag.get(tag)
if v2_limit and v2_limit.active:
v2_to_acquire.append(v2_limit.id)
v2_tags_map[v2_limit.id] = tag
elif v1_limit:
# Check V1 limit availability
if len(v1_limit.active_slots) >= v1_limit.concurrency_limit:
raise HTTPException(
status_code=status.HTTP_423_LOCKED,
detail=f"Concurrency limit for the {tag} tag has been reached",
headers={
"Retry-After": str(
PREFECT_TASK_RUN_TAG_CONCURRENCY_SLOT_WAIT_SECONDS.value()
)
},
)
v1_to_acquire.append(v1_limit)
# Bulk acquire all V2 limits at once
acquired_v2_ids = []
if v2_to_acquire:
acquired = await cl_v2_models.bulk_increment_active_slots(
session=session,
concurrency_limit_ids=v2_to_acquire,
slots=1,
)
if not acquired:
# Find which limit was at capacity
for lid in v2_to_acquire:
tag = v2_tags_map[lid]
raise HTTPException(
status_code=status.HTTP_423_LOCKED,
detail=f"Concurrency limit for the {tag} tag has been reached",
headers={
"Retry-After": str(
PREFECT_TASK_RUN_TAG_CONCURRENCY_SLOT_WAIT_SECONDS.value()
)
},
)
acquired_v2_ids = v2_to_acquire
# Add V2 results
for lid in acquired_v2_ids:
tag = v2_tags_map[lid]
limit = v2_by_name[f"tag:{tag}"]
results.append(
MinimalConcurrencyLimitResponse(
id=limit.id, name=tag, limit=limit.limit
)
)
# Apply V1 increments (already checked availability)
for v1_limit in v1_to_acquire:
active_slots = set(v1_limit.active_slots)
active_slots.add(str(task_run_id))
v1_limit.active_slots = list(active_slots)
results.append(
MinimalConcurrencyLimitResponse(
id=v1_limit.id, name=v1_limit.tag, limit=v1_limit.concurrency_limit
)
)
# Create lease for V2 limits
if acquired_v2_ids:
lease_storage = get_concurrency_lease_storage()
await lease_storage.create_lease(
resource_ids=acquired_v2_ids,
ttl=V1_LEASE_TTL,
metadata=ConcurrencyLimitLeaseMetadata(
slots=1,
holder=ConcurrencyLeaseHolder(type="task_run", id=task_run_id),
),
)
return results
@router.post("/decrement")
async def decrement_concurrency_limits_v1(
names: List[str] = Body(..., description="The tags to release a slot for"),
task_run_id: UUID = Body(
..., description="The ID of the task run releasing the slot"
),
db: PrefectDBInterface = Depends(provide_database_interface),
) -> List[MinimalConcurrencyLimitResponse]:
"""
Decrement concurrency limits for the given tags.
Finds and revokes the lease for V2 limits or decrements V1 active slots.
Returns the list of limits that were decremented.
"""
results: list[MinimalConcurrencyLimitResponse] = []
lease_storage = get_concurrency_lease_storage()
v2_names = [f"tag:{tag}" for tag in names]
async with db.session_context(begin_transaction=True) as session:
# Bulk read V2 limits
v2_limits = await cl_v2_models.bulk_read_concurrency_limits(
session=session, names=v2_names
)
v2_by_name = {limit.name: limit for limit in v2_limits}
# Find and revoke lease for V2 limits
if v2_limits:
leases_ids_to_revoke: set[UUID] = set()
for limit in v2_limits:
holders = await lease_storage.list_holders_for_limit(limit.id)
for lease_id, holder in holders:
if holder.id == task_run_id:
lease = await lease_storage.read_lease(lease_id)
if lease:
leases_ids_to_revoke.add(lease.id)
for lease_id in leases_ids_to_revoke:
lease = await lease_storage.read_lease(lease_id)
if lease:
await cl_v2_models.bulk_decrement_active_slots(
session=session,
concurrency_limit_ids=lease.resource_ids,
slots=lease.metadata.slots if lease.metadata else 0,
)
await lease_storage.revoke_lease(lease.id)
else:
logger.warning(f"Lease {lease_id} not found during decrement")
results.extend(
[
MinimalConcurrencyLimitResponse(
id=limit.id, name=limit.name, limit=limit.limit
)
for limit in v2_limits
]
)
# Handle V1 decrements (for pre-migration compatibility)
v1_limits = (
await concurrency_limits.filter_concurrency_limits_for_orchestration(
session, tags=names
)
)
for cl in v1_limits:
# Skip if already handled as V2
v2_name = f"tag:{cl.tag}"
if v2_name not in v2_by_name:
active_slots = set(cl.active_slots)
if str(task_run_id) in active_slots:
active_slots.discard(str(task_run_id))
cl.active_slots = list(active_slots)
results.append(
MinimalConcurrencyLimitResponse(
id=cl.id, name=cl.tag, limit=cl.concurrency_limit
)
)
return results
| Delay |
python | ray-project__ray | python/ray/data/_internal/logical/operators/from_operators.py | {
"start": 2834,
"end": 2922
} | class ____(AbstractFrom):
"""Logical operator for `from_numpy`."""
pass
| FromNumpy |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/cloud_storage_compute_log_manager.py | {
"start": 11105,
"end": 13974
} | class ____(CloudStorageComputeLogManager[T_DagsterInstance]):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._truncated = set()
@contextmanager
def _truncate_file(self, path, max_bytes: int) -> Iterator[str]:
dest = tempfile.NamedTemporaryFile(mode="w+b", delete=False)
try:
with open(path, "rb") as src:
remaining = max_bytes
bufsize = 64 * 1024
while remaining:
chunk = src.read(min(bufsize, remaining))
if not chunk:
break
dest.write(chunk)
remaining -= len(chunk)
dest.flush()
dest.close()
yield dest.name
finally:
try:
os.remove(dest.name)
except FileNotFoundError:
pass
@abstractmethod
def _upload_file_obj(
self, data: IO[bytes], log_key: Sequence[str], io_type: ComputeIOType, partial=False
):
pass
def upload_to_cloud_storage(
self, log_key: Sequence[str], io_type: ComputeIOType, partial: bool = False
) -> None:
"""Uploads the logs for a given log key from local storage to cloud storage."""
# We've already truncated
if (tuple(log_key), io_type) in self._truncated:
logger.debug(f"Compute logs have already been truncated; Skipping upload to {log_key}")
return
path = self.local_manager.get_captured_local_path(log_key, IO_TYPE_EXTENSION[io_type])
ensure_file(path)
max_bytes = int(
os.environ.get(
"DAGSTER_TRUNCATE_COMPUTE_LOGS_UPLOAD_BYTES",
DEFAULT_TRUNCATE_COMPUTE_LOGS_UPLOAD_BYTES,
)
)
if max_bytes and os.stat(path).st_size >= max_bytes:
self._truncated.add((tuple(log_key), io_type))
with self._truncate_file(path, max_bytes=max_bytes) as truncated_path:
with open(truncated_path, "rb") as data:
logger.info(
f"Truncating compute logs to {max_bytes} bytes and uploading to {log_key}"
)
self._upload_file_obj(data, log_key, io_type, partial)
else:
with open(path, "rb") as data:
self._upload_file_obj(data, log_key, io_type, partial)
def _upload_partial_logs(
compute_log_manager: CloudStorageComputeLogManager,
log_key: Sequence[str],
thread_exit: threading.Event,
interval: int,
) -> None:
while True:
time.sleep(interval)
if thread_exit.is_set() or compute_log_manager.is_capture_complete(log_key):
return
compute_log_manager.on_progress(log_key)
| TruncatingCloudStorageComputeLogManager |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 12324,
"end": 12429
} | class ____(SubclassSelectorProxyBaseModel):
class Meta:
proxy = True
| SubclassSelectorProxyModel |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 42032,
"end": 44676
} | class ____(MemoryLeakMixin, TestCase):
def test_is_immutable(self):
@njit
def foo():
l = make_test_list()
return l._is_mutable()
self.assertTrue(foo())
def test_make_immutable_is_immutable(self):
@njit
def foo():
l = make_test_list()
l._make_immutable()
return l._is_mutable()
self.assertFalse(foo())
def test_length_still_works_when_immutable(self):
@njit
def foo():
l = make_test_list()
l._make_immutable()
return len(l),l._is_mutable()
length, mutable = foo()
self.assertEqual(length, 1)
self.assertFalse(mutable)
def test_getitem_still_works_when_immutable(self):
@njit
def foo():
l = make_test_list()
l._make_immutable()
return l[0], l._is_mutable()
test_item, mutable = foo()
self.assertEqual(test_item, 1)
self.assertFalse(mutable)
def test_append_fails(self):
self.disable_leak_check()
@njit
def foo():
l = make_test_list()
l._make_immutable()
l.append(int32(1))
with self.assertRaises(ValueError) as raises:
foo()
self.assertIn(
'list is immutable',
str(raises.exception),
)
def test_mutation_fails(self):
""" Test that any attempt to mutate an immutable typed list fails. """
self.disable_leak_check()
def generate_function(line):
context = {}
exec(dedent("""
from numba.typed import listobject
from numba import int32
def bar():
lst = listobject.new_list(int32)
lst.append(int32(1))
lst._make_immutable()
zero = int32(0)
{}
""".format(line)), context)
return njit(context["bar"])
for line in ("lst.append(zero)",
"lst[0] = zero",
"lst.pop()",
"del lst[0]",
"lst.extend((zero,))",
"lst.insert(0, zero)",
"lst.clear()",
"lst.reverse()",
"lst.sort()",
):
foo = generate_function(line)
with self.assertRaises(ValueError) as raises:
foo()
self.assertIn(
"list is immutable",
str(raises.exception),
)
| TestImmutable |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_ip_address_in_network.py | {
"start": 861,
"end": 1936
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.ip_address_in_network"
condition_value_keys = ("ip_network",)
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, ip_network, **kwargs):
return column.apply(lambda x: is_ip_address_in_network(x, ip_network))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesIpAddressInNetwork |
python | pytorch__pytorch | torch/distributed/pipelining/schedules.py | {
"start": 116017,
"end": 123568
} | class ____(_PipelineScheduleRuntime):
"""
The Zero Bubble schedule (ZBV variant).
See https://arxiv.org/pdf/2401.10241 Section 6 for details.
This schedules requires exactly two stages per rank.
This schedule will perform one forward and one backward on inputs for the microbatches in steady
state and supports multiple stages per rank. Uses backward with respect to weights to fill in
the pipeline bubble.
This ZB-V schedule would have the "zero bubble" property only if time forward == time backward input == time backward weights.
In practice, this is not likely true for real models so alternatively
a greedy scheduler could be implemented for unequal/unbalanced time.
"""
def __init__(
self,
stages: list[_PipelineStageBase],
n_microbatches: int,
loss_fn: Callable | None = None,
args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
scale_grads: bool = True,
backward_requires_autograd: bool = True,
):
# TODO: we dont support input/weight backward split with torch.compile
_check_torch_compile_compatibility(stages, self.__class__.__name__)
self.pp_group_size = stages[0].group_size
super().__init__(
stages=stages,
n_microbatches=n_microbatches,
loss_fn=loss_fn,
args_chunk_spec=args_chunk_spec,
kwargs_chunk_spec=kwargs_chunk_spec,
output_merge_spec=output_merge_spec,
scale_grads=scale_grads,
backward_requires_autograd=backward_requires_autograd,
)
self.stage_index_to_group_rank = generate_stage_to_rank_mapping(
self.pp_group_size, self._num_stages, style="v"
)
for stage in self._stages:
stage.stage_index_to_group_rank = self.stage_index_to_group_rank
self.n_local_stages = len(stages)
if self.n_local_stages != 2:
raise ValueError(
"ZBV requires exactly 2 stages per rank, but got "
f"{self.n_local_stages}."
)
self.rank = stages[0].group_rank
self.num_stages = stages[0].num_stages
# 1. Create the pipeline_order (all ranks do this calculation)
# This will be used to keep track of the current state of the entire pipeline
# pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
self.pipeline_order: dict[int, list[_Action | None]] = {}
for rank in range(self.pp_group_size):
rank_ops = self._calculate_single_rank_operations(rank)
self.pipeline_order[rank] = rank_ops
# Initialize the pipeline order with communication necessary to run with _PipelineScheduleRuntime
self._prepare_schedule_with_comms(self.pipeline_order)
def _calculate_single_rank_operations(self, rank) -> list[_Action | None]:
# max(2 * self.pp_group_size - 1, ...) ensure the number of microbatches is at least
# as large of the number of microbatches needed to fully utilize the pipeline
n_micro = max(2 * self.pp_group_size - 1, self._n_microbatches)
rank_ops: list[_Action | None] = [None for _ in range(rank)]
# Forward and backward action counts for stage chunk 0 and chunk 1
f0_cnt, f1_cnt, b0_cnt, b1_cnt = 0, 0, 0, 0
# warm-up phase
warmup_n1 = 2 * (self.pp_group_size - rank) - 1
stage_id_chunk0 = rank
stage_id_chunk1 = self.num_stages - 1 - rank
for _ in range(warmup_n1):
rank_ops.append(
_Action(stage_id_chunk0, computation_type=F, microbatch_index=f0_cnt)
)
f0_cnt += 1
warmup_n2 = rank
for _ in range(warmup_n2):
rank_ops.append(
_Action(stage_id_chunk1, computation_type=F, microbatch_index=f1_cnt)
)
f1_cnt += 1
rank_ops.append(
_Action(stage_id_chunk0, computation_type=F, microbatch_index=f0_cnt)
)
f0_cnt += 1
warmup_n3 = self.pp_group_size - rank
for _ in range(warmup_n3):
rank_ops.append(
_Action(stage_id_chunk1, computation_type=F, microbatch_index=f1_cnt)
)
f1_cnt += 1
rank_ops.append(
_Action(stage_id_chunk1, computation_type=I, microbatch_index=b1_cnt)
)
rank_ops.append(
_Action(stage_id_chunk1, computation_type=W, microbatch_index=b1_cnt)
)
b1_cnt += 1
# stable phase
while f1_cnt < f0_cnt or f0_cnt < n_micro:
if f0_cnt < n_micro:
rank_ops.append(
_Action(
stage_id_chunk0, computation_type=F, microbatch_index=f0_cnt
)
)
f0_cnt += 1
rank_ops.append(
_Action(stage_id_chunk0, computation_type=I, microbatch_index=b0_cnt)
)
rank_ops.append(
_Action(stage_id_chunk0, computation_type=W, microbatch_index=b0_cnt)
)
b0_cnt += 1
rank_ops.append(
_Action(stage_id_chunk1, computation_type=F, microbatch_index=f1_cnt)
)
f1_cnt += 1
rank_ops.append(
_Action(stage_id_chunk1, computation_type=I, microbatch_index=b1_cnt)
)
rank_ops.append(
_Action(stage_id_chunk1, computation_type=W, microbatch_index=b1_cnt)
)
b1_cnt += 1
# cool-down phase
w0_cnt, w1_cnt = b0_cnt, b1_cnt
cooldown_n1 = rank
for _ in range(cooldown_n1):
rank_ops.append(
_Action(stage_id_chunk0, computation_type=I, microbatch_index=b0_cnt)
)
b0_cnt += 1
rank_ops.append(
_Action(stage_id_chunk1, computation_type=I, microbatch_index=b1_cnt)
)
b1_cnt += 1
cooldown_n2 = self.pp_group_size - rank
for _ in range(cooldown_n2):
rank_ops.append(
_Action(stage_id_chunk0, computation_type=I, microbatch_index=b0_cnt)
)
b0_cnt += 1
rank_ops.append(
_Action(stage_id_chunk0, computation_type=W, microbatch_index=w0_cnt)
)
w0_cnt += 1
while w1_cnt < b1_cnt:
rank_ops.append(
_Action(stage_id_chunk1, computation_type=W, microbatch_index=w1_cnt)
)
w1_cnt += 1
while w0_cnt < b0_cnt:
rank_ops.append(
_Action(stage_id_chunk0, computation_type=W, microbatch_index=w0_cnt)
)
w0_cnt += 1
assert w0_cnt == b0_cnt and b0_cnt == f0_cnt
assert w1_cnt == b1_cnt and b1_cnt == f1_cnt
# We use max() in the n_micro computation above, so we may need to
# remove redundant microbatches
rank_ops = [
(
action
if action is not None
and action.microbatch_index is not None
and action.microbatch_index < self._n_microbatches
else None
)
for action in rank_ops
]
return rank_ops
| ScheduleZBVZeroBubble |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride1.py | {
"start": 8985,
"end": 9055
} | class ____:
def test(self, t: Sequence[int]) -> Sequence[str]: ...
| A |
python | getsentry__sentry | tests/sentry/auth/test_staff.py | {
"start": 1529,
"end": 10874
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.current_datetime = timezone.now()
self.default_token = "abcdefghijklmnog"
self.staff_user = self.create_user(is_staff=True)
def build_request(
self,
cookie_token=UNSET,
session_token=UNSET,
expires=UNSET,
uid=UNSET,
session_data=True,
user=None,
):
if user is None:
user = self.staff_user
request = self.make_request(user=user)
if cookie_token is not None:
request.COOKIES[COOKIE_NAME] = signing.get_cookie_signer(
salt=COOKIE_NAME + COOKIE_SALT
).sign(self.default_token if cookie_token is UNSET else cookie_token)
if session_data:
request.session[SESSION_KEY] = {
"exp": (self.current_datetime + MAX_AGE if expires is UNSET else expires).strftime(
"%s"
),
"tok": self.default_token if session_token is UNSET else session_token,
"uid": str(user.id) if uid is UNSET else uid,
}
return request
def test_ips(self) -> None:
request = self.make_request(user=self.staff_user)
request.META["REMOTE_ADDR"] = "10.0.0.1"
user = request.user
assert isinstance(user, User)
# no ips = any host
staff = Staff(request, allowed_ips=())
staff.set_logged_in(user)
assert staff.is_active is True
staff = Staff(request, allowed_ips=("127.0.0.1",))
staff.set_logged_in(user)
assert staff.is_active is False
staff = Staff(request, allowed_ips=("10.0.0.1",))
staff.set_logged_in(user)
assert staff.is_active is True
def test_sso(self) -> None:
request = self.make_request(user=self.staff_user)
user = request.user
assert isinstance(user, User)
# no ips = any host
staff = Staff(request)
staff.set_logged_in(user)
assert staff.is_active is True
# Set ORG_ID so we run the SSO check
with override_org_id(new_org_id=self.organization.id):
staff = Staff(request)
staff.set_logged_in(user)
assert staff.is_active is False
mark_sso_complete(request, self.organization.id)
staff = Staff(request)
staff.set_logged_in(user)
assert staff.is_active is True
def test_valid_data(self) -> None:
request = self.build_request()
staff = Staff(request, allowed_ips=())
assert staff.is_active is True
def test_missing_cookie(self) -> None:
request = self.build_request(cookie_token=None)
staff = Staff(request, allowed_ips=())
assert staff.is_active is False
def test_invalid_cookie_token(self) -> None:
request = self.build_request(cookie_token="foobar")
staff = Staff(request, allowed_ips=())
assert staff.is_active is False
def test_invalid_session_token(self) -> None:
request = self.build_request(session_token="foobar")
staff = Staff(request, allowed_ips=())
assert staff.is_active is False
def test_missing_data(self) -> None:
request = self.build_request(session_data=False)
staff = Staff(request, allowed_ips=())
assert staff.is_active is False
def test_invalid_uid(self) -> None:
request = self.build_request(uid=-1)
staff = Staff(request, allowed_ips=())
assert staff.is_active is False
@freeze_time(BASETIME)
def test_expired(self) -> None:
request = self.build_request(expires=EXPIRED_TIME)
staff = Staff(request, allowed_ips=())
assert staff.is_active is False
@freeze_time(BASETIME)
def test_not_expired(self) -> None:
request = self.build_request(expires=VALID_TIME)
staff = Staff(request, allowed_ips=())
assert staff.is_active is True
def test_login_saves_session(self) -> None:
request = self.make_request()
staff = Staff(request, allowed_ips=())
staff.set_logged_in(self.staff_user)
# request.user wasn't set
assert not staff.is_active
request.user = self.staff_user
assert staff.is_active
# See mypy issue: https://github.com/python/mypy/issues/9457
data = request.session.get(SESSION_KEY) # type:ignore[unreachable]
assert data
assert data["exp"] == (self.current_datetime + MAX_AGE).strftime("%s")
assert len(data["tok"]) == 12
assert data["uid"] == str(self.staff_user.id)
def test_staff_from_request_does_not_modify_session(self) -> None:
# Active staff in request
request = self.make_request(user=self.staff_user, is_staff=True)
request.session.modified = False
request_staff = getattr(request, "staff")
assert request_staff.is_active
# mock the signed cookie in the request to match the token in the session
with mock.patch.object(request, "get_signed_cookie", return_value=request_staff.token):
activated_staff = Staff(request)
# Staff should still be active
assert activated_staff.is_active
# The session should not be modified because the staff key in the
# session wasn't replaced
assert request.session.modified is False
# See mypy issue: https://github.com/python/mypy/issues/9457
data = request.session.get(SESSION_KEY)
assert data
assert data["exp"] == (self.current_datetime + MAX_AGE).strftime("%s")
assert len(data["tok"]) == 12
assert data["uid"] == str(self.staff_user.id)
def test_logout_clears_session(self) -> None:
request = self.build_request()
staff = Staff(request, allowed_ips=())
staff.set_logged_out()
assert not staff.is_active
assert not request.session.get(SESSION_KEY)
def test_middleware_as_staff(self) -> None:
request = self.build_request()
delattr(request, "staff")
middleware = StaffMiddleware(placeholder_get_response)
middleware.process_request(request)
assert request.staff.is_active
assert is_active_staff(request)
response = mock.Mock()
middleware.process_response(request, response)
response.set_signed_cookie.assert_called_once_with(
COOKIE_NAME,
request.staff.token,
salt=COOKIE_SALT,
max_age=None,
secure=request.is_secure() if COOKIE_SECURE is None else COOKIE_SECURE,
httponly=COOKIE_HTTPONLY,
path=COOKIE_PATH,
domain=COOKIE_DOMAIN,
)
def test_middleware_as_staff_without_session(self) -> None:
request = self.build_request(session_data=False)
delattr(request, "staff")
middleware = StaffMiddleware(placeholder_get_response)
middleware.process_request(request)
assert not request.staff.is_active
assert not is_active_staff(request)
response = mock.Mock()
middleware.process_response(request, response)
response.delete_cookie.assert_called_once_with(COOKIE_NAME)
def test_middleware_as_non_staff(self) -> None:
user = self.create_user("foo@example.com", is_staff=False)
request = self.build_request(user=user)
delattr(request, "staff")
middleware = StaffMiddleware(placeholder_get_response)
middleware.process_request(request)
assert not request.staff.is_active
assert not is_active_staff(request)
response = mock.Mock()
middleware.process_response(request, response)
assert not response.set_signed_cookie.called
def test_changed_user(self) -> None:
request = self.build_request()
staff = Staff(request, allowed_ips=())
assert staff.is_active
# anonymous
request.user = AnonymousUser()
assert not staff.is_active
# a non-staff
# See mypy issue: https://github.com/python/mypy/issues/9457
request.user = self.create_user( # type:ignore[unreachable]
"baz@example.com", is_staff=False
)
assert not staff.is_active
# a staff
request.user.update(is_staff=True)
assert not staff.is_active
def test_is_active_staff_sys_token(self) -> None:
request = self.build_request()
request.auth = SystemToken()
assert is_active_staff(request)
def test_is_active_staff(self) -> None:
request = self.build_request()
request.staff = Staff(request, allowed_ips=())
request.staff._is_active = True
assert is_active_staff(request)
def test_is_not_active_staff(self) -> None:
request = self.build_request()
request.staff = Staff(request, allowed_ips=())
request.staff._is_active = False
assert not is_active_staff(request)
@mock.patch.object(Staff, "is_active", return_value=True)
def test_is_active_staff_from_request(self, mock_is_active: mock.MagicMock) -> None:
request = self.build_request()
request.staff = None
assert is_active_staff(request)
| StaffTestCase |
python | pytorch__pytorch | torch/_inductor/runtime/caching/context.py | {
"start": 4055,
"end": 7010
} | class ____(_Context):
"""Context provider for compilation-related configuration and environment settings.
Collects information that affects compilation behavior, such as PyTorch and Triton
versions, runtime environment, and accelerator properties.
"""
@override
@staticmethod
def forms_of_context() -> Sequence[str]:
"""Return the compile context forms provided by this class.
Returns:
A sequence containing the available compile context forms:
- "torch_version_hash": PyTorch version hash
- "triton_version_hash": Triton version hash (if available)
- "runtime": Runtime type (CUDA/HIP/None)
- "runtime_version": Runtime version string
- "accelerator_properties": GPU/accelerator properties
"""
return (
"torch_version_hash",
"triton_version_hash",
"runtime",
"runtime_version",
"accelerator_properties",
)
@cache
@staticmethod
def torch_version_hash() -> str:
"""Get base64-encoded PyTorch version hash.
Returns:
A base64-encoded string representing the PyTorch version hash.
"""
from torch._inductor.codecache import torch_key
return b64encode(torch_key()).decode()
@cache
@staticmethod
def triton_version_hash() -> str | None:
"""Get Triton version key if Triton is available.
Returns:
Triton version key if Triton is available, None otherwise.
"""
from torch._inductor.runtime.triton_compat import HAS_TRITON, triton_key
return triton_key() if HAS_TRITON else None
@cache
@staticmethod
def runtime() -> str | None:
"""Determine the runtime type based on available backends.
Returns:
"CUDA" if CUDA is available, "HIP" if HIP is available, None otherwise.
"""
return "CUDA" if torch.version.cuda else "HIP" if torch.version.hip else None
@cache
@staticmethod
def runtime_version() -> str | None:
"""Get the version string for the detected runtime.
Returns:
Version string for the current runtime (CUDA or HIP), or None if
no supported runtime is detected.
"""
return {
"CUDA": torch.version.cuda,
"HIP": torch.version.hip,
}.get(_CompileContext.runtime()) # type: ignore[arg-type]
@cache
@staticmethod
def accelerator_properties() -> str | None:
"""Get string representation of CUDA device properties.
Returns:
String representation of CUDA device properties if a runtime is
available, None otherwise.
"""
return (
repr(torch.cuda.get_device_properties())
if _CompileContext.runtime() and torch.cuda.is_available()
else None
)
| _CompileContext |
python | optuna__optuna | tests/hypervolume_tests/test_box_decomposition.py | {
"start": 310,
"end": 5945
} | class ____(Protocol):
def __call__(self, n_trials: int, n_objectives: int, seed: int) -> np.ndarray:
raise NotImplementedError
def _extract_pareto_sols(loss_values: np.ndarray) -> np.ndarray:
sorted_loss_vals = np.unique(loss_values, axis=0)
on_front = _is_pareto_front(sorted_loss_vals, assume_unique_lexsorted=True)
return sorted_loss_vals[on_front]
def _generate_uniform_samples(n_trials: int, n_objectives: int, seed: int) -> np.ndarray:
rng = np.random.RandomState(seed)
return np.maximum(_EPS, rng.random((n_trials, n_objectives)))
def _generate_instances_with_negative(n_objectives: int, n_trials: int, seed: int) -> np.ndarray:
rng = np.random.RandomState(seed)
return _extract_pareto_sols(rng.normal(size=(n_trials, n_objectives)))
def _generate_concave_instances(n_trials: int, n_objectives: int, seed: int) -> np.ndarray:
"""See Section 4.2 of https://arxiv.org/pdf/1510.01963"""
points = _generate_uniform_samples(n_trials, n_objectives, seed)
loss_values = points / np.maximum(_EPS, np.sum(points**2, axis=-1))[:, np.newaxis]
return _extract_pareto_sols(loss_values)
def _generate_convex_instances(n_trials: int, n_objectives: int, seed: int) -> np.ndarray:
"""See Section 4.2 of https://arxiv.org/pdf/1510.01963"""
points = _generate_uniform_samples(n_trials, n_objectives, seed)
loss_values = 1 - points / np.maximum(_EPS, np.sum(points**2, axis=-1))[:, np.newaxis]
return _extract_pareto_sols(loss_values)
def _generate_linear_instances(n_trials: int, n_objectives: int, seed: int) -> np.ndarray:
"""See Section 4.2 of https://arxiv.org/pdf/1510.01963"""
points = _generate_uniform_samples(n_trials, n_objectives, seed)
loss_values = points / np.maximum(_EPS, np.sum(points, axis=-1))[:, np.newaxis]
return _extract_pareto_sols(loss_values)
def _calculate_hypervolume_improvement(
lbs: np.ndarray, ubs: np.ndarray, new_points: np.ndarray
) -> np.ndarray:
diff = np.maximum(0.0, ubs - np.maximum(new_points[..., np.newaxis, :], lbs))
# The minimization version of Eq. (1) in https://arxiv.org/pdf/2006.05078.
return np.sum(np.prod(diff, axis=-1), axis=-1)
def _verify_exact_hypervolume_improvement(pareto_sols: np.ndarray) -> None:
ref_point = np.max(pareto_sols, axis=0)
ref_point = np.maximum(ref_point * 1.1, ref_point * 0.9)
hv = compute_hypervolume(pareto_sols, ref_point, assume_pareto=True)
for i in range(pareto_sols.shape[0]):
# LOO means leave one out.
loo = np.arange(pareto_sols.shape[0]) != i
correct = hv - compute_hypervolume(pareto_sols[loo], ref_point)
lbs, ubs = get_non_dominated_box_bounds(pareto_sols[loo], ref_point)
out = _calculate_hypervolume_improvement(lbs, ubs, pareto_sols[np.newaxis, i])
assert out.shape == (1,)
assert np.isclose(out[0], correct)
@pytest.mark.parametrize(
"gen",
(
_generate_concave_instances,
_generate_convex_instances,
_generate_instances_with_negative,
_generate_linear_instances,
),
)
@pytest.mark.parametrize("n_objectives", [2, 3, 4])
def test_exact_box_decomposition(gen: InstanceGenerator, n_objectives: int) -> None:
n_trials = 30 if n_objectives == 4 else 60
pareto_sols = gen(n_objectives=n_objectives, n_trials=n_trials, seed=42)
_verify_exact_hypervolume_improvement(pareto_sols)
@pytest.mark.parametrize(
"gen",
(
_generate_concave_instances,
_generate_convex_instances,
_generate_instances_with_negative,
_generate_linear_instances,
),
)
@pytest.mark.parametrize("n_objectives", [2, 3, 4])
def test_box_decomposition_with_non_general_position(
gen: InstanceGenerator, n_objectives: int
) -> None:
# By using integer values, duplications can be guaranteed.
# We are testing Proposition 2.2 in the paper: https://arxiv.org/abs/1510.01963
# General position means that no two distinct points share the same value in any dimensions.
pareto_sols = _extract_pareto_sols(
np.round(gen(n_objectives=n_objectives, n_trials=100, seed=42) * 5)
)
_verify_exact_hypervolume_improvement(pareto_sols)
@pytest.mark.parametrize("n_objectives", [2, 3, 4])
def test_box_decomposition_with_1_solution(n_objectives: int) -> None:
pareto_sols = np.ones((1, n_objectives))
ref_point = np.ones(n_objectives) * 10.0
lbs, ubs = get_non_dominated_box_bounds(pareto_sols, ref_point)
hvi = _calculate_hypervolume_improvement(lbs, ubs, np.zeros((1, n_objectives)))[0]
assert np.isclose(hvi, 10**n_objectives - 9**n_objectives)
@pytest.mark.parametrize("n_objectives", [2, 3, 4])
def test_box_decomposition_with_empty_set(n_objectives: int) -> None:
pareto_sols = np.ones((0, n_objectives))
ref_point = np.ones(n_objectives) * 10.0
lbs, ubs = get_non_dominated_box_bounds(pareto_sols, ref_point)
hvi = _calculate_hypervolume_improvement(lbs, ubs, np.zeros((1, n_objectives)))[0]
assert np.isclose(hvi, 10**n_objectives)
@pytest.mark.parametrize(
"values", [np.array([[np.inf, 0.0]]), np.array([[-np.inf, 0.0]]), np.array([[np.nan, 0.0]])]
)
def test_assertion_for_non_finite_values(values: np.ndarray) -> None:
# NOTE(nabenabe): Since GPSampler trains regression models, values must be clipped, which is
# done by `optuna._gp.gp.warn_and_convert_inf`. If `values` includes any non-finite values,
# hypervolume improvement becomes either `inf` or `nan` anyways.
with pytest.raises(AssertionError):
get_non_dominated_box_bounds(values, np.ones(values.shape[-1]) * 10.0)
| InstanceGenerator |
python | eth-brownie__brownie | brownie/network/multicall.py | {
"start": 1263,
"end": 7424
} | class ____:
"""Context manager for batching multiple calls to constant contract functions."""
_lock = Lock()
def __init__(self) -> None:
self.address = None
self.default_verbose = False
self._block_number = defaultdict(lambda: None)
self._verbose = defaultdict(lambda: None)
self._contract = None
self._pending_calls: Dict[int, List[Call]] = defaultdict(list)
setattr(ContractCall, "__original_call_code", ContractCall.__call__.__code__)
setattr(ContractCall, "__proxy_call_code", self._proxy_call.__code__)
setattr(ContractCall, "__multicall", defaultdict(lambda: None))
ContractCall.__call__.__code__ = self._proxy_call.__code__
@property
def block_number(self) -> int:
return self._block_number[get_ident()]
def __call__(
self,
address: Optional[str] = None,
block_identifier: Union[str, bytes, int, None] = None,
verbose: Optional[bool] = None,
) -> "Multicall":
self.address = address
self._block_number[get_ident()] = block_identifier
self._verbose[get_ident()] = verbose if verbose is not None else self.default_verbose
return self
def _flush(self, future_result: Result = None) -> Any:
pending_calls = self._pending_calls[get_ident()]
self._pending_calls[get_ident()] = []
if not pending_calls:
# either all calls have already been made
# or this result has already been retrieved
return future_result
with self._lock:
if self._verbose.get(get_ident(), self.default_verbose):
message = (
"Multicall:"
f"\n Thread ID: {get_ident()}"
f"\n Block number: {self._block_number[get_ident()]}"
f"\n Calls: {len(pending_calls)}"
)
for c, item in enumerate(pending_calls, start=1):
u = "\u2514" if c == len(pending_calls) else "\u251c"
message = f"{message}\n {u}\u2500{item.readable}"
print(color.highlight(f"{message}\n"))
ContractCall.__call__.__code__ = getattr(ContractCall, "__original_call_code")
try:
results = self._contract.tryAggregate(
False,
[_call.calldata for _call in pending_calls],
block_identifier=self._block_number[get_ident()],
)
finally:
ContractCall.__call__.__code__ = getattr(ContractCall, "__proxy_call_code")
for _call, result in zip(pending_calls, results):
_call.__wrapped__ = _call.decoder(result[1]) if result[0] else None
return future_result
def flush(self) -> Any:
"""Flush the pending queue of calls, retrieving all the results."""
return self._flush()
def _call_contract(self, call: ContractCall, *args: Any, **kwargs: Any) -> Proxy:
"""Add a call to the buffer of calls to be made"""
calldata = (call._address, call.encode_input(*args, **kwargs))
readable = f"{call._name}({', '.join(str(i) for i in args)})"
call_obj = Call(calldata, call.decode_output, readable)
# future result
result = Result(call_obj)
self._pending_calls[get_ident()].append(result)
return LazyResult(lambda: self._flush(result))
@staticmethod
def _proxy_call(*args: Any, **kwargs: Any) -> Any:
"""Proxy code which substitutes `ContractCall.__call__"""
if self := getattr(ContractCall, "__multicall", {}).get(get_ident()):
return self._call_contract(*args, **kwargs)
# standard call we let pass through
ContractCall.__call__.__code__ = getattr(ContractCall, "__original_call_code")
try:
result = ContractCall.__call__(*args, **kwargs)
finally:
ContractCall.__call__.__code__ = getattr(ContractCall, "__proxy_call_code")
return result
def __enter__(self) -> "Multicall":
"""Enter the Context Manager and substitute `ContractCall.__call__`"""
# we set the code objects on ContractCall class so we can grab them later
active_network = CONFIG.active_network
if "multicall2" in active_network:
self.address = active_network["multicall2"]
elif "cmd" in active_network:
deployment = self.deploy({"from": accounts[0]})
self.address = deployment.address
self._block_number[get_ident()] = deployment.tx.block_number
self._block_number[get_ident()] = (
self._block_number[get_ident()] or web3.eth.get_block_number()
)
if self.address is None:
raise ContractNotFound(
"Must set Multicall address via `brownie.multicall(address=...)`"
)
elif not web3.eth.get_code(self.address, block_identifier=self.block_number):
raise ContractNotFound(
f"Multicall at address {self.address} does not exist at block {self.block_number}"
)
self._contract = Contract.from_abi("Multicall", self.address, MULTICALL2_ABI)
getattr(ContractCall, "__multicall")[get_ident()] = self
def __exit__(self, exc_type: Exception, exc_val: Any, exc_tb: TracebackType) -> None:
"""Exit the Context Manager and reattach original `ContractCall.__call__` code"""
self.flush()
getattr(ContractCall, "__multicall")[get_ident()] = None
self._block_number.pop(get_ident(), None)
self._verbose.pop(get_ident(), None)
@staticmethod
def deploy(tx_params: Dict) -> Contract:
"""Deploy an instance of the `Multicall2` contract.
Args:
tx_params: parameters passed to the `deploy` method of the `Multicall2` contract
container.
"""
project = compile_source(MULTICALL2_SOURCE)
deployment = project.Multicall2.deploy(tx_params)
CONFIG.active_network["multicall2"] = deployment.address
return deployment
| Multicall |
python | scrapy__scrapy | scrapy/commands/parse.py | {
"start": 1036,
"end": 14347
} | class ____(BaseRunSpiderCommand):
requires_project = True
spider: Spider | None = None
items: dict[int, list[Any]] = {}
requests: dict[int, list[Request]] = {}
spidercls: type[Spider] | None
first_response = None
def syntax(self) -> str:
return "[options] <url>"
def short_desc(self) -> str:
return "Parse URL (using its spider) and print the results"
def add_options(self, parser: argparse.ArgumentParser) -> None:
super().add_options(parser)
parser.add_argument(
"--spider",
dest="spider",
default=None,
help="use this spider without looking for one",
)
parser.add_argument(
"--pipelines", action="store_true", help="process items through pipelines"
)
parser.add_argument(
"--nolinks",
dest="nolinks",
action="store_true",
help="don't show links to follow (extracted requests)",
)
parser.add_argument(
"--noitems",
dest="noitems",
action="store_true",
help="don't show scraped items",
)
parser.add_argument(
"--nocolour",
dest="nocolour",
action="store_true",
help="avoid using pygments to colorize the output",
)
parser.add_argument(
"-r",
"--rules",
dest="rules",
action="store_true",
help="use CrawlSpider rules to discover the callback",
)
parser.add_argument(
"-c",
"--callback",
dest="callback",
help="use this callback for parsing, instead looking for a callback",
)
parser.add_argument(
"-m",
"--meta",
dest="meta",
help="inject extra meta into the Request, it must be a valid raw json string",
)
parser.add_argument(
"--cbkwargs",
dest="cbkwargs",
help="inject extra callback kwargs into the Request, it must be a valid raw json string",
)
parser.add_argument(
"-d",
"--depth",
dest="depth",
type=int,
default=1,
help="maximum depth for parsing requests [default: %(default)s]",
)
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="store_true",
help="print each depth level one by one",
)
@property
def max_level(self) -> int:
max_items, max_requests = 0, 0
if self.items:
max_items = max(self.items)
if self.requests:
max_requests = max(self.requests)
return max(max_items, max_requests)
def handle_exception(self, _failure: Failure) -> None:
logger.error(
"An error is caught while iterating the async iterable",
exc_info=failure_to_exc_info(_failure),
)
@overload
def iterate_spider_output(
self, result: AsyncGenerator[_T] | Coroutine[Any, Any, _T]
) -> Deferred[_T]: ...
@overload
def iterate_spider_output(self, result: _T) -> Iterable[Any]: ...
def iterate_spider_output(self, result: Any) -> Iterable[Any] | Deferred[Any]:
if inspect.isasyncgen(result):
d = deferred_from_coro(
collect_asyncgen(aiter_errback(result, self.handle_exception))
)
d.addCallback(self.iterate_spider_output)
return d
if inspect.iscoroutine(result):
d = deferred_from_coro(result)
d.addCallback(self.iterate_spider_output)
return d
return arg_to_iter(deferred_from_coro(result))
def add_items(self, lvl: int, new_items: list[Any]) -> None:
old_items = self.items.get(lvl, [])
self.items[lvl] = old_items + new_items
def add_requests(self, lvl: int, new_reqs: list[Request]) -> None:
old_reqs = self.requests.get(lvl, [])
self.requests[lvl] = old_reqs + new_reqs
def print_items(self, lvl: int | None = None, colour: bool = True) -> None:
if lvl is None:
items = [item for lst in self.items.values() for item in lst]
else:
items = self.items.get(lvl, [])
print("# Scraped Items ", "-" * 60)
display.pprint([ItemAdapter(x).asdict() for x in items], colorize=colour)
def print_requests(self, lvl: int | None = None, colour: bool = True) -> None:
if lvl is not None:
requests = self.requests.get(lvl, [])
elif self.requests:
requests = self.requests[max(self.requests)]
else:
requests = []
print("# Requests ", "-" * 65)
display.pprint(requests, colorize=colour)
def print_results(self, opts: argparse.Namespace) -> None:
colour = not opts.nocolour
if opts.verbose:
for level in range(1, self.max_level + 1):
print(f"\n>>> DEPTH LEVEL: {level} <<<")
if not opts.noitems:
self.print_items(level, colour)
if not opts.nolinks:
self.print_requests(level, colour)
else:
print(f"\n>>> STATUS DEPTH LEVEL {self.max_level} <<<")
if not opts.noitems:
self.print_items(colour=colour)
if not opts.nolinks:
self.print_requests(colour=colour)
def _get_items_and_requests(
self,
spider_output: Iterable[Any],
opts: argparse.Namespace,
depth: int,
spider: Spider,
callback: CallbackT,
) -> tuple[list[Any], list[Request], argparse.Namespace, int, Spider, CallbackT]:
items, requests = [], []
for x in spider_output:
if isinstance(x, Request):
requests.append(x)
else:
items.append(x)
return items, requests, opts, depth, spider, callback
def run_callback(
self,
response: Response,
callback: CallbackT,
cb_kwargs: dict[str, Any] | None = None,
) -> Deferred[Any]:
cb_kwargs = cb_kwargs or {}
return maybeDeferred(
self.iterate_spider_output, callback(response, **cb_kwargs)
)
def get_callback_from_rules(
self, spider: Spider, response: Response
) -> CallbackT | str | None:
if getattr(spider, "rules", None):
for rule in spider.rules: # type: ignore[attr-defined]
if rule.link_extractor.matches(response.url):
return rule.callback or "parse"
else:
logger.error(
"No CrawlSpider rules found in spider %(spider)r, "
"please specify a callback to use for parsing",
{"spider": spider.name},
)
return None
def set_spidercls(self, url: str, opts: argparse.Namespace) -> None:
assert self.crawler_process
spider_loader = self.crawler_process.spider_loader
if opts.spider:
try:
self.spidercls = spider_loader.load(opts.spider)
except KeyError:
logger.error(
"Unable to find spider: %(spider)s", {"spider": opts.spider}
)
else:
self.spidercls = spidercls_for_request(spider_loader, Request(url))
if not self.spidercls:
logger.error("Unable to find spider for: %(url)s", {"url": url})
async def start(spider: Spider) -> AsyncIterator[Any]:
yield self.prepare_request(spider, Request(url), opts)
if self.spidercls:
self.spidercls.start = start # type: ignore[assignment,method-assign]
def start_parsing(self, url: str, opts: argparse.Namespace) -> None:
assert self.crawler_process
assert self.spidercls
self.crawler_process.crawl(self.spidercls, **opts.spargs)
self.pcrawler = next(iter(self.crawler_process.crawlers))
self.crawler_process.start()
if not self.first_response:
logger.error("No response downloaded for: %(url)s", {"url": url})
def scraped_data(
self,
args: tuple[
list[Any], list[Request], argparse.Namespace, int, Spider, CallbackT
],
) -> list[Any]:
items, requests, opts, depth, spider, callback = args
if opts.pipelines:
assert self.pcrawler.engine
itemproc = self.pcrawler.engine.scraper.itemproc
if hasattr(itemproc, "process_item_async"):
for item in items:
_schedule_coro(itemproc.process_item_async(item))
else:
for item in items:
itemproc.process_item(item, spider)
self.add_items(depth, items)
self.add_requests(depth, requests)
scraped_data = items if opts.output else []
if depth < opts.depth:
for req in requests:
req.meta["_depth"] = depth + 1
req.meta["_callback"] = req.callback
req.callback = callback
scraped_data += requests
return scraped_data
def _get_callback(
self,
*,
spider: Spider,
opts: argparse.Namespace,
response: Response | None = None,
) -> CallbackT:
cb: str | CallbackT | None = None
if response:
cb = response.meta["_callback"]
if not cb:
if opts.callback:
cb = opts.callback
elif response and opts.rules and self.first_response == response:
cb = self.get_callback_from_rules(spider, response)
if not cb:
raise ValueError(
f"Cannot find a rule that matches {response.url!r} in spider: "
f"{spider.name}"
)
else:
cb = "parse"
if not callable(cb):
assert cb is not None
cb_method = getattr(spider, cb, None)
if callable(cb_method):
cb = cb_method
else:
raise ValueError(
f"Cannot find callback {cb!r} in spider: {spider.name}"
)
assert callable(cb)
return cb
def prepare_request(
self, spider: Spider, request: Request, opts: argparse.Namespace
) -> Request:
def callback(response: Response, **cb_kwargs: Any) -> Deferred[list[Any]]:
# memorize first request
if not self.first_response:
self.first_response = response
cb = self._get_callback(spider=spider, opts=opts, response=response)
# parse items and requests
depth: int = response.meta["_depth"]
d = self.run_callback(response, cb, cb_kwargs)
d.addCallback(self._get_items_and_requests, opts, depth, spider, callback)
d.addCallback(self.scraped_data)
return d
# update request meta if any extra meta was passed through the --meta/-m opts.
if opts.meta:
request.meta.update(opts.meta)
# update cb_kwargs if any extra values were was passed through the --cbkwargs option.
if opts.cbkwargs:
request.cb_kwargs.update(opts.cbkwargs)
request.meta["_depth"] = 1
request.meta["_callback"] = request.callback
if not request.callback and not opts.rules:
cb = self._get_callback(spider=spider, opts=opts)
functools.update_wrapper(callback, cb)
request.callback = callback
return request
def process_options(self, args: list[str], opts: argparse.Namespace) -> None:
super().process_options(args, opts)
self.process_request_meta(opts)
self.process_request_cb_kwargs(opts)
def process_request_meta(self, opts: argparse.Namespace) -> None:
if opts.meta:
try:
opts.meta = json.loads(opts.meta)
except ValueError:
raise UsageError(
"Invalid -m/--meta value, pass a valid json string to -m or --meta. "
'Example: --meta=\'{"foo" : "bar"}\'',
print_help=False,
)
def process_request_cb_kwargs(self, opts: argparse.Namespace) -> None:
if opts.cbkwargs:
try:
opts.cbkwargs = json.loads(opts.cbkwargs)
except ValueError:
raise UsageError(
"Invalid --cbkwargs value, pass a valid json string to --cbkwargs. "
'Example: --cbkwargs=\'{"foo" : "bar"}\'',
print_help=False,
)
def run(self, args: list[str], opts: argparse.Namespace) -> None:
# parse arguments
if not len(args) == 1 or not is_url(args[0]):
raise UsageError
url = args[0]
# prepare spidercls
self.set_spidercls(url, opts)
if self.spidercls and opts.depth > 0:
self.start_parsing(url, opts)
self.print_results(opts)
| Command |
python | doocs__leetcode | lcof/面试题36. 二叉搜索树与双向链表/Solution.py | {
"start": 29,
"end": 174
} | class ____:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
"""
| Node |
python | getsentry__sentry | src/sentry/integrations/pagerduty/client.py | {
"start": 611,
"end": 1140
} | class ____(StrEnum):
DEFAULT = "default"
CRITICAL = "critical"
WARNING = "warning"
ERROR = "error"
INFO = "info"
LEVEL_SEVERITY_MAP: dict[str, PagerdutySeverity] = {
"debug": PagerdutySeverity.INFO,
"info": PagerdutySeverity.INFO,
"warning": PagerdutySeverity.WARNING,
"error": PagerdutySeverity.ERROR,
"fatal": PagerdutySeverity.CRITICAL,
}
PAGERDUTY_DEFAULT_SEVERITY = PagerdutySeverity.DEFAULT # represents using LEVEL_SEVERITY_MAP
PAGERDUTY_SUMMARY_MAX_LENGTH = 1024
| PagerdutySeverity |
python | justquick__django-activity-stream | runtests/testapp_nested/migrations/0001_initial.py | {
"start": 108,
"end": 445
} | class ____(migrations.Migration):
operations = [
migrations.CreateModel(
name='NestedModel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('text', models.TextField()),
],
),
]
| Migration |
python | astropy__astropy | astropy/visualization/wcsaxes/tests/test_wcsapi.py | {
"start": 24618,
"end": 26519
} | class ____(BaseLowLevelWCS):
# APE 14 WCS that has celestial coordinates that are deliberately not in degrees
@property
def pixel_n_dim(self):
return 2
@property
def world_n_dim(self):
return 2
@property
def world_axis_physical_types(self):
return [
"pos.eq.ra",
"pos.eq.dec",
]
@property
def world_axis_units(self):
return ["arcsec", "arcsec"]
@property
def world_axis_names(self):
return ["RA", "DEC"]
# Since the units are in arcsec, we can just go for an identity transform
# where 1 pixel = 1" since this is not completely unrealistic
def pixel_to_world_values(self, *pixel_arrays):
return pixel_arrays
def world_to_pixel_values(self, *world_arrays):
return world_arrays
@property
def world_axis_object_components(self):
return [
("celestial", 0, "spherical.lon.arcsec"),
("celestial", 1, "spherical.lat.arcsec"),
]
@property
def world_axis_object_classes(self):
return {
"celestial": (SkyCoord, (), {"unit": "arcsec"}),
}
@figure_test
def test_wcsapi_2d_celestial_arcsec():
# Regression test for plot_coord/scatter_coord/text_coord with celestial WCS that is not in degrees
fig = Figure(figsize=(6, 6))
ax = fig.add_axes([0.15, 0.1, 0.8, 0.8], projection=LowLevelWCSCelestial2D())
ax.set_xlim(-0.5, 200.5)
ax.set_ylim(-0.5, 200.5)
ax.coords[0].set_format_unit("arcsec")
ax.plot_coord(SkyCoord([50, 150], [100, 100], unit="arcsec"), "ro")
ax.scatter_coord(
SkyCoord([100, 100], [50, 150], unit="arcsec"), color="green", s=50
)
ax.text_coord(
SkyCoord(50, 50, unit="arcsec"),
"Plot Label",
color="blue",
ha="right",
va="top",
)
return fig
| LowLevelWCSCelestial2D |
python | ray-project__ray | release/train_tests/xgboost_lightgbm/train_batch_inference_benchmark.py | {
"start": 1096,
"end": 1325
} | class ____:
def __init__(self, report_callback_cls, result: ray.train.Result):
self.model = report_callback_cls.get_model(result.checkpoint)
def __call__(self, data):
raise NotImplementedError
| BasePredictor |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/containers/datatype.py | {
"start": 6841,
"end": 9310
} | class ____:
"""A datatype, preserving polars metadata."""
polars_type: pl.datatypes.DataType
plc_type: plc.DataType
def __init__(self, polars_dtype: PolarsDataType) -> None:
# Convert DataTypeClass to DataType instance if needed
# polars allows both pl.Int64 (class) and pl.Int64() (instance)
if isinstance(polars_dtype, type):
polars_dtype = polars_dtype()
# After conversion, it's guaranteed to be a DataType instance
self.polars_type = cast(pl.DataType, polars_dtype)
self.plc_type = _from_polars(self.polars_type)
def id(self) -> plc.TypeId:
"""The pylibcudf.TypeId of this DataType."""
return self.plc_type.id()
@property
def children(self) -> list[DataType]:
"""The children types of this DataType."""
# Type checker doesn't narrow polars_type through plc_type.id() checks
if self.plc_type.id() == plc.TypeId.STRUCT:
# field.dtype returns DataTypeClass | DataType, need to cast to DataType
return [
DataType(cast(pl.DataType, field.dtype))
for field in cast(pl.Struct, self.polars_type).fields
]
elif self.plc_type.id() == plc.TypeId.LIST:
# .inner returns DataTypeClass | DataType, need to cast to DataType
return [DataType(cast(pl.DataType, cast(pl.List, self.polars_type).inner))]
return []
def scale(self) -> int:
"""The scale of this DataType."""
return self.plc_type.scale()
@staticmethod
def common_decimal_dtype(left: DataType, right: DataType) -> DataType:
"""Return a common decimal DataType for the two inputs."""
if not (
plc.traits.is_fixed_point(left.plc_type)
and plc.traits.is_fixed_point(right.plc_type)
):
raise ValueError("Both inputs required to be decimal types.")
return DataType(pl.Decimal(38, abs(min(left.scale(), right.scale()))))
def __eq__(self, other: object) -> bool:
"""Equality of DataTypes."""
if not isinstance(other, DataType):
return False
return self.polars_type == other.polars_type
def __hash__(self) -> int:
"""Hash of the DataType."""
return hash(self.polars_type)
def __repr__(self) -> str:
"""Representation of the DataType."""
return f"<DataType(polars={self.polars_type}, plc={self.id()!r})>"
| DataType |
python | kubernetes-client__python | kubernetes/client/models/v1_container_state.py | {
"start": 383,
"end": 4915
} | 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.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'running': 'V1ContainerStateRunning',
'terminated': 'V1ContainerStateTerminated',
'waiting': 'V1ContainerStateWaiting'
}
attribute_map = {
'running': 'running',
'terminated': 'terminated',
'waiting': 'waiting'
}
def __init__(self, running=None, terminated=None, waiting=None, local_vars_configuration=None): # noqa: E501
"""V1ContainerState - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._running = None
self._terminated = None
self._waiting = None
self.discriminator = None
if running is not None:
self.running = running
if terminated is not None:
self.terminated = terminated
if waiting is not None:
self.waiting = waiting
@property
def running(self):
"""Gets the running of this V1ContainerState. # noqa: E501
:return: The running of this V1ContainerState. # noqa: E501
:rtype: V1ContainerStateRunning
"""
return self._running
@running.setter
def running(self, running):
"""Sets the running of this V1ContainerState.
:param running: The running of this V1ContainerState. # noqa: E501
:type: V1ContainerStateRunning
"""
self._running = running
@property
def terminated(self):
"""Gets the terminated of this V1ContainerState. # noqa: E501
:return: The terminated of this V1ContainerState. # noqa: E501
:rtype: V1ContainerStateTerminated
"""
return self._terminated
@terminated.setter
def terminated(self, terminated):
"""Sets the terminated of this V1ContainerState.
:param terminated: The terminated of this V1ContainerState. # noqa: E501
:type: V1ContainerStateTerminated
"""
self._terminated = terminated
@property
def waiting(self):
"""Gets the waiting of this V1ContainerState. # noqa: E501
:return: The waiting of this V1ContainerState. # noqa: E501
:rtype: V1ContainerStateWaiting
"""
return self._waiting
@waiting.setter
def waiting(self, waiting):
"""Sets the waiting of this V1ContainerState.
:param waiting: The waiting of this V1ContainerState. # noqa: E501
:type: V1ContainerStateWaiting
"""
self._waiting = waiting
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1ContainerState):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1ContainerState):
return True
return self.to_dict() != other.to_dict()
| V1ContainerState |
python | huggingface__transformers | src/transformers/pipelines/base.py | {
"start": 14332,
"end": 14754
} | class ____(Exception):
"""
Raised by a [`Pipeline`] when handling __call__.
Args:
task (`str`): The task of the pipeline.
model (`str`): The model used by the pipeline.
reason (`str`): The error message to display.
"""
def __init__(self, task: str, model: str, reason: str):
super().__init__(reason)
self.task = task
self.model = model
| PipelineException |
python | getsentry__sentry | tests/sentry/uptime/subscriptions/test_subscriptions.py | {
"start": 24247,
"end": 31271
} | class ____(UptimeTestCase):
def test(self) -> None:
with self.tasks():
detector = create_uptime_detector(
self.project,
self.environment,
url="https://sentry.io",
interval_seconds=3600,
timeout_ms=1000,
mode=UptimeMonitorMode.AUTO_DETECTED_ACTIVE,
)
prev_uptime_subscription = get_uptime_subscription(detector)
prev_uptime_subscription.refresh_from_db()
prev_subscription_id = prev_uptime_subscription.subscription_id
update_uptime_detector(
detector,
environment=self.environment,
url="https://santry.io",
interval_seconds=60,
timeout_ms=1000,
method="POST",
headers=[("some", "header")],
body="a body",
name="New name",
owner=Actor.from_orm_user(self.user),
trace_sampling=False,
)
detector.refresh_from_db()
assert detector.name == "New name"
assert detector.owner_user_id == self.user.id
assert detector.owner_team_id is None
assert detector.config["mode"] == UptimeMonitorMode.MANUAL
prev_uptime_subscription.refresh_from_db()
assert prev_uptime_subscription.url == "https://santry.io"
assert prev_uptime_subscription.interval_seconds == 60
assert prev_uptime_subscription.timeout_ms == 1000
assert prev_uptime_subscription.method == "POST"
assert prev_uptime_subscription.headers == [["some", "header"]]
assert prev_uptime_subscription.body == "a body"
assert prev_uptime_subscription.subscription_id == prev_subscription_id
# Detector fields should be updated
assert detector.config["environment"] == self.environment.name
# Threshold values should remain at defaults since not specified in update
assert detector.config["recovery_threshold"] == DEFAULT_RECOVERY_THRESHOLD
assert detector.config["downtime_threshold"] == DEFAULT_DOWNTIME_THRESHOLD
def test_update_thresholds(self) -> None:
detector = self.create_uptime_detector()
# Verify initial defaults
assert detector.config["recovery_threshold"] == DEFAULT_RECOVERY_THRESHOLD
assert detector.config["downtime_threshold"] == DEFAULT_DOWNTIME_THRESHOLD
update_uptime_detector(
detector,
recovery_threshold=3,
downtime_threshold=7,
)
detector.refresh_from_db()
assert detector.config["recovery_threshold"] == 3
assert detector.config["downtime_threshold"] == 7
def test_already_exists(self) -> None:
with self.tasks():
detector = create_uptime_detector(
self.project,
self.environment,
url="https://sentry.io",
interval_seconds=3600,
timeout_ms=1000,
mode=UptimeMonitorMode.MANUAL,
)
uptime_subscription = get_uptime_subscription(detector)
other_detector = create_uptime_detector(
self.project,
self.environment,
url="https://santry.io",
interval_seconds=3600,
timeout_ms=1000,
mode=UptimeMonitorMode.MANUAL,
)
other_uptime_subscription = get_uptime_subscription(other_detector)
update_uptime_detector(
detector,
environment=self.environment,
url=uptime_subscription.url,
interval_seconds=other_uptime_subscription.interval_seconds,
timeout_ms=1000,
method=other_uptime_subscription.method,
headers=other_uptime_subscription.headers,
body=other_uptime_subscription.body,
name=other_detector.name,
owner=other_detector.owner,
trace_sampling=other_uptime_subscription.trace_sampling,
)
# Verify that we still have both detectors after the update
sentry_detectors = Detector.objects.filter(
project=self.project,
data_sources__source_id=str(uptime_subscription.id),
config__mode=UptimeMonitorMode.MANUAL.value,
)
assert sentry_detectors.count() == 1
santry_detectors = Detector.objects.filter(
project=self.project,
data_sources__source_id=str(other_uptime_subscription.id),
config__mode=UptimeMonitorMode.MANUAL.value,
)
assert santry_detectors.count() == 1
@mock.patch("sentry.uptime.subscriptions.subscriptions.disable_uptime_detector")
def test_status_disable(self, mock_disable_uptime_detector: mock.MagicMock) -> None:
with self.tasks():
detector = create_uptime_detector(
self.project,
self.environment,
url="https://sentry.io",
interval_seconds=3600,
timeout_ms=1000,
mode=UptimeMonitorMode.AUTO_DETECTED_ACTIVE,
)
update_uptime_detector(
detector,
environment=self.environment,
url="https://santry.io",
interval_seconds=60,
timeout_ms=1000,
method="POST",
headers=[("some", "header")],
body="a body",
name="New name",
owner=Actor.from_orm_user(self.user),
trace_sampling=False,
status=ObjectStatus.DISABLED,
)
mock_disable_uptime_detector.assert_called()
@mock.patch("sentry.uptime.subscriptions.subscriptions.enable_uptime_detector")
def test_status_enable(self, mock_enable_uptime_detector: mock.MagicMock) -> None:
with self.tasks():
detector = create_uptime_detector(
self.project,
self.environment,
url="https://sentry.io",
interval_seconds=3600,
timeout_ms=1000,
mode=UptimeMonitorMode.AUTO_DETECTED_ACTIVE,
status=ObjectStatus.DISABLED,
)
update_uptime_detector(
detector,
environment=self.environment,
url="https://santry.io",
interval_seconds=60,
timeout_ms=1000,
method="POST",
headers=[("some", "header")],
body="a body",
name="New name",
owner=Actor.from_orm_user(self.user),
trace_sampling=False,
status=ObjectStatus.ACTIVE,
ensure_assignment=True,
)
mock_enable_uptime_detector.assert_called_with(mock.ANY, ensure_assignment=True)
| UpdateUptimeDetectorTest |
python | run-llama__llama_index | llama-index-integrations/graph_stores/llama-index-graph-stores-tidb/llama_index/graph_stores/tidb/graph.py | {
"start": 1243,
"end": 8414
} | class ____(GraphStore):
def __init__(
self,
db_connection_string: str,
entity_table_name: str = "entities",
relation_table_name: str = "relations",
) -> None:
# TiDB Serverless clusters have a limitation: if there are no active connections for 5 minutes,
# they will shut down, which closes all connections, so we need to recycle the connections
self._engine = create_engine(db_connection_string, pool_recycle=300)
check_db_availability(self._engine)
self._entity_table_name = entity_table_name
self._relation_table_name = relation_table_name
self._entity_model, self._rel_model = self.init_schema()
def init_schema(self) -> Tuple[Any, Any]:
"""Initialize schema."""
Base = declarative_base()
class EntityModel(Base):
__tablename__ = self._entity_table_name
id = Column(Integer, primary_key=True)
name = Column(String(512), nullable=False)
created_at = Column(DateTime, nullable=False, server_default=sql.func.now())
updated_at = Column(
DateTime,
nullable=False,
server_default=sql.func.now(),
onupdate=sql.func.now(),
)
class RelationshipModel(Base):
__tablename__ = self._relation_table_name
id = Column(Integer, primary_key=True)
description = Column(Text, nullable=False)
subject_id = Column(Integer, ForeignKey(f"{self._entity_table_name}.id"))
object_id = Column(Integer, ForeignKey(f"{self._entity_table_name}.id"))
created_at = Column(DateTime, nullable=False, server_default=sql.func.now())
updated_at = Column(
DateTime,
nullable=False,
server_default=sql.func.now(),
onupdate=sql.func.now(),
)
subject = relationship("EntityModel", foreign_keys=[subject_id])
object = relationship("EntityModel", foreign_keys=[object_id])
Base.metadata.create_all(self._engine)
return EntityModel, RelationshipModel
@property
def get_client(self) -> Any:
"""Get client."""
return self._engine
def upsert_triplet(self, subj: str, rel: str, obj: str) -> None:
"""Add triplet."""
with Session(self._engine) as session:
subj_instance, _ = get_or_create(session, self._entity_model, name=subj)
obj_instance, _ = get_or_create(session, self._entity_model, name=obj)
get_or_create(
session,
self._rel_model,
description=rel,
subject=subj_instance,
object=obj_instance,
)
def get(self, subj: str) -> List[List[str]]:
"""Get triplets."""
with Session(self._engine) as session:
rels = (
session.query(self._rel_model)
.options(
joinedload(self._rel_model.subject),
joinedload(self._rel_model.object),
)
.filter(self._rel_model.subject.has(name=subj))
.all()
)
return [[rel.description, rel.object.name] for rel in rels]
def get_rel_map(
self, subjs: Optional[List[str]] = None, depth: int = 2, limit: int = 30
) -> Dict[str, List[List[str]]]:
"""Get depth-aware rel map."""
rel_map: Dict[str, List[List[str]]] = defaultdict(list)
with Session(self._engine) as session:
# `raw_rels`` is a list of tuples (depth, subject, description, object), ordered by depth
# Example:
# +-------+------------------+------------------+------------------+
# | depth | subject | description | object |
# +-------+------------------+------------------+------------------+
# | 1 | Software | Mention in | Footnotes |
# | 1 | Viaweb | Started by | Paul graham |
# | 2 | Paul graham | Invited to | Lisp conference |
# | 2 | Paul graham | Coded | Bel |
# +-------+------------------+------------------+------------------+
raw_rels = session.execute(
sql.text(
rel_depth_query.format(
relation_table=self._relation_table_name,
entity_table=self._entity_table_name,
)
),
{
"subjs": subjs,
"depth": depth,
"limit": limit,
},
).fetchall()
# `obj_reverse_map` is a dict of sets, where the key is a tuple (object, depth)
# and the value is a set of subjects that have the object at the previous depth
obj_reverse_map = defaultdict(set)
for depth, subj, rel, obj in raw_rels:
if depth == 1:
rel_map[subj].append([subj, rel, obj])
obj_reverse_map[(obj, depth)].update([subj])
else:
for _subj in obj_reverse_map[(subj, depth - 1)]:
rel_map[_subj].append([subj, rel, obj])
obj_reverse_map[(obj, depth)].update([_subj])
return dict(rel_map)
def delete(self, subj: str, rel: str, obj: str) -> None:
"""Delete triplet."""
with Session(self._engine) as session:
stmt = delete(self._rel_model).where(
self._rel_model.subject.has(name=subj),
self._rel_model.description == rel,
self._rel_model.object.has(name=obj),
)
result = session.execute(stmt)
session.commit()
# no rows affected, do not need to delete entities
if result.rowcount == 0:
return
def delete_entity(entity_name: str):
stmt = delete(self._entity_model).where(
self._entity_model.name == entity_name
)
session.execute(stmt)
session.commit()
def entity_was_referenced(entity_name: str):
return (
session.query(self._rel_model)
.filter(
self._rel_model.subject.has(name=entity_name)
| self._rel_model.object.has(name=entity_name)
)
.one_or_none()
)
if not entity_was_referenced(subj):
delete_entity(subj)
if not entity_was_referenced(obj):
delete_entity(obj)
def query(self, query: str, param_map: Optional[Dict[str, Any]] = {}) -> Any:
"""Query the graph store with statement and parameters."""
with Session(self._engine) as session:
return session.execute(query, param_map).fetchall()
| TiDBGraphStore |
python | nedbat__coveragepy | tests/test_html.py | {
"start": 31806,
"end": 51701
} | class ____(HtmlTestHelpers, CoverageTest):
"""Tests of HTML reporting that use gold files."""
def test_a(self) -> None:
self.make_file(
"a.py",
"""\
if 1 < 2:
# Needed a < to look at HTML entities.
a = 3
else:
a = 4
""",
)
cov = coverage.Coverage()
a = self.start_import_stop(cov, "a")
cov.html_report(a, directory="out/a")
compare_html(gold_path("html/a"), "out/a")
contains(
"out/a/a_py.html",
(
'<span class="key">if</span> <span class="num">1</span> '
+ '<span class="op"><</span> <span class="num">2</span>'
),
(
' <span class="nam">a</span> '
+ '<span class="op">=</span> <span class="num">3</span>'
),
'<span class="pc_cov">67%</span>',
)
contains(
"out/a/index.html",
'<a href="a_py.html">a.py</a>',
'<span class="pc_cov">67%</span>',
'<td data-ratio="2 3">67%</td>',
)
def test_b_branch(self) -> None:
self.make_file(
"b.py",
"""\
def one(x):
# This will be a branch that misses the else.
if x < 2:
a = 3
else:
a = 4
one(1)
def two(x):
# A missed else that branches to "exit"
if x:
a = 5
two(1)
def three():
try:
# This if has two branches, *neither* one taken.
if name_error_this_variable_doesnt_exist:
a = 1
else:
a = 2
except:
pass
three()
""",
)
cov = coverage.Coverage(branch=True)
b = self.start_import_stop(cov, "b")
cov.html_report(b, directory="out/b_branch")
compare_html(gold_path("html/b_branch"), "out/b_branch")
contains(
"out/b_branch/b_py.html",
(
'<span class="key">if</span> <span class="nam">x</span> '
+ '<span class="op"><</span> <span class="num">2</span>'
),
(
' <span class="nam">a</span> <span class="op">=</span> '
+ '<span class="num">3</span>'
),
'<span class="pc_cov">70%</span>',
(
'<span class="annotate short">3 ↛ 6</span>'
+ '<span class="annotate long">line 3 didn\'t jump to line 6 '
+ "because the condition on line 3 was always true</span>"
),
(
'<span class="annotate short">12 ↛ exit</span>'
+ "<span class=\"annotate long\">line 12 didn't return from function 'two' "
+ "because the condition on line 12 was always true</span>"
),
(
'<span class="annotate short">20 ↛ anywhere</span>'
+ '<span class="annotate long">line 20 didn\'t jump anywhere: '
+ "it always raised an exception.</span>"
),
)
contains(
"out/b_branch/index.html",
'<a href="b_py.html">b.py</a>',
'<span class="pc_cov">70%</span>',
'<td data-ratio="16 23">70%</td>',
)
def test_bom(self) -> None:
self.make_file(
"bom.py",
bytes=b"""\
\xef\xbb\xbf# A Python source file in utf-8, with BOM.
math = "3\xc3\x974 = 12, \xc3\xb72 = 6\xc2\xb10"
assert len(math) == 18
assert len(math.encode('utf-8')) == 21
""".replace(b"\n", b"\r\n"),
)
# It's important that the source file really have a BOM, which can
# get lost, so check that it's really there, and that we have \r\n
# line endings.
with open("bom.py", "rb") as f:
data = f.read()
assert data[:3] == b"\xef\xbb\xbf"
assert data.count(b"\r\n") == 5
cov = coverage.Coverage()
bom = self.start_import_stop(cov, "bom")
cov.html_report(bom, directory="out/bom")
compare_html(gold_path("html/bom"), "out/bom")
contains(
"out/bom/bom_py.html",
'<span class="str">"3×4 = 12, ÷2 = 6±0"</span>',
)
def test_isolatin1(self) -> None:
self.make_file(
"isolatin1.py",
bytes=b"""\
# -*- coding: iso8859-1 -*-
# A Python source file in another encoding.
math = "3\xd74 = 12, \xf72 = 6\xb10"
assert len(math) == 18
""",
)
cov = coverage.Coverage()
isolatin1 = self.start_import_stop(cov, "isolatin1")
cov.html_report(isolatin1, directory="out/isolatin1")
compare_html(gold_path("html/isolatin1"), "out/isolatin1")
contains(
"out/isolatin1/isolatin1_py.html",
'<span class="str">"3×4 = 12, ÷2 = 6±0"</span>',
)
def make_main_etc(self) -> None:
"""Make main.py and m1-m3.py for other tests."""
self.make_file(
"main.py",
"""\
import m1
import m2
import m3
a = 5
b = 6
assert m1.m1a == 1
assert m2.m2a == 1
assert m3.m3a == 1
""",
)
self.make_file(
"m1.py",
"""\
m1a = 1
m1b = 2
""",
)
self.make_file(
"m2.py",
"""\
m2a = 1
m2b = 2
""",
)
self.make_file(
"m3.py",
"""\
m3a = 1
m3b = 2
""",
)
def test_omit_1(self) -> None:
self.make_main_etc()
cov = coverage.Coverage(include=["./*"])
self.start_import_stop(cov, "main")
cov.html_report(directory="out/omit_1")
compare_html(gold_path("html/omit_1"), "out/omit_1")
def test_omit_2(self) -> None:
self.make_main_etc()
cov = coverage.Coverage(include=["./*"])
self.start_import_stop(cov, "main")
cov.html_report(directory="out/omit_2", omit=["m1.py"])
compare_html(gold_path("html/omit_2"), "out/omit_2")
def test_omit_3(self) -> None:
self.make_main_etc()
cov = coverage.Coverage(include=["./*"])
self.start_import_stop(cov, "main")
cov.html_report(directory="out/omit_3", omit=["m1.py", "m2.py"])
compare_html(gold_path("html/omit_3"), "out/omit_3")
def test_omit_4(self) -> None:
self.make_main_etc()
self.make_file(
"omit4.ini",
"""\
[report]
omit = m2.py
""",
)
cov = coverage.Coverage(config_file="omit4.ini", include=["./*"])
self.start_import_stop(cov, "main")
cov.html_report(directory="out/omit_4")
compare_html(gold_path("html/omit_4"), "out/omit_4")
def test_omit_5(self) -> None:
self.make_main_etc()
self.make_file(
"omit5.ini",
"""\
[report]
omit =
fooey
gooey, m[23]*, kablooey
helloworld
[html]
directory = out/omit_5
""",
)
cov = coverage.Coverage(config_file="omit5.ini", include=["./*"])
self.start_import_stop(cov, "main")
cov.html_report()
compare_html(gold_path("html/omit_5"), "out/omit_5")
def test_other(self) -> None:
self.make_file(
"src/here.py",
"""\
import other
if 1 < 2:
h = 3
else:
h = 4
""",
)
self.make_file(
"othersrc/other.py",
"""\
# A file in another directory. We're checking that it ends up in the
# HTML report.
print("This is the other src!")
""",
)
with change_dir("src"):
sys.path.insert(0, "../othersrc")
cov = coverage.Coverage(include=["./*", "../othersrc/*"])
self.start_import_stop(cov, "here")
cov.html_report(directory="../out/other")
# Different platforms will name the "other" file differently. Rename it
actual_file = list(glob.glob("out/other/*_other_py.html"))
assert len(actual_file) == 1
os.rename(actual_file[0], "out/other/blah_blah_other_py.html")
compare_html(
gold_path("html/other"),
"out/other",
extra_scrubs=[
(r'href="z_[0-9a-z]{16}_other_', 'href="_TEST_TMPDIR_other_othersrc_'),
(r"TEST_TMPDIR\\othersrc\\other.py", "TEST_TMPDIR/othersrc/other.py"),
],
)
contains(
"out/other/index.html",
'<a href="here_py.html">here.py</a>',
'other_py.html">',
"other.py</a>",
)
def test_partial(self) -> None:
self.make_file(
"partial.py",
"""\
# partial branches and excluded lines
a = 2
while "no peephole".upper(): # t4
break
while a: # pragma: no branch
break
if 0:
never_happen()
if 13:
a = 14
if a == 16:
raise ZeroDivisionError("17")
""",
)
self.make_file(
"partial.ini",
"""\
[run]
branch = True
[report]
exclude_lines =
raise ZeroDivisionError
""",
)
cov = coverage.Coverage(config_file="partial.ini")
partial = self.start_import_stop(cov, "partial")
cov.html_report(partial, directory="out/partial")
compare_html(gold_path("html/partial"), "out/partial")
contains_rx(
"out/partial/partial_py.html",
r'<p class="par run show_par">.* id="t4"',
r'<p class="run">.* id="t7"',
# The "if 0" and "if 1" statements are marked as run.
r'<p class="run">.* id="t10"',
# The "raise ZeroDivisionError" is excluded by regex in the .ini.
r'<p class="exc show_exc">.* id="t17"',
)
contains(
"out/partial/index.html",
'<a href="partial_py.html">partial.py</a>',
'<span class="pc_cov">92%</span>',
)
def test_styled(self) -> None:
self.make_file(
"a.py",
"""\
if 1 < 2:
# Needed a < to look at HTML entities.
a = 3
else:
a = 4
""",
)
self.make_file("myfile/myextra.css", "/* Doesn't matter what's here, it gets copied. */\n")
cov = coverage.Coverage()
a = self.start_import_stop(cov, "a")
cov.html_report(a, directory="out/styled", extra_css="myfile/myextra.css")
self.assert_valid_hrefs("out/styled")
compare_html(gold_path("html/styled"), "out/styled")
unbust("out/styled")
compare(gold_path("html/styled"), "out/styled", file_pattern="*.css")
contains_rx(
"out/styled/a_py.html",
r'<link rel="stylesheet" href="myextra_cb_\w{8}.css" type="text/css">',
(
r'<span class="key">if</span> <span class="num">1</span> '
+ r'<span class="op"><</span> <span class="num">2</span>'
),
(
r' <span class="nam">a</span> <span class="op">=</span> '
+ r'<span class="num">3</span>'
),
r'<span class="pc_cov">67%</span>',
)
contains_rx(
"out/styled/index.html",
r'<link rel="stylesheet" href="myextra_cb_\w{8}.css" type="text/css">',
r'<a href="a_py.html">a.py</a>',
r'<span class="pc_cov">67%</span>',
)
def test_multiline(self) -> None:
self.make_file(
"multiline.py",
"""\
x = 0
if (
x or x
):
print(
# wut
"hello",
)
else:
print(
"bye",
# wut
)
if 0: # pragma: no cover
print(
"never"
)
""",
)
cov = coverage.Coverage(branch=True)
multiline = self.start_import_stop(cov, "multiline")
cov.html_report(multiline, directory="out/multiline")
compare_html(gold_path("html/multiline"), "out/multiline")
contains(
"out/multiline/multiline_py.html",
'<p class="mis mis2 show_mis"><span class="n"><a id="t6" href="#t6">6</a></span>',
'<p class="exc exc2 show_exc"><span class="n"><a id="t17" href="#t17">17</a>',
)
def test_tabbed(self) -> None:
# The file contents would look like this with 8-space tabs:
# x = 1
# if x:
# a = "tabbed" # aligned comments
# if x: # look nice
# b = "no spaces" # when they
# c = "done" # line up.
self.make_file(
"tabbed.py",
"""\
x = 1
if x:
\ta = "Tabbed"\t\t\t\t# Aligned comments
\tif x:\t\t\t\t\t# look nice
\t\tb = "No spaces"\t\t\t# when they
\tc = "Done"\t\t\t\t# line up.
""",
)
cov = coverage.Coverage()
tabbed = self.start_import_stop(cov, "tabbed")
cov.html_report(tabbed, directory="out")
# Editors like to change things, make sure our source file still has tabs.
contains("tabbed.py", "\tif x:\t\t\t\t\t# look nice")
contains(
"out/tabbed_py.html",
'> <span class="key">if</span> '
+ '<span class="nam">x</span><span class="op">:</span>'
+ " "
+ '<span class="com"># look nice</span>',
)
doesnt_contain("out/tabbed_py.html", "\t")
def test_bug_1828(self) -> None:
# https://github.com/coveragepy/coveragepy/pull/1828
self.make_file(
"backslashes.py",
"""\
a = ["aaa",\\
"bbb \\
ccc"]
""",
)
cov = coverage.Coverage()
backslashes = self.start_import_stop(cov, "backslashes")
cov.html_report(backslashes)
contains(
"htmlcov/backslashes_py.html",
# line 2 is `"bbb \`
r'<a id="t2" href="#t2">2</a></span>'
+ r'<span class="t"> <span class="str">"bbb \</span>',
# line 3 is `ccc"]`
r'<a id="t3" href="#t3">3</a></span>'
+ r'<span class="t"><span class="str"> ccc"</span><span class="op">]</span>',
)
assert self.get_html_report_text_lines("backslashes.py") == [
'1a = ["aaa",\\',
'2 "bbb \\',
'3 ccc"]',
]
@pytest.mark.parametrize(
"leader",
["", "f", "r", "fr", "rf"],
ids=["string", "f-string", "raw_string", "f-raw_string", "raw_f-string"],
)
def test_bug_1836(self, leader: str) -> None:
# https://github.com/coveragepy/coveragepy/issues/1836
self.make_file(
"py312_fstrings.py",
f"""\
prog_name = 'bug.py'
err_msg = {leader}'''\\
{{prog_name}}: ERROR: This is the first line of the error.
{{prog_name}}: ERROR: This is the second line of the error.
\\
{{prog_name}}: ERROR: This is the third line of the error.
'''
""",
)
cov = coverage.Coverage()
py312_fstrings = self.start_import_stop(cov, "py312_fstrings")
cov.html_report(py312_fstrings)
assert self.get_html_report_text_lines("py312_fstrings.py") == [
"1" + "prog_name = 'bug.py'",
"2" + f"err_msg = {leader}'''\\",
"3" + "{prog_name}: ERROR: This is the first line of the error.",
"4" + "{prog_name}: ERROR: This is the second line of the error.",
"5" + "\\",
"6" + "{prog_name}: ERROR: This is the third line of the error.",
"7" + "'''",
]
def test_bug_1980(self) -> None:
self.make_file(
"fstring_middle.py",
"""\
x = 1
f'Look: {x} {{x}}!'
""",
)
cov = coverage.Coverage()
the_mod = self.start_import_stop(cov, "fstring_middle")
cov.html_report(the_mod)
assert self.get_html_report_text_lines("fstring_middle.py") == [
"1" + "x = 1",
"2" + "f'Look: {x} {{x}}!'",
]
def test_unicode(self) -> None:
surrogate = "\U000e0100"
self.make_file(
"unicode.py",
"""\
# -*- coding: utf-8 -*-
# A Python source file with exotic characters.
upside_down = "ʎd˙ǝbɐɹǝʌoɔ"
surrogate = "db40,dd00: x@"
""".replace("@", surrogate),
)
cov = coverage.Coverage()
unimod = self.start_import_stop(cov, "unicode")
cov.html_report(unimod, directory="out/unicode")
compare_html(gold_path("html/unicode"), "out/unicode")
contains(
"out/unicode/unicode_py.html",
'<span class="str">"ʎd˙ǝbɐɹǝʌoɔ"</span>',
)
contains_any(
"out/unicode/unicode_py.html",
'<span class="str">"db40,dd00: x��"</span>',
'<span class="str">"db40,dd00: x󠄀"</span>',
)
def test_accented_dot_py(self) -> None:
# Make a file with a non-ascii character in the filename.
self.make_file("h\xe2t.py", "print('accented')")
self.make_data_file(lines={abs_file("h\xe2t.py"): [1]})
cov = coverage.Coverage()
cov.load()
cov.html_report()
self.assert_exists("htmlcov/h\xe2t_py.html")
with open("htmlcov/index.html", encoding="utf-8") as indexf:
index = indexf.read()
assert '<a href="hât_py.html">hât.py</a>' in index
def test_accented_directory(self) -> None:
# Make a file with a non-ascii character in the directory name.
self.make_file("\xe2/accented.py", "print('accented')")
self.make_data_file(lines={abs_file("\xe2/accented.py"): [1]})
# The HTML report uses ascii-encoded HTML entities.
cov = coverage.Coverage()
cov.load()
cov.html_report()
self.assert_exists("htmlcov/z_5786906b6f0ffeb4_accented_py.html")
with open("htmlcov/index.html", encoding="utf-8") as indexf:
index = indexf.read()
expected = (
'<a href="z_5786906b6f0ffeb4_accented_py.html">â %s accented.py</a>'
)
assert expected % os.sep in index
@pytest.mark.skipif(not testenv.DYN_CONTEXTS, reason="No dynamic contexts with this core.")
| HtmlGoldTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/records/fields/list_template_path.py | {
"start": 157,
"end": 456
} | class ____(Path):
def update(self, template: List[Dict[str, Any]], value: List[Dict[str, Any]]) -> None:
template.clear()
template.extend(value)
def write(self, template: List[Dict[str, Any]], value: List[Dict[str, Any]]) -> None:
template.extend(value)
| ListTemplatePath |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-aws-datalake/destination_aws_datalake/config_reader.py | {
"start": 655,
"end": 1089
} | class ____(enum.Enum):
SNAPPY = "SNAPPY"
GZIP = "GZIP"
ZSTD = "ZSTD"
UNCOMPRESSED = "UNCOMPRESSED"
@staticmethod
def from_config(str: str):
if str == "SNAPPY":
return CompressionCodec.SNAPPY
elif str == "GZIP":
return CompressionCodec.GZIP
elif str == "ZSTD":
return CompressionCodec.ZSTD
return CompressionCodec.UNCOMPRESSED
| CompressionCodec |
python | plotly__plotly.py | plotly/graph_objs/treemap/hoverlabel/_font.py | {
"start": 233,
"end": 17143
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "treemap.hoverlabel"
_path_str = "treemap.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizesrc",
"style",
"stylesrc",
"textcase",
"textcasesrc",
"variant",
"variantsrc",
"weight",
"weightsrc",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `family`.
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"]
@familysrc.setter
def familysrc(self, val):
self["familysrc"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
- A list or array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def linepositionsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`lineposition`.
The 'linepositionsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["linepositionsrc"]
@linepositionsrc.setter
def linepositionsrc(self, val):
self["linepositionsrc"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def shadowsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `shadow`.
The 'shadowsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["shadowsrc"]
@shadowsrc.setter
def shadowsrc(self, val):
self["shadowsrc"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `size`.
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"]
@sizesrc.setter
def sizesrc(self, val):
self["sizesrc"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def stylesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `style`.
The 'stylesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["stylesrc"]
@stylesrc.setter
def stylesrc(self, val):
self["stylesrc"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def textcasesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `textcase`.
The 'textcasesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["textcasesrc"]
@textcasesrc.setter
def textcasesrc(self, val):
self["textcasesrc"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def variantsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `variant`.
The 'variantsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["variantsrc"]
@variantsrc.setter
def variantsrc(self, val):
self["variantsrc"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def weightsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `weight`.
The 'weightsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["weightsrc"]
@weightsrc.setter
def weightsrc(self, val):
self["weightsrc"] = val
@property
def _prop_descriptions(self):
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
"""
def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
lineposition=None,
linepositionsrc=None,
shadow=None,
shadowsrc=None,
size=None,
sizesrc=None,
style=None,
stylesrc=None,
textcase=None,
textcasesrc=None,
variant=None,
variantsrc=None,
weight=None,
weightsrc=None,
**kwargs,
):
"""
Construct a new Font object
Sets the font used in hover labels.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.treemap.hoverlabel.Font`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.treemap.hoverlabel.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.treemap.hoverlabel.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("family", arg, family)
self._set_property("familysrc", arg, familysrc)
self._set_property("lineposition", arg, lineposition)
self._set_property("linepositionsrc", arg, linepositionsrc)
self._set_property("shadow", arg, shadow)
self._set_property("shadowsrc", arg, shadowsrc)
self._set_property("size", arg, size)
self._set_property("sizesrc", arg, sizesrc)
self._set_property("style", arg, style)
self._set_property("stylesrc", arg, stylesrc)
self._set_property("textcase", arg, textcase)
self._set_property("textcasesrc", arg, textcasesrc)
self._set_property("variant", arg, variant)
self._set_property("variantsrc", arg, variantsrc)
self._set_property("weight", arg, weight)
self._set_property("weightsrc", arg, weightsrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | django__django | tests/test_runner/test_parallel.py | {
"start": 1571,
"end": 2204
} | class ____(SimpleTestCase):
# This method name doesn't begin with "test" to prevent test discovery
# from seeing it.
def dummy_test(self):
"""
A dummy test for testing subTest failures.
"""
for i in range(3):
with self.subTest(index=i):
self.assertEqual(i, 1)
# This method name doesn't begin with "test" to prevent test discovery
# from seeing it.
def pickle_error_test(self):
with self.subTest("TypeError: cannot pickle memoryview object"):
self.x = memoryview(b"")
self.fail("expected failure")
| SampleFailingSubtest |
python | ansible__ansible | test/lib/ansible_test/_internal/completion.py | {
"start": 6781,
"end": 7114
} | class ____(RemoteCompletionConfig):
"""Configuration for remote network platforms."""
collection: str = ''
connection: str = ''
placeholder: bool = False
def __post_init__(self):
if not self.placeholder:
super().__post_init__()
@dataclasses.dataclass(frozen=True)
| NetworkRemoteCompletionConfig |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/model_tests/run_models.py | {
"start": 4514,
"end": 11020
} | class ____(object):
"""The driver to run all sample models in all specified configurations."""
def __init__(self, saved_model_dir: str, saved_model_tags: Sequence[str],
saved_model_signature_key: str, batch_size: int, output_dir: str,
output_format: str, use_tf2: bool, use_int8: bool,
analyzer: result_analyzer.ResultAnalyzer):
self._output_dir = output_dir or tempfile.mkdtemp(
prefix="tf2trt_model_tests")
logging.info("Use output directory as: %s", self._output_dir)
self._output_format = output_format
# The model_configs contains (saved_model_dir, saved_model_signature_key,
# batch_size) for each model
self._configs = (model_handler.ModelConfig(
saved_model_dir=saved_model_dir,
saved_model_tags=tuple(saved_model_tags),
saved_model_signature_key=saved_model_signature_key,
default_batch_size=batch_size),)
self._model_handler_manager_cls = (
model_handler.ModelHandlerManagerV2
if use_tf2 else model_handler.ModelHandlerManagerV1)
if use_int8:
self._precision_modes = [
trt.TrtPrecisionMode.FP32, trt.TrtPrecisionMode.FP16,
trt.TrtPrecisionMode.INT8]
else:
self._precision_modes = [
trt.TrtPrecisionMode.FP32, trt.TrtPrecisionMode.FP16]
self._analyzer = analyzer
def _write_analysis_result(self, df: result_analyzer.DataFrame,
path: str) -> None:
if self._output_format == "CSV":
df.to_csv(os.path.join(path, "result.csv"))
elif self._output_format == "JSON":
df.to_json(os.path.join(path, "result.json"))
else:
raise NotImplementedError("Unsupported output format: {}".format(
self._output_format))
def _run_impl(
self, test_name: str,
default_trt_converter_params: trt.TrtConversionParams,
trt_converter_params_updater: Callable[[trt.TrtConversionParams],
Iterable[trt.TrtConversionParams]]
) -> None:
"""Runs all sample models based on a key varying parameter."""
for model_config in self._configs:
# Loads, compiles, calibrates and runs models.
manager = self._model_handler_manager_cls(
name=test_name,
model_config=model_config,
default_trt_convert_params=default_trt_converter_params,
trt_convert_params_updater=trt_converter_params_updater)
inputs = manager.generate_random_inputs()
# As all the data are randomly generated, directly use inference data as
# calibration data to produce reliable dynamic ranges.
manager.convert(inputs)
test_results = manager.run(inputs)
# Analyzes the latency and numerical results.
analysis_result_df, _, acc_hist = self._analyzer.analysis(test_results)
# Outputs the analysis results
model_name = os.path.split(manager.model_config.saved_model_dir)[-1]
model_dir = os.path.join(self._output_dir, model_name)
gfile.MkDir(model_dir)
test_dir = os.path.join(model_dir, test_name)
gfile.MkDir(test_dir)
with gfile.Open(
os.path.join(test_dir, "default_tensorrt_params.txt"), "w") as f:
f.write(repr(default_trt_converter_params))
with gfile.Open(os.path.join(test_dir, "accuracy_histograms.txt"),
"w") as f:
[f.write(h) for h in acc_hist]
self._write_analysis_result(analysis_result_df, test_dir)
def run_trt_precision_tests(self) -> None:
"""Runs tests for all TensorRT precisions."""
def trt_converter_params_updater(params: trt.TrtConversionParams):
for precision_mode in self._precision_modes:
yield params._replace(
precision_mode=precision_mode,
use_calibration=(precision_mode == trt.TrtPrecisionMode.INT8))
self._run_impl(
test_name="precision_mode_test",
default_trt_converter_params=DEFAUL_TRT_CONVERT_PARAMS,
trt_converter_params_updater=trt_converter_params_updater)
def run_all_tests(self) -> None:
"""Runs all tests available."""
self.run_trt_precision_tests()
logging.info("Check analysis result at: %s", self._output_dir)
def main(argv):
if len(argv) > 1:
raise app.UsageError("Too many command-line arguments.")
os.environ["TF_TRT_ALLOW_ENGINE_NATIVE_SEGMENT_EXECUTION"] = "False"
if FLAGS.use_tf2:
logging.info("Running in TF2 mode. Eager execution is enabled.")
framework_ops.enable_eager_execution()
else:
logging.info("Running in TF1 mode. Eager execution is disabled.")
framework_ops.disable_eager_execution()
if FLAGS.use_int8:
logging.info("Will try converting with INT8 precision.")
else:
logging.info("Will not try converting with INT8 precision.")
if FLAGS.gpu_memory_limit_mb:
set_up_gpu_memory_limit(FLAGS.gpu_memory_limit_mb)
tol = namedtuple("tol", "perf acc")
tolerances = {
trt.TrtPrecisionMode.FP32:
tol(perf=float(FLAGS.fp32_speedup_tolerance),
acc=float(FLAGS.fp32_abs_tolerance)),
trt.TrtPrecisionMode.FP16:
tol(perf=float(FLAGS.fp16_speedup_tolerance),
acc=float(FLAGS.fp16_abs_tolerance)),
trt.TrtPrecisionMode.INT8:
tol(perf=float(FLAGS.int8_speedup_tolerance),
acc=float(FLAGS.int8_abs_tolerance)),
}
analyzer = result_analyzer.ResultAnalyzer(
use_cpu_latency_baseline=FLAGS.latency_baseline == "CPU",
use_cpu_numerics_baseline=FLAGS.numerics_baseline == "CPU",
perf_checkers={
precision: functools.partial(
result_analyzer.check_column,
name="speedup",
fn=lambda x: x > tol.perf)
for precision, tol in tolerances.items()
},
acc_checkers={
precision: functools.partial(
result_analyzer.check_column,
name="abs_diff_mean",
fn=lambda x: all(v < tol.acc for v in x.values()))
for precision, tol in tolerances.items()
})
runner = SampleRunner(
saved_model_dir=FLAGS.saved_model_dir,
saved_model_tags=FLAGS.saved_model_tags,
saved_model_signature_key=FLAGS.saved_model_signature_key,
batch_size=FLAGS.batch_size,
output_dir=FLAGS.output_dir,
output_format=FLAGS.output_format,
use_tf2=FLAGS.use_tf2,
use_int8=FLAGS.use_int8,
analyzer=analyzer)
runner.run_all_tests()
if __name__ == "__main__":
app.run(main)
| SampleRunner |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/conjecture/test_provider.py | {
"start": 22918,
"end": 25297
} | class ____(TrivialProvider):
add_observability_callback = True
def __init__(self, conjecturedata: "ConjectureData", /) -> None:
super().__init__(conjecturedata)
# calls to per_test_case_context_manager and on_observation alternate,
# starting with per_test_case_context_manager
self.expected = "per_test_case_context_manager"
@contextmanager
def per_test_case_context_manager(self):
assert self.expected == "per_test_case_context_manager"
self.expected = "on_observation"
yield
def on_observation(self, observation: Observation) -> None:
assert self.expected == "on_observation"
self.expected = "per_test_case_context_manager"
@temp_register_backend("observation", ObservationProvider)
def test_on_observation_alternates():
@given(st.integers())
@settings(backend="observation")
def f(n):
pass
f()
@temp_register_backend("observation", ObservationProvider)
def test_on_observation_alternates_on_failure():
@given(st.integers())
@settings(backend="observation")
def f(n):
# Hypothesis tries n == 0 first, and if that fails then we don't exercise
# any provider-specific paths.
if n == 1:
raise ValueError("unique identifier")
with pytest.raises(ValueError, match="unique identifier"):
f()
@temp_register_backend("observation", TrivialProvider)
def test_on_observation_no_override():
@given(st.integers())
@settings(backend="observation")
def f(n):
assert _callbacks == {}
f()
@pytest.mark.parametrize("provider", [HypothesisProvider, PrngProvider])
def test_provider_conformance(provider):
run_conformance_test(
provider, settings=settings(max_examples=20, stateful_step_count=20)
)
# see https://github.com/HypothesisWorks/hypothesis/issues/4462 and discussion
# in https://github.com/HypothesisWorks/hypothesis/pull/4470
def test_backend_deadline_exceeded_raised_as_flaky_backend_failure():
with temp_register_backend("trivial", TrivialProvider):
@given(st.integers())
@settings(backend="trivial", database=None)
def f(n):
if isinstance(current_build_context().data.provider, TrivialProvider):
time.sleep(1)
with pytest.raises(FlakyBackendFailure):
f()
| ObservationProvider |
python | facebookresearch__faiss | tests/test_index_accuracy.py | {
"start": 19682,
"end": 21222
} | class ____(unittest.TestCase):
# translated from test_opq.lua
def test_OPQ(self):
M = 4
ev = Randu10kUnbalanced()
d = ev.d
index = faiss.IndexPQ(d, M, 8)
res = ev.launch("PQ", index)
e_pq = ev.evalres(res)
index_pq = faiss.IndexPQ(d, M, 8)
opq_matrix = faiss.OPQMatrix(d, M)
# opq_matrix.verbose = true
opq_matrix.niter = 10
opq_matrix.niter_pq = 4
index = faiss.IndexPreTransform(opq_matrix, index_pq)
res = ev.launch("OPQ", index)
e_opq = ev.evalres(res)
# verify that OPQ better than PQ
for r in 1, 10, 100:
assert e_opq[r] > e_pq[r]
def test_OIVFPQ(self):
# Parameters inverted indexes
ncentroids = 50
M = 4
ev = Randu10kUnbalanced()
d = ev.d
quantizer = faiss.IndexFlatL2(d)
index = faiss.IndexIVFPQ(quantizer, d, ncentroids, M, 8)
index.nprobe = 20
res = ev.launch("IVFPQ", index)
e_ivfpq = ev.evalres(res)
quantizer = faiss.IndexFlatL2(d)
index_ivfpq = faiss.IndexIVFPQ(quantizer, d, ncentroids, M, 8)
index_ivfpq.nprobe = 20
opq_matrix = faiss.OPQMatrix(d, M)
opq_matrix.niter = 12
index = faiss.IndexPreTransform(opq_matrix, index_ivfpq)
res = ev.launch("O+IVFPQ", index)
e_oivfpq = ev.evalres(res)
# verify same on OIVFPQ
for r in 1, 10, 100:
assert e_oivfpq[r] >= e_ivfpq[r]
| OPQRelativeAccuracy |
python | Pylons__pyramid | src/pyramid/request.py | {
"start": 12087,
"end": 16100
} | class ____:
"""
A store that caches values during for the lifecycle of a request.
Wrapping Functions
Instantiate and use it to decorate functions that accept a request
parameter. The result is cached and returned in subsequent invocations
of the function.
.. code-block:: python
@RequestLocalCache()
def get_user(request):
result = ... # do some expensive computations
return result
value = get_user(request)
# manipulate the cache directly
get_user.cache.clear(request)
The cache instance is attached to the resulting function as the ``cache``
attribute such that the function may be used to manipulate the cache.
Wrapping Methods
A method can be used as the creator function but it needs to be bound to
an instance such that it only accepts one argument - the request. An easy
way to do this is to bind the creator in the constructor and then use
:meth:`.get_or_create`:
.. code-block:: python
class SecurityPolicy:
def __init__(self):
self.identity_cache = RequestLocalCache(self.load_identity)
def load_identity(self, request):
result = ... # do some expensive computations
return result
def identity(self, request):
return self.identity_cache.get_or_create(request)
The cache maintains a weakref to each request and will release the cached
values when the request is garbage-collected. However, in most scenarios,
it will release resources earlier via
:meth:`pyramid.request.Request.add_finished_callback`.
.. versionadded:: 2.0
"""
NO_VALUE = Sentinel('NO_VALUE')
def __init__(self, creator=None):
self._store = weakref.WeakKeyDictionary()
self._creator = creator
def __call__(self, fn):
@functools.wraps(fn)
def wrapper(request):
return wrapper.cache.get_or_create(request, fn)
wrapper.cache = self
self._creator = fn
return wrapper
def get_or_create(self, request, creator=None):
"""
Return the value from the cache. Compute if necessary.
If no value is cached then execute the creator, cache the result,
and return it.
The creator may be passed in as an argument or bound to the cache
by decorating a function or supplied as a constructor argument.
"""
result = self._store.get(request, self.NO_VALUE)
if result is self.NO_VALUE:
if creator is None:
creator = self._creator
if creator is None:
raise ValueError(
'no creator function has been registered with the '
'cache or supplied to "get_or_create"'
)
result = creator(request)
self.set(request, result)
return result
def get(self, request, default=NO_VALUE):
"""
Return the value from the cache.
The cached value is returned or ``default``.
"""
return self._store.get(request, default)
def set(self, request, value):
"""
Update the cache with a new value.
"""
already_set = request in self._store
self._store[request] = value
# avoid registering the callback more than once
if not already_set:
request.add_finished_callback(self._store.pop)
def clear(self, request):
"""
Delete the value from the cache.
The cached value is returned or :attr:`.NO_VALUE`.
"""
old_value = self.NO_VALUE
if request in self._store:
old_value = self._store[request]
# keep a value in the store so that we don't register another
# finished callback when set is invoked
self._store[request] = self.NO_VALUE
return old_value
| RequestLocalCache |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 6596,
"end": 6746
} | class ____(BaseCopy):
blas_func = fblas.zcopy
dtype = complex128
##################################################
# Test blas ?swap
| TestZcopy |
python | Netflix__metaflow | metaflow/plugins/gcp/gcp_secret_manager_secrets_provider.py | {
"start": 772,
"end": 1525
} | class ____(MetaflowException):
"""Raised when the SecretString response from GCP Secrets Manager is not valid JSON dictionary"""
def _sanitize_key_as_env_var(key):
"""
Sanitize a key as an environment variable name.
This is purely a convenience trade-off to cover common cases well, vs. introducing
ambiguities (e.g. did the final '_' come from '.', or '-' or is original?).
1/27/2023(jackie):
We start with few rules and should *sparingly* add more over time.
Also, it's TBD whether all possible providers will share the same sanitization logic.
Therefore we will keep this function private for now
"""
return key.replace("-", "_").replace(".", "_").replace("/", "_")
| MetaflowGcpSecretsManagerNotJSONObject |
python | huggingface__transformers | src/transformers/models/deepseek_v2/modular_deepseek_v2.py | {
"start": 11420,
"end": 11580
} | class ____(Qwen2MoeExperts):
def __init__(self, config):
super().__init__(config)
self.num_experts = config.n_routed_experts
| DeepseekV2Experts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.